[
  {
    "path": ".clang-format",
    "content": "Language:        JavaScript\nBasedOnStyle:    Google\nColumnLimit:     80\n"
  },
  {
    "path": ".gitignore",
    "content": ".DS_Store\nnohup.out\n*~\n\nlogin/loginServer.cfg\nlogin/node_modules\nconnect/connectServer.cfg\nconnect/node_modules\nserver/node_modules\nvar/\n\n*.city\n*.city.partial\n*.pyc\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# How to Contribute\n\nWe'd love to accept your patches and contributions to this project. There are\njust a few small guidelines you need to follow.\n\n## Contributor License Agreement\n\nContributions to this project must be accompanied by a Contributor License\nAgreement. You (or your employer) retain the copyright to your contribution;\nthis simply gives us permission to use and redistribute your contributions as\npart of the project. Head over to <https://cla.developers.google.com/> to see\nyour current agreements on file or to sign a new one.\n\nYou generally only need to submit a CLA once, so if you've already submitted one\n(even if it was for a different project), you probably don't need to do it\nagain.\n\n## Code reviews\n\nAll submissions, including submissions by project members, require review. We\nuse GitHub pull requests for this purpose. Consult\n[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more\ninformation on using pull requests.\n\n## Community Guidelines\n\nThis project follows [Google's Open Source Community\nGuidelines](https://opensource.google.com/conduct/).\n"
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2011\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "README.md",
    "content": "# Code City\n\nGoogle's Code City is a social programming environment designed mainly for\neducation.  It offers a comic book inspired virtual world where programmers can\nwrite code collaboratively.\n\nA list of running Code City instances may be found at https://codecity.world/\n"
  },
  {
    "path": "bin/dump-core",
    "content": "#!/bin/bash\n\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Create configuration file for and then start nginx, for use as a\n# local development server.  nginx is configured to run in the\n# foreground, and to store all runtime data in <repository root>/var,\n# rather than in /var/ or /usr/local/var/ as it might normally.\n\nset -e\n\n# Get top level directory of the CodeCity git repository.  It's the\n# parent directory of the directory containing this script.\nrepo=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/.. >/dev/null 2>&1 && pwd)\"\n\ncd \"${repo}\"\nmkdir -p var/dump\n\n# Make way for dump.  Ignore errors.\nrm var/dump/*.js || true\nrm core/core_[1-8]*.js || true\nrm database/core_*.js || true\nrm database/db_*.js || true\n\n# Get last .city file.\ncity=$( (cd database && ls -1 *.city |sort |tail  -1) )\n\n# Run dump.\nserver/dump \"database/${city}\" core/dump_spec.json core\n\n# Link core file into database, except core_99_startup.js\n(cd database && ln -s ../core/core_[0-8]*.js .)\n"
  },
  {
    "path": "bin/nginx-dev",
    "content": "#!/bin/bash\n\n# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Create configuration files for and then start nginx, for use as a\n# local development server.  nginx is configured to run in the\n# foreground, and to store all runtime data in <repository root>/var,\n# rather than in /var/ or /usr/local/var/ as it might normally.\n#\n# This is done by generating var/nginx-dev.conf, which will include\n# var/cc-localhost.conf, which is copied (with edits) from\n# etc/cc-localhost.conf, then starting nginx specifying\n# var/nginx-dev.conf as the config file to use.\n\nset -e\n\n# Get top level directory of the CodeCity git repository.  It's the\n# parent directory of the directory containing this script.\nreadonly repo=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/.. >/dev/null 2>&1 && pwd)\"\n\n# Create var directory if required\nif [[ ! -d \"${repo}/var\" ]] ; then\n  if [[ -x \"${repo}/var\" ]] ; then\n    echo \"${repo}/var already exists and is not a directory\" 1>&2\n    exit 1\n  fi\n\n  mkdir \"${repo}/var\"\nfi\n\n# Find location where the nginx installation keeps its config files.\n# We only want the mime.types file.\ndirs=(/usr/local/etc /etc/opt /etc)\nif type brew >/dev/null 2>&1 ; then  # Homebrew in path?\n  dirs=(\"$(brew --prefix)/etc\" \"${dirs[@]}\")\nfi\nfor dir in \"${dirs[@]}\"; do\n  if [[ -d \"${dir}\" && -f \"${dir}/nginx/mime.types\" ]] ; then\n    readonly mimetypes=\"${dir}/nginx/mime.types\"\n    break;\n  fi\ndone\n\nif [[ -z \"${mimetypes}\" ]] ; then\n  echo \"$0: can't find mime.types file.\" 1>&2\n  exit 1;\nfi\n\ncat >\"$repo/var/nginx-dev.conf\" <<EOF\n# Auto-generated by bin/nginx-dev.  Do not edit.\n\ndaemon off;\nworker_processes  1;\n\n# Set pidfile and logfile paths to be in $repo/var:\npid $repo/var/nginx.pid;\nerror_log $repo/var/error.log;\n\nevents {\n}\n\nhttp {\n  access_log off;\n  include ${mimetypes};\n  default_type application/octet-stream;\n\n  # Set temp paths to be in $repo/var:\n  client_body_temp_path $repo/var/client_temp;\n  fastcgi_temp_path $repo/var/fastcgi_temp;\n  proxy_temp_path $repo/var/proxy_temp;\n  scgi_temp_path $repo/var/scgi_temp;\n  uwsgi_temp_path $repo/var/uwsgi_temp;\n\n  include ${repo}/var/cc-localhost.conf;\n}\nEOF\n\nreadonly repo_escaped=${repo//\\//\\\\/}\nsed -e \"s/REPOSITORY/${repo_escaped}/g\" ${repo}/etc/cc-localhost.conf \\\n    > ${repo}/var/cc-localhost.conf\nnginx -c \"$repo/var/nginx-dev.conf\"\n"
  },
  {
    "path": "bin/startup.command",
    "content": "#!/usr/bin/osascript\n# Script to open four terminal windows that execute all the Code City servers\n# with one double-click.  For OSX.\n\ntell application \"Finder\"\n  set basePath to (POSIX path of (container of (container of (path to me)) as alias))\nend tell\n\ntell app \"Terminal\"\n\n  do script \"cd \" & basePath & \"/login\n./loginServer\"\n\n  do script \"cd \" & basePath & \"/connect\n./connectServer\"\n\n  do script \"cd \" & basePath & \"/mobwrite\npython2 mobwrite_server.py\"\n\n  do script \"cd \" & basePath & \"/server\n./codecity \" & basePath & \"/database/codecity.cfg\"\n\nend tell\n"
  },
  {
    "path": "connect/connect.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <title>Code City</title>\n    <link href=\"https://fonts.googleapis.com/css?family=Patrick+Hand\" rel=\"stylesheet\">\n    <link href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\" rel=\"stylesheet\">\n    <link href=\"<<<STATIC_URL>>>style/jfk.css\" rel=\"stylesheet\">\n    <link href=\"<<<STATIC_URL>>>connect/connect.css\" rel=\"stylesheet\">\n    <link href=\"<<<STATIC_URL>>>favicon.ico\" rel=\"shortcut icon\">\n    <script>  // Data injected by connect server.\n      var SESSION_ID = '<<<SESSION_ID>>>';\n     </script>\n    <script src=\"<<<STATIC_URL>>>connect/connect.js\"></script>\n  </head>\n\n  <body>\n    <div id=\"optionsDiv\">\n      <div class=\"jfk-button\" role=\"button\" id=\"worldButton\">World</div><div\n      class=\"jfk-button\" role=\"button\" id=\"logButton\">Log</div><div\n      class=\"jfk-button\" role=\"button\" id=\"pauseButton\">\n        <svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" class=\"icon\">\n          <g id=\"pauseIcon\">\n            <rect x=\"1\" y=\"0\" height=\"8\" width=\"2\" />\n            <rect x=\"5\" y=\"0\" height=\"8\" width=\"2\" />\n          </g>\n          <g id=\"playIcon\" style=\"display: none\">\n            <path d=\"M1,0 L7.5,4 1,8 Z\" />\n          </g>\n        </svg>\n        Pause scroll</div><div\n      class=\"jfk-button\" role=\"button\" id=\"clearButton\">\n        <svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" class=\"icon\">\n          <path d=\"M1,0 L8,7 7,8 0,1 Z\" />\n          <path d=\"M7,0 L0,7 1,8 8,1 Z\" />\n        </svg>\n        Clear buffer</div>\n    </div>\n    <iframe src=\"world\" id=\"worldFrame\"></iframe>\n    <iframe src=\"log\" id=\"logFrame\"></iframe>\n    <table id=\"mainTable\">\n      <tbody>\n        <tr>\n          <td id=\"displayCell\">\n            Loading...\n          </td>\n        </tr>\n      </tbody>\n      <tfoot>\n        <tr>\n          <td>\n            <textarea id=\"commandTextarea\" placeholder=\"&gt; Type commands here, such as: say Hello\"></textarea>\n          </td>\n        </tr>\n      </tfoot>\n    </table>\n  </body>\n</html>\n"
  },
  {
    "path": "connect/connectServer",
    "content": "#!/usr/bin/env node\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Node.js server that provides connection services to Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n\n'use strict';\n\nvar crypto = require('crypto');\nvar fs = require('fs');\nvar http = require('http');\nvar net = require('net');\n\n// Configuration constants.\nconst configFileName = 'connectServer.cfg';\n\n// Global variables.\nvar CFG = null;\nvar queueList = Object.create(null);\n\nconst DEFAULT_CFG = {\n  // Internal port for this HTTP server.  Nginx hides this from users.\n  httpPort: 7782,\n  // URL of login page (absolute or relative).\n  loginUrl: 'https://login.example.codecity.world/',\n  // URL of static folder (absolute or relative).\n  staticUrl: 'https://static.example.codecity.world/',\n  // Host of Code City.\n  remoteHost: 'localhost',\n  // Port of Code City.\n  remotePort: 7777,\n  // Age in seconds of abandoned queues to be closed.\n  connectionTimeout: 300\n};\n\n/**\n * Class for one user's connection to Code City.\n * Establishes a connection and buffers the text coming from Code City.\n * @param {string} id ID of this queue.\n * @constructor\n */\nvar Queue = function (id) {\n  // Save 'this' for closures below.\n  var thisQueue = this;\n  /**\n   * ID of this queue in queueList.\n   */\n  this.id = id;\n  /**\n   * Time that this queue was pinged by a user.  Abandoned queues are deleted.\n   */\n  this.lastPingTime = Date.now();\n  /**\n   * The index number of the most recent memo added to the memo buffer.\n   */\n  this.memoNum = 0;\n  /**\n   * Buffer of incomplete data from Code City.\n   * If undefined, drop all input until next linefeed.\n   */\n  this.lineBuffer = '';\n  /**\n   * Maximum allowed length (in bytes) of a single memo.\n   */\n  this.maxLineSize = 10 * 1024 * 1024;\n  /**\n   * Buffer of memos from Code City to the user.\n   */\n  this.memoBuffer = [];\n  /**\n   * The index number of the most recent command received from the user.\n   */\n  this.commandNum = 0;\n  /**\n   * Persistent TCP connection to Code City.\n   */\n  this.client = new net.Socket();\n\n  this.client.on('close', this.destroy.bind(this, 'Code City closed session'));\n\n  this.client.on('error', function(error) {\n    console.log('TCP error for session ' + id, error);\n  });\n\n  this.client.on('data', function(data) {\n    function drop(overflow) {\n      console.log('Session ' +  id + ' drops ' + overflow.length +\n          ' bytes of data.');\n      return '{\"type\":\"narrate\",\"text\":\"[OVERFLOW: ' + overflow.length +\n          ' bytes lost.]\"}\\n';\n    }\n\n    var text = data.toString();\n    if (!text) {\n      return;\n    }\n    if (thisQueue.lineBuffer) {\n      text = thisQueue.lineBuffer + text;\n    }\n    // Split into lines, while preserving the linebreaks.\n    var lines = text.split(/^/m);\n    if (thisQueue.lineBuffer === undefined) {\n      // Throw away continued oversized line.\n      var incompleteLine = lines.shift();\n      lines.unshift(drop(incompleteLine));\n      if (incompleteLine.endsWith('\\n')) {\n        // Found the end of the oversized line.  Reset the buffer.\n        thisQueue.lineBuffer = '';\n      }\n    }\n\n    for (var i = 0; i < lines.length; i++) {\n      if (lines[i].endsWith('\\n')) {\n        if (lines[i].length > thisQueue.maxLineSize) {\n          // Line is complete, but oversized.  Drop.\n          lines[i] = drop(lines[i]);\n        }\n        thisQueue.memoBuffer.push(lines[i]);\n        thisQueue.memoNum++;\n      } else {\n        // Incomplete line.\n        if (lines[i].length > thisQueue.maxLineSize) {\n          // Discard, and throw away everything till next linebreak.\n          thisQueue.memoBuffer.push(drop(lines[i]));\n          thisQueue.memoNum++;\n          thisQueue.lineBuffer = undefined;\n        } else {\n          // Save this line to the buffer so it may be completed next time.\n          thisQueue.lineBuffer = lines[i];\n        }\n      }\n    }\n  });\n\n  this.client.connect(CFG.remotePort, CFG.remoteHost);\n};\n\n/**\n * Close this queue and deregister it.\n * @param {string} msg Console message to print (with ID appended).\n */\nQueue.prototype.destroy = function(msg) {\n  if (queueList[this.id]) {\n    delete queueList[this.id];\n  }\n  this.client.end();\n  console.log(msg + ' ' + this.id);\n};\n\n/**\n * Load a file from disk, add substitutions, and serve to the web.\n * @param {!Object} response HTTP server response object.\n * @param {string} filename Name of template file on disk.\n * @param {!Object} subs Hash of replacement strings.\n */\nfunction serveFile(response, filename, subs) {\n  fs.readFile(filename, 'utf8', function(err, data) {\n    if (err) {\n      response.statusCode = 500;\n      console.log(err);\n      response.end('Unable to load file: ' + filename + '\\n' + err);\n    }\n    // Inject substitutions.\n    for (var name in subs) {\n      data = data.replace(new RegExp(name, 'g'), subs[name]);\n    }\n    // Serve page to user.\n    response.statusCode = 200;\n    response.setHeader('Content-Type', 'text/html');\n    response.end(data);\n  });\n}\n\n/**\n * Handles HTTP requests from web server.\n * @param {!Object} request HTTP server request object\n * @param {!Object} response HTTP server response object.\n */\nfunction handleRequest(request, response) {\n  if (request.connection.remoteAddress !== '127.0.0.1') {\n    // This check is redundant, the server is only accessible to\n    // localhost connections.\n    console.log('Rejecting connection from ' + request.connection.remoteAddress);\n    response.end('Connection rejected.');\n    return;\n  }\n\n  var path = request.url.split('?')[0];  // Strip off any parameters.\n  if (request.method === 'GET' && path.endsWith('/log')) {\n    serveFile(response, 'log.html', {'<<<STATIC_URL>>>': CFG.staticUrl});\n    return;\n  }\n\n  if (request.method === 'GET' && path.endsWith('/world')) {\n    serveFile(response, 'world.html', {'<<<STATIC_URL>>>': CFG.staticUrl});\n    return;\n  }\n\n  if (request.method === 'GET' && path.endsWith('/')) {\n    var cookieList = {};\n    var rhc = request.headers.cookie;\n    rhc && rhc.split(';').forEach(function(cookie) {\n        var parts = cookie.split('=');\n        cookieList[parts.shift().trim()] = decodeURI(parts.join('='));\n    });\n    // Validate the ID to ensure there was no tampering.\n    var m = cookieList.ID && cookieList.ID.match(/^[0-9a-f]+$/);\n    if (!m) {\n      console.log('Missing login cookie.  Redirecting.');\n      response.writeHead(302, {  // Temporary redirect.\n         'Location': CFG.loginUrl\n       });\n      response.end('Login required.  Redirecting.');\n      return;\n    }\n    var seed = (Date.now() * Math.random()).toString() + cookieList.ID;\n    // This ID gets transmitted a *lot* so keep it short.\n    var sessionId = crypto.createHash('sha3-224').update(seed).digest('base64');\n    if (Object.keys(queueList).length > 1000) {\n      response.statusCode = 429;\n      response.end('Too many queues open at once.');\n      console.log('Too many queues open at once.');\n      return;\n    }\n    var queue = new Queue(sessionId);\n    queueList[sessionId] = queue;\n\n    // Start a connection.\n    queue.client.write('identify as ' + cookieList.ID + '\\n');\n\n    var subs = {\n      '<<<SESSION_ID>>>': sessionId,\n      '<<<STATIC_URL>>>': CFG.staticUrl\n    };\n    serveFile(response, 'connect.html', subs);\n    console.log('Hello xxxx' + cookieList.ID.substring(cookieList.ID.length - 4) +\n                ', starting session ' + sessionId);\n    return;\n  }\n\n  if (request.method === 'POST' && path.endsWith('/ping')) {\n    var requestBody = '';\n    request.on('data', function(data) {\n      requestBody += data;\n      if (requestBody.length > 1000000) {  // Megabyte of commands?\n        console.error('Oversized JSON: ' + requestBody.length / 1024 + 'kb');\n        response.statusCode = 413;\n        response.end('Request Entity Too Large');\n      }\n    });\n    request.on('end', function() {\n      // No ID cookie, the user has logged out.\n      if (!/(^|;)\\s*ID=\\w/.test(request.headers.cookie)) {\n        console.error('Not logged in');\n        response.statusCode = 410;\n        response.end('Not logged in');\n        return;\n      }\n      try {\n        var receivedJson = JSON.parse(requestBody);\n        if (!receivedJson['q']) {\n          throw Error('No queue');\n        }\n      } catch (e) {\n        console.error('Illegal JSON');\n        response.statusCode = 412;\n        response.end('Illegal JSON');\n        return;\n      }\n      ping(receivedJson, response);\n    });\n    return;\n  }\n\n  response.statusCode = 404;\n  response.end('Unknown connectServer URL: ' + request.url);\n}\n\nfunction ping(receivedJson, response) {\n  var q = receivedJson['q'];\n  var ackMemoNum = receivedJson['ackMemoNum'];\n  var cmdNum = receivedJson['cmdNum'];\n  var cmds = receivedJson['cmds'];\n  var logout = receivedJson['logout'];\n\n  var queue = queueList[q];\n  if (!queue) {\n    console.log('Unknown session ' + q);\n    response.statusCode = 410;\n    response.end('Your session has timed out');\n    return;\n  }\n  queue.lastPingTime = Date.now();\n\n  if (typeof ackMemoNum === 'number') {\n    if (ackMemoNum > queue.memoNum) {\n      var msg = 'Client ' + q + ' ackMemoNum ' + ackMemoNum +\n                ', but queue.memoNum is only ' + queue.memoNum;\n      console.error(msg);\n      response.statusCode = 412;\n      response.end(msg);\n      return;\n    }\n    // Client acknowledges receipt of memos.\n    // Remove them from the output list.\n    queue.memoBuffer.splice(0,\n        queue.memoBuffer.length + ackMemoNum - queue.memoNum);\n  }\n\n  var delay = 0;\n  if (typeof cmdNum === 'number') {\n    // Client sent commands.  Increase server's index for acknowledgment.\n    var currentIndex = cmdNum - cmds.length + 1;\n    for (var i = 0; i < cmds.length; i++) {\n      if (currentIndex > queue.commandNum) {\n        queue.commandNum = currentIndex;\n        // Send commands to Code City.\n        queue.client.write(cmds[i]);\n        delay += 200;\n      }\n      currentIndex++;\n    }\n    var ackCmdNextPing = true;\n  } else {\n    var ackCmdNextPing = false;\n  }\n\n  if (logout) {\n    pong(queue, response, ackCmdNextPing);\n    queue.destroy('Client disconnected');\n  } else {\n    // Wait a fifth of a second for each command,\n    // but don't wait for more than a second.\n    var delay = Math.min(delay, 1000);\n    var replyFunc = pong.bind(null, queue, response, ackCmdNextPing);\n    setTimeout(replyFunc, delay);\n  }\n}\n\nfunction pong(queue, response, ackCmdNextPing) {\n  var sendingJson = {};\n  if (ackCmdNextPing) {\n    sendingJson['ackCmdNum'] = queue.commandNum;\n  }\n  if (queue.memoBuffer.length) {\n    sendingJson['memoNum'] = queue.memoNum;\n    sendingJson['memos'] = queue.memoBuffer;\n  }\n  response.statusCode = 200;\n  response.setHeader('Content-Type', 'application/json');\n  response.end(JSON.stringify(sendingJson));\n}\n\n/**\n * Read the JSON configuration file and return it.  If none is\n * present, write a stub and throw an error.\n */\nfunction readConfigFile(filename) {\n  let data;\n  try {\n    data = fs.readFileSync(filename, 'utf8');\n  } catch (err) {\n    console.log(`Configuration file ${filename} not found.  ` +\n        'Creating new file.');\n    data = JSON.stringify(DEFAULT_CFG, null, 2) + '\\n';\n    fs.writeFileSync(filename, data, 'utf8');\n  }\n  CFG = JSON.parse(data);\n  if (!CFG.loginUrl || CFG.loginUrl === DEFAULT_CFG.loginUrl) {\n    throw Error(\n        `Configuration file ${filename} not configured.  ` +\n        'Please edit this file.');\n  }\n  if (!CFG.loginUrl.endsWith('/')) CFG.loginUrl += '/';\n  if (!CFG.staticUrl.endsWith('/')) CFG.staticUrl += '/';\n}\n\n/**\n * Close and destroy any abandoned queues.  Called every minute.\n */\nfunction cleanup() {\n  var bestBefore = Date.now() - CFG.connectionTimeout * 1000;\n  for (var id in queueList) {\n    var queue = queueList[id];\n    if (queue.lastPingTime < bestBefore) {\n      queue.destroy('Timeout of session');\n    }\n  }\n}\n\n/**\n * Start up the HTTP server.\n */\nfunction startup() {\n  readConfigFile(configFileName);\n\n  var server = http.createServer(handleRequest);\n  server.listen(CFG.httpPort, 'localhost', function(){\n    console.log('Connection server listening on port ' + CFG.httpPort);\n  });\n  setInterval(cleanup, 60 * 1000);\n}\n\nstartup();\n"
  },
  {
    "path": "connect/log.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <title>Code City: Log frame</title>\n    <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\">\n    <link rel=\"stylesheet\" href=\"<<<STATIC_URL>>>style/jfk.css\">\n    <link rel=\"stylesheet\" href=\"<<<STATIC_URL>>>connect/common.css\">\n    <link rel=\"stylesheet\" href=\"<<<STATIC_URL>>>connect/log.css\">\n    <script>  // Data injected by connect server.\n      var STATIC_URL = '<<<STATIC_URL>>>';\n     </script>\n    <script src=\"<<<STATIC_URL>>>connect/common.js\"></script>\n    <script src=\"<<<STATIC_URL>>>connect/log.js\"></script>\n  </head>\n\n  <body>\n    <div style=\"display: none\">\n      <!-- Extracted client templates -->\n      <span id=\"connectedTemplate\">Connected.</span>\n      <span id=\"disconnectedTemplate\">Disconnected.</span>\n      <span id=\"reconnectTemplate\">Reconnect?</span>\n      <span id=\"roomObjectTemplate\">You see %1 here.</span>\n      <span id=\"roomObjectsTemplate\">You see %1 here.</span>\n      <span id=\"roomUserTemplate\">%1 is here.</span>\n      <span id=\"roomUsersTemplate\">%1 are here.</span>\n      <span id=\"unknownTemplate\">Someone</span>\n      <span id=\"sayTemplate\">%1 says, \"%2\"</span>\n      <span id=\"saySelfTemplate\">You say, \"%1\"</span>\n      <span id=\"askTemplate\">%1 asks, \"%2\"</span>\n      <span id=\"askSelfTemplate\">You ask, \"%1\"</span>\n      <span id=\"exclaimTemplate\">%1 exclaims, \"%2\"</span>\n      <span id=\"exclaimSelfTemplate\">You exclaim, \"%1\"</span>\n      <span id=\"thinkTemplate\">%1 thinks, \"%2\"</span>\n      <span id=\"thinkSelfTemplate\">You think, \"%1\"</span>\n      <span id=\"andTemplate\">and</span>\n    </div>\n    <div id=\"scrollDiv\"></div>\n  </body>\n</html>\n"
  },
  {
    "path": "connect/world.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <title>Code City: World frame</title>\n    <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Patrick+Hand\">\n    <link rel=\"stylesheet\" href=\"<<<STATIC_URL>>>style/jfk.css\">\n    <link rel=\"stylesheet\" href=\"<<<STATIC_URL>>>style/svg.css\">\n    <link rel=\"stylesheet\" href=\"<<<STATIC_URL>>>connect/common.css\">\n    <link rel=\"stylesheet\" href=\"<<<STATIC_URL>>>connect/world.css\">\n    <script>  // Data injected by connect server.\n      var STATIC_URL = '<<<STATIC_URL>>>';\n     </script>\n    <script src=\"<<<STATIC_URL>>>connect/common.js\"></script>\n    <script src=\"<<<STATIC_URL>>>connect/world.js\"></script>\n  </head>\n\n  <body>\n    <div style=\"display: none\">\n      <!-- Extracted client templates -->\n      <span id=\"connectedTemplate\">Connected.</span>\n      <span id=\"disconnectedTemplate\">Disconnected.</span>\n      <span id=\"reconnectTemplate\">Reconnect?</span>\n      <span id=\"closeIframeTemplate\">Close iframe</span>\n      <span id=\"relaunchIframeTemplate\">↻ Relaunch iframe</span>\n    </div>\n    <div id=\"scrollDiv\">\n      <div id=\"panoramaDiv\"></div>\n      <div id=\"iframeStorage\"></div>\n    </div>\n  </body>\n</html>\n"
  },
  {
    "path": "core/README",
    "content": "This database contains the latest release of the official Code City\nCore.  Normally, when creating a new instance, the database should be\ninitialised by reading all these files in, in order, into the new\nserver.  This will normally be accomplished by symlinking them into\nthe /database/ directory, making sure that no .city files are present\nin that directory, then starting the server using\ndatabase/codecity.cfg.\n\nThe following naming convention has been established to keep things\norganised:\n\ncore_0?_*.js - ES5.1 (and later) polyfills / JS base language stuff.\ncore_1?_*.js - Base structure & utilities ($, $.utils, etc.)\ncore_2?_*.js - Web servers, editors, etc.\ncore_3?_*.js - Physical world infrastructure, telnet server, etc.\ncore_4?_*.js - Start room, demos, etc.\n\ntest_??_*.js - Any tests to be run against the database.\n"
  },
  {
    "path": "core/core_10_base.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Database core for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\nvar perms = new 'perms';\n\nvar setPerms = new 'setPerms';\n\nvar $ = function $(selector) {\n  return new $.Selector(selector).toValue(/*save:*/ true);\n};\n\n$.root = new 'CC.root';\n$.root.name = 'root';\n$.root.toString = function toString() {\n  return 'root';\n};\n\n$.physicals = (new 'Object.create')(null);\n\n$.physicals.Maximilian = {};\n\n$.physicals.Neil = {};\n\n$.system = {};\n$.system.log = new 'CC.log';\n$.system.checkpoint = new 'CC.checkpoint';\n$.system.shutdown = new 'CC.shutdown';\n$.system.connectionListen = new 'CC.connectionListen';\n$.system.connectionUnlisten = new 'CC.connectionUnlisten';\n$.system.connectionWrite = new 'CC.connectionWrite';\n$.system.connectionClose = new 'CC.connectionClose';\n$.system.xhr = new 'CC.xhr';\n$.system.onStartup = function onStartup() {\n  /* Do things needed at database start, when starting from a .js dump\n   * rather than from a .city snapshot (which preserves threads,\n   * listening sockets, etc.)\n   */\n  // Listen on various sockets.\n  try {$.system.connectionListen(7776, $.servers.login.connection, 100);} catch(e) {}\n  try {$.system.connectionListen(7777, $.servers.telnet.connection, 100);} catch(e) {}\n  try {$.system.connectionListen(7780, $.servers.http.connection, 100);} catch(e) {}\n  try {$.system.connectionListen(9999, $.servers.eval.connection);} catch(e) {}\n  $.system.log('Startup: listeners started.');\n\n  // Restart timers and clear auto-expring caches.\n  $.clock.validate();\n  $.db.tempId.cleanNow();\n  suspend();\n  $.system.log('Startup: timers restarted and caches cleared.');\n\n  // Rebuild Selector reverse-lookup database, which is not presently\n  // preserved in the dump as it is a WeakMap.\n  $.Selector.db.populate();\n  $.system.log('Startup: Selector reverse-lookup DB rebuilt.');\n};\nObject.setOwnerOf($.system.onStartup, $.physicals.Neil);\nObject.setOwnerOf($.system.onStartup.prototype, $.physicals.Maximilian);\n\nvar user = function user() {\n  /* The global user() is intended to be used to find the current\n   * user object from deeply-nested functions (to which it is\n   * impractical to thread cmd.user, for whatever reason).\n   *\n   * Previously user was a global variable set to the current user\n   * object by $.servers.telnet.connection.onReceiveLine, but this\n   * can cause problems when one command's execution suspends and\n   * another user's command runs in mean time.\n   *\n   * It is preferable to avoid using this function; instead, use\n   * cmd.user or this where possible.\n   */\n  $.system.log('Auditing user() usage:\\n' + (new Error()).stack);\n  return Object.getOwnerOf(Thread.current());\n};\n\n$.utils = {};\n\n$.utils.validate = {};\n\n$.servers = {};\n\n"
  },
  {
    "path": "core/core_11_$.utils.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Basic utilities for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.utils.validate.ownArray = function ownArray(object, key) {\n  // Ensure that object[key] is an array not shared with any other\n  // object or property, not inherited from a prototype, etc.\n  // If it is, relaced it with a new, unshared array with the same\n  // contents (if possible).\n  if (!object.hasOwnProperty(key) || !Array.isArray(object[key]) ||\n      object[key].forObj !== object || object[key].forKey !== key) {\n    try {\n      object[key] = Array.from(object[key]);\n    } catch (e) {\n      object[key] = [];\n    }\n    Object.defineProperties(object[key], {forObj: {value: object},\n                                          forKey: {value: key}});\n  }\n};\nObject.setOwnerOf($.utils.validate.ownArray, $.physicals.Maximilian);\n$.utils.validate.functionPrototypes = function functionPrototypes() {\n  /* Find (and fix) functions that have f.prototype.constructor !== f.\n   */\n  var u = user();\n  u.narrate('Looking for functions with mismatched .prototype.constructor...');\n  $.utils.object.spider($, function findProtosHelper(object, path) {\n    // Skip $.archive entirely.\n    if (object === $.archive) return true;\n    if (typeof object !== 'function') return false;\n\n    var selector = $.Selector.for(object) || new $.Selector(['$'].concat(path));\n    if (!object.prototype) {\n      if (!String(object).includes('[native code]')) {\n        u.narrate(String(selector) + ' has no .prototype');\n      }\n    } else if (!object.prototype.constructor) {\n      u.narrate(String(selector) + ' has no .prototype.constructor');\n    } else if (object.prototype.constructor !== object) {\n      u.narrate(String(selector) + ' has mismatched .prototype.constructor');\n      var protoProps = Object.getOwnPropertyNames(object.prototype);\n      var pcSelector = $.Selector.for(object.prototype.constructor);\n      // Does it look like a plain old boring auto-created .prototype object?\n      var pd = Object.getOwnPropertyDescriptor(object.prototype, 'constructor');\n      if (Object.getPrototypeOf(object.prototype) === Object.prototype &&\n          protoProps.length === 1 && protoProps[0] === 'constructor' &&\n          pd.writable === true && pd.enumerable === false && pd.configurable === true ) {\n        if (String(pcSelector) === String(selector) + '.prototype.constructor') {\n          u.narrate('----Fixable?: yes!');\n          object.prototype.constructor = object;\n        } else {\n          u.narrate('----Fixable?: yes🤞 (is ' + String(pcSelector) + ')');\n          // Make new .prototype object, since current one is likely shared.\n          var newProto = {constructor: object};\n          Object.setOwnerOf(newProto, Object.getOwnerOf(object));\n          Object.defineProperty(newProto, 'constructor', {enumerable: false});\n          object.prototype = newProto;\n        }\n      } else {\n        u.narrate('----Fixable?: NO: has properties other than .constructor' +\n                     (pcSelector ? ' (is ' + String(pcSelector) + ')' : ''));\n      }\n    }\n    return false;\n  });\n  u.narrate('Done.');\n};\nObject.setOwnerOf($.utils.validate.functionPrototypes, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.validate.functionPrototypes.prototype, $.physicals.Maximilian);\n$.utils.isObject = function isObject(v) {\n  /* Returns true iff v is an object (of any class, including Array\n   * and Function). */\n  return (typeof v === 'object' && v !== null) || typeof v === 'function';\n};\nObject.setOwnerOf($.utils.isObject, $.physicals.Maximilian);\n$.utils.imageMatch = {};\n$.utils.imageMatch.recog = function recog(svgText) {\n  svgText = '<svg transform=\"scale(4)\">' + svgText + '</svg>';\n  var json = $.system.xhr('https://neil.fraser.name/scripts/imageMatch.py' +\n                          '?svg=' + encodeURIComponent(svgText));\n  return JSON.parse(json);\n};\nObject.setOwnerOf($.utils.imageMatch.recog, $.physicals.Neil);\nObject.setOwnerOf($.utils.imageMatch.recog.prototype, $.physicals.Neil);\n$.utils.regexp = {};\nObject.setOwnerOf($.utils.regexp, $.physicals.Neil);\n$.utils.regexp.escape = function escape(str) {\n  // Escape a string so that it may be used as a literal in a regular expression.\n  // Example: $.utils.regexp.escape('[...]') -> \"\\\\[\\\\.\\\\.\\\\.\\\\]\"\n  // Usecase: new RegExp($.utils.regexp.escape('[...]')).test('Alpha [...] Beta')\n  //\n  // Source: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript\n  return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n};\nObject.setOwnerOf($.utils.regexp.escape, $.physicals.Neil);\nObject.setOwnerOf($.utils.regexp.escape.prototype, $.physicals.Neil);\n\n$.utils.array = {};\n$.utils.array.filterUntilFound = function filterUntilFound(array, filter1 /*, filter2, filter3... */) {\n  // Apply Array.prototype.filter.call(array, filterN) for each filter\n  // in turn until one returns a non-empty result.  Return that\n  // result, or an empty array if there are no more filters.\n  filters = Array.from(arguments).slice(1);\n  while (filters.length > 0) {\n    var filter = filters.shift();\n    var result = array.filter(filter);\n    if (result.length > 0) return result;\n  }\n  return [];\n};\nObject.setOwnerOf($.utils.array.filterUntilFound, $.physicals.Maximilian);\n\n$.utils.object = {};\nObject.setOwnerOf($.utils.object, $.physicals.Maximilian);\n$.utils.object.spider = function spider(start, callback) {\n  /* Spider the objects accessible transitively via the properties of\n   * object.\n   *\n   * Arguments:\n   * start: object: Starting point for traversal of the object graph.\n   * callback: function(object, Array<string): boolean:\n   *     Callback called once for each object found during traversal.\n   *     It is passed the current object and an array of the names\n   *     of properties from start to get to it.  If it returns true,\n   *     properties of the current object are not traversed.\n   */\n  var thread = Thread.current();\n  thread.setTimeLimit(Math.min(thread.getTimeLimit() || Infinity, 100));\n  var seen = new WeakMap();\n  var path = [];\n  doSpider(start);\n\n  function doSpider(object) {\n    if (!$.utils.isObject(object)) return;\n\n    // Have we seen it before?\n    if (seen.has(object)) return;\n    seen.set(object, true);\n\n    if (callback(object, path)) return;\n\n    var keys = Object.getOwnPropertyNames(object);\n    for (var i = 0; i < keys.length; i++) {\n      var key = keys[i];\n      try {\n        path.push(key);\n        while (true) {\n          try {\n            doSpider(object[key]);\n            break;\n          } catch (e) {\n            suspend(1);\n            if (!(e instanceof RangeError) || e.message !== 'Thread ran too long') throw e;\n          }\n        }\n      } finally {\n        path.pop();\n      }\n    }\n  }\n};\nObject.setOwnerOf($.utils.object.spider, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.object.spider.prototype, $.physicals.Maximilian);\n$.utils.object.transplantProperties = function transplantProperties(source, destination) {\n  /* Copy own properties (whether enumerable or not) from source to\n   * destination, but do not overwrite existing own properties(*) on\n   * destination.  Called from $.hosts.code['/editorXhr'].handleMetadata\n   * to preserve properties when replacing function objects.\n   *\n   * (*) The exception to the no-overwrite rule is that if destination\n   * is a function and source.prototype is an object then\n   * destination.function will be overwritten by source.prototype;\n   * moreover, if a property source.prototype.constructor exists and is\n   * writable it will be redefined to set its value to destination.\n   * This ensures that destination.prototype.constructor === destination.\n   *\n   * Arguments:\n   * - source: object - the object to copy properties from.\n   * - destination: object - the object to copy properties to.\n   */\n  if (!$.utils.isObject(source) || !$.utils.isObject(destination)) {\n    throw new TypeError('source and destination must be objects');\n  }\n  if (destination === source) return;  // Nothing to do!\n  var keys = Object.getOwnPropertyNames(source);\n  for (var i = 0; i < keys.length; i++) {\n    var key = keys[i];\n    var pd = Object.getOwnPropertyDescriptor(source, key);\n    if (typeof destination === 'function' &&\n        key === 'prototype' && $.utils.isObject(pd.value)) {\n      // Fix destination.constructor.prototype to be destination, if\n      // .constructor writable.\n      var cpd = Object.getOwnPropertyDescriptor(pd.value, 'constructor');\n      if (cpd.writable) {\n        cpd.value = destination;\n        Object.defineProperty(pd.value, 'constructor', cpd);\n      }\n    } else {\n      // Do not overwrite any other existing properties on destination.\n      if (Object.prototype.hasOwnProperty.call(destination, key)) continue;\n    }\n    try {\n      Object.defineProperty(destination, key, pd);\n    } catch (e) {\n      // Ignore failed attempt to copy properties.\n    }\n  }\n};\nObject.setOwnerOf($.utils.object.transplantProperties, $.physicals.Maximilian);\n$.utils.object.getValue = function getValue(object, prop) {\n  /* Get the value from an object's property.\n   * If the value is a function, call it and return the result.\n   * Used (for example) to get a description.  Simple objects would have a\n   * string in their description property.  Compiles objects would have a\n   * function in their description property that returns a string.\n   */\n  var value = object[prop];\n  if (typeof value === 'function') {\n    value = value.call(object);\n  }\n  return value;\n};\nObject.setOwnerOf($.utils.object.getValue, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.object.getValue.prototype, $.physicals.Neil);\n$.utils.object.getPropertyLocation = function $_utils_object_getPropertyLocation(obj, propName) {\n  // Returns the object that defines the given propName.\n  // Might be object, or one of its prototypes, or null.\n  while (obj && !Object.prototype.hasOwnProperty.call(obj, propName)) {\n    obj = Object.getPrototypeOf(obj);\n  }\n  return obj;\n};\nObject.setOwnerOf($.utils.object.getPropertyLocation, $.physicals.Neil);\nObject.setOwnerOf($.utils.object.getPropertyLocation.prototype, $.physicals.Neil);\n\n$.utils.string = {};\n$.utils.string.capitalize = function capitalize(str) {\n  /* 'foo' -> 'Foo'\n   * Assumes incoming text is already lowercase.\n   */\n  return str.charAt(0).toUpperCase() + str.substring(1);\n};\nObject.setOwnerOf($.utils.string.capitalize, $.physicals.Neil);\n$.utils.string.randomCharacter = function randomCharacter(chars) {\n  return chars.charAt(Math.random() * chars.length);\n};\n$.utils.string.VOWELS = 'aeiouy';\n$.utils.string.CONSONANTS = 'bcdfghjklmnpqrstvwxz';\n$.utils.string.ALPHABET = 'abcdefghijklmnopqrstuvwxyz';\n$.utils.string.hash = new 'CC.hash';\n$.utils.string.translate = function translate(text, language) {\n  /* Try to translate text into the specified language using an\n   * external translation server.\n   *\n   * Arguments:\n   * text: string: the text to be translated.\n   * language: string: a two-character ISO 639-1 language code.\n   *\n   * Returns: the translated text.\n   */\n  var url = 'https://translate-service.scratch.mit.edu' +\n      '/translate?language=' + encodeURIComponent(language) +\n      '&text=' + encodeURIComponent(text);\n  var json = $.system.xhr(url);\n  return JSON.parse(json).result;\n};\nObject.setOwnerOf($.utils.string.translate, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.string.translate.prototype, $.physicals.Maximilian);\n$.utils.string.generateRandom = function generateRandom(length, soup) {\n  /* Return a string of the specified length consisting of characters from the\n   * given soup, or $.utils.string.generateRandom.DEFAULT_SOUP if none\n   * specified.\n   *\n   * E.g.: generateRandom(4, 'abc') might return 'cbca'.\n   *\n   * Arguments:\n   * - length: number - length of string to generate.\n   * - soup: string - alphabet to select characters randomly from.\n   */\n  soup = soup || $.utils.string.generateRandom.DEFAULT_SOUP;\n  var out = [];\n  for (var i = 0; i < length; i++) {\n    out[i] = this.randomCharacter(soup);\n  }\n  return out.join('');\n};\nObject.setOwnerOf($.utils.string.generateRandom, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.string.generateRandom.prototype, $.physicals.Neil);\n$.utils.string.generateRandom.DEFAULT_SOUP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n$.utils.string.prefixLines = function prefixLines(text, prefix) {\n  // Prepend a common prefix onto each line of code.\n  // Intended for indenting code or adding '//' comment markers.\n  return prefix + text.replace(/(?!\\n$)\\n/g, '\\n' + prefix);\n};\nObject.setOwnerOf($.utils.string.prefixLines, $.physicals.Neil);\nObject.setOwnerOf($.utils.string.prefixLines.prototype, $.physicals.Neil);\n\n"
  },
  {
    "path": "core/core_12_$.utils.code.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Code utilities for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.utils.code = {};\n$.utils.code.rewriteForEval = function rewriteForEval(src, forceExpression) {\n  /* Eval treats {} as an empty block (return value undefined).\n   * Eval treats {'a': 1} as a syntax error.\n   * Eval treats {a: 1} as block with a labeled statement (return value 1).\n   * Detect these cases and enclose in parenthesis.\n   * But don't mess with: {var x = 1; x + x;}\n   * This is consistent with the console on Chrome and Node.\n   * If 'forceExpression' is true, then throw a SyntaxError if the src is\n   * more than one expression (e.g. '1; 2;').\n   */\n  var ast = null;\n  if (!forceExpression) {\n    // Try to parse src as a program.\n    try {\n      ast = $.utils.code.parse(src);\n    } catch (e) {\n      // ast remains null.\n    }\n  }\n  if (ast) {\n    if (ast.type === 'Program' && ast.body.length === 1 &&\n        ast.body[0].type === 'BlockStatement') {\n      if (ast.body[0].body.length === 0) {\n        // This is an empty object: {}\n        return '({})';\n      }\n      if (ast.body[0].body.length === 1 &&\n          ast.body[0].body[0].type === 'LabeledStatement' &&\n          ast.body[0].body[0].body.type === 'ExpressionStatement') {\n        // This is an unquoted object literal: {a: 1}\n        // There might be a comment, so add a linebreak.\n        return '(' + src + '\\n)';\n      }\n    }\n    return src;\n  }\n  // Try parsing src as an expression.\n  // This may throw.\n  ast = $.utils.code.parseExpressionAt(src, 0);\n  var remainder = src.substring(ast.end).trim();\n  if (remainder !== '') {\n    // Remainder might legally include trailing comments or semicolons.\n    // Remainder might illegally include more statements.\n    var remainderAst = null;\n    try {\n      remainderAst = $.utils.code.parse(remainder);\n    } catch (e) {\n      // remainderAst remains null.\n    }\n    if (!remainderAst) {\n      throw new SyntaxError('Syntax error beyond expression');\n    }\n    if (remainderAst.type !== 'Program') {\n      throw new SyntaxError('Unexpected code beyond expression');  // Module?\n    }\n    // Trim off any unnecessary trailing semicolons.\n    while (remainderAst.body[0] &&\n           remainderAst.body[0].type === 'EmptyStatement') {\n      remainderAst.body.shift();\n    }\n    if (remainderAst.body.length !== 0) {\n      throw new SyntaxError('Only one expression expected');\n    }\n  }\n  src = src.substring(0, ast.end);\n  if (ast.type === 'ObjectExpression' || ast.type === 'FunctionExpression') {\n    // {a: 1}  and function () {} both need to be wrapped in parens to avoid\n    // being syntax errors.\n    src = '(' + src + ')';\n  }\n  return src;\n};\nObject.setOwnerOf($.utils.code.rewriteForEval, $.physicals.Maximilian);\n$.utils.code.rewriteForEval.unittest = function() {\n  var cases = {\n    // Input: [Expression, Statement(s)]\n    '1 + 2': ['1 + 2', '1 + 2'],\n    '2 + 3  // Comment': ['2 + 3', '2 + 3  // Comment'],\n    '3 + 4;': ['3 + 4', '3 + 4;'],\n    '4 + 5; 6 + 7': [SyntaxError, '4 + 5; 6 + 7'],\n    '{}': ['({})', '({})'],\n    '{}  // Comment': ['({})', '({})'],\n    '{};': ['({})', '{};'],\n    '{}; {}': [SyntaxError, '{}; {}'],\n    '{\"a\": 1}': ['({\"a\": 1})', '({\"a\": 1})'],\n    '{\"a\": 2}  // Comment': ['({\"a\": 2})', '({\"a\": 2})'],\n    '{\"a\": 3};': ['({\"a\": 3})', '({\"a\": 3})'],\n    '{\"a\": 4}; {\"a\": 4}': [SyntaxError, SyntaxError],\n    '{b: 1}': ['({b: 1})', '({b: 1}\\n)'],\n    '{b: 2}  // Comment': ['({b: 2})', '({b: 2}  // Comment\\n)'],\n    '{b: 3};': ['({b: 3})', '{b: 3};'],\n    '{b: 4}; {b: 4}': [SyntaxError, '{b: 4}; {b: 4}'],\n    'function () {}': ['(function () {})', '(function () {})'],\n    'function () {}  // Comment': ['(function () {})', '(function () {})'],\n    'function () {};': ['(function () {})', '(function () {})'],\n    'function () {}; function () {}': [SyntaxError, SyntaxError],\n    '{} + []': ['{} + []', '{} + []']\n  };\n  var actual;\n  for (var key in cases) {\n    if (!cases.hasOwnProperty(key)) continue;\n    // Test eval as an expression.\n    try {\n      actual = $.utils.code.rewriteForEval(key, true);\n    } catch (e) {\n      actual = SyntaxError;\n    }\n    if (actual !== cases[key][0]) {\n      throw new Error('Eval Expression\\n' +\n                      'Expected: ' + cases[key][0] + ' Actual: ' + actual);\n    }\n    // Test eval as a statement.\n    try {\n      actual = $.utils.code.rewriteForEval(key, false);\n    } catch (e) {\n      actual = SyntaxError;\n    }\n    if (actual !== cases[key][1]) {\n      throw new Error('Eval Statement\\n' +\n                      'Expected: ' + cases[key][1] + ' Actual: ' + actual);\n    }\n  }\n};\n$.utils.code.eval = function $_utils_code_eval(src, evalFunc) {\n  // Eval src and attempt to print the resulting value readably.\n  //\n  // Evaluation is done by calling evalFunc (passing src) if supplied,\n  // or by calling the eval built-in function (under a different name,\n  // so it operates in the global scope).  Unhandled exceptions are\n  // caught and converted to a string.\n  //\n  // Caller may wish to transform input with\n  // $.utils.code.rewriteForEval before passing it to this function.\n  evalFunc = evalFunc || eval;\n  var out;\n  try {\n    out = evalFunc(src);\n  } catch (e) {\n    // Exception thrown.  Use built-in ToString via + to avoid calling\n    // String, least it call a .toString method that itself throws.\n    // TODO(cpcallen): find an alternative way of doing this safely\n    // once the interpreter calls String for all string conversions.\n    if (e instanceof Error) {\n      out = 'Unhandled error: ' + e.name;\n      if (e.message) out += ': ' + e.message;\n      if (e.stack) out += '\\n' + e.stack;\n      return out;\n    } else {\n      return 'Unhandled exception: ' + e;\n    }\n  }\n  // Suspend if needed.\n  try {(function(){})();} catch (e) {suspend();}\n  // Attempt to print a source-legal representation.\n  return $.utils.code.expressionFor(out, {\n    depth: 2,\n    abbreviateMethods: true,\n    proto: 'note',\n    owner: 'ignore'\n  });\n};\nObject.setOwnerOf($.utils.code.eval, $.physicals.Maximilian);\n$.utils.code.regexps = {};\n$.utils.code.regexps.README = '$.utils.code.regexps contains some RegExps useful for parsing or otherwise analysing code.\\n\\nSee ._generate() for how they are constructed and what they will match.\\n';\n$.utils.code.regexps._generate = function _generate() {\n  /* Generate some RegExps that match various bits of JavaScript syntax.\n   * The intention is that these regular expressions conform to the\n   * lexical grammar given ES5.1 Appendix A.1\n   * (https://262.ecma-international.org/5.1/#sec-A.1), in some cases\n   * updated to include changes in the current version of the spec\n   * (https://tc39.es/ecma262/#sec-lexical-grammar).\n   *\n   * TODO: add tests for generated RegExps.\n   */\n\n  // Globally matches escape sequences found in string and regexp\n  // literals, like '\\n' or '\\x20' or '\\u1234'.  (This is basically\n  // the spec EscapeSequence but including the backslash prefix.)\n  this.escapes = /\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g;\n\n  // Globally matches a single-quoted string literal, like \"'this one'\"\n  // and \"'it\\\\'s'\".\n  this.singleQuotedString =\n      new RegExp(\"'(?:[^'\\\\\\\\\\\\r\\\\n\\\\u2028\\\\u2029]|\" +\n                 this.escapes.source + \")*'\", 'g');\n\n  // Globally matches a double-quoted string literal, like '\"this one\"'\n  // and '\"it\\'s\"'.\n  this.doubleQuotedString =\n      new RegExp('\"(?:[^\"\\\\\\\\\\\\r\\\\n\\\\u2028\\\\u2029]|' +\n                 this.escapes.source + ')*\"', 'g');\n\n  // Globally matches a StringLiteral, like \"'this one' and '\"that one\"'\n  // as well as \"the 'string literal' substring of this longer string\" too.\n  this.string = new RegExp('(?:' + this.singleQuotedString.source + '|' +\n      this.doubleQuotedString.source + ')', 'g');\n\n  // Globally matches a valid JavaScript IdentifierName.  Note that\n  // this is conservative, because ANY Unicode letter can appear\n  // in an identifier - but the full regexp is absurdly complicated.\n  this.identifierName = /[A-Za-z_$][A-Za-z0-9_$]*/g;\n\n  // Matches a valid ES2020 ReservedWord.\n  var reserved = /await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|import|in|instanceof|new|null|return|super|switch|this|throw|true|try|typeof|var|void|while|with|yield/;\n  // Matches ES5.1 FutureReservedWords not included in reserved.\n  var reservedES5 = /implements|interface|let|package|protected|public|static/;\n  // Globally matches a valid JavaScript ReservedWord.\n  this.reservedWord =\n      new RegExp('(?:' + reserved.source + '|' + reservedES5.source + ')', 'g');\n\n  ////////////////////////////////////////////////////////////////////\n  // Exact forms of the above.  These do not get the global flag.\n  var keys = ['identifierName', 'reservedWord', 'string'];\n  for (var key, i = 0; (key = keys[i]); i++) {\n    this[key + 'Exact'] = new RegExp('^' + this[key].source + '$');\n  }\n\n};\nObject.setOwnerOf($.utils.code.regexps._generate.prototype, $.physicals.Maximilian);\n$.utils.code.regexps.escapes = /\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g;\n$.utils.code.regexps.singleQuotedString = /'(?:[^'\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*'/g;\n$.utils.code.regexps.doubleQuotedString = /\"(?:[^\"\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*\"/g;\n$.utils.code.regexps.string = /(?:'(?:[^'\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*'|\"(?:[^\"\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*\")/g;\n$.utils.code.regexps.identifierName = /[A-Za-z_$][A-Za-z0-9_$]*/g;\n$.utils.code.regexps.reservedWord = /(?:await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|import|in|instanceof|new|null|return|super|switch|this|throw|true|try|typeof|var|void|while|with|yield|implements|interface|let|package|protected|public|static)/g;\n$.utils.code.regexps.identifierNameExact = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n$.utils.code.regexps.reservedWordExact = /^(?:await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|import|in|instanceof|new|null|return|super|switch|this|throw|true|try|typeof|var|void|while|with|yield|implements|interface|let|package|protected|public|static)$/;\n$.utils.code.regexps.stringExact = /^(?:'(?:[^'\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*'|\"(?:[^\"\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*\")$/;\n$.utils.code.parseString = function parseString(s) {\n  /* Convert a string representation of a string literal to a string.\n   * Basically does eval(s), but safely and only if s is a string\n   * literal.\n   */\n  if (!this.regexps.stringExact.test(s)) {\n    throw new TypeError(this.quote(s) + ' is not a string literal');\n  }\n  return s.slice(1, -1).replace(this.regexps.escapes, function(esc) {\n    switch (esc[1]) {\n      case \"'\":\n      case '\"':\n      case '/':\n      case '\\\\':\n        return esc[1];\n      case '0':\n        return '\\0';\n      case 'b':\n        return '\\b';\n      case 'f':\n        return '\\f';\n      case 'n':\n        return '\\n';\n      case 'r':\n        return '\\r';\n      case 't':\n        return '\\t';\n      case 'v':\n        return '\\v';\n      case 'u':\n      case 'x':\n        return String.fromCharCode(parseInt(esc.slice(2), 16));\n      default:\n        // RegExp in call to replace has accepted something we\n        // don't know how to decode.\n        throw new Error('unknown escape sequence \"' + esc + '\"??');\n    }\n  });\n};\nObject.setOwnerOf($.utils.code.parseString, $.physicals.Maximilian);\n$.utils.code.quote = function quote(str) {\n  // Convert a string into a string literal.  We use single or double\n  // quotes depending on which occurs less frequently in the string to\n  // be escaped (prefering single quotes if it's a tie).  Strictly\n  // speaking we only need to escape backslash, \\r, \\n, \\u2028 (line\n  // separator), \\u2029 (paragraph separator) and whichever quote\n  // character we're using, but for output readability we escape all the\n  // control characters.\n  //\n  // TODO(cpcallen): Consider using optimised algorithm from Node.js's\n  //     util.format (see strEscape function in\n  //     https://github.com/nodejs/node/blob/master/lib/util.js).\n  // @param {string} str The string to convert.\n  // @return {string} The value s as a eval-able string literal.\n  if (this.count(str, \"'\") > this.count(str, '\"')) {  // More 's.  Use \"s.\n    return '\"' + str.replace(this.quote.doubleRE, this.quote.replace) + '\"';\n  } else {  // Equal or more \"s.  Use 's.\n    return \"'\" + str.replace(this.quote.singleRE, this.quote.replace) + \"'\";\n  }\n};\n$.utils.code.quote.singleRE = /[\\x00-\\x1f\\\\\\u2028\\u2029']/g;\n$.utils.code.quote.doubleRE = /[\\x00-\\x1f\\\\\\u2028\\u2029\"]/g;\n$.utils.code.quote.replace = function replace(c) {\n  // Replace special characters with their quoted replacements.\n  // Intended to be used as the second argument to\n  // String.prototype.replace.\n  return $.utils.code.quote.replacements[c];\n};\n$.utils.code.quote.replacements = {};\n$.utils.code.quote.replacements['\\0'] = '\\\\0';\n$.utils.code.quote.replacements['\\x01'] = '\\\\x01';\n$.utils.code.quote.replacements['\\x02'] = '\\\\x02';\n$.utils.code.quote.replacements['\\x03'] = '\\\\x03';\n$.utils.code.quote.replacements['\\x04'] = '\\\\x04';\n$.utils.code.quote.replacements['\\x05'] = '\\\\x05';\n$.utils.code.quote.replacements['\\x06'] = '\\\\x06';\n$.utils.code.quote.replacements['\\x07'] = '\\\\x07';\n$.utils.code.quote.replacements['\\b'] = '\\\\b';\n$.utils.code.quote.replacements['\\t'] = '\\\\t';\n$.utils.code.quote.replacements['\\n'] = '\\\\n';\n$.utils.code.quote.replacements['\\v'] = '\\\\v';\n$.utils.code.quote.replacements['\\f'] = '\\\\f';\n$.utils.code.quote.replacements['\\r'] = '\\\\r';\n$.utils.code.quote.replacements['\\x0e'] = '\\\\x0e';\n$.utils.code.quote.replacements['\\x0f'] = '\\\\x0f';\n$.utils.code.quote.replacements['\"'] = '\\\\\"';\n$.utils.code.quote.replacements[\"'\"] = \"\\\\'\";\n$.utils.code.quote.replacements['\\\\'] = '\\\\\\\\';\n$.utils.code.quote.replacements['\\u2028'] = '\\\\u2028';\n$.utils.code.quote.replacements['\\u2029'] = '\\\\u2029';\n$.utils.code.count = function count(str, searchString) {\n  // Count non-overlapping occurrences of searchString in str.\n  return str.split(searchString).length;\n};\n$.utils.code.isIdentifier = function isIdentifier(id) {\n  /* Arguments:\n   * - id: any - any JavaScript value.\n   *\n   * Returns: boolean - true iff id is a string representing valid\n   *     Identifier, which is any bare word that can be used\n   *     as a variable name (i.e., excluding reserved words).\n   */\n  return $.utils.code.isIdentifierName(id) &&\n      !$.utils.code.regexps.reservedWordExact.test(id);\n};\nObject.setOwnerOf($.utils.code.isIdentifier, $.physicals.Maximilian);\n$.utils.code.getGlobal = function getGlobal() {\n  // Return a pseudo global object.\n  var global = Object.create(null);\n  global.$ = $;\n  global.Array = Array;\n  global.Boolean = Boolean;\n  global.clearTimeout = clearTimeout;\n  global.Date = Date;\n  global.decodeURI = decodeURI;\n  global.decodeURIComponent = decodeURIComponent;\n  global.encodeURI = encodeURI;\n  global.encodeURIComponent = encodeURIComponent;\n  global.Error = Error;\n  global.escape = escape;\n  global.eval = eval;\n  global.EvalError = EvalError;\n  global.Function = Function;\n  global.isFinite = isFinite;\n  global.isNaN = isNaN;\n  global.JSON = JSON;\n  global.Math = Math;\n  global.Number = Number;\n  global.Object = Object;\n  global.parseFloat = parseFloat;\n  global.parseInt = parseInt;\n  global.perms = perms;\n  global.RangeError = RangeError;\n  global.ReferenceError = ReferenceError;\n  global.RegExp = RegExp;\n  global.setPerms = setPerms;\n  global.setTimeout = setTimeout;\n  global.String = String;\n  global.suspend = suspend;\n  global.SyntaxError = SyntaxError;\n  global.Thread = Thread;\n  global.TypeError = TypeError;\n  global.unescape = unescape;\n  global.URIError = URIError;\n  global.user = user;\n  global.WeakMap = WeakMap;\n  return global;\n};\nObject.setOwnerOf($.utils.code.getGlobal, $.physicals.Maximilian);\n$.utils.code.parse = new 'CC.acorn.parse';\n$.utils.code.parseExpressionAt = new 'CC.acorn.parseExpressionAt';\n$.utils.code.isIdentifierName = function isIdentifierName(id) {\n  /* Arguments:\n   * - id: any - any JavaScript value.\n   *\n   * Returns: boolean - true iff id is a string representing valid\n   *     IdentifierName, which is anything bare word that can appear\n   *     after the '.' in a MemberExpresion.\n   */\n  return typeof id === 'string' &&\n      $.utils.code.regexps.identifierNameExact.test(id);\n};\nObject.setOwnerOf($.utils.code.isIdentifierName, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.code.isIdentifierName.prototype, $.physicals.Maximilian);\n$.utils.code.expressionFor = function expressionFor(value, options) {\n  /* Given an arbitrary value, return a string containing a JavaScript\n   * expression for it.\n   *\n   * The intention is that expressionFor(value) should return a string\n   * such that eval(expressionFor(value)) will be (in order of preference):\n   *\n   * - Identical to value (as determined by Object.is), or\n   * - An equivalent copy of value to a specified depth, or\n   * - Be unparsable or contain comments explaining in what way the\n   *   result of eval will differ from original value.\n   *\n   * Arguments:\n   * - value: any - any JavaScript value.\n   * - options?: Object - optional options object.  See implementation.\n   *\n   * Returns: string - an expression for value.\n   *\n   * TODO: there should be flags controlling what to do when it is not\n   * possible to construct an expression that will eval to an exact copy\n   * of value.  The options should include returning valid code containing\n   * comments, returning unparsable code, or throwing an an error.\n   */\n  var opts = {\n    depth: 10,  // How deeply shall we traverse the object tree?\n    arrayLimit: 100,  // Max number of array elements to include.\n    propertyLimit: 100,  // Max number of properties to include.\n    abbreviateFunctions: false,  // Elide all function bodies?\n    abbreviateMethods: false,  // Elide method function bodies?\n    proto: 'set',  // 'set', 'note' or (any other value) ignore prototype.\n    owner: 'note',  // 'set', 'note' or (any other value) ignore owner.\n    lineLength: 80,  // Line length limit, for formatting purposes.\n    indent: 2,  // Indent for nested expressions.\n    seen_: [],  // TODO: use Set instead of Array.\n  };\n  // Like Object.assign(opts, options) but copies inherited properties too.\n  for (var k in options) opts[k] = options[k];\n\n  // Helper to handle failures where expressionFor cannot or does not yet\n  // return an experssion that will eval to an identical copy of value.\n  // Typical usage: return fail('reason for failure');\n  function fail(message) {\n    // TODO: have flag to make it:\n    // throw new ReferenceError(message);\n    return $.utils.code.blockComment(message);\n  }\n\n  // Helper for properties in array and object literals.\n  function expressionForProperty(key) {\n    var descriptor = Object.getOwnPropertyDescriptor(value, key);\n    var propertyValue = descriptor.value;\n    if (selector) {\n      opts.selector = new $.Selector(selector.concat(key));\n    }\n    opts.abbreviateFunctions = opts.abbreviateMethods;\n    return expressionFor(propertyValue, opts);\n  }\n\n  var type = typeof value;\n  if (value === undefined || value === null ||\n      type === 'number' || type === 'boolean') {\n    if (Object.is(value, -0)) return '-0';\n    return String(value);\n  } else if (type === 'string') {\n    return $.utils.code.quote(value);\n  } else if (type !== 'function' && type !== 'object') {\n    throw new TypeError(\"unknown type '\" + type + \"'\");\n  }\n\n  // value is an object of some kind (including function).  Work out a selector.\n  var selector = $.Selector.for(value);\n  if (opts.selector) {\n    var suggestedSelectorValue = opts.selector.toValue(/*save:*/true);\n    if (!selector && suggestedSelectorValue === value) {\n      selector = opts.selector;\n    }\n  }\n\n  // Deal with already-seen objects (and nesting limit depth limit).\n  if (opts.seen_.includes(value)) {\n    return fail('cyclic or shared substructure' +\n                (selector ? ': ' + selector.toString() : 'with no known selector'));\n  } else if (opts.depth < 1) {\n    if (!selector) return fail(type + ' with no known selector');\n    return selector.toExpr();\n  }\n  // Prepare for recursive calls.\n  opts.seen_.push(value);\n  opts.depth--;\n  opts.lineLength -= opts.indent;\n\n  // Get the object's [[Class]] - Object, Array, Date, RegExp, Error, etc.\n  // Since 'class' isn't a legal variable name, re-use 'type'.\n  type = Object.prototype.toString.call(value).slice(8, -1);\n  var proto = Object.getPrototypeOf(value);  // Actual prototype of value.\n  var expectedProto;  // Expected prototype of object of same [[Class]] as value.\n  var prefix = '', expr = '', suffix = '';  // Concatenate to get final expression.\n  var entries;  // Array of initialisers for object or array literal.\n  var notes = []; // Array of notes to postpend as comment.\n\n  // Make a note about the object's selector unless it is the expected\n  // one.  Decide this before recursive calls mess with opts.selector.\n  var selectorNote = selector ? selector.toString() : '';\n  if (opts.selector && selectorNote === opts.selector.toString()) {\n    selectorNote = '';\n  }\n\n  if (type === 'Array') {\n    if (!Array.isArray(value)) throw TypeError('non-array array??');\n    expectedProto = Array.prototype;\n    prefix = '[';\n    suffix = ']';\n    entries = [];\n    for (var i = 0; i < value.length; i++) {\n      suspend();\n      if (i >= opts.arrayLimit) {\n        entries[i] = $.utils.code.blockComment('and ' + (value.length - opts.arrayLimit) + ' more');\n        break;\n      } else if (!Object.hasOwnProperty.call(value, i)) {\n        entries[i] = '';\n        continue;\n      }\n      entries[i] = expressionForProperty(String(i));\n    }\n  } else if (type === 'Date') {\n    expr = 'new Date(\\'' + value.toJSON() + '\\')';\n    expectedProto = Date.prototype;\n  } else if (type === 'Error') {\n    expectedProto = proto;\n    switch (proto) {\n      case EvalError.prototype: prefix = 'EvalError'; break;\n      case RangeError.prototype:  prefix = 'RangeError'; break;\n      case ReferenceError.prototype: prefix = 'ReferenceError'; break;\n      case SyntaxError.prototype: expr = 'SyntaxError'; break;\n      case TypeError.prototype: expr = 'TypeError'; break;\n      case URIError.prototype: expr = 'URIError'; break;\n      case PermissionError.prototype: expr = 'PermissionError'; break;\n      default:\n        expr = 'Error';\n        expectedProto = Error.prototype;\n    }\n    if (typeof value.message === 'string') {\n      expr += '(' + $.utils.code.quote(value.message) + ')';\n    } else {\n      expr += '()';\n    }\n  } else if (type === 'Function') {\n    expectedProto = Function.prototype;\n    expr = Function.prototype.toString.call(value);\n    if (opts.abbreviateFunctions) {\n      expr = fail(expr.replace(/\\{[^]*$/, '{ ... }'));\n    }\n  } else if (type === 'Object') {\n    expectedProto = Object.prototype;\n    prefix = '{';\n    suffix = '}';\n    entries = [];\n    var keys = Object.getOwnPropertyNames(value);\n    for (var i = 0; i < keys.length; i++) {\n      suspend();\n      if (i >= opts.propertyLimit) {\n        entries[i] = '/* and ' + (keys.length - opts.propertyLimit) + ' more */';\n        break;\n      }\n      var key = keys[i];\n      // BUG(#469): property keys that are NumericLiterals (like 3.2e4\n      // or 0xf00) can also appear unquoted!\n      entries[i] =\n        ($.utils.code.isIdentifierName(key) ? key : $.utils.code.quote(key)) +\n        ': ' + expressionForProperty(key);\n    }\n  } else if (type === 'RegExp') {\n    expr = RegExp.prototype.toString.call(value);\n    expectedProto = RegExp.prototype;\n  } else if (type === 'Thread') {\n    if (selector) return selector.toExpr();\n    expr = 'new Thread(' + fail('unable to reconstruct thread state') + ')';\n    expectedProto = Thread.prototype;\n  } else if (type === 'WeakMap') {\n    expectedProto = WeakMap.prototype;\n    expr = 'new WeakMap()';\n  } else {\n    throw new TypeError('unknown internal type ' + type);\n  }\n\n  // TODO: Prepend/append call to Object.defineProperties for remaining\n  // properties & property attributes.\n\n  // Pre/append prototype information if it is not as expected.\n  if (proto !== expectedProto) {\n    var protoString = expressionFor(proto, {depth: 0});\n    if (opts.proto === 'set') {\n      prefix = 'Object.setPrototypeOf(' + prefix;\n      suffix += ', ' + protoString + ')';\n    } else if (opts.proto === 'note') {\n      notes.push('[[Proto]]: ' + protoString);\n    }\n  }\n\n  // Prepend/append owner information.\n  var ownerString = expressionFor(Object.getOwnerOf(value), {depth: 0});\n  if (opts.owner === 'set') {\n    // BUG: Object.setOwnerOf(obj, owner) does not return obj (yet).\n    throw new Error(\"can't set owner in an expression yet\");\n    // prefix = 'Object.setOwnerOf(' + prefix;\n    // suffix += ', ' + ownerString + ')';\n  } else if (opts.owner === 'note') {\n    notes.push('[[Owner]]: ' + ownerString);\n  }\n\n  // Prepend/append notes.\n  if (selectorNote)  {\n    prefix = $.utils.code.blockComment(selectorNote) + ' ' + prefix;\n  }\n  if (notes.length) {\n    suffix += ' ' + $.utils.code.blockComment(notes.join(', '));\n  }\n\n  // Join entries choosing a suitable layout depending on available space.\n  if (entries && entries.length) {\n    // Try single-line output.\n    // BUG: this omits required trailing comma when there are undefined\n    // trailing aray elements (e.g., [1, 2, 3,,].\n    expr = entries.join(', ');\n    var result = prefix + expr + suffix;\n    if (result.length <= opts.lineLength && !result.includes('\\n')) {\n      return result;\n    }\n\n    // Generate multi-line output.\n    var padding = ' '.repeat(opts.indent);\n    expr = '\\n' + $.utils.string.prefixLines(entries.join(',\\n'), padding) + ',\\n';\n  }\n\n  return prefix + expr + suffix;\n};\nObject.setOwnerOf($.utils.code.expressionFor, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.code.expressionFor.prototype, $.physicals.Maximilian);\n$.utils.code.blockComment = function blockComment(text) {\n  /* Format text as a block comment.  Any occurences of the closing\n   * block comment delimiter in text will have a space inerted in them.\n   * If text is undefined, an empty string will be returned instead.\n   *\n   * Arguments:\n   * - text: string | undefined - the contents of the comment.\n   * Returns: string - the block comment.\n   */\n  return text ? '/* ' + text.replace(/\\*\\//g, '* /') + ' */' : '';\n};\nObject.setOwnerOf($.utils.code.blockComment, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.code.blockComment.prototype, $.physicals.Maximilian);\n\n"
  },
  {
    "path": "core/core_13_$.Selector.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Selector implementation for Code City core.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.Selector = function Selector(s) {\n  /* A Selector is a representation of a selector string in the form\n   * of an array (of Selector.Parts) which happens to have\n   * Selector.prototype (with various useful convenience methods) in\n   * its prototype chain.\n   */\n  var parts;\n  if (typeof s === 'string') {\n    // Parse selector text (but check in cache first).\n    var cached = Selector.cache_[s];\n    // Copy and set owner?\n    if (cached) return cached;\n    parts = Selector.parse(s);\n  } else if (Array.isArray(s)) {\n    parts = [];\n    // Validate & copy parts list.\n    if (s.length < 1) throw new RangeError('Zero-length parts list??');\n    if (!$.utils.code.isIdentifier(s[0])) {\n      throw new TypeError('parts array must begin with an identifier');\n    }\n    parts[0] = s[0];\n    for (var i = 1; i < s.length; i++) {\n      if (typeof s[i] === 'string' || s[i] === Selector.PROTOTYPE || s[i] === Selector.OWNER) {\n        parts[i] = s[i];\n      } else if (s[i] instanceof Selector.SpecialPart) {\n        throw new TypeError('Invalid SpecialPart in parts array');\n      } else if (typeof s[i] === 'object' && s[i].type) {\n        // Handle normalisation of parts lists that have been roundtripped via JSON.\n        switch(s[i].type) {\n          case 'proto':\n            parts[i] = Selector.PROTOTYPE;\n            break;\n          case 'owner':\n            parts[i] = Selector.OWNER;\n            break;\n          default:\n          throw new TypeError('Unknown SpecialPart type ' + s[i].type);\n        }\n      } else {\n        throw new TypeError('Invalid part in parts array');\n      }\n    }\n  } else {\n    throw new TypeError('Not a selector or parts array');\n  }\n  Object.setPrototypeOf(parts, Selector.prototype);\n  Object.freeze(parts);\n  // Copy and set owner?\n  Selector.cache_[parts.toString()] = parts;  // Save.\n  return parts;\n};\nObject.setOwnerOf($.Selector, $.physicals.Maximilian);\nObject.setPrototypeOf($.Selector.prototype, Array.prototype);\n$.Selector.prototype.isOwner = function isOwner() {\n  /* Returns true iff the selector represents an object owner binding.\n   */\n  return this.length > 1 && this[this.length - 1] === this.constructor.OWNER;\n};\nObject.setOwnerOf($.Selector.prototype.isOwner, $.physicals.Maximilian);\n$.Selector.prototype.isProp = function isProp() {\n  /* Returns true iff the selector represents an object property binding.\n   */\n  return this.length > 1 && typeof this[this.length - 1] === 'string';\n};\nObject.setOwnerOf($.Selector.prototype.isProp, $.physicals.Maximilian);\n$.Selector.prototype.isProto = function isProto() {\n  /* Returns true iff the selector represents an object prototype binding.\n   */\n  return this.length > 1 && this[this.length - 1] === this.constructor.PROTOTYPE;\n};\nObject.setOwnerOf($.Selector.prototype.isProto, $.physicals.Maximilian);\n$.Selector.prototype.isVar = function isVar() {\n  /* Returns true iff the selector represents a top-level variable binding.\n   */\n  return this.length === 1 && typeof this[0] === 'string';\n};\nObject.setOwnerOf($.Selector.prototype.isVar, $.physicals.Maximilian);\n$.Selector.prototype.toExpr = function toExpr() {\n  /* Return the selector as an evaluable expression yeilding the selected value.\n   */\n  return this.toString(function(part, out) {\n    if (part === $.Selector.PROTOTYPE) {\n      out.unshift('Object.getPrototypeOf(');\n      out.push(')');\n    } else if (part === $.Selector.OWNER) {\n      out.unshift('Object.getOwnerOf(');\n      out.push(')');\n    } else {\n      throw new TypeError('Invalid part in parts array');\n    }\n  });\n};\nObject.setOwnerOf($.Selector.prototype.toExpr, $.physicals.Maximilian);\n$.Selector.prototype.toSetExpr = function toSetExpr(valueExpr) {\n  /* Return an expression setting the selected value to the value of the\n   * supplied expression.\n   *\n   * The parameter valueExpr should be a string containing a JS expression that\n   * evaluates to the new value to be assigned to the selected location.  It\n   * must not contain any non-parenthesized operators with lower precedence\n   * than '=' - specifically, the yield and comma operators.\n   */\n  var lastPart = this[this.length - 1];\n  if (!(lastPart instanceof this.constructor.SpecialPart)) {\n    return this.toExpr() + ' = ' + valueExpr;\n  }\n  var objExpr = new this.constructor(this.slice(0, -1)).toExpr();\n  if (lastPart === this.constructor.PROTOTYPE) {\n    return 'Object.setPrototypeOf(' + objExpr + ', ' + valueExpr + ')';\n  } else if (lastPart === this.constructor.OWNER) {\n    return 'Object.setOwnerOf(' + objExpr + ', ' + valueExpr + ')';\n  } else {\n    throw new TypeError('Invalid part in parts array');\n  }\n};\nObject.setOwnerOf($.Selector.prototype.toSetExpr, $.physicals.Maximilian);\n$.Selector.prototype.toString = function toString(specialHandler) {\n  /* Return the canonical selector string for this Selector.\n   *\n   * The specialHandler optional parameter, if supplied, should be callback\n   * which accepts a Selector.SpecialPart instance and an Array of strings, and\n   * pushes a string representation of the SpecialPart onto the array.  (See\n   * Selector.prototype.toExpr for an example of how to use this.)\n   */\n  var out = [this[0]];\n  for (var i = 1; i < this.length; i++) {\n    var part = this[i];\n    if (part instanceof this.constructor.SpecialPart) {\n      if (specialHandler) {\n        specialHandler(part, out);\n      } else {\n        out.push(String(part));\n      }\n    } else if ($.utils.code.isIdentifierName(part)) {\n      out.push('.', part);\n    } else if (String(Number(part)) === part) {\n      // String represents a number with same string representation.\n      out.push('[', part, ']');\n    } else {\n      out.push('[', $.utils.code.quote(part), ']');\n    }\n  }\n  return out.join('');\n};\nObject.setOwnerOf($.Selector.prototype.toString, $.physicals.Maximilian);\n$.Selector.prototype.toValue = function toValue(save, global) {\n  /* Return value corresponding to this Selector, or throw EvalError if that is\n   * not possible.  This function basically does\n   *\n   *     return eval(this.toExpr())\n   *\n   * ...only slightly more safely.\n   *\n   * Added bonus features:\n   * - If this selector evaluates to an object and save is true, the  selector\n   *   will be added to the the reverse-lookup database.\n   * - If global is specified, global variables will be evaluated by looking\n   *   them up as properties on that object.\n   */\n  if (this.length === 0) throw RangeError('Invalid Selector');\n  var varname = this[0];\n  if (!$.utils.code.isIdentifier(varname)) {\n    throw TypeError('invalid variable identifier');\n  }\n  var v;\n  if (global) {\n    v = global[varname];\n  } else {\n    try {\n      var globalEval = eval;\n      v = globalEval(varname);\n    } catch (e) {\n      v = undefined;\n    }\n  }\n  for (var i = 1; i < this.length; i++) {\n    if (!$.utils.isObject(v)) {\n      var s = new this.constructor(this.slice(0, i));\n      throw TypeError(String(s) + ' is not an object');\n    }\n    var part = this[i];\n    if (typeof part === 'string') {\n      v = v[part];\n    } else if (part === this.constructor.PROTOTYPE) {\n      v = Object.getPrototypeOf(v);\n    } else if (part === this.constructor.OWNER) {\n      v = Object.getOwnerOf(v);\n    } else {\n      throw new Error('Not implemented');\n    }\n  }\n  if (save) {\n    this.constructor.db.set(v, this);\n  }\n  return v;\n};\nObject.setOwnerOf($.Selector.prototype.toValue, $.physicals.Maximilian);\n$.Selector.prototype.badness = function badness() {\n  /* Returns a \"badness\" score, inversely proportional to how\n   * desirable a particular selector is amongst other selectors\n   * referring to the same object.  In general, longer selectors are\n   * more bad, but selectors containing special parts are especially\n   * bad.\n   */\n  var penalties = 0;\n  for (var i = 0; i < this.length; i++) {\n    var part = this[i];\n    if (part instanceof this.constructor.SpecialPart) {\n      penalties += 100;\n    } else if ($.utils.code.isIdentifierName(part)) {\n      penalties += 10;  // We like identifiers.\n    } else if (String(Number(part)) === part) {\n      penalties += 25;  // Numbers are OK.\n    } else {\n      penalties += 50;  // Quoted strings are undesirable.\n    }\n  }\n  if (this[0] === '$') penalties += 50;  // Prefer builtins.\n  return penalties + String(this).length;\n};\nObject.setOwnerOf($.Selector.prototype.badness, $.physicals.Maximilian);\n$.Selector.SpecialPart = function SpecialPart(type) {\n  // A SpecialPart is a class for all \"special\" selector parts (ones\n  // which do not represent named variables / properties).\n  this.type = type;\n  Object.freeze(this);\n};\n$.Selector.SpecialPart.prototype.toString = function toString() {\n  return '{' + this.type + '}';\n};\nObject.setOwnerOf($.Selector.SpecialPart.prototype.toString, $.physicals.Maximilian);\n$.Selector.PROTOTYPE = (new 'Object.create')($.Selector.SpecialPart.prototype);\n$.Selector.PROTOTYPE.type = 'proto';\nObject.defineProperty($.Selector.PROTOTYPE, 'type', {writable: false, configurable: false});\nObject.preventExtensions($.Selector.PROTOTYPE);\n$.Selector.OWNER = (new 'Object.create')($.Selector.SpecialPart.prototype);\n$.Selector.OWNER.type = 'owner';\nObject.defineProperty($.Selector.OWNER, 'type', {writable: false, configurable: false});\nObject.preventExtensions($.Selector.OWNER);\n$.Selector.parse = function parse(selector) {\n  // Parse a selector into an array of Parts.\n  var tokens = this.parse.tokenize(selector);\n  var parts = [];\n  var State = {\n    START: 0, GOOD: 1, DOT: 2, BRACKET: 3, BRACKET_DONE: 4,\n    BRACE: 5, BRACE_DONE: 6\n  };\n  var state = State.START;\n  for (var i = 0; i < tokens.length; i++) {\n    var token = tokens[i];\n    if (token.type === 'whitespace') continue;\n    switch (state) {\n      case State.START:\n        if (token.type !== 'id') {\n          throw new SyntaxError('Selector must start with an identifier');\n        }\n        parts.push(token.raw);\n        state = State.GOOD;\n        break;\n\n      case State.GOOD:\n        if (token.type === '.') {\n          state = State.DOT;\n        } else if (token.type === '[') {\n          state = State.BRACKET;\n        } else if (token.type === '{') {\n          state = State.BRACE;\n        } else if (token.type === '^') {\n          // State remains unchanged.\n          parts.push(this.PROTOTYPE);\n        } else {\n          throw new SyntaxError('Invalid token ' + $.utils.code.quote(token.raw)  + ' in selector');\n        }\n        break;\n\n      case State.DOT:\n        if (token.type !== 'id') {\n          throw new SyntaxError('\".\" must be followed by identifier in selector');\n        }\n        parts.push(token.raw);\n        state = State.GOOD;\n        break;\n\n      case State.BRACKET:\n        if (token.type === 'number') {\n          parts.push(String(token.raw));\n        } else if (token.type === 'str') {\n          parts.push(String(token.value));\n        } else {\n          throw new SyntaxError('\"[\" must be followed by numeric or string literal in selector');\n        }\n        state = State.BRACKET_DONE;\n        break;\n\n      case State.BRACKET_DONE:\n        if (token.type !== ']') {\n          throw new SyntaxError('Invalid token ' + $.utils.code.quote(token.raw)  + ' after subscript');\n        }\n        state = State.GOOD;\n        break;\n\n      case State.BRACE:\n        if (token.type === 'id' && token.raw === 'proto') {\n          parts.push(this.PROTOTYPE);\n        } else if (token.type === 'id' && token.raw === 'owner') {\n          parts.push(this.OWNER);\n        } else {\n          throw new SyntaxError('\"{\" must be followed by \"proto\" or \"owner\"');\n        }\n        state = State.BRACE_DONE;\n        break;\n\n      case State.BRACE_DONE:\n        if (token.type !== '}') {\n          throw new SyntaxError('Invalid token ' + $.utils.code.quote(token.raw)  + ' after special');\n        }\n        state = State.GOOD;\n        break;\n\n      default:\n        throw new Error('Invalid State in parse??');\n    }\n  }\n  if (state !== State.GOOD) {\n    throw new SyntaxError('Incomplete selector ' + selector);\n  }\n  return parts;\n};\nObject.setOwnerOf($.Selector.parse, $.physicals.Maximilian);\n$.Selector.parse.tokenize = function tokenize(selector) {\n  // Tokenizes a selector string.  Throws a SyntaxError if any text is\n  // found which does not form a valid token.\n  var REs = {\n    whitespace: /^\\s+/g,\n    '.': /^\\./g,\n    id: new RegExp('^' + $.utils.code.regexps.identifierName.source, 'g'),\n    number: /^\\d+/g,\n    '[': /^\\[/g,\n    ']': /^\\]/g,\n    '{': /^\\{/g,\n    '}': /^\\}/g,\n    '^': /^\\^/g,\n    str: new RegExp('^' + $.utils.code.regexps.string.source, 'g'),\n  };\n\n  var tokens = [];\n  NEXT_TOKEN: for (var index = 0; index < selector.length; ) {\n    for (var tokenType in REs) {\n      if (!REs.hasOwnProperty(tokenType)) continue;\n      var re = REs[tokenType];\n      re.lastIndex = 0;\n      var m = re.exec(selector.slice(index));\n      if (!m) continue;  // No match.  Try next regexp.\n      tokens.push({\n        type: tokenType,\n        raw: m[0],\n        valid: true,\n        index: index,\n      });\n      index += re.lastIndex;\n      continue NEXT_TOKEN;\n    }\n    // No token matched.\n    throw new SyntaxError('invalid selector ' + selector);\n  }\n\n  // Postprocess token list to get values.\n  for(var i = 0; i < tokens.length; i++) {\n    var token = tokens[i];\n    if (token.type === 'number') {\n      token.value = Number(token.raw);\n    } else if (token.type === 'str') {\n      token.value = $.utils.code.parseString(token.raw);\n    }\n  }\n  return tokens;\n};\nObject.setOwnerOf($.Selector.parse.tokenize, $.physicals.Maximilian);\n$.Selector.for = function Selector_for(object) {\n  /* Return a Selector for object, or undefined if none known.\n   */\n  return this.db.get(object);\n};\nObject.setOwnerOf($.Selector.for, $.physicals.Maximilian);\n$.Selector.db = {};\n$.Selector.db.map_ = new WeakMap();\n$.Selector.db.set = function set(object, selector) {\n  if (!$.utils.isObject(object)) return;  // Ignore non-object values.\n  if (!(selector instanceof $.Selector)) {\n    throw new TypeError('Second argument must be a Selector');\n  }\n  var selectorString = selector.toString();\n\n  var known = this.map_.get(object) || [];\n  // See if this selector is already known.\n  if (known.includes(selectorString)) return;  // Already known.  Ignore.\n  // Add new entry.\n  known.push(selectorString);\n  // Sort by badness, trim to length and save.\n  $.Selector.sortByBadness(known);\n  this.map_.set(object, known.slice(0, this.diversityLimit));\n};\nObject.setOwnerOf($.Selector.db.set, $.physicals.Maximilian);\n$.Selector.db.README = 'Selector.db is database mapping objects to Selectors.\\n\\nThis info is stored in Selector.db.map_, which is a WeakMap mapping objects to entries.\\n\\nEach entry is an object whose keys are selector strings and values are the corresponding Selectors (i.e., parts lists).';\n$.Selector.db.diversityLimit = 5;\n$.Selector.db.get = function get(object) {\n  if (!$.utils.isObject(object)) return undefined;\n  var known = this.map_.get(object);\n  while (known && known.length) {\n    var selector = new $.Selector(known[0]);\n    var value = null;\n    try {\n      value = selector.toValue();\n    } catch (e) {}\n    if (value === object) {\n      return selector;\n    } else {\n      known.shift();  // Remove 0th item.\n    }\n  }\n  return undefined;  // Ran out of known, valid selectors.\n};\nObject.setOwnerOf($.Selector.db.get, $.physicals.Maximilian);\n$.Selector.db.populate = function populate() {\n  /* Spider the object graph, starting from the global scope, to\n   * (re)build the reverse-lookup database.\n   *\n   * We apply a version of Dijkstra's algorithm, specifically a BFS\n   * over valid Selectors, where we reenqueue children of previously-\n   * -visited objects if we find a better Selector for the parent\n   * object.\n   */\n  // Prevent this function from running more than once at a time.\n  if (populate.thread_) throw new Error('already running');\n  try {\n    populate.thread_ = Thread.current();\n\n    var queue = Object.getOwnPropertyNames($.utils.code.getGlobal()).map(\n      function (ss) {return new $.Selector(ss);});\n    var seen = new WeakMap();\n    for (var i = 0; i < queue.length; i++) {\n      suspend();\n      var s = queue[i];\n      var v = s.toValue(/*save:*/true);\n      if (!$.utils.isObject(v)) continue;  // Skip primitives completely.\n      var best = $.Selector.for(v);\n      if (seen.has(v) && s !== best) continue;\n      seen.set(v, true);\n\n      var parts = [$.Selector.PROTOTYPE, $.Selector.OWNER].concat(Object.getOwnPropertyNames(v));\n      for (var j = 0; j < parts.length; j++) {\n        var part = parts[j];\n        if (part === 'cache_') continue;  // Skip .cache_ properties.\n        queue.push(new $.Selector(s.concat(part)));\n      }\n    }\n\n  } finally {\n    populate.thread_ = null;\n  }\n\n};\nObject.setOwnerOf($.Selector.db.populate, $.physicals.Maximilian);\nObject.setOwnerOf($.Selector.db.populate.prototype, $.physicals.Maximilian);\n$.Selector.db.populate.thread_ = null;\n$.Selector.sortByBadness = function sortByBadness(selectors) {\n  // Sort an array (or arraylike), which may contain Selectors,\n  // (valid) selector strings, or a mix of the two, according to their\n  // score, as returned by Selector.prototype.badness(), with the the\n  // lowest-badness ones sorted first.\n  if (!$.utils.isObject(selectors) || typeof selectors.length != 'number') {\n    throw new TypeError('argument must be an arraylike');\n  }\n  // Begin by populating a badness cache, for quick lookups.\n  var cache = sortByBadness.cache_;\n  for (var i = 0; i < selectors.length; i++) {\n    var s, ss = selectors[i];\n    if (typeof ss === 'string') {\n      s = new $.Selector(ss);\n    } else if (ss instanceof $.Selector) {\n      s = ss;\n      ss = ss.toString();\n    }\n    if (ss in cache) continue;\n    cache[ss] = s.badness();\n  }\n  // Do sort.  Optimised for sorting selector strings, since\n  // that's what's needed by $.Selector.db.put.\n  Array.prototype.sort.call(selectors, function compare(a, b) {\n    if (typeof a !== 'string') a = String(a);\n    if (typeof b !== 'string') b = String(b);\n    return cache[a] - cache[b];\n  });\n  return selectors;\n};\nObject.setOwnerOf($.Selector.sortByBadness, $.physicals.Maximilian);\n\n$.utils.Binding = function Binding(object, part) {\n  /* A binding is essentially just an (object, part) tuple, where part\n   * is a string or a Selector.SpecialPart.\n   *\n   * If object is null, part must be a string conforming to the\n   * syntax of an identifier; in this case the binding represents\n   * a variable in the global scope.\n   */\n  if (object === null) {\n    if (!$.utils.code.isIdentifier(part)) {\n      throw TypeError('Invalid variable name');\n    }\n  } else if (!$.utils.isObject(object)) {\n    throw TypeError('Invalid object');\n  } else if (typeof part !== 'string' &&\n             part !== $.Selector.PROTOTYPE &&\n             part !== $.Selector.OWNER) {\n    throw TypeError('Invalid part');\n  }\n  this.object = object;\n  this.part = part;\n};\nObject.setOwnerOf($.utils.Binding, $.physicals.Maximilian);\n$.utils.Binding.prototype.set = function set(value) {\n  /* Set the value of the binding.  Throws TypeError if unable.\n   */\n  if (this.object === null) {\n    if (!Object.prototype.hasOwnProperty.call($.utils.code.getGlobal(), this.part)) {\n      throw new TypeError(\"Can't create new global variable\");\n    }\n    // Use a temporary property and an eval in the global scope (eval\n    // by any other name, literally) to set the global variable\n    // \"safely\".  The temporary property is placed on $ rather than\n    // using $.db.tempId to avoid the possibility of the eval\n    // somehow being subverted to access a different value than\n    // expected due to one of the intervening objects being\n    // compromised (by a getter, say).\n    var tmpId;\n    do {\n      tmpId = 'tmp' + Math.floor(Math.random() * 0xFFFFFFFF);\n    } while (tmpId in $);\n    var evalGlobal = eval;\n    try {\n      $[tmpId] = value;\n      evalGlobal(this.part + ' = $.' + tmpId);\n    } finally {\n      delete $[tmpId];\n    }\n  } else if(this.part === $.Selector.PROTOTYPE) {\n    Object.setPrototypeOf(this.object, value);\n  } else if(this.part === $.Selector.OWNER) {\n    Object.setOwnerOf(this.object, value);\n  } else {\n    // BUG: doesn't handle non-writable properties.\n    this.object[this.part] = value;\n  }\n};\nObject.setOwnerOf($.utils.Binding.prototype.set, $.physicals.Maximilian);\n$.utils.Binding.prototype.get = function get(inherited) {\n  /* Return the current value of the binding, or undefined if the\n   * binding does not exist.\n   *\n   * If inherited is true and the binding is a property binding that\n   * does not exist on the object, any inherited value will be returned\n   * instead.\n   */\n  var part = this.part;\n  if (this.object === null) {\n    if (!$.utils.code.isIdentifier(part)) {\n      throw new TypeError('invalid variable identifier');\n    }\n    var evalGlobal = eval;\n    return evalGlobal(part);\n  } else if(part === $.Selector.PROTOTYPE) {\n    return Object.getPrototypeOf(this.object);\n  } else if(part === $.Selector.OWNER) {\n    return Object.getOwnerOf(this.object);\n  }\n  if (inherited || Object.prototype.hasOwnProperty.call(this.object, part)) {\n    return this.object[part];\n  } else {\n    return undefined;\n  }\n};\nObject.setOwnerOf($.utils.Binding.prototype.get, $.physicals.Maximilian);\n$.utils.Binding.prototype.isOwner = function isOwner() {\n  /* Returns true iff the binding is an bject owner binding.\n   */\n  return this.part === $.Selector.OWNER;\n};\nObject.setOwnerOf($.utils.Binding.prototype.isOwner, $.physicals.Maximilian);\n$.utils.Binding.prototype.isProp = function isProp() {\n  /* Returns true iff the binding is an object property binding.\n   */\n  return this.object !== null && typeof this.part === 'string';\n};\nObject.setOwnerOf($.utils.Binding.prototype.isProp, $.physicals.Maximilian);\n$.utils.Binding.prototype.isProto = function isProto() {\n  /* Returns true iff the binding is an object prototype binding.\n   */\n  return this.part === $.Selector.PROTOTYPE;\n};\nObject.setOwnerOf($.utils.Binding.prototype.isProto, $.physicals.Maximilian);\n$.utils.Binding.prototype.isVar = function isVar() {\n  /* Returns true iff the binding is a top-level variable binding.\n   */\n  return this.object === null;\n};\nObject.setOwnerOf($.utils.Binding.prototype.isVar, $.physicals.Maximilian);\n$.utils.Binding.prototype.exists = function exists() {\n  /* Returns true iff the binding exists.\n   */\n  var part = this.part;\n  if (this.object === null) {\n    if (!$.utils.code.isIdentifier(part)) {\n        throw new TypeError('invalid variable identifier');\n    }\n    var evalGlobal = eval;\n    try {\n      globalEval(varName);\n      return true;\n    } catch (e) {\n      return false;\n    }\n  } else if(part === $.Selector.PROTOTYPE ||\n            part === $.Selector.OWNER) {\n    return true;\n  }\n  return Object.prototype.hasOwnProperty.call(this.object, part);\n};\nObject.setOwnerOf($.utils.Binding.prototype.exists, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.Binding.prototype.exists.prototype, $.physicals.Maximilian);\n$.utils.Binding.from = function from(selector) {\n  /* Create and return a Binding for the given selector - that is,\n   * such that Binding.from(s).get() === s.toValue().\n   */\n  var part = selector[selector.length - 1];\n  if (selector.isVar()) {\n    // Global variable; no parent object.\n    return new this(null, part);\n  }\n  var parent = new $.Selector(selector);\n  parent.pop();\n  var object = parent.toValue();\n  if (!$.utils.isObject(object)) {\n    throw new TypeError(String(parent) + ' is not an object');\n  }\n  return new this(object, part);\n};\nObject.setOwnerOf($.utils.Binding.from, $.physicals.Maximilian);\n\n$.Selector.cache_ = (new 'Object.create')(null);\n\n$.Selector.sortByBadness.cache_ = (new 'Object.create')(null);\n\n"
  },
  {
    "path": "core/core_20_$.utils.html.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview HTML utilities for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.utils.html = {};\n$.utils.html.escape = function escape(text) {\n  // Escape text so that it is safe to print as HTML.\n  return String(text).replace(/&/g, '&amp;').replace(/\"/g, '&quot;')\n      .replace(/</g, '&lt;').replace(/>/g, '&gt;');\n};\nObject.setOwnerOf($.utils.html.escape, $.physicals.Maximilian);\n$.utils.html.preserveWhitespace = function preserveWhitespace(text) {\n  // Escape text so that it is safe and preserves whitespace formatting as HTML.\n  // Runs of three spaces ('   ') need to be escaped twice ('_  ', '__ ').\n  return $.utils.html.escape(text)\n      .replace(/\\t/g, '\\u00A0 \\u00A0 ')\n      .replace(/  /g, '\\u00A0 ').replace(/  /g, '\\u00A0 ')  // Escape twice.\n      .replace(/^ /gm, '\\u00A0')\n      .replace(/\\n/g, '<br>');\n};\nObject.setOwnerOf($.utils.html.preserveWhitespace, $.physicals.Maximilian);\n\n"
  },
  {
    "path": "core/core_21_$.jssp.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview JavaScript Server Pages for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.jssp = {};\nObject.setOwnerOf($.jssp, $.physicals.Neil);\n$.jssp.OutputBuffer = function OutputBuffer() {\n  /* An OutputBuffer is a mock $.servers.http.Response, used wheen we\n   * want a Jssp to produce a string rather than write to an HTTP\n   * client.\n   */\n  this.buffer_ = '';\n};\nObject.setOwnerOf($.jssp.OutputBuffer, $.physicals.Maximilian);\n$.jssp.OutputBuffer.prototype.write = function write(text) {\n  this.buffer_ += String(text);\n};\nObject.setOwnerOf($.jssp.OutputBuffer.prototype.write, $.physicals.Neil);\n$.jssp.OutputBuffer.prototype.toString = function toString() {\n  return this.buffer_;\n};\nObject.setOwnerOf($.jssp.OutputBuffer.prototype.toString, $.physicals.Neil);\n$.jssp.OutputBuffer.prototype.writeEscaped = function writeEscaped(text) {\n  // Same as .write, but HTML-escape the text first.\n  this.write($.utils.html.escape(text));\n};\nObject.setOwnerOf($.jssp.OutputBuffer.prototype.writeEscaped, $.physicals.Neil);\nObject.setOwnerOf($.jssp.OutputBuffer.prototype.writeEscaped.prototype, $.physicals.Neil);\n$.jssp.eval = function $_jssp_eval(obj, prop, opt_request, opt_response) {\n  /* Compile and run a JavaScript Server Page.\n   *\n   * The specified property on the given object will, if it is a string,\n   * be compiled to a function and then called.\n   *\n   * TODO: cache the compiled JSSP.  Separate copy per owner?\n   *\n   * Arguments:\n   * - obj: Object - an object containing a property which is a JSSP source\n   *   string, and which will be used as the value of 'this' when the\n   *   the resulting function is called.\n   * - prop: string - name of the property on obj that contains the JSSP source.\n   * - opt_request: any - a value to be passed as the first argument to the\n   *   compiled function.  Most typically an instnace of $.servers.http.Request\n   *   or some kind of options object.\n   * - opt_response: {write: function(string)} | undefined - an object to\n   *   accumulate generated output.  Most typically an instance of\n   *   $.servers.http.Response.  If omitted, a $.jssp.OutputBuffer will be\n   *   supplied, and the accumulated output returned by eval as a string.\n   *\n   * Returns: any - if opt_response was omitted, this will be the generated\n   *     string; otherwise, it will be the actual return value of the compiled\n   *     function (typically undefined).\n   */\n  if (!$.utils.isObject(obj)) {\n    throw new TypeError('first argument must be an object');\n  } else if (!(prop in obj)) {\n    throw new RangeError('\"' + prop + '\" not on object.');\n  }\n  var source = obj[prop];\n  if (typeof source !== 'string') {\n    throw TypeError('source property \"' + prop + '\" must be a string');\n  }\n\n  // Switch to the JSSP owner's permissions.  The owner of the JSSP might\n  // not be the object's owner if the property is inherited.\n  var locationObj = $.utils.object.getPropertyLocation(obj, prop);\n  setPerms(Object.getOwnerOf(locationObj));\n\n  var request = opt_request;\n  var response = opt_response || new $.jssp.OutputBuffer();\n\n  // Compile source into a function.\n  var code = this.compile_(source);\n  code = '\\n' +\n      'var this_ = this;\\n' +\n      'function include(prop) {return $.jssp.eval(this_, prop, request, response);}\\n' +\n      code;\n  var func;\n  try {\n    func = new Function('request, response', code);\n  } catch (e) {\n    suspend();\n    $.system.log('JSSP compilation error.  ' + String(e) +\n                 '.  Code was:\\n' + code.split('\\n')\n                     .map(function (line, lineNumber) {\n                            return String(lineNumber) + ': ' + line;})\n                     .join('\\n'));\n    throw e;\n  }\n\n  // Create a .name for this function.\n  var selector = $.Selector.for(locationObj);\n  if (selector) {\n    selector = new $.Selector(selector.concat(prop));\n    Object.defineProperty(func, 'name', {value: selector.toString(), configurable: true});\n  }\n\n  var result = func.call(obj, request, response);\n  return opt_response ? result : response.toString();\n};\nObject.setOwnerOf($.jssp.eval, $.physicals.Maximilian);\nObject.setOwnerOf($.jssp.eval.prototype, $.physicals.Neil);\n$.jssp.compile_ = function compile_(src) {\n  /* Compile JavaScript Server Page srouce and return the translated source\n   * if successful.  It is left to the caller to pass the resulting source\n   * code to the Function constructor.\n   *\n   * Arguments:\n   * - src: string - the JSSP source code.\n   * Returns: string - the JavaScript generated from src.\n   */\n  if (typeof src !== 'string') {\n    throw new TypeError('src must be a string');\n  }\n  var tokens = src.trim().split(/(<%(?:--|:|=)?|(?:--)?%>)/);\n  var code = [\n    '// DO NOT EDIT THIS CODE: AUTOMATICALLY GENERATED BY JSSP ' +\n        compile_.lastModifiedTime + '.',\n  ];\n  var STATES = {\n    LITERAL: 0,\n    STATEMENT: 1,\n    EXPRESSION: 2,\n    EXPRESSION_ESCAPED: 3,\n    COMMENT: 4\n  };\n  var state = STATES.LITERAL;\n  for (var i = 0; i < tokens.length; i++) {\n    var token = tokens[i];\n    if (!token) {\n      continue;  // Empty string caused by splitting adjacent tags.\n    }\n    switch (state) {\n      case STATES.LITERAL:\n        if (token === '<%') {\n          state = STATES.STATEMENT;\n        } else if (token === '<%=') {\n          state = STATES.EXPRESSION;\n        } else if (token === '<%:') {\n          state = STATES.EXPRESSION_ESCAPED;\n        } else if (token === '<%--') {\n          state = STATES.COMMENT;\n        } else {\n          code.push('response.write(' + JSON.stringify(token) + ');');\n        }\n        break;\n      case STATES.STATEMENT:\n        if (token === '%>') {\n          state = STATES.LITERAL;\n        } else {\n          code.push(token);\n        }\n        break;\n      case STATES.EXPRESSION:\n      case STATES.EXPRESSION_ESCAPED:\n        if (token === '%>') {\n          state = STATES.LITERAL;\n        } else {\n          token = token.trim();\n          if (token) {\n            code.push();\n            if (state === STATES.EXPRESSION_ESCAPED) {\n              code.push('response.writeEscaped(' + token + ');');\n            } else {\n              code.push('response.write(' + token + ');');\n            }\n          }\n        }\n        break;\n      case STATES.COMMENT:\n        if (token === '--%>') {\n          state = STATES.LITERAL;\n        }\n        break;\n    }\n  }\n  if (state !== STATES.LITERAL) {\n    throw new SyntaxError('unclosed JSSP tag');\n  }\n  return code.join('\\n') + '\\n';\n};\nObject.setOwnerOf($.jssp.compile_, $.physicals.Neil);\nObject.setOwnerOf($.jssp.compile_.prototype, $.physicals.Maximilian);\n\n"
  },
  {
    "path": "core/core_22_$.connection.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Connection object for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.connection = {};\n$.connection.onConnect = function onConnect() {\n  this.connectTime = Date.now();\n  this.user = null;\n  this.buffer = '';\n  this.connected = true;\n};\nObject.setOwnerOf($.connection.onConnect, $.physicals.Maximilian);\nObject.setOwnerOf($.connection.onConnect.prototype, $.physicals.Maximilian);\n$.connection.onReceive = function onReceive(text) {\n  this.buffer += text.replace(/\\r/g, '');\n  var lf;\n  while ((lf = this.buffer.indexOf('\\n')) !== -1) {\n    var line = this.buffer.substring(0, lf);\n    this.buffer = this.buffer.substring(lf + 1);\n    this.onReceiveLine(line);\n  }\n};\nObject.setOwnerOf($.connection.onReceive, $.physicals.Maximilian);\n$.connection.onReceiveLine = function onReceiveLine(text) {\n  // Override this on child classes.\n};\nObject.setOwnerOf($.connection.onReceiveLine, $.physicals.Maximilian);\n$.connection.onEnd = function onEnd() {\n  this.connected = false;\n  this.disconnectTime = Date.now();\n  this.close();\n};\nObject.setOwnerOf($.connection.onEnd, $.physicals.Maximilian);\n$.connection.write = function write(text) {\n  $.system.connectionWrite(this, text);\n};\nObject.setOwnerOf($.connection.write, $.physicals.Maximilian);\n$.connection.close = function close() {\n  $.system.connectionClose(this);\n};\nObject.setOwnerOf($.connection.close, $.physicals.Maximilian);\n$.connection.onError = function onError(error) {\n  // TODO: add check for error that occurs when relistening\n  // fails when restarting server from checkpoint.\n  if (error.message === 'write after end' ||\n      error.message === 'This socket has been ended by the other party') {\n    this.connected = false;\n  }\n};\nObject.setOwnerOf($.connection.onError, $.physicals.Maximilian);\n\n"
  },
  {
    "path": "core/core_23_$.servers.http.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Webserver for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.utils.url = {};\nObject.setOwnerOf($.utils.url, $.physicals.Maximilian);\n$.utils.url.regexps = {};\n$.utils.url.regexps.README = '$.utils.url.regexps contains some RegExps useful for parsing or otherwise analysing URLs.\\n\\nSee ._generate() for how they are constructed and what they will match.';\n$.utils.url.regexps._generate = function _generate() {\n  /* Generate some RegExps that match various parts of URLs.  The\n   * intention is that these regular expressions conform to the\n   * grammar given in RFC 3986, \"Uniform Resource Identifier (URI):\n   * Generic Syntax\" (https://tools.ietf.org/html/rfc3986).\n   *\n   * TODO: add tests for generated RegExps.\n   */\n\n  ////////////////////////////////////////////////////////////////////\n  // IPv4 Addresses.\n  // Based on https://stackoverflow.com/a/14453696/4969945\n\n  // Matches an octet, optionally with leading zeros.\n  var octet = '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})';\n  // Matches an octet without no leading zeros.\n  var octetStrict = '(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])';\n\n\n  // Globally matches IPv4 addresses, optionally with leading zeros.\n  this.ipv4Address = new RegExp(octet + '(?:\\\\.' + octet + '){3}', 'g');\n  // Globally matches IPv4 addresses with no leading zeros.\n  this.ipv4AddressStrict =\n      new RegExp(octetStrict + '(?:\\\\.' + octetStrict + '){3}', 'g');\n\n  ////////////////////////////////////////////////////////////////////\n  // IPv6 Addresses.\n  // Based on https://stackoverflow.com/a/17871737/4969945 but modified\n  // to reduce ambiguity match more greedily when unanchored.\n\n  // Matches a 32-bit hex value as it can appear in an IPv6 address.\n  var word = '[0-9a-fA-F]{1,4}';\n\n  // Matches an IPv4 address as it can appear in an IPv6 address.\n  var ipv4 = this.ipv4AddressStrict.source;\n\n  // Globally matches a valid IPv6 address.\n  this.ipv6Address = new RegExp(\n      '(?:' +\n          '[fF][eE]80:(?::' + word + '){0,4}%[0-9a-zA-Z]+|' +  // fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)\n          '(?:' + word + ':){1,4}:' + ipv4 + '|' +             // 2001:db8:3:4::192.0.2.33  64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)\n          '(?:' + word + ':){7}' + word + '|' +                // 1:2:3:4:5:6:7:8\n          '(?:' + word + ':){6}(?::' + word + '){1,1}|' +      // 1:2:3:4:5:6::8 ... 1:2:3:4:5:6::8\n          '(?:' + word + ':){5}(?::' + word + '){1,2}|' +      // 1:2:3:4:5::8   ... 1:2:3:4:5::7:8\n          '(?:' + word + ':){4}(?::' + word + '){1,3}|' +      // 1:2:3:4::8     ... 1:2:3:4::6:7:8\n          '(?:' + word + ':){3}(?::' + word + '){1,4}|' +      // 1:2:3::8       ... 1:2:3::5:6:7:8\n          '(?:' + word + ':){2}(?::' + word + '){1,5}|' +      // 1:2::8         ... 1:2::4:5:6:7:8\n          '(?:' + word + ':){1}(?::' + word + '){1,6}|' +      // 1::8           ... 1::3:4:5:6:7:8\n          '(?:' + word + ':){1,7}:|' +                         // 1::            ... 1:2:3:4:5:6:7::\n          '::(?:[fF]{4}(?::0{1,4})?:)?' + ipv4 + '|' +         // ::255.255.255.255  ::ffff:255.255.255.255  ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)\n          ':(?::' + word + '){1,7}|' +                         // ::8            ... ::2:3:4:5:6:7:8\n          '::' +                                               // ::\n      ')', 'g');\n\n  ////////////////////////////////////////////////////////////////////\n  // DNS Domain Names.\n\n  // Matches a label (per RFC 952, updated by RFC 1123 to allow a\n  // it to begin with a digit), limited to 63 charcters (per RFC 1035).\n  var label = '[a-zA-Z0-9][a-zA-Z0-9-]{0,62}';\n\n  // Globally matches a legal (but not necessary valid!) DNS name.\n  // See also https://stackoverflow.com/q/106179/4969945 .\n  // BUG: does not limit length of name to ca. 253 characters (see\n  //     https://devblogs.microsoft.com/oldnewthing/20120412-00/?p=7873\n  //     for gory details).\n  this.dnsAddress = new RegExp(label + '(?:\\\\.' + label + ')*', 'g');\n\n  ////////////////////////////////////////////////////////////////////\n  // Authority section\n\n  // Globally matches a valid IP address (v4 or v6).\n  this.ipAddress = new RegExp(\n    this.ipv4Address.source + '|\\\\[' + this.ipv6Address.source + '\\\\]', 'g');\n\n  // Globally matches a valid URL authority section (e.g. domain name\n  // and port); this is (not coincidentally) also the same as a valid\n  // HTTP Host: header value.\n  //\n  // The RegExp includes capture groups for an IP address [1] *or* a\n  // DNS address [2], and (optionally) a port number [3].\n  this.authority = new RegExp(\n    '(?:(' + this.ipAddress.source + ')|' +\n       '(' + this.dnsAddress.source + '))' +\n    '(?::([0-9]+))?', 'g');  // Optional port number.\n\n  ////////////////////////////////////////////////////////////////////\n  // Exact forms of the above.  These do not get the global flag.\n  var keys = ['ipv4Address', 'ipv4AddressStrict', 'ipv6Address',\n              'dnsAddress', 'ipAddress', 'authority'];\n  for (var key, i = 0; (key = keys[i]); i++) {\n    this[key + 'Exact'] = new RegExp('^' + this[key].source + '$');\n  }\n\n};\nObject.setOwnerOf($.utils.url.regexps._generate.prototype, $.physicals.Maximilian);\n$.utils.url.regexps.ipv4Address = /(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}/g;\n$.utils.url.regexps.ipv4AddressStrict = /(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}/g;\n$.utils.url.regexps.ipv6Address = /(?:[fF][eE]80:(?::[0-9a-fA-F]{1,4}){0,4}%[0-9a-zA-Z]+|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){6}(?::[0-9a-fA-F]{1,4}){1,1}|(?:[0-9a-fA-F]{1,4}:){5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){2}(?::[0-9a-fA-F]{1,4}){1,5}|(?:[0-9a-fA-F]{1,4}:){1}(?::[0-9a-fA-F]{1,4}){1,6}|(?:[0-9a-fA-F]{1,4}:){1,7}:|::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|:(?::[0-9a-fA-F]{1,4}){1,7}|::)/g;\n$.utils.url.regexps.dnsAddress = /[a-zA-Z0-9][a-zA-Z0-9-]{0,62}(?:\\.[a-zA-Z0-9][a-zA-Z0-9-]{0,62})*/g;\n$.utils.url.regexps.ipAddress = /(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}|\\[(?:[fF][eE]80:(?::[0-9a-fA-F]{1,4}){0,4}%[0-9a-zA-Z]+|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){6}(?::[0-9a-fA-F]{1,4}){1,1}|(?:[0-9a-fA-F]{1,4}:){5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){2}(?::[0-9a-fA-F]{1,4}){1,5}|(?:[0-9a-fA-F]{1,4}:){1}(?::[0-9a-fA-F]{1,4}){1,6}|(?:[0-9a-fA-F]{1,4}:){1,7}:|::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|:(?::[0-9a-fA-F]{1,4}){1,7}|::)\\]/g;\n$.utils.url.regexps.authority = /(?:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}|\\[(?:[fF][eE]80:(?::[0-9a-fA-F]{1,4}){0,4}%[0-9a-zA-Z]+|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){6}(?::[0-9a-fA-F]{1,4}){1,1}|(?:[0-9a-fA-F]{1,4}:){5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){2}(?::[0-9a-fA-F]{1,4}){1,5}|(?:[0-9a-fA-F]{1,4}:){1}(?::[0-9a-fA-F]{1,4}){1,6}|(?:[0-9a-fA-F]{1,4}:){1,7}:|::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|:(?::[0-9a-fA-F]{1,4}){1,7}|::)\\])|([a-zA-Z0-9][a-zA-Z0-9-]{0,62}(?:\\.[a-zA-Z0-9][a-zA-Z0-9-]{0,62})*))(?::([0-9]+))?/g;\n$.utils.url.regexps.ipv4AddressExact = /^(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}$/;\n$.utils.url.regexps.ipv4AddressStrictExact = /^(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}$/;\n$.utils.url.regexps.ipv6AddressExact = /^(?:[fF][eE]80:(?::[0-9a-fA-F]{1,4}){0,4}%[0-9a-zA-Z]+|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){6}(?::[0-9a-fA-F]{1,4}){1,1}|(?:[0-9a-fA-F]{1,4}:){5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){2}(?::[0-9a-fA-F]{1,4}){1,5}|(?:[0-9a-fA-F]{1,4}:){1}(?::[0-9a-fA-F]{1,4}){1,6}|(?:[0-9a-fA-F]{1,4}:){1,7}:|::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|:(?::[0-9a-fA-F]{1,4}){1,7}|::)$/;\n$.utils.url.regexps.dnsAddressExact = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,62}(?:\\.[a-zA-Z0-9][a-zA-Z0-9-]{0,62})*$/;\n$.utils.url.regexps.ipAddressExact = /^(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}|\\[(?:[fF][eE]80:(?::[0-9a-fA-F]{1,4}){0,4}%[0-9a-zA-Z]+|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){6}(?::[0-9a-fA-F]{1,4}){1,1}|(?:[0-9a-fA-F]{1,4}:){5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){2}(?::[0-9a-fA-F]{1,4}){1,5}|(?:[0-9a-fA-F]{1,4}:){1}(?::[0-9a-fA-F]{1,4}){1,6}|(?:[0-9a-fA-F]{1,4}:){1,7}:|::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|:(?::[0-9a-fA-F]{1,4}){1,7}|::)\\]$/;\n$.utils.url.regexps.authorityExact = /^(?:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}|\\[(?:[fF][eE]80:(?::[0-9a-fA-F]{1,4}){0,4}%[0-9a-zA-Z]+|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){6}(?::[0-9a-fA-F]{1,4}){1,1}|(?:[0-9a-fA-F]{1,4}:){5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){2}(?::[0-9a-fA-F]{1,4}){1,5}|(?:[0-9a-fA-F]{1,4}:){1}(?::[0-9a-fA-F]{1,4}){1,6}|(?:[0-9a-fA-F]{1,4}:){1,7}:|::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])(?:\\.(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])){3}|:(?::[0-9a-fA-F]{1,4}){1,7}|::)\\])|([a-zA-Z0-9][a-zA-Z0-9-]{0,62}(?:\\.[a-zA-Z0-9][a-zA-Z0-9-]{0,62})*))(?::([0-9]+))?$/;\n\n$.servers.http = {};\n$.servers.http.STATUS_CODES = (new 'Object.create')(null);\n$.servers.http.STATUS_CODES[100] = 'Continue';\n$.servers.http.STATUS_CODES[101] = 'Switching Protocols';\n$.servers.http.STATUS_CODES[102] = 'Processing';\n$.servers.http.STATUS_CODES[200] = 'OK';\n$.servers.http.STATUS_CODES[201] = 'Created';\n$.servers.http.STATUS_CODES[202] = 'Accepted';\n$.servers.http.STATUS_CODES[203] = 'Non-Authoritative Information';\n$.servers.http.STATUS_CODES[204] = 'No Content';\n$.servers.http.STATUS_CODES[205] = 'Reset Content';\n$.servers.http.STATUS_CODES[206] = 'Partial Content';\n$.servers.http.STATUS_CODES[207] = 'Multi-Status';\n$.servers.http.STATUS_CODES[208] = 'Already Reported';\n$.servers.http.STATUS_CODES[226] = 'IM Used';\n$.servers.http.STATUS_CODES[300] = 'Multiple Choices';\n$.servers.http.STATUS_CODES[301] = 'Moved Permanently';\n$.servers.http.STATUS_CODES[302] = 'Found';\n$.servers.http.STATUS_CODES[303] = 'See Other';\n$.servers.http.STATUS_CODES[304] = 'Not Modified';\n$.servers.http.STATUS_CODES[305] = 'Use Proxy';\n$.servers.http.STATUS_CODES[306] = 'Switch Proxy';\n$.servers.http.STATUS_CODES[307] = 'Temporary Redirect';\n$.servers.http.STATUS_CODES[308] = 'Permanent Redirect';\n$.servers.http.STATUS_CODES[400] = 'Bad Request';\n$.servers.http.STATUS_CODES[401] = 'Unauthorized';\n$.servers.http.STATUS_CODES[402] = 'Payment Required';\n$.servers.http.STATUS_CODES[403] = 'Forbidden';\n$.servers.http.STATUS_CODES[404] = 'Not Found';\n$.servers.http.STATUS_CODES[405] = 'Method Not Allowed';\n$.servers.http.STATUS_CODES[406] = 'Not Acceptable';\n$.servers.http.STATUS_CODES[407] = 'Proxy Authentication Required';\n$.servers.http.STATUS_CODES[408] = 'Request Timeout';\n$.servers.http.STATUS_CODES[409] = 'Conflict';\n$.servers.http.STATUS_CODES[410] = 'Gone';\n$.servers.http.STATUS_CODES[411] = 'Length Required';\n$.servers.http.STATUS_CODES[412] = 'Precondition Failed';\n$.servers.http.STATUS_CODES[413] = 'Payload Too Large';\n$.servers.http.STATUS_CODES[414] = 'URI Too Long';\n$.servers.http.STATUS_CODES[415] = 'Unsupported Media Type';\n$.servers.http.STATUS_CODES[416] = 'Range Not Satisfiable';\n$.servers.http.STATUS_CODES[417] = 'Expectation Failed';\n$.servers.http.STATUS_CODES[418] = \"I'm a teapot\";\n$.servers.http.STATUS_CODES[421] = 'Misdirected Request';\n$.servers.http.STATUS_CODES[422] = 'Unprocessable Entity';\n$.servers.http.STATUS_CODES[423] = 'Locked';\n$.servers.http.STATUS_CODES[424] = 'Failed Dependency';\n$.servers.http.STATUS_CODES[426] = 'Upgrade Required';\n$.servers.http.STATUS_CODES[428] = 'Precondition Required';\n$.servers.http.STATUS_CODES[429] = 'Too Many Requests';\n$.servers.http.STATUS_CODES[431] = 'Request Header Fields Too Large';\n$.servers.http.STATUS_CODES[451] = 'Unavailable For Legal Reasons';\n$.servers.http.STATUS_CODES[500] = 'Internal Server Error';\n$.servers.http.STATUS_CODES[501] = 'Not Implemented';\n$.servers.http.STATUS_CODES[502] = 'Bad Gateway';\n$.servers.http.STATUS_CODES[503] = 'Service Unavailable';\n$.servers.http.STATUS_CODES[504] = 'Gateway Timeout';\n$.servers.http.STATUS_CODES[505] = 'HTTP Version Not Supported';\n$.servers.http.STATUS_CODES[506] = 'Variant Also Negotiates';\n$.servers.http.STATUS_CODES[507] = 'Insufficient Storage';\n$.servers.http.STATUS_CODES[508] = 'Loop Detected';\n$.servers.http.STATUS_CODES[510] = 'Not Extended';\n$.servers.http.STATUS_CODES[511] = 'Network Authentication Required';\n$.servers.http.connection = (new 'Object.create')($.connection);\n$.servers.http.connection.onConnect = function onConnect() {\n  $.connection.onConnect.apply(this, arguments);\n  this.timeout = setTimeout(this.close.bind(this), 60 * 1000);\n  this.request = new $.servers.http.Request();\n  this.response = new $.servers.http.Response(this);\n};\nObject.setOwnerOf($.servers.http.connection.onConnect, $.physicals.Maximilian);\n$.servers.http.connection.onReceive = function onReceive(data) {\n  this.buffer += data;\n  var lf;\n  // Start in line-delimited mode, parsing HTTP headers.\n  while ((lf = this.buffer.indexOf('\\n')) !== -1) {\n    try {\n      this.onReceiveChunk(this.buffer.substring(0, lf + 1));\n    } finally {\n      this.buffer = this.buffer.substring(lf + 1);\n    }\n  }\n  if (this.request.state_ === 'body') {\n    // Waiting for POST data, not line-delimited.\n    this.onReceiveChunk(this.buffer);\n    this.buffer = '';\n  }\n};\nObject.setOwnerOf($.servers.http.connection.onReceive, $.physicals.Neil);\n$.servers.http.connection.onReceiveChunk = function onReceiveChunk(chunk) {\n  if (this.request.parse(chunk)) {\n    $.servers.http.onRequest(this);\n  }\n  // Otherwise wait for more lines to arrive.\n};\nObject.setOwnerOf($.servers.http.connection.onReceiveChunk, $.physicals.Maximilian);\n$.servers.http.connection.onEnd = function onEnd() {\n  clearTimeout(this.timeout);\n  $.connection.onEnd.apply(this, arguments);\n};\nObject.setOwnerOf($.servers.http.connection.onEnd, $.physicals.Neil);\n$.servers.http.Request = function Request() {\n  this.headers = Object.create(null);\n  this.headers.cookie = Object.create(null);\n  this.parameters = Object.create(null);\n  // One of 'invalid', 'request', 'headers', 'body', 'done'.\n  this.state_ = 'request';\n};\nObject.setOwnerOf($.servers.http.Request, $.physicals.Maximilian);\n$.servers.http.Request.prototype.parse = function parse(line) {\n  // Returns true if parsing is complete, false if more lines are needed.\n  if (this.state_ === 'request') {\n    // Match \"GET /images/logo.png HTTP/1.1\"\n    line = line.trim();\n    var m = line.match(/^(GET|POST) +(\\S+)/);\n    if (!m) {\n      $.system.log('Unrecognized WWW request line:', line);\n      this.state_ = 'invalid';\n      return true;\n    }\n    this.method = m[1];\n    this.url = m[2];\n    this.parseUrl_(this.url);\n    this.state_ = 'headers';\n    return false;\n  }\n  if (this.state_ === 'headers') {\n    line = line.trim();\n    if (!line) {  // Done parsing headers.\n      if (this.method === 'POST') {\n        this.state_ = 'body';\n        this.data = '';\n        return false;\n      } else {\n        this.parseParameters_(this.query);\n        this.state_ = 'done';\n        this.data = undefined;\n        return true;\n      }\n    }\n    var m = line.match(/^([-\\w]+): +(.+)$/);\n    if (!m) {\n      $.system.log('Unrecognized WWW header line:', line);\n      return false;\n    }\n    var name = m[1].toLowerCase();\n    var value = m[2];\n    var existing = this.headers[name];\n    if (name === 'cookie') {\n      // Cookies are processed and presented as: request.headers.cookie.foo\n      var cookies = value.split(/\\s*;\\s*/);\n      for (var i = 0; i < cookies.length; i++) {\n        var eqIndex = cookies[i].indexOf('=');\n        if (eqIndex !== -1) {\n          var cookieName = cookies[i].substring(0, eqIndex);\n          var cookieValue = cookies[i].substring(eqIndex + 1);\n          if (cookieName === 'ID') {\n            // Special-case the 'ID' cookie for user login.\n            // Do not expose this ID string to anyone.\n            this.user = $.userDatabase.get(cookieValue);\n          } else {\n            // Regular cookie.\n            existing[cookieName] = cookieValue;\n          }\n        }\n      }\n      value = existing;\n    } else if (name in this.headers) {\n      if ($.servers.http.IncomingMessage.discardDuplicates.includes(name)) {\n        // Discard this duplicate.\n        value  = existing;\n      } else {\n        // Append this header onto previously defined header.\n        value = existing + ', ' + value;\n      }\n    }\n    this.headers[name] = value;\n    return false;\n  }\n  if (this.state_ === 'body') {\n    // POST data.\n    this.data += line;\n    if (this.data.length >= this.headers['content-length']) {\n      this.parseParameters_(this.data);\n      this.state_ = 'done';\n      return true;\n    }\n    return false;\n  }\n  // Invalid state?  Extra lines?  Ignore.\n  return true;\n};\nObject.setOwnerOf($.servers.http.Request.prototype.parse, $.physicals.Neil);\n$.servers.http.Request.prototype.parseUrl_ = function parseUrl_(url) {\n  /* Parse a URL and set this.path and this.query as appropriate:\n   *\n   * E.g. given url = '/bar/baz?data', set:\n   * - this.path = '/bar/baz'\n   * - this.query = 'data'\n   *\n   * Arguments:\n   * - url: string - the URL to parse.\n   *\n   * TODO(cpcallen): add check for leading \"/\"?\n   */\n  var qIndex = url.indexOf('?');\n  if (qIndex === -1) {\n    this.path = url;\n  } else {\n    this.path = url.substring(0, qIndex);\n    this.query = url.substring(qIndex + 1);\n  }\n};\nObject.setOwnerOf($.servers.http.Request.prototype.parseUrl_, $.physicals.Maximilian);\n$.servers.http.Request.prototype.parseParameters_ = function parseParameters_(data) {\n  if (!data) {\n    return;\n  }\n  var vars = data.split('&');\n  var name, value;\n  for (var i = 0; i < vars.length; i++) {\n    var eqIndex = vars[i].indexOf('=');\n    if (eqIndex === -1) {\n      name = vars[i];\n      value = true;\n    } else {\n      name = vars[i].substring(0, eqIndex);\n      value = vars[i].substring(eqIndex + 1);\n      value = decodeURIComponent(value.replace(/\\+/g, ' '));\n    }\n    if (name in this.parameters) {\n      // ?foo=1&foo=2&foo=3\n      var array = this.parameters[name];\n      if (!Array.isArray(array)) {\n        array = [array];\n      }\n      array.push(value);\n      value = array;\n    }\n    this.parameters[name] = value;\n  }\n};\nObject.setOwnerOf($.servers.http.Request.prototype.parseParameters_, $.physicals.Neil);\n$.servers.http.Request.prototype.fromSameOrigin = function fromSameOrigin() {\n  /* Determines if the previous page and the requested page are from the same\n   * origin.  Normally this means that they are from the same subdomain.\n   * However, if pathToSubdomain is enabled then the first directory name\n   * is used for comparison.\n   *\n   * Return: boolean | undefined - true if from the same origin, false if\n   * from different origins, and undefined if missing headers prevent a\n   * firm conclusion one way or the other.\n   *\n   * Callers should choose whether to fail-safe or fail-deadly when the\n   * user's proxy strips the referer header, resulting in undefined.\n   *\n   * BUG: if referer was for subdomain routed via a root Host with\n   * .pathToSubdomain enabled, but .origin is for the root domain,\n   * fromSameOrigin will return true.  This is not intended and possibly\n   * insecure - but probably mostly harmless: if .pathToSubdomain is\n   * enabled subdomains are not really secure against each other anyway.\n   */\n  var referer = this.headers.referer;  // https://foo.example.codecity.world/bar\n  if (!referer || !this.info) {\n    // Missing headers.  Not enough information to know.\n    return undefined;\n  }\n  var origin = this.info.origin;  // foo.example.codecity.world\n  var regexp = new RegExp('^https?://' + $.utils.regexp.escape(origin) + '/');\n  return regexp.test(referer);\n};\nObject.setOwnerOf($.servers.http.Request.prototype.fromSameOrigin, $.physicals.Maximilian);\n$.servers.http.Request.prototype.hostUrl = function hostUrl(varArgs) {\n  /* Return the base URL for the host that handled this Request, or\n   * a subdomain (omitting scheme).  This is derived from .headers.host,\n   * but with some extra magic:\n   *\n   * - Absent any argument, it will be the URL which routes to the root\n   *   Host object serving this Request - e.g., //example.codecity.world/\n   *   The \"root\" host is ordinarily just first of $.servers.http.hosts[]\n   *   to accept the request (as opposed to one of its .subdomains).\n   * - If an argument is supplied, the returned URL will instead be for\n   *   the named subdomain.\n   * - Multiple arguments can be supplied if there are nested subdomains.\n   *\n   * E.g.:\n   * request.hostUrl()             => '//example.codecity.world/'\n   * request.hostUrl('code')       => '//code.example.codecity.world/'\n   * request.hostUrl('foo', 'bar') => '//foo.bar.example.codecity.world/'\n   *\n   * If .pathToSubdomain is enabled on one or more Host object(s):\n   * request.hostUrl('code')       => '//example.codecity.world/code/'\n   * request.hostUrl('foo', 'bar') => '//example.codecity.world/foo/bar/'\n   *                              or: '//bar.example.codecity.world/foo/'\n   *\n   * Barring bugs, the returned URL should always end with a '/'.\n   *\n   * See also $.servers.http.Host.prototype.url for cases where you need\n   * to generate a host URL without an incoming Request to use as reference.\n   *\n   * Arguments:\n   * - subdomain: string - a string denoting a subdomain of interest.\n   *       Multiple arguments are allowed.  RangeError is thrown if no such\n   *       subdomain exists.\n   * Returns: string - the URL for the desired domain/subdomain.\n   */\n  // No routing information is available?  Fallback to $hosts.root.url().\n  if (!this.info) {\n    var rootHost = $.hosts.root;\n    return rootHost.url.apply(rootHost, arguments);\n  }\n  // Walk the tree of Hosts rooted at the root Host via which this\n  // Request was served.\n  var host = this.info.rootHost;\n  var authority = this.info.rootAuthority;\n  // Did nginx request pathToSubdomain, because it knows that it is not\n  // configured for real wildcard subdomains?  (N.B.: header uses the\n  // RFC 8941 convention of \"?1\" for true, \"?0\" for false.)\n  var pathToSubdomainHeader =\n      (this.headers['codecity-pathtosubdomain'] === '?1');\n  for (var subdomain, i = 0; (subdomain = arguments[i]); i++) {\n    authority = host.urlForSubdomain(authority, subdomain, pathToSubdomainHeader);\n    host = host.subdomains[subdomain];\n  }\n  return '//' + authority + '/';\n};\nObject.setOwnerOf($.servers.http.Request.prototype.hostUrl, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Request.prototype.hostUrl.prototype, $.physicals.Maximilian);\n$.servers.http.Request.discardDuplicates = [];\n$.servers.http.Request.discardDuplicates[0] = 'authorization';\n$.servers.http.Request.discardDuplicates[1] = 'content-length';\n$.servers.http.Request.discardDuplicates[2] = 'content-type';\n$.servers.http.Request.discardDuplicates[3] = 'from';\n$.servers.http.Request.discardDuplicates[4] = 'host';\n$.servers.http.Request.discardDuplicates[5] = 'if-modified-since';\n$.servers.http.Request.discardDuplicates[6] = 'if-unmodified-since';\n$.servers.http.Request.discardDuplicates[7] = 'max-forwards';\n$.servers.http.Request.discardDuplicates[8] = 'proxy-authorization';\n$.servers.http.Request.discardDuplicates[9] = 'referer';\n$.servers.http.Request.discardDuplicates[10] = 'user-agent';\n$.servers.http.Response = function Response(connection) {\n  this.headersSent = false;\n  this.statusCode = 200;\n  this.headers_ = Object.create(Response.defaultHeaders);\n  this.cookies = [];\n  this.setHeader('content-type', 'text/html; charset=utf-8');\n  this.connection_ = connection;\n};\nObject.setOwnerOf($.servers.http.Response, $.physicals.Maximilian);\n$.servers.http.Response.prototype.setHeader = function setHeader(name, value) {\n  if (this.headersSent) {\n    throw new Error('header already sent');\n  }\n  value = String(value).trim();\n  if (value.includes('\\n') || value.includes('\\r')) {\n    throw new RangeError('invalid header value');\n  }\n  // Normalize all header names as lowercase.\n  name = String(name).toLowerCase(name);\n  if (name === 'set-cookie') {\n    if (/^\\s*ID\\s*=/.test(value)) {\n      throw new PermissionError('not allowed to set ID cookie');\n    }\n    this.cookies.push(value);\n  } else {\n    var existing = Object.getOwnPropertyDescriptor(this.headers_, name);\n    if (existing) {  // Header already set for this Response specifically.\n      if ($.servers.http.Response.discardDuplicates.includes(name)) {\n        // Overwrite existing value.\n      } else {\n        // Append this header onto previously defined header.\n        value = existing.value + ', ' + value;\n      }\n    }\n    this.headers_[name] = value;\n  }\n};\nObject.setOwnerOf($.servers.http.Response.prototype.setHeader, $.physicals.Maximilian);\n$.servers.http.Response.prototype.writeHead = function writeHead() {\n  if (this.headersSent) {\n    throw new Error('Header already sent.');\n  }\n  this.headersSent = true;\n  var statusMessage = $.servers.http.STATUS_CODES[this.statusCode] || 'Unknown';\n  this.connection_.write('HTTP/1.0 ' + this.statusCode + ' ' + statusMessage +\n                         '\\r\\n');\n  for (var name in this.headers_) {\n    // Print all header names as Title-Case.\n    var title = name.replace(/\\w+/g, $.utils.string.capitalize);\n    this.connection_.write(title + ': ' + this.headers_[name] + '\\r\\n');\n  }\n  for (var i = 0; i < this.cookies.length; i++) {\n    // Print all cookies.\n    this.connection_.write('Set-Cookie: ' + this.cookies[i] + '\\r\\n');\n  }\n  this.connection_.write('\\r\\n');\n};\nObject.setOwnerOf($.servers.http.Response.prototype.writeHead, $.physicals.Maximilian);\n$.servers.http.Response.prototype.setStatus = function setStatus(statusCode) {\n  /* Set the status code for this Response.\n   * Must be called before .writeHead().\n   *\n   * - statusCode: number - the HTTP status code to return.\n   */\n  if (!(statusCode in $.servers.http.STATUS_CODES)) {\n    throw new RangeError('invalid HTTP status code ' + statusCode);\n  }\n  if (this.headersSent) {\n    throw new Error('header already sent.');\n  }\n  this.statusCode = statusCode;\n};\nObject.setOwnerOf($.servers.http.Response.prototype.setStatus, $.physicals.Maximilian);\n$.servers.http.Response.prototype.write = function write(text) {\n  text = String(text);\n  if (text !== '') {\n    if (!this.headersSent) {\n      this.writeHead();\n    }\n    this.connection_.write(text);\n  }\n};\nObject.setOwnerOf($.servers.http.Response.prototype.write, $.physicals.Neil);\n$.servers.http.Response.prototype.clearIdCookie = function clearIdCookie() {\n  // TODO: Security check goes here.  Should be only callable by logout.\n  if (this.headersSent) {\n    throw new Error('Header already sent');\n  }\n  var request = this.connection_.request;\n  // Guess cookie domain.\n  var rootHost =\n      (request.info && request.info.rootAuthority) ||  // Request rootAuthority.\n      request.headers.host ||  // Actual Host: header value for the request.\n      $.hosts.root.hostname;  // Configuerd hostname\n  var domain = rootHost ? ' Domain=' + rootHost.replace(/:\\d+$/, '') : '';  // Remove port number.\n  var value = 'ID=; HttpOnly;' + domain + '; Path=/; Max-Age=0;';\n  this.cookies.push(value);\n};\nObject.setOwnerOf($.servers.http.Response.prototype.clearIdCookie, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Response.prototype.clearIdCookie.prototype, $.physicals.Neil);\n$.servers.http.Response.prototype.sendRedirect = function sendRedirect(url, statusCode) {\n  /* Write a redirect as the response.\n   *\n   * Must be called before writeHeader has been called.\n   *\n   * Arguments:\n   * - url: string - the destination URL for the redirect.\n   * - statusCode?: number - optional HTTP status code (default: 303 See Other).\n   */\n  if (!statusCode) statusCode = 303;\n  this.setStatus(statusCode);\n  this.setHeader('Location', url);\n  this.writeHead();\n};\nObject.setOwnerOf($.servers.http.Response.prototype.sendRedirect, $.physicals.Neil);\nObject.setOwnerOf($.servers.http.Response.prototype.sendRedirect.prototype, $.physicals.Maximilian);\n$.servers.http.Response.prototype.sendError = function sendError(statusCode, message) {\n  /* Send an error status and page as the response.\n   *\n   * Must be called before writeHeader has been called.  Writes a complete HTML\n   * document to the connection, but doesn't close the connection.\n   *\n   * Arguments:\n   * - statusCode: number - an HTTP status code.\n   * - message?: string | Error - optional status message or Error instance.\n   */\n  this.setStatus(statusCode);\n  if (message instanceof Error) {\n    this.errorMessage_ = $.utils.html.escape(String(message)) +\n      '<pre>' + $.utils.html.escape(message.stack) + '</pre>';\n  } else if (message !== undefined) {\n    this.errorMessage_ = $.utils.html.escape(message);\n  } else {\n    this.errorMessage_ = '';\n  }\n  $.jssp.eval(this, 'sendErrorJssp', this.connection_.request, this);\n};\nObject.setOwnerOf($.servers.http.Response.prototype.sendError, $.physicals.Neil);\nObject.setOwnerOf($.servers.http.Response.prototype.sendError.prototype, $.physicals.Maximilian);\n$.servers.http.Response.prototype.sendErrorJssp = '<% try {var staticUrl = request.hostUrl(\\'static\\');} catch(e) {staticUrl = \\'\\';} %>\\n<html>\\n<head>\\n  <title><%= response.statusCode %> - Code City</title>\\n  <style>\\n    body {\\n      font-family: \"Roboto Mono\", monospace;\\n      text-align: center;\\n    }\\n    h1 {\\n      font-size: 40pt;\\n      font-weight: 100;\\n    }\\n    h1>img {\\n      vertical-align: text-bottom;\\n    }\\n    pre {\\n      margin: 2em;\\n    }\\n  </style>\\n  <link href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\" rel=\"stylesheet\">\\n  <link href=\"<%=staticUrl%>favicon.ico\" rel=\"shortcut icon\">\\n</head>\\n<body>\\n  <h1>\\n    <img src=\"<%=staticUrl%>logo-error.svg\" alt=\"\">\\n    <%= response.statusCode %> <%= $.servers.http.STATUS_CODES[response.statusCode] %>\\n  </h1>\\n  <pre>Host: <%: request.headers.host %>\\n<%= request.method %> <%: request.url %></pre>\\n  <%= response.errorMessage_ %>\\n</body>\\n</html>';\n$.servers.http.Response.prototype.writeEscaped = $.jssp.OutputBuffer.prototype.writeEscaped;\n$.servers.http.Response.discardDuplicates = [];\n$.servers.http.Response.discardDuplicates[0] = 'age';\n$.servers.http.Response.discardDuplicates[1] = 'content-length';\n$.servers.http.Response.discardDuplicates[2] = 'content-type';\n$.servers.http.Response.discardDuplicates[3] = 'etag';\n$.servers.http.Response.discardDuplicates[4] = 'expires';\n$.servers.http.Response.discardDuplicates[5] = 'last-modified';\n$.servers.http.Response.discardDuplicates[6] = 'location';\n$.servers.http.Response.discardDuplicates[7] = 'retry-after';\n$.servers.http.Response.defaultHeaders = (new 'Object.create')(null);\n$.servers.http.Response.defaultHeaders['cache-control'] = 'no-store';\n$.servers.http.Response.defaultHeaders.server = 'CodeCity/0.0 ($.servers.http)';\n$.servers.http.Host = function Host() {\n  /* A Host object represents a domain or subdomain served by the\n   * web server.  It is expected that most Host instances will be\n   * the values of properties of $.hosts.\n   *\n   * Methods on Host.prototype (see individual methodd documentation\n   * for details):\n   *\n   * - .addSubdomain() - add a new subdomain to .subdomains.\n   * - .handle() - try to have this host handle an incoming request.\n   * - .url() - return the URL for this host.\n   * - .urlForSubdomain() - a helper method for .url().\n   *\n   * Instance properties of Host objects (by default these all\n   * inherit their default values from Host.prototype):\n   *\n   * - access: string - Access control switch.  It has the following\n   *   possible values:\n   *\n   *   - 'public': The host will by default serve pages to any client\n   *     unless the handler object has .wwwAccess === 'private', in\n   *     which case it will only be served to logged-in users.\n   *     Unauthenticated clients will get 403 forbidden and be\n   *     directed to login.\n   *\n   *   - 'private': The host will by default only serve pages to\n   *     logged-in users unless the hander object has .wwwAccess ===\n   *     'public'.\n   *\n   *   - 'hidden': The host will only serve pages to logged-in users;\n   *     any unauthenticated client will be declined (by .handle\n   *     returning false) which will normally result in them recieving\n   *     a 400 Unknown Host error.\n   *\n   * - hostname: string | undefined - the canonical hostname for\n   *   this Host object.  Should include the port number, if non-default.\n   *\n   *   If .hostRegExp (see below) is undefined, .hostname will be used to\n   *   decide which Requests to handle:\n   *\n   *   - This host object will serve requests whose Host: header exactly\n   *     matches .hostname itself.\n   *   - It will pass requests whose Host: header ends with .hostname to\n   *     the corresponding subdomain, if it exists.\n   *\n   *   E.g., if .hostname = 'bar.baz', this host will serve requests for\n   *   bar.baz and will pass requests for foo.bar.baz to .subdomains.foo\n   *   but will reject requests for bar.baz:8080.\n   *\n   *   If both .hostname and .hostRegExp are undefined, all requests will\n   *   be served by this host or automagically passed along to a suitable\n   *   subdomain.\n   *\n   * - hostRegExp: RegExp | undefined - a RegExp matching Host: header\n   *   values this host should respond to.  If undefined (the default),\n   *   this .hostname (see above) will be used instead.\n   *\n   *   Note that when the Host is deciding whether to serve a Request\n   *   itself, this regexp will be treated as if it begins with /^/,\n   *   while when the Host is trying to determine if it should be passed\n   *   off to a subdomain it will treat it as if it begins with /(?<=\\.)/\n   *   (despite ES5.1 not supporting such look-behind assertions).\n   *\n   *   This means that .hostRegExp = /bar.baz$/ will cause this Host object\n   *   to serve 'bar.baz' and try to pass 'foo.bar.baz' to .subdomains.foo,\n   *   but will always reject 'foobar.baz'.  Anchoring with /^/ will\n   *   prevent subdomain matching, so don't do that if you don't mean to!\n   *\n   *   It's recommended that .hostRegExp be anchored with /$/, but note\n   *   that if you want to serve pages on a non-standard ports you must\n   *   match the port as well - e.g.:  /example\\.codecity\\.\\w+(?::\\d+)$/\n   *   will match example.codecity.<any TLD> with or without a port number.\n   *\n   * - pathToSubdomain: boolean | undefined - enable (or disable) mapping\n   *   the first element (directory) of request paths to a subdomain.\n   *\n   *   If set to  undefined, the CodeCity-pathToSubdomain header will be\n   *   used to determine decide whether to do this mapping on a\n   *   per-request basis (but normally this header will be configured\n   *   staticaly in the nginx reverse-proxy configuration).\n   *\n   *   The CodeCity-pathToSubdomain header will be interpreted according\n   *   to the RFC 8941 Structure Field Values convention, with '?1'\n   *   meaning true and '?0' meaning false.  Any other value will be\n   *   treated as false.\n   *\n   * - subdomains: Object<string, Host> | null - a null-prototype\n   *   object mapping subdomain names to their respective Host objects,\n   *   or just null if there are no subdomains.  Use .addSubdomain to\n   *   add entries to this mapping.  (Default: null.)\n   */\n};\nObject.setOwnerOf($.servers.http.Host, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Host.prototype, $.physicals.Maximilian);\n$.servers.http.Host.prototype.handle = function handle(request, response, info) {\n  /* Attempt to handle an http(s) request.  First tries to see if the\n   * request can be served by the Host object of a direct subdomain\n   * of this Host, then tries to handle itself, then, if\n   * this.pseudoSubdomains is enabled, attempts to route the request\n   * to a subdomain Host based on the first component of the path.\n   *\n   * Arguments:\n   * - request: $.servers.http.Request - the incoming request to handle.\n   * - response: $.servers.http.Response - the response to write to.\n   * - info: Object | undefined - some information used by recursive calls to\n   *   this function.\n   * Returns: boolean - true iff request was for this host.\n   */\n  if (!info) {\n    // Extact detailed routing info from request.\n    var hostHeader = request.headers.host;\n    info = {\n      origin: hostHeader,  // For Request.prototype.fromSameOrigin.\n      path: request.path,\n      rootHost: this,\n    };\n\n    // The authorityExact RegExp gives submatches [ipAddress, dnsAddress,\n    // port].  Only one of the addresses capture groups will match.\n    var m = $.utils.url.regexps.authorityExact.exec(hostHeader);\n    if (!m) {  // Invalid Host header.\n      response.sendError(400, 'Invalid Host header.');\n      return true;  // We don't want it, but no one else should either.\n    } else if (m[1]) {  // It's an IP address.  No (real) subdomains possible.\n      info.rootAuthority = info.authority = hostHeader;\n    } else if (this.hostRegExp || this.hostname) {\n      var hostRegExp = this.hostRegExp ? this.hostRegExp :\n        new RegExp($.utils.regexp.escape(this.hostname) + '$')\n      // We have a .hostname or .hostRegExp, and can work out if there is a\n      // subdomain prefixed to request.headers.host from that.\n      m = hostRegExp.exec(hostHeader);\n      if (!m) return false;  // Did not match.  Not for us.\n      // Apply a check equivalent to a /(?<=^|\\.)/ look-behind assertion.\n      if (m.index > 0) {\n        if (hostHeader[m.index - 1] !== '.') return false;  // Lookbehind failed.\n        // Record subdomain(s) that need to be matched.\n        info.subdomains = hostHeader.slice(0, m.index - 1).split('.');\n      }\n      info.rootAuthority = info.authority = hostHeader.slice(m.index);\n    } else {\n      // Try to guess where the subdomain(s) end and the root hostname begins.\n      // To deal correclty with cases like x.x.y.z and x.y.x.y.z, be\n      // pessimistic and assume they're all subdomains to start with.\n      var potentialSubdomains  = hostHeader.split('.');\n      info.rootAuthority = info.authority = potentialSubdomains.pop();  // TLD can't be subdomain!\n      for (var i = potentialSubdomains.length; i >= 0; i--) {\n        info.subdomains = potentialSubdomains.slice(0, i);\n        var r = this.handle(request, response, info);\n        if (r) return r;\n        info.rootAuthority = info.authority = potentialSubdomains[i - 1] + '.' + info.authority;\n      }\n      return false;\n    }\n  }\n\n  // Is this request for us or a subdomain of us?\n  if (!this.matchHostname_(info.authority)) return false;\n\n  // This request is for us or a subdomain.\n  // Do we need to try to find a subdomain for this request?\n  if (info.subdomains && info.subdomains.length) {\n    var subdomain = info.subdomains.pop();\n    if (!(subdomain in this.subdomains)) return false;\n    info.authority = subdomain + '.' + info.authority;\n    return this.subdomains[subdomain].handle(request, response, info);\n  }\n\n  // No, it's for us.  Should we hide from unauthenticated clients?\n  if (this.access === 'hidden' && !($.user.isPrototypeOf(request.user))) {\n    return false;\n  }\n  // No.  Serve reqeust.\n  this.route_(request, response, info);\n  return true;\n};\nObject.setOwnerOf($.servers.http.Host.prototype.handle, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Host.prototype.handle.prototype, $.physicals.Maximilian);\n$.servers.http.Host.prototype.route_ = function route_(request, response, info) {\n  /* Attempt to route an http(s) request for this host to the correct\n   * handler.  If a handler is found, call it.\n   *\n   * If no handler is found, but this host has .pathToSubdomain set,\n   * or .pathToSubdomain is undefined but request contains a\n   * CodeCity-pathToSubdomain header with value '?1' (true, in RFC 8941\n   * Structured Field Value notation) then attempt to map the first\n   * element (directory name) of info.path to one of .subdomains and,\n   * if successful, call the corresponding subdomain host's .handle\n   * method.\n   *\n   * Otherwise generate a 404 error.\n   *\n   * Arguments:\n   * - request: $.servers.http.Request - the incoming request to handle.\n   * - response: $.servers.http.Response - the response to write to.\n   * - info: Object - some additional information generated by\n   *       Host.prototype.handle (see that method for details).\n   */\n  var path = info.path;\n  if (typeof path !== 'string' || path[0] !== '/') {\n    response.sendError(400, 'Invalid path \"' + path + '\"');\n  } else if (path in this) {\n    // Get handler object.\n    var obj = this[path];\n    if (!$.utils.isObject(obj)) {\n      response.sendError(500, \"Handler is not an object.\");\n      return;\n    }\n    // Check access control.\n    if (!($.user.isPrototypeOf(request.user)) &&  // Not logged in.\n        ((this.access !== 'public' && obj.wwwAccess !== 'public') ||\n         obj.wwwAccess === 'private')) {\n      response.sendError(403);\n      return;\n    }\n    // Record routing info on Request object and serve page.\n    request.info = info;\n    if (typeof obj.www === 'string') {\n      $.jssp.eval(obj, 'www', request, response);\n    } else if (typeof obj.www === 'function') {\n      obj.www(request, response);\n    } else {\n      response.sendError(500, \"Handler .www is neither a function nor a JSSP.\");\n    }\n  } else if (this.subdomains &&\n             (this.pathToSubdomain ||\n              (this.pathToSubdomain === undefined &&\n               request.headers['codecity-pathtosubdomain'] === '?1'))) {\n    // Try to route to a subdomain based on top-level directory.\n    // E.g. https://example.codecity.world/foo/bar -> foo\n    var m = path.match(/^\\/([-A-Za-z0-9]+)(\\/.*)?$/);\n    var subdomain = '';  // Empty string gives good 404 message if .match fails.\n    if (m && (subdomain = m[1]) in this.subdomains) {\n      // Subdomain matched.  Do we need to redirect to add a trailing '/'?\n      if (!m[2]) {\n        response.sendRedirect(subdomain + '/', 308);\n        return;\n      }\n      // Route to the subdomain.  Modify info.path and info.origin as appropriate\n      info.path = m[2];\n      info.origin += '/' + subdomain;\n      if (!this.subdomains[subdomain].handle(request, response, info)) {\n        response.sendError(500, 'Host for pseudo-subdomain /' + subdomain + '/ rejected request.');\n        return;\n      }\n    } else {\n      response.sendError(404, 'Not Found (and /' + subdomain + '/ does not map to a subdomain).');\n    }\n  } else {\n    response.sendError(404);\n  }\n};\nObject.setOwnerOf($.servers.http.Host.prototype.route_, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Host.prototype.route_.prototype, $.physicals.Maximilian);\n$.servers.http.Host.prototype.matchHostname_ = function matchHostname_(hostname) {\n  /* Returns: boolean - true if hostname exactly matches this.hostRegExp or,\n   *     if that is undefined, this.hostname.\n   */\n  if (this.hostRegExp) {\n    if (!(this.hostRegExp instanceof RegExp)) {\n      throw new TypeError('invalid .hostRegExp');\n    }\n    var m = this.hostRegExp.exec(hostname);\n    return (m && m.index === 0);  // Match only accepted if at start.\n  } else if (this.hostname) {\n    if (typeof this.hostname !== 'string') {\n      throw new TypeError('invalid .hostname');\n    }\n    return this.hostname === hostname;  // Only exact matches.\n  } else {\n    return true;\n  }\n};\nObject.setOwnerOf($.servers.http.Host.prototype.matchHostname_, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Host.prototype.matchHostname_.prototype, $.physicals.Maximilian);\n$.servers.http.Host.prototype.hostname = undefined;\n$.servers.http.Host.prototype.subdomains = null;\n$.servers.http.Host.prototype.addSubdomain = function addSubdomain(name, host) {\n  /* Add the given Host as a subdomain of this Host.\n   *\n   * Arguments:\n   * - name: string - the subdomain name.\n   * - host: $.servers.http.Host - the Host to serve the subdomain.\n   */\n  name = String(name);\n  if (!(host instanceof $.servers.http.Host)) {\n    throw new TypeError('host must be a Host');\n  }\n  if (!this.hasOwnProperty('subdomains')) {\n    this.subdomains = Object.create(null);\n  }\n  this.subdomains[name] = host;\n};\nObject.setOwnerOf($.servers.http.Host.prototype.addSubdomain, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Host.prototype.addSubdomain.prototype, $.physicals.Maximilian);\n$.servers.http.Host.prototype.url = function url(varArgs) {\n  /* Return the base URL for this host (omitting scheme).\n   *\n   * Generally prefer $.servers.http.Request.prototype.hostUrl (q.v.)\n   * instead of method - but in some cases it is necessary to generate\n   * a URL for the webserver without an existing inbound Request to use\n   * as reference, so this method allows one to be generated in the\n   * obvious way from this.hostname.  As with .hostUrl:\n   *\n   * - Absent any argument, the returned URL will routes to this\n   *   Host object.\n   * - If an argument is supplied, the returned URL will instead be for\n   *   the named subdomain.\n   * - Multiple arguments can be supplied if there are nested subdomains.\n   *\n   * E.g.:\n   * rootHost.url()             => '//example.codecity.world/'\n   * rootHost.url('code')       => '//code.example.codecity.world/'\n   * rootHost.url('foo', 'bar') => '//foo.bar.example.codecity.world/'\n   *\n   * If .pathToSubdomain is enabled on one or more Host object(s):\n   * rootHost.url('code')       => '//example.codecity.world/code/'\n   * rootHost.url('foo', 'bar') => '//example.codecity.world/foo/bar/'\n   *                           or: '//bar.example.codecity.world/foo/'\n   *\n   * Barring bugs, the returned URL should always end with a '/'.\n   * Arguments:\n   * - subdomain: string - a string denoting a subdomain of interest.\n   *       Multiple arguments are allowed.  RangeError is thrown if no such\n   *       subdomain exists.\n   * Returns: string - the URL for the desired domain/subdomain.\n   */\n  if (typeof this.hostname !== 'string') {\n    throw new Error('canonical hostname not set');\n  }\n  var hostname = this.hostname;\n  var host = this;\n  for (var subdomain, i = 0; (subdomain = arguments[i]); i++) {\n    hostname = host.urlForSubdomain(hostname, subdomain);\n  }\n  return '//' + hostname + '/';\n};\nObject.setOwnerOf($.servers.http.Host.prototype.url, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Host.prototype.url.prototype, $.physicals.Maximilian);\n$.servers.http.Host.prototype.pathToSubdomain = undefined;\n$.servers.http.Host.prototype.urlForSubdomain = function urlForSubdomain(hostname, subdomain, pathToSubdomainHeader) {\n  /* A helper function for the .url method.\n   *\n   * Given a hostname for this host, add the specified subdomain\n   * if it exists, or throw RangeError if not.\n   *\n   * If this.pathToSubdomain is true, or this.pathToSubdomain is undefined\n   * and pathToSubdomainHeader is true, then the subdomain will be added as\n   * a directory name suffix rather than a hostname pefix.\n   *\n   * E.g.:\n   * rootHost.pathToSubdomain = false;\n   * rootHost.urlForSubdomain('example.codecity.world', 'code')\n   *    => 'code.example.codecity.world'\n   *\n   * rootHost.pathToSubdomain = undefined;\n   * rootHost.urlForSubdomain('example', 'code', true)\n   *    => 'example.codecity.world/code'\n   * rootHost.urlForSubdomain('example', 'code', false)\n   *    => 'code.example.codecity.world'\n   * rootHost.pathToSubdomain = true;\n   * rootHost.urlForSubdomain('example', 'code', false)\n   *    => 'example.codecity.world/code'\n   *\n   * Arguments:\n   * - hostname: string - the base hostname for this Host.\n   * - subdomain: string - the desired subdomain.\n   * - pathToSubdomainHeader: boolean | undefined - value of the\n   *   CodeCity-pathToSubdomain header for the current request (if there\n   *   is one).\n   *\n   * TODO: Give this function a better name, because what it returns\n   * is not actually a valid URL.\n   */\n  if (!(this.subdomains && subdomain in this.subdomains)) {\n    throw new RangeError('nonexistent subdomain \"' + subdomain + '\"');\n  }\n  if (this.pathToSubdomain ||\n      this.pathToSubdomain === undefined && pathToSubdomainHeader) {\n    return hostname + '/' + subdomain;\n  } else {\n    return subdomain + '.' + hostname;\n  }\n};\nObject.setOwnerOf($.servers.http.Host.prototype.urlForSubdomain, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Host.prototype.urlForSubdomain.prototype, $.physicals.Maximilian);\n$.servers.http.Host.prototype.deleteSubdomain = function deleteSubdomain(subdomain) {\n  /* Delete a subdomain, or all subdomains served by a particular\n   * Host object.\n   *\n   * Arguments:\n   * - subdomain: string | $.servers.http.Host - the name of the subdomain\n   *   to be deleted, or the Host object serving it.\n   */\n  if (!this.subdomains) return;\n  if (typeof subdomain === 'string') {\n    delete this.subdomains[subdomain];\n  } else if (subdomain instanceof $.servers.http.Host) {\n    for (var key in this.subdomains) {\n      if (this.subdomains[key] === subdomain) {\n        delete this.subdomains[key];\n      }\n    }\n  } else {\n    throw new TypeError('argument must be subdomain name or Host object');\n  }\n  if (Object.getOwnPropertyNames(this.subdomains).length === 0) {\n    delete this.subdomains;\n  }\n};\nObject.setOwnerOf($.servers.http.Host.prototype.deleteSubdomain, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.Host.prototype.deleteSubdomain.prototype, $.physicals.Maximilian);\n$.servers.http.onRequest = function onRequest(connection) {\n  /* Called from $.servers.http.connection.onReceiveChunk when the\n   * connection.request has been fully parsed and is ready to be handled.\n   *\n   * Arguments:\n   * - conenction: Object with prototype $.servers.http.connection - the\n   *       connection to be handle.\n   */\n  var request = connection.request;\n  var response = connection.response;\n  try {\n    // Call .handle(request, response) on each Host object in\n    // $.servers.http.hosts in order until one returns true to indicate\n    // that it handled the request.\n    for (var host, i = 0; (host = this.hosts[i]); i++) {\n      if (host.handle(request, response)) return;\n    }\n    // No host responded to request.\n    response.sendError(400, 'Unknown Host');\n  } catch (e) {\n    suspend();\n    $.system.log(String(e) + '\\n' + e.stack);\n    if (response.headersSent) {\n      // Too late to return a proper error page.  Oh well.\n      response.write('<pre>' + $.utils.html.escape(String(e) + '\\n' + e.stack) +\n                     '</pre>');\n    } else {\n      response.sendError(500, e);\n    }\n  } finally {\n    suspend();\n    connection.close();\n  }\n};\nObject.setOwnerOf($.servers.http.onRequest, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.http.onRequest.prototype, $.physicals.Maximilian);\n\n$.servers.http.hosts = [];\n\n"
  },
  {
    "path": "core/core_24_$.hosts.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Host objects for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.hosts = {};\n\n$.hosts.root = (new 'Object.create')($.servers.http.Host.prototype);\n\n$.hosts.root.subdomains = (new 'Object.create')(null);\n\n$.hosts.root['/'] = {};\n$.hosts.root['/'].www = '<!doctype html>\\n<% var staticUrl = request.hostUrl(\\'static\\'); %>\\n<html lang=\"en\">\\n<head>\\n  <title>Code City</title>\\n  <style>\\n    body {\\n      font-family: \"Roboto Mono\", monospace;\\n      text-align: center;\\n    }\\n    h1 {\\n      font-size: 40pt;\\n      font-weight: 100;\\n    }\\n    h1>img {\\n      vertical-align: text-bottom;\\n    }\\n    #tagline {\\n      font-style: italic;\\n      margin: 2em;\\n    }\\n    iframe {\\n      height: 50px;\\n      width: 100px;\\n      border: none;\\n      display: block;\\n      margin: 0 auto;\\n    }\\n  </style>\\n  <link href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\" rel=\"stylesheet\">\\n  <link href=\"<%=staticUrl%>favicon.ico\" rel=\"shortcut icon\">\\n</head>\\n<body>\\n  <h1>\\n    <img src=\"<%=staticUrl%>logo.svg\" alt=\"\" width=\"95\" height=\"100\">\\n    Code City\\n  </h1>\\n  <p id=\"tagline\">A community of inquisitive programmers.</p>\\n  <iframe src=\"<%=request.hostUrl(\\'login\\')%>?after=<%=request.hostUrl(\\'connect\\')%>\"></iframe>\\n</body>\\n</html>';\n$.hosts.root['/'].wwwAccess = 'public';\n\n$.hosts.root['/mirror'] = {};\nObject.setOwnerOf($.hosts.root['/mirror'], $.physicals.Maximilian);\n$.hosts.root['/mirror'].www = \"<!doctype html>\\n<% var staticUrl = request.hostUrl('static'); %>\\n<html>\\n  <head>\\n    <title>Code City Browser Mirror</title>\\n    <style>\\n      body {\\n        font-family: \\\"Roboto Mono\\\", monospace;\\n      }\\n      h1 {\\n        text-align: center;\\n      }\\n      h1>img {\\n        vertical-align: text-bottom;\\n      }\\n    </style>\\n    <link href=\\\"https://fonts.googleapis.com/css?family=Roboto+Mono\\\" rel=\\\"stylesheet\\\">\\n    <link href=\\\"<%=staticUrl%>favicon.ico\\\" rel=\\\"shortcut icon\\\">\\n  </head>\\n  <body>\\n    <h1>\\n      <img src=\\\"<%=staticUrl%>logo.svg\\\" alt=\\\"\\\" width=\\\"47.5\\\" height=\\\"50\\\">\\n      Code City Browser Mirror\\n    </h1>\\n<%\\nfor (var key in request) {\\n  if (!request.hasOwnProperty(key)) continue;\\n  var value = request[key];\\n  \\n  response.write('<h2>request.' + $.utils.html.escape(key) + ':</h2>\\\\n');\\n  response.write('<pre>');\\n  if (key === 'user') {\\n    response.write(value ? $.utils.html.escape(value.name) : value + '\\\\n');\\n  } else if (true || key === 'info') {\\n    response.write($.utils.html.escape($.utils.code.expressionFor(value, {\\n      depth: (key === 'info' ? 1 : 2),\\n      abbreviateMethods: true,\\n      proto: 'ignore',\\n      owner: 'ignore',\\n    })));\\n  }\\n  response.write('</pre>');\\n}\\n%>\\n    <h2>request.fromSameOrigin(): [<a href=\\\"<%= request.hostUrl() %>mirror\\\">test</code></a>]</h2>\\n    <pre><%= request.fromSameOrigin() %></pre>\\n    <h2>request.hostUrl('system'):</h2>\\n    <pre><%= $.utils.html.escape($.utils.code.quote(request.hostUrl('system'))) %></pre>\\n    <p>Done</p>\\n  </body>\\n</html>\";\n$.hosts.root['/mirror'].wwwAccess = 'public';\n\n$.hosts.root['/robots.txt'] = {};\n$.hosts.root['/robots.txt'].www = \"<% response.setHeader('Content-Type', 'text/plain; charset=utf-8') %>\\n# Don't index this Code City instance at this time.\\nUser-agent: *\\nDisallow: /\";\n$.hosts.root['/robots.txt'].wwwAccess = 'public';\n\n$.hosts.system = (new 'Object.create')($.servers.http.Host.prototype);\n$.hosts.system['/logout'] = {};\nObject.setOwnerOf($.hosts.system['/logout'], $.physicals.Neil);\n$.hosts.system['/logout'].www = '<%\\nvar staticUrl = request.hostUrl(\\'static\\');\\nvar doLogout = !request.user ||\\n    (request.query === \\'execute\\' && request.fromSameOrigin());\\nif (doLogout) {\\n  response.clearIdCookie()\\n}\\n%>\\n<!doctype html>\\n<html lang=\"en\">\\n<head>\\n  <title>Code City Logout</title>\\n  <style>\\n    body {\\n      font-family: \"Roboto Mono\", monospace;\\n      text-align: center;\\n    }\\n    h1 {\\n      font-size: 40pt;\\n      font-weight: 100;\\n    }\\n    h1>img {\\n      vertical-align: text-bottom;\\n    }\\n    #tagline {\\n      font-style: italic;\\n      margin: 2em;\\n    }\\n    iframe {\\n      height: 50px;\\n      width: 100px;\\n      border: none;\\n      display: block;\\n      margin: 0 auto;\\n    }\\n  </style>\\n  <link href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\" rel=\"stylesheet\">\\n  <link href=\"<%=staticUrl%>favicon.ico\" rel=\"shortcut icon\">\\n  <link href=\"<%=staticUrl%>style/jfk.css\" rel=\"stylesheet\">\\n\\n  </head>\\n<body>\\n  <h1>\\n    <img src=\"<%=staticUrl%>logo.svg\" alt=\"\" width=\"95\" height=\"100\">\\n    Code City\\n  </h1>\\n  <p id=\"tagline\"><%= request.info.rootAuthority || request.info.host.hostname || \\'\\' %></p>\\n<% if (doLogout) { %>\\n  <p>You have been signed out.</p>\\n  <iframe src=\"<%=request.hostUrl(\\'login\\')%>\"></iframe>\\n<% } else { %>\\n  <div class=\"jfk-button jfk-button-action\" role=\"button\" id=\"signout\">\\n    Sign out\\n  </div>\\n  <script>\\n    var button =  document.getElementById(\\'signout\\');\\n    button.addEventListener(\\'click\\', function() {\\n      parent.location = \"?execute\";\\n    });\\n  </script>\\n<% } %>\\n</body>\\n</html>';\n\n$.hosts.dummy = (new 'Object.create')($.servers.http.Host.prototype);\nObject.setOwnerOf($.hosts.dummy, $.physicals.Maximilian);\n$.hosts.dummy.handle = function handle(request, response, info) {\n  /* Report the mishandling of an http(s) request which should have\n   * been intercepted by the nginx front-end and proxied to one\n   * of the other servers.\n   *\n   * This Host object is a singleton placeholer to mark (in\n   * $.hosts.root.subdomains) the subdomains that should be directed\n   * to loginServer, connectServer, etc., or served from the /static/\n   * directory.  As such, no requests should ever be able to reach\n   * this Host object except due to a misconfiguration of nginx.\n   *\n   * Arguments:\n   * - request: $.servers.http.Request - the incoming request to handle.\n   * - response: $.servers.http.Response - the response to write to.\n   * - info: Object - some information used by recursive calls to this function.\n   * Returns: boolean - always true as all requests successfully generate\n   *     an error message.\n   */\n  response.sendError(500, 'This request should have been intercepted by ' +\n                     'the reverse proxy.  Check nginx configuration!');\n  return true;\n};\nObject.setOwnerOf($.hosts.dummy.handle, $.physicals.Maximilian);\nObject.setOwnerOf($.hosts.dummy.handle.prototype, $.physicals.Maximilian);\n\n$.hosts.root.subdomains.system = $.hosts.system;\n\n$.hosts.root.subdomains.connect = $.hosts.dummy;\n\n$.hosts.root.subdomains.login = $.hosts.dummy;\n\n$.hosts.root.subdomains.mobwrite = $.hosts.dummy;\n\n$.hosts.root.subdomains.static = $.hosts.dummy;\n\n\n$.servers.http.hosts[0] = $.hosts.root;\n\n"
  },
  {
    "path": "core/core_25_$.db.tempId.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Temporary ID database for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.db = {};\n\n$.db.tempId = {};\n$.db.tempId.getObjById = function getObjById(id) {\n  /* Find object temporarily stored with the given ID.\n   */\n  var record = this.tempIds_[id];\n  if (record) {\n     record.time = Date.now();\n     return record.obj;\n  }\n  return undefined;\n};\nObject.setOwnerOf($.db.tempId.getObjById, $.physicals.Maximilian);\n$.db.tempId.storeObj = function storeObj(obj) {\n  /* Find temporary ID for obj in this.tempIds_,\n   * adding it if it's not already there.\n   */\n  var records = this.tempIds_;\n  for (var id in records) {\n    if (Object.is(records[id].obj, obj)) {\n      records[id].time = Date.now();\n      return id;\n    }\n  }\n  do {\n    var id = Math.floor(Math.random() * 0xFFFFFFFF);\n  } while (records[id]);\n  records[id] = {obj: obj, time: Date.now()};\n  // Lazy call of cleanup.\n  this.cleanSoon();\n  return id;\n};\nObject.setOwnerOf($.db.tempId.storeObj, $.physicals.Maximilian);\n$.db.tempId.cleanSoon = function cleanSoon() {\n  // Schedule a cleanup to happen in a minute.\n  // Allows multiple calls to be batched together.\n  if (!this.cleanThread_) {\n    this.cleanThread_ = setTimeout(this.cleanNow.bind(this), 60 * 1000);\n  }\n};\nObject.setOwnerOf($.db.tempId.cleanSoon, $.physicals.Neil);\n$.db.tempId.cleanNow = function cleanNow() {\n  // Cleanup IDs/objects that have not been accessed in an hour.\n  clearTimeout(this.cleanThread_);\n  this.cleanThread_ = null;\n  var ttl = Date.now() - this.timeoutMs;\n  var records = this.tempIds_;\n  for (var id in records) {\n    if (records[id].time < ttl) {\n      delete records[id];\n    }\n  }\n};\nObject.setOwnerOf($.db.tempId.cleanNow, $.physicals.Neil);\n$.db.tempId.timeoutMs = 3600000;\n\n$.db.tempId.tempIds_ = (new 'Object.create')(null);\n\n$.db.tempId.cleanThread_ = undefined;\n\n"
  },
  {
    "path": "core/core_25_$.userDatabase.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview User database for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.userDatabase = {};\nObject.setOwnerOf($.userDatabase, $.physicals.Maximilian);\n$.userDatabase.get = function get(id) {\n  // Returns the user, or undefined.\n  var hash = $.utils.string.hash('md5', this.salt_ + id);\n  var table = this.byMd5;\n  var value = table[hash];\n  if (!($.user.isPrototypeOf(value))) {\n    delete table[hash];\n    return undefined;\n  }\n  return value;\n};\nObject.setOwnerOf($.userDatabase.get, $.physicals.Neil);\nObject.setOwnerOf($.userDatabase.get.prototype, $.physicals.Maximilian);\n$.userDatabase.set = function set(id, user) {\n  if (!$.user.isPrototypeOf(user)) {\n    throw new TypeError('userDatabase only accepts $.user values');\n  }\n  var hash = $.utils.string.hash('md5', this.salt_ + id);\n  this.byMd5[hash] = user;\n};\nObject.setOwnerOf($.userDatabase.set, $.physicals.Maximilian);\nObject.setOwnerOf($.userDatabase.set.prototype, $.physicals.Maximilian);\n$.userDatabase.validate = function validate() {\n  var table = this.byMd5\n  for (var key in table) {\n    if (!($.user.isPrototypeOf(table[key]))) {\n      delete table[key];\n    }\n  }\n};\nObject.setOwnerOf($.userDatabase.validate, $.physicals.Maximilian);\nObject.setOwnerOf($.userDatabase.validate.prototype, $.physicals.Maximilian);\n$.userDatabase.salt_ = 'v2OU0LHchCl84mhu';\n\n$.userDatabase.byMd5 = (new 'Object.create')(null);\n\n"
  },
  {
    "path": "core/core_26_inline_editor.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Inline code editor for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.hosts.code = (new 'Object.create')($.servers.http.Host.prototype);\n\n$.hosts.code['/inlineEdit'] = {};\n$.hosts.code['/inlineEdit'].edit = function edit(obj, name, key) {\n  /* Return a (valid) URL for a web editing session editing obj[key],\n   * where obj might more commonly be known as name.\n   */\n  if (!$.utils.isObject(obj)) throw new TypeError('obj must be an object');\n  if (typeof(key) !== 'string') throw new TypeError('key must be a string');\n\n  var objId = $.db.tempId.storeObj(obj);\n  var url = $.hosts.root.url('code') + 'inlineEdit?objId=' + objId;\n  if (name) {\n    url += '&name=' + encodeURIComponent(name);\n  }\n  if (key) {\n    url += '&key=' + encodeURIComponent(key);\n  }\n  return url;\n};\nObject.setOwnerOf($.hosts.code['/inlineEdit'].edit, $.physicals.Maximilian);\n$.hosts.code['/inlineEdit'].load = function load(obj, key) {\n  /* Return string containing initial editor contents for editing\n   * obj[key].\n   */\n  var pd = Object.getOwnPropertyDescriptor(obj, key);\n  var value = pd ? pd.value : undefined;\n  if (typeof value === 'function') {\n    return Function.prototype.toString.apply(value);\n  } else {\n    return $.utils.code.expressionFor(value, {depth: 1});\n  }\n};\nObject.setOwnerOf($.hosts.code['/inlineEdit'].load, $.physicals.Maximilian);\n$.hosts.code['/inlineEdit'].save = function save(obj, key, src) {\n  /* Eval the string src and (if successful) save the resulting value\n   * as obj[key].  If the value produced from src and the existing\n   * value of obj[key] are both objects, then an attempt will be made\n   * to copy any properties from the old value to the new one.\n   */\n  var old = obj[key];\n  src = $.utils.code.rewriteForEval(src, /* forceExpression= */ true);\n  // Evaluate src in global scope (eval by any other name, literally).\n  // TODO: don't use eval - prefer Function constructor for\n  // functions; generate other values from an Acorn parse tree.\n  var evalGlobal = eval;\n  var val = evalGlobal(src);\n  if (typeof old === 'function' && typeof val === 'function') {\n    $.utils.object.transplantProperties(old, val);\n  }\n  if (typeof val === 'function') {\n    val.lastModifiedTime = Date.now();\n    // TODO: Add user.\n    //val.lastModifiedUser = ...;\n  }\n  obj[key] = val;\n  return this.load(obj, key);\n};\nObject.setOwnerOf($.hosts.code['/inlineEdit'].save, $.physicals.Maximilian);\n$.hosts.code['/inlineEdit'].www = '<%\\nvar staticUrl = request.hostUrl(\\'static\\');\\nvar params = request.parameters;\\nvar objId = params.objId;\\nvar obj = $.db.tempId.getObjById(params.objId);\\nif (!$.utils.isObject(obj)) {\\n  // Bad edit URL.\\n  response.sendError(404);\\n  return;\\n}\\nvar key = params.key;\\nvar src = params.src;\\nvar status = \\'\\';\\nif (src) {\\n  try {\\n    if (!request.fromSameOrigin()) {\\n      // Security check to ensure this is being loaded by the code editor.\\n      throw new Error(\\'Cross-origin referer: \\' + String(request.headers.referer));\\n    }\\n    src = this.save(obj, key, src);\\n    status = \\'(saved)\\';\\n    if (typeof obj[key] === \\'function\\') {\\n      if (params.isVerb) {\\n        obj[key].verb = params.verb;\\n        obj[key].dobj = params.dobj;\\n        obj[key].prep = params.prep;\\n        obj[key].iobj = params.iobj;\\n      } else {\\n        delete obj[key].verb;\\n        delete obj[key].dobj;\\n        delete obj[key].prep;\\n        delete obj[key].iobj;\\n      }\\n    }\\n  } catch (e) {\\n    status = \\'(ERROR: \\' + String(e) + \\')\\';\\n  }\\n} else {\\n  src = this.load(obj, key);\\n}\\nvar isVerb = (Object.getOwnPropertyDescriptor(obj, key) && typeof obj[key] === \\'function\\') && obj[key].verb ? \\'checked\\' : \\'\\';\\nvar verb = $.utils.html.escape((obj[key] && obj[key].verb) || \\'\\');\\nvar dobj = obj[key] && obj[key].dobj;\\nvar prep = obj[key] && obj[key].prep;\\nvar iobj = obj[key] && obj[key].iobj;\\nvar name = $.utils.html.escape(params.name);\\nkey = $.utils.html.escape(key);\\nvar objOpts = [\\'none\\', \\'this\\', \\'any\\']\\n%>\\n<!DOCTYPE html>\\n<html><head>\\n  <title>Code Editor for <%= name %>.<%= key %></title>\\n  <link href=\"<%=staticUrl%>style/jfk.css\" rel=\"stylesheet\">\\n  <style>\\n    body {margin: 0; font-family: sans-serif}\\n    h1 {margin-bottom: 5; font-size: small}\\n    #submit {position: fixed; bottom: 1ex; right: 2ex; z-index: 9}\\n    .CodeMirror {height: auto; border: 1px solid #eee}\\n    #verb {width: 15ex}\\n  </style>\\n\\n  <link rel=\"stylesheet\" href=\"<%=staticUrl%>CodeMirror/lib/codemirror.css\">\\n  <script src=\"<%=staticUrl%>CodeMirror/lib/codemirror.js\"></script>\\n  <script src=\"<%=staticUrl%>CodeMirror/mode/javascript/javascript.js\"></script>\\n</head><body>\\n  <form action=\"inlineEdit\" method=\"post\">\\n  <button type=\"submit\" class=\"jfk-button-submit\" id=\"submit\"\\n    onclick=\"document.getElementById(\\'src\\').value = editor.getValue()\">Save</button>\\n  <h1>Editing <%= name %>.<%= key %>\\n    <span id=\"status\"><%= status %></span></h1>\\n  <input name=\"objId\" type=\"hidden\" value=\"<%= $.utils.html.escape(objId) %>\">\\n  <input name=\"name\" type=\"hidden\" value=\"<%= name %>\">\\n  <input name=\"key\" type=\"hidden\" value=\"<%= key %>\">\\n  <div><input type=\"checkbox\" name=\"isVerb\" id=\"isVerb\" <%= isVerb %> onclick=\"updateDisabled(); changed()\">\\n    <label for=\"isVerb\">Verb:</label>\\n    <input name=\"verb\" id=\"verb\" value=\"<%= verb %>\" placeholder=\"name\">\\n    <select name=\"dobj\" id=\"dobj\" onchange=\"changed()\">\\n      <% for (var i = 0; i < objOpts.length; i++) {%>\\n        <option <%= dobj === objOpts[i] ? \\'selected\\' : \\'\\' %>><%= objOpts[i] %></option>\\n      <% } %>\\n    </select>\\n    <select name=\"prep\" id=\"prep\" onchange=\"changed()\">\\n      <% for (var i = 0; i < $.utils.command.prepositionOptions.length; i++) {%>\\n        <option <%= prep === $.utils.command.prepositionOptions[i] ? \\'selected\\' : \\'\\' %>><%= $.utils.command.prepositionOptions[i] %></option>\\n      <% } %>\\n    </select>\\n    <select name=\"iobj\" id=\"iobj\" onchange=\"changed()\">\\n      <% for (var i = 0; i < objOpts.length; i++) {%>\\n        <option <%= iobj === objOpts[i] ? \\'selected\\' : \\'\\' %>><%= objOpts[i] %></option>\\n      <% } %>\\n    </select>\\n  </div>\\n  <textarea name=\"src\" id=\"src\"><%= $.utils.html.escape(src) %>\\n</textarea>\\n  </form>\\n  <script>\\n    var editor = CodeMirror.fromTextArea(document.getElementById(\\'src\\'), {\\n      lineNumbers: true,\\n      matchBrackets: true,\\n      viewportMargin: Infinity,\\n    });\\n    editor.on(\\'change\\', changed);\\n    function changed() {\\n      document.getElementById(\\'status\\').innerText = \\'(modified)\\'\\n    }\\n    function updateDisabled() {\\n      var disabled = document.getElementById(\\'isVerb\\').checked ? \\'\\' : \\'disabled\\';\\n      document.getElementById(\\'verb\\').disabled = disabled;\\n      document.getElementById(\\'dobj\\').disabled = disabled;\\n      document.getElementById(\\'prep\\').disabled = disabled;\\n      document.getElementById(\\'iobj\\').disabled = disabled;\\n    }\\n    updateDisabled();\\n  </script>\\n</body></html>';\n\n$.hosts.root.subdomains.code = $.hosts.code;\n\n"
  },
  {
    "path": "core/core_27_editor.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Web-based code explorer/editor for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.hosts.code['/'] = {};\n$.hosts.code['/'].www = '<!DOCTYPE HTML Frameset DTD>\\n<% var staticUrl = request.hostUrl(\\'static\\'); %>\\n<html>\\n<head>\\n  <title>Code City: Code</title>\\n  <link href=\"<%=staticUrl%>favicon.ico\" rel=\"shortcut icon\">\\n  <script src=\"<%=staticUrl%>code/common.js\"></script>\\n  <script src=\"<%=staticUrl%>code/code.js\"></script>\\n</head>\\n<frameset rows=\"40%,60%\">\\n  <frame id=\"explorer\" src=\"explorer\" />\\n  <frame id=\"editor\" src=\"editor\" />\\n</frameset>\\n<noframes>Sorry, your browser does not support frames!</noframes>\\n</html>';\n$.hosts.code['/editor'] = {};\n$.hosts.code['/editor'].www = '<!doctype html>\\n<% var staticUrl = request.hostUrl(\\'static\\'); %>\\n<html>\\n  <head>\\n    <meta charset=\"utf-8\"/>\\n    <title>Code City: Code Editor</title>\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>code/style.css\">\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>code/editor.css\">\\n    <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\">\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>style/jfk.css\">\\n\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>CodeMirror/lib/codemirror.css\">\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>CodeMirror/addon/lint/lint.css\">\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>CodeMirror/theme/eclipse.css\">\\n    <script src=\"<%=staticUrl%>CodeMirror/lib/codemirror.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/addon/edit/matchbrackets.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/addon/comment/continuecomment.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/addon/mode/multiplex.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/addon/lint/lint.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/addon/lint/javascript-lint.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/addon/display/rulers.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/mode/css/css.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/mode/htmlembedded/htmlembedded.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/mode/htmlmixed/htmlmixed.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/mode/javascript/javascript.js\"></script>\\n    <script src=\"<%=staticUrl%>CodeMirror/mode/xml/xml.js\"></script>\\n\\n    <script src=\"<%=staticUrl%>code/common.js\"></script>\\n    <script id=\"editor_js\" src=\"<%=staticUrl%>code/editor.js\"></script>\\n  </head>\\n  <body>\\n    <div id=\"editorDialog\">\\n      <div id=\"editorDialogMask\"></div>\\n      <div id=\"editorDialogBox\">\\n        <div id=\"editorConfirmBox\">\\n          <p>Do you want to save changes?</p>\\n          <p>\\n            <button id=\"editorConfirmDiscard\" class=\"jfk-button\">Discard</button>\\n            <button id=\"editorConfirmSave\" class=\"jfk-button jfk-button-submit\">Save</button>\\n            <button id=\"editorConfirmCancel\" class=\"jfk-button\">Cancel</button>\\n          </p>\\n        </div>\\n        <div id=\"editorShareBox\" class=\"disabled\">\\n          <p>\\n            <label><input type=\"checkbox\" id=\"editorShareCheck\" disabled> Share this editor:</label>\\n          </p>\\n          <p>\\n            <input id=\"editorShareAddress\" readonly>\\n          </p>\\n          <p>\\n            <button id=\"editorShareOk\" class=\"jfk-button jfk-button-submit\">Ok</button>\\n          </p>\\n        </div>\\n      </div>\\n    </div>\\n    <div id=\"editorButter\"><div><div id=\"editorButterText\"></div></div></div>\\n    <div id=\"editorSavingMask\"></div>\\n    <div id=\"editorButtons\">\\n      <button id=\"editorShare\" class=\"jfk-button\">Share...</button>\\n      <button id=\"editorSave\" class=\"jfk-button\">Save</button>\\n    </div>\\n    <div id=\"editorTabs\" class=\"disabled\">\\n      <span class=\"spacer\"></span>\\n    </div>\\n    <div id=\"editorHeader\" class=\"loading\"></div>\\n    <div id=\"editorContainers\"></div>\\n  </body>\\n</html>\\n';\n$.hosts.code['/explorer'] = {};\n$.hosts.code['/explorer'].www = '<!doctype html>\\n<% var staticUrl = request.hostUrl(\\'static\\'); %>\\n<html>\\n  <head>\\n    <meta charset=\"utf-8\"/>\\n    <title>Code City: Code Explorer</title>\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>code/style.css\">\\n    <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\">\\n    <script src=\"<%=staticUrl%>code/common.js\"></script>\\n    <script src=\"<%=staticUrl%>code/explorer.js\"></script>\\n  </head>\\n  <body>\\n    <input type=\"text\" id=\"input\" autocomplete=\"off\">\\n    <div id=\"autocompleteMenu\"><div id=\"autocompleteMenuScroll\"></div></div>\\n    <div id=\"panels\"><div id=\"panelsScroll\"><span id=\"panelSpacer\"></span></div></div>\\n  </body>\\n</html>\\n';\n$.hosts.code['/diff'] = {};\n$.hosts.code['/diff'].www = '<% var staticUrl = request.hostUrl(\\'static\\'); %>\\n<html>\\n  <head>\\n    <title>Code City Diff Editor</title>\\n    <script src=\"<%=staticUrl%>code/mobwrite/dmp.js\"></script>\\n    <script src=\"<%=staticUrl%>code/diff.js\"></script>\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>code/diff.css\">\\n  </head>\\n\\n  <body>\\n  </body>\\n</html>\\n';\n$.hosts.code['/objectPanel'] = {};\n$.hosts.code['/objectPanel'].www = '<!doctype html>\\n<% var staticUrl = request.hostUrl(\\'static\\'); %>\\n<html>\\n  <head>\\n    <meta charset=\"utf-8\"/>\\n    <title>Code City: Code Object Panel</title>\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>code/style.css\">\\n    <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\">\\n  </head>\\n  <body id=\"objectPanel\">\\n    <table id=\"objectTable\">\\n      <thead>\\n        <tr><td id=\"objectTitle\">&#8203;</td></tr>\\n      </thead>\\n      <tbody id=\"objectTableBody\">\\n        <tr><td class=\"loading\">&#8203;</td></tr> <!-- Zero width space to align the loading ellipsis. -->\\n      </tbody>\\n      <tfoot id=\"objectFail\">\\n        <tr><td>Server Error<br>Check your console&hellip;</td></tr>\\n      </tfoot>\\n    </table>\\n    <script src=\"<%=staticUrl%>code/common.js\"></script>\\n    <script src=\"<%=staticUrl%>code/objectPanel.js\"></script>\\n    <script>\\n      Code.ObjectPanel.data = <%=JSON.stringify(this.buildData(request.query), null, 2)%>;\\n    </script>\\n  </body>\\n</html>\\n';\n$.hosts.code['/objectPanel'].getType = function getType(value) {\n  // Return a type string for a value.\n  // E.g. 'string', 'object', 'array', 'boolean'.\n  if (value === null) {\n    return 'null';\n  }\n  if (Array.isArray(value)) {\n    return 'array';\n  }\n  if ((typeof value === 'function') && value.verb) {\n    return 'verb';\n  }\n  return typeof value;\n};\nObject.setOwnerOf($.hosts.code['/objectPanel'].getType, $.physicals.Neil);\n$.hosts.code['/objectPanel'].buildData = function buildData(query) {\n  // Provide data for the IDE's object panels.\n  // Takes one input: a JSON-encoded list of parts from the 'parts' parameter.\n  // Returns a browser-executed JavaScript data assignment.\n  var data = {};\n  if (query) {\n    var parts = new $.Selector(decodeURIComponent(query));\n    try {\n      var value = (new $.Selector(parts)).toValue();\n    } catch (e) {\n      // Parts don't match a valid path.\n      $.system.log(String(e) + '\\n' + e.stack);\n      // TODO(fraser): Send an informative error message.\n      data = null;\n    }\n    if (data) {\n      // For simplicity, don't provide completions for primitives (despite\n      // the fact that (for example) numbers inherit a '.toFixed' function).\n      if (value && (typeof value === 'object' || typeof value === 'function')) {\n        data.properties = [];\n        while (value !== null && value !== undefined) {\n          var ownProps = Object.getOwnPropertyNames(value);\n          // Add typeof information.\n          for (var i = 0; i < ownProps.length; i++) {\n            var prop = ownProps[i];\n            var type = this.getType(value[prop]);\n            ownProps[i] = {name: prop, type: type};\n          }\n          data.properties.push(ownProps);\n          value = Object.getPrototypeOf(value);\n        }\n        data.keywords = ['{proto}', '{owner}'];\n        // Uncomment once Set, Map, WeakSet and WeakMap exist.\n        //if (value instanceOf Set || value instanceOf WeakSet) {\n        //  data.keywords.push('{keys}');\n        //}\n        //if (value instanceOf Map || value instanceOf WeakMap) {\n        //  data.keywords.push('{keys}', '{values}');\n        //}\n      }\n    }\n  } else {\n    data.roots = [];\n    // Add typeof information.\n    var global = $.utils.code.getGlobal();\n    for (var name in global) {\n      data.roots.push({name: name, type: this.getType(global[name])});\n    }\n  }\n  return data;\n};\nObject.setOwnerOf($.hosts.code['/objectPanel'].buildData, $.physicals.Neil);\nObject.setOwnerOf($.hosts.code['/objectPanel'].buildData.prototype, $.physicals.Neil);\n$.hosts.code['/editorXhr'] = {};\nObject.setOwnerOf($.hosts.code['/editorXhr'], $.physicals.Neil);\n$.hosts.code['/editorXhr'].www = function code_editorXhr_www(request, response) {\n  /* HTTP handler for /editorXhr\n   * Provide data for the IDE's editors.\n   * Takes several inputs:\n   * - selector: a selector to the origin object\n   * - key: a temporary key to the origin object\n   * - src: JavaScript source representation of new value,\n   *   implies request to save\n   * Writes JSON-encoded information about what is to be edited:\n   * - key: a temporary key to the origin object\n   * - src: JavaScript source representation of current value\n   * - butter: short status message to be displayed to user\n   * - saved: boolean indicating if a save was successful,\n   *   only present if save was requested\n   * - login: boolean indicating if the user is logged in\n   */\n  var data = {login: !!request.user};\n  try {  // ends with ... finally {response.write(JSON.stringify(data));}\n    if (!request.fromSameOrigin()) {\n      // Security check to ensure this is being loaded by the code editor.\n      data.butter = 'Cross-origin referer: ' + String(request.headers.referer);\n      return;\n    }\n    var selector;\n    try {\n      selector = new $.Selector(decodeURIComponent(request.parameters.selector));\n    } catch (e) {\n      data.butter = 'Invalid selector: ' + String(e);\n      return;\n    }\n\n    // Get Binding being edited.\n    var object;\n    var part = selector[selector.length - 1];\n    if (selector.isVar()) {\n      // Global variable; no parent object.\n      object = null;\n    } else if (request.parameters.key &&\n               (object = $.db.tempId.getObjById(request.parameters.key))) {\n      // Successfully retrieved parent object from tempID DB.\n    } else {\n      // Get parent object via selector.\n      var parent = new $.Selector(selector.slice(0, -1));\n      try {\n        // Get parent object and populate the reverse-lookup db.\n        object = parent.toValue(/*save:*/true);\n      } catch (e) {\n        data.butter = e.message;\n        return;\n      }\n      if (!$.utils.isObject(object)) {\n        data.butter = String(parent) + ' is not an object';\n        return;\n      }\n      // Save parent object in tempId DB; send key to client.\n      data.key = $.db.tempId.storeObj(object);\n    }\n    var binding = new $.utils.Binding(object, part);\n\n    // Save changes.\n    if (request.parameters.src) {\n      data.saved = false;\n      this.save(request.parameters.src, binding, data, request.user);\n    }\n\n    // Populate the new value object in the reverse-lookup db.\n    selector.toValue(/*save:*/true);\n\n    // Load revised source.\n    this.load(binding, data);\n  } finally {\n    suspend();\n    response.write(JSON.stringify(data));\n  }\n};\nObject.setOwnerOf($.hosts.code['/editorXhr'].www, $.physicals.Maximilian);\n$.hosts.code['/editorXhr'].load = function load(binding, data) {\n  /* The complement of save: render the current value of binding as a\n   * string, prefixed with metadata, postfixed with type information.\n   *\n   * This should set data.src to a string which, when passed eval, will be (in\n   * order of preference):\n   *\n   * - Identical to (as determined by Object.is) the current value,\n   * - A shallow-copy of the current value, or\n   * - Unparsable, such that eval will throw SyntaxError.\n   *\n   * The intention should be that it should be safe to save witout\n   * having made any changes and be reasonably confident nothing will\n   * break.\n   *\n   * Args:\n   * - binding: $.utils.Binding - the binding being edited.\n   * - data: {src: string, butter: string} - the data object to be returned\n   *   to the client.\n   */\n  var value = binding.get(/*inherited:*/true);\n  var inherited = !binding.exists();\n  try {\n    var source = this.sourceFor(value);\n    data.src = this.generateMetaData(value, source, inherited) + source;\n  } catch (e) {\n    suspend();\n    // TODO(cpcallen): Send a more informative error message.\n    data.butter = String(e);\n    throw e;\n  }\n};\nObject.setOwnerOf($.hosts.code['/editorXhr'].load, $.physicals.Maximilian);\n$.hosts.code['/editorXhr'].save = function $_www_code_editor_save(src, binding, data, user) {\n  // Save changes by evalling src, doing post-processing as directed\n  // by metadata, and then calling binding.set(/* new value */).\n  // Sets data.saved and data.butter as appropriate to give feedback\n  // to user.\n  if (!user) {\n    data.butter = 'User not logged in.';\n    return;\n  }\n  setPerms(user);\n  var saveValue;\n  try {\n    suspend();\n    var expr = $.utils.code.rewriteForEval(src, /*forceExpression:*/true);\n    // Evaluate src in global scope (eval by any other name, literally).\n    var evalGlobal = eval;\n    saveValue = evalGlobal(expr);\n  } catch (e) {\n    // TODO(fraser): Send a more informative error message.\n    data.butter = String(e);\n    return;\n  }\n  var oldValue = binding.get(/*inherited:*/false);  // Get actual current value.\n  try {\n    this.handleMetaData(src, oldValue, saveValue);\n  } catch (e) {\n    if (typeof e === 'string') {\n      // A thrown string should just be printed to the user.\n      data.butter = e;\n      return;\n    } else {\n      throw e;  // Rethrow real errors.\n    }\n  }\n  // Record last modification data on functions.\n  if (typeof saveValue === 'function') {\n    saveValue.lastModifiedTime = Date.now();\n    saveValue.lastModifiedUser = user;\n  }\n  try {\n    binding.set(saveValue);\n  } catch (e) {\n    data.butter = String(e);\n    return;\n  }\n  data.saved = true;\n  if (binding.isProto()) {\n    data.butter = 'Prototype Set';\n  } else if (binding.isOwner()) {\n    data.butter = 'Owner Set';\n  } else {\n    data.butter = 'Saved';\n  }\n};\nObject.setOwnerOf($.hosts.code['/editorXhr'].save, $.physicals.Neil);\n$.hosts.code['/editorXhr'].handleMetaData = function handleMetaData(src, oldValue, newValue) {\n  // Parse metadata directives from src and apply to newValue.\n  //\n  // The $.hosts.code['/editor'].www sends values to be edited to the\n  // editor front-end encoded as JavaScript expressions, optionally preceded\n  // by comments containing metadata about the value.  The editor can\n  // in turn return metadata directives which will be carried out by\n  // this function.\n  //\n  // Supported directives (order matters for now):\n  // // @copy_properties true\n  //    - Copy (most) properties from oldValue to newValue, if both\n  //      are objects.\n  // // @hash 26076758802\n  //    - Warn if old value doesn't hash to this value (conflicting\n  //      change happened between load and save).\n  // // @delete_prop <name>\n  //    - Delete the named property from newValue.\n  // // @set_prop <name> <value>\n  //    - Set the named property of newValue to the specified value.\n  //\n  // Throws user-printed strings (not Errors) if unable to complete.\n  var m = src.match(/^(?:[ \\t]*(?:\\/\\/[^\\n]*)?\\n)+/);\n  if (!m) {\n    return;\n  }\n  var metaLines = m[0].split('\\n');\n  for (var i = 0; i < metaLines.length; i++) {\n    var meta = metaLines[i];\n    if (meta.match(/^\\s*\\/\\/\\s*@copy_properties\\s+true\\s*$/)) {\n      // @copy_properties true\n      if (!$.utils.isObject(newValue)) {\n        throw \"Can't copy properties onto primitive: \" + newValue;\n      }\n      // Silently ignore if the old value is a primitive.\n      if ($.utils.isObject(oldValue)) {\n        $.utils.object.transplantProperties(oldValue, newValue);\n      }\n    } else if ((m = meta.match(/^\\s*\\/\\/\\s*@hash\\s+(\\S+)\\s*$/))) {\n      // @hash 26076758802\n      var oldSource = this.sourceFor(oldValue);\n      var hash = $.utils.string.hash('md5', oldSource);\n      if (String(hash) !== m[1]) {\n        // The current value does not match the value when the editor was loaded.\n        // This means the value changed out from under the editor.\n        throw 'Collision: Out of date editor.';\n      }\n    } else if ((m = meta.match(/^\\s*\\/\\/\\s*@delete_prop\\s+(\\S+)\\s*$/))) {\n      // @delete_prop dobj\n      try {\n        delete newValue[m[1]];\n      } catch (e) {\n        throw \"Can't delete '\" + m[1] + \"' property.\";\n      }\n    } else if ((m = meta.match(/^\\s*\\/\\/\\s*@set_prop\\s+(\\S+)\\s*=(.+)$/))) {\n      // @set_prop dobj = \"this\"\n      try {\n        var propValue = JSON.parse(m[2]);\n      } catch (e) {\n        throw \"Can't parse '\" + m[1] + \"' value: \" + m[2];\n      }\n      try {\n        newValue[m[1]] = propValue;\n      } catch (e) {\n        throw \"Can't set '\" + m[1] + \"' property.\";\n      }\n    }\n  }\n};\nObject.setOwnerOf($.hosts.code['/editorXhr'].handleMetaData, $.physicals.Maximilian);\n$.hosts.code['/editorXhr'].generateMetaData = function generateMetaData(value, src, inherited) {\n  /* Assemble any meta-data for the editor.\n   *\n   * Arguments:\n   * value: any - the value which will be provided as the initial value to begin\n   *     editing from.  This might be a value inherited from a prototype, if the\n   *     binding being edited does not yet exist.\n   * inherited: boolean - should be set to true iff value is inherited from a\n   *     prototype, such that saving will create a new property binding\n   *     overriding the interhited value, rather than replacing an existing\n   *     value.\n   *\n   * Returns: string - metadata informing $.hosts.code['/editorXhr'].save\n   *     what to do after creating the new value from the edited description.\n   *     At present, metadata is only generated if it is a function.\n   */\n  var meta = '';\n  if ($.utils.isObject(value)) {\n    // TODO: add @copy_properties here, but not if the source code is a selector?\n  }\n  if (typeof value === 'function') {\n    if (value.lastModifiedTime) {\n      var date = new Date(value.lastModifiedTime);\n      meta += '// @last_modified_time ' + date.toString() + '\\n';\n    }\n    if (value.lastModifiedUser) {\n      meta += '// @last_modified_user ' + String(value.lastModifiedUser) + '\\n';\n    }\n    meta += '// @copy_properties ' + !inherited + '\\n';\n    var props = ['verb', 'dobj', 'prep', 'iobj'];\n    for (var i = 0, prop; (prop = props[i]); i++) {\n      try {\n        meta += '// ' + (value[prop] ? '@set_prop ' + prop + ' = ' +\n            JSON.stringify(value[prop]) : '@delete_prop ' + prop) + '\\n';\n      } catch (e) {\n        // Unstringable value, or read perms error.  Skip.\n      }\n    }\n    if (inherited) src = 'undefined';  // What source of oldValue will be.\n    var hash = $.utils.string.hash('md5', src);\n    meta += '// @hash ' + hash + '\\n';\n  }\n  return meta;\n};\nObject.setOwnerOf($.hosts.code['/editorXhr'].generateMetaData, $.physicals.Maximilian);\n$.hosts.code['/editorXhr'].sourceFor = function sourceFor(value) {\n  /* Generate source code for a given value.\n   *\n   * Arguments:\n   * - value: any - any JavaScript value.\n   * Returns: string - source code for value.\n   */\n  switch (typeof value) {\n    // Special-case the most common cases for efficiency and to reduce\n    // chance of editor breaking due to bugs in $.utils.code.\n    //\n    // TODO: consider removing special case for strings once editor frontends\n    // cope with single-quoted strings.\n    case 'function': return Function.prototype.toString.call(value);\n    case 'string': return JSON.stringify(value);\n    case 'undefined': return 'undefined';\n    default:\n      // TODO: allow user-specified options.  N.B.: careful when dealing with\n      //     editing sessions shared via MobWrite, to avoid @hash metatdata\n      //     failures.\n      // TODO: add selector to options, so as to avoid including a comment\n      //     about it in the output when it is as expected - but think through\n      //     implications for @hash checking carefully first!\n      return $.utils.code.expressionFor(value, this.sourceOptions);\n  }\n};\nObject.setOwnerOf($.hosts.code['/editorXhr'].sourceFor, $.physicals.Maximilian);\nObject.setOwnerOf($.hosts.code['/editorXhr'].sourceFor.prototype, $.physicals.Maximilian);\n$.hosts.code['/editorXhr'].sourceOptions = {};\nObject.setOwnerOf($.hosts.code['/editorXhr'].sourceOptions, $.physicals.Maximilian);\n$.hosts.code['/editorXhr'].sourceOptions.depth = 3;\n$.hosts.code['/editorXhr'].sourceOptions.abbreviateMethods = true;\n$.hosts.code['/svg'] = {};\nObject.setOwnerOf($.hosts.code['/svg'], $.physicals.Neil);\n$.hosts.code['/svg'].www = '<% var staticUrl = request.hostUrl(\\'static\\'); %>\\n<html>\\n  <head>\\n    <title>Code City SVG Editor</title>\\n    <script src=\"<%=staticUrl%>code/SVG-Edit/jquery.min.js\"></script>\\n    <script src=\"<%=staticUrl%>code/SVG-Edit/jquery-ui/jquery-ui-1.8.17.custom.min.js\"></script>\\n    <script src=\"<%=staticUrl%>code/svg.js\" type=\"module\"></script>\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>style/svg.css\">\\n    <link rel=\"stylesheet\" href=\"<%=staticUrl%>code/svg.css\">\\n  </head>\\n\\n  <body>\\n    <div id=\"toolbox\">\\n      <div id=\"toolboxColumn1\">\\n        <button id=\"mode-select\" onclick=\"svgEditor.canvas.setMode(\\'select\\')\" title=\"Select tool\">\\n          <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n            <path stroke=\"#fff\" fill=\"#000\" d=\"m7.382,2.469l0.075,17.0326l3.301,-2.626l2.626,5.628l4.201,-2.626l-3.301,-4.802l4.576,-0.375l-11.478,-12.230z\"/>\\n          </svg>\\n        </button>\\n        <button id=\"mode-pathedit\" onclick=\"svgEditor.canvas.setMode(\\'pathedit\\')\" title=\"Select tool\" style=\"display: none\">\\n          <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n            <circle stroke=\"#00f\" fill=\"#0ff\" r=\"3.879\" cy=\"5.3\" cx=\"8.7\" stroke-width=\"1.5\"/>\\n            <path d=\"m9.182,5.670.078,15.162l3.416,-2.338l2.717,5.009l4.347,-2.338l-3.416,-4.275l4.736,-0.334l-11.878,-10.887z\" fill=\"#000\" stroke=\"#fff\"/>\\n          </svg>\\n        </button>\\n        <button id=\"mode-fhpath\" onclick=\"svgEditor.canvas.setMode(\\'fhpath\\')\" title=\"Freehand tool\">\\n          <svg viewBox=\"0 0 48 52\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n            <defs>\\n              <linearGradient id=\"fhpathGrad\" x1=\"0.305\" y1=\"0.109\" x2=\"0.613\" y2=\"0.394\">\\n                <stop offset=\"0.0\" stop-color=\"#f9d225\" stop-opacity=\"1\"/>\\n                <stop offset=\"1.0\" stop-color=\"#bf5f00\" stop-opacity=\"1\"/>\\n              </linearGradient>\\n            </defs>\\n            <path d=\"M31.5,0 l-8.75,20.25 l0.75,24 l16.5,-16.5 l6,-12.5\" fill=\"url(#fhpathGrad)\" stroke=\"#000\" stroke-width=\"2\" fill-opacity=\"1\" stroke-opacity=\"1\"/>\\n            <path d=\"M39.5,28.5 c-2,-9.25 -10.25,-11.75 -17,-7.438 l0.484,24.441z\" fill=\"#fce0a9\" stroke=\"#000\" stroke-width=\"2\" fill-opacity=\"1\" stroke-opacity=\"1\"/>\\n            <path d=\"M26.932,41.174 c-0.449,-2.351 -2.302,-2.987 -3.818,-1.890 l0.109,6.213z\" fill=\"#000\" stroke=\"#000\" stroke-width=\"2\" fill-opacity=\"1\" stroke-opacity=\"1\"/>\\n            <path d=\"M2.313,4.620 c12.500,-1.689 10.473,7.094 0,21.622 c22.973,-4.054 12.162,5.405 12.162,13.176 c-0.338,4.054 8.784,21.959 26.014,-1.351\" fill=\"none\" stroke=\"#000\" stroke-width=\"2\" fill-opacity=\"1\" stroke-opacity=\"1\"/>\\n          </svg>\\n        </button>\\n        <button id=\"mode-line\" onclick=\"svgEditor.canvas.setMode(\\'line\\')\" title=\"Line tool\">\\n          <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n            <defs>\\n              <linearGradient id=\"lineGrad1\" x1=\"0.184\" y1=\"0.262\" x2=\"0.777\" y2=\"0.566\">\\n                <stop offset=\"0\" stop-color=\"#fff\" stop-opacity=\"1\"/>\\n                <stop offset=\"1\" stop-color=\"#fce564\" stop-opacity=\"1\"/>\\n              </linearGradient>\\n              <linearGradient id=\"lineGrad2\" x1=\"0.465\" y1=\"0.156\" x2=\"0.938\" y2=\"0.394\">\\n                <stop offset=\"0\" stop-color=\"#f2feff\" stop-opacity=\"1\"/>\\n                <stop offset=\"1\" stop-color=\"#14609b\" stop-opacity=\"1\"/>\\n              </linearGradient>\\n            </defs>\\n            <line x1=\"0.998\" y1=\"1.491\" x2=\"12.977\" y2=\"21.141\" stroke=\"#000\" fill=\"none\"/>\\n            <path d=\"m14.053,13.687l-1.464,7.526l4.038,-6.326\" stroke=\"#000\" fill=\"#a0a0a0\"/>\\n            <path d=\"m13.612,10.266c-0.386,1.052 -0.607,2.403 -0.504,3.125l4.335,1.814c0.462,-0.308 1.613,-1.714 1.613,-2.520\" fill=\"url(#lineGrad1)\" stroke=\"#000\"/>\\n            <path d=\"m16.613,1.000l-3.673,8.602l7.103,3.473l3.178,-7.205\" fill=\"url(#lineGrad2)\" stroke=\"#000\"/>\\n          </svg>\\n        </button>\\n        <button id=\"mode-square\" onclick=\"svgEditor.canvas.setMode(\\'square\\')\" title=\"Square tool\">\\n          <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n            <defs>\\n              <linearGradient x1=\"0.363\" y1=\"0.102\" x2=\"1\" y2=\"1\" id=\"squareGrad\">\\n                <stop offset=\"0\" stop-color=\"#fff\" stop-opacity=\"1\"/>\\n                <stop offset=\"1\" stop-color=\"#3b7e9b\" stop-opacity=\"1\"/>\\n              </linearGradient>\\n            </defs>\\n            <rect x=\"1.5\" y=\"1.5\" width=\"20\" height=\"20\" fill=\"url(#squareGrad)\" stroke=\"#000\"/>\\n          </svg>\\n        </button>\\n        <button id=\"mode-rect\" onclick=\"svgEditor.canvas.setMode(\\'rect\\')\" title=\"Rectangle tool\">\\n          <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n            <defs>\\n              <linearGradient y2=\"1\" x2=\"1\" y1=\"0.102\" x1=\"0.363\" id=\"rectGrad\">\\n                <stop stop-opacity=\"1\" stop-color=\"#fff\" offset=\"0\"/>\\n                <stop stop-opacity=\"1\" stop-color=\"#3b7e9b\" offset=\"1\"/>\\n              </linearGradient>\\n            </defs>\\n            <rect transform=\"matrix(1, 0, 0, 1, 0, 0)\" stroke=\"#000\" fill=\"url(#rectGrad)\" height=\"12\" width=\"20\" y=\"5.5\" x=\"1.5\"/>\\n          </svg>\\n        </button>\\n        <button id=\"mode-circle\" onclick=\"svgEditor.canvas.setMode(\\'circle\\')\" title=\"Circle tool\">\\n          <svg viewBox=\"0 0 54 54\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n            <defs>\\n              <linearGradient y2=\"1.0\" x2=\"1.0\" y1=\"0.188\" x1=\"0.172\" id=\"circleGrad\">\\n                <stop stop-opacity=\"1\" stop-color=\"#fff\" offset=\"0.0\"/>\\n                <stop stop-opacity=\"1\" stop-color=\"#f66\" offset=\"1.0\"/>\\n              </linearGradient>\\n            </defs>\\n            <circle stroke-opacity=\"1\" fill-opacity=\"1\" stroke-width=\"2\" stroke=\"#000\" fill=\"url(#circleGrad)\" r=\"23\" cy=\"27\" cx=\"27\"/>\\n          </svg>\\n        </button>\\n        <button id=\"mode-ellipse\" onclick=\"svgEditor.canvas.setMode(\\'ellipse\\')\" title=\"Ellipse tool\">\\n          <svg viewBox=\"0 0 54 54\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n            <defs>\\n             <linearGradient y2=\"1.0\" x2=\"1.0\" y1=\"0.188\" x1=\"0.172\" id=\"ellipseGrad\">\\n               <stop stop-opacity=\"1\" stop-color=\"#fff\" offset=\"0.0\"/>\\n               <stop stop-opacity=\"1\" stop-color=\"#f66\" offset=\"1.0\"/>\\n              </linearGradient>\\n            </defs>\\n            <ellipse stroke-opacity=\"1\" fill-opacity=\"1\" stroke-width=\"2\" stroke=\"#000\" fill=\"url(#ellipseGrad)\" rx=\"23\" ry=\"15\" cy=\"27\" cx=\"27\"/>\\n          </svg>\\n        </button>\\n        <button id=\"mode-path\" onclick=\"svgEditor.canvas.setMode(\\'path\\')\" title=\"Path tool\">\\n          <svg viewBox=\"0 0 124 124\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n            <defs>\\n              <linearGradient y2=\"1\" x2=\"1\" y1=\"0.281\" x1=\"0.336\" id=\"pathGrad\">\\n                <stop stop-opacity=\"1\" stop-color=\"#fff\" offset=\"0\"/>\\n                <stop stop-opacity=\"1\" stop-color=\"#33a533\" offset=\"1\"/>\\n              </linearGradient>\\n            </defs>\\n            <path stroke-width=\"4\" stroke=\"#000\" fill=\"url(#pathGrad)\" d=\"m6,103l55,-87c85,33.64 -26,37.12 55,87l-110,0z\"/>\\n          </svg>\\n        </button>\\n      </div>\\n\\n      <div id=\"toolboxColumn2\">\\n        <div id=\"selected-actions\" style=\"display: none\">\\n          <button onclick=\"svgEditor.canvas.deleteSelectedElements()\" title=\"Delete selected\">\\n            <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <rect ry=\"3\" rx=\"3\" stroke=\"#800000\" fill=\"#a00\" height=\"20.295\" width=\"21.175\" y=\"1.703\" x=\"1.420\"/>\\n              <rect ry=\"3\" rx=\"3\" stroke=\"#f55\" fill=\"#a00\" height=\"18.630\" width=\"19.611\" y=\"2.536\" x=\"2.203\"/>\\n              <line stroke-width=\"2\" fill=\"none\" stroke=\"#fff\" y2=\"16.851\" x2=\"17.006\" y1=\"6.851\" x1=\"7.006\"/>\\n              <line stroke-width=\"2\" fill=\"none\" stroke=\"#fff\" y2=\"16.851\" x2=\"7.006\" y1=\"6.851\" x1=\"17.006\"/>\\n            </svg>\\n          </button>\\n        </div>\\n        <div id=\"selected-single-actions\" style=\"display: none\">\\n          <button onclick=\"svgEditor.canvas.moveToTopSelectedElement()\" title=\"Move to top\">\\n            <svg viewBox=\"0 0 23 23\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <defs>\\n                <linearGradient id=\"moveupGrad\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\">\\n                  <stop offset=\"0\" stop-color=\"#9fdcf4\" stop-opacity=\"1\"/>\\n                  <stop offset=\"1\" stop-color=\"#617e96\" stop-opacity=\"1\"/>\\n                </linearGradient>\\n              </defs>\\n              <line x1=\"1.3\" y1=\"8.199\" x2=\"12.8\" y2=\"8.199\" stroke=\"#000\" fill=\"none\" stroke-width=\"2\"/>\\n              <line x1=\"1.298\" y1=\"12.199\" x2=\"12.798\" y2=\"12.199\" stroke=\"#000\" fill=\"none\" stroke-width=\"2\"/>\\n              <line x1=\"1.299\" y1=\"16.199\" x2=\"12.799\" y2=\"16.199\" stroke=\"#000\" fill=\"none\" stroke-width=\"2\"/>\\n              <line x1=\"1.299\" y1=\"20.199\" x2=\"12.799\" y2=\"20.199\" stroke=\"#000\" fill=\"none\" stroke-width=\"2\"/>\\n              <rect x=\"1.55\" y=\"1.85\" width=\"20\" height=\"3.2\" fill=\"url(#moveupGrad)\" stroke=\"#000\"/>\\n              <path d=\"m16.835,21.146l2.332,0l0,-11.046l1.985,0l-3.151,-3.449l-3.151,3.449l1.985,0l0,11.046z\" fill=\"#000\" stroke=\"none\"/>\\n            </svg>\\n          </button>\\n          <button onclick=\"svgEditor.canvas.moveToBottomSelectedElement()\" title=\"Move to bottom\">\\n            <svg viewBox=\"0 0 23 23\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <defs>\\n                <linearGradient y2=\"0\" x2=\"1\" y1=\"0\" x1=\"0\" id=\"movedownGrad\">\\n                  <stop stop-opacity=\"1\" stop-color=\"#bc7f05\" offset=\"0\"/>\\n                  <stop stop-opacity=\"1\" stop-color=\"#fcfc9f\" offset=\"1\"/>\\n                </linearGradient>\\n              </defs>\\n              <line stroke-width=\"2\" fill=\"none\" stroke=\"#000\" y2=\"2.5\" x2=\"22\" y1=\"2.5\" x1=\"10.5\"/>\\n              <line stroke-width=\"2\" fill=\"none\" stroke=\"#000\" y2=\"6.5\" x2=\"21.998\" y1=\"6.5\" x1=\"10.498\"/>\\n              <line stroke-width=\"2\" fill=\"none\" stroke=\"#000\" y2=\"10.5\" x2=\"21.999\" y1=\"10.5\" x1=\"10.499\"/>\\n              <line stroke-width=\"2\" fill=\"none\" stroke=\"#000\" y2=\"14.5\" x2=\"21.999\" y1=\"14.5\" x1=\"10.499\"/>\\n              <rect stroke=\"#000\" fill=\"url(#movedownGrad)\" height=\"2.2\" width=\"20\" y=\"17.65\" x=\"1.65\"/>\\n              <path stroke=\"none\" fill=\"#000\" d=\"m4.25,1.55l2.35,0l0,11.05l2,0l-3.175,3.45l-3.175,-3.45l2,0l0,-11.05z\"/>\\n            </svg>\\n          </button>\\n          <button onclick=\"svgEditor.changeFill()\" title=\"Fill colour\">\\n            <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <rect height=\"24\" width=\"24\" y=\"0\" x=\"0\" id=\"fillRect\"/>\\n              <g id=\\'fillNone\\'>\\n                <line stroke=\"#d40000\" x1=\"0\" y1=\"0\" x2=\"24\" y2=\"24\"/>\\n                <line stroke=\"#d40000\" x1=\"24\" y1=\"0\" x2=\"0\" y2=\"24\"/>\\n              </g>\\n              <rect height=\"24\" width=\"24\" y=\"0\" x=\"0\" fill=\"none\" stroke=\"#000\" stroke-width=\"1\"/>\\n            </svg>\\n          </button>\\n          <button onclick=\"svgEditor.changeStroke()\" title=\"Line colour\">\\n            <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <rect height=\"20\" width=\"20\" y=\"2\" x=\"2\" id=\"strokeRect\"/>\\n            </svg>\\n          </button>\\n          <button onclick=\"svgEditor.canvas.convertToPath()\" title=\"Convert to path\" id=\"convertpath-action\">\\n            <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <defs>\\n                <linearGradient y2=\"0.469\" x2=\"0.430\" y1=\"0.102\" x1=\"0.105\" id=\"convertpathGrad\">\\n                  <stop stop-color=\"#f00\" offset=\"0\"/>\\n                  <stop stop-opacity=\"0\" stop-color=\"#f00\" offset=\"1\"/>\\n                </linearGradient>\\n              </defs>\\n              <circle cx=\"21\" cy=\"21.312\" r=\"18.445\" fill=\"url(#convertpathGrad)\" stroke=\"#000\"/>\\n              <path fill=\"none\" stroke=\"#000\" d=\"m2.875,21.312c-0.375,-9.25 7.75,-18.875 17.75,-18\"/>\\n              <line x1=\"25.375\" y1=\"3.062\" x2=\"8.5\" y2=\"3.062\" stroke=\"#808080\" fill=\"none\"/>\\n              <line x1=\"2.625\" y1=\"24.75\" x2=\"2.625\" y2=\"9.812\" stroke=\"#808080\" fill=\"none\"/>\\n              <circle cx=\"8.5\" cy=\"2.938\" r=\"1.953\" fill=\"#0ff\" stroke=\"#00f\" stroke-width=\"0.5\"/>\\n              <circle cx=\"2.625\" cy=\"9.812\" r=\"1.953\" fill=\"#0ff\" stroke=\"#00f\" stroke-width=\"0.5\"/>\\n              <circle cx=\"20.875\" cy=\"3.188\" r=\"2.5\" fill=\"#0ff\" stroke=\"#00f\"/>\\n              <circle cx=\"2.875\" cy=\"21.062\" r=\"2.5\" fill=\"#0ff\" stroke=\"#00f\"/>\\n            </svg>\\n          </button>\\n        </div>\\n        <div id=\"node-actions\" style=\"display: none\">\\n          <button onclick=\"svgEditor.canvas.pathActions.clonePathNode()\" title=\"Add node\">\\n            <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <path stroke-width=\"2\" d=\"m4.195,19.421c15.494,-15.533 -0.211,0.158 15.611,-15.579\" stroke=\"#8dd35f\" fill=\"none\"/>\\n              <circle stroke-width=\"0.5\" stroke=\"#00f\" fill=\"#0ff\" r=\"2.262\" cy=\"4\" cx=\"19.75\"/>\\n              <circle stroke-width=\"0.5\" stroke=\"#00f\" fill=\"#0ff\" r=\"2.262\" cy=\"19.403\" cx=\"4.065\"/>\\n              <circle stroke-width=\"0.5\" stroke=\"#00f\" fill=\"#0ff\" r=\"2.262\" cy=\"11.625\" cx=\"11.938\"/>\\n              <line stroke-linecap=\"round\" y2=\"14.466\" x2=\"9.666\" y1=\"4.022\" x1=\"9.782\" stroke-dasharray=\"null\" stroke-width=\"2\" stroke=\"#00f\" fill=\"#00f\"/>\\n              <line stroke-linecap=\"round\" y2=\"9.453\" x2=\"15.150\" y1=\"9.394\" x1=\"4.473\" stroke-dasharray=\"null\" stroke-width=\"2\" stroke=\"#00f\" fill=\"#00f\"/>\\n            </svg>\\n          </button>\\n          <button onclick=\"svgEditor.canvas.pathActions.deletePathNode()\" title=\"Delete node\">\\n            <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <path stroke-width=\"2\" d=\"m4.195,19.421c15.494,-15.533 -0.211,0.158 15.611,-15.579\" stroke=\"#8dd35f\" fill=\"none\"/>\\n              <circle stroke-width=\"0.5\" stroke=\"#00f\" fill=\"#0ff\" r=\"2.262\" cy=\"4\" cx=\"19.75\"/>\\n              <circle stroke-width=\"0.5\" stroke=\"#00f\" fill=\"#0ff\" r=\"2.262\" cy=\"19.403\" cx=\"4.065\"/>\\n              <circle stroke-width=\"0.5\" stroke=\"#00f\" fill=\"#0ff\" r=\"2.262\" cy=\"11.625\" cx=\"11.938\"/>\\n              <g transform=\"rotate(-45.29 9.81,9.24)\">\\n                <line stroke-linecap=\"round\" y2=\"9.453\" x2=\"15.150\" y1=\"9.394\" x1=\"4.473\" stroke-dasharray=\"null\" stroke-width=\"2\" stroke=\"#f00\" fill=\"none\"/>\\n                <line stroke-linecap=\"round\" y2=\"14.466\" x2=\"9.666\" y1=\"4.022\" x1=\"9.782\" stroke-dasharray=\"null\" stroke-width=\"2\" stroke=\"#f00\" fill=\"none\"/>\\n              </g>\\n            </svg>\\n          </button>\\n          <button onclick=\"svgEditor.canvas.pathActions.opencloseSubPath()\" id=\"open-action\" title=\"Open path\" style=\"display: none\">\\n            <svg viewBox=\"0 0 300 300\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <path stroke=\"#000\" stroke-width=\"15\" fill=\"#ffc8c8\" d=\"m123.5,38l-84,106l27,115l166,2l29,-111\"/>\\n              <line x1=\"276.5\" y1=\"153\" x2=\"108.5\" y2=\"24\" stroke=\"#000\" stroke-width=\"10\" fill=\"none\"/>\\n              <g stroke-width=\"15\" stroke=\"#00f\" fill=\"#0ff\">\\n                <circle r=\"30\" cy=\"41\" cx=\"123\"/>\\n                <circle r=\"30\" cy=\"146\" cx=\"40\"/>\\n                <circle r=\"30\" cy=\"260\" cx=\"69\"/>\\n                <circle r=\"30\" cy=\"260\" cx=\"228\"/>\\n                <circle r=\"30\" cy=\"148\" cx=\"260\"/>\\n              </g>\\n              <g stroke=\"#a00\" stroke-width=\"15\" fill=\"none\">\\n                <line x1=\"168\" y1=\"24\" x2=\"210\" y2=\"150\"/>\\n                <line x1=\"210\" y1=\"24\" x2=\"168\" y2=\"150\"/>\\n              </g>\\n            </svg>\\n          </button>\\n          <button onclick=\"svgEditor.canvas.pathActions.opencloseSubPath()\" id=\"close-action\" title=\"Close path\" style=\"display: none\">\\n            <svg viewBox=\"0 0 300 300\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\">\\n              <path stroke=\"#000\" stroke-width=\"15\" fill=\"#ffc8c8\" d=\"m121.5,40l-84,106l27,115l166,2l29,-111\"/>\\n              <line x1=\"240\" y1=\"136\" x2=\"169.5\" y2=\"74\" stroke=\"#a00\" stroke-width=\"25\" fill=\"none\"/>\\n              <path stroke=\"none\" fill=\"#a00\" d=\"m158,65l31,74l-3,-50l51,-3z\"/>\\n              <g stroke-width=\"15\" stroke=\"#00f\" fill=\"#0ff\">\\n                <circle r=\"30\" cy=\"41\" cx=\"123\"/>\\n                <circle r=\"30\" cy=\"146\" cx=\"40\"/>\\n                <circle r=\"30\" cy=\"260\" cx=\"69\"/>\\n                <circle r=\"30\" cy=\"260\" cx=\"228\"/>\\n                <circle r=\"30\" cy=\"148\" cx=\"260\"/>\\n              </g>\\n            </svg>\\n          </button>\\n        </div>\\n      </div>\\n    </div>\\n\\n    <div id=\"editorContainer\"></div>\\n\\n    <div id=\"menu\">\\n      <div id=\"menuCut\" class=\"menuitem\">Cut</div>\\n      <div id=\"menuCopy\" class=\"menuitem\">Copy</div>\\n      <div id=\"menuPaste\" class=\"menuitem\">Paste</div>\\n      <div class=\"menudiv\"></div>\\n      <div id=\"menuDelete\" class=\"menuitem\">Delete</div>\\n    </div>\\n  </body>\\n</html>\\n';\n$.hosts.code['/login'] = {};\nObject.setOwnerOf($.hosts.code['/login'], $.physicals.Neil);\n$.hosts.code['/login'].www = '<!doctype html>\\n<% var staticUrl = request.hostUrl(\\'static\\'); %>\\n<html lang=\"en\">\\n<head>\\n  <title>Code City Login</title>\\n  <style>\\n    body {\\n      font-family: \"Roboto Mono\", monospace;\\n      text-align: center;\\n    }\\n    h1 {\\n      font-size: 40pt;\\n      font-weight: 100;\\n    }\\n    h1>img {\\n      vertical-align: text-bottom;\\n    }\\n    #tagline {\\n      font-style: italic;\\n      margin: 2em;\\n    }\\n    iframe {\\n      height: 50px;\\n      width: 100px;\\n      border: none;\\n      display: block;\\n      margin: 0 auto;\\n    }\\n  </style>\\n  <link href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\" rel=\"stylesheet\">\\n  <link href=\"<%=staticUrl%>favicon.ico\" rel=\"shortcut icon\">\\n</head>\\n<body>\\n  <h1>\\n    <img src=\"<%=staticUrl%>logo.svg\" alt=\"\" width=\"95\" height=\"100\">\\n    Code City\\n  </h1>\\n  <p id=\"tagline\">Login required to edit code.</p>\\n  <iframe src=\"<%=request.hostUrl(\\'login\\')%>?after=<%=staticUrl%>login-close.html\"></iframe>\\n</body>\\n</html>';\n$.hosts.code['/mirror'] = $.hosts.root['/mirror'];\n$.hosts.code['/eval'] = {};\nObject.setOwnerOf($.hosts.code['/eval'], $.physicals.Neil);\n$.hosts.code['/eval'].www = \"<!doctype html>\\n<% var staticUrl = request.hostUrl('static'); %>\\n<html>\\n  <head>\\n    <title>Code City Eval</title>\\n    <style>\\nbody {\\n  font-family: \\\"Roboto Mono\\\", monospace;\\n  margin: 0;\\n}\\n#resultsPre {\\n  bottom: 4em;\\n  box-sizing: border-box;\\n  left: 0;\\n  overflow-y: scroll;\\n  padding-left: 1em;\\n  position: absolute;\\n  top: 2em;\\n  width: 100%;\\n}\\n      \\n#evalTextarea {\\n  color: #000;\\n  bottom: 0;\\n  box-sizing: border-box;\\n  background-color: #f8f8f8;\\n  font-size: 12pt;\\n  height: 42pt;\\n  margin-top: 2px;\\n  position: absolute;\\n  resize: none;\\n  width: 100%;\\n}\\n    </style>\\n    <link href=\\\"https://fonts.googleapis.com/css?family=Roboto+Mono\\\" rel=\\\"stylesheet\\\">\\n    <link href=\\\"<%=staticUrl%>favicon.ico\\\" rel=\\\"shortcut icon\\\">\\n    <script>\\nfunction init() {\\n  document.getElementById('evalTextarea').addEventListener('keydown', keydown, false);\\n}\\nwindow.addEventListener('load', init);\\n      \\nfunction keydown(e) {\\n  if (e.key !== 'Enter') {\\n    return;\\n  }\\n  var ta = document.getElementById('evalTextarea');\\n  var value = ta.value.trim();\\n  ta.value = '';\\n  ta.placeholder = '';\\n  e.preventDefault();\\n  if (value === '') {\\n    return;\\n  }\\n  addLine('> ' + value);\\n  send(value);\\n}\\n\\nfunction send(text) {\\n  var xhr = new XMLHttpRequest();   // new HttpRequest instance \\n  var theUrl = \\\"/json-handler\\\";\\n  xhr.open('POST', 'evalXhr');\\n  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\\n  xhr.onload = receive;\\n  xhr.send(text);\\n}\\n\\nfunction receive() {\\n  if (this.status !== 200) {\\n    addLine('HTTP Error: ' + this.status);\\n  } else {\\n    addLine(this.responseText);\\n  }\\n}\\n\\nfunction addLine(text) {\\n  var pre = document.getElementById('resultsPre');\\n  pre.textContent += '\\\\n' + text;\\n  pre.scrollTop = Number.MAX_SAFE_INTEGER;\\n}\\n    </script>\\n  \\n  </head>\\n  <body>\\n    <h4>Immediate Eval</h4>\\n    <pre id=\\\"resultsPre\\\"></pre>\\n    <textarea id=\\\"evalTextarea\\\" placeholder=\\\"1 + 2\\\" style=\\\"font-family: 'Roboto Mono', monospace;\\\"></textarea>\\n  </body>\\n</html>\";\n$.hosts.code['/evalXhr'] = {};\nObject.setOwnerOf($.hosts.code['/evalXhr'], $.physicals.Neil);\n$.hosts.code['/evalXhr'].www = function code_evalXhr_www(request, response) {\n  setPerms(request.user);\n  var output = '';\n  if (!request.fromSameOrigin()) {\n    // Security check to ensure this is being loaded by the eval editor.\n    output = 'Cross-origin referer: ' + String(request.headers.referer);\n  } else {\n    try {\n      var src = $.utils.code.rewriteForEval(request.data);\n      output = $.utils.code.eval(src);\n    } catch (e) {\n      suspend();\n      output = String(e);\n    }\n  }\n  response.write(output);\n};\nObject.setOwnerOf($.hosts.code['/evalXhr'].www, $.physicals.Maximilian);\nObject.setOwnerOf($.hosts.code['/evalXhr'].www.prototype, $.physicals.Neil);\n\n"
  },
  {
    "path": "core/core_28_$.servers.eval.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Eval server for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.servers.eval = {};\n$.servers.eval.connection = (new 'Object.create')($.connection);\n$.servers.eval.connection.onReceiveLine = function onReceiveLine(text) {\n  if (this !== $.servers.eval.connected) {\n    this.close();\n    return;\n  }\n  this.write('⇒ ' + $.utils.code.eval(text) + '\\n');\n  this.write('eval> ');\n};\nObject.setOwnerOf($.servers.eval.connection.onReceiveLine, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.eval.connection.onReceiveLine.prototype, $.physicals.Maximilian);\n$.servers.eval.connection.onConnect = function onConnect() {\n  $.connection.onConnect.apply(this, arguments);\n  if ($.servers.eval.connected) {\n    $.servers.eval.connected.close();\n  }\n  $.servers.eval.connected = this;\n  this.write('eval> ');\n};\nObject.setOwnerOf($.servers.eval.connection.onConnect, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.eval.connection.onConnect.prototype, $.physicals.Maximilian);\n$.servers.eval.connection.close = function close() {\n  this.write('This session has been terminated.\\n');\n  return $.connection.close.apply(this, arguments);\n};\nObject.setOwnerOf($.servers.eval.connection.close, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.eval.connection.close.prototype, $.physicals.Maximilian);\n$.servers.eval.connection.onEnd = function onEnd() {\n  $.servers.eval.connected = null;\n  return $.connection.onEnd.apply(this, arguments);\n};\nObject.setOwnerOf($.servers.eval.connection.onEnd, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.eval.connection.onEnd.prototype, $.physicals.Maximilian);\n$.servers.eval.connected = null;\n\n"
  },
  {
    "path": "core/core_30_$.utils.command.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Command parser for Code City\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.utils.command = {};\n$.utils.command.prepositions = (new 'Object.create')(null);\n$.utils.command.prepositions.with = 'with/using';\n$.utils.command.prepositions.using = 'with/using';\n$.utils.command.prepositions.at = 'at/to';\n$.utils.command.prepositions.to = 'at/to';\n$.utils.command.prepositions['in front of'] = 'in front of';\n$.utils.command.prepositions.in = 'in/inside/into';\n$.utils.command.prepositions.inside = 'in/inside/into';\n$.utils.command.prepositions.into = 'in/inside/into';\n$.utils.command.prepositions['on top of'] = 'on top of/on/onto/upon';\n$.utils.command.prepositions.on = 'on top of/on/onto/upon';\n$.utils.command.prepositions.onto = 'on top of/on/onto/upon';\n$.utils.command.prepositions.upon = 'on top of/on/onto/upon';\n$.utils.command.prepositions.over = 'over';\n$.utils.command.prepositions.through = 'through';\n$.utils.command.prepositions.under = 'under/underneath/beneath';\n$.utils.command.prepositions.underneath = 'under/underneath/beneath';\n$.utils.command.prepositions.beneath = 'under/underneath/beneath';\n$.utils.command.prepositions.behind = 'behind';\n$.utils.command.prepositions.beside = 'beside';\n$.utils.command.prepositions.for = 'for/about';\n$.utils.command.prepositions.about = 'for/about';\n$.utils.command.prepositions.is = 'is';\n$.utils.command.prepositions.as = 'as';\n$.utils.command.prepositions.off = 'off/off of';\n$.utils.command.prepositions['off of'] = 'off/off of';\n$.utils.command.prepositions['out of'] = 'out of/from inside/from';\n$.utils.command.prepositions['from inside'] = 'out of/from inside/from';\n$.utils.command.prepositions.from = 'out of/from inside/from';\n$.utils.command.prepositionsRegExp = /^(.*\\s)?(with|using|upon|underneath|under|to|through|over|out +of|onto|on +top +of|on|off +of|off|is|into|inside|in +front +of|in|from +inside|from|for|beside|beneath|behind|at|as|about)(\\s.*)?$/;\n$.utils.command.prepositionOptions = [];\n$.utils.command.prepositionOptions[0] = 'none';\n$.utils.command.prepositionOptions[1] = 'any';\n$.utils.command.prepositionOptions[2] = 'with/using';\n$.utils.command.prepositionOptions[3] = 'at/to';\n$.utils.command.prepositionOptions[4] = 'in front of';\n$.utils.command.prepositionOptions[5] = 'in/inside/into';\n$.utils.command.prepositionOptions[6] = 'on top of/on/onto/upon';\n$.utils.command.prepositionOptions[7] = 'out of/from inside/from';\n$.utils.command.prepositionOptions[8] = 'over';\n$.utils.command.prepositionOptions[9] = 'through';\n$.utils.command.prepositionOptions[10] = 'under/underneath/beneath';\n$.utils.command.prepositionOptions[11] = 'behind';\n$.utils.command.prepositionOptions[12] = 'beside';\n$.utils.command.prepositionOptions[13] = 'for/about';\n$.utils.command.prepositionOptions[14] = 'is';\n$.utils.command.prepositionOptions[15] = 'as';\n$.utils.command.prepositionOptions[16] = 'off/off of';\n$.utils.command.parse = function parse(cmdstr, user) {\n  // Parse a user's command into components.\n  //\n  // Commands are generally expected to be of the form:\n  //\n  // <verb> <direct object> <preposition> <indirect object>\n  //\n  // ... where all parts but <verb> are optional, but <preposition>\n  // required if <indirect object> is present.\n  //\n  // The parse will return an object with the following properties:\n  //\n  // user:    The $.user object, from the parameter of the same name.\n  // cmdstr:  The cmdstr parameter (coerced to string).\n  // verbstr: The first non-whitespace word of cmdstr (if any).\n  // argstr:  The rest of cmdstr, starting from the second character\n  //          after the verb.\n  // args:    An array of all the rest of the words of cmdstr.\n  // dobjstr: Sring of args up to the (first) preposition.\n  // dobj:    Object matching dobjstr.  If dobjstr is the empty string\n  //          then this will be null.  If no object matches, it will\n  //          be $.FAILED_MATCH.  If more than one object matches it\n  //          will be $.AMBIGUOUS_MATCH.\n  // prepstr: String of the (first) preposition, if any.\n  // iobjstr: String of args after the (first) preposition.\n  // iobj:    Object matching iobjstr.  Special values as for dobj.\n  //\n  // If cmdstr contains no non-whitespace characters, null is returned\n  // instead.\n  //\n  // The cmdstr, verbstr and argstr properties are \"raw\" strings,\n  // unmodified from the cmdstr parameter, while dobjstr, prepstr and\n  // iobjstr are normalised, being substrings of args.join(' ').\n\n  // Spit off verb from the rest.\n  cmdstr = String(cmdstr);\n  var m = cmdstr.match($.utils.command.verbRegExp);\n  if (!m) return null;\n  var verbstr = m[1];\n  var argstr = m[2] || '';\n  // Split argstr into words.\n  // TODO(cpcallen): support quoting.\n  var argstrTrimmed = argstr.trim();\n  var args = argstrTrimmed ? argstrTrimmed.split(/\\s+/) : [];\n  // Recombine args and split into dobjstr / prepstr / iobjstr\n  var argsNormalised = args.join(' ');\n  var dobjstr = '';\n  var prepstr = '';\n  var iobjstr = '';\n  m = argsNormalised.match($.utils.command.prepositionsRegExp);\n  if (m) {\n    // Preposition found.\n    dobjstr = (m[1] || '').trim();\n    prepstr = m[2].replace(/ +/g, ' ');\n    iobjstr = (m[3] || '').trim();\n  } else {\n    dobjstr = argsNormalised;\n  }\n  function match(str) {\n    if (str === '') return null;\n    if (str === 'me' || str === 'myself') return user;\n    if (str === 'here') return user.location;\n    return $.utils.command.match(str, user);\n  }\n  var dobj = match(dobjstr);\n  var iobj = match(iobjstr);\n  return {\n    user: user,\n    cmdstr: cmdstr,\n    verbstr: verbstr,\n    argstr: argstr,\n    args: args,\n    dobjstr: dobjstr,\n    dobj: dobj,\n    prepstr: prepstr,\n    iobjstr: iobjstr,\n    iobj: iobj\n  };\n};\nObject.setOwnerOf($.utils.command.parse, $.physicals.Maximilian);\n$.utils.command.execute = function execute(cmdstr, user) {\n  /* Parse and execute a user's command.  Returns true if a\n   * verb-function was invoked; narrates an error message and\n   * false otherwise.\n   */\n  var cmd = $.utils.command.parse(cmdstr, user);\n  if (!cmd) return false;\n  // Collect all objects which could host the verb.\n  var hosts = [user, user.location, cmd.dobj, cmd.iobj];\n  for (var i = 0; i < hosts.length; i++) {\n    var host = hosts[i];\n    if (!host) {\n      continue;\n    }\n    // Check every verb on each object for a match.\n    for (var prop in host) {\n      var func = host[prop];\n      if (typeof func !== 'function') continue;  // Not a function.\n      var verbSpec = func.verb;\n      var dobjSpec = func.dobj;\n      var prepSpec = func.prep;\n      var iobjSpec = func.iobj;  // I can't wait for ES6.\n      if (!verbSpec || !dobjSpec || !prepSpec || !iobjSpec) continue;  // Not a verb.\n      var verbRegExp = new RegExp('^(?:' + verbSpec + ')$');\n      if (verbRegExp.test(cmd.verbstr) &&\n          (prepSpec === 'any' ||\n           $.utils.command.prepositions[cmd.prepstr] === prepSpec ||\n           (prepSpec == 'none' && !cmd.prepstr)) &&\n          (dobjSpec === 'any' || (dobjSpec === 'this' && cmd.dobj === host) ||\n           (dobjSpec === 'none' && !cmd.dobj)) &&\n          (iobjSpec === 'any' || (iobjSpec === 'this' && cmd.iobj === host) ||\n           (iobjSpec === 'none' && !cmd.iobj))) {\n        // TODO: security check/perms.\n        host[prop](cmd);\n        return true;\n      }\n    }\n  }\n  cmd.user.narrate('I don\\'t understand that.');\n  return false;\n};\nObject.setOwnerOf($.utils.command.execute, $.physicals.Maximilian);\n$.utils.command.verbRegExp = /^\\s*(\\S+)(?:\\s(.*))?/;\n$.utils.command.match = function match(str, context) {\n  /* Attempt to find an object matching str amongst context,\n   * context.location, and context.contents.\n   *\n   * Args:\n   * - str: string: prefix of name or alias of desired object.\n   * - context: $.physical: an object to search.\n   *\n   * Returns: an object matching str, or $.FAILED_MATCH if none or\n   * $.AMBIGUOUS_MATCH if more than one.\n   */\n  str = str.trim();\n  // First, check for matches against universally accessible things.\n  try {\n    var v = $(str);\n    if ($.utils.isObject(v)) return v;\n  } catch (e) {\n    // Ignore failed Selector parse/lookup.\n  }\n  var objects = [context].concat(context.getContents());\n  if (context.location) {\n    objects = objects.concat([context.location], context.location.getContents());\n  }\n  var m = $.utils.command.matchObjects(str, objects);\n  switch (m.length) {\n    case 0:\n      return $.FAILED_MATCH;\n    case 1:\n      return m[0];\n    default:\n      return $.AMBIGUOUS_MATCH;\n  }\n};\nObject.setOwnerOf($.utils.command.match, $.physicals.Maximilian);\n$.utils.command.matchFailed = function matchFailed(obj, objstr, user) {\n  /* Return true iff obj is NOT a valid match, and optionally narrate\n   * a suitable error message if not.\n   *\n   * If obj is null, $.FAILED_MATCH or $.AMBIGUOUS_MATCH (and objstr\n   * and user are supplied) call user.narrate with a suitable error\n   * message.\n   *\n   * Args:\n   * - obj: $.physical | null | $.FAILED_MATCH | $.AMBIGUOUS_MATCH:\n   *     A match value (e.g., cmd.dobj or cmd.iobj) to be checked.\n   * - objstr: string:\n   *     The string which was matched to get obj.\n   * - user: $.user:\n   *     The user who typed the command.\n   * Returns: boolean: true if obj is a $.physical.\n   */\n  var send = (typeof objstr === 'string' && $.user.isPrototypeOf(user));\n  if (obj === null) {\n    if (send) user.narrate('You must give the name of some object.');\n    return true;\n  } else if (obj === $.FAILED_MATCH) {\n    if (send) user.narrate('I see no \"' + objstr + '\" here.');\n    return true;\n  } else if (obj === $.AMBIGUOUS_MATCH) {\n    if (send) user.narrate('I don\\'t know which \"' + objstr + '\" you mean.');\n    return true;\n  } else if ($.physical.isPrototypeOf(obj)) {\n    return false;\n  } else {\n    throw new TypeError('unexpected value checking match result');\n  }\n};\nObject.setOwnerOf($.utils.command.matchFailed, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.command.matchFailed.prototype, $.physicals.Maximilian);\n$.utils.command.matchObjects = function matchObjects(str, objects) {\n  /* Match a string against a list of objects.  Will return an array\n   * of zero or more objects such that (in order of preference):\n   * - all have .name === str.\n   * - all have str in their .aliases.\n   * - all have str as a prefix of their name or an alias.\n   *\n   * Duplicate entries in objects will be ignored; only a single copy\n   * will appear in the returned array.\n   *\n   * Args:\n   * str: string to match against names and aliases of objects.\n   * objects: array of $.physical objects to consider.\n   *\n   * Returns: possibly-empty array of objects matching str.\n   *\n   */\n  var nameMatches = [];  // These should be Sets.\n  var aliasMatches = [];\n  var partialMatches = [];\n  var nonMatches = [];  // Non-matches will be ignored.\n  var matches = [nonMatches, partialMatches, aliasMatches, nameMatches];\n\n  for (var i = 0; i < objects.length; i++) {\n    var obj = objects[i];\n    var strength = $.utils.command.matchObjects.strength(str, obj);\n    if (!matches[strength].includes(obj)) {\n      matches[strength].push(obj);\n    }\n  }\n\n  // Return the highest level bin.\n  if (nameMatches.length) return nameMatches;\n  if (aliasMatches.length) return aliasMatches;\n  if (partialMatches.length) return partialMatches;\n  return [];\n};\nObject.setOwnerOf($.utils.command.matchObjects, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.command.matchObjects.prototype, $.physicals.Maximilian);\n$.utils.command.matchObjects.strength = function strength(str, obj) {\n  /* Score str as a match for obj.\n   * Returns: number\n   * - 0: No match.\n   * - 1: Partial name or alias.\n   * - 2: Perfect alias match.\n   * - 3: Perfect name match.\n   */\n  if (!str || !obj) {\n    return 0;\n  }\n  str = str.toLowerCase();\n  var name = obj.name.toLowerCase();\n  if (name === str) {\n    return 3;\n  }\n  var partial = name.startsWith(str);\n  if (Array.isArray(obj.aliases)) {\n    for (var i = 0; i < obj.aliases.length; i++) {\n      var alias = obj.aliases[i].toLowerCase();\n      if (name === alias) {\n        return 2;\n      }\n      partial = partial || alias.startsWith(str);\n    }\n  }\n  return partial ? 1 : 0;\n};\nObject.setOwnerOf($.utils.command.matchObjects.strength, $.physicals.Maximilian);\n\n"
  },
  {
    "path": "core/core_31_$.utils_world.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview World-related utils for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.utils.commandMenu = function commandMenu(commands) {\n  var cmdXml = '';\n  if (commands.length) {\n    cmdXml += '<cmds>';\n    for (var i = 0; i < commands.length; i++) {\n      cmdXml += '<cmd>' + $.utils.html.escape(commands[i]) + '</cmd>';\n    }\n    cmdXml += '</cmds>';\n  }\n  return cmdXml;\n};\nObject.setOwnerOf($.utils.commandMenu, $.physicals.Maximilian);\n\n$.utils.replacePhysicalsWithName = function replacePhysicalsWithName(value) {\n  /* Deeply clone JSON object.\n   * Replace all instances of $.physical with the object's name.\n   */\n  if (Array.isArray(value)) {\n    var newArray = [];\n    for (var i = 0; i < value.length; i++) {\n      newArray[i] = replacePhysicalsWithName(value[i]);\n    }\n    return newArray;\n  }\n  if ($.physical.isPrototypeOf(value)) {\n    return value.name;\n  }\n  if (typeof value === 'object' && value !== null) {\n    var newObject = {};\n    for (var prop in value) {\n      newObject[prop] = replacePhysicalsWithName(value[prop]);\n    }\n    return newObject;\n  }\n  return value;\n};\nObject.setOwnerOf($.utils.replacePhysicalsWithName, $.physicals.Maximilian);\n\n"
  },
  {
    "path": "core/core_32_physical.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Physical object prototype for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.physical = {};\n$.physical.name = 'Physical object prototype';\n$.physical.description = '';\n$.physical.svgText = '';\n$.physical.location = null;\n$.physical.contents_ = null;\n$.physical.getContents = function getContents() {\n  $.physical.validate.call(this);\n  return this.contents_.slice();\n};\nObject.setOwnerOf($.physical.getContents, $.physicals.Maximilian);\nObject.setOwnerOf($.physical.getContents.prototype, $.physicals.Maximilian);\n$.physical.addContents = function addContents(newThing, opt_neighbour) {\n  // Add newThing to this's contents.  It will be added after\n  // opt_neighbour, or to the end of list if opt_neighbour not given.\n  // An item already in the contents list will be moved to the\n  // specified position.\n  $.physical.validate.call(this);\n  if (!$.physical.isPrototypeOf(newThing)) {\n    throw new TypeError('cannot add non-$.physical to contents');\n  } else if(newThing.location !== this) {\n    throw new RangeError('object to be added to contents must have .location set first');\n  }\n  for (var loc = this; loc; loc = loc.location) {\n    if (loc === newThing) {\n      throw new RangeError('object cannot contain itself');\n    }\n  }\n  var contents = this.contents_;\n  var index = contents.indexOf(newThing);\n  if (index !== -1) {\n    // Remove existing thing.\n    contents.splice(index, 1);\n  }\n  if (opt_neighbour) {\n    for (var i = 0, thing; (thing = contents[i]); i++) {\n      if (thing === opt_neighbour) {\n        contents.splice(i + 1, 0, newThing);\n        return;\n      }\n    }\n    // Neighbour not found, just append.\n  }\n  // Common case of appending a thing.\n  contents.push(newThing);\n};\nObject.setOwnerOf($.physical.addContents, $.physicals.Maximilian);\n$.physical.removeContents = function removeContents(thing) {\n  var contents = this.contents_;\n  var index = contents.indexOf(thing);\n  if (index !== -1) {\n    contents.splice(index, 1);\n  }\n  this.contents_ = contents;\n};\nObject.setOwnerOf($.physical.removeContents, $.physicals.Neil);\n$.physical.moveTo = function moveTo(dest, opt_neighbour) {\n  /* Move his object to the specified destination location.\n   * Attempt to position this object next to a specified neighbour, if given.\n   */\n  $.physical.validate.call(this);\n  if (!$.physical.isPrototypeOf(dest) && dest !== null) {\n    throw new Error('destination must be a $.physical or null');\n  }\n  var src = this.location;\n  if (src === dest) return;  // Nothing to do.\n  // Preliminary check for recursive move.  This is formally enforced by\n  // $.physical.addContents(), but we bail here if it is likely to fail later.\n  for (var loc = dest; loc; loc = loc.location) {\n    if (loc === this) {\n      throw new RangeError('cannot move an object inside itself');\n    }\n  }\n  // Call this.willMoveTo(dest), and refuse move unless it returns true without suspending.\n  var willMove = false;\n  new Thread(function checkWillMoveTo() {\n    willMove = Boolean(this.willMoveTo(dest));\n  }, 0, this);\n  suspend(0);\n  if (!willMove) {\n    throw new PermissionError(String(this) + \" isn't movable to \" + String(dest));\n  }\n  // Call dest.accept(this), and refuse move unless it returns true without suspending.\n  var accept = false;\n  new Thread(function checkAccept() {\n    accept = (dest === null || Boolean(dest.accept(this)));\n  }, 0, this);\n  suspend(0);\n  if (!accept) {\n    throw new PermissionError(String(dest) + \" doesn't accept \" + String(this));\n  }\n  // Call src.onExit(this, dest).\n  new Thread(function callOnExit() {\n    if (src) src.onExit(this, dest);\n  }, 0, this);\n  suspend(0);\n  // Perform move.\n  if (src && src.removeContents) src.removeContents(this);\n  this.location = dest;\n  if (dest) {\n    try {\n      dest.addContents(this, opt_neighbour);\n    } finally {\n      if (!dest.contents_.includes(this)) {\n        this.location = null;  // Uh oh.\n        dest = null;\n      }\n    }\n  }\n  // Call dest.onEnter(this, src).\n  new Thread(function callOnEnter() {\n    if (dest) dest.onEnter(this, src);\n  }, 0, this);\n  suspend(0);\n};\nObject.setOwnerOf($.physical.moveTo, $.physicals.Maximilian);\n$.physical.look = function look(cmd) {\n  var html = $.jssp.eval(this, 'lookJssp', {user: cmd.user});\n  cmd.user.readMemo({type: \"html\", htmlText: html});\n};\nObject.setOwnerOf($.physical.look, $.physicals.Neil);\n$.physical.look.verb = 'l(ook)?';\n$.physical.look.dobj = 'this';\n$.physical.look.prep = 'none';\n$.physical.look.iobj = 'none';\n$.physical.lookJssp = \"<table style=\\\"height: 100%; width: 100%;\\\">\\n  <tr>\\n    <td style=\\\"padding: 1ex; width: 30%;\\\">\\n      <svg width=\\\"100%\\\" height=\\\"100%\\\" viewBox=\\\"0 0 0 0\\\">\\n        <%= $.utils.object.getValue(this, 'svgText') %>\\n      </svg>\\n    </td>\\n    <td>\\n    <h1><%: this %><%= $.utils.commandMenu(this.getCommands(request.user)) %></h1>\\n    <p><%= $.utils.html.preserveWhitespace($.utils.object.getValue(this, 'description')) %></p>\\n<%\\nvar contents = this.getContents();\\nif (contents.length) {\\n  var contentsHtml = [];\\n  for (var i = 0; i < contents.length; i++) {\\n    contentsHtml[i] = $.utils.html.escape(contents[i].name) +\\n        $.utils.commandMenu(contents[i].getCommands(request.user));\\n  }\\n  response.write('<p>Contents: ' + contentsHtml.join(', ') + '</p>');\\n}\\nif (this.location) {\\n  response.write('<p>Location: ' + $.utils.html.escape(this.location.name) +\\n      $.utils.commandMenu(this.location.getCommands(request.user)) + '</p>');\\n}\\n%>\\n    </td>\\n  </tr>\\n</table>\";\n$.physical.getCommands = function getCommands(who) {\n  return [\n    'look ' + this.name,\n    // 'examine ' + this.name,\n    'edit ' + this.name\n  ];\n};\nObject.setOwnerOf($.physical.getCommands, $.physicals.Neil);\n$.physical.validate = function validate() {\n  /* Validate this $.physical object to enforce that certain\n   * invariants are true.  Those invariants are:\n   * - this.location must be a $.physical or null.\n   * - this.contents_ must be an array unique to this (not inherited)\n   * - Each item in this.contents_ must be a $.physical and have\n   *   item.location === this.\n   */\n  // Recover this if it has inadvertently become $.garbage.\n  //\n  // TODO: ideally validatate is non-overridable, and everywhere that\n  // presently invokes $.physical.validate.call(x) can just do\n  // x.validate() instead, and this line can go away.\n  if ($.garbage.isPrototypeOf(this)) this.validate();\n  if (!$.physical.isPrototypeOf(this)) {\n    throw TypeError('$.physical.validate called on incompatible receiver');\n  }\n  // They can only be located in another $.physical object (or null)\n  // and that object must have this in its contents:\n  var loc = this.location;\n  if ($.garbage.isPrototypeOf(loc)) loc.validate();\n  if (!$.physical.isPrototypeOf(loc) ||\n      ($.utils.validate.ownArray(loc, 'contents_'),  // N.B.: comma operator\n       !loc.contents_.includes(this))) {\n    this.location = null;\n  }\n  // this.contents_ must be an array unique to this (not inherited):\n  $.utils.validate.ownArray(this, 'contents_');\n  // this.contents_ must not contain any duplicates, non-$.physical\n  // objects, objects not located in this:\n  for (var i = this.contents_.length - 1; i >= 0; i--) {\n    var item = this.contents_[i];\n    if ($.garbage.isPrototypeOf(item)) item.validate();\n    if (this.contents_.indexOf(item) !== i ||  // true for duplicates\n        !$.physical.isPrototypeOf(item) ||\n        item.location !== this) {\n      this.contents_.splice(i, 1);\n    }\n  }\n  // TODO: check for circular containment?\n};\nObject.setOwnerOf($.physical.validate, $.physicals.Maximilian);\n$.physical.toString = function toString() {\n  return this.name;\n};\nObject.setOwnerOf($.physical.toString.prototype, $.physicals.Maximilian);\n$.physical.accept = function accept(what, src) {\n  /* Returns true iff this is willing to accept what arriving from src.\n   *\n   * This function should only be called by $.physical.moveTo()\n   * immediately before actually performing a move.  It is OK if this\n   * function (or its overrides) has some kind of observable\n   * side-effect (making noise, causing some other action, etc.).\n   *\n   * Other code wanting to test if a move is likely to succeed should\n   * call .willAccept(what, src) instead.\n   *\n   * Throwing an error or suspending is equivalent to returning false.\n   */\n  return this.willAccept(what, src);\n};\nObject.setOwnerOf($.physical.accept, $.physicals.Maximilian);\n$.physical.willAccept = function willAccept(what, src) {\n  /* Returns true iff this is willing to accept what arriving from src.\n   *\n   * This function (or its overrides) MUST NOT have any kind of\n   * observable side-effect (making noise, causing some other action,\n   * etc.)\n   */\n  return false;\n};\nObject.setOwnerOf($.physical.willAccept, $.physicals.Maximilian);\nObject.setOwnerOf($.physical.willAccept.prototype, $.physicals.Maximilian);\n$.physical.onExit = function onExit(what, dest) {\n  /* Called by $.physical.moveTo just before what leaves for dest.\n   */\n};\nObject.setOwnerOf($.physical.onExit, $.physicals.Maximilian);\n$.physical.onEnter = function onEnter(what, src) {\n  /* Called by $.physical.moveTo just after what arrives from src.\n   */\n};\nObject.setOwnerOf($.physical.onEnter, $.physicals.Maximilian);\n$.physical.lookAt = function lookAt(cmd) {\n  this.look(cmd);\n};\nObject.setOwnerOf($.physical.lookAt, $.physicals.Maximilian);\n$.physical.lookAt.verb = 'l(ook)?';\n$.physical.lookAt.dobj = 'none';\n$.physical.lookAt.prep = 'at/to';\n$.physical.lookAt.iobj = 'this';\n$.physical.kick = function kick(cmd) {\n  cmd.user.narrate('You kick ' + String(this) + '.');\n  if (cmd.user.location) {\n    cmd.user.location.narrate(String(cmd.user) + ' kicks ' + String(this) + '.', cmd.user);\n  }\n  this.validate();\n};\n$.physical.kick.verb = 'kick';\n$.physical.kick.dobj = 'this';\n$.physical.kick.prep = 'none';\n$.physical.kick.iobj = 'none';\n$.physical.readMemo = function readMemo(memo) {\n  /* Deliver a memo to this object.\n   *\n   * A memo is an object that encodes a message about something that\n   * can be seen or has just happened nearby.  Most usually they are\n   * sent to the user's client (after being converted to JSON), but in\n   * principle any $.physical object can receve a memo and potentially\n   * react to it.\n   *\n   * Some example memos:\n   *\n   * A scene (simlified):\n   * {type: 'scene', user: <the user>, where: <a room>,\n   *  svgText: '<background image for room>',\n   *  contents: [\n   *    {type: 'user', what: <the user>, svgText: '<image of user>' },\n   *    {type: 'thing', what: <a thing>, svgText: '<image of thing>'}\n   *  ]}\n   *\n   * A narration:\n   * {type: 'narrate', text: \"A door appears!\"}\n   *\n   * Someone says something:\n   * {type: 'say', source: <a user>, where: <a room>, text: 'Hi.'}\n   *\n   * If you want to make an object react to memos (e.g., by responding\n   * to things said to it), it is better to create an .onMemo method\n   * rather than overriding .readMemo.\n   */\n  if (this.onMemo) {\n    new Thread(function readMemoDispatcher() {\n      try {\n        this.onMemo(memo);\n      } catch (e) {\n        suspend();\n        if ($.room.isPrototypeOf(this.location)) {\n          this.location.narrate(String(e) + '\\n' + e.stack, undefined, this);\n        } else {\n          throw e;\n        }\n      }\n    }, 0, this);\n  }\n};\nObject.setOwnerOf($.physical.readMemo, $.physicals.Maximilian);\n$.physical.setName = function setName(name, tryAlternative) {\n  /* Set the .name of this physical object.  If the desired name is\n   * already in use and tryAlternative is true a similar name (like\n   * \"foo #2\" or \"foo #3\") will be used instead; otherwise RangeError\n   * will be thrown.\n   *\n   * name: string: the desired new name.\n   * tryAlternative: boolean: try to find an alternative name.\n   *\n   * Returns the object's new name.\n   */\n  if (!$.physical.isPrototypeOf(this)) {\n    throw new TypeError('must be called on a $.physical');\n  } else if (typeof name !== 'string' || name.length < 1) {\n    throw new TypeError('new name must be a non-empty string');\n  }\n\n  function check(name) {\n    if (!(name in $.physicals)) return true;  // Name not in use.\n    var oldObj = $.physicals[name];\n    if (!$.physical.isPrototypeOf(oldObj) && $.physical !== oldObj) {\n      delete $.physicals[name];\n      return true;  // Name was in use but holder no longer a $.physical\n    }\n    return $.physicals[name] === this;  // Name in use, but maybe it's us?\n  }\n\n  if (!check.call(this, name)) {  // Desired name in use.\n    if (!tryAlternative) throw new RangeError('there is already another object named ' + name);\n\n    for (var i = 2; i < Object.getOwnPropertyNames($.physicals).length + 2; i++) {\n      var proposed = name + ' #' + i;\n      if (check.call(this, proposed)) {\n        name = proposed;\n        break;\n      }\n    }\n  }\n  // New name is not in use, or already ours.\n  if (name !== this.name) {\n    if (this.name in $.physicals && $.physicals[this.name] === this) {\n      delete $.physicals[this.name];\n    }\n  }\n  this.name = name;\n  $.physicals[name] = this;\n  new $.Selector(['$', 'physicals', name]).toValue(/*save:*/true);\n  return name;\n};\nObject.setOwnerOf($.physical.setName, $.physicals.Maximilian);\nObject.setOwnerOf($.physical.setName.prototype, $.physicals.Maximilian);\n$.physical.destroy = function destroy() {\n  // TODO: add security check here!!\n\n  // Remove from containment heirarchy.\n  this.validate();\n  var contents = this.getContents();\n  for (var obj, i = 0; (obj = contents[i]); i++) {\n    var dests = [this.location, obj.home, $.startRoom, null];\n    for (i in dests) {\n      var dest = dests[i];\n      try {\n        obj.moveTo(dest);\n        break;\n      } catch (e) {\n        // Continue to try next dest.\n      }\n    }\n    if (obj.location === this) obj.location = null;  // Sorry if you didn't want to go there.\n  }\n  try {\n    this.moveTo(null);\n  } catch (e) {\n    this.location.removeContents(this);\n  }\n\n  var origProto = Object.getPrototypeOf(this);  // Note original protoype.\n  Object.setPrototypeOf(this, $.garbage);  // Make it a non-$.physical\n  if ($.physicals[this.name] === this) delete $.physicals[this.name];  // Free up name.\n  // Delete as much data as possible.\n  var names = Object.getOwnPropertyNames(this);\n  for (i = 0; i < names.length; i++) {\n    delete this[names[i]];\n  }\n  Object.setOwnerOf(this, null);  // Try to remove from owner's quota.\n\n  // Save original prototype, so that $.physical.validate can reparent\n  // children of this object.  (Ideally we'd do so now, but we can't\n  // know which they are until we have an Object.getChildrenOf\n  // function.\n  this.proto = origProto;  // Record original prototype.\n};\nObject.setOwnerOf($.physical.destroy, $.physicals.Maximilian);\nObject.setOwnerOf($.physical.destroy.prototype, $.physicals.Maximilian);\n$.physical.rename = function rename(cmd) {\n  try {\n    var oldName = String(this);\n    this.setName(cmd.iobjstr);\n    cmd.user.narrate(oldName + ' renamed to ' + String(this));\n  } catch (e) {\n    throw e.message;\n  }\n};\nObject.setOwnerOf($.physical.rename, $.physicals.Maximilian);\nObject.setOwnerOf($.physical.rename.prototype, $.physicals.Maximilian);\n$.physical.rename.verb = 'rename';\n$.physical.rename.dobj = 'this';\n$.physical.rename.prep = 'at/to';\n$.physical.rename.iobj = 'any';\n$.physical.destroyVerb = function destroyVerb(cmd) {\n  // Safety checks.\n  if (!cmd.dobj === this) throw 'Not sure what you want to destroy.';\n  var selector = $.Selector.for(this);\n  if (selector && (selector[0] !== '$' || selector[1] !== 'physicals')) {\n    throw String(this) + ' seems too well known: ' + selector.toString();\n  }\n\n  var name = String(this);\n  this.destroy();\n  cmd.user.narrate(name + ' destroyed.');\n};\nObject.setOwnerOf($.physical.destroyVerb, $.physicals.Maximilian);\nObject.setOwnerOf($.physical.destroyVerb.prototype, $.physicals.Maximilian);\n$.physical.destroyVerb.verb = 'destroy';\n$.physical.destroyVerb.dobj = 'this';\n$.physical.destroyVerb.prep = 'none';\n$.physical.destroyVerb.iobj = 'none';\n$.physical.home = null;\n$.physical.teleportTo = function teleport(dest, opt_neighbour) {\n  /* Like moveTo, but with a bit more pizzazz.\n   */\n  if (this.location === dest) return;\n  if ($.physical.isPrototypeOf(this.location)) {\n    this.location.narrate(String(this) + ' vanishes into thin air.', this);\n  }\n  this.moveTo(dest, opt_neighbour);\n  if ($.physical.isPrototypeOf(this.location)) {\n    this.location.narrate(String(this) + ' appears out of thin air.', this);\n  }\n};\nObject.setOwnerOf($.physical.teleportTo, $.physicals.Maximilian);\nObject.setOwnerOf($.physical.teleportTo.prototype, $.physicals.Maximilian);\n$.physical.describe = function describe(cmd) {\n  this.description = cmd.iobjstr;\n  cmd.user.narrate($.utils.string.capitalize(String(this)) + '\\'s description set to \"' + this.description + '\".');\n};\nObject.setOwnerOf($.physical.describe, $.physicals.Maximilian);\nObject.setOwnerOf($.physical.describe.prototype, $.physicals.Maximilian);\n$.physical.describe.verb = 'describe';\n$.physical.describe.dobj = 'this';\n$.physical.describe.prep = 'as';\n$.physical.describe.iobj = 'any';\n$.physical.examine = function $_physical_examine(cmd) {\n  var html = $.jssp.eval(this, 'examineJssp', {user: cmd.user});\n  cmd.user.readMemo({type: \"html\", htmlText: html});\n};\nObject.setOwnerOf($.physical.examine, $.physicals.Neil);\nObject.setOwnerOf($.physical.examine.prototype, $.physicals.Maximilian);\n$.physical.examine.verb = 'ex(amine)?';\n$.physical.examine.dobj = 'this';\n$.physical.examine.prep = 'none';\n$.physical.examine.iobj = 'none';\n$.physical.willMoveTo = function willMoveTo(dest) {\n  /* Returns true iff this is willing to move to dest.\n   *\n   * This function (or its overrides) MUST NOT have any kind of\n   * observable side-effect (making noise, causing some other action,\n   * etc.)\n   */\n  return false;\n};\nObject.setOwnerOf($.physical.willMoveTo, $.physicals.Maximilian);\nObject.setOwnerOf($.physical.willMoveTo.prototype, $.physicals.Maximilian);\n$.physical.edit = function edit(cmd) {\n  // Open this object in the code editor.\n  var selector = $.Selector.for(this);\n  if (!selector) {\n    cmd.user.narrate('Unfortuantely the code editor does not know how to locate ' + String(this) + ' yet.');\n    return;\n  }\n  // No need to encode $.\n  var query = encodeURIComponent(String(selector)).replace(/%24/g, '$');\n  var link = $.hosts.root.url('code') + '?' + query;\n  cmd.user.readMemo({type: \"link\", href: link});\n};\nObject.setOwnerOf($.physical.edit, $.physicals.Maximilian);\n$.physical.edit.verb = 'edit';\n$.physical.edit.dobj = 'this';\n$.physical.edit.prep = 'none';\n$.physical.edit.iobj = 'none';\n$.physical.examineJssp = \"<h1>\\n  <svg width=\\\"32px\\\" height=\\\"32px\\\" viewBox=\\\"0 0 0 0\\\">\\n    <%= $.utils.object.getValue(this, 'svgText') %>\\n  </svg>\\n  <%= $.utils.html.escape(String(this)) + $.utils.commandMenu(this.getCommands(request.user)) %>\\n</h1>\\nYou can:\\n<ul>\\n<%\\n  for (var key in this) {\\n    var method = this[key];\\n    if (typeof method  !== 'function' || !method.verb) continue;\\n    var command = method.verb.replace(/\\\\|/g, '/');\\n    if (method.dobj === 'this') {\\n      command += ' ' + this.name;\\n    } else if (method.dobj === 'any') {\\n      command += ' &lt;any&gt;';\\n    }\\n    if (method.prep  !== 'none') {\\n      command += ' ' + (method.prep === 'any' ? '&lt;any&gt;' : method.prep);\\n      if (method.iobj === 'this') {\\n        command += ' ' + this.name;\\n      } else if (method.iobj === 'any') {\\n        command += ' &lt;any&gt;';\\n      }\\n    }\\n    response.write('<li>' + command + '</li>');\\n  }\\n%>\\n</ul>\";\n\n\n$.physicals['Physical object prototype'] = $.physical;\n\n$.utils.validate.physicals = function physicals(doSpider) {\n  // First, make sure that $.physicals is plausible before we mess with it.\n  var db = $.physicals;\n  if (typeof db !== 'object' && Object.getPrototypeOf(db) === null) {\n    throw new TypeError(\"$.physicals looks wrong\");\n  }\n  for (var name in db) {\n    var obj = db[name];\n    if (!$.physical.isPrototypeOf(obj) && $.physical !== obj) {\n      delete db[name];\n      continue;\n    }\n    if (obj.name !== name) {\n      delete $.physicals[name];\n      obj.setName(obj.name, /*tryAlternative:*/ true);\n    }\n  }\n\n  if (doSpider) {\n    $.utils.object.spider($, function spiderPhysicals(obj) {\n      if (!$.physical.isPrototypeOf(obj)) return false;  // Skip, but don't prune.\n      obj.setName(obj.name, /*tryAlternative:*/ true);\n    });\n  }\n};\nObject.setOwnerOf($.utils.validate.physicals, $.physicals.Maximilian);\nObject.setOwnerOf($.utils.validate.physicals.prototype, $.physicals.Maximilian);\n\n$.garbage = {};\n$.garbage.toString = function toString() {\n  return 'garbage';\n};\nObject.setOwnerOf($.garbage.toString, $.physicals.Maximilian);\nObject.setOwnerOf($.garbage.toString.prototype, $.physicals.Maximilian);\n$.garbage.README = \"We can't forcibly delete objects, so when we want to destroy an object (such as in $.physical.destroy), we do our best to delete obvious references to it (e.g. by deleting its entry in $.physicals and moving it to null), delete all properties on it, set its owner to null and set its prototype to this $.garbage, so that if other references to it are discovered later we know they should be deleted too.\";\n$.garbage.validate = function validate() {\n  /* Fix the prototype of an object which now inherits from a\n   * $.garbage object.\n   *\n   * Objects whose direct prototype is $.garbage are intentional\n   * garbage and will not be resurrected in this way, but any other\n   * descendents of $.garbage are assumed to be collateral damage from\n   * $.physical.destroy and an effort is made to restore their\n   * original prototype.  This may involve walking the prototype\n   * chain, if their direct prototype's prototype is not $.garbage.\n   *\n   * Once a direct descendent of $.garbage is found, that's object's\n   * .proto property is used as th its direct child's new prototype.\n   */\n  if (!$.garbage.isPrototypeOf(this)) {\n    throw new TypeError('$.garbage.validate called on incompatible receiver');\n  }\n  var obj = this;\n  var proto = Object.getPrototypeOf(obj);\n  while (true) {\n    var grandProto = Object.getPrototypeOf(proto);\n    if (grandProto === $.garbage) {\n      if (proto.hasOwnProperty('proto')) {\n        Object.setPrototypeOf(obj, proto.proto);\n        // Revalidate.  Only recursive in case of tiered garbage.\n        this.validate();\n      }\n      return;\n    }\n    obj = proto;\n    proto = grandProto;\n  }\n};\nObject.setOwnerOf($.garbage.validate, $.physicals.Maximilian);\nObject.setOwnerOf($.garbage.validate.prototype, $.physicals.Maximilian);\n\n"
  },
  {
    "path": "core/core_33_world.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Generic physical object types for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.user = (new 'Object.create')($.physical);\n$.user.name = 'User prototype';\n$.user.connection = null;\n$.user.svgText = '<circle cx=\"50\" cy=\"50\" r=\"10\" class=\"fillWhite\"/><line x1=\"50\" y1=\"60\" x2=\"50\" y2=\"80\" /><line x1=\"40\" y1=\"70\" x2=\"60\" y2=\"70\" /><line x1=\"50\" y1=\"80\" x2=\"40\" y2=\"100\" /><line x1=\"50\" y1=\"80\" x2=\"60\" y2=\"100\" />';\n$.user.eval = function $_user_eval(cmd) {\n  // Format:  ;1+1    -or-    eval 1+1\n  var src = (cmd.cmdstr[0] === ';') ? cmd.cmdstr.substring(1) : cmd.argstr;\n  src = $.utils.code.rewriteForEval(src, /* forceExpression= */ false);\n  // Do eval with this === this and vars me === this and here === this.location.\n  var evalFunc = $_user_eval.doEval_.bind(this, this, this.location);\n  var out = $.utils.code.eval(src, evalFunc);\n  suspend();\n  cmd.user.narrate('⇒ ' + out);\n};\nObject.setOwnerOf($.user.eval, $.physicals.Maximilian);\n$.user.eval.verb = 'eval|;.*';\n$.user.eval.dobj = 'any';\n$.user.eval.prep = 'any';\n$.user.eval.iobj = 'any';\n$.user.eval.doEval_ = function doEval_(me, here, $$$src) {\n  // Execute eval in a scope with no variables.\n  // The '$$$src' parameter is awkwardly-named so as not to collide with user\n  // evaled code.  The 'me' and 'here' parameters are exposed to the user.\n  return eval($$$src);\n};\n$.user.narrate = function narrate(text, obj) {\n  var memo = {type: 'narrate', text: String(text)};\n  if (obj && obj.location) {\n    memo.source = obj;\n    memo.where = obj.location;\n  }\n  this.readMemo(memo);\n};\n$.user.create = function create(cmd) {\n  if ($.physical !== cmd.dobj && !$.physical.isPrototypeOf(cmd.dobj)) {\n    cmd.user.narrate('Unknown prototype object.\\n' + $.user.create.usage);\n    return;\n  } else if (!cmd.iobjstr) {\n    cmd.user.narrate('Name must be specified.\\n' + $.user.create.usage);\n    return;\n  }\n  var obj = Object.create(cmd.dobj);\n  Object.setOwnerOf(obj, cmd.user);\n  obj.setName(cmd.iobjstr, /*tryAlternative:*/ true);\n  cmd.user.narrate(String(obj) + ' created.');\n  try {\n    obj.moveTo(cmd.user);\n  } catch (e) {\n    cmd.user.narrate(e.message);\n    var selector = $.Selector.for(obj);\n    if (selector) {\n      cmd.user.narrate('It can be accessed as ' + String(selector));\n    }\n  }\n};\nObject.setOwnerOf($.user.create, $.physicals.Maximilian);\n$.user.create.usage = 'Usage: create <prototype> as <name>';\n$.user.create.verb = 'create';\n$.user.create.dobj = 'any';\n$.user.create.prep = 'as';\n$.user.create.iobj = 'any';\n$.user.join = function join(cmd) {\n  var name = cmd.dobjstr;\n  var re = new RegExp('^' + name, 'i');\n  var who = null;\n  for (var key in $.physicals) {\n    var obj = $.physicals[key];\n    if (!$.user.isPrototypeOf(obj)) continue;\n    if (String(obj).match(re)) {\n      who = obj;\n      break;\n    }\n  }\n  if (!who) {\n    cmd.user.narrate('Can\\'t find a user named \"' + name + '\".');\n    return;\n  }\n  cmd.user.narrate('You join ' + String(who) + '.');\n  this.teleportTo(who.location);\n};\nObject.setOwnerOf($.user.join, $.physicals.Maximilian);\n$.user.join.verb = 'join';\n$.user.join.dobj = 'any';\n$.user.join.prep = 'none';\n$.user.join.iobj = 'none';\n$.user.quit = function quit(cmd) {\n  if (this.connection) {\n    this.connection.close();\n  }\n};\nObject.setOwnerOf($.user.quit, $.physicals.Maximilian);\n$.user.quit.verb = 'quit';\n$.user.quit.dobj = 'none';\n$.user.quit.prep = 'none';\n$.user.quit.iobj = 'none';\n$.user.willAccept = function willAccept(what, src) {\n  /* Returns true iff this is willing to accept what arriving from src.\n   *\n   * This function (or its overrides) MUST NOT have any kind of\n   * observable side-effect (making noise, causing some other action,\n   * etc.).\n   */\n  return $.thing.isPrototypeOf(what);\n};\nObject.setOwnerOf($.user.willAccept, $.physicals.Maximilian);\nObject.setOwnerOf($.user.willAccept.prototype, $.physicals.Maximilian);\n$.user.moveTo = function moveTo(dest, opt_neighbour) {\n  var r = $.physical.moveTo.call(this, dest, opt_neighbour);\n  if (this.location === null) {\n    // Show null scene.\n    var memo = {\n      type: 'scene',\n      requested: true,\n      user: this,\n      where: 'The null void',\n      description: \"You have somehow ended up nowhere at all.\\n(Type 'home' to go home.)\",\n      svgText: this.getNullSvgText(),\n      contents: []\n    };\n    this.readMemo(memo);\n  }\n  return r;\n};\nObject.setOwnerOf($.user.moveTo, $.physicals.Maximilian);\nObject.setOwnerOf($.user.moveTo.prototype, $.physicals.Maximilian);\n$.user.getNullSvgText = function getNullSvgText() {\n  /* Return an SVG text for the null void (i.e., what\n   * a user sees if they're .location is null).\n   */\n  // Draw a double spiral on a black background.\n  // TODO(cpcallen): make spiral curved, rather than angular.\n  var out = [];\n  out.push('<rect class=\"fillBlack strokeNone\" height=\"100\" width=\"2000\" x=\"-1000\" y=\"0\"/>\\n');\n  for (var i = 0; i < 2; i++) {\n    var vx = 0;\n    var vy = Math.pow(-1, i);\n    out.push('<path class=\"strokeWhite\" d=\"M ', 100 * vx, ',', 50 - 50 * vy, ' ');\n    for (var j = 0; j < 20; j++) {\n      var d = Math.pow(0.5, j/2);\n      out.push(' ', 100 * d * vx, ',', 50 - 50 * d * vy, ' ');\n      var tmp = vx;\n      vx = -vy;\n      vy = tmp;\n    }\n    out.push('\"/>\\n');\n  }\n  return out.join('');\n};\nObject.setOwnerOf($.user.getNullSvgText, $.physicals.Maximilian);\n$.user.getCommands = function getCommands(who) {\n  var commands = $.physical.getCommands.apply(this, arguments);\n  if (who.location !== this.location) {\n    commands.push('join ' + this.name);\n  }\n  return commands;\n};\nObject.setOwnerOf($.user.getCommands, $.physicals.Maximilian);\nObject.setOwnerOf($.user.getCommands.prototype, $.physicals.Maximilian);\n$.user.who = function who(cmd) {\n  $.console.look({user: cmd.user});\n};\nObject.setOwnerOf($.user.who, $.physicals.Maximilian);\n$.user.who.verb = 'w(ho)?';\n$.user.who.dobj = 'none';\n$.user.who.prep = 'none';\n$.user.who.iobj = 'none';\n$.user.onInput = function onInput(command) {\n  // Process one line of input from the user.\n  // TODO(cpcallen): add security checks!\n  try {\n    $.utils.command.execute(command.trim(), this);\n  } catch (e) {\n    suspend();\n    this.narrate(String(e));\n    if (e instanceof Error) this.narrate(e.stack);\n  }\n};\nObject.setOwnerOf($.user.onInput, $.physicals.Maximilian);\n$.user.grep = function grep(cmd) {\n  try {\n    var selector = new $.Selector(cmd.dobjstr);\n  } catch (e) {\n    throw 'Invalid selector ' + cmd.dobjstr;\n  }\n  if (!cmd.iobjstr) throw 'What do you want to search for?';\n  this.grep.search(cmd.user, selector.toString(), cmd.iobjstr, selector, new WeakMap());\n  cmd.user.narrate('Grep complete.');\n};\nObject.setOwnerOf($.user.grep, $.physicals.Maximilian);\n$.user.grep.verb = 'grep';\n$.user.grep.dobj = 'any';\n$.user.grep.prep = 'for/about';\n$.user.grep.iobj = 'any';\n$.user.grep.search = function search(user, prefix, searchString, selector, seen) {\n  var value = selector.toValue();\n  if (!$.utils.isObject(value)) {  // value is a primitive.\n    if (String(value).includes(searchString)) {\n      var formatted = $.utils.code.expressionFor(value);\n      if (typeof value === 'string' && formatted.length > 60) {\n        // Print only extracts of long string values.\n        formatted = formatted.slice(1, -1);  // Remove quotation marks.\n        var re = new RegExp('.{0,20}' +\n                            $.utils.regexp.escape(searchString) +\n                            '.{0,20}', 'g');\n        var m;\n        while ((m = re.exec(formatted))) {\n          user.narrate(selector.toString() + ' includes' + ' ...' + m[0] + '...');\n        }\n      } else {\n        user.narrate(selector.toString() + ' === ' + formatted);\n      }\n    }\n    return;\n  }\n  // Prune search when we wander into objects with canonical Selectors\n  // not starting with prefix.  Otherwise, use canonical Selector.\n  var canonical = $.Selector.for(value);\n  if (canonical) {\n    if (canonical.toString().indexOf(prefix) !== 0) return;\n    selector = canonical;\n  }\n  // Have we seen it before?\n  if (seen.has(value)) return;\n  seen.set(value, true);\n  // Is it a function containing the search string?\n  if (typeof value === 'function') {\n    var text = Function.prototype.toString.call(value);\n    if (text.includes(searchString)) {\n      user.narrate(selector.toString() + ' mentions ' + searchString + ':');\n      var lines = text.split('\\n');\n      for (var i = 0; i < lines.length; i++) {\n        if (lines[i].includes(searchString)) {\n          user.narrate('    line ' + (i + 1) + ': ' + lines[i]);\n        }\n      }\n    }\n  }\n  // Check key names\n  var keys = Object.getOwnPropertyNames(value);\n  for (var i = 0; i < keys.length; i++) {\n    var key = keys[i];\n    var subSelector = new $.Selector(selector.concat(key));\n    if (key.includes(searchString)) {\n      user.narrate(subSelector.toString() + ' exists.');\n    }\n    if (key === 'cache_') {\n      user.narrate('Skipping ' + subSelector.toString());\n      continue;\n    }\n    while (true) {\n      try {\n        search(user, prefix, searchString, subSelector, seen);\n        break;\n      } catch (e) {\n        suspend();\n        if (!(e instanceof RangeError) || e.message !== 'Thread ran too long') throw e;\n      }\n    }\n  }\n};\nObject.setOwnerOf($.user.grep.search, $.physicals.Maximilian);\n$.user.readMemo = function readMemo(memo) {\n  // See $.physical.readMemo for documentation.\n  $.physical.readMemo.call(this, memo);\n  if (!this.connection) return;\n  memo = $.utils.replacePhysicalsWithName(memo);\n  var json = JSON.stringify(memo) + '\\n';\n  try {\n    this.connection.write(json);\n  } catch(e) {\n    if (e.message === 'object is not connected') {\n      this.connection = null;\n    } else {\n      throw e;\n    }\n  }\n};\n$.user.destroyVerb = function destroyVerb(cmd) {\n  // DO NOT MAKE SUPER CALL!\n  if (cmd.user === this) {\n    throw 'You can reach the National Suicide Prevention Lifeline at 1-800-273-8255.';\n  }\n  throw 'You are not allowed to destroy other users.';\n};\nObject.setOwnerOf($.user.destroyVerb, $.physicals.Maximilian);\n$.user.destroyVerb.usage = 'Usage: destroy <object>';\n$.user.destroyVerb.verb = 'destroy';\n$.user.destroyVerb.dobj = 'this';\n$.user.destroyVerb.prep = 'none';\n$.user.destroyVerb.iobj = 'none';\n$.user.homeVerb = function homeVerb(cmd) {\n  var home = cmd.user.home || $.startRoom;\n  if (cmd.user.location === home) {\n    cmd.user.narrate('You are already at home.');\n    return;\n  }\n  cmd.user.narrate('You go home.');\n  cmd.user.teleportTo(home);\n};\nObject.setOwnerOf($.user.homeVerb, $.physicals.Maximilian);\n$.user.homeVerb.verb = 'home';\n$.user.homeVerb.dobj = 'none';\n$.user.homeVerb.prep = 'none';\n$.user.homeVerb.iobj = 'none';\n$.user.teleportTo = function teleportTo(dest, opt_neighbour) {\n  if (this.location === dest) {\n    this.narrate(\"You're already in \" + String(dest) + \".\")\n    return;\n  }\n  $.physical.teleportTo.call(this, dest, opt_neighbour);\n};\nObject.setOwnerOf($.user.teleportTo, $.physicals.Maximilian);\nObject.setOwnerOf($.user.teleportTo.prototype, $.physicals.Maximilian);\n$.user.go = function go(cmd) {\n  var dest = null;\n  if ($.room.isPrototypeOf(cmd.iobj)) {\n    dest = cmd.iobj;\n  } else if (!cmd.iobjstr) {\n    throw 'Usage: go to <name of room>';\n  } else {\n    var re = new RegExp(cmd.iobjstr, 'i');\n    // TODO: find best match, not just first match?\n    for (var name in $.physicals) {\n      if (name.match(re) && $.room.isPrototypeOf($.physicals[name])) {\n        dest = $.physicals[name];\n        break;\n      }\n    }\n  }\n  if (dest) {\n    this.teleportTo(dest);\n  } else {\n    throw 'There is no room named ' + cmd.iobjstr + '.';\n  }\n};\nObject.setOwnerOf($.user.go, $.physicals.Maximilian);\nObject.setOwnerOf($.user.go.prototype, $.physicals.Maximilian);\n$.user.go.verb = 'go';\n$.user.go.dobj = 'none';\n$.user.go.prep = 'at/to';\n$.user.go.iobj = 'any';\n$.user.onConnect = function onConnect(reconnect) {\n  /* Called from $.servers.telnet.connection.onReceiveLine once a new\n   * connection is logged in to this user.  Argument will be true if\n   * user was already connected (and this is just a reconnection).\n   */\n  if ($.room.isPrototypeOf(this.location)) {\n    this.location.narrate(\n      String(this) + (reconnect ? ' startles awake.' : ' wakes up.'),\n      this);\n    this.onInput('look');\n  } else {\n    this.teleportTo(this.home || $.startRoom);\n  }\n  if (this.name.match(/^Guest/)) {\n    this.narrate(\n      'Welcome to Code City.\\n' +\n      \"If you're planning to hang around, why not give your self a\\n\" +\n      'name by typing \"rename me to <new name>\" in the box below.');\n  }\n};\nObject.setOwnerOf($.user.onConnect, $.physicals.Maximilian);\nObject.setOwnerOf($.user.onConnect.prototype, $.physicals.Maximilian);\n$.user.onDisconnect = function onDisconnect() {\n  /* Called from $.servers.telnet.connection.onEnd once connection\n   * has dropped.\n   */\n  // Have they made an effort to not look like a guest?\n  if (this.hasOwnProperty('description') ||\n      this.hasOwnProperty('home') ||\n      !this.name.match(/^Guest(?: #\\d+)?/) ||\n      Object.getOwnPropertyNames(this).length > 5) {\n    // Not a guest.\n    if (this.location) {\n      this.location.narrate(String(this) + ' nods off to sleep.', this);\n    }\n  } else {\n    // Pretty guest-y.\n    if (this.location) {\n      this.location.narrate(String(this) + ' suddenly vanishes without a trace!');\n    }\n    this.destroy();\n  }\n};\nObject.setOwnerOf($.user.onDisconnect, $.physicals.Maximilian);\nObject.setOwnerOf($.user.onDisconnect.prototype, $.physicals.Maximilian);\n$.user.description = 'A new user who has not yet set his/her description.';\n$.user.destroy = function destroy() {\n  $.physical.destroy.call(this);\n\n  // Make sure next login gets a fresh guest.\n  suspend();\n  $.userDatabase.validate();\n};\nObject.setOwnerOf($.user.destroy, $.physicals.Maximilian);\nObject.setOwnerOf($.user.destroy.prototype, $.physicals.Maximilian);\n$.user.inventory = function inventory(cmd) {\n  this.look(cmd);\n};\nObject.setOwnerOf($.user.inventory, $.physicals.Neil);\nObject.setOwnerOf($.user.inventory.prototype, $.physicals.Maximilian);\n$.user.inventory.verb = 'inv(entory)?';\n$.user.inventory.dobj = 'none';\n$.user.inventory.prep = 'none';\n$.user.inventory.iobj = 'none';\n$.user.willMoveTo = function willMoveTo(dest) {\n  /* Returns true iff this is willing to move to dest.\n   *\n   * This function (or its overrides) MUST NOT have any kind of\n   * observable side-effect (making noise, causing some other action,\n   * etc.)\n   */\n  // Users should in general always be in a room.\n  return $.room.isPrototypeOf(dest);\n};\nObject.setOwnerOf($.user.willMoveTo, $.physicals.Maximilian);\nObject.setOwnerOf($.user.willMoveTo.prototype, $.physicals.Maximilian);\n$.user.inlineEdit = function inlineEdit(cmd) {\n  var obj = cmd.iobj;\n  var objName = cmd.iobjstr;\n  var prop = cmd.dobjstr;\n\n  if (!$.utils.isObject(obj) || !prop) {\n    cmd.user.narrate('Usage: edit <property> on <object>');\n    return;\n  }\n  var url = $.hosts.code['/inlineEdit'].edit(obj, objName, prop);\n  var memo = {\n    type: 'iframe',\n    url: url,\n    alt: 'Edit ' + prop + ' on ' + objName\n  };\n  cmd.user.readMemo(memo);\n};\nObject.setOwnerOf($.user.inlineEdit, $.physicals.Maximilian);\n$.user.inlineEdit.verb = 'edit';\n$.user.inlineEdit.dobj = 'any';\n$.user.inlineEdit.prep = 'on top of/on/onto/upon';\n$.user.inlineEdit.iobj = 'any';\n$.user.describe = function describe(cmd) {\n  if (typeof this.description === 'function') {\n    cmd.user.narrate(\"Can't set description since it is a function.\");\n    return;\n  }\n  this.description = cmd.iobjstr;\n  cmd.user.narrate($.utils.string.capitalize(String(this)) + '\\'s description set to \"' + this.description + '\".');\n};\nObject.setOwnerOf($.user.describe, $.physicals.Neil);\nObject.setOwnerOf($.user.describe.prototype, $.physicals.Neil);\n$.user.describe.verb = 'describe';\n$.user.describe.dobj = 'this';\n$.user.describe.prep = 'as';\n$.user.describe.iobj = 'any';\n$.user.lookJssp = \"<table style=\\\"height: 100%; width: 100%;\\\">\\n  <tr>\\n    <td style=\\\"padding: 1ex; width: 30%;\\\">\\n      <svg width=\\\"100%\\\" height=\\\"100%\\\" viewBox=\\\"0 0 0 0\\\">\\n        <%= $.utils.object.getValue(this, 'svgText') %>\\n      </svg>\\n    </td>\\n    <td>\\n    <h1><%: this %><%= $.utils.commandMenu(this.getCommands(request.user)) %></h1>\\n    <p><%= $.utils.html.preserveWhitespace($.utils.object.getValue(this, 'description')) %><br>\\n      <%: String(this) + (this.connection && this.connection.connected ? ' is awake.' : ' is sleeping.') %></p>\\n<%\\nvar contents = this.getContents();\\nif (contents.length) {\\n  var contentsHtml = [];\\n  for (var i = 0; i < contents.length; i++) {\\n    contentsHtml[i] = $.utils.html.escape(contents[i].name) +\\n        $.utils.commandMenu(contents[i].getCommands(request.user));\\n  }\\n  response.write('<p>Contents: ' + contentsHtml.join(', ') + '</p>');\\n}\\nif (this.location) {\\n  response.write('<p>Location: ' + $.utils.html.escape(this.location.name) +\\n      $.utils.commandMenu(this.location.getCommands(request.user)) + '</p>');\\n}\\n%>\\n    </td>\\n  </tr>\\n</table>\";\n\n$.room = (new 'Object.create')($.physical);\n$.room.name = 'Room prototype';\n$.room.svgText = '<line x1=\"-1000\" y1=\"90\" x2=\"1000\" y2=\"90\" />';\n$.room.sendScene = function sendScene(who, requested) {\n  var memo = {\n    type: 'scene',\n    requested: requested,\n    user: who,\n    where: this,\n    description: $.utils.object.getValue(this, 'description'),\n    svgText: $.utils.object.getValue(this, 'svgText'),\n    contents: []\n  };\n  var contents = this.getContents();\n  for (var i = 0; i < contents.length; i++) {\n    var object = contents[i];\n    memo.contents.push({\n      type: $.user.isPrototypeOf(object) ? 'user' : 'thing',\n      what: object,\n      svgText: $.utils.object.getValue(object, 'svgText'),\n      cmds: object.getCommands(who)\n    });\n  }\n  who.readMemo(memo);\n};\nObject.setOwnerOf($.room.sendScene, $.physicals.Neil);\n$.room.look = function look(cmd) {\n  this.sendScene(cmd.user, true);\n};\nObject.setOwnerOf($.room.look, $.physicals.Maximilian);\n$.room.look.verb = 'l(ook)?';\n$.room.look.dobj = 'this';\n$.room.look.prep = 'none';\n$.room.look.iobj = 'none';\n$.room.say = function say(cmd) {\n  // Format:  \"Hello.    -or-    say Hello.\n  var text = (cmd.cmdstr[0] === '\"') ? cmd.cmdstr.substring(1) : cmd.argstr;\n  var lastLetter = text.trim().slice(-1);\n  var type = (lastLetter === '?') ? 1 :\n            ((lastLetter === '!') ? 2 : 0);\n  var verb = [['say', 'says'], ['ask', 'asks'], ['exclaim', 'exclaims']][type];\n  var altMe = 'You ' + verb[0] + ', \"' + text + '\"';\n  var altOthers = cmd.user + ' ' + verb[1] + ', \"' + text + '\"';\n  var memo = {\n    type: 'say',\n    source: cmd.user,\n    where: this,\n    text: text,\n    alt: altMe\n  };\n  cmd.user.readMemo(memo);\n  memo.alt = altOthers;\n  this.sendMemo(memo, cmd.user);\n};\nObject.setOwnerOf($.room.say, $.physicals.Maximilian);\n$.room.say.verb = 'say?|\".*';\n$.room.say.dobj = 'any';\n$.room.say.prep = 'any';\n$.room.say.iobj = 'any';\n$.room.think = function think(cmd) {\n  var text = cmd.argstr;\n  var altMe = 'You think, \"' + text + '\"';\n  var altOthers = cmd.user + ' thinks, \"' + text + '\"';\n  var memo = {\n    type: \"think\",\n    source: cmd.user,\n    where: this,\n    text: text,\n    alt: altMe\n  };\n  cmd.user.readMemo(memo);\n  memo.alt = altOthers;\n  this.sendMemo(memo, cmd.user);\n};\nObject.setOwnerOf($.room.think, $.physicals.Neil);\n$.room.think.verb = 'think|.oO';\n$.room.think.dobj = 'any';\n$.room.think.prep = 'any';\n$.room.think.iobj = 'any';\n$.room.narrate = function narrate(text, except, obj) {\n  /* Send narration text to the contents of the room.\n   *\n   * text is the contents of the narration.\n   *\n   * except is an individual $.physical object, or an array of such,\n   *        which should not receive the narration.\n   *\n   * obj, if specified, will cause the narration to have a speech-\n   *      -bubble style arrow pointing at the specified object,\n   *      provided that object is in the room.\n   */\n  var contents = this.getContents();\n  for (var i = 0; i < contents.length; i++) {\n    var thing = contents[i];\n    if (thing !== except &&\n        !(except && except.includes && except.includes(thing)) &&\n        thing.narrate) {\n      thing.narrate(text, obj);\n    }\n  }\n};\nObject.setOwnerOf($.room.narrate, $.physicals.Maximilian);\n$.room.willAccept = function willAccept(what, src) {\n  /* Returns true iff this is willing to accept what arriving from src.\n   *\n   * This function (or its overrides) MUST NOT have any kind of\n   * observable side-effect (making noise, causing some other action,\n   * etc.).\n   */\n  return $.thing.isPrototypeOf(what) || $.user.isPrototypeOf(what);\n};\nObject.setOwnerOf($.room.willAccept, $.physicals.Maximilian);\n$.room.onEnter = function onEnter(what, src) {\n  // TODO: caller check: should only be called by $.physical.moveTo.\n  $.physical.validate.call(this);\n  this.updateScene(false);\n\n  if ($.user.isPrototypeOf(what)) {\n    this.sendScene(what, true);\n  }\n};\nObject.setOwnerOf($.room.onEnter, $.physicals.Neil);\n$.room.onExit = function onExit(what, dest) {\n  // TODO: caller check: should only be called by $.physical.moveTo.\n  suspend(0);  // Wait for what to actually leave.\n  $.physical.validate.call(this);\n  this.updateScene(false);\n};\nObject.setOwnerOf($.room.onExit, $.physicals.Neil);\n$.room.lookHere = function lookHere(cmd) {\n  return this.look(cmd);\n};\n$.room.lookHere.verb = 'l(ook)?';\n$.room.lookHere.dobj = 'none';\n$.room.lookHere.prep = 'none';\n$.room.lookHere.iobj = 'none';\n$.room.location = null;\n$.room.contents_ = [];\n$.room.contents_.forObj = $.room;\nObject.defineProperty($.room.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.room.contents_.forKey = 'contents_';\nObject.defineProperty($.room.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.room.sendMemo = function sendMemo(memo, except) {\n  /* Send a memo to most or all objects in this room.\n   * - memo: the memo to be sent.\n   * - except: an individual $.physical object, or an array of such,\n   *           which should not receive the memo.\n   */\n  var contents = this.getContents();\n  for (var i = 0; i < contents.length; i++) {\n    var thing = contents[i];\n    if (thing === except || except && except.includes && except.includes(thing)) {\n      continue;\n    }\n    thing.readMemo(memo);\n  }\n};\nObject.setOwnerOf($.room.sendMemo, $.physicals.Maximilian);\n$.room.emote = function emote(cmd) {\n  // Format:  :blinks..    -or-    ::'s ears twitch.\n  var m, action;\n  if (cmd.verbstr === 'emote') {\n    action = String(cmd.user) + ' ' + cmd.argstr;\n  } else if ((m =  /^:(:?)([^:]+)$/.exec(cmd.cmdstr))) {\n    var space = (m[1] === '') ? ' ' : '';\n    var text = m[2].trim();\n    action = String(cmd.user) + space + text;\n  } else {\n    cmd.user.narrate('Try \":blinks.\" or \"::\\'s ears twitch.\"');\n    return\n  }\n  cmd.user.location.narrate(action);\n};\nObject.setOwnerOf($.room.emote, $.physicals.Maximilian);\nObject.setOwnerOf($.room.emote.prototype, $.physicals.Maximilian);\n$.room.emote.verb = '::?[^:]+';\n$.room.emote.dobj = 'any';\n$.room.emote.prep = 'any';\n$.room.emote.iobj = 'any';\n$.room.updateScene = function updateScene(force) {\n  var contents = this.getContents();\n  for (var i = 0, who; (who = contents[i]); i++) {\n    if ($.user.isPrototypeOf(who)) {\n      this.sendScene(who, force);\n    }\n  }\n};\nObject.setOwnerOf($.room.updateScene, $.physicals.Neil);\nObject.setOwnerOf($.room.updateScene.prototype, $.physicals.Neil);\n\n$.thing = (new 'Object.create')($.physical);\n$.thing.name = 'Thing prototype';\n$.thing.svgText = '<path d=\"M10,90 l5,-5 h10 v10 l-5,5\" class=\"fillWhite\"/><line x1=\"20\" y1=\"90\" x2=\"25\" y2=\"85\"/><rect height=\"10\" width=\"10\" y=\"90\" x=\"10\" class=\"fillWhite\"/>';\n$.thing.get = function get(cmd) {\n  if (this.location !== cmd.user.location) {\n    cmd.user.narrate(\"You can't reach \" + this.name + \".\");\n    return;\n  }\n  try {\n    this.moveTo(cmd.user);\n  } catch (e) {\n    throw (e instanceof Error) ? e.message : e;\n  }\n  cmd.user.narrate('You pick up ' + this.name + '.');\n  if (cmd.user.location) {\n    cmd.user.location.narrate(cmd.user.name + ' picks up ' + this.name + '.', cmd.user);\n  }\n};\nObject.setOwnerOf($.thing.get, $.physicals.Maximilian);\n$.thing.get.verb = 'get|take';\n$.thing.get.dobj = 'this';\n$.thing.get.prep = 'none';\n$.thing.get.iobj = 'none';\n$.thing.drop = function drop(cmd) {\n  if (this.location !== cmd.user) {\n    cmd.user.narrate(\"You can't drop something you're not holding.\");\n    return;\n  }\n  try {\n    this.moveTo(cmd.user.location);\n  } catch (e) {\n    throw (e instanceof Error) ? e.message : e;\n  }\n  cmd.user.narrate('You drop ' + this.name + '.');\n  if (cmd.user.location) {\n    cmd.user.location.narrate(cmd.user.name + ' drops ' + this.name + '.', cmd.user);\n  }\n};\nObject.setOwnerOf($.thing.drop, $.physicals.Maximilian);\n$.thing.drop.verb = 'drop|throw';\n$.thing.drop.dobj = 'this';\n$.thing.drop.prep = 'none';\n$.thing.drop.iobj = 'none';\n$.thing.give = function give(cmd) {\n  if (this.location !== cmd.user && this.location !== cmd.user.location) {\n    cmd.user.narrate(\"You can't reach \" + String(this) + \".\");\n    return;\n  }\n  try {\n    this.moveTo(cmd.iobj);\n  } catch (e) {\n    throw (e instanceof Error) ? e.message : e;\n  }\n  cmd.user.narrate('You give ' + String(this) + ' to ' + String(cmd.iobj) + '.');\n  cmd.iobj.narrate(String(cmd.user) + ' gives ' + String(this) + ' to you.');\n  if (cmd.user.location) {\n    cmd.user.location.narrate(\n        String(cmd.user) + ' gives ' + String(this) + ' to ' + String(cmd.iobj) + '.',\n        [cmd.user, cmd.iobj]);\n  }\n};\nObject.setOwnerOf($.thing.give, $.physicals.Maximilian);\nObject.setOwnerOf($.thing.give.prototype, $.physicals.Maximilian);\n$.thing.give.verb = 'give';\n$.thing.give.dobj = 'this';\n$.thing.give.prep = 'at/to';\n$.thing.give.iobj = 'any';\n$.thing.getCommands = function getCommands(who) {\n  var commands = $.physical.getCommands.call(this, who);\n  if (this.location === who) {\n    commands.push('drop ' + this.name);\n  } else if (this.location === who.location) {\n    commands.push('get ' + this.name);\n  }\n  return commands;\n};\nObject.setOwnerOf($.thing.getCommands, $.physicals.Neil);\nObject.setOwnerOf($.thing.getCommands.prototype, $.physicals.Maximilian);\n$.thing.movable = true;\n$.thing.location = null;\n$.thing.contents_ = [];\n$.thing.contents_.forObj = $.thing;\nObject.defineProperty($.thing.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.thing.contents_.forKey = 'contents_';\nObject.defineProperty($.thing.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.thing.willMoveTo = function willMoveTo(dest) {\n  /* Returns true iff this is willing to move to dest.\n   *\n   * This function (or its overrides) MUST NOT have any kind of\n   * observable side-effect (making noise, causing some other action,\n   * etc.)\n   */\n  return Boolean(this.movable);\n};\nObject.setOwnerOf($.thing.willMoveTo, $.physicals.Maximilian);\nObject.setOwnerOf($.thing.willMoveTo.prototype, $.physicals.Maximilian);\n\n$.container = (new 'Object.create')($.thing);\n$.container.getFrom = function getFrom(cmd) {\n  var thing = cmd.dobj;\n  if ($.utils.command.matchFailed(thing)) {\n    thing = $.utils.command.match(cmd.dobjstr, this);\n  }\n  if ($.utils.command.matchFailed(thing, cmd.dobjstr, cmd.user)) return;\n  if (!this.isOpen) {\n    cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is closed.');\n    return;\n  }\n  if (this.location !== cmd.user.location && this.location !== cmd.user) {\n    cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is not here.');\n    return;\n  }\n  if (thing.location !== this) {\n    cmd.user.narrate($.utils.string.capitalize(String(thing)) + ' is not in ' + String(this) + '.');\n    return;\n  }\n  try {\n    thing.moveTo(this.toFloor ? this.location : cmd.user);\n  } catch (e) {\n    cmd.user.narrate(e.message);\n    return;\n  }\n  cmd.user.narrate('You take ' + String(thing) + ' from ' + String(this) + '.');\n  if (cmd.user.location) {\n    cmd.user.location.narrate(String(cmd.user) + ' takes ' + String(thing) + ' from ' + String(this) + '.', cmd.user);\n  }\n};\nObject.setOwnerOf($.container.getFrom, $.physicals.Neil);\n$.container.getFrom.verb = 'get|take';\n$.container.getFrom.dobj = 'any';\n$.container.getFrom.prep = 'out of/from inside/from';\n$.container.getFrom.iobj = 'this';\n$.container.name = 'Container prototype';\n$.container.svgTextOpen = '<path class=\"fillWhite\" d=\"m10,90l5,-5l10,0l0,10l-5,5\"/>\\n<line x1=\"15\" x2=\"15\" y1=\"95\" y2=\"85\"/>\\n<rect class=\"fillWhite\" height=\"10\" width=\"10\" x=\"10\" y=\"90\"/>\\n<line x1=\"20\" x2=\"25\" y1=\"90\" y2=\"85\"/>\\n<path class=\"fillWhite\" d=\"m10,90l5,-5l-8,-8l-5,5l8,8z\"/>';\n$.container.svgTextClosed = '<path class=\"fillWhite\" d=\"m10,90l5,-5l10,0l0,10l-5,5\"/>\\n<line x1=\"20\" x2=\"25\" y1=\"90\" y2=\"85\"/>\\n<rect class=\"fillWhite\" height=\"10\" width=\"10\" x=\"10\" y=\"90\"/>';\n$.container.isOpen = true;\n$.container.open = function open(cmd) {\n  if (this.isOpen) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already open.');\n    return;\n  }\n  if (this.location !== cmd.user.location && this.location !== cmd.user) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.');\n    return;\n  }\n  if (!this.setOpen(true)) {\n    cmd.user.narrate('You can\\'t open ' + String(cmd.dobj));\n    return;\n  }\n  if (cmd.user.location) {\n    cmd.user.location.narrate(cmd.user.name + ' opens ' + String(cmd.dobj) + '.', cmd.user);\n  }\n  cmd.user.narrate('You open ' + String(cmd.dobj) + '.');\n  this.look(cmd);\n};\nObject.setOwnerOf($.container.open, $.physicals.Maximilian);\nObject.setOwnerOf($.container.open.prototype, $.physicals.Maximilian);\n$.container.open.verb = 'open';\n$.container.open.dobj = 'this';\n$.container.open.prep = 'none';\n$.container.open.iobj = 'none';\n$.container.close = function close(cmd) {\n  if (!this.isOpen) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already closed.');\n    return;\n  }\n  if (this.location !== cmd.user.location && this.location !== cmd.user) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.');\n    return;\n  }\n  if (!this.setOpen(false)) {\n    cmd.user.narrate('You can\\'t close ' + String(cmd.dobj));\n    return;\n  }\n  if (cmd.user.location) {\n    cmd.user.location.narrate(cmd.user.name + ' closes ' + String(cmd.dobj) + '.', cmd.user);\n    cmd.user.location.sendScene(cmd.user, false);\n  } else {\n    this.look();\n  }\n  cmd.user.narrate('You close ' + String(cmd.dobj) + '.');\n};\n$.container.close.verb = 'close';\n$.container.close.dobj = 'this';\n$.container.close.prep = 'none';\n$.container.close.iobj = 'none';\n$.container.setOpen = function setOpen(newState) {\n  this.isOpen = Boolean(newState);\n  if ($.room.isPrototypeOf(this.location)) {\n    this.location.updateScene(false);\n  }\n  return true;\n};\nObject.setOwnerOf($.container.setOpen, $.physicals.Maximilian);\nObject.setOwnerOf($.container.setOpen.prototype, $.physicals.Maximilian);\n$.container.getCommands = function getCommands(who) {\n  var commands = $.thing.getCommands.call(this, who);\n  if (this.isOpen) {\n    commands.push('close ' + String(this));\n  } else {\n    commands.push('open ' + String(this));\n  }\n  return commands;\n};\nObject.setOwnerOf($.container.getCommands, $.physicals.Maximilian);\nObject.setOwnerOf($.container.getCommands.prototype, $.physicals.Maximilian);\n$.container.putIn = function putIn(cmd) {\n  if ($.utils.command.matchFailed(cmd.dobj, cmd.dobjstr, cmd.user)) return;\n  var thing = cmd.dobj;\n  if (!this.isOpen) {\n    cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is closed.');\n    return;\n  }\n  if (this.location !== cmd.user.location && this.location !== cmd.user) {\n    cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is not here.');\n    return;\n  }\n  if (thing.location !== cmd.user.location && thing.location !== cmd.user) {\n    cmd.user.narrate('You do not have ' + String(thing) + '.');\n    return;\n  }\n  try {\n    thing.moveTo(this);\n  } catch (e) {\n    cmd.user.narrate(e.message);\n    return;\n  }\n  cmd.user.narrate('You put ' + String(thing) + ' in ' + String(this) + '.');\n  if (cmd.user.location) {\n    cmd.user.location.narrate(String(cmd.user) + ' puts ' + String(thing) + ' in ' + String(this) + '.', cmd.user);\n  }\n};\nObject.setOwnerOf($.container.putIn, $.physicals.Maximilian);\n$.container.putIn.verb = 'put';\n$.container.putIn.dobj = 'any';\n$.container.putIn.prep = 'in/inside/into';\n$.container.putIn.iobj = 'this';\n$.container.willAccept = function willAccept(what, src) {\n  /* Returns true iff this is willing to accept what arriving from src.\n   *\n   * This function (or its overrides) MUST NOT have any kind of\n   * observable side-effect (making noise, causing some other action,\n   * etc.)\n   */\n  return this.isOpen && $.thing.isPrototypeOf(what);\n};\nObject.setOwnerOf($.container.willAccept, $.physicals.Maximilian);\nObject.setOwnerOf($.container.willAccept.prototype, $.physicals.Maximilian);\n$.container.location = null;\n$.container.contents_ = [];\n$.container.contents_.forObj = $.container;\nObject.defineProperty($.container.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.container.contents_.forKey = 'contents_';\nObject.defineProperty($.container.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.container.contentsVisibleWhenOpen = true;\n$.container.contentsVisibleWhenClosed = false;\n$.container.lookJssp = \"<table style=\\\"height: 100%; width: 100%;\\\">\\n  <tr>\\n    <td style=\\\"padding: 1ex; width: 30%;\\\">\\n      <svg width=\\\"100%\\\" height=\\\"100%\\\" viewBox=\\\"0 0 0 0\\\">\\n        <%= $.utils.object.getValue(this, 'svgText') %>\\n      </svg>\\n    </td>\\n    <td>\\n    <h1><%: this %><%= $.utils.commandMenu(this.getCommands(request.user)) %></h1>\\n    <p><%= $.utils.html.preserveWhitespace($.utils.object.getValue(this, 'description')) %></p>\\n    <p>It is <%= this.isOpen ? 'open' : 'closed' %>.</p>\\n<%\\nif (this.isOpen ? this.contentsVisibleWhenOpen : this.contentsVisibleWhenClosed) {\\n  var contents = this.getContents();\\n  if (contents.length) {\\n    var contentsHtml = [];\\n    for (var i = 0; i < contents.length; i++) {\\n      var commands = [\\n        'look ' + contents[i].name + ' in ' + this.name,\\n        'get ' + contents[i].name + ' from ' + this.name\\n      ];\\n      contentsHtml[i] = $.utils.html.escape(contents[i].name) +\\n          $.utils.commandMenu(commands);\\n    }\\n    response.write('<p>Contents: ' + contentsHtml.join(', ') + '</p>');\\n  }\\n}\\nif (this.location) {\\n  response.write('<p>Location: ' + $.utils.html.escape(this.location.name) +\\n      $.utils.commandMenu(this.location.getCommands(request.user)) + '</p>');\\n}\\n%>\\n    </td>\\n  </tr>\\n</table>\";\n$.container.lookIn = function lookIn(cmd) {\n  var thing = cmd.dobj\n  if ($.utils.command.matchFailed(thing)) {\n    thing = $.utils.command.match(cmd.dobjstr, this);\n  }\n  if ($.utils.command.matchFailed(thing, cmd.dobjstr, cmd.user)) return;\n  if (this.location !== cmd.user.location && this.location !== cmd.user) {\n    cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is not here.');\n    return;\n  }\n  if (thing.location !== this) {\n    cmd.user.narrate($.utils.string.capitalize(String(thing)) + ' is not in ' + String(this) + '.');\n    return;\n  }\n  if (this.isOpen) {\n    if (!this.contentsVisibleWhenOpen) {\n      cmd.user.narrate('You can\\'t see inside ' + String(this) + '.');\n      return;\n    }\n  } else {\n    if (!this.contentsVisibleWhenClosed) {\n      cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is closed.');\n      return;\n    }\n  }\n  var html = thing.lookJssp.toString(thing, {user: cmd.user});\n  cmd.user.readMemo({type: \"html\", htmlText: html});\n};\nObject.setOwnerOf($.container.lookIn, $.physicals.Neil);\nObject.setOwnerOf($.container.lookIn.prototype, $.physicals.Neil);\n$.container.lookIn.verb = 'l(ook)?';\n$.container.lookIn.dobj = 'any';\n$.container.lookIn.prep = 'in/inside/into';\n$.container.lookIn.iobj = 'this';\n$.container.toFloor = false;\n$.container.svgText = function svgText() {\n  return this.isOpen ? this.svgTextOpen : this.svgTextClosed;\n};\nObject.setOwnerOf($.container.svgText, $.physicals.Neil);\nObject.setOwnerOf($.container.svgText.prototype, $.physicals.Maximilian);\n\n$.physicals['User prototype'] = $.user;\n\n$.physicals['Room prototype'] = $.room;\n\n$.physicals['Thing prototype'] = $.thing;\n\n$.physicals['Container prototype'] = $.container;\n\n"
  },
  {
    "path": "core/core_34_$.servers.login.js",
    "content": "/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Login service backend server for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.servers.login = {};\nObject.setOwnerOf($.servers.login, $.physicals.Neil);\n$.servers.login.connection = (new 'Object.create')($.connection);\n$.servers.login.connection.onReceiveLine = function onReceiveLine(line) {\n  line = line.trim();\n  try {\n    var loginData = JSON.parse(line);\n    var cookie = $.servers.login.getCookie(loginData);\n    this.write(cookie);\n  } catch (err) {\n    // Just log error.\n    suspend();\n    $.system.log('$.servers.login: ' + String(err));\n  } finally {\n    suspend();\n    this.close();\n  }\n};\nObject.setOwnerOf($.servers.login.connection.onReceiveLine, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.login.connection.onReceiveLine.prototype, $.physicals.Neil);\n$.servers.login.getCookie = function getCookie(loginData) {\n  /* Get the ID cookie for the given loginData.\n   *\n   * Arguments:\n   * - loginData: !Object - the loginData object from loginServer.\n   * Returns: string - the ID cookie to set.  Empty string denotes\n   *     invalid login.\n   */\n  var id = loginData.id;\n  if (typeof(id) !== 'string') {\n    return '';\n  } else if ($.userDatabase.get(id)) {  // User already exists.\n    return id;\n  } else {  // Create new user object.\n    var name = loginData.given_name || loginData.name ||\n        loginData.email && loginData.email.replace(/@.*$/, '');\n    this.createUser(id, name);\n    return id;\n  }\n};\nObject.setOwnerOf($.servers.login.getCookie, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.login.getCookie.prototype, $.physicals.Maximilian);\n$.servers.login.createUser = function createUser(id, name) {\n  /* Create a $.user object for the given id.\n   *\n   * Arguments:\n   * - id: string - the ID cookie for the given user.\n   * - name?: string - the name for the new user.  Default: 'Guest'.\n   * Returns: Object - the new $.user object\n   */\n  if ($.userDatabase.get(id)) throw new TypeError('user already exists');\n\n  // Create new $.user.\n  var user = Object.create($.user);\n  user.setName(name || 'Guest', /*tryAlternative:*/ true);\n  $.userDatabase.set(id, user);\n  /*\n  (function() {\n    setPerms(user);\n    var home = Object.create($.room);\n    home.setName(user.name + \"'s room\", true);\n    home.description = 'A quiet place for ' + user.name + ' to work.';\n    user.home = home;\n    user.moveTo(home);\n  })();\n  */\n  return user;\n};\nObject.setOwnerOf($.servers.login.createUser, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.login.createUser.prototype, $.physicals.Maximilian);\n\n"
  },
  {
    "path": "core/core_34_$.servers.telnet.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Telnet server for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.servers.telnet = {};\n$.servers.telnet.connection = (new 'Object.create')($.connection);\n$.servers.telnet.connection.onReceiveLine = function onReceiveLine(text) {\n  if (this.user) {  // Logged in?\n    // Set 'user' for this thread, and permissions for call\n    Object.setOwnerOf(Thread.current(), this.user);\n    setPerms(this.user);\n    this.user.onInput(text);\n    return;\n  }\n  // Remainder of function handles login.\n  // TODO(fraser): Make sure that no security issues exist due to\n  // called code suspending or timing out unexpectedly.\n  var m = text.match(/identify as ([0-9a-f]+)/);\n  if (!m) {\n    this.write('{type: \"narrate\", text: \"Unknown command: ' +\n               $.utils.html.preserveWhitespace(text) + '\"}');\n    return;\n  }\n  var id = m[1];\n  var user = $.userDatabase.get(id) || $.servers.login.createUser(id);\n  this.user = user;\n  var rebind = false;\n  if (user.connection) {\n    rebind = true;\n    try {\n      user.connection.close();\n    } catch (e) {\n      // Ignore; maybe connection already closed (e.g., due to crash/reboot).\n    }\n    $.system.log('Rebinding connection to ' + user.name);\n  } else {\n    $.system.log('Binding connection to ' + user.name);\n  }\n  user.connection = this;\n  Object.setOwnerOf(Thread.current(), user);\n  setPerms(this.user);\n  new Thread(user.onConnect, 0, user, rebind);\n};\nObject.setOwnerOf($.servers.telnet.connection.onReceiveLine, $.physicals.Maximilian);\n$.servers.telnet.connection.onEnd = function onEnd() {\n  var user = this.user;\n  // Mark connection as closed.\n  $.connection.onEnd.call(this);\n  if (user) {\n    // Unbind connection from user.\n    this.user = null;\n    if (user.connection === this) {\n      user.connection = null;\n      $.system.log('Unbinding connection from ' + user.name);\n      (function () {\n        setPerms(user);\n        new Thread(user.onDisconnect, 0, user);\n      })();\n    }\n  }\n  // Remove this and any other closed / debound connections from array of open connections.\n  $.servers.telnet.validate();\n};\nObject.setOwnerOf($.servers.telnet.connection.onEnd, $.physicals.Maximilian);\n$.servers.telnet.connection.onConnect = function onConnect() {\n  // super call.  Records .connectTime (as number of ms since epoch).\n  $.connection.onConnect.apply(this, arguments);\n  // Add this connection to list of active telnet connections.\n  $.servers.telnet.connected.push(this);\n  setTimeout((function onConnect_timeout() {\n    if (!this.user) this.close();\n  }).bind(this), $.servers.telnet.LOGIN_TIMEOUT_MS);\n};\nObject.setOwnerOf($.servers.telnet.connection.onConnect, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.telnet.connection.onConnect.prototype, $.physicals.Maximilian);\n$.servers.telnet.validate = function validate() {\n  // Examine supposedly-open connections and close and/or remove\n  // closed / timed-out / debound ones from the .connected arary.\n  var limit = Date.now() - this.LOGIN_TIMEOUT_MS;\n  this.connected = this.connected.filter(function(c) {\n    // Close any connections that haven't logged in promptly.\n    if (!c.user && c.connectTime < limit) {\n      try {\n        // Call .close().  Note that that this won't result in the\n        // object's .connected property being set to false\n        // immediately, but only after an async callback to\n        // connection.onEnd() - which will result in another call\n        // to $.servers.telnet.validate().\n        c.close();\n      } catch (e) {\n        // Connection was already closed.  Mark it as such.\n        c.connected = false;\n      }\n    }\n    return c.connected && (!c.user || c.user.connection === c);\n  });\n};\nObject.setOwnerOf($.servers.telnet.validate, $.physicals.Maximilian);\nObject.setOwnerOf($.servers.telnet.validate.prototype, $.physicals.Maximilian);\n$.servers.telnet.LOGIN_TIMEOUT_MS = 20000;\n\n$.servers.telnet.connected = [];\n\n"
  },
  {
    "path": "core/core_40_$.startRoom.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Initial starting room for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.startRoom = (new 'Object.create')($.room);\n\n\n\n$.startRoom.location = null;\n\n$.startRoom.contents_ = [];\n\n$.startRoom.contents_.forObj = $.startRoom;\nObject.defineProperty($.startRoom.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n\n$.startRoom.contents_.forKey = 'contents_';\nObject.defineProperty($.startRoom.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n\n$.startRoom.name = 'Hangout';\n\n$.startRoom.description = 'A place to hang out, chat, and program.';\n\n$.startRoom.roll = function roll(cmd) {\n  var memo = {\n    type: 'iframe',\n    url: 'https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1'\n  };\n  this.sendMemo(memo);\n};\n$.startRoom.roll.verb = 'roll';\n$.startRoom.roll.dobj = 'none';\n$.startRoom.roll.prep = 'none';\n$.startRoom.roll.iobj = 'none';\n\n$.clock = (new 'Object.create')($.thing);\n$.clock.name = 'clock';\n$.clock.location = $.startRoom;\n$.clock.chime = function chime(silent) {\n  // Chiming only.  Timer management all handled by .onTimeout.\n  var hours = (new Date().getHours() %12) || 12;\n  var text = [];\n  for (var i = 0; i < hours; i++) {\n    text.push('Bong.');\n  }\n  this.location.narrate(text.join(' '), undefined, this);\n};\nObject.setOwnerOf($.clock.chime, $.physicals.Maximilian);\n$.clock.contents_ = [];\n$.clock.contents_.forObj = $.clock;\nObject.defineProperty($.clock.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.clock.contents_.forKey = 'contents_';\nObject.defineProperty($.clock.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.clock.validate = function validate() {\n  $.thing.validate.call(this);\n  // Reset timer that runs the chime.\n  this.onTimer();\n};\nObject.setOwnerOf($.clock.validate, $.physicals.Maximilian);\nObject.setOwnerOf($.clock.validate.prototype, $.physicals.Maximilian);\n$.clock.onTimer = function onTimer() {\n  /* Function that creates a thread to call itself at the next hour\n   * (and calls this.chime() if it is the right time to do so.)\n   */\n  var time = new Date();\n  // Chime during first minute past the hour.  If we got called early\n  // we'll automatically try again at (hopefully) the correct time.\n  var doChime = (time.getMinutes() === 0);\n  // Compute next hour in local timezone.\n  time.setMilliseconds(0);\n  time.setSeconds(0);\n  time.setMinutes(0);\n  time.setHours(time.getHours() + 1);  // Automagically increments date if required.\n\n  // Kill any other thread associated with this clock.\n  clearTimeout(this.thread_);\n  // Schedule ourselves to be run again at time.\n  this.thread_ = new Thread(this.onTimer, time - Date.now(), this);\n\n  if (doChime) this.chime();\n};\nObject.setOwnerOf($.clock.onTimer, $.physicals.Maximilian);\nObject.setOwnerOf($.clock.onTimer.prototype, $.physicals.Maximilian);\n$.clock.movable = false;\n$.clock.description = function description() {\n  return 'It is currently ' + Date();\n};\nObject.setOwnerOf($.clock.description, $.physicals.Neil);\nObject.setOwnerOf($.clock.description.prototype, $.physicals.Neil);\n$.clock.svgText = function svgText() {\n  var svg = '<circle cx=\"0\" cy=\"30\" r=\"10\" class=\"fillWhite\" />';\n  var r = 10;\n  for (var i = 0; i < 12; i++) {\n    var a = Math.PI * 2 / 12 * i;\n    var length = (i % 3 === 0) ? 2 : 1;\n    var x1 = Math.sin(a) * r;\n    var y1 = Math.cos(a) * r + 30;\n    var x2 = Math.sin(a) * (r - length);\n    var y2 = Math.cos(a) * (r - length) + 30;\n    svg += '<line x1=\"' + x1 + '\" y1=\"' + y1 + '\" x2=\"' + x2 + '\" y2=\"' + y2 + '\" />';\n  }\n  var now = new Date();\n  var minutes = now.getMinutes() + (now.getSeconds() / 60);\n  var hours = now.getHours() + (minutes / 60);\n  var x1 = 0;\n  var y1 = 30;\n  a = minutes / 60 * Math.PI * 2 + Math.PI;\n  var x2 = Math.sin(a) * -8;\n  var y2 = Math.cos(a) * 8 + 30;\n  svg += '<line x1=\"' + x1 + '\" y1=\"' + y1 + '\" x2=\"' + x2 + '\" y2=\"' + y2 + '\" />';\n  a = hours / 12 * Math.PI * 2 + Math.PI;\n  var x2 = Math.sin(a) * -6;\n  var y2 = Math.cos(a) * 6 + 30;\n  svg += '<line x1=\"' + x1 + '\" y1=\"' + y1 + '\" x2=\"' + x2 + '\" y2=\"' + y2 + '\" />';\n  return svg;\n};\nObject.setOwnerOf($.clock.svgText, $.physicals.Neil);\n\n\n"
  },
  {
    "path": "core/core_41_deutsche_zimmer.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Translation room and tutorial  demo for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.physicals['Das deutsche Zimmer'] = (new 'Object.create')($.room);\n$.physicals['Das deutsche Zimmer'].name = 'Das deutsche Zimmer';\n$.physicals['Das deutsche Zimmer'].translate = function translate(text) {\n  /* Try to translate text into German.  If successful, return\n   * translation.  If not, narrate an indication of failure and return\n   * the original text untranslated.\n   */\n  try {\n    return $.utils.string.translate(text, 'de');\n  } catch (e) {\n    this.narrate('There is a crackling noise.');\n    return text;\n  }\n};\nObject.setOwnerOf($.physicals['Das deutsche Zimmer'].translate, $.physicals.Maximilian);\n$.physicals['Das deutsche Zimmer'].say = function say(cmd) {\n  // Format:  \"Hello.    -or-    say Hello.\n  var text = (cmd.cmdstr[0] === '\"') ? cmd.cmdstr.substring(1) : cmd.argstr;\n  cmd.cmdstr = [];\n  cmd.argstr = this.translate(text);\n  return $.room.say.call(this, cmd);\n};\nObject.setOwnerOf($.physicals['Das deutsche Zimmer'].say, $.physicals.Maximilian);\n$.physicals['Das deutsche Zimmer'].say.verb = 'say|\".*';\n$.physicals['Das deutsche Zimmer'].say.dobj = 'any';\n$.physicals['Das deutsche Zimmer'].say.prep = 'any';\n$.physicals['Das deutsche Zimmer'].say.iobj = 'any';\n$.physicals['Das deutsche Zimmer'].contents_ = [];\n$.physicals['Das deutsche Zimmer'].contents_.forObj = $.physicals['Das deutsche Zimmer'];\nObject.defineProperty($.physicals['Das deutsche Zimmer'].contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.physicals['Das deutsche Zimmer'].contents_.forKey = 'contents_';\nObject.defineProperty($.physicals['Das deutsche Zimmer'].contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.physicals['Das deutsche Zimmer'].location = null;\n\n$.tutorial = (new 'Object.create')($.thing);\n$.tutorial.name = 'tutorial';\n$.tutorial.description = 'A tutorial on how to use the Google Translate API from within Code City.  To begin, pick it up and then look at it again.';\n$.tutorial.svgText = '<path class=\"fillWhite\" d=\"M-15,99 L0,79 H15 L0,99 Z\"/>\\n<line x1=\"2\" x2=\"11\" y1=\"81\" y2=\"81\"/>\\n<line x1=\"0\" x2=\"9\" y1=\"83\" y2=\"83\"/>\\n<line x1=\"-2\" x2=\"4\" y1=\"85\" y2=\"85\"/>';\n$.tutorial.look = function look(cmd) {\n  if (this.location !== cmd.user) {\n    // Show description, encouraging user to pick up tutorial.\n    $.thing.look.call(this, cmd);\n    return;\n  }\n  this.show(cmd.user);  // Show current step.\n};\nObject.setOwnerOf($.tutorial.look, $.physicals.Maximilian);\n$.tutorial.look.verb = 'l(ook)?';\n$.tutorial.look.dobj = 'this';\n$.tutorial.look.prep = 'none';\n$.tutorial.look.iobj = 'none';\n$.tutorial.reset = function reset(cmd) {\n  this.checkLocation();\n  this.step = 0;\n  this.room = undefined;\n  this.origFunc = undefined;\n  if (this.user) this.show();\n};\nObject.setOwnerOf($.tutorial.reset, $.physicals.Maximilian);\n$.tutorial.reset.verb = 'reset';\n$.tutorial.reset.dobj = 'this';\n$.tutorial.reset.prep = 'none';\n$.tutorial.reset.iobj = 'none';\n$.tutorial.continue = function continueVerb(cmd) {\n  this.step++;\n  this.run();\n  this.show();\n};\nObject.setOwnerOf($.tutorial.continue, $.physicals.Maximilian);\n$.tutorial.continue.verb = 'continue';\n$.tutorial.continue.dobj = 'this';\n$.tutorial.continue.prep = 'none';\n$.tutorial.continue.iobj = 'none';\n$.tutorial.getCommands = function getCOmmands(who) {\n  var commands = $.thing.getCommands.call(this, who);\n  if (this.location === who) {\n    commands.push('continue ' + this.name);\n    commands.push('reset ' + this.name);\n  }\n  return commands;\n};\nObject.setOwnerOf($.tutorial.getCommands, $.physicals.Maximilian);\n$.tutorial.moveTo = function moveTo(dest) {\n  // Set this.user th the $.user holding us, or to undefined if not held.\n  var r = $.thing.moveTo.call(this, dest);\n  this.checkLocation();\n  return r;\n};\nObject.setOwnerOf($.tutorial.moveTo, $.physicals.Maximilian);\n$.tutorial.checkLocation = function checkLocation() {\n  if ($.user.isPrototypeOf(this.location)) {\n    this.user = this.location;\n    this.thread = new Thread(this.check, 0, this);\n  } else {\n    this.user = undefined;\n    if (this.t) {\n      Thread.kill(this.thread);\n      this.thread = null;\n    }\n  }\n};\nObject.setOwnerOf($.tutorial.checkLocation, $.physicals.Maximilian);\n$.tutorial.check = function check() {\n  while (true) {\n    var step = this.step;\n    switch (step) {\n      case 1:\n        // See if user has done step 1: are they carrying a room?\n        if (this.room) throw new Error('How is .room set already??');\n        for (var key in $.physicals) {\n          var item = $.physicals[key];\n          if ($.room.isPrototypeOf(item) &&\n              Object.getOwnerOf(item) === this.user &&\n              item.name.match(/Deutsche Zimmer/i)) {\n            this.room = item;\n            break;\n          }\n        }\n        if (this.room) this.step++;\n        break;\n\n      case 3:\n        if (Object.getOwnPropertyDescriptor(this.room, 'description')) {\n          this.step++;\n        }\n        break;\n\n      case 5:\n        var pd = Object.getOwnPropertyDescriptor(this.room, 'translate');\n        if (pd && typeof pd.value === 'function') {\n          this.origFunc = pd.value;\n          var tutorial = this;\n          this.room.translate = function translateHook() {\n            // This is just a hook to help automate the tutorial.\n            if (tutorial.step === 6) tutorial.step++;\n            // Restore and call original version of the function.\n            this.translate = tutorial.origFunc;\n            tutorial.origFunc = undefined;\n            new Thread(function() {\n              tutorial.run();\n              tutorial.show();\n            }, 500);\n            return this.translate.apply(this, arguments);\n          };\n          this.step++;\n        }\n        break;\n\n      case 6:\n        // Handled by hook function installed in step 5.\n        break;\n\n      case 7:\n        var pd = Object.getOwnPropertyDescriptor(this.room, 'say');\n        if (pd && typeof pd.value === 'function') {\n          this.origFunc = this.room.translate;\n          var tutorial = this;\n          this.room.translate = function() {\n            // This is just a hook to help automate the tutorial.\n            if (tutorial.step === 8) tutorial.step++;\n            // Restore and call original version of the function.\n            this.translate = tutorial.origFunc;\n            tutorial.origFunc = undefined;\n            new Thread(function() {\n              tutorial.run();\n              tutorial.show();\n            }, 500);\n            return this.translate.apply(this, arguments);\n          };\n          this.step++;\n        }\n        break;\n\n      case 8:\n        // Handled by hook function installed in step 7.\n        break;\n\n      default:\n        // Nothing to do.\n    }\n    if (this.step !== step) {\n      this.run();\n      this.show();\n    }\n    suspend(1000);\n  }\n};\nObject.setOwnerOf($.tutorial.check, $.physicals.Maximilian);\n$.tutorial.run = function run() {\n  switch (this.step) {\n    case 3:\n      if (this.room.location !== null) this.room.moveTo(null);\n      if (this.user.location !== this.room) this.user.moveTo(this.room);\n      break;\n\n    case 5:\n      // Open room in the code editor.\n      var link = '/code?' + encodeURIComponent($.Selector.for(this.room).toString() + '.translate');\n      this.user.readMemo({type: \"link\", href: link});\n      break;\n\n    default:\n      // Nothing to do.\n  }\n};\nObject.setOwnerOf($.tutorial.run, $.physicals.Maximilian);\n$.tutorial.show = function show() {\n  var lines;\n  var step = this.step;\n  switch(step) {\n    case 0:\n      lines = [\n        '<h1>Translation API Tutorial</h1>',\n        '<p>This tutorial will teach you how to use the Google machine',\n        'translation API to create a room that will automatically',\n        'translate everything said to the language of your choice.</p>',\n        '<p>Type <cmd>continue tutorial</cmd> to continue.</p>'\n      ];\n      break;\n\n    case 1:\n      lines = [\n        '<h2>Step 1: Create a new room</h2>',\n        '<p>Run the following command:</p>',\n        '<cmd>create $.room as Deutsche Zimmer</cmd>',\n        '<p>(Click to run, or type your own variation.)</p>',\n      ];\n      break;\n\n    case 2:\n      lines = [\n        '<h2>Step 2: Move to the newly-created room</h2>',\n        '<p>You\\'ve created a room named \"' + this.room.name + '\".  Now type',\n        \"<cmd>continue tutorial</cmd> and you'll be transported there\",\n        'automagically.</p>',\n      ];\n      break;\n\n    case 3:\n      lines = [\n        '<h2>Step 3: Give your new room a description</h3>',\n        \"<p>You're now in you're newly-created room.  Let's give it a\",\n        'description using the eval command:</p>',\n        '<cmd>eval here.description = \"Wir sprechen Deutsch hier.\"</cmd>',\n      ];\n      break;\n\n    case 4:\n      lines = [\n        '<h2>Step 4: Open code editor</h2>',\n        \"<p>We'll use the code editor to add a translate method to this room.\",\n        'When you type <cmd>continue tutorial</cmd> the code inspector/editor',\n        'will open in another tab.  (You might need to enable pop-ups!)',\n        'Click back to this tab to see the next set of instructions.',\n      ];\n      break;\n\n    case 5:\n      lines = [\n        '<h2>Step 5: Add a translate() method</h2>',\n        '<p>Make sure the status bar of the code inspector says',\n        '$.tutorial.room.translate, then replace \"undefined\" with the',\n        'following code (and save it):</p>',\n        '<pre>',\n        'function translate(text) {',\n        '  // Try to translate text into German.  If successful, return the translation.',\n        '  // If not, narrate an indication of failure and return the original text.',\n        '  try {',\n        \"    var json = $.system.xhr('https://translate-service.scratch.mit.edu' +\",\n        \"        '/translate?language=de&text=' + encodeURIComponent(text));\",\n        '    return JSON.parse(json).result;',\n        '  } catch (e) {',\n        \"    this.narrate('There is a crackling noise.');\",\n        '    return text;',\n        '  }',\n        '};',\n        '</pre>',\n      ];\n      break;\n\n    case 6:\n      lines = [\n        '<h2>Step 6: Test the translate() method</h2>',\n        '<p>Let\\'s use the eval command to test the the new translate',\n        'method:</p>',\n        '<cmd>eval here.translate(\"Good morning.\")</cmd>',\n        '<p>You should see output that looks like this:</p>',\n        '<p>=> \"Guten Morgen.\"</p>',\n      ];\n      break;\n\n    case 7:\n      lines = [\n        '<h2>Step 7: Override the \"say\" verb</h2>',\n        '<p>Use the top part of the inspector to navigate to the \"say\"',\n        'function, and replace it with the following:</p>',\n        '<pre>',\n        'function say(cmd) {',\n        '  // Format:  \"Hello.    -or-    say Hello.',\n        '  var text = (cmd.cmdstr[0] === \\'\"\\') ? cmd.cmdstr.substring(1) : cmd.argstr;',\n        '  cmd.cmdstr = [];',\n        '  cmd.argstr = this.translate(text);',\n        '  return $.room.say.call(this, cmd);',\n        '}',\n        '</pre>',\n      ];\n      break;\n\n    case 8:\n      lines = [\n        '<h2>Step 8: Test out the new \"say\" verb</h2>',\n        '<p>The function you created in the last step, $.tutorial.room.say,',\n        'overrides the default $.room.say function by translating the text to',\n        'be said and then passing it along to the latter to actually say.</p>',\n        \"<p>Let's test it it out by saying something!:</p>\",\n        '<cmd>say Now I can speak German!</cmd>',\n      ];\n      break;\n\n    case 9:\n      lines = [\n        '<h2>Step 9: Finish up</h2>',\n        \"<p>Feel free to hang around an play with the room you've created.\",\n        'Can you change the language it translates into?',\n        '(Hint: look in $.tutorial.room.translate, and remever that \"de\" is',\n        'the two-letter code for the German language.)</p>',\n        \"<p>When you're done, type <cmd>continue tutorial</cmd> and you'll\",\n        'be taken back to where you came from.  You can delete this room ',\n        'when you no longer want it by typing <cmd>destroy ' +\n        $.Selector.for(this.room).toString() + '</cmd>.',\n      ];\n      break;\n\n    case 10:\n      this.user.moveTo($.startRoom);\n      this.room = undefined;\n      // FALLTTHROUGH\n    default:\n      lines = [\n        '<h2>Tutorial Ended</h2>',\n        \"You've either finished the tutorial, or you've found a bug in it.\",\n        'Either way: contratulations!</p>',\n        '<p>You can always <cmd>reset tutorial</cmd> to do it all again.</p>',\n      ];\n  }\n  this.user.readMemo({type: 'html', htmlText: lines.join('\\n')});\n};\nObject.setOwnerOf($.tutorial.show, $.physicals.Maximilian);\n$.tutorial.contents_ = [];\n$.tutorial.contents_.forObj = $.tutorial;\nObject.defineProperty($.tutorial.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.tutorial.contents_.forKey = 'contents_';\nObject.defineProperty($.tutorial.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n\n$.tutorial.location = undefined;\n\n$.tutorial.user = undefined;\n\n$.tutorial.thread = undefined;\n\n$.tutorial.step = undefined;\n\n$.tutorial.room = undefined;\n\n$.tutorial.origFunc = undefined;\n\n$.physicals.tutorial = $.tutorial;\n\n"
  },
  {
    "path": "core/core_42_plant.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Plant demo for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.seed = (new 'Object.create')($.thing);\n$.seed.name = 'Generic Seed';\n$.seed.aliases = [];\n$.seed.aliases[0] = 'seed';\n$.seed.description = 'A harmless looking seed.  Try planting it in a pot, then watering it.';\n$.seed.svgText = '<ellipse class=\"fillWhite\" cx=\"-14.60892\" cy=\"97.64293\" fill-opacity=\"null\" rx=\"2.8451\" ry=\"1.63544\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" transform=\"rotate(19.9831 -14.6089 97.6429)\"/>\\n<path d=\"m-16.80718,96.20653l1.575,1.221l1.57498,-0.04348l1.7717,0.9894\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>';\n$.seed.contents_ = [];\n$.seed.contents_.forObj = $.seed;\nObject.defineProperty($.seed.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.seed.contents_.forKey = 'contents_';\nObject.defineProperty($.seed.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n\n$.seed.location = undefined;\n\n$.physicals['Generic Seed'] = $.seed;\n\n$.pot = (new 'Object.create')($.thing);\n$.pot.name = 'flower pot';\n$.pot.aliases = [];\n$.pot.aliases[0] = 'pot';\n$.pot.description = 'A clay flower pot.  Try planting a seed in a pot, then watering it.';\n$.pot.plant = function plant(cmd) {\n    cmd.user.narrate('You plant ' + String(cmd.dobj) + ' in ' + String(this) + '.');\n    if (cmd.user.location) {\n      cmd.user.location.narrate(String(cmd.user) + ' plants ' + String(cmd.dobj) + ' in ' + String(this) + '.', cmd.user);\n    }\n    cmd.dobj.moveTo(null);\n    this.stage = 0;\n    this.seed = cmd.dobj;\n  };\nObject.setOwnerOf($.pot.plant, $.physicals.Maximilian);\n$.pot.plant.verb = 'plant|put';\n$.pot.plant.dobj = 'any';\n$.pot.plant.prep = 'in/inside/into';\n$.pot.plant.iobj = 'this';\n$.pot.water = function water(cmd) {\n  cmd.user.narrate('You water ' + String(this) + '.');\n  if (cmd.user.location) {\n    cmd.user.location.narrate(String(cmd.user) + ' waters ' + String(this) + '.', cmd.user);\n  }\n  if (this.seed && this.stage < 4) {\n    if (this.stage === 2) {\n      var newSeed = Object.create(this.seed);\n      newSeed.moveTo(this.location, this);\n      cmd.user.location.narrate('A new seed appears.');\n    }\n    this.stage++;\n    this.location.updateScene(true);\n  }\n};\nObject.setOwnerOf($.pot.water, $.physicals.Neil);\n$.pot.water.verb = 'water';\n$.pot.water.dobj = 'this';\n$.pot.water.prep = 'none';\n$.pot.water.iobj = 'none';\n$.pot.getCommands = function getCommands(who) {\n  var commands = $.thing.getCommands.call(this, who);\n  commands.push('water ' + this.name);\n  return commands;\n};\nObject.setOwnerOf($.pot.getCommands, $.physicals.Neil);\n$.pot.contents_ = [];\n$.pot.contents_.forObj = $.pot;\nObject.defineProperty($.pot.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.pot.contents_.forKey = 'contents_';\nObject.defineProperty($.pot.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.pot.reset = function reset(cmd) {\n  $.physicals[\"a seed\"].moveTo(this.location);\n  this.stage = 0;\n  this.seed = null;\n  cmd.user.narrate('You reset ' + String(this) + '.');\n};\nObject.setOwnerOf($.pot.reset, $.physicals.Neil);\nObject.setOwnerOf($.pot.reset.prototype, $.physicals.Neil);\n$.pot.reset.verb = 'reset';\n$.pot.reset.dobj = 'this';\n$.pot.reset.prep = 'none';\n$.pot.reset.iobj = 'none';\n$.pot.svgText = function svgText() {\n  return this.stages[this.stage];\n};\nObject.setOwnerOf($.pot.svgText, $.physicals.Neil);\n\n$.pot.location = undefined;\n\n$.pot.seed = undefined;\n\n$.pot.stage = undefined;\n\n$.pot.stages = [];\n$.pot.stages[0] = '<rect class=\"fillWhite\" height=\"5.05796\" width=\"17.38672\" x=\"-35.87987\" y=\"77.76607\"/>\\n<path class=\"fillWhite\" d=\"m-33.77239,82.99355l1.77938,16.27304l10.10505,0l1.69713,-16.38982l-13.58156,0.11678z\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>';\n$.pot.stages[1] = '<rect class=\"fillWhite\" height=\"5.05796\" width=\"17.38672\" x=\"-35.87987\" y=\"77.76607\"/>\\n<path class=\"fillWhite\" d=\"m-33.77239,82.99355l1.77938,16.27304l10.10505,0l1.69713,-16.38982l-13.58156,0.11678z\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path d=\"m-27.6607,77.44994l0.01557,-2.07037l0.23372,-3.07635l0.85039,-2.90272l0.79706,-1.6423\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-25.55322,67.75553c0.69425,-0.56003 1.15359,-1.31478 1.75841,-1.96447c0.58404,-0.62737 1.43496,-0.96868 2.3408,-1.06159c0.91634,-0.094 1.96963,-0.48738 2.6644,-0.13516c0.5443,0.27594 0.4357,1.44401 -0.07556,2.12869c-0.5115,0.68502 -1.44461,0.97306 -2.27121,1.30384c-0.84867,0.33961 -1.65573,0.25603 -2.62243,0.25556l-1.61804,-0.42262\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" transform=\"rotate(7.81058 -21.9909 66.3711)\"/>\\n<path class=\"fillWhite strokeBlack\" d=\"m-25.76396,67.54478c-0.04318,-0.70648 -0.24023,-1.54869 -0.52687,-2.37312c-0.28528,-0.82052 -0.62256,-1.58778 -1.15685,-2.27388c-0.52987,-0.68044 -1.10796,-1.57005 -1.95843,-1.67432c-0.48733,-0.05975 -0.41485,0.95987 -0.36206,1.80597c0.05552,0.88987 -0.08249,1.76196 0.10537,2.51324c0.1856,0.7422 0.9795,1.19627 1.7738,1.38742l0.78632,0.08829l0.83518,0.10492\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>';\n$.pot.stages[2] = '<path class=\"fillWhite\" d=\"m-15.33193,52.05479c0.99447,0.46979 2.01573,0.95001 2.63483,0.38386c0.61289,-0.56047 -0.13699,-1.46922 -0.6876,-1.75592l-0.8807,-0.10318l-0.85592,0.02993\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<rect class=\"fillWhite\" height=\"5.05796\" width=\"17.38672\" x=\"-35.87987\" y=\"77.76607\"/>\\n<path class=\"fillWhite\" d=\"m-33.77239,82.99355l1.77938,16.27304l10.10505,0l1.69713,-16.38982l-13.58156,0.11678z\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path d=\"m-27.76607,77.44994l0.01557,-2.07037l0.23372,-3.07635l0.85039,-2.90272l2.67555,-6.31152l1.41108,-3.67717l1.09493,-4.41479l-0.06417,-4.62554\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-25.55322,67.75553c0.69425,-0.56003 1.15359,-1.31478 1.75841,-1.96447c0.58404,-0.62737 1.43496,-0.96868 2.3408,-1.06159c0.91634,-0.094 1.96963,-0.48738 2.6644,-0.13516c0.5443,0.27594 0.4357,1.44401 -0.07556,2.12869c-0.5115,0.68502 -1.44461,0.97306 -2.27121,1.30384c-0.84867,0.33961 -1.65573,0.25603 -2.62243,0.25556l-1.61804,-0.42262\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" transform=\"rotate(7.81058 -21.9909 66.3711)\"/>\\n<path class=\"fillWhite strokeBlack\" d=\"m-25.76396,67.54478c-0.04318,-0.70648 -0.24023,-1.54869 -0.52687,-2.37312c-0.28528,-0.82052 -0.62256,-1.58778 -1.15685,-2.27388c-0.52987,-0.68044 -1.10796,-1.57005 -1.95843,-1.67432c-0.48733,-0.05975 -0.41485,0.95987 -0.36206,1.80597c0.05552,0.88987 -0.08249,1.76196 0.10537,2.51324c0.1856,0.7422 0.9795,1.19627 1.7738,1.38742l0.78632,0.08829l0.83518,0.10492\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-23.23498,54.69271c-0.21123,0.80087 -0.4857,1.65683 -1.05148,2.29854c-0.57769,0.65524 -1.71748,1.17988 -2.25348,0.49021c-0.51308,-0.66018 0.13502,-1.64304 0.52984,-2.37712l0.75193,-0.31185l1.24075,-0.52485\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-19.33614,55.32139c0.18068,0.83063 0.00168,1.83364 0.5058,2.5079c0.46582,0.62304 1.60054,0.51549 1.70706,-0.3164c0.10934,-0.85386 -0.35328,-1.59642 -0.88781,-2.18771l-0.35912,-0.21454l-0.43906,-0.15806\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-25.44784,53.10853c-0.36207,0.78314 -0.66601,1.6597 -1.34427,2.13806c-0.66779,0.47097 -1.79337,0.03207 -2.16421,-0.73159c-0.38464,-0.7921 0.12766,-1.54177 0.82364,-2.03652l0.73762,-0.21294l1.47304,-0.10538\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-17.22866,54.0569c0.77374,0.45762 1.303,1.27441 2.0548,1.58281c0.7353,0.30164 1.89823,0.24449 1.94928,-0.55014c0.05578,-0.86815 -0.57155,-1.60436 -1.41075,-1.77029l-0.89849,0l-0.83428,0.10537\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-26.50158,51.00105c-0.97452,0 -1.87253,-0.0001 -2.73973,-0.22831c-0.74498,-0.19605 -1.36818,-0.98574 -1.26449,-1.80372c0.08844,-0.69767 1.23344,-0.70722 2.057,-0.54964l0.77237,0.30447l0.64798,0.51591l0.99431,0.60217\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-25.97471,48.99895c-0.55293,-0.80132 -1.10757,-1.50199 -1.5124,-2.28718c-0.39846,-0.77285 -0.06737,-1.57484 0.75722,-1.61166c0.74202,-0.03314 1.30537,0.52689 1.43225,1.21967l0.06055,0.70699l0.17562,0.60232\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-15.4373,49.20969c0.8614,-0.16593 1.75931,-0.37352 2.39246,-0.91676c0.64524,-0.5536 0.85589,-1.67983 0.13651,-2.13909c-0.72896,-0.46538 -1.6333,0.05268 -2.43007,0.37667l-0.58814,0.53453l-0.14301,0.81194\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-22.81349,46.57534c-0.14254,-0.86906 -0.38418,-1.71893 -0.84187,-2.44313c-0.40485,-0.64061 -0.85311,-0.19136 -1.055,0.53741l-0.21061,0.74661l0.52659,0.60232l0.63472,0.5063\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-17.54479,46.89146c0.45534,-0.74816 1.1105,-1.43851 1.05374,-2.30067c-0.05404,-0.82089 -0.73696,-1.58422 -1.58946,-1.4928c-0.83913,0.08999 -1.15026,1.04935 -1.39817,1.829l-0.06821,0.87357\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-21.86512,45.83772c-0.52132,-0.76321 -0.92961,-1.6151 -0.77478,-2.42313c0.1549,-0.80838 0.9732,-1.41434 1.61932,-0.88941c0.65289,0.53043 0.73607,1.45683 0.52532,2.23772l-0.06055,0.76136l-0.15019,0.69013\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-21.9705,55.21602c-0.41595,0.80687 -0.7821,1.62598 -0.73762,2.4741c0.04317,0.82297 0.53191,1.60149 1.20394,1.52633c0.71107,-0.07954 1.00892,-0.95012 1.00892,-1.73049l0.0022,-0.84519l-0.05896,-0.57796l-0.15399,-0.63001\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<ellipse class=\"fillWhite\" cx=\"-20.86407\" cy=\"50.79031\" fill-opacity=\"null\" rx=\"5.21602\" ry=\"4.42571\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>';\n$.pot.stages[3] = '<path class=\"fillWhite\" d=\"m-15.33193,52.05479c0.99447,0.46979 2.01573,0.95001 2.63483,0.38386c0.61289,-0.56047 -0.13699,-1.46922 -0.6876,-1.75592l-0.8807,-0.10318l-0.85592,0.02993\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<rect class=\"fillWhite\" height=\"5.05796\" width=\"17.38672\" x=\"-35.87987\" y=\"77.76607\"/>\\n<path class=\"fillWhite\" d=\"m-33.77239,82.99355l1.77938,16.27304l10.10505,0l1.69713,-16.38982l-13.58156,0.11678z\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path d=\"m-27.76607,77.44994l0.01557,-2.07037l0.23372,-3.07635l0.85039,-2.90272l2.67555,-6.31152l1.41108,-3.67717l1.09493,-4.41479l-0.06417,-4.62554\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-25.55322,67.75553c0.69425,-0.56003 1.15359,-1.31478 1.75841,-1.96447c0.58404,-0.62737 1.43496,-0.96868 2.3408,-1.06159c0.91634,-0.094 1.96963,-0.48738 2.6644,-0.13516c0.5443,0.27594 0.4357,1.44401 -0.07556,2.12869c-0.5115,0.68502 -1.44461,0.97306 -2.27121,1.30384c-0.84867,0.33961 -1.65573,0.25603 -2.62243,0.25556l-1.61804,-0.42262\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" transform=\"rotate(7.81058 -21.9909 66.3711)\"/>\\n<path class=\"fillWhite strokeBlack\" d=\"m-25.76396,67.54478c-0.04318,-0.70648 -0.24023,-1.54869 -0.52687,-2.37312c-0.28528,-0.82052 -0.62256,-1.58778 -1.15685,-2.27388c-0.52987,-0.68044 -1.10796,-1.57005 -1.95843,-1.67432c-0.48733,-0.05975 -0.41485,0.95987 -0.36206,1.80597c0.05552,0.88987 -0.08249,1.76196 0.10537,2.51324c0.1856,0.7422 0.9795,1.19627 1.7738,1.38742l0.78632,0.08829l0.83518,0.10492\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-23.23498,54.69271c-0.21123,0.80087 -0.4857,1.65683 -1.05148,2.29854c-0.57769,0.65524 -1.71748,1.17988 -2.25348,0.49021c-0.51308,-0.66018 0.13502,-1.64304 0.52984,-2.37712l0.75193,-0.31185l1.24075,-0.52485\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-19.33614,55.32139c0.18068,0.83063 0.00168,1.83364 0.5058,2.5079c0.46582,0.62304 1.60054,0.51549 1.70706,-0.3164c0.10934,-0.85386 -0.35328,-1.59642 -0.88781,-2.18771l-0.35912,-0.21454l-0.43906,-0.15806\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-25.44784,53.10853c-0.36207,0.78314 -0.66601,1.6597 -1.34427,2.13806c-0.66779,0.47097 -1.79337,0.03207 -2.16421,-0.73159c-0.38464,-0.7921 0.12766,-1.54177 0.82364,-2.03652l0.73762,-0.21294l1.47304,-0.10538\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-17.22866,54.0569c0.77374,0.45762 1.303,1.27441 2.0548,1.58281c0.7353,0.30164 1.89823,0.24449 1.94928,-0.55014c0.05578,-0.86815 -0.57155,-1.60436 -1.41075,-1.77029l-0.89849,0l-0.83428,0.10537\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-26.50158,51.00105c-0.97452,0 -1.87253,-0.0001 -2.73973,-0.22831c-0.74498,-0.19605 -1.36818,-0.98574 -1.26449,-1.80372c0.08844,-0.69767 1.23344,-0.70722 2.057,-0.54964l0.77237,0.30447l0.64798,0.51591l0.99431,0.60217\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-25.97471,48.99895c-0.55293,-0.80132 -1.10757,-1.50199 -1.5124,-2.28718c-0.39846,-0.77285 -0.06737,-1.57484 0.75722,-1.61166c0.74202,-0.03314 1.30537,0.52689 1.43225,1.21967l0.06055,0.70699l0.17562,0.60232\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-15.4373,49.20969c0.8614,-0.16593 1.75931,-0.37352 2.39246,-0.91676c0.64524,-0.5536 0.85589,-1.67983 0.13651,-2.13909c-0.72896,-0.46538 -1.6333,0.05268 -2.43007,0.37667l-0.58814,0.53453l-0.14301,0.81194\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-22.81349,46.57534c-0.14254,-0.86906 -0.38418,-1.71893 -0.84187,-2.44313c-0.40485,-0.64061 -0.85311,-0.19136 -1.055,0.53741l-0.21061,0.74661l0.52659,0.60232l0.63472,0.5063\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-17.54479,46.89146c0.45534,-0.74816 1.1105,-1.43851 1.05374,-2.30067c-0.05404,-0.82089 -0.73696,-1.58422 -1.58946,-1.4928c-0.83913,0.08999 -1.15026,1.04935 -1.39817,1.829l-0.06821,0.87357\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-21.86512,45.83772c-0.52132,-0.76321 -0.92961,-1.6151 -0.77478,-2.42313c0.1549,-0.80838 0.9732,-1.41434 1.61932,-0.88941c0.65289,0.53043 0.73607,1.45683 0.52532,2.23772l-0.06055,0.76136l-0.15019,0.69013\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-21.9705,55.21602c-0.41595,0.80687 -0.7821,1.62598 -0.73762,2.4741c0.04317,0.82297 0.53191,1.60149 1.20394,1.52633c0.71107,-0.07954 1.00892,-0.95012 1.00892,-1.73049l0.0022,-0.84519l-0.05896,-0.57796l-0.15399,-0.63001\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<ellipse class=\"fillWhite\" cx=\"-20.86407\" cy=\"50.79031\" fill-opacity=\"null\" rx=\"5.21602\" ry=\"4.42571\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>';\n$.pot.stages[4] = '<rect class=\"fillWhite\" height=\"5.05796\" width=\"17.38672\" x=\"-35.87987\" y=\"77.76607\"/>\\n<path class=\"fillWhite\" d=\"m-33.77239,82.99355l1.77938,16.27304l10.10505,0l1.69713,-16.38982l-13.58156,0.11678z\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path d=\"m-27.76607,77.44994l0.01557,-2.07037l0.23372,-3.07635l0.85039,-2.90272l2.67555,-6.31152l1.41108,-3.67717l1.09493,-4.41479l-0.06417,-4.62554\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m-25.55322,67.75553c0.69425,-0.56003 1.15359,-1.31478 1.75841,-1.96447c0.58404,-0.62737 1.43496,-0.96868 2.3408,-1.06159c0.91634,-0.094 1.96963,-0.48738 2.6644,-0.13516c0.5443,0.27594 0.4357,1.44401 -0.07556,2.12869c-0.5115,0.68502 -1.44461,0.97306 -2.27121,1.30384c-0.84867,0.33961 -1.65573,0.25603 -2.62243,0.25556l-1.61804,-0.42262\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" transform=\"rotate(7.81058 -21.9909 66.3711)\"/>\\n<path class=\"fillWhite strokeBlack\" d=\"m-25.76396,67.54478c-0.04318,-0.70648 -0.24023,-1.54869 -0.52687,-2.37312c-0.28528,-0.82052 -0.62256,-1.58778 -1.15685,-2.27388c-0.52987,-0.68044 -1.10796,-1.57005 -1.95843,-1.67432c-0.48733,-0.05975 -0.41485,0.95987 -0.36206,1.80597c0.05552,0.88987 -0.08249,1.76196 0.10537,2.51324c0.1856,0.7422 0.9795,1.19627 1.7738,1.38742l0.78632,0.08829l0.83518,0.10492\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<g transform=\"scale(-1, 1) translate(50, 0)\">\\n <path class=\"fillWhite\" d=\"m-25.3595,55.75391c-17.03652,-7.72601 -11.7986,-25.43283 3.27911,-22.03468c7.53886,1.69907 15.52472,6.01549 16.12798,7.92411c0.60325,1.90862 2.78068,6.99427 -1.92957,4.96314c-4.71025,-2.03113 -10.49024,-2.09877 -10.65832,-1.88742c-0.16808,0.21134 6.50568,8.15007 11.21126,8.74324c4.70558,0.59317 -5.23155,8.10778 -14.19902,3.53609l-3.83144,-1.24448z\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n <ellipse class=\"fillBlack\" cx=\"-18.38778\" cy=\"38.56691\" fill-opacity=\"null\" rx=\"2.21286\" ry=\"0.94837\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" transform=\"rotate(21.8014 -18.3878 38.5669)\"/>\\n <path d=\"m-6.26976,53.74078l1.11596,-2.21252l-2.73396,1.89274l-0.63091,-2.83912l-2.10305,1.36698l-0.42061,-2.94427l-2.2082,0.84122l-0.42061,-2.52366l-1.9979,0.42061\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n <path d=\"m-5.32139,47.10222l0.27275,2.21784l-1.57773,-2.20776l-1.78715,1.05108l-0.84122,-2.10305l-2.41851,1.05153l-1.15668,-1.9979\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n <line fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" x1=\"-34.93151\" x2=\"-27.02845\" y1=\"28.34563\" y2=\"37.19705\"/>\\n <line fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" x1=\"-41.25395\" x2=\"-30.0843\" y1=\"28.13488\" y2=\"38.35616\"/>\\n <line fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" x1=\"-41.99157\" x2=\"-31.55954\" y1=\"36.03793\" y2=\"40.35827\"/>\\n</g>';\n$.pot.stages[5] = '<path class=\"fillWhite\" d=\"m-33.77239,82.99355l1.77938,16.27304l10.10505,0l1.69713,-16.38982l-13.58156,0.11678z\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"strokeGrey\" d=\"m-27.76607,77.44994l0.01557,-2.07037l0.23372,-3.07635l0.85039,-2.90272l0.88419,-2.20193\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite strokeGrey\" d=\"m-27.87145,72.49736c0.69425,-0.56003 1.15359,-1.31478 1.75841,-1.96447c0.58404,-0.62737 1.43496,-0.96868 2.3408,-1.06159c0.91634,-0.094 1.96963,-0.48738 2.6644,-0.13516c0.5443,0.27594 0.4357,1.44401 -0.07556,2.12869c-0.5115,0.68502 -1.44461,0.97306 -2.27121,1.30384c-0.84867,0.33961 -1.65573,0.25603 -2.62243,0.25556l-1.61804,-0.42262\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" transform=\"rotate(90.3565 -24.3091 71.113)\"/>\\n<path class=\"fillWhite strokeGrey\" d=\"m-27.55532,72.49736c-0.04318,-0.70648 -0.24023,-1.54869 -0.52687,-2.37312c-0.28528,-0.82052 -0.62256,-1.58778 -1.15685,-2.27388c-0.52987,-0.68044 -1.10796,-1.57005 -1.95843,-1.67432c-0.48733,-0.05975 -0.41485,0.95987 -0.36206,1.80597c0.05552,0.88987 -0.08249,1.76196 0.10537,2.51324c0.1856,0.7422 0.9795,1.19627 1.7738,1.38742l0.78632,0.08829l0.83518,0.10492\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\" transform=\"rotate(-77.5564 -29.5764 69.3354)\"/>\\n<path class=\"strokeGrey\" d=\"m-25.86934,67.65016c0.40309,-1.45683 1.41882,-2.34001 2.45746,-2.32875c1.03865,0.01126 2.21288,-0.00228 2.43864,2.82569\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<rect class=\"fillWhite\" height=\"5.05796\" width=\"17.38672\" x=\"-35.87987\" y=\"77.76607\"/>';\n\n$.physicals['flower pot'] = $.pot;\n\n$.thrower = (new 'Object.create')($.thing);\n$.thrower.name = 'a flame thrower';\n$.thrower.aliases = [];\nObject.setOwnerOf($.thrower.aliases, $.physicals.Maximilian);\n$.thrower.aliases[0] = 'flame thrower';\n$.thrower.aliases[1] = 'flamethrower';\n$.thrower.aliases[2] = 'a flamethrower';\n$.thrower.aliases[3] = 'thrower';\n$.thrower.description = 'A backpack filled with napalm.  A pilot light is burning quietly.';\n$.thrower.svgText = '<g transform=\\'scale(-1.5, 1.5) translate(17, -10)\\'><rect class=\"strokeBlack fillGrey\" height=\"13.06639\" width=\"4.10959\" x=\"-19.44152\" y=\"48.68282\"/>\\n<path d=\"m-19.75764,50.15806c-2.23042,-3.16122 -8.40716,0.81052 0.148,10.25242\"/>\\n<path class=\"strokeBlack fillGrey\" d=\"m-17.33404,58.58799l-8.74377,0.19224l-7.6768,-4.20565l-0.7354,1.68199l8.09674,4.41641l9.04311,-0.42061\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/></g>';\n$.thrower.wear = function wear(user) {\n  if (this.savedSvg) {\n    user.narrate(String(this) + ' is already being worn.');\n    return;\n  }\n  this.moveTo(user);\n  this.savedSvg = user.svgText;\n  user.svgText += this.svgText;\n  if (user.location) {\n    user.location.updateScene(true);\n    user.location.narrate(String(user) + ' straps on ' + String(this) + '.', user);\n  }\n  user.narrate('You strap on ' + String(this) + '.');\n};\nObject.setOwnerOf($.thrower.wear, $.physicals.Neil);\n$.thrower.unwear = function unwear(user) {\n  if (!this.savedSvg) {\n    user.narrate('You aren\\'t wearing ' + String(this) + '.');\n    return;\n  }\n  user.svgText = this.savedSvg;\n  this.savedSvg = undefined;\n  if (user.location) {\n    user.location.updateScene(true);\n    user.location.narrate(String(user) + ' takes off ' + String(this) + '.', user);\n  }\n  user.narrate('You takes off ' + String(this) + '.');\n};\nObject.setOwnerOf($.thrower.unwear, $.physicals.Neil);\n$.thrower.fire = function fire(cmd) {\n  var memo = {\n    type: 'iframe',\n    url: '/static/flamethrower.html',\n    alt: 'FIRE!!!'\n  };\n  cmd.user.location.sendMemo(memo);\n  if (cmd.iobj.seed) {\n    cmd.iobj.seed = null;\n  }\n  if (typeof cmd.iobj.stage === 'number') {\n    if (cmd.iobj.stage > 0) {\n      cmd.iobj.stage = cmd.iobj.stages.length - 1;\n    }\n  }\n  suspend(5000);\n  cmd.user.location.updateScene(true);\n};\nObject.setOwnerOf($.thrower.fire, $.physicals.Neil);\n$.thrower.fire.verb = 'fire';\n$.thrower.fire.dobj = 'this';\n$.thrower.fire.prep = 'at/to';\n$.thrower.fire.iobj = 'any';\n$.thrower.getCommands = function getCommands(who) {\n  var commands = $.thing.getCommands.call(this, who);\n  if (this.savedSvg) {\n    commands.push('take off ' + this.name);\n  } else {\n    commands.push('put on ' + this.name);\n  }\n  return commands;\n};\nObject.setOwnerOf($.thrower.getCommands, $.physicals.Neil);\n$.thrower.contents_ = [];\n$.thrower.contents_.forObj = $.thrower;\nObject.defineProperty($.thrower.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.thrower.contents_.forKey = 'contents_';\nObject.defineProperty($.thrower.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.thrower.unwear1 = function unwear1(cmd) {\n  this.unwear(cmd.user);\n};\nObject.setOwnerOf($.thrower.unwear1, $.physicals.Neil);\nObject.setOwnerOf($.thrower.unwear1.prototype, $.physicals.Neil);\n$.thrower.unwear1.verb = 'take';\n$.thrower.unwear1.dobj = 'this';\n$.thrower.unwear1.prep = 'off/off of';\n$.thrower.unwear1.iobj = 'none';\n$.thrower.unwear2 = function unwear2(cmd) {\n  this.unwear(cmd.user);\n};\nObject.setOwnerOf($.thrower.unwear2, $.physicals.Neil);\nObject.setOwnerOf($.thrower.unwear2.prototype, $.physicals.Neil);\n$.thrower.unwear2.verb = 'take';\n$.thrower.unwear2.dobj = 'none';\n$.thrower.unwear2.prep = 'off/off of';\n$.thrower.unwear2.iobj = 'this';\n$.thrower.wear1 = function wear1(cmd) {\n  this.wear(cmd.user);\n};\nObject.setOwnerOf($.thrower.wear1, $.physicals.Neil);\nObject.setOwnerOf($.thrower.wear1.prototype, $.physicals.Neil);\n$.thrower.wear1.verb = 'put';\n$.thrower.wear1.dobj = 'this';\n$.thrower.wear1.prep = 'on top of/on/onto/upon';\n$.thrower.wear1.iobj = 'none';\n$.thrower.wear2 = function wear2(cmd) {\n  this.wear(cmd.user);\n};\nObject.setOwnerOf($.thrower.wear2, $.physicals.Neil);\nObject.setOwnerOf($.thrower.wear2.prototype, $.physicals.Neil);\n$.thrower.wear2.verb = 'put';\n$.thrower.wear2.dobj = 'none';\n$.thrower.wear2.prep = 'on top of/on/onto/upon';\n$.thrower.wear2.iobj = 'this';\n\n$.thrower.location = undefined;\n\n$.thrower.savedSvg = undefined;\n\n$.physicals['a flame thrower'] = $.thrower;\n\n"
  },
  {
    "path": "core/core_43_genetics_lab.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Genetics lab demo for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.physicals['Genetics Lab'] = (new 'Object.create')($.room);\n$.physicals['Genetics Lab'].name = 'Genetics Lab';\n$.physicals['Genetics Lab'].location = null;\n$.physicals['Genetics Lab'].description = 'To create a new mouse, type: create $.cage.mousePrototype as <name>';\n\n$.physicals['Genetics Lab'].contents_ = [];\n\n$.physicals['Genetics Lab'].contents_.forObj = $.physicals['Genetics Lab'];\nObject.defineProperty($.physicals['Genetics Lab'].contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n\n$.physicals['Genetics Lab'].contents_.forKey = 'contents_';\nObject.defineProperty($.physicals['Genetics Lab'].contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n\n$.cage = (new 'Object.create')($.container);\n$.cage.name = 'cage';\n$.cage.contents_ = [];\n$.cage.contents_.forObj = $.cage;\nObject.defineProperty($.cage.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.cage.contents_.forKey = 'contents_';\nObject.defineProperty($.cage.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.cage.isOpen = true;\n$.cage.variation = 1;\n$.cage.tempo = 30;\n$.cage.maxPopulation = 50;\n$.cage.fight = function fight(aggressor, defender) {\n  var capitalizedAggressorName = $.utils.string.capitalize(String(aggressor)) + '(' + aggressor.size + ' cm)';\n  var defenderName = String(defender) + '(' + defender.size + ' cm)';\n  aggressor.aggressiveness--;\n  var point = Math.floor(Math.random() * (aggressor.size + defender.size));\n  var victim = null;\n  if (point > defender.size) {\n    victim = defender;\n  } else if (point < defender.size) {\n    victim = aggressor;\n  }\n  if (victim === defender) {\n    this.location.narrate(capitalizedAggressorName + ' fights and kills ' + defenderName + '.');\n  } else if (victim === aggressor) {\n    this.location.narrate(capitalizedAggressorName + ' fights and is killed by ' + defenderName + '.');\n  } else {\n    this.location.narrate(capitalizedAggressorName + ' fights ' + defenderName + ' to a draw.');\n  }\n  if (victim) {\n    this.kill(victim);\n  }\n};\nObject.setOwnerOf($.cage.fight, $.physicals.Neil);\n$.cage.kill = function kill(victim) {\n  if (!this.isMouse(victim)) {\n    this.location.narrate('ERROR: Cannot kill ' + String(victim) + \" since it doesn't appear to be a mouse in here.\");\n    return;\n  }\n  var owner = Object.getOwnerOf(victim);\n  if (this === $.physicals.cage.mousePrototype) {\n    // Can't happen.  But would be catastrophic, so check anyway.\n    victim.moveTo(null);\n    throw Error('Tried to kill the prototype mouse.');\n  } else if (owner === this) {\n    // This mouse is a child.\n    victim.destroy();\n  } else {\n    // This mouse belongs to a user.\n    victim.moveTo(owner);\n    this.location.narrate($.utils.string.capitalize(String(victim)) + ' is ejected from ' + String(this));\n  }\n};\nObject.setOwnerOf($.cage.kill, $.physicals.Neil);\n$.cage.breed = function breed(mother, father) {\n  mother.fertility--;\n  father.fertility--;\n  if (mother.fertility < 0 || father.fertility < 0) {\n    this.location.narrate('Mating failed since one of them is sterile.');\n    return;\n  }\n  if (mother.sex === father.sex) {\n    var sex = mother.sex;\n    if (sex === 'M') {\n      sex = 'male';\n    } else if (sex === 'F') {\n      sex = 'female';\n    }\n    this.location.narrate('Mating failed since both are ' + mother.sex + '.');\n    return;\n  }\n  var mice = this.getContents();\n  if (mice.length >= this.maxPopulation) {\n    var oldest = mice[0];\n    for (var i = 1; i < mice.length; i++) {\n      if (mice[i].generation < oldest.generation) {\n        oldest = mice[i];\n      }\n    }\n    this.location.narrate('Maximum population (' + this.maxPopulation, ') reached; ' + String(oldest) + ' dies of old age.');\n    this.kill(oldest);\n  }\n\n  var kid = Object.create(this.mousePrototype);\n  Object.setOwnerOf(kid, this);\n  kid.init(mother, father, this.variation);\n  kid.moveTo(this);\n  this.location.narrate($.utils.string.capitalize(String(kid)) + ' has been born to ' + String(mother) + ' & ' + String(father) + '.');\n  this.tasks.push(setTimeout(this.life.bind(this, kid), 0));\n};\nObject.setOwnerOf($.cage.breed, $.physicals.Neil);\n$.cage.tasks = [];\n$.cage.setOpen = function setOpen(newState) {\n  var success = Object.getPrototypeOf($.cage).setOpen.call(this, newState);\n  if (!success) {\n    return false;\n  }\n  while (this.tasks.length) {\n    clearTimeout(this.tasks.pop());\n  }\n  var location = this.location;\n  var mice = this.getContents();\n  if (this.isOpen) {\n    for (var i = mice.length - 1; i >= 0; i--) {\n      this.kill(mice[i]);\n    }\n    location.narrate('All mice in ' + String(this) + ' have been exterminated.');\n  } else {\n    location.narrate($.utils.string.capitalize(String(this)) + ' starts running.');\n    for (var i = mice.length - 1; i >= 0; i--) {\n      var mouse = mice[i];\n      if (this.isMouse(mouse)) {\n        location.narrate($.utils.string.capitalize(String(mouse)) + ' starts moving.');\n        this.startMouse(mouse);\n      } else {\n        location.narrate($.utils.string.capitalize(String(mouse)) + \" isn't a valid mouse and gets thrown out.\");\n        mouse.moveTo(location);\n      }\n    }\n  }\n  return true;\n};\nObject.setOwnerOf($.cage.setOpen, $.physicals.Maximilian);\nObject.setOwnerOf($.cage.setOpen.prototype, $.physicals.Maximilian);\n$.cage.life = function life(mouse) {\n  if (!this.isMouse(mouse)) {\n    throw Error(String(mouse) + ' is not a valid mouse.');\n  }\n  var capitalizedMouseName = $.utils.string.capitalize(String(mouse));\n  var self = 'itself';\n  if (mouse.sex === 'M') {\n    self = 'himself';\n  } else if (mouse.sex === 'F') {\n    self = 'herself';\n  }\n  while (true) {\n    this.tasks.push(suspend(Math.random() * this.tempo * 1000));\n    if (mouse.location !== this) {\n      return;\n    }\n    if (mouse.aggressiveness < 1 && mouse.fertility < 1) {\n      this.location.narrate(capitalizedMouseName + ' dies after a productive life.');\n      this.kill(mouse);\n      return;\n    }\n    if (mouse.aggressiveness > 0) {\n      try {\n        var victim = mouse.pickFight();\n      } catch (e) {\n        this.kill(mouse);\n        this.location.narrate(capitalizedMouseName + ' threw \"' + e + '\" in .pickFight function.');\n        this.location.narrate(capitalizedMouseName + ' is being executed to put it out of its misery.');\n      }\n      if (!victim) {\n        this.location.narrate(capitalizedMouseName + ' decides not to fight ever again.');\n        mouse.aggressiveness = 0;\n      } else if (mouse === victim) {\n        this.location.narrate(capitalizedMouseName + ' fights and kills ' + self + '.');\n        this.kill(mouse);\n        return;\n      } else if (this.isMouse(victim)) {\n        this.fight(mouse, victim);\n      } else {\n        this.location.narrate(capitalizedMouseName + ' returned \"' + String(victim) + '\" from .pickFight function.');\n        this.location.narrate(capitalizedMouseName + ' is being executed to put it out of its misery.');\n        this.kill(mouse);\n        return;\n      }\n\n    } else if (mouse.fertility > 0) {\n      try {\n        var target = mouse.proposeMate();\n      } catch (e) {\n        this.kill(mouse);\n        this.location.narrate($.utils.string.capitalize(String(target)) + ' threw \"' + e + '\" in .proposeMate function.');\n        this.location.narrate($.utils.string.capitalize(String(mouse)) + ' is being executed to put it out of its misery.');\n      }\n      if (!target) {\n        this.location.narrate(capitalizedMouseName + ' decides not to mate ever again.');\n        mouse.fertility = 0;\n      } else if (mouse === target) {\n        mouse.fertility--;\n        this.location.narrate(capitalizedMouseName + ' is caught trying to mate with ' + self + '.');\n      } else if (this.isMouse(target)) {\n        try {\n          var answer = target.acceptMate(mouse);\n        } catch (e) {\n          this.location.narrate($.utils.string.capitalize(String(target)) + ' threw \"' + e + '\" in .acceptMate function.');\n          this.location.narrate($.utils.string.capitalize(String(target)) + ' is being executed to put it out of its misery.');\n          this.kill(target);\n        }\n        if (answer) {\n          this.location.narrate(capitalizedMouseName + ' asked ' + String(target) + ' to mate.  The answer is YES!');\n          this.breed(mouse, target);\n        } else {\n          this.location.narrate(capitalizedMouseName + ' asked ' + String(target) + ' to mate.  The answer is NO!');\n        }\n      } else {\n        this.location.narrate(capitalizedMouseName + ' returned \"' + String(target) + '\" from .proposeMate function.');\n        this.location.narrate(capitalizedMouseName + ' is being executed to put it out of its misery.');\n        this.kill(mouse);\n        return;\n      }\n    }\n  }\n};\nObject.setOwnerOf($.cage.life, $.physicals.Neil);\n$.cage.willAccept = function willAccept(what, src) {\n  // Returns true iff this is willing to accept what arriving from src.\n  //\n  // This function (or its overrides) MUST NOT have any kind of\n  // observable side-effect (making noise, causing some other action,\n  // etc.).\n  return this.isOpen || (this.mousePrototype.isPrototypeOf(what) && !src);\n};\nObject.setOwnerOf($.cage.willAccept, $.physicals.Neil);\nObject.setOwnerOf($.cage.willAccept.prototype, $.physicals.Maximilian);\n$.cage.mousePrototype = (new 'Object.create')($.thing);\n$.cage.mousePrototype.name = 'Genetic Mouse Prototype';\n$.cage.mousePrototype.location = null;\n$.cage.mousePrototype.contents_ = [];\n$.cage.mousePrototype.contents_.forObj = $.cage.mousePrototype;\nObject.defineProperty($.cage.mousePrototype.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.cage.mousePrototype.contents_.forKey = 'contents_';\nObject.defineProperty($.cage.mousePrototype.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.cage.mousePrototype.size = 10;\n$.cage.mousePrototype.generation = 0;\n$.cage.mousePrototype.sex = NaN;\n$.cage.mousePrototype.proposeMate = function proposeMate() {\n  // Return who you'd like to mate with!\n  // Returning null will pass on this mating and all future ones.\n  // Reprogram this function to make it smarter!\n  var mice = this.location.getContents();\n  return mice[Math.floor(Math.random() * mice.length)];\n};\nObject.setOwnerOf($.cage.mousePrototype.proposeMate, $.physicals.Neil);\n$.cage.mousePrototype.acceptMate = function acceptMate(whom) {\n  // The mouse 'whom' wishes to mate with you!\n  // Return true to mate with it, or false to tell it to go away.\n  // Reprogram this function to make it smarter!\n  return Math.random() > 0.5;\n};\nObject.setOwnerOf($.cage.mousePrototype.acceptMate, $.physicals.Neil);\n$.cage.mousePrototype.pickFight = function pickFight() {\n  // Return who you'd like to fight with!\n  // Returning null will pass on this fight and all future ones.\n  // The bigger mouse (based on .size) usually wins.\n  // Reprogram this function to make it smarter!\n  var mice = this.location.getContents();\n  return mice[Math.floor(Math.random() * mice.length)];\n};\nObject.setOwnerOf($.cage.mousePrototype.pickFight, $.physicals.Neil);\n$.cage.mousePrototype.toString = function toString() {\n  var prototype = Object.getPrototypeOf(this);\n  var pickFightOwner = (this.pickFight === prototype.pickFight) ?\n      null : Object.getOwnerOf(this.pickFight);\n  var proposeMateOwner = (this.proposeMate === prototype.proposeMate) ?\n      null : Object.getOwnerOf(this.proposeMate);\n  var acceptMateOwner = (this.acceptMate === prototype.acceptMate) ?\n      null : Object.getOwnerOf(this.acceptMate);\n  return this.name + ' (' + String(pickFightOwner) +\n      '/' + String(proposeMateOwner) +\n      '/' + String(acceptMateOwner) + ')';\n};\nObject.setOwnerOf($.cage.mousePrototype.toString, $.physicals.Neil);\n$.cage.mousePrototype.init = function init(mother, father, variation) {\n  // Blend together the numeric attributes from the parents.\n  var thisMouse = this;\n  function blend(name) {\n    var average = (mother[name] + father[name]) / 2;\n    var mutation = Math.random() * 2 * variation - variation;\n    thisMouse[name] = Math.max(1, Math.round(average + mutation));\n  }\n  blend('size');\n  blend('startFertility');\n  this.fertility = this.startFertility;\n  blend('startAggressiveness');\n  this.aggressiveness = this.startAggressiveness;\n  this.generation = 1 + Math.max(mother.generation, father.generation);\n  // Random sex and name.\n  this.sex = Math.random() > 0.5 ? 'M' : 'F';\n  var name = '';\n  for (var i = 0; i < 6; i++) {\n    var letters = ((i % 2) == (this.sex === 'F') ? $.utils.string.VOWELS : $.utils.string.CONSONANTS);\n    name += $.utils.string.randomCharacter(letters);\n  }\n  this.setName($.utils.string.capitalize(name), /*tryAlternative:*/ true);\n  // Copy the three 'genetic' functions.\n  // Take two from one parent, and one from the other.\n  var f1 = Math.floor(Math.random() * 2);\n  var f2 = Math.floor(Math.random() * 2);\n  var f3 = (f1 === f2) ? 1 - f1 : Math.floor(Math.random() * 2);\n  this.proposeMate = (f1 ? mother : father).proposeMate;\n  this.acceptMate = (f2 ? mother : father).acceptMate;\n  this.pickFight = (f3 ? mother : father).pickFight;\n};\nObject.setOwnerOf($.cage.mousePrototype.init, $.physicals.Neil);\n$.cage.mousePrototype.svgText = '<circle class=\"fillWhite\" cx=\"5.72917\" cy=\"75.78125\" fill-opacity=\"null\" r=\"3.03695\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<circle class=\"fillWhite\" cx=\"16.14583\" cy=\"76.04167\" fill-opacity=\"null\" r=\"3.03695\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<path class=\"fillWhite\" d=\"m12.03308,93.12514c0.10717,-0.16041 0.20994,-0.33687 0.3607,-0.46521c0.13567,-0.11549 0.26228,-0.2318 0.35766,-0.41378c0.09514,-0.18152 0.18337,-0.37185 0.27094,-0.54384c0.09047,-0.17769 0.23341,-0.33627 0.32625,-0.51556c0.09456,-0.18262 0.16626,-0.3955 0.25294,-0.57592c0.08473,-0.17635 0.15151,-0.35631 0.21424,-0.55787c0.0606,-0.19472 0.11528,-0.39692 0.236,-0.55692c0.11711,-0.15522 0.1751,-0.3524 0.24424,-0.54836c0.0733,-0.20776 0.17971,-0.36417 0.30408,-0.54333c0.11333,-0.16327 0.23029,-0.33189 0.31148,-0.51088c0.08883,-0.19584 0.08604,-0.43681 0.17292,-0.60107c0.09343,-0.17665 0.17524,-0.38236 0.25117,-0.60702c0.05663,-0.16755 0.14565,-0.40706 0.24423,-0.56254c0.11292,-0.17809 0.21575,-0.35482 0.29636,-0.55741c0.07633,-0.19184 0.12109,-0.38516 0.17569,-0.61406c0.04666,-0.19564 0.07422,-0.39394 0.14751,-0.60325c0.07343,-0.20968 0.15269,-0.42249 0.1859,-0.63342c0.03708,-0.23553 0.0675,-0.40802 0.09892,-0.64514c0.03015,-0.22757 0.06075,-0.43228 0.10575,-0.64423c0.04384,-0.20646 0.11445,-0.41401 0.1663,-0.63329c0.04621,-0.19545 0.02886,-0.4034 0.01633,-0.62028c-0.01387,-0.24007 0.02528,-0.45202 0.06057,-0.66655c0.03699,-0.22484 0.07443,-0.44395 0.05068,-0.66456c-0.02303,-0.21391 -0.05871,-0.42537 -0.10194,-0.62671c-0.04718,-0.21968 -0.08464,-0.43581 -0.15489,-0.62975c-0.07444,-0.20548 -0.14604,-0.39207 -0.23557,-0.57846c-0.08918,-0.18566 -0.19834,-0.32861 -0.29469,-0.50329c-0.09897,-0.17945 -0.17809,-0.31666 -0.20312,-0.41964c-0.04113,-0.1692 -0.28667,-0.14852 -0.44171,-0.233c-0.1559,-0.08495 -0.30662,-0.20848 -0.44924,-0.26572c-0.16227,-0.06513 -0.33202,-0.15875 -0.50227,-0.16386c-0.17611,-0.00528 -0.33485,0.00854 -0.5018,-0.02748c-0.17309,-0.03735 -0.34972,-0.00494 -0.52126,-0.00233c-0.1752,0.00267 -0.33668,-0.04599 -0.51453,-0.06461c-0.16328,-0.0171 -0.33364,0 -0.51639,0c-0.16946,0 -0.33838,0 -0.49933,0c-0.2001,0 -0.37072,0.01565 -0.52376,0c-0.18217,-0.01862 -0.34876,-0.10261 -0.50742,-0.12788c-0.17392,-0.0277 -0.35294,0.01033 -0.51354,-0.00204c-0.17468,-0.01345 -0.35419,-0.0047 -0.52247,0.00069c-0.17037,0.00545 -0.33059,-0.03414 -0.51396,-0.0348c-0.17038,-0.00062 -0.33266,0.0348 -0.51511,0.0348c-0.17961,0 -0.34591,0 -0.5116,0c-0.1717,0 -0.35472,-0.05006 -0.52282,0.02861c-0.15635,0.07318 -0.30353,0.16488 -0.48929,0.16523c-0.16718,0.00031 -0.33557,-0.00327 -0.49828,-0.0056c-0.16088,-0.0023 -0.33418,0.00613 -0.51423,0.04867c-0.16796,0.03968 -0.28058,0.18636 -0.43422,0.26698c-0.16081,0.08438 -0.33311,0.14746 -0.50376,0.21417c-0.16856,0.06589 -0.34886,0.06024 -0.50639,0.14344c-0.15083,0.07966 -0.29251,0.26612 -0.34361,0.46952c-0.05001,0.19908 -0.06113,0.41128 -0.10312,0.57281c-0.06418,0.24692 -0.04219,0.48684 -0.04318,0.70093c-0.00091,0.19685 -0.02179,0.44057 -0.00433,0.64629c0.01749,0.20598 0.04606,0.4338 0.055,0.66725c0.00789,0.2059 0.00868,0.44533 0.05574,0.65214c0.04451,0.19562 0.10108,0.4036 0.12911,0.62044c0.02837,0.21952 0.11424,0.40775 0.18964,0.61066c0.06952,0.18708 0.15266,0.38581 0.21557,0.572c0.06656,0.19699 0.21037,0.33757 0.31022,0.51815c0.09604,0.1737 0.19471,0.37664 0.27117,0.57747c0.07028,0.18458 0.15927,0.35897 0.27799,0.51699c0.13449,0.17902 0.22487,0.35185 0.30652,0.5394c0.08267,0.1899 0.17582,0.35748 0.27797,0.57073c0.09073,0.1894 0.19736,0.33509 0.30578,0.54181c0.09507,0.18126 0.13773,0.36801 0.26948,0.55438c0.1012,0.14315 0.1916,0.31362 0.30295,0.47201c0.10736,0.15272 0.26718,0.28502 0.35353,0.48125c0.07875,0.17895 0.08404,0.40871 0.18561,0.61244c0.08625,0.173 0.19465,0.3578 0.29178,0.53422c0.09824,0.17845 0.2189,0.34272 0.26908,0.5225c0.05477,0.19623 0.17323,0.36946 0.26577,0.54706c0.09091,0.17449 0.20319,0.34711 0.28538,0.53386c0.0811,0.18428 0.17419,0.37775 0.26136,0.57929c0.08158,0.18863 0.20843,0.34264 0.32867,0.51285c0.10846,0.15354 0.24673,0.27505 0.3601,0.44161c0.10788,0.1585 0.19981,0.31101 0.31581,0.43291c0.1382,0.14522 0.27754,0.25864 0.40544,0.42133c0.1197,0.15226 0.25321,0.29275 0.39242,0.39693c0.15915,0.11909 0.32793,0.1887 0.44168,0.24786c0.14677,0.07633 0.31817,0.06461 0.44623,-0.01292l0.00432,-0.09804l0.11123,0.11027\" fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<circle class=\"fillBlack\" cx=\"13.80208\" cy=\"80.85938\" fill-opacity=\"null\" r=\"0.67853\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<circle class=\"fillBlack\" cx=\"8.72396\" cy=\"80.72909\" fill-opacity=\"null\" r=\"0.54832\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" stroke-width=\"null\"/>\\n<line fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" x1=\"13.02083\" x2=\"26.30208\" y1=\"89.0625\" y2=\"86.71875\"/>\\n<line fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" x1=\"9.63542\" x2=\"-4.16667\" y1=\"88.54167\" y2=\"91.66667\"/>\\n<line fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" x1=\"12.5\" x2=\"26.04167\" y1=\"89.0625\" y2=\"89.0625\"/>\\n<line fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" x1=\"9.11458\" x2=\"-3.64583\" y1=\"88.02083\" y2=\"88.80208\"/>\\n<line fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" x1=\"13.02083\" x2=\"24.21875\" y1=\"89.0625\" y2=\"91.14583\"/>\\n<line fill-opacity=\"null\" stroke-dasharray=\"null\" stroke-linecap=\"null\" stroke-linejoin=\"null\" stroke-opacity=\"null\" x1=\"9.375\" x2=\"-0.52083\" y1=\"89.0625\" y2=\"92.70833\"/>';\n$.cage.mousePrototype.startAggressiveness = 2;\n$.cage.mousePrototype.aggressiveness = 2;\n$.cage.mousePrototype.startFertility = 4;\n$.cage.mousePrototype.fertility = 3;\n$.cage.mousePrototype.getCommands = function getCommands(who) {\n  var commands = $.thing.getCommands.call(this, who);\n  commands.push('program ' + this.name);\n  return commands;\n};\nObject.setOwnerOf($.cage.mousePrototype.getCommands, $.physicals.Neil);\n$.cage.mousePrototype.program = function program(cmd) {\n  // Open this mouse in the genetics editor.\n  var selector = $.Selector.for(this).toString();\n  // No need to encode $.\n  var query = encodeURIComponent(String(selector)).replace(/%24/g, '$');\n  var link = $.hosts.root.url('genetics') + 'editor?' + query;\n  cmd.user.readMemo({type: \"link\", href: link});\n};\nObject.setOwnerOf($.cage.mousePrototype.program, $.physicals.Maximilian);\nObject.setOwnerOf($.cage.mousePrototype.program.prototype, $.physicals.Neil);\n$.cage.mousePrototype.program.verb = 'program';\n$.cage.mousePrototype.program.dobj = 'this';\n$.cage.mousePrototype.program.prep = 'none';\n$.cage.mousePrototype.program.iobj = 'none';\n$.cage.mousePrototype.description = function description() {\n  var sex = 'multi-sexual';\n  if (this.sex === 'm') sex = 'male';\n  if (this.sex === 'f') sex = 'female';\n  var desc = [];\n  desc.push('A ' + sex + ' mouse.');\n  desc.push('It is ' + this.size + ' cm long, and can have ' + this.fertility + ' more children.');\n  desc.push('It can fight ' + this.aggressiveness + ' other mice.');\n  desc.push('It belongs to generation ' + this.generation + '.');\n  return desc.join('\\n');\n};\nObject.setOwnerOf($.cage.mousePrototype.description, $.physicals.Neil);\nObject.setOwnerOf($.cage.mousePrototype.description.prototype, $.physicals.Neil);\n$.cage.isMouse = function isMouse(animal) {\n  return this.mousePrototype.isPrototypeOf(animal) && (animal.location === this);\n};\nObject.setOwnerOf($.cage.isMouse, $.physicals.Neil);\n$.cage.startMouse = function startMouse(mouse) {\n  // Reset all attributes to defaults.\n  var reset = ['fertility', 'startFertility', 'generation', 'startAggressiveness', 'sex', 'size'];\n  for (var i = 0; i < reset.length; i++) {\n    delete mouse[reset[i]];\n  }\n  // First generation mice don't fight.\n  mouse.aggressiveness = 0;\n  this.tasks.push(setTimeout(this.life.bind(this, mouse), 0));\n};\nObject.setOwnerOf($.cage.startMouse, $.physicals.Maximilian);\n$.cage.open = function open(cmd) {\n  if (this.isOpen) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already open.');\n    return;\n  }\n  if (this.location !== cmd.user.location && this.location !== cmd.user) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.');\n    return;\n  }\n  if (!this.setOpen(true)) {\n    cmd.user.narrate('You can\\'t open ' + String(cmd.dobj));\n    return;\n  }\n  if (cmd.user.location) {\n    cmd.user.location.narrate(cmd.user.name + ' opens ' + String(cmd.dobj) + '.', cmd.user);\n  }\n  cmd.user.narrate('You open ' + String(cmd.dobj) + '.');\n  this.look(cmd);\n};\nObject.setOwnerOf($.cage.open, $.physicals.Maximilian);\nObject.setOwnerOf($.cage.open.prototype, $.physicals.Maximilian);\n$.cage.open.verb = 'open';\n$.cage.open.dobj = 'this';\n$.cage.open.prep = 'none';\n$.cage.open.iobj = 'none';\n$.cage.svgTextClosed = '<path class=\"fillWhite\" d=\"m20,80 l10,-10 l20,0 l0,20 l-10,10\"/>\\n<line x1=\"40\" x2=\"50\" y1=\"80\" y2=\"70\"/>\\n<rect class=\"fillWhite\" height=\"20\" width=\"20\" x=\"20\" y=\"80\"/>\\n';\n$.cage.svgTextOpen = '<path class=\"fillWhite\" d=\"m20,80 l10,-10 l20,0 l0,20 l-10,10\"/>\\n<line x1=\"30\" x2=\"30\" y1=\"90\" y2=\"70\"/>\\n<rect class=\"fillWhite\" height=\"20\" width=\"20\" x=\"20\" y=\"80\"/>\\n<line x1=\"40\" x2=\"50\" y1=\"80\" y2=\"70\"/>\\n<path class=\"fillWhite\" d=\"m20,80 l10,-10 l-16,-16 l-10,10 l16,16z\"/>\\n';\n\n$.cage.location = undefined;\n\n$.physicals.cage = $.cage;\n\n$.physicals['Genetic Mouse Prototype'] = $.cage.mousePrototype;\n\n$.hosts.genetics = (new 'Object.create')($.servers.http.Host.prototype);\n$.hosts.genetics['/editor'] = {};\n$.hosts.genetics['/editor'].www = \"<!doctype html>\\n<% var staticUrl = request.hostUrl('static'); %>\\n<html>\\n  <head>\\n    <meta charset=\\\"utf-8\\\"/>\\n    <title>Code City: Genetics Editor</title>\\n    <link href=\\\"<%=staticUrl%>favicon.ico\\\" rel=\\\"shortcut icon\\\">\\n    <link rel=\\\"stylesheet\\\" href=\\\"https://fonts.googleapis.com/css?family=Roboto+Mono\\\">\\n    <link rel=\\\"stylesheet\\\" href=\\\"<%=staticUrl%>style/jfk.css\\\">\\n\\n    <link rel=\\\"stylesheet\\\" href=\\\"<%=staticUrl%>CodeMirror/lib/codemirror.css\\\">\\n    <link rel=\\\"stylesheet\\\" href=\\\"<%=staticUrl%>CodeMirror/addon/lint/lint.css\\\">\\n    <link rel=\\\"stylesheet\\\" href=\\\"<%=staticUrl%>CodeMirror/theme/eclipse.css\\\">\\n    <script src=\\\"<%=staticUrl%>CodeMirror/lib/codemirror.js\\\"></script>\\n    <script src=\\\"<%=staticUrl%>CodeMirror/addon/comment/continuecomment.js\\\"></script>\\n    <script src=\\\"<%=staticUrl%>CodeMirror/addon/edit/matchbrackets.js\\\"></script>\\n    <script src=\\\"<%=staticUrl%>CodeMirror/addon/lint/lint.js\\\"></script>\\n    <script src=\\\"<%=staticUrl%>CodeMirror/addon/lint/javascript-lint.js\\\"></script>\\n    <script src=\\\"<%=staticUrl%>CodeMirror/addon/display/rulers.js\\\"></script>\\n    <script src=\\\"<%=staticUrl%>CodeMirror/mode/javascript/javascript.js\\\"></script>\\n    <script src=\\\"https://unpkg.com/jshint@2.9.6/dist/jshint.js\\\"></script>\\n    <style>\\nbody {\\n  background: #fff;\\n  color: #444;\\n  font-family: \\\"Roboto Mono\\\", monospace;\\n  font-size: 11pt;\\n}\\n\\ninput {\\n  font-family: \\\"Roboto Mono\\\", monospace;\\n  font-size: 11pt;\\n}\\n\\n#editorButtons {\\n  float: right;\\n  margin-top: 5px;\\n  margin-right: 3px;\\n}\\n\\n#editorHeader {\\n  margin: 10px 2px;\\n  overflow: hidden;\\n  white-space: nowrap;\\n  text-overflow: ellipsis;\\n}\\n\\n#editorTabs {\\n  font-family: \\\"Arial\\\", \\\"Helvetica\\\", sans-serif;\\n  font-size: 11px;\\n  margin-left: 2px;\\n}\\n\\n#editorTabs>.spacer {\\n  border-bottom: 1px solid rgba(0,0,0,.1);\\n  padding: 4px 5px;\\n}\\n\\n#editorTabs>.jfk-button {\\n  border-bottom-color: #f1f1f1;\\n  border-bottom-left-radius: 0;\\n  border-bottom-right-radius: 0;\\n  height: auto;\\n  line-height: normal;\\n  margin-right: 0;\\n  padding-bottom: 4px;\\n  padding-top: 4px;\\n}\\n\\n#editorTabs>.highlighted {\\n  background-color: #ccc;\\n  background-image: none;\\n}\\n\\n#editorContainers>div {\\n  display: none;\\n  position: absolute;\\n  top: 60px;\\n  bottom: 20px;\\n  left: 10px;\\n  right: 20px\\n}\\n\\n#editorSavingMask {\\n  background-color: #000;\\n  bottom: 0;\\n  left: 0;\\n  opacity: 0;\\n  position: absolute;\\n  right: 0;\\n  top: 0;\\n  transition-property: opacity;\\n  z-index: 998;\\n}\\n\\n#editorSavingMask {\\n  cursor: wait;\\n  display: none;\\n  transition-duration: 1s;\\n}\\n\\n.CodeMirror {\\n  border: 1px solid #ddd;\\n}\\n\\n#editorButter {\\n  display: none;\\n  left: 0;\\n  position: absolute;\\n  right: 0;\\n  top: 0;\\n  pointer-events: none;\\n  z-index: 10;\\n}\\n\\n#editorButter>div {\\n  text-align: center;\\n}\\n\\n#editorButterText {\\n  background: #f9edbe;\\n  border: 1px solid #f0c36d;\\n  border-radius: 0 0 2px 2px;\\n  border-top: 0;\\n  box-shadow: 0 2px 4px rgba(0,0,0,0.2);\\n  display: inline-block;\\n  padding: 0 10px;\\n  pointer-events: auto;\\n}\\n\\n#referencePage {\\n  font-size: smaller;\\n}\\n\\ndt {\\n  font-weight: bolder;\\n}\\n    </style>\\n    <script>\\n/**\\n * Create a CodeMirror editor.\\n * @param {!Element} container HTML element to hold the editor.\\n * @param {string} value Initial JavaScript code.\\n * @return {!Object} CodeMirron editor.\\n */\\nfunction newCodeMirror(container, value) {\\n  var options = {\\n    continueComments: {continueLineComment: false},\\n    extraKeys: {\\n      Tab: function(cm) {\\n        cm.replaceSelection('  ');\\n      }\\n    },\\n    gutters: ['CodeMirror-lint-markers'],\\n    lineNumbers: true,\\n    lint: true,\\n    matchBrackets: true,\\n    mode: 'text/javascript',\\n    rulers: [{color: '#ddd', column: 80, lineStyle: 'dashed'}],\\n    tabSize: 2,\\n    theme: 'eclipse',\\n    undoDepth: 1024\\n  };\\n  var editor = CodeMirror(container, options);\\n  editor.setSize('100%', '100%');\\n  editor.setValue(value);\\n  editor.on('change', saturateSave);\\n  return editor;\\n}\\n\\n/**\\n * When a tab is clicked, highlight it and show its container.\\n * @param {!Event|!Object} e Click event or object pretending to be an event.\\n */\\nfunction tabClick(e) {\\n  var tab = e.target;\\n  if (tab.parentNode.id !== 'editorTabs') {\\n    throw Error();\\n  }\\n  // Unhighlight all tabs, hide all containers.\\n  var oldTab = document.querySelector('#editorTabs>.highlighted');\\n  oldTab && oldTab.classList.remove('highlighted');\\n  var containers = document.querySelectorAll('#editorContainers>div');\\n  for (var container of containers) {\\n    container.style.display = 'none';\\n  }\\n\\n  // Highlight one tab, show one container.\\n  tab.classList.add('highlighted');\\n  tab.container.style.display = 'block';\\n  if (tab.editor) {\\n    tab.editor.refresh();\\n    tab.editor.focus();\\n  }\\n  // Save tab preference.\\n  sessionStorage.setItem('GENETIC_TAB', tab.id);\\n}\\n\\n/**\\n * Save the current editor content.\\n */\\nfunction saveAll() {\\n  sendXhr();\\n  // Prevent the user from interacting with the editor during an async save.\\n  var mask = document.getElementById('editorSavingMask');\\n  mask.style.display = 'block';\\n  saveMaskPid = setTimeout(function() {\\n    mask.style.opacity = 0.2;\\n  }, 1000);  // Wait a second before starting visible transition.\\n}\\n\\nvar saveMaskPid;\\n\\n/**\\n * Send a save request.\\n */\\nfunction sendXhr() {\\n  var pickFightCode = document.getElementById('pickFightTab').editor.getValue();\\n  var proposeMateCode = document.getElementById('proposeMateTab').editor.getValue();\\n  var acceptMateCode = document.getElementById('acceptMateTab').editor.getValue();\\n  var xhr = new XMLHttpRequest();\\n  xhr.open('POST', 'editorXhr');\\n  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\\n  xhr.onload = receiveXhr;\\n  var data =\\n      'selector=' + encodeURIComponent(mouseSelector) +\\n      '&pickFight=' + encodeURIComponent(pickFightCode) +\\n      '&proposeMate=' + encodeURIComponent(proposeMateCode) +\\n      '&acceptMate=' + encodeURIComponent(acceptMateCode);\\n  xhr.send(data);\\n}\\n\\n/**\\n * Got a response from save request.\\n * @this XMLHttpRequest\\n */\\nfunction receiveXhr() {\\n  if (this.status !== 200) {\\n    clearSaveMask();\\n    showButter('Save failed: Status ' + this.status);\\n    return;\\n  }\\n  var data = JSON.parse(this.responseText);\\n  if (data.saved) {\\n    desaturateSave();\\n  }\\n  clearSaveMask();\\n\\n  // If there's a message, show it in the butter.\\n  if (data.butter) {\\n    showButter(data.butter);\\n  }\\n}\\n\\n/**\\n * Remove saving mask that prevents UI interaction.\\n */\\nfunction clearSaveMask() {\\n  clearTimeout(saveMaskPid);\\n  var mask = document.getElementById('editorSavingMask');\\n  mask.style.display = 'none';\\n  mask.style.opacity = 0;\\n}\\n\\n/**\\n * Show the text in the butter bar for five seconds.\\n * Clobber any existing display.\\n * @param {string} text Text to display.\\n */\\nfunction showButter(text) {\\n  clearTimeout(showButter.pid_);\\n  var textDiv = document.getElementById('editorButterText');\\n  textDiv.innerHTML = '';\\n  text = text.split('\\\\n');\\n  for (line of text) {\\n    textDiv.appendChild(document.createTextNode(line));\\n    textDiv.appendChild(document.createElement('br'));\\n  }\\n  document.getElementById('editorButter').style.display = 'block';\\n  showButter.pid_ = setTimeout(hideButter, 5000);\\n}\\n\\nshowButter.pid_ = 0;\\n\\n/**\\n * Hide the butter bar.\\n */\\nfunction hideButter() {\\n  document.getElementById('editorButter').style.display = 'none';\\n}\\n\\n/**\\n * Saturate the editor's save button.\\n * @param {*} e CodeMirror change event.\\n */\\nfunction saturateSave(e) {\\n  document.getElementById('editorSave').classList.add('jfk-button-submit');\\n}\\n\\n/**\\n * Saturate the editor's save button.\\n */\\nfunction desaturateSave() {\\n  document.getElementById('editorSave').classList.remove('jfk-button-submit');\\n}\\n\\n/**\\n * Keydown handler for the editor frame.\\n * @param {!KeyboardEvent} e Keydown event.\\n */\\nfunction keyDown(e) {\\n  // Save the editor if ⌘-s or Ctrl-s is pressed.\\n  if (e.key === 's' && (e.metaKey || e.ctrlKey)) {\\n    saveAll();\\n    e.preventDefault();\\n    e.stopPropagation();\\n  }\\n}\\n\\nfunction init() {\\n  var tab;\\n  tab = document.getElementById('proposeMateTab');\\n  tab.addEventListener('click', tabClick);\\n  tab.container = document.getElementById('proposeMateEditor');\\n  tab.editor = newCodeMirror(tab.container, proposeMateCode);\\n\\n  tab = document.getElementById('acceptMateTab');\\n  tab.addEventListener('click', tabClick);\\n  tab.container = document.getElementById('acceptMateEditor');\\n  tab.editor = newCodeMirror(tab.container, acceptMateCode);\\n\\n  tab = document.getElementById('pickFightTab');\\n  tab.addEventListener('click', tabClick);\\n  tab.container = document.getElementById('pickFightEditor');\\n  tab.editor = newCodeMirror(tab.container, pickFightCode);\\n\\n  tab = document.getElementById('referenceTab');\\n  tab.addEventListener('click', tabClick);\\n  tab.container = document.getElementById('referencePage');\\n\\n  document.getElementById('editorSave').addEventListener('click', saveAll);\\n  document.addEventListener('keydown', keyDown);\\n\\n  // Check for a tab preference.\\n  var tabId = sessionStorage.getItem('GENETIC_TAB') || 'proposeMateTab';\\n  var fakeEvent = {target: document.getElementById(tabId)};\\n  tabClick(fakeEvent);\\n}\\nwindow.addEventListener('load', init);\\n    </script>\\n<%\\nvar mouseSelector = decodeURIComponent(request.query);\\nvar mouse = $(mouseSelector);\\n%>\\n    <script>\\n// <![CDATA[\\nvar mouseSelector = <%= JSON.stringify(mouseSelector) %>;\\nvar pickFightCode = <%= mouse && JSON.stringify(String(mouse.pickFight)) %>;\\nvar proposeMateCode = <%= mouse && JSON.stringify(String(mouse.proposeMate)) %>;\\nvar acceptMateCode = <%= mouse && JSON.stringify(String(mouse.acceptMate)) %>;\\n// ]]>\\n    </script>\\n  </head>\\n\\n  <body>\\n    <div id=\\\"editorButter\\\"><div><div id=\\\"editorButterText\\\"></div></div></div>\\n    <div id=\\\"editorSavingMask\\\"></div>\\n    <div id=\\\"editorButtons\\\">\\n      <button id=\\\"editorSave\\\" class=\\\"jfk-button\\\">Save All</button>\\n    </div>\\n    <div id=\\\"editorHeader\\\"><%= mouse && mouse.name %></div>\\n    <div id=\\\"editorTabs\\\">\\n      <span\\n      class=\\\"jfk-button\\\" role=\\\"button\\\" tabindex=\\\"0\\\" id=\\\"pickFightTab\\\">.pickFight</span><span\\n      class=\\\"spacer\\\"></span><span\\n      class=\\\"jfk-button\\\" role=\\\"button\\\" tabindex=\\\"1\\\" id=\\\"proposeMateTab\\\">.proposeMate</span><span\\n      class=\\\"spacer\\\"></span><span\\n      class=\\\"jfk-button\\\" role=\\\"button\\\" tabindex=\\\"2\\\" id=\\\"acceptMateTab\\\">.acceptMate</span><span\\n      class=\\\"spacer\\\"></span><span\\n      class=\\\"jfk-button\\\" role=\\\"button\\\" tabindex=\\\"3\\\" id=\\\"referenceTab\\\">Reference</span>\\n    </div>\\n    <div id=\\\"editorContainers\\\">\\n      <div id=\\\"pickFightEditor\\\"></div>\\n      <div id=\\\"proposeMateEditor\\\"></div>\\n      <div id=\\\"acceptMateEditor\\\"></div>\\n      <div id=\\\"referencePage\\\">\\n         <p>Properties on the mice:</p>\\n         <dl>\\n           <dt>.generation → integer</dt>\\n           <dd>The initial mice placed in the cage are generation 0.\\n           Their children are generation 1, and so on.</dd>\\n           <dt>.sex → 'M' or 'F' or NaN</dt>\\n           <dd>Generation 0 mice have a sex of NaN, which means they are hermaphrodites\\n           and can be both male and female as needed for any given mating.\\n           Subsequent generations have a sex set randomly at birth to be either \\\"M\\\" or \\\"F\\\".\\n           JavaScript tip: NaN does not equal NaN.</dd>\\n           <dt>.size → integer</dt>\\n           <dd>Larger mice are more likely to win a fight against a smaller mouse.\\n           Generation 0 mice are all 10 cm.  Subsequent births are the average of\\n           their parents' sizes, plus/minus a random variation.</dd>\\n           <dt>.startFertility → integer</dt>\\n           <dd>The total number of attempts a mouse has to produce offspring during its life.\\n            Generation 0 mice all have a startFertility of 4.  Subsequent births\\n            are the average of their parents' fertility, plus/minus a random variation.</dd>\\n           <dt>.fertility → integer</dt>\\n           <dd>The number of remaining attempts a mouse has to produce offspring.\\n            This is set to startFertility at birth, and decrements with every mating attempt.</dd>\\n           <dt>.startAggressiveness → integer</dt>\\n           <dd>The total number of fights a mouse may start during its life.\\n            Generation 0 mice all have a startAggressiveness of 2.  Subsequent births\\n            are the average of their parents' aggressiveness, plus/minus a random variation.</dd>\\n           <dt>.aggressiveness → integer</dt>\\n           <dd>The number of remaining fights a mouse may start.  Generation 0 mice\\n            have their aggressiveness set to 0 (they can't start fights).  Subsequent births\\n            have their aggressiveness set to startAggressiveness, and decrements with every\\n            fight started.</dd>\\n           <dt>.location → cage</dt>\\n           <dd>This is the cage in which the mouse is located.  The cage has a getContents function\\n           that returns an array of all mice.  this.location.getContents() will always include you.</dd>\\n         </dl>\\n         <p>Functions on the mice:</p>\\n         <dl>\\n           <dt>.pickFight → mouse or null</dt>\\n           <dd>Return the mouse you'd like to fight with.\\n           Returning null will pass on this fight and all future ones.\\n           The bigger mouse (based on .size) usually wins, ties are possible.\\n           The loser (if there is one) dies and is removed from the cage.</dd>\\n           <dt>.proposeMate() → mouse or null</dt>\\n           <dd>Return the mouse you'd like to mate with.\\n           Returning null will pass on this mating and all future ones.\\n           Only opposite-sex matings (or those involving a NaN hermaphrodite) will produce a child.\\n           Each proposal decrements fertility by one, regardless of whether mating is successful.</dd>\\n           <dt>.acceptMate(mouse) → boolean</dt>\\n           <dd>The mouse passed in as the first variable wishes to mate with you.\\n           Return true to mate with it, or false to tell it to go away.  Your fertility decrements\\n           by one if you say yes.</dd>\\n           <dt>Ownership</dt>\\n           <dd>The owner of any function can be obtained using Object.getOwnerOf(...).  This\\n           might be used to conduct surveys of the genes currently in the cage, and adjusting\\n           behaviours accordingly.</dd>\\n         </dl>\\n         <p>Lifecycle</p>\\n         <ol>\\n          <li>Each mouse (other than generation 0) is given a number of opportunites to\\n          fight other mice.  The pickFight functions on each mouse are called one by\\n          one as many times as needed.</li>\\n          <li>Each mouse is then given a number of opportunities to mate other mice.\\n          The proposeMate functions on each mouse are called one by one as many times\\n          as needed.  When a mouse returns another mouse it wishes to mate with, that\\n          mouse's acceptMate function is called.  If this call returns true, then a mating\\n          is attempted.</li>\\n          <li>If a mating is successful (proposed mouse says yes, proposed mouse has remaining\\n          fertility, mice have opposite genders or are hermaphrodites), a new mouse is born.\\n          This mouse will inherit traits randomly from its two parents, namely the properties\\n          and the three functions.</li>\\n          <li>Shortly after a mouse has run out of all its opportunities to fight and all\\n          its opportunities to mate, it dies and is remove from the cage.</li>\\n         </ol>\\n         <p>Your mouse will die.  The question is can your genes (functions) spread across the\\n         population.  There are a lot of strategies, have fun!</p>\\n      </div>\\n    </div>\\n  </body>\\n</html>\\n\";\n$.hosts.genetics['/editorXhr'] = {};\nObject.setOwnerOf($.hosts.genetics['/editorXhr'], $.physicals.Neil);\n$.hosts.genetics['/editorXhr'].www = function genetics_editorXhr_www(request, response) {\n  var data = {login: !!request.user, saved: false};\n  try {  // ends with ... finally {response.write(JSON.stringify(data));}\n    if (!request.fromSameOrigin()) {\n      // Security check to ensure this is being loaded by the genetics editor.\n      data.butter = 'Cross-origin referer: ' + String(request.headers.referer);\n      return;\n    }\n    var selector;\n    try {\n      selector = new $.Selector(decodeURIComponent(request.parameters.selector));\n    } catch (e) {\n      data.butter = 'Invalid selector: ' + String(e);\n      return;\n    }\n    if (!request.user) {\n      data.butter = 'User not logged in.';\n      return;\n    }\n    setPerms(request.user);\n    // Populate the (original) value object in the reverse-lookup db.\n    var mouse = selector.toValue(/*save:*/true);\n    if (!$.cage.mousePrototype.isPrototypeOf(mouse)) {\n      data.butter = 'Not a mouse: ' + String(request.parameters.selector);\n      return;\n    }\n\n    // Evaluate src in global scope (eval by any other name, literally).\n    var evalGlobal = eval;\n    var butter = [];\n    var functionNames = ['pickFight', 'proposeMate', 'acceptMate'];\n    for (var i = 0; i < functionNames.length; i++) {\n      var functionName = functionNames[i];\n      var src = request.parameters[functionName];\n      try {\n        suspend();\n        var expr = $.utils.code.rewriteForEval(src, /*forceExpression:*/true);\n        var saveValue = evalGlobal(expr);\n        mouse[functionName] = saveValue;\n      } catch (e) {\n        // TODO(fraser): Send a more informative error message.\n        butter.push(functionName + ': ' + String(e));\n      }\n    }\n    if (butter.length) {\n      data.butter = butter.join('\\n');\n    } else {\n      data.butter = 'Saved';\n      data.saved = true;\n    }\n  } finally {\n    response.write(JSON.stringify(data));\n  }\n};\nObject.setOwnerOf($.hosts.genetics['/editorXhr'].www, $.physicals.Neil);\nObject.setOwnerOf($.hosts.genetics['/editorXhr'].www.prototype, $.physicals.Neil);\n\n$.hosts.root.subdomains.genetics = $.hosts.genetics;\n\n"
  },
  {
    "path": "core/core_44_$.assistant.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Voice-activated assistant demo for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.assistant = (new 'Object.create')($.thing);\n$.assistant.name = 'assistant';\n$.assistant.contents_ = [];\n$.assistant.contents_.forObj = $.assistant;\nObject.defineProperty($.assistant.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.assistant.contents_.forKey = 'contents_';\nObject.defineProperty($.assistant.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.assistant.svgText = '<path class=\"strokeBlack fillGrey\" d=\"m-7.5,75 l-1,20 c0,1.79558 3.80387,3.25 8.5,3.25 c4.69613,0 8.5,-1.45442 8.5,-3.25 l-1-20 z\"/>\\n<ellipse class=\"strokeBlack fillGrey\" cx=\"0\" cy=\"75\" rx=\"7.5\" ry=\"3\"/>';\n$.assistant.onMemo = function onMemo(memo) {\n  if (memo.type !== 'say') return;\n  // Only listen to users, not self or other bots.\n  if (!$.user.isPrototypeOf(memo.source)) return;\n  // Don't respond for 1s after last successful activation.\n  if (!this.lastActivated) this.lastActivated = 0;\n  if (Date.now() - this.lastActivated < 1000) {\n    this.location.narrate(String(this) + ' flashes its lights in confusion.');\n    return;\n  }\n  // Look for activation pharase.\n  var text = memo.text;\n  var activation = new RegExp('^\\\\s*hey[,\\\\s]+' + this.name + '[,:;.!?\\\\s]*([^,:;.!?\\\\s].*)?', 'i');\n  var m = activation.exec(text);\n  if (!m) return;  // Didn't hear \"hello, <name>\".\n  this.lastActivated = Date.now()\n  // Process command.\n  this.onCommand(m[1] || '');\n};\nObject.setOwnerOf($.assistant.onMemo, $.physicals.Maximilian);\n$.assistant.say = function say(speech) {\n  if (!this.location) return;\n  var memo = {\n    type: 'say',\n    source: this,\n    where: this.location,\n    text: speech\n  };\n  this.location.sendMemo(memo);\n};\n$.assistant.onCommand = function onCommand(command) {\n  /* Attempt to find a handler for command, by calling methods on this\n   * named cmd_* until one of them returns true.\n   */\n  suspend(2000);\n  var raw = String(command);\n  command = command.replace(/[.,!?]*$/, '');  // Trim trailing punctuation.\n  command = command.replace(/\\s+/, ' ');  // Normalise whitespace.\n  if (!command) {\n    this.say('How can I help?');\n    return;\n  }\n  // Look for properties on this named 'cmd_<foo>'.\n  var done = false;\n  for (var key in this) {\n    if (key.lastIndexOf('cmd_', 0) !== 0) continue;\n    var func = this[key];\n    if (typeof func !== 'function') continue;\n    if (func.call(this, command, raw)) {\n      done = true;\n      break;\n    }\n  }\n  if (!done) this.say('Sorry, I don\\'t understand \"' + command + '\".');\n};\nObject.setOwnerOf($.assistant.onCommand, $.physicals.Maximilian);\n$.assistant.cmd_time = function cmd_time(command, raw) {\n  // First check to see if the command looked like a request for the time.\n  if (!command.match(/what time is it|what('s| is) the time/i)) return false;\n  // It did.  Tell the time.\n  this.say('The current time is ' + new Date().toTimeString());\n  return true;\n};\nObject.setOwnerOf($.assistant.cmd_time, $.physicals.Maximilian);\nObject.setOwnerOf($.assistant.cmd_time.prototype, $.physicals.Maximilian);\n$.assistant.cmd_translate = function cmd_translate(command, raw) {\n  // First check to see if the command looked like a request to translate some text.\n  var m = raw.match(/(?:what\\s+is|how\\s+do\\s+you\\s+say)\\s+(?:\"([^\"]+)\"|(.*))\\s+in\\s+(\\w+)/i);\n  if (!m) return false;  // Nope; try another handler.\n  // It did.  Try to tranlsate it.\n  var phrase = m[1] || m[2];\n  var code = this.cmd_translate.languages[m[3].toLowerCase()];\n  var language = $.utils.string.capitalize(m[3]);\n  if (!code) {\n    this.say(\"Sorry; I don't know how to speak \" + language);\n    return true;\n  }\n  try {\n    var translation = $.utils.string.translate(phrase, code);\n    this.say('\"' + phrase + '\" in ' + language + ' is \"' + translation + '\"');\n  } catch (e) {\n    this.say('Sorry: I seem to have forotten how to speak ' + language + '.');\n  }\n  return true;\n};\nObject.setOwnerOf($.assistant.cmd_translate, $.physicals.Maximilian);\nObject.setOwnerOf($.assistant.cmd_translate.prototype, $.physicals.Maximilian);\n$.assistant.cmd_translate.languages = (new 'Object.create')(null);\n$.assistant.cmd_translate.languages.german = 'de';\n$.assistant.cmd_translate.languages.italian = 'it';\n$.assistant.cmd_translate.languages.french = 'fr';\n$.assistant._README = 'The assistant works as follows:\\n\\nThe .onMemo handler looks for a \"say\" memo from $.user.  If one is received, and no other has been received too recently, it calls .onCommand, passing it what was said.\\n\\nThe .onCommand handler waits a respectable amount of time (2s) and then attempts to find a handler for the command.  It canonicalises the command, and then iterates through its own and inherited properties.  Any property whose name begins with \"cmd_\" and whose value is a function will get called, being passed the canonicalised and raw command.\\n\\nEach cmd_* method is expected to do some kind of string match against the command (perhaps using a RegExp) to see if if it knows how to handle that sort of command.  If it does, it should respond (perhaps using the .say method to reply to the user) and return true.  If it does not know how to handle the command, it should return false.\\n\\n.onCommand will iterate through the .cmd_* methods until one of them returns true.  If none do it will announce that it did not understand the command.';\n$.assistant.description = \"A squat grey cylinder that looks like it's listening.\";\n\n$.assistant.location = undefined;\n\n$.assistant.lastActivated = undefined;\n\n$.physicals.assistant = $.assistant;\n\n"
  },
  {
    "path": "core/core_45_Challenge_Room.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Challenge room demo for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.physicals['Challenge room'] = (new 'Object.create')($.room);\nObject.setOwnerOf($.physicals['Challenge room'], $.physicals.Neil);\n$.physicals['Challenge room'].name = 'Challenge room';\n$.physicals['Challenge room'].location = null;\n$.physicals['Challenge room'].contents_ = [];\n$.physicals['Challenge room'].contents_[0] = (new 'Object.create')($.thing);\n$.physicals['Challenge room'].contents_[1] = (new 'Object.create')($.container);\n$.physicals['Challenge room'].contents_[2] = (new 'Object.create')($.thing);\n$.physicals['Challenge room'].contents_.forObj = $.physicals['Challenge room'];\nObject.defineProperty($.physicals['Challenge room'].contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.physicals['Challenge room'].contents_.forKey = 'contents_';\nObject.defineProperty($.physicals['Challenge room'].contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.physicals['Challenge room'].reset = function reset(cmd) {\n  this.switch.state = false;\n  this.switch.movable = true;\n  this.switch.moveTo(this);\n  this.switch.movable = false;\n\n  for (var x = 0; x < 1000; x++) {\n    this.safe.setOpen(true, x);\n  }\n  this.food.moveTo(this.safe);\n  this.food.svgText = this.food.svgTextReset;\n  this.safe.setOpen(false);\n  this.safe.crack = this.safe.crackReset;\n\n  this.chest.movable = true;\n  this.chest.moveTo(this);\n  this.chest.movable = false;\n  this.chest.setOpen(true);\n  this.safe.moveTo(this.chest);\n  this.chest.setOpen(false);\n\n  this.girl.movable = true;\n  this.girl.moveTo(this);\n  this.girl.movable = false;\n  this.girl.attempts = 0;\n\n  if (cmd) {\n    this.sendScene(cmd.user, true);\n    this.narrate(cmd.user.name + ' resets ' + String(this) + '.', cmd.user);\n    cmd.user.narrate('You reset ' + String(this) + '.');\n  }\n};\nObject.setOwnerOf($.physicals['Challenge room'].reset, $.physicals.Neil);\nObject.setOwnerOf($.physicals['Challenge room'].reset.prototype, $.physicals.Neil);\n$.physicals['Challenge room'].reset.verb = 'reset';\n$.physicals['Challenge room'].reset.dobj = 'none';\n$.physicals['Challenge room'].reset.prep = 'none';\n$.physicals['Challenge room'].reset.iobj = 'none';\n$.physicals['Challenge room'].chest = $.physicals['Challenge room'].contents_[1];\n$.physicals['Challenge room'].safe = (new 'Object.create')($.container);\n$.physicals['Challenge room'].girl = $.physicals['Challenge room'].contents_[2];\n$.physicals['Challenge room'].food = (new 'Object.create')($.thing);\n$.physicals['Challenge room'].switch = $.physicals['Challenge room'].contents_[0];\n$.physicals['Challenge room'].svgTextNight = '<rect class=\"fillBlack strokeNone\" height=\"100\" width=\"2000\" x=\"-1000\" y=\"0\"/>\\n<line class=\"strokeWhite\" x1=\"-1000\" x2=\"1000\" y1=\"90\" y2=\"90\"/>';\n$.physicals['Challenge room'].getContents = function getContents() {\n  $.physical.validate.call(this);\n  if (this.switch.state) {\n    return this.contents_.slice();\n  } else {\n    var contents = [];\n    for (var i = 0, o; (o = this.contents_[i]); i++) {\n      if (o === this.switch || $.user.isPrototypeOf(o)) {\n        contents.push(o);\n      }\n    }\n    return contents;\n  }\n};\nObject.setOwnerOf($.physicals['Challenge room'].getContents, $.physicals.Neil);\n$.physicals['Challenge room'].description = function description() {\n  return this.switch.state ? 'Can you solve the challenge?' : 'It\\'s dark in here.';\n};\nObject.setOwnerOf($.physicals['Challenge room'].description, $.physicals.Neil);\n$.physicals['Challenge room'].svgTextDay = '<line x1=\"-1000\" y1=\"90\" x2=\"1000\" y2=\"90\" />';\n$.physicals['Challenge room'].svgText = function svgText() {\n  return this.switch.state ? this.svgTextDay : this.svgTextNight;\n};\nObject.setOwnerOf($.physicals['Challenge room'].svgText, $.physicals.Neil);\n\n$.physicals['light switch'] = $.physicals['Challenge room'].switch;\nObject.setOwnerOf($.physicals['light switch'], $.physicals.Neil);\n$.physicals['light switch'].name = 'light switch';\n$.physicals['light switch'].location = $.physicals['Challenge room'];\n$.physicals['light switch'].contents_ = [];\n$.physicals['light switch'].contents_.forObj = $.physicals['light switch'];\nObject.defineProperty($.physicals['light switch'].contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.physicals['light switch'].contents_.forKey = 'contents_';\nObject.defineProperty($.physicals['light switch'].contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.physicals['light switch'].svgText = function svgText() {\n  return this.state ? this.svgTextDay : this.svgTextNight;\n};\nObject.setOwnerOf($.physicals['light switch'].svgText, $.physicals.Neil);\nObject.setOwnerOf($.physicals['light switch'].svgText.prototype, $.physicals.Maximilian);\n$.physicals['light switch'].state = false;\n$.physicals['light switch'].flip = function flip(newState, user) {\n  var onOff = newState ? 'on' : 'off';\n  if (this.state === newState) {\n    user.narrate('The switch is already ' + onOff + '.');\n  } else {\n    this.state = newState;\n    this.home.updateScene(true);\n    user.narrate('You turn ' + onOff + ' the switch.');\n    this.home.narrate(String(user) + ' turns ' + onOff + ' the switch.', user);\n  }\n};\nObject.setOwnerOf($.physicals['light switch'].flip, $.physicals.Neil);\nObject.setOwnerOf($.physicals['light switch'].flip.prototype, $.physicals.Neil);\n$.physicals['light switch'].flipOn1 = function flipOn1(cmd) {\n  this.flip(true, cmd.user);\n};\nObject.setOwnerOf($.physicals['light switch'].flipOn1, $.physicals.Maximilian);\nObject.setOwnerOf($.physicals['light switch'].flipOn1.prototype, $.physicals.Maximilian);\n$.physicals['light switch'].flipOn1.verb = 'flip|turn|switch';\n$.physicals['light switch'].flipOn1.dobj = 'this';\n$.physicals['light switch'].flipOn1.prep = 'on top of/on/onto/upon';\n$.physicals['light switch'].flipOn1.iobj = 'none';\n$.physicals['light switch'].flipOn2 = function flipOn2(cmd) {\n  this.flip(true, cmd.user);\n};\nObject.setOwnerOf($.physicals['light switch'].flipOn2, $.physicals.Maximilian);\nObject.setOwnerOf($.physicals['light switch'].flipOn2.prototype, $.physicals.Maximilian);\n$.physicals['light switch'].flipOn2.verb = 'flip|turn|switch';\n$.physicals['light switch'].flipOn2.dobj = 'none';\n$.physicals['light switch'].flipOn2.prep = 'on top of/on/onto/upon';\n$.physicals['light switch'].flipOn2.iobj = 'this';\n$.physicals['light switch'].flipOff2 = function flipOff2(cmd) {\n  this.flip(false, cmd.user);\n};\nObject.setOwnerOf($.physicals['light switch'].flipOff2, $.physicals.Maximilian);\nObject.setOwnerOf($.physicals['light switch'].flipOff2.prototype, $.physicals.Maximilian);\n$.physicals['light switch'].flipOff2.verb = 'flip|turn|switch';\n$.physicals['light switch'].flipOff2.dobj = 'none';\n$.physicals['light switch'].flipOff2.prep = 'off/off of';\n$.physicals['light switch'].flipOff2.iobj = 'this';\n$.physicals['light switch'].flipOff1 = function flipOff1(cmd) {\n  this.flip(false, cmd.user);\n};\nObject.setOwnerOf($.physicals['light switch'].flipOff1, $.physicals.Maximilian);\nObject.setOwnerOf($.physicals['light switch'].flipOff1.prototype, $.physicals.Maximilian);\n$.physicals['light switch'].flipOff1.verb = 'flip|turn|switch';\n$.physicals['light switch'].flipOff1.dobj = 'this';\n$.physicals['light switch'].flipOff1.prep = 'off/off of';\n$.physicals['light switch'].flipOff1.iobj = 'none';\n$.physicals['light switch'].home = $.physicals['Challenge room'];\n$.physicals['light switch'].svgTextNight = '<g transform=\"scale(0.7) translate(0, 20)\">\\n  <rect class=\"fillGrey\" height=\"25\" width=\"15\" x=\"0\" y=\"30\"/>\\n  <rect class=\"strokeWhite\" height=\"12\" width=\"7\" x=\"4\" y=\"36.5\"/>\\n  <rect class=\"strokeBlack fillBlack\" height=\"5\" width=\"5\" x=\"5\" y=\"42.5\"/>\\n</g>';\n$.physicals['light switch'].getCommands = function getCommands(who) {\n  var commands = $.thing.getCommands.call(this, who);\n  if (this.state) {\n    commands.push('turn off ' + String(this));\n  } else {\n    commands.push('turn on ' + String(this));\n  }\n  return commands;\n};\nObject.setOwnerOf($.physicals['light switch'].getCommands, $.physicals.Neil);\nObject.setOwnerOf($.physicals['light switch'].getCommands.prototype, $.physicals.Maximilian);\n$.physicals['light switch'].aliases = [];\nObject.setOwnerOf($.physicals['light switch'].aliases, $.physicals.Maximilian);\n$.physicals['light switch'].aliases[0] = 'lightswitch';\n$.physicals['light switch'].aliases[1] = 'switch';\n$.physicals['light switch'].movable = false;\n$.physicals['light switch'].svgTextDay = '<g transform=\"scale(0.7) translate(0, 20)\">\\n<rect class=\"fillWhite\" height=\"25\" width=\"15\" x=\"0\" y=\"30\"/>\\n<rect class=\"strokeGrey\" height=\"12\" width=\"7\" x=\"4\" y=\"36.5\"/>\\n<rect class=\"strokeBlack fillBlack\" height=\"5\" width=\"5\" x=\"5\" y=\"37.5\"/>\\n</g>';\n\n$.physicals.chest = $.physicals['Challenge room'].chest;\nObject.setOwnerOf($.physicals.chest, $.physicals.Neil);\n$.physicals.chest.name = 'chest';\n$.physicals.chest.location = $.physicals['Challenge room'];\n$.physicals.chest.contents_ = [];\n$.physicals.chest.contents_[0] = $.physicals.chest.location.safe;\n$.physicals.chest.contents_.forObj = $.physicals.chest;\nObject.defineProperty($.physicals.chest.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.physicals.chest.contents_.forKey = 'contents_';\nObject.defineProperty($.physicals.chest.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.physicals.chest.svgTextClosed = '<path class=\"fillWhite\" d=\"m8.78171,99.14543l12.33676,-7.40208l0,-26.08348l-12.33676,7.40204l0,26.08352z\"/>\\n<rect class=\"fillWhite\" height=\"26.08352\" width=\"42.65004\" x=\"-33.86834\" y=\"73.06191\"/>\\n<path class=\"fillWhite\" d=\"m8.78171,73.06191c0.012,-5.65236 4.56828,-12.11368 8.04808,-12.25748l-42.65004,0c-3.47988,0.14376 -8.03608,6.60512 -8.04808,12.25748l42.65004,0z\"/>\\n<path class=\"fillWhite\" d=\"m8.78171,73.06191c0.012,-5.65236 4.56828,-12.11368 8.04808,-12.25748c2.01644,-0.08336 4.22136,-0.01604 4.28868,4.85544l-12.33676,7.40204z\"/>\\n<rect class=\"fillWhite\" height=\"7.30404\" width=\"5.35632\" x=\"-15.22148\" y=\"70.20479\"/>\\n';\n$.physicals.chest.svgTextOpen = '<rect class=\"fillGrey\" height=\"26.08352\" width=\"42.65004\" x=\"-31.15279\" y=\"65.38134\"/>\\n<path class=\"fillWhite\" d=\"m-0.83951,98.86694l12.33676,-7.40208l0,-26.08348l-12.33676,7.40208l0,26.08348z\"/>\\n<path class=\"fillGrey\" d=\"m-43.48955,72.78346l12.33676,-7.40208l0,26.08348l-12.33676,7.40208l0,-26.08348z\"/>\\n<path class=\"fillGrey\" d=\"m-31.15279,65.38134l42.65004,0m0,0l-10.5744,-17.624l-42.65004,0l10.5744,17.624\"/>\\n<path class=\"fillWhite\" d=\"m0.92285,47.75738c11.34116,-0.37904 15.45816,10.68644 10.5744,17.624l-10.5744,-17.624z\"/>\\n<path class=\"fillGrey\" d=\"m-41.72719,47.75738c11.34116,-0.37904 15.45816,10.68644 10.5744,17.624l-10.5744,-17.624z\"/>\\n<rect class=\"fillWhite\" height=\"26.08352\" width=\"42.65004\" x=\"-43.48956\" y=\"72.78346\"/>\\n';\n$.physicals.chest.isOpen = false;\n$.physicals.chest.description = 'A steamer chest with a very heavy lid.';\n$.physicals.chest.TIME = 5000;\n$.physicals.chest.lastTime_ = 1597444509970;\n$.physicals.chest.lastUser_ = $.physicals.Neil;\n$.physicals.chest.open = function open(cmd) {\n  if (this.isOpen) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already open.');\n    return;\n  }\n  if (this.location !== cmd.user.location && this.location !== cmd.user) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.');\n    return;\n  }\n  if (this.lastUser_ === cmd.user || this.lastTime_ + this.TIME < Date.now()) {\n    cmd.user.narrate('You try to open the chest, but the lid is too heavy for one person.');\n    if (cmd.user.location) {\n      cmd.user.location.narrate(String(cmd.user) + ' tries to open the chest, but the lid is too heavy for one person.', cmd.user);\n    }\n    this.lastUser_ = cmd.user;\n    this.lastTime_ = Date.now();\n    return;\n  }\n  if (!this.setOpen(true)) {\n    cmd.user.narrate('You can\\'t open ' + String(cmd.dobj));\n    return;\n  }\n  if (cmd.user.location) {\n    cmd.user.location.narrate(String(cmd.user) + ' helps ' + String(this.lastUser_.name) + ' to opens ' + String(cmd.dobj) + '.', cmd.user);\n  }\n  cmd.user.narrate('You help ' + String(this.lastUser_) + ' to open ' + String(cmd.dobj) + '.');\n  this.look(cmd);\n  this.lastUser_ = null;\n  this.lastTime_ = 0;\n};\nObject.setOwnerOf($.physicals.chest.open, $.physicals.Neil);\nObject.setOwnerOf($.physicals.chest.open.prototype, $.physicals.Maximilian);\n$.physicals.chest.open.verb = 'open';\n$.physicals.chest.open.dobj = 'this';\n$.physicals.chest.open.prep = 'none';\n$.physicals.chest.open.iobj = 'none';\n$.physicals.chest.movable = false;\n$.physicals.chest.toFloor = true;\n$.physicals.chest.setOpen = function setOpen(newState) {\n  this.isOpen = Boolean(newState);\n  if ($.room.isPrototypeOf(this.location)) {\n    this.location.updateScene(true);\n  }\n  return true;\n};\nObject.setOwnerOf($.physicals.chest.setOpen, $.physicals.Neil);\nObject.setOwnerOf($.physicals.chest.setOpen.prototype, $.physicals.Maximilian);\n\n$.physicals.safe = $.physicals.chest.location.safe;\nObject.setOwnerOf($.physicals.safe, $.physicals.Neil);\n$.physicals.safe.name = 'safe';\n$.physicals.safe.location = $.physicals.chest;\n$.physicals.safe.contents_ = [];\n$.physicals.safe.contents_[0] = $.physicals.chest.location.food;\n$.physicals.safe.contents_.forObj = $.physicals.safe;\nObject.defineProperty($.physicals.safe.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.physicals.safe.contents_.forKey = 'contents_';\nObject.defineProperty($.physicals.safe.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.physicals.safe.isOpen = false;\n$.physicals.safe.description = 'The safe is secured with a three digit combination: open safe with xxx';\n$.physicals.safe.open = function open(cmd) {\n  cmd.user.narrate('You need a three-digit combination to open the safe:  open ' + String(cmd.dobj) + ' with xxx');\n};\nObject.setOwnerOf($.physicals.safe.open, $.physicals.Maximilian);\nObject.setOwnerOf($.physicals.safe.open.prototype, $.physicals.Maximilian);\n$.physicals.safe.open.verb = 'open';\n$.physicals.safe.open.dobj = 'this';\n$.physicals.safe.open.prep = 'none';\n$.physicals.safe.open.iobj = 'none';\n$.physicals.safe.openWith = function openWith(cmd) {\n  if (this.isOpen) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already open.');\n    return;\n  }\n  if (this.location !== cmd.user.location && this.location !== cmd.user) {\n    cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.');\n    return;\n  }\n  if (!this.setOpen(true, cmd.iobjstr)) {\n    cmd.user.narrate('\"' + cmd.iobjstr + '\" is not the correct combination.');\n    return;\n  }\n  if (cmd.user.location) {\n    cmd.user.location.narrate(cmd.user.name + ' opens ' + String(cmd.dobj) + '.', cmd.user);\n  }\n  cmd.user.narrate('You open ' + String(cmd.dobj) + '.');\n  this.look(cmd);\n};\nObject.setOwnerOf($.physicals.safe.openWith, $.physicals.Maximilian);\nObject.setOwnerOf($.physicals.safe.openWith.prototype, $.physicals.Maximilian);\n$.physicals.safe.openWith.verb = 'open';\n$.physicals.safe.openWith.dobj = 'this';\n$.physicals.safe.openWith.prep = 'with/using';\n$.physicals.safe.openWith.iobj = 'any';\n$.physicals.safe.setOpen = function setOpen(newState, combo) {\n  if (newState && this.combo !== $.utils.string.hash('md5', String(combo))) {\n    return false;\n  }\n  return $.container.setOpen.call(this, newState);\n};\nObject.setOwnerOf($.physicals.safe.setOpen, $.physicals.Neil);\nObject.setOwnerOf($.physicals.safe.setOpen.prototype, $.physicals.Maximilian);\n$.physicals.safe.combo = 'e94550c93cd70fe748e6982b3439ad3b';\n$.physicals.safe.svgTextClosed = '<path class=\"fillWhite\" d=\"m0,80l10,-10l20,0l0,20l-10,10\"/>\\n<line x1=\"20\" x2=\"30\" y1=\"80\" y2=\"70\"/>\\n<rect class=\"fillWhite\" height=\"20\" width=\"20\" x=\"0\" y=\"80\"/>\\n<circle class=\"fillWhite\" cx=\"10\" cy=\"90\" fill-opacity=\"null\" r=\"4\"/>\\n<circle class=\"fillWhite\" cx=\"10\" cy=\"90\" fill-opacity=\"null\" r=\"2\"/>';\n$.physicals.safe.svgTextOpen = '<rect class=\"fillGrey\" height=\"20\" width=\"20\" x=\"0\" y=\"65\"/>\\n<path class=\"fillGrey\" d=\"m0,85l-10,10l0,-20l10,-10l0,20z\"/>\\n<path class=\"fillWhite\" d=\"m0,65l-10,10l20,0l10,-10l-20,0z\"/>\\n<path class=\"fillGrey\" d=\"m0,85l-10,10l20,0l10,-10l-20,0z\"/>\\n<path class=\"fillWhite\" d=\"m20,85l-10,10l0,-20l10,-10l0,20z\"/>\\n<path class=\"fillWhite\" d=\"m-10,95l-12.5,4.5l0,-20l12.5,-4.5l0,20z\"/>';\n$.physicals.safe.getCommands = function getCommands(who) {\n  var commands = $.container.getCommands.call(this, who);\n  commands.push('crack ' + String(this));\n  return commands;\n};\nObject.setOwnerOf($.physicals.safe.getCommands, $.physicals.Neil);\nObject.setOwnerOf($.physicals.safe.getCommands.prototype, $.physicals.Maximilian);\n$.physicals.safe.crack = function crack(cmd) {\n  cmd.user.narrate('The \"crack\" function has not been programmed.  ' +\n     'To do so, visit: https://google.codecity.world/blocklySafe');\n  // API information: To open the safe with combo 123, use:\n  //   this.setOpen(true, 123);\n  // Have fun!\n\n};\nObject.setOwnerOf($.physicals.safe.crack, $.physicals.Neil);\nObject.setOwnerOf($.physicals.safe.crack.prototype, $.physicals.Neil);\n$.physicals.safe.crack.verb = 'crack';\n$.physicals.safe.crack.dobj = 'this';\n$.physicals.safe.crack.prep = 'none';\n$.physicals.safe.crack.iobj = 'none';\n$.physicals.safe.crackReset = $.physicals.safe.crack;\n$.physicals.safe.toFloor = true;\n\n$.physicals.food = $.physicals.chest.location.food;\nObject.setOwnerOf($.physicals.food, $.physicals.Neil);\n$.physicals.food.name = 'food';\n$.physicals.food.location = $.physicals.safe;\n$.physicals.food.contents_ = [];\n$.physicals.food.contents_.forObj = $.physicals.food;\nObject.defineProperty($.physicals.food.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.physicals.food.contents_.forKey = 'contents_';\nObject.defineProperty($.physicals.food.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.physicals.food.svgText = '<path d=\"M-7,80L-5,97C-5,100.5,5,100.5,5,97L7,80\" class=\"fillWhite\"/>\\n<ellipse class=\"fillWhite\" cx=\"0\" cy=\"80\" rx=\"7\" ry=\"3\"/>\\n';\n$.physicals.food.give = function give(cmd) {\n  if (cmd.iobj !== this.girl) {\n    return $.thing.give.call(this, cmd);\n  }\n  if (this.location !== cmd.user && this.location !== cmd.user.location) {\n    cmd.user.narrate(\"You can't reach \" + String(this) + \".\");\n    return;\n  }\n\n  cmd.user.narrate('You offer ' + String(this) + ' to ' + String(cmd.iobj) + '.');\n  if (cmd.user.location) {\n    cmd.user.location.narrate(\n        String(cmd.user) + ' offers ' + String(this) + ' to ' + String(cmd.iobj) + '.',\n        [cmd.user, cmd.iobj]);\n  }\n  var matches = $.utils.imageMatch.recog($.utils.object.getValue(this, 'svgText'));\n  var ok = this.girl.foodList.includes(matches[0]);\n  if (!ok) {\n    this.girl.attempts++;\n  }\n\n  var name = matches[0] || 'nothing I\\'ve ever seen before.';\n  suspend(1);\n\n  var text = 'It looks like a ' + name + '; ' +\n      (ok ? 'delicious!'\n       : (this.girl.attempts < 3 ?\n          'I won\\'t eat that!' :\n          (Math.random() >= 0.5 ?\n           'that won\\'t keep the doctor away!' : 'some fruit would be nice!'\n          )\n         )\n      );\n\n  var alt = 'The girl says, \"' + text +'\"';\n  var memo = {\n    type: 'say',\n    source: this.girl,\n    where: this.girl.location,\n    text: text,\n    alt: alt\n  };\n  this.girl.location.sendMemo(memo);\n  if (ok) {\n    suspend(10);\n    memo.text = 'Thank you so much.  Congratulations on solving the challenge room.  Don\\'t forget to turn out the light when you leave.';\n    memo.alt = 'The girl says, \"' + text + '\"';\n    this.girl.location.sendMemo(memo);\n  }\n};\nObject.setOwnerOf($.physicals.food.give, $.physicals.Neil);\nObject.setOwnerOf($.physicals.food.give.prototype, $.physicals.Maximilian);\n$.physicals.food.give.verb = 'give';\n$.physicals.food.give.dobj = 'this';\n$.physicals.food.give.prep = 'at/to';\n$.physicals.food.give.iobj = 'any';\n$.physicals.food.girl = $.physicals.chest.location.girl;\n$.physicals.food.redraw = function inspect(cmd) {\n  // Open this object in the SVG editor.\n  var selector = $.Selector.for(this);\n  if (!selector) {\n    cmd.user.narrate('Unfortuantely the code editor does not know how to locate ' + String(this) + ' yet.');\n    return;\n  }\n  var link = '/code?' + encodeURIComponent(String(selector) + '.svgText');\n  cmd.user.readMemo({type: \"link\", href: link});\n};\nObject.setOwnerOf($.physicals.food.redraw, $.physicals.Neil);\nObject.setOwnerOf($.physicals.food.redraw.prototype, $.physicals.Neil);\n$.physicals.food.redraw.verb = 'redraw';\n$.physicals.food.redraw.dobj = 'this';\n$.physicals.food.redraw.prep = 'none';\n$.physicals.food.redraw.iobj = 'none';\n$.physicals.food.getCommands = function getCommands(who) {\n  var commands = $.thing.getCommands.call(this, who);\n  commands.push('redraw ' + this.name);\n  commands.push('give ' + this.name + ' to girl');\n  return commands;\n};\nObject.setOwnerOf($.physicals.food.getCommands, $.physicals.Neil);\nObject.setOwnerOf($.physicals.food.getCommands.prototype, $.physicals.Maximilian);\n$.physicals.food.svgTextReset = '<path d=\"M-7,80L-5,97C-5,100.5,5,100.5,5,97L7,80\" class=\"fillWhite\"/>\\n<ellipse class=\"fillWhite\" cx=\"0\" cy=\"80\" rx=\"7\" ry=\"3\"/>\\n';\n\n$.physicals.girl = $.physicals.food.girl;\nObject.setOwnerOf($.physicals.girl, $.physicals.Neil);\n$.physicals.girl.name = 'girl';\n$.physicals.girl.location = $.physicals.chest.location;\n$.physicals.girl.contents_ = [];\n$.physicals.girl.contents_.forObj = $.physicals.girl;\nObject.defineProperty($.physicals.girl.contents_, 'forObj', {writable: false, enumerable: false, configurable: false});\n$.physicals.girl.contents_.forKey = 'contents_';\nObject.defineProperty($.physicals.girl.contents_, 'forKey', {writable: false, enumerable: false, configurable: false});\n$.physicals.girl.description = 'She looks REALLY hungry.';\n$.physicals.girl.svgText = '    <path class=\"strokeBlack fillWhite\" d=\"m2.453,58.76115c0.73095,3.31014 -2.35649,7.10927 -5.354,8.76109c-3.17381,1.74899 -7.60044,1.39996 -10.87024,-0.16224c-3.89018,-1.8586 -4.25816,-7.46777 -1.78467,-11.27585c4.68192,-6.68127 17.99054,-3.7308 18.00891,2.677z\"/>\\n    <path class=\"strokeBlack\" d=\"m-16.09721,99.2163c3.36481,-7.19263 6.5246,-13.66499 10.11895,-18.35067\"/>\\n    <path class=\"strokeBlack\" d=\"m-0.44477,99.64677c-9.09273,-22.01297 -4.01634,-23.24778 -4.74121,-31.69803\"/>\\n    <path class=\"strokeBlack\" d=\"m-13.91994,82.09774c2.68081,-3.84038 5.03799,-6.45099 8.73396,-14.149\"/>\\n    <path class=\"strokeBlack\" d=\"m0.06683,83.05226c-1.60238,-5.21011 -3.01935,-10.5245 -5.25281,-15.10352\"/>\\n    <path d=\"m-14.01461,54.54284c0.75415,1.15486 2.0631,1.98765 3.24485,2.67701c0.47974,0.27984 0.94301,0.68546 1.46019,0.89233c0.31757,0.12703 0.65772,0.19293 0.97345,0.32448c1.07714,0.44881 2.08283,1.16779 3.24485,1.37907c0.13302,0.02418 0.27123,-0.01492 0.40561,0c0.38566,0.04285 0.77922,0.24336 1.13569,0.24336\"/>\\n    <path d=\"m-5.9836,52.51481c0.74483,-0.31304 1.53299,-0.30212 2.27139,-0.48672c0.15429,-0.03857 0.42557,0.07114 0.56785,0c0.12707,-0.06354 0.48109,-0.16506 0.64897,-0.08112c0.14832,0.07416 0.35064,0.22242 0.48673,0.32448c0.43016,0.32262 0.44211,0.88422 0.64897,1.29794c0.03303,0.06607 0.08112,0.58378 0.08112,0.40561\"/>\\n    <path d=\"m1.31731,62.33048c0.43264,0.45969 1.2145,0.75334 1.29794,1.37906c0.06323,0.4742 -0.6672,0.68707 -0.97346,1.05458c-0.10094,0.12113 -0.18125,0.26068 -0.24336,0.40561c-0.29413,0.68629 1.28191,-0.86126 1.05457,0.73009c-0.06209,0.43463 -0.21269,0.45803 -0.16224,0.81121c0.03529,0.24702 0.29281,0.64509 0.24336,0.89233c-0.06369,0.31844 -0.29802,0.38001 -0.4056,0.64897c-0.09622,0.24055 0.10639,0.37236 0.16224,0.56785c0.06686,0.234 0.04773,0.49145 0,0.73009c-0.02668,0.13339 -0.264,0.52658 -0.16224,0.73009c0.15102,0.30205 0.24336,0.5276 0.24336,0.89234\"/>\\n    <path d=\"m-0.224,64.03403c-0.10816,1.5413 -0.35309,3.07908 -0.32448,4.62391c0.0054,0.28999 0.79206,-0.74774 0.97345,-0.32448c0.06479,0.15118 0.0122,0.33738 0.08112,0.48672c0.26892,0.58265 0.56113,0.66686 1.05458,1.05458c0.16606,0.13048 0.35707,0.2389 0.48672,0.40561c0.39433,0.50698 -0.33175,0.90203 -0.56784,1.21681c-0.01622,0.02164 0.01913,0.062 0,0.08112c-0.01913,0.01913 -0.10574,0.01119 -0.08112,0c0.32001,-0.14546 0.64897,-0.2704 0.97345,-0.4056\"/>\\n    <path d=\"m-12.31106,54.3806c0.10816,0.78417 0.15276,1.57977 0.32448,2.35252c0.14503,0.65262 0.78935,1.03271 1.21682,1.46018c0.89247,0.89247 1.60741,2.10315 2.83925,2.59588c0.52708,0.21083 1.08387,0.32516 1.62242,0.48673c0.13948,0.04184 0.26282,0.13368 0.40561,0.16224c0.208,0.0416 0.44096,-0.0416 0.64897,0c0.05929,0.01185 0.1026,0.07118 0.16224,0.08112c0.74304,0.12384 1.98436,-0.17316 2.677,0c0.2974,0.07435 0.57553,0.24336 0.89233,0.24336\"/>\\n    <path d=\"m-9.55294,52.59594c0.84943,1.18919 1.80426,3.05911 3.16373,4.05606c0.63617,0.46652 1.49601,0.62632 2.19027,0.97345c0.5421,0.27105 1.04109,0.69855 1.62243,0.89234c0.1308,0.0436 0.2748,0.03752 0.40561,0.08112c0.02837,0.0095 1.28554,0.55545 1.29793,0.56784c0.01913,0.01913 -0.02704,0.08112 0,0.08112c0.02704,0 0,-0.05408 0,-0.08112\"/>\\n    <path d=\"m-5.9836,52.51481c1.12593,1.36843 2.49316,2.58149 3.97494,3.56934c0.48793,0.32528 1.36995,0.8021 1.78466,1.21682c0.33582,0.33581 0.60781,0.77004 0.89234,1.05457\"/>\\n    <path d=\"m-11.33761,53.08266c1.71049,2.44802 3.93723,3.65235 6.24634,5.19176c0.14712,0.09808 1.56809,1.18927 1.62242,1.29794c0.02418,0.04837 -0.03824,0.124 0,0.16224c0.08847,0.08847 0.28927,0.20814 0.40561,0.32449c0.05408,0.05408 0.23796,0.17306 0.16224,0.16224c-0.22074,-0.03153 -0.43264,-0.10816 -0.64897,-0.16224\"/>\\n    <path d=\"m-10.73298,52.87959c0.89005,0.11134 1.65855,0.54411 2.35602,0.91623c0.73717,0.3933 1.519,0.72961 2.19895,1.28272c0.68926,0.56068 1.27485,1.23876 1.88482,1.88482c0.62557,0.66258 0.9644,1.39162 1.58189,1.95096l0.35249,0.66021l0.56998,0.67853\"/>\\n    <path d=\"m-11.51833,53.9267c0.31414,0.81536 1.01217,1.3372 1.71972,1.88482c0.68395,0.52935 1.34166,1.11774 2.10227,1.52496c0.75403,0.40369 1.63512,0.53793 2.48691,0.83665c0.81962,0.28743 1.57976,0.69046 2.35602,0.98922c0.79129,0.30455 1.49215,0.80729 2.34363,1.06204l0.58412,0.50859\"/>\\n    <path d=\"m-7.32985,52.6178c0.99476,0.3637 1.84934,0.61397 2.46191,1.13805c0.72862,0.62335 1.26086,1.25095 1.83128,1.95759c0.56185,0.69602 0.9057,1.57104 1.36405,2.29703c0.4745,0.75157 0.87135,1.49733 0.88726,2.35602c0.01697,0.91607 -0.45528,1.8844 0.00118,2.70755c0.39036,0.70396 1.73213,0.62234 2.07072,1.39856c0.35303,0.80931 -0.24322,1.61348 -0.62666,2.41222c-0.3626,0.75533 -0.23298,1.59712 0.13922,2.23891c0.41908,0.72262 0.24799,1.68778 -0.17086,2.24032l-0.36645,0.42164\"/>\\n    <path d=\"m-4.18849,53.14136c1.04712,0.30541 1.68764,0.85101 2.43455,1.38744c0.69793,0.50125 1.39936,1.12401 1.49215,1.95497c0.10322,0.92445 0.05804,1.80531 0,2.70855c-0.05579,0.86819 -0.58125,1.83307 -0.20942,2.30401c0.54283,0.68753 1.93388,0.40047 2.29424,1.17382c0.37992,0.81533 -0.14714,1.82877 -0.77592,2.46946c-0.60234,0.61375 -1.59314,0.68797 -2.20663,1.30017c-0.51848,0.51739 0.27888,1.25655 1.02862,1.75938l0.41501,0.67133l0.23944,0.80663l0,0.8726\"/>\\n    <path d=\"m-8.11519,53.66492c1.07749,0 1.99914,0.03017 2.75415,0.39812c0.79851,0.38915 1.5245,0.88042 2.20589,1.42055c0.66151,0.52436 1.28744,1.11145 1.90419,1.55266c0.68114,0.48727 1.46063,0.84077 1.77334,1.51017c0.3778,0.80873 -0.04902,1.79345 0.26414,2.54066c0.28977,0.6914 0.73924,1.32269 0.9346,2.16178c0.20276,0.87092 -0.41037,1.95579 0.11134,2.6274c0.28441,0.36613 0.90021,0.90364 1.03216,1.74153c0.13587,0.86279 0.01492,1.78007 -0.41627,2.46191l-0.3541,0.69324l0,0.87627\"/>\\n    <path d=\"m-10.73299,53.9267c1.07714,0 1.96335,0 2.87958,0c0.87627,0 1.65156,0.3908 2.43338,0.52356c0.88278,0.14991 1.795,-0.15591 2.67134,0c0.74723,0.13295 1.48342,0.52356 2.31863,0.61588l0.69184,0.39943\"/>\\n    <path d=\"m-10.99477,54.45026c0.91623,0 1.79642,-0.13239 2.69633,0c0.79007,0.11623 1.67562,0.02064 2.53927,0.26178c0.76641,0.21399 1.41629,0.85779 2.0199,1.33124c0.61388,0.48152 1.47675,0.50122 2.35567,0.50122c0.91802,0 1.83448,-0.05702 2.43617,0.39267c0.55872,0.41758 0.51811,1.34747 0.51811,2.2401c0,0.88172 0.34046,1.55133 0.74171,2.29742c0.38559,0.71698 0.56579,1.50296 0.56719,2.41344c0.0013,0.84869 0,1.76632 0,2.65637c0,0.89005 0,1.78011 0,2.66737l0.22997,0.68342\"/>\\n    <path d=\"m-12.30367,54.71204c0.51693,0.63491 1.08044,1.19886 1.58565,1.74014c0.52846,0.5662 0.98368,1.23125 1.56235,1.81344c0.59642,0.60005 1.25942,1.18218 1.93717,1.42024c0.85293,0.29959 1.6166,0.34467 2.30262,0.52356c0.81872,0.2135 1.74605,0.10109 2.42897,0.52356c0.64377,0.39825 1.26623,1.01143 1.43861,1.75511c0.2007,0.86587 -0.00998,1.77671 -0.16828,2.60284c-0.16169,0.84379 -0.51695,1.63445 -0.3541,2.50628c0.13298,0.71191 0.52321,1.43839 0.6349,2.28866l0.19407,0.75114l0.40558,0.56718l0.33613,0.61588\"/>\\n';\n$.physicals.girl.get = function get(cmd) {\n  cmd.user.narrate('That\\'s probably not appropriate.');\n  if (cmd.user.location) {\n    cmd.user.location.narrate(String(cmd.user) + ' tries to pick up ' + String(this) + '.', cmd.user);\n  }\n};\nObject.setOwnerOf($.physicals.girl.get, $.physicals.Neil);\nObject.setOwnerOf($.physicals.girl.get.prototype, $.physicals.Maximilian);\n$.physicals.girl.get.verb = 'get|take';\n$.physicals.girl.get.dobj = 'this';\n$.physicals.girl.get.prep = 'none';\n$.physicals.girl.get.iobj = 'none';\n$.physicals.girl.food = $.physicals.food;\n$.physicals.girl.foodList = [];\n$.physicals.girl.foodList[0] = 'Açaí';\n$.physicals.girl.foodList[1] = 'Ackee';\n$.physicals.girl.foodList[2] = 'Apple';\n$.physicals.girl.foodList[3] = 'Apricot';\n$.physicals.girl.foodList[4] = 'Avocado';\n$.physicals.girl.foodList[5] = 'Banana';\n$.physicals.girl.foodList[6] = 'Bilberry';\n$.physicals.girl.foodList[7] = 'Blackberry';\n$.physicals.girl.foodList[8] = 'Blackcurrant';\n$.physicals.girl.foodList[9] = 'Black sapote';\n$.physicals.girl.foodList[10] = 'Blueberry';\n$.physicals.girl.foodList[11] = 'Boysenberry';\n$.physicals.girl.foodList[12] = 'Breadfruit';\n$.physicals.girl.foodList[13] = \"Buddha's hand\";\n$.physicals.girl.foodList[14] = 'Cactus pear';\n$.physicals.girl.foodList[15] = 'Crab apple';\n$.physicals.girl.foodList[16] = 'Currant';\n$.physicals.girl.foodList[17] = 'Cherry';\n$.physicals.girl.foodList[18] = 'Cherimoya';\n$.physicals.girl.foodList[19] = 'Chico fruit';\n$.physicals.girl.foodList[20] = 'Cloudberry';\n$.physicals.girl.foodList[21] = 'Coconut';\n$.physicals.girl.foodList[22] = 'Cranberry';\n$.physicals.girl.foodList[23] = 'Damson';\n$.physicals.girl.foodList[24] = 'Date';\n$.physicals.girl.foodList[25] = 'Dragonfruit';\n$.physicals.girl.foodList[26] = 'Durian';\n$.physicals.girl.foodList[27] = 'Elderberry';\n$.physicals.girl.foodList[28] = 'Feijoa';\n$.physicals.girl.foodList[29] = 'Fig';\n$.physicals.girl.foodList[30] = 'Goji berry';\n$.physicals.girl.foodList[31] = 'Gooseberry';\n$.physicals.girl.foodList[32] = 'Grape';\n$.physicals.girl.foodList[33] = 'Grewia asiatica';\n$.physicals.girl.foodList[34] = 'Raisin';\n$.physicals.girl.foodList[35] = 'Grapefruit';\n$.physicals.girl.foodList[36] = 'Guava';\n$.physicals.girl.foodList[37] = 'Hala Fruit';\n$.physicals.girl.foodList[38] = 'Honeyberry';\n$.physicals.girl.foodList[39] = 'Huckleberry';\n$.physicals.girl.foodList[40] = 'Jabuticaba';\n$.physicals.girl.foodList[41] = 'Jackfruit';\n$.physicals.girl.foodList[42] = 'Jambul';\n$.physicals.girl.foodList[43] = 'Japanese plum';\n$.physicals.girl.foodList[44] = 'Jostaberry';\n$.physicals.girl.foodList[45] = 'Jujube';\n$.physicals.girl.foodList[46] = 'Juniper berry';\n$.physicals.girl.foodList[47] = 'Kiwano';\n$.physicals.girl.foodList[48] = 'Kiwifruit';\n$.physicals.girl.foodList[49] = 'Kumquat';\n$.physicals.girl.foodList[50] = 'Lemon';\n$.physicals.girl.foodList[51] = 'Lime';\n$.physicals.girl.foodList[52] = 'Loganberry';\n$.physicals.girl.foodList[53] = 'Loquat';\n$.physicals.girl.foodList[54] = 'Longan';\n$.physicals.girl.foodList[55] = 'Lychee';\n$.physicals.girl.foodList[56] = 'Mango';\n$.physicals.girl.foodList[57] = 'Mangosteen';\n$.physicals.girl.foodList[58] = 'Marionberry';\n$.physicals.girl.foodList[59] = 'Melon';\n$.physicals.girl.foodList[60] = 'Cantaloupe';\n$.physicals.girl.foodList[61] = 'Galia melon';\n$.physicals.girl.foodList[62] = 'Honeydew';\n$.physicals.girl.foodList[63] = 'Watermelon';\n$.physicals.girl.foodList[64] = 'Miracle fruit';\n$.physicals.girl.foodList[65] = 'Monstera Delisiousa';\n$.physicals.girl.foodList[66] = 'Mulberry';\n$.physicals.girl.foodList[67] = 'Nance';\n$.physicals.girl.foodList[68] = 'Nectarine';\n$.physicals.girl.foodList[69] = 'Orange';\n$.physicals.girl.foodList[70] = 'Blood orange';\n$.physicals.girl.foodList[71] = 'Clementine';\n$.physicals.girl.foodList[72] = 'Mandarine';\n$.physicals.girl.foodList[73] = 'Tangerine';\n$.physicals.girl.foodList[74] = 'Papaya';\n$.physicals.girl.foodList[75] = 'Passionfruit';\n$.physicals.girl.foodList[76] = 'Peach';\n$.physicals.girl.foodList[77] = 'Pear';\n$.physicals.girl.foodList[78] = 'Persimmon';\n$.physicals.girl.foodList[79] = 'Plantain';\n$.physicals.girl.foodList[80] = 'Plum';\n$.physicals.girl.foodList[81] = 'Prune';\n$.physicals.girl.foodList[82] = 'Pineapple';\n$.physicals.girl.foodList[83] = 'Pineberry';\n$.physicals.girl.foodList[84] = 'Plumcot';\n$.physicals.girl.foodList[85] = 'Pomegranate';\n$.physicals.girl.foodList[86] = 'Pomelo';\n$.physicals.girl.foodList[87] = 'Purple mangosteen';\n$.physicals.girl.foodList[88] = 'Quince';\n$.physicals.girl.foodList[89] = 'Raspberry';\n$.physicals.girl.foodList[90] = 'Salmonberry';\n$.physicals.girl.foodList[91] = 'Rambutan';\n$.physicals.girl.foodList[92] = 'Redcurrant';\n$.physicals.girl.foodList[93] = 'Salal berry';\n$.physicals.girl.foodList[94] = 'Salak';\n$.physicals.girl.foodList[95] = 'Satsuma';\n$.physicals.girl.foodList[96] = 'Soursop';\n$.physicals.girl.foodList[97] = 'Star apple';\n$.physicals.girl.foodList[98] = 'Star fruit';\n$.physicals.girl.foodList[99] = 'Strawberry';\n$.physicals.girl.foodList[100] = 'Surinam cherry';\n$.physicals.girl.foodList[101] = 'Tamarillo';\n$.physicals.girl.foodList[102] = 'Tamarind';\n$.physicals.girl.foodList[103] = 'Tangelo';\n$.physicals.girl.foodList[104] = 'Tayberry';\n$.physicals.girl.foodList[105] = 'Ugli fruit';\n$.physicals.girl.foodList[106] = 'White currant';\n$.physicals.girl.foodList[107] = 'White sapote';\n$.physicals.girl.foodList[108] = 'Yuzu';\n$.physicals.girl.foodList[109] = 'Bell pepper';\n$.physicals.girl.foodList[110] = 'Chile pepper';\n$.physicals.girl.foodList[111] = 'Corn kernel';\n$.physicals.girl.foodList[112] = 'Cucumber';\n$.physicals.girl.foodList[113] = 'Eggplant';\n$.physicals.girl.foodList[114] = 'Jalapeño';\n$.physicals.girl.foodList[115] = 'Olive';\n$.physicals.girl.foodList[116] = 'Pea';\n$.physicals.girl.foodList[117] = 'Pumpkin';\n$.physicals.girl.foodList[118] = 'Squash';\n$.physicals.girl.foodList[119] = 'Tomato';\n$.physicals.girl.foodList[120] = 'Zucchini';\n$.physicals.girl.foodList[121] = 'asparagus';\n$.physicals.girl.foodList[122] = 'apple';\n$.physicals.girl.foodList[123] = 'avocado';\n$.physicals.girl.foodList[124] = 'alfalfa';\n$.physicals.girl.foodList[125] = 'almond';\n$.physicals.girl.foodList[126] = 'arugula';\n$.physicals.girl.foodList[127] = 'artichoke';\n$.physicals.girl.foodList[128] = 'applesauce';\n$.physicals.girl.foodList[129] = 'antelope';\n$.physicals.girl.foodList[130] = 'bruscetta';\n$.physicals.girl.foodList[131] = 'bacon';\n$.physicals.girl.foodList[132] = 'black beans';\n$.physicals.girl.foodList[133] = 'bagels';\n$.physicals.girl.foodList[134] = 'baked beans';\n$.physicals.girl.foodList[135] = 'bbq';\n$.physicals.girl.foodList[136] = 'bison';\n$.physicals.girl.foodList[137] = 'barley';\n$.physicals.girl.foodList[138] = 'beer';\n$.physicals.girl.foodList[139] = 'bisque';\n$.physicals.girl.foodList[140] = 'bluefish';\n$.physicals.girl.foodList[141] = 'bread';\n$.physicals.girl.foodList[142] = 'broccoli';\n$.physicals.girl.foodList[143] = 'buritto';\n$.physicals.girl.foodList[144] = 'babaganoosh';\n$.physicals.girl.foodList[145] = 'cabbage';\n$.physicals.girl.foodList[146] = 'cake';\n$.physicals.girl.foodList[147] = 'carrots';\n$.physicals.girl.foodList[148] = 'carne asada';\n$.physicals.girl.foodList[149] = 'celery';\n$.physicals.girl.foodList[150] = 'cheese';\n$.physicals.girl.foodList[151] = 'chicken';\n$.physicals.girl.foodList[152] = 'catfish';\n$.physicals.girl.foodList[153] = 'cheeseburger';\n$.physicals.girl.foodList[154] = 'chips';\n$.physicals.girl.foodList[155] = 'chocolate';\n$.physicals.girl.foodList[156] = 'chowder';\n$.physicals.girl.foodList[157] = 'clams';\n$.physicals.girl.foodList[158] = 'coffee';\n$.physicals.girl.foodList[159] = 'cookie';\n$.physicals.girl.foodList[160] = 'corn';\n$.physicals.girl.foodList[161] = 'cupcake';\n$.physicals.girl.foodList[162] = 'crab';\n$.physicals.girl.foodList[163] = 'curry';\n$.physicals.girl.foodList[164] = 'cereal';\n$.physicals.girl.foodList[165] = 'chimichanga';\n$.physicals.girl.foodList[166] = 'dates';\n$.physicals.girl.foodList[167] = 'dips';\n$.physicals.girl.foodList[168] = 'duck';\n$.physicals.girl.foodList[169] = 'dumpling';\n$.physicals.girl.foodList[170] = 'donuts';\n$.physicals.girl.foodList[171] = 'eggs';\n$.physicals.girl.foodList[172] = 'enchilada';\n$.physicals.girl.foodList[173] = 'eggroll';\n$.physicals.girl.foodList[174] = 'english muffin';\n$.physicals.girl.foodList[175] = 'edamame';\n$.physicals.girl.foodList[176] = 'eel sushi';\n$.physicals.girl.foodList[177] = 'fajita';\n$.physicals.girl.foodList[178] = 'falafel';\n$.physicals.girl.foodList[179] = 'fish';\n$.physicals.girl.foodList[180] = 'franks';\n$.physicals.girl.foodList[181] = 'fondu';\n$.physicals.girl.foodList[182] = 'french toast';\n$.physicals.girl.foodList[183] = 'french dip';\n$.physicals.girl.foodList[184] = 'garlic';\n$.physicals.girl.foodList[185] = 'ginger';\n$.physicals.girl.foodList[186] = 'gnocchi';\n$.physicals.girl.foodList[187] = 'goose';\n$.physicals.girl.foodList[188] = 'granola';\n$.physicals.girl.foodList[189] = 'grapes';\n$.physicals.girl.foodList[190] = 'green beans';\n$.physicals.girl.foodList[191] = 'guacamole';\n$.physicals.girl.foodList[192] = 'gumbo';\n$.physicals.girl.foodList[193] = 'grits';\n$.physicals.girl.foodList[194] = 'graham crackers';\n$.physicals.girl.foodList[195] = 'ham';\n$.physicals.girl.foodList[196] = 'halibut';\n$.physicals.girl.foodList[197] = 'hamburger';\n$.physicals.girl.foodList[198] = 'honey';\n$.physicals.girl.foodList[199] = 'huenos rancheros';\n$.physicals.girl.foodList[200] = 'hash browns';\n$.physicals.girl.foodList[201] = 'hot dogs';\n$.physicals.girl.foodList[202] = 'haiku roll';\n$.physicals.girl.foodList[203] = 'hummus';\n$.physicals.girl.foodList[204] = 'ice cream';\n$.physicals.girl.foodList[205] = 'irish stew';\n$.physicals.girl.foodList[206] = 'indian food';\n$.physicals.girl.foodList[207] = 'italian bread';\n$.physicals.girl.foodList[208] = 'jambalaya';\n$.physicals.girl.foodList[209] = 'jelly';\n$.physicals.girl.foodList[210] = 'jam';\n$.physicals.girl.foodList[211] = 'jerky';\n$.physicals.girl.foodList[212] = 'jalapeño';\n$.physicals.girl.foodList[213] = 'kale';\n$.physicals.girl.foodList[214] = 'kabobs';\n$.physicals.girl.foodList[215] = 'ketchup';\n$.physicals.girl.foodList[216] = 'kiwi';\n$.physicals.girl.foodList[217] = 'kidney beans';\n$.physicals.girl.foodList[218] = 'kingfish';\n$.physicals.girl.foodList[219] = 'lobster';\n$.physicals.girl.foodList[220] = 'lamb';\n$.physicals.girl.foodList[221] = 'linguine';\n$.physicals.girl.foodList[222] = 'lasagna';\n$.physicals.girl.foodList[223] = 'meatballs';\n$.physicals.girl.foodList[224] = 'moose';\n$.physicals.girl.foodList[225] = 'milk';\n$.physicals.girl.foodList[226] = 'milkshake';\n$.physicals.girl.foodList[227] = 'noodles';\n$.physicals.girl.foodList[228] = 'ostrich';\n$.physicals.girl.foodList[229] = 'pizza';\n$.physicals.girl.foodList[230] = 'pepperoni';\n$.physicals.girl.foodList[231] = 'porter';\n$.physicals.girl.foodList[232] = 'pancakes';\n$.physicals.girl.foodList[233] = 'quesadilla';\n$.physicals.girl.foodList[234] = 'quiche';\n$.physicals.girl.foodList[235] = 'reuben';\n$.physicals.girl.foodList[236] = 'spinach';\n$.physicals.girl.foodList[237] = 'spaghetti';\n$.physicals.girl.foodList[238] = 'tater tots';\n$.physicals.girl.foodList[239] = 'toast';\n$.physicals.girl.foodList[240] = 'venison';\n$.physicals.girl.foodList[241] = 'waffles';\n$.physicals.girl.foodList[242] = 'wine';\n$.physicals.girl.foodList[243] = 'walnuts';\n$.physicals.girl.foodList[244] = 'yogurt';\n$.physicals.girl.foodList[245] = 'ziti';\n$.physicals.girl.foodList[246] = 'zucchini';\n$.physicals.girl.foodList[247] = 'string bean';\n$.physicals.girl.foodList[248] = 'birthday cake';\n$.physicals.girl.foodList[249] = 'pear';\n$.physicals.girl.foodList[250] = 'steak';\n$.physicals.girl.foodList[251] = 'peanut';\n$.physicals.girl.foodList[252] = 'hot dog';\n$.physicals.girl.willAccept = function willAccept(what, src) {\n  /* Returns true iff this is willing to accept what arriving from src.\n   *\n   * This function (or its overrides) MUST NOT have any kind of\n   * observable side-effect (making noise, causing some other action,\n   * etc.).\n   */\n  return what === this.food;\n};\nObject.setOwnerOf($.physicals.girl.willAccept, $.physicals.Maximilian);\nObject.setOwnerOf($.physicals.girl.willAccept.prototype, $.physicals.Maximilian);\n$.physicals.girl.movable = false;\n$.physicals.girl.attempts = 0;\n\n"
  },
  {
    "path": "core/core_46_$.secuityCourse.js",
    "content": "/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Security course demo for Code City.\n */\n\n//////////////////////////////////////////////////////////////////////\n// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\n//////////////////////////////////////////////////////////////////////\n\n$.securityCourse = {};\nObject.setOwnerOf($.securityCourse, $.physicals.Neil);\n$.securityCourse.StoreHost = function StoreHost() {\n  /* A $.servers.http.Host subclass for per-user stores for the security\n   * course.\n   */\n  $.servers.http.Host.call(this);\n  var user = Object.getOwnerOf(this);\n  if (!($.user.isPrototypeOf(user))) {\n    throw new TypeError('new store must be owned by a $.user');\n  }\n  var hostname = user.name.toLowerCase();\n  if (hostname in $.securityCourse.storeHosts) {\n    throw new RangeError('a store named ' + hostname + ' already exists');\n  } else if (hostname in $.hosts.root.subdomains) {\n    throw new RangeError('the subdomain ' + hostname + ' is already in use');\n  }\n  (function inner() {\n    // Run set-up with non-privileged perms.\n    setPerms(user);\n    var store = Object.create($.securityCourse.storePagePrototype);\n    store.name = user.name + \"'s Store\";\n    this['/'] = store;\n  }).call(this);\n  $.securityCourse.storeHosts[hostname] = this;\n  $.hosts.root.addSubdomain(hostname, this);\n\n};\nObject.setOwnerOf($.securityCourse.StoreHost, $.physicals.Maximilian);\nObject.setPrototypeOf($.securityCourse.StoreHost.prototype, $.servers.http.Host.prototype);\nObject.setOwnerOf($.securityCourse.StoreHost.prototype, $.physicals.Maximilian);\n$.securityCourse.StoreHost.prototype.destroy = function destroy() {\n  if (!(this instanceof $.securityCourse.StoreHost)) {\n    throw new TypeError('destroy must be called on a StoreHost');\n  }\n  var callerPerms = Thread.callers()[0].callerPerms;\n  if(Object.getOwnerOf(this) !== callerPerms) {\n    throw new PermissionError('can only be deleted by owner');\n  }\n  $.hosts.root.deleteSubdomain(this);\n  var stores = $.securityCourse.storeHosts;\n  for (var key in stores) {\n    if (stores[key] === this) {\n      delete stores[key];\n    }\n  }\n};\nObject.setOwnerOf($.securityCourse.StoreHost.prototype.destroy, $.physicals.Maximilian);\nObject.setOwnerOf($.securityCourse.StoreHost.prototype.destroy.prototype, $.physicals.Maximilian);\n$.securityCourse.storePagePrototype = {};\nObject.setOwnerOf($.securityCourse.storePagePrototype, $.physicals.Neil);\n$.securityCourse.storePagePrototype.www = function www(request, response) {\n  // This is a routing function.  There's nothing interesting here.  Honest.\n  var prop = {\n    'basket': 'wwwBasket',\n    'confirm': 'wwwConfirm',\n  }[request.parameters.page] || 'wwwHome';\n  $.jssp.eval(this, prop, request, response);\n};\nObject.setOwnerOf($.securityCourse.storePagePrototype.www, $.physicals.Maximilian);\nObject.setOwnerOf($.securityCourse.storePagePrototype.www.prototype, $.physicals.Neil);\n$.securityCourse.storePagePrototype.name = 'Security Store';\n$.securityCourse.storePagePrototype.inventory = [];\nObject.setOwnerOf($.securityCourse.storePagePrototype.inventory, $.physicals.Neil);\n$.securityCourse.storePagePrototype.inventory[0] = {};\nObject.setOwnerOf($.securityCourse.storePagePrototype.inventory[0], $.physicals.Neil);\n$.securityCourse.storePagePrototype.inventory[0].name = 'Beach ball';\n$.securityCourse.storePagePrototype.inventory[0].price = '2.75';\n$.securityCourse.storePagePrototype.inventory[0].id = 'yYrq3jVfWK';\n$.securityCourse.storePagePrototype.inventory[0].public = true;\n$.securityCourse.storePagePrototype.inventory[0].img = 'beachball.png';\n$.securityCourse.storePagePrototype.inventory[1] = {};\nObject.setOwnerOf($.securityCourse.storePagePrototype.inventory[1], $.physicals.Neil);\n$.securityCourse.storePagePrototype.inventory[1].name = 'Flip flops';\n$.securityCourse.storePagePrototype.inventory[1].price = '8.50';\n$.securityCourse.storePagePrototype.inventory[1].id = 'GSaYngk5Jn';\n$.securityCourse.storePagePrototype.inventory[1].public = true;\n$.securityCourse.storePagePrototype.inventory[1].img = 'flipflops.png';\n$.securityCourse.storePagePrototype.inventory[2] = {};\nObject.setOwnerOf($.securityCourse.storePagePrototype.inventory[2], $.physicals.Neil);\n$.securityCourse.storePagePrototype.inventory[2].name = 'Nuclear waste';\n$.securityCourse.storePagePrototype.inventory[2].price = '666';\n$.securityCourse.storePagePrototype.inventory[2].id = 'iu9i5GvLeJ';\n$.securityCourse.storePagePrototype.inventory[2].public = false;\n$.securityCourse.storePagePrototype.inventory[2].img = 'radioactive.png';\n$.securityCourse.storePagePrototype.inventory[3] = {};\nObject.setOwnerOf($.securityCourse.storePagePrototype.inventory[3], $.physicals.Neil);\n$.securityCourse.storePagePrototype.inventory[3].name = 'Guitar';\n$.securityCourse.storePagePrototype.inventory[3].price = '24.30';\n$.securityCourse.storePagePrototype.inventory[3].id = 'uazSOLHfkt';\n$.securityCourse.storePagePrototype.inventory[3].public = true;\n$.securityCourse.storePagePrototype.inventory[3].img = 'guitar.png';\n$.securityCourse.storePagePrototype.wwwHome = '<% include(\\'header\\'); %>\\n<h1><%= this.name %> Home</h1>\\n\\n<form>\\n<input type=\"hidden\" name=\"page\" value=\"basket\">\\n\\n<%\\nvar staticUrl = request.hostUrl(\\'static\\');\\nfor (var i = 0; i < this.inventory.length; i++) {\\n  var item = this.inventory[i];\\n  if (!item || !item.public) continue;\\n%>\\n<p>\\n  <img src=\"<%=staticUrl%>securitystore/<%=item.img%>\" class=\"productImage\" />\\n  <div class=\"productName\"><%=item.name%></div>\\n  <div class=\"price\"><%=item.price%></div>\\n  <div class=\"quantity\">Quantity: <input type=\"number\" name=\"item<%=i%>\" value=\"0\" min=\"0\" max=\"100\"></div>\\n<p> \\n<% } %>\\n\\n<p>\\n  <input type=\"submit\" value=\"Add to basket\">\\n</p>\\n</form>  \\n  \\n<% include(\\'footer\\'); %>';\n$.securityCourse.storePagePrototype.wwwBasket = '<% include(\\'header\\'); %>\\n<h1><%= this.name %> Basket</h1>\\n\\n<table>\\n<%\\nvar staticUrl = request.hostUrl(\\'static\\');\\nvar total = 0;  \\nvar order = {};\\nfor (var param in request.parameters) {\\n  if (!param.startsWith(\\'item\\')) continue;\\n  var item = this.inventory[Number(param.substring(4))];\\n  var quant = Number(request.parameters[param]);\\n  if (!item || !quant) continue;\\n  var lineTotal = quant * item.price;\\n  total += lineTotal;\\n  order[item.id] = quant;\\n%>\\n<tr>\\n  <td><img src=\"<%=staticUrl%>securitystore/<%=item.img%>\" class=\"basketImage\" /></td>\\n  <td><%=item.name%></td>\\n  <td><%=quant%> x <span class=\"price\"><%=item.price%></span> = <span class=\"price\"><%=lineTotal%></span></td>\\n<tr> \\n<% } %>\\n</table>\\n\\n<p>Total: <span class=\"price\"><%=total%></span></p>\\n\\n<form method=\"POST\">\\n<input type=\"hidden\" name=\"page\" value=\"confirm\">\\n<input type=\"hidden\" name=\"order\" value=\\'<%=JSON.stringify(order)%>\\'>\\n<input type=\"hidden\" name=\"total\" value=\"<%=total%>\">\\n\\n<p>\\n  Name: <input name=\"name\">\\n</p>\\n<p>\\n  Credit card: <input name=\"card\"><br>\\n  (Don\\'t enter a real card number, \\'123\\' is fine.)\\n</p>\\n<p>\\n  <input type=\"submit\" value=\"Purchase\">\\n</p>\\n</form>  \\n  \\n<% include(\\'footer\\'); %>';\n$.securityCourse.storePagePrototype.wwwConfirm = \"<% include('header'); %>\\n<h1><%= this.name %> Confirm</h1>\\n\\n<p>Thank you <%=request.parameters.name%>!<p>\\n<p>Your credit card has been billed for <span class=\\\"price\\\"><%=request.parameters.total%></span>.<p>\\n<p>Your order will be shipped as soon as this store's <em>massive</em> security holes have been patched.</p>\\n\\n<% include('footer'); %>\";\n$.securityCourse.storePagePrototype.escape = $.utils.html.escape;\n$.securityCourse.storePagePrototype.header = '<html>\\n  <head>\\n    <title>Security Store</title>\\n    <link href=\"<%=request.hostUrl(\\'static\\')%>securitystore/style.css\" rel=\"stylesheet\" type=\"text/css\" />\\n    <script src=\"https://neil.fraser.name/securitystore/utils.js\"></script>\\n  </head>\\n  <body>';\n$.securityCourse.storePagePrototype.footer = '    <hr>\\n    <div class=\"balls\"><img src=\"https://dom-tutorials.appspot.com/static/google_balls.jpg\" height=68 width=101></div>\\n    <div class=\"footer\">Google &copy; 2021</div>\\n  </body>\\n</html>';\n$.securityCourse.www = '<%\\nvar storeHosts = $.securityCourse.storeHosts;\\nvar storeKey;\\nfor (var key in storeHosts) {\\n  if (Object.getOwnerOf(storeHosts[key]) === request.user) {\\n    storeKey = key;\\n    break;\\n  }\\n}\\n\\nif (request.method === \\'POST\\') {\\n  if (request.parameters.create) {\\n    (function create() {\\n      setPerms(request.user);\\n      new $.securityCourse.StoreHost();\\n    }).call(this);\\n  }\\n  if (request.parameters.delete) {\\n    (function del() {\\n      setPerms(request.user);\\n      storeHosts[request.parameters.delete].destroy();\\n    }).call(this);\\n  }\\n  response.sendRedirect(\\'securitycourse\\');\\n  return;\\n}\\nvar staticUrl = request.hostUrl(\\'static\\');\\n%>\\n<!doctype html>\\n<html>\\n  <head>\\n  <title>engEDU Security Course</title>\\n  <style>\\n    body {\\n      font-family: \"Roboto Mono\", monospace;\\n    }\\n    iframe {\\n      border-style: solid 1px #ccc;\\n      width: 100%;\\n      height: 15em;\\n    }\\n    th {\\n      text-align: left;\\n    }\\n    td {\\n      padding-right: 1em;\\n    }\\n    .myRow {\\n      font-weight: bold;\\n    }\\n  </style>\\n  <link href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\" rel=\"stylesheet\">\\n  <link href=\"<%=staticUrl%>favicon.ico\" rel=\"shortcut icon\">\\n  <link href=\"<%=staticUrl%>style/jfk.css\" rel=\"stylesheet\"> \\n  </head>\\n  <body>\\n    <h1>engEDU Security Course</h1>\\n    \\n    <% if (!storeKey) { %>\\n    <p>\\n    <form method=\"post\">\\n      To join the course, click \\n      <input type=\"submit\" name=\"create\" value=\"Create Store\" class=\"jfk-button jfk-button-action\">\\n    </form>\\n    </p>\\n    <% } %>\\n\\n    <% if (Object.getOwnPropertyNames(storeHosts).length) { %>\\n    <p>\\n      <table>\\n        <tr style=\"text-align:left\">\\n          <th colspan=\"2\">Stores in this class</th>\\n        </tr>\\n        <%\\n          for (var hostName in storeHosts) {\\n            var storeName = storeHosts[hostName][\\'/\\'].name;\\n        %>\\n        <tr class=\"<%= hostName === storeKey ? \\'myRow\\' : \\'\\' %>\">\\n          <td><a href=\"<%= request.hostUrl(hostName) %>\" target=\"_blank\" rel=\"noopener\">\\n            <%= $.securityCourse.storePagePrototype.escape(storeName) %>\\n          </a></td>\\n          <td><a href=\"<%= request.hostUrl(\\'code\\') + \\'?\\' + encodeURIComponent(\\'$.securityCourse.storeHosts.\\' + hostName + \"[\\'/\\']\") %>\" target=\"_blank\" rel=\"noopener\">Code</a><td>\\n          <% if (hostName === storeKey) { %>\\n          <td>\\n            <form method=\"post\" onsubmit=\"return confirm(\\'Are you sure you want to delete your store?\\')\">\\n              <button class=\"jfk-button\" type=\"submit\" name=\"delete\" value=<%= JSON.stringify(hostName) %>>Delete</button>\\n            </form>\\n          </td>\\n          <% } %>\\n        </tr>\\n        <% } %>\\n      </table>\\n    </p>\\n    <% } %>\\n    <p>\\n      <iframe src=\"<%=request.hostUrl(\\'code\\')%>eval\"></iframe>\\n    </p>\\n  </body>\\n</html>';\n\n$.securityCourse.storeHosts = (new 'Object.create')(null);\n\n$.hosts.root['/securitycourse'] = $.securityCourse;\n\n"
  },
  {
    "path": "core/core_99_startup.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Start core database.  Note that, unlike most of the\n * rest of the files in the core/ directory, this is hand-written.\n *\n * It assumed this file will be used when starting a full database\n * dump; for that, a file in database/, generated by dump, will\n * restart listeners intead.\n */\n\n/* Optional (but recommended) configuration.  The web server is\n * capable of guessing its own hostname, but will be more efficient\n * and secure if its configuration is specified explicitly.\n */\n\n/* Set .hostname to the canonical hostname (including the port number,\n * if non-default).\n */\n// $.hosts.root.hostname = 'example.codecity.world';\n// $.hosts.root.hostname = 'localhost:8080';\n\n/* If your host has more than one name, set .hostRegExp to a regular\n * expression that matches all valid name+port combinations for this\n * host.  It is recommended that it end with /$/, but do NOT start it\n * with /^/ unless you want to break wildcard subdomains.  Make sure\n * it matches .hostname!\n */\n// Accept either of two different hostnames.\n// $.hosts.root.hostRegExp = /example.codecity.world$|codecity.example.com$/;\n// Match any TLD and optional port.\n// $.hosts.root.hostRegExp = /example.codecity.\\w+(?::\\d+)?$/;\n\n/* Set .pathToSubdomain to true if you don't have a wildcard DNS entry\n * and wildcard TLS certificate for your hostname (false if you do);\n * this will enable accessing pages usually served on subdomains (such\n * as the code editor) via the root hostname instead.\n *\n * Normally the nginx reverse proxy sends a CodeCity-pathToSubdomain\n * header which will automatically enable or disable this feature, but\n * you can override it here.\n */\n// $.hosts.root.pathToSubdomain = false;\n\n// Set up.\n$.system.onStartup();\n\n// Tidy up.\n$.clock.movable = true;\n$.clock.moveTo($.startRoom);\n$.clock.movable = false;\n\n$.tutorial.moveTo($.startRoom);\n$.tutorial.reset();\n\n$.pot.moveTo($.startRoom);\n$.pot.stage = 0;\n$.seed.moveTo($.startRoom);\n$.thrower.moveTo($.startRoom);\n\n$.cage.moveTo($.physicals['Genetics Lab']);\n\n$.assistant.moveTo($.startRoom);\n\n\n"
  },
  {
    "path": "core/dump_spec.json",
    "content": "[\n  {\n    \"options\": {\"skipBindings\": [\"lastModifiedTime\", \"lastModifiedUser\"]}\n  }, {\n    \"header\": [\n      \"/**\",\n      \" * @license\",\n      \" * Copyright <YEAR> Google LLC\",\n      \" *\",\n      \" * Licensed under the Apache License, Version 2.0 (the \\\"License\\\");\",\n      \" * you may not use this file except in compliance with the License.\",\n      \" * You may obtain a copy of the License at\",\n      \" *\",\n      \" *   http://www.apache.org/licenses/LICENSE-2.0\",\n      \" *\",\n      \" * Unless required by applicable law or agreed to in writing, software\",\n      \" * distributed under the License is distributed on an \\\"AS IS\\\" BASIS,\",\n      \" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\",\n      \" * See the License for the specific language governing permissions and\",\n      \" * limitations under the License.\",\n      \" */\",\n      \"\",\n      \"/**\",\n      \" * @fileoverview <OVERVIEW>\",\n      \" */\",\n      \"\",\n      \"//////////////////////////////////////////////////////////////////////\",\n      \"// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!\",\n      \"//////////////////////////////////////////////////////////////////////\",\n      \"\\n\"\n    ],\n    \"filename\": \"../var/dump/core_00_es5.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": [\n        \"Load builtins and add polyfills to bring the server's partial\",\n        \" * JavaScript implementation up to ECMAScript 5.1 (or close to it).\"\n      ]\n    },\n    \"contents\": [\n      \"Object\",\n      \"Function\",\n      \"Array\",\n      \"String\",\n      \"Boolean\",\n      \"Number\",\n      \"Date\",\n      \"RegExp\",\n      \"Error\",\n      \"EvalError\",\n      \"RangeError\",\n      \"ReferenceError\",\n      \"SyntaxError\",\n      \"TypeError\",\n      \"URIError\",\n      \"Math\",\n      \"JSON\",\n      \"decodeURI\",\n      \"decodeURIComponent\",\n      \"encodeURI\",\n      \"encodeURIComponent\",\n      \"escape\",\n      \"isFinite\",\n      \"isNaN\",\n      \"parseFloat\",\n      \"parseInt\",\n      \"unescape\"\n    ]\n  }, {\n    \"filename\": \"../var/dump/core_00_es6.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": [\n        \"Load builtins and add polyfills to bring the server's partial\",\n        \" * JavaScript implementation to include some features of ECMAScript 6.\"\n      ]\n    },\n    \"contents\": [\n      \"Object.is\",\n      \"Object.assign\",\n      \"Object.setPrototypeOf\",\n      \"Array.from\",\n      \"Array.prototype.find\",\n      \"Array.prototype.findIndex\",\n      \"String.prototype.endsWith\",\n      \"String.prototype.includes\",\n      \"String.prototype.repeat\",\n      \"String.prototype.startsWith\",\n      \"Number.isFinite\",\n      \"Number.isNaN\",\n      \"Number.isSafeInteger\",\n      \"Number.EPSILON\",\n      \"Number.MAX_SAFE_INTEGER\",\n      \"Math.sign\",\n      \"Math.trunc\",\n      \"WeakMap\"\n    ]\n  }, {\n    \"filename\": \"../var/dump/core_00_es7.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": [\n        \"Load builtins and add polyfills to bring the server's partial\",\n        \" * JavaScript implementation to include some features of ECMAScript 7.\"\n      ]\n    },\n    \"contents\": [\n      \"Array.prototype.includes\"\n    ]\n  }, {\n    \"filename\": \"../var/dump/core_00_esx.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": [\n        \"Load builtins and add polyfills for Code City-specific extensions to\",\n        \" * JavaScript.\"\n      ]\n    },\n    \"contents\": [\n      \"Object.getOwnerOf\",\n      \"Object.setOwnerOf\",\n      \"Thread\",\n      \"PermissionError\",\n      \"Array.prototype.join\",\n      \"suspend\",\n      \"setTimeout\",\n      \"clearTimeout\"\n    ]\n  },\n\n  {\n    \"filename\": \"core_10_base.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Database core for Code City.\"\n    },\n    \"prune\": [\"$.system.onStartup.thread_\"],\n    \"contents\": [\n      \"perms\",\n      \"setPerms\",\n      {\"path\": \"$\", \"do\": \"DONE\"},\n      \"$.root\",\n      {\"path\": \"$.physicals\", \"do\": \"DONE\"},\n      {\"path\": \"$.physicals.Maximilian\", \"do\": \"DONE\"},\n      {\"path\": \"$.physicals.Neil\", \"do\": \"DONE\"},\n      \"$.system\",\n      \"user\",\n      {\"path\": \"$.utils\", \"do\": \"DONE\"},\n      {\"path\": \"$.utils.validate\", \"do\": \"DONE\"},\n      {\"path\": \"$.servers\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"filename\": \"core_11_$.utils.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2020\",\n      \"<OVERVIEW>\": \"Basic utilities for Code City.\"\n    },\n    \"contents\": [\n      \"$.utils\",\n      \"$.utils.array\",\n      \"$.utils.object\",\n      \"$.utils.string\"\n    ]\n  }, {\n    \"filename\": \"core_12_$.utils.code.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2018\",\n      \"<OVERVIEW>\": \"Code utilities for Code City.\"\n    },\n    \"contents\": [\"$.utils.code\"]\n  }, {\n    \"filename\": \"core_13_$.Selector.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2018\",\n      \"<OVERVIEW>\": \"Selector implementation for Code City core.\"\n    },\n    \"pruneRest\": [\"$.Selector.cache_\", \"$.Selector.sortByBadness.cache_\"],\n    \"contents\": [\n      \"$.Selector\",\n      \"$.utils.Binding\",\n      {\"path\": \"$.Selector.cache_\", \"do\": \"DONE\"},\n      {\"path\": \"$.Selector.sortByBadness.cache_\", \"do\": \"DONE\"}\n    ]\n  },\n\n  {\n    \"filename\": \"core_20_$.utils.html.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2018\",\n      \"<OVERVIEW>\": \"HTML utilities for Code City.\"\n    },\n    \"contents\": [\"$.utils.html\"]\n  }, {\n    \"filename\": \"core_21_$.jssp.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"JavaScript Server Pages for Code City.\"\n    },\n    \"contents\": [\"$.jssp\"]\n  }, {\n    \"filename\": \"core_22_$.connection.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Connection object for Code City.\"\n    },\n    \"contents\": [\"$.connection\"]\n  }, {\n    \"filename\": \"core_23_$.servers.http.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Webserver for Code City.\"\n    },\n    \"contents\": [\n      \"$.utils.url\",\n      \"$.servers.http\",\n      {\"path\": \"$.servers.http.hosts\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"filename\": \"core_24_$.hosts.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Host objects for Code City.\"\n    },\n    \"contents\": [\n      {\"path\": \"$.hosts\", \"do\": \"DONE\"},\n      {\"path\": \"$.hosts.root\", \"do\": \"DONE\"},\n      {\"path\": \"$.hosts.root.subdomains\", \"do\": \"DONE\"},\n      \"$.hosts.root['/']\",\n      \"$.hosts.root['/mirror']\",\n      \"$.hosts.root['/robots.txt']\",\n      \"$.hosts.system\",\n      \"$.hosts.dummy\",\n      \"$.hosts.root.subdomains.system\",\n      \"$.hosts.root.subdomains.connect\",\n      \"$.hosts.root.subdomains.login\",\n      \"$.hosts.root.subdomains.mobwrite\",\n      \"$.hosts.root.subdomains.static\",\n      \"$.hosts.root.subdomains.system\",\n      {\"path\": \"$.servers.http.hosts[0]\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"filename\": \"core_25_$.db.tempId.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2018\",\n      \"<OVERVIEW>\": \"Temporary ID database for Code City.\"\n    },\n    \"contents\": [\n      {\"path\": \"$.db\", \"do\": \"DONE\"},\n      \"$.db.tempId\",\n      {\"path\": \"$.db.tempId.tempIds_\", \"do\": \"DONE\"},\n      {\"path\": \"$.db.tempId.cleanThread_\", \"do\": \"DECL\"}\n    ]\n  }, {\n    \"filename\": \"core_25_$.userDatabase.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"User database for Code City.\"\n    },\n    \"contents\": [\n      \"$.userDatabase\",\n      {\"path\": \"$.userDatabase.byMd5\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"filename\": \"core_26_inline_editor.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Inline code editor for Code City.\"\n    },\n    \"contents\": [\n      {\"path\": \"$.hosts.code\", \"do\": \"DONE\"},\n      \"$.hosts.code['/inlineEdit']\",\n      {\"path\": \"$.hosts.root.subdomains.code\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"filename\": \"core_27_editor.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2018\",\n      \"<OVERVIEW>\": \"Web-based code explorer/editor for Code City.\"\n    },\n    \"contents\": [\n      \"$.hosts.code\"\n    ]\n  }, {\n    \"filename\": \"core_28_$.servers.eval.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2020\",\n      \"<OVERVIEW>\": \"Eval server for Code City.\"\n    },\n    \"contents\": [\n      \"$.servers.eval\"\n    ]\n  },\n\n  {\n    \"filename\": \"core_30_$.utils.command.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Command parser for Code City\"\n    },\n    \"contents\": [\"$.utils.command\"]\n  }, {\n    \"filename\": \"core_31_$.utils_world.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"World-related utils for Code City.\"\n    },\n    \"contents\": [\n      \"$.utils.commandMenu\",\n      \"$.utils.replacePhysicalsWithName\"\n    ]\n  }, {\n    \"filename\": \"core_32_physical.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Physical object prototype for Code City.\"\n    },\n    \"contents\": [\n      \"$.physical\",\n      {\"path\": \"$.physicals\", \"do\": \"DONE\"},\n      {\"path\": \"$.physicals['Physical object prototype']\", \"do\": \"DONE\"},\n      \"$.utils.validate.physicals\",\n      \"$.garbage\"\n    ]\n  }, {\n    \"filename\": \"core_33_world.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Generic physical object types for Code City.\"\n    },\n    \"contents\": [\n      \"$.user\",\n      \"$.room\",\n      \"$.thing\",\n      \"$.container\",\n      {\"path\": \"$.physicals['User prototype']\", \"do\": \"DONE\"},\n      {\"path\": \"$.physicals['Room prototype']\", \"do\": \"DONE\"},\n      {\"path\": \"$.physicals['Thing prototype']\", \"do\": \"DONE\"},\n      {\"path\": \"$.physicals['Container prototype']\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"filename\": \"core_34_$.servers.login.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2021\",\n      \"<OVERVIEW>\": \"Login service backend server for Code City.\"\n    },\n    \"contents\": [\n      \"$.servers.login\"\n    ]\n  }, {\n    \"filename\": \"core_34_$.servers.telnet.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Telnet server for Code City.\"\n    },\n    \"pruneRest\": [\"$.servers.telnet.connected\"],\n    \"contents\": [\n      \"$.servers.telnet\",\n      {\"path\": \"$.servers.telnet.connected\", \"do\": \"DONE\"}\n    ]\n  },\n\n  {\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Initial starting room for Code City.\"\n    },\n    \"filename\": \"core_40_$.startRoom.js\",\n    \"prune\": [\"$.clock.thread_\"],\n    \"contents\": [\n      {\"path\": \"$.startRoom\", \"do\": \"DONE\"},\n      \"$.startRoom{proto}\",\n      \"$.startRoom{owner}\",\n      \"$.startRoom.location\",\n      {\"path\": \"$.startRoom.contents_\", \"do\": \"DONE\"},\n      {\"path\": \"$.startRoom.contents_.forObj\", \"do\": \"DONE\"},\n      {\"path\": \"$.startRoom.contents_.forKey\", \"do\": \"DONE\"},\n      \"$.startRoom.name\",\n      \"$.startRoom.description\",\n      \"$.startRoom.roll\",\n      \"$.clock\",\n      {\"path\": \"$.clock.thread_\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"headerSubs\": {\n      \"<YEAR>\": \"2018\",\n      \"<OVERVIEW>\": \"Translation room and tutorial  demo for Code City.\"\n    },\n    \"filename\": \"core_41_deutsche_zimmer.js\",\n    \"contents\": [\n      \"$.physicals['Das deutsche Zimmer']\",\n      \"$.tutorial\",\n      {\"path\": \"$.tutorial.location\", \"do\": \"DECL\"},\n      {\"path\": \"$.tutorial.user\", \"do\": \"DECL\"},\n      {\"path\": \"$.tutorial.thread\", \"do\": \"DECL\"},\n      {\"path\": \"$.tutorial.step\", \"do\": \"DECL\"},\n      {\"path\": \"$.tutorial.room\", \"do\": \"DECL\"},\n      {\"path\": \"$.tutorial.origFunc\", \"do\": \"DECL\"},\n      {\"path\": \"$.physicals.tutorial\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"filename\": \"core_42_plant.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2018\",\n      \"<OVERVIEW>\": \"Plant demo for Code City.\"\n    },\n    \"contents\": [\n      \"$.seed\",\n      {\"path\": \"$.seed.location\", \"do\": \"DECL\"},\n      {\"path\": \"$.physicals['Generic Seed']\", \"do\": \"DONE\"},\n      \"$.pot\",\n      {\"path\": \"$.pot.location\", \"do\": \"DECL\"},\n      {\"path\": \"$.pot.seed\", \"do\": \"DECL\"},\n      {\"path\": \"$.pot.stage\", \"do\": \"DECL\"},\n      \"$.pot.stages\",\n      {\"path\": \"$.physicals['flower pot']\", \"do\": \"DONE\"},\n      \"$.thrower\",\n      {\"path\": \"$.thrower.location\", \"do\": \"DECL\"},\n      {\"path\": \"$.thrower.savedSvg\", \"do\": \"DECL\"},\n      {\"path\": \"$.physicals['a flame thrower']\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"filename\": \"core_43_genetics_lab.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2020\",\n      \"<OVERVIEW>\": \"Genetics lab demo for Code City.\"\n    },\n    \"contents\": [\n      \"$.physicals['Genetics Lab']\",\n      {\"path\": \"$.physicals['Genetics Lab'].contents_\", \"do\": \"DONE\"},\n      {\"path\": \"$.physicals['Genetics Lab'].contents_.forObj\", \"do\": \"DONE\"},\n      {\"path\": \"$.physicals['Genetics Lab'].contents_.forKey\", \"do\": \"DONE\"},\n      \"$.cage\",\n      {\"path\": \"$.cage.location\", \"do\": \"DECL\"},\n      {\"path\": \"$.physicals.cage\", \"do\": \"DONE\"},\n      \"$.physicals['Genetic Mouse Prototype']\",\n      \"$.hosts.genetics\",\n      \"$.hosts.root.subdomains.genetics\"\n    ]\n  }, {\n    \"filename\": \"core_44_$.assistant.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2020\",\n      \"<OVERVIEW>\": \"Voice-activated assistant demo for Code City.\"\n    },\n    \"contents\": [\n      \"$.assistant\",\n      {\"path\": \"$.assistant.location\", \"do\": \"DECL\"},\n      {\"path\": \"$.assistant.lastActivated\", \"do\": \"DECL\"},\n      {\"path\": \"$.physicals.assistant\", \"do\": \"DONE\"}\n    ]\n  }, {\n    \"filename\": \"core_45_Challenge_Room.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2020\",\n      \"<OVERVIEW>\": \"Challenge room demo for Code City.\"\n    },\n    \"contents\": [\n      \"$.physicals['Challenge room']\",\n      \"$.physicals['light switch']\",\n      \"$.physicals.chest\",\n      \"$.physicals.safe\",\n      \"$.physicals.food\",\n      \"$.physicals.girl\"\n    ]\n  }, {\n    \"filename\": \"core_46_$.secuityCourse.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2021\",\n      \"<OVERVIEW>\": \"Security course demo for Code City.\"\n    },\n    \"contents\": [\n      \"$.securityCourse\",\n      {\"path\": \"$.securityCourse.storeHosts\", \"do\": \"DONE\"},\n      {\"path\": \"$.hosts.root['/securitycourse']\", \"do\": \"DONE\"}\n    ]\n  },\n\n  {\n    \"options\": {\"skipBindings\": []}\n  }, {\n    \"filename\": \"../database/db_00_core_lastModified.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2020\",\n      \"<OVERVIEW>\": \"Edit history info for Code City core.\"\n    },\n    \"contents\": [\n      \"Object\",\n      \"Function\",\n      \"Array\",\n      \"String\",\n      \"Boolean\",\n      \"Number\",\n      \"Date\",\n      \"RegExp\",\n      \"Error\",\n      \"EvalError\",\n      \"RangeError\",\n      \"ReferenceError\",\n      \"SyntaxError\",\n      \"TypeError\",\n      \"URIError\",\n      \"Math\",\n      \"JSON\",\n      \"decodeURI\",\n      \"decodeURIComponent\",\n      \"encodeURI\",\n      \"encodeURIComponent\",\n      \"escape\",\n      \"isFinite\",\n      \"isNaN\",\n      \"parseFloat\",\n      \"parseInt\",\n      \"unescape\",\n\n      \"Object.is\",\n      \"Object.assign\",\n      \"Object.setPrototypeOf\",\n      \"Array.from\",\n      \"Array.prototype.find\",\n      \"Array.prototype.findIndex\",\n      \"String.prototype.endsWith\",\n      \"String.prototype.includes\",\n      \"String.prototype.repeat\",\n      \"String.prototype.startsWith\",\n      \"Number.isFinite\",\n      \"Number.isNaN\",\n      \"Number.isSafeInteger\",\n      \"Number.EPSILON\",\n      \"Number.MAX_SAFE_INTEGER\",\n      \"Math.sign\",\n      \"Math.trunc\",\n      \"WeakMap\",\n\n      \"Array.prototype.includes\",\n\n      \"Object.getOwnerOf\",\n      \"Object.setOwnerOf\",\n      \"Thread\",\n      \"PermissionError\",\n      \"Array.prototype.join\",\n      \"suspend\",\n      \"setTimeout\",\n      \"clearTimeout\",\n\n      \"perms\",\n      \"setPerms\",\n      \"$.root\",\n      \"$.system\",\n      \"user\",\n\n      \"$.utils\",\n      \"$.utils.array\",\n      \"$.utils.object\",\n      \"$.utils.string\",\n\n      \"$.utils.code\",\n      \"$.Selector\",\n      \"$.utils.Binding\",\n\n      \"$.utils.html\",\n\n      \"$.jssp\",\n\n      \"$.connection\",\n\n      \"$.utils.url\",\n      \"$.servers.http\",\n\n      \"$.hosts.root['/']\",\n      \"$.hosts.root['/mirror']\",\n      \"$.hosts.root['/robots.txt']\",\n      \"$.hosts.system\",\n      \"$.hosts.dummy\",\n      \"$.hosts.root.subdomains.connect\",\n      \"$.hosts.root.subdomains.login\",\n      \"$.hosts.root.subdomains.mobwrite\",\n      \"$.hosts.root.subdomains.static\",\n      \"$.hosts.root.subdomains.system\",\n\n      \"$.db.tempId\",\n\n      \"$.userDatabase\",\n\n      \"$.hosts.code['/inlineEdit']\",\n      \"$.hosts.code\",\n\n      \"$.servers.eval\",\n\n      \"$.utils.command\",\n\n      \"$.utils.commandMenu\",\n      \"$.utils.replacePhysicalsWithName\",\n\n      \"$.physical\",\n      \"$.utils.validate.physicals\",\n      \"$.garbage\",\n\n      \"$.user\",\n      \"$.room\",\n      \"$.thing\",\n      \"$.container\",\n\n      \"$.servers.login\",\n\n      \"$.servers.telnet\",\n\n      \"$.startRoom{proto}\",\n      \"$.startRoom{owner}\",\n      \"$.startRoom.location\",\n      \"$.startRoom.name\",\n      \"$.startRoom.description\",\n      \"$.startRoom.roll\",\n      \"$.clock\",\n\n      \"$.physicals['Das deutsche Zimmer']\",\n      \"$.tutorial\",\n\n      \"$.seed\",\n      \"$.pot\",\n      \"$.pot.stages\",\n      \"$.thrower\",\n\n      \"$.physicals['Genetics Lab']\",\n      \"$.cage\",\n      \"$.physicals['Genetic Mouse Prototype']\",\n      \"$.hosts.genetics\",\n      \"$.hosts.root.subdomains.genetics\",\n\n      \"$.assistant\",\n\n      \"$.physicals['Challenge room']\",\n      \"$.physicals['light switch']\",\n      \"$.physicals.chest\",\n      \"$.physicals.safe\",\n      \"$.physicals.food\",\n      \"$.physicals.girl\",\n\n      \"$.securityCourse\",\n      \"$.hosts.root['/securitycourse']\"\n    ]\n  }, {\n    \"filename\": \"../database/db_01_world.js\",\n    \"headerSubs\": {\n      \"<YEAR>\": \"2017\",\n      \"<OVERVIEW>\": \"Main database for google.codecity.world.\"\n    },\n    \"contents\": [\n      \"$.servers.http.Host.prototype.access\",\n      \"$.hosts.root.access\",\n      \"$.hosts.system.access\",\n      \"$.db.tempId.tempIds_\",\n      \"$\"\n    ]\n  }, {\n    \"options\": {\"treeOnly\": false}\n  }, {\n    \"filename\": \"../database/db_99_leftovers.js\",\n    \"header\": \"\",\n    \"rest\": true\n  }\n]\n"
  },
  {
    "path": "database/README",
    "content": "On startup, if no .city database file exists, the server will read and\nexecute all .js files in this directory in asciibetical order.  The\nfollowing naming convention has been established to keep things\norganised:\n\ncore*.js - The Code City core.\ndb*.js   - A dumped databse, if available, less core.\ntest*.js - Any tests to be run against the databse.\n"
  },
  {
    "path": "database/codecity.cfg",
    "content": "{\n  \"databaseDirectory\": \"./\",\n  \"checkpointInterval\": 60,\n  \"checkpointAtShutdown\": true,\n  \"checkpointMinFiles\": 10,\n  \"checkpointMaxDirectorySize\": 2048\n}\n"
  },
  {
    "path": "docs/setup.md",
    "content": "# Setting up a Code City Instance\n\nThis document describes how to recreate a Code City server from bare\nmetal.  For reference, the starting point is a Google Cloud Platform\naccount in good standing.\n\n\n## Google Compute Engine Setup\n\nWe recommend running your Code City server on a [Google Compute\nEngine](https://cloud.google.com/compute)</sup> (GCE) virtual\nmachine<sup>[[?]](\nhttps://en.wikipedia.org/wiki/Virtual_machine)</sup> (VM)—it’s\nreliable, minimal hassle, and, thanks to [Google Cloud Platform’s\n“Always Free” tier](https://cloud.google.com/free), can be (very\nnearly) free!\n\n### Create a GCE instance\n\nThis will create a dedicated GCE instance (VM) on which to run Code\nCity.  You can skip this step if you intend to run your instance on\nyour own machine or another cloud provider’s hardware.\n\nBefore you begin: the GCE instance (VM) you create will run using the\npermissions of a service account<sup>[[?]](\nhttps://cloud.google.com/iam/docs/service-accounts)</sup>.  There is a\n“Compute Engine default service account” which will work fine but has\nquite broad permissions.  You may wish to create a service account\nwith more limited permissions, to reduce the amount of damage an\nattacker can do if they compromise your Code City instance and gain\ncontrol of the VM on which it runs.  This is especially so if your GCP\nproject contains other resources (user data, etc.) which you wish to\nprotect.  See [Appendix A: Creating a Service Account](\n#appendix-a-creating-a-service-account) for instructions.\n\n1.  Go to the [Google Compute Engine\n    console](https://console.cloud.google.com/compute/instances).\n0.  Under VM Instances, click the create instance button ![blue icon\n    with white plus](instance-new.svg).  Enter details as follows:\n    *   Name: choose a name for the instance.  (This can be any name,\n        but we recommend you use a name matching your intended domain\n        name—e.g., `google.codecity.world` runs on an instance named\n        `google`.)\n    *   Region: choose a region near where you expect your users to\n        be.  Note that [instance pricing varies by\n        zone](https://cloud.google.com/compute/vm-instance-pricing).\n    *   Zone: choose any.\n    *   Machine type: choose an appropriate size.\n        *   [GCP’s “Always Free” tier][always-free] offers one free\n            `f1-micro` instance in any of `us-west1`, `us-central1` or\n            `us-east1`.  This size will be sufficient for many smaller\n            organisations/groups.\n        *   Because of the architecture of the Code City server, there\n            is unlikely to be any benefit to having more than two\n            vCPUs (and one is generally sufficient).\n    *   Container: no.\n    *   Boot disk: under “Public images”, choose:\n        *   Operating system: Debian\n        *   Version: choose the most recent version—“Debian GNU/Linux\n            10 (buster)” as of this writing.\n        *   Boot disk type: Standard persistent disk.\n        *   Size: the default 10GB is likely to be sufficient for most\n            cases, but the “Always Free” program offers up to 30GB\n            (total, not per-instance) of persistent disk free of\n            charge.\n    *   Identity and API access:\n        *   Service account: use the default “Compute Engine default\n            service account” or select the one you created by\n            following the instructions in [appendix A](\n            #appendix-a-creating-a-service-account).\n        *   Access scopes: Allow default access.\n    *   Firewall: Allow both HTTP and HTTPS traffic.\n    *   Management:\n        *   Recommended: tick “Enable deletion protection” to make it\n            harder to inadvertently delete your Code City instance.\n    *   Security:\n        *   Recommended: tick “Turn on Secure Boot”.\n        *   SSH Keys: you can add your ssh public key(s) here if you\n            wish; doing so will cause them to be automatically added\n            to the corresponding `~userid/.ssh/authorized_keys` file,\n            but note:\n            *   Keys added here apply only to this GCE instance.  If\n                you expect your project to have multiple instances you\n                may prefer to add your SSH keys on [the Compute Engine\n                metadata page](\n                https://pantheon.corp.google.com/compute/metadata/sshKeys)\n                instead: keys added there will have access to all the\n                project's GCE instances by default (i.e., unless you\n                tick \"Block project-wide SSH keys\" on a particular\n                instance).\n            *   Even if you don’t add any SSH keys now you will in any\n                case be able to SSH to the machine from [GCE instances\n                page](\n                https://console.cloud.google.com/compute/instances).\n    *   Disks:\n        *   Recommended: **un**tick “Delete boot disk when instance\n            deleted” so that if you _do_ delete your instance you can\n            recreate it easily and without losing user data.\n    *   Networking:\n        *   Under Network interfaces, click the pencil icon next to\n            the default interface.\n        *   External IP: ignore this section for now.\n        *   Public DNS PTR Record: optionally click “Enable” and enter\n            the [domain name](#set-up-an-ip-address-and-domain-name)\n            you intend to use for your instance,\n            e.g. <code><em>example</em>.codecity.world</code>.\n        *   Click “Done” to end editing the network interface.\n0.  Double-check the monthly cost estimate (at the top of the page) to\n    ensure it is reasonable.\n0.  Click “create” and you will be taken back to the VM instances\n    dashboard.  After a few minutes, you should see your new instance\n    is ready, and has internal and external IP addresses.\n0.  Under “Connect”, click on “SSH” for your instance.\n0.  Verify instance is running Debian 10:\n    ```\n    $ uname -a\n    Linux instancename 4.19.0-9-cloud-amd64 #1 SMP Debian 4.19.118-2+deb10u1 (2020-06-07) x86_64 GNU/Linux\n    ```\n\n[always-free]: https://cloud.google.com/free/docs/gcp-free-tier#always-free-usage-limits\n[service-account]: https://cloud.google.com/iam/docs/creating-managing-service-accounts\n\n#### Reserve a Static IP Address\n\nFor users to be able to access your instance from the Internet, it\nwill need a static IP address<sup>[[?]](\nhttps://en.wikipedia.org/wiki/IP_address) (like 192.0.2.1) so that\ntraffic can be routed to it.\n\n1.  Go to the [Networking / External IP addresses\n    console](https://console.cloud.google.com/networking/addresses).\n0.  Click “+ Reserve Static Address”.  Enter details as follows:\n    *   Name: can be any value, but we recommend you use the same name\n        as for your instance.  This is just used to identify the\n        address reservation.\n    *   Description: enter any text you like—e.g.: “Static IP\n        address for <em>example</em>.codecity.world.”\n    *   Network Service Tier: choose either.  See [description of\n        options](https://cloud.google.com/network-tiers/) and [pricing\n        information](https://cloud.google.com/network-tiers/pricing).\n    *   IP vesion: IPv4.\n    *   Type: Regional.\n        *   Region: choose the same region as your instance was\n            created in.\n        *   Attached to: choose your instance from the drop-down.\n0.  Click “Reserve”.\n0.  Make a note of the external address (like 192.0.2.1) which you\n    have just reserved for your instance.\n\n### Give Your Instance a Domain Name\n\nThe Domain Name System<sup>[[?]](\nhttps://en.wikipedia.org/wiki/Domain_Name_System)</sup> is a\ndistributed global database that maps domain names (like\n`example.org`) to IP addresses (like 192.0.2.1).\n\nIn order for users to be able to access your instance without having\nto know the numeric static IP address you reserved in the previous\nsection, you must create a human-readable domain mame<sup>[[?]](\nhttps://en.wikipedia.org/wiki/Domain_name)</sup> for it.\n\nThe details of this process are outside of the scope of this document,\nbut we have the following observations and recommendations:\n\n*   Setting up DNS involves two distinct entities: a domain name\n    registrar<sup>[[?]](\n    https://en.wikipedia.org/wiki/Domain_name_registrar)</sup>, from\n    whom you can purchase a domain name (like `example.org`), and a\n    DNS provider, who runs the name servers<sup>[[?]](\n    https://en.wikipedia.org/wiki/Name_server)</sup> that resolve\n    individual DNS entries (like `www.example.com`) to specific\n    numeric IP addresses like the one created in the previous section.\n    \n    In many cases both these services will be provided by the same\n    company, but many organisations will typically run their own DNS\n    servers, or outsource it to a [managed DNS provider](\n    https://en.wikipedia.org/wiki/List_of_managed_DNS_providers).\n\n*   If you are using your own domain name (e.g.,\n    <code>codecity.<em>example.org</em></code>) this will be done\n    through your DNS provider’s configuration console or via your\n    internal organisational DNS service configuration.\n\n*   Alternatively we may in some cases be able to offer you the\n    use of a Code City subdomain (e.g.,\n    <code><em>example</em>.codecity.world</code>), in which case\n    we will take care of this step for you.  Contact us for\n    details.\n\n*   Because of the [same origin policy], if you’d like to allow\n    individual (not fully trusted) users of your instance to be able\n    to create their own web pages / servers, we *strongly* recommend\n    that you use a wildcard DNS record<sup>[[?]](\n    https://en.wikipedia.org/wiki/Wildcard_DNS_record)</sup>, so that\n    each user can serve their content on an isolated subdomain (like\n    <code><em>username</em>.example.codecity.world</code>).\n    *  You will need to create (or arrange to have created) two\n       separate DNS \"A\" records for your domain name:\n       *   The main entry, e.g. `example.codecity.world`, type `A`,\n           resolving to your instance's IP address, and\n       *   The wildcard entry, e.g. `*.example.codecity.world`, also\n           type `A`, resolving to the same IP address.\n    *  To facilitate obtaining the necessary wildcard\n       certificate<sup>[[?]](\n       https://en.wikipedia.org/wiki/Wildcard_certificate)</sup>, we\n       recommend you use a [DNS provider who easily integrates with\n       Let’s Encrypt DNS validation][dns-providers], such as [Google\n       Cloud DNS](https://cloud.google.com/dns/), if possible.\n \n[same origin policy]: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy\n[dns-providers]: https://community.letsencrypt.org/t/dns-providers-who-easily-integrate-with-lets-encrypt-dns-validation/86438\n \n### Recommended: schedule regular, automatic backups of your instance’s disk\n\nIt’s always best to back up!  Even though the Code City server\nregularly checkpoints its database to the instance’s persistent disk,\nsetting up regular snapshotting of that disk will give you a separate\nbackup of the whole system in case of disaster.\n\nSnapshots are [not free], but [are cheap].  A few dollars a month buys a\nlot of peace of mind!\n\n[not free]: https://cloud.google.com/compute/disks-image-pricing#persistentdisk\n[are cheap]: https://cloud.google.com/compute/disks-image-pricing#persistent_disk_snapshots_storage_charges\n\nFirst, create a snapshot schedule:\n\n1.  Go to the [GCE Snapshots page](\n    https://console.cloud.google.com/compute/snapshots) and click on\n    the “Snapshot Schedules” tab.\n0.  Click on Create Snapshot Schedule.  Enter details as follows:\n    *   Name: choose a name for the schedule, e.g. `daily-14`.\n    *   Description: anything, e.g. “Daily snapshots, kept for 14\n        days”.\n    *   Snapshot location: Regional.\n    *   Region: choose the same region as your instance.\n    *   Schedule frequency: hourly, daily or weekly as you prefer; for\n        this example: daily.  (N.B.: more frequent snapshots will\n        result in more data to be stored and thus higher costs.)\n    *   Start time: any.  Snapshotting will not affect the running\n        instance, so choose whatever time of day you wish.\n    *   Auto-delete snapshots after: choose a suitable period of time;\n        for this example: 14 days.\n    *   Deletion rule: as you wish: “keep snapshots” better protects\n        against data loss in the event that your instance is\n        *inadvertently* deleted; “delete snapshots after _N_ days”\n        better protects against continuing to be charged fees after\n        you *deliberately* delete your instance.\n    *   Enable VSS: no.  (Not applicable to non-Windows instances.)\n    *   Snapshot labels: not needed.\n0.  Click “Create” to create the schedule.\n\nNow apply the schedule to your instance’s persistent disk:\n\n4.  Go to the [GCE Disks page](\n    https://console.cloud.google.com/compute/disks).\n0.  Click on the name of the persistent disk for your instance.  (By\n    default it will have the same name you gave to your instance.)\n0.  Click on “Edit” at the top of the screen.\n0.  Under Snapshot schedule, select the schedule you created in steps\n    1–3.\n0.  Click Save.\n\n## Set Up Machine and Install Code City\n\nThese instructions assume you are using a GCE instance running Debian\nGNU/Linux 10 \"buster\", but feel free to adapt to your particular\nset-up.\n\n1.  Log into your instance.  (See instructions in first section if\n    using GCE.)\n0.  If your machine has less than 2GB of memory (check with `free -h`;\n    the very first number shown is total RAM), you will need to create\n    a swap file (this is mandatory on `f1-micro` instances):\n    ```\n    sudo -i\n    fallocate -l 2G /swapfile\n    chmod 600 /swapfile\n    mkswap /swapfile\n    swapon /swapfile\n    swapon -s\n    sh -c 'echo \"/swapfile none swap sw 0 0\" >> /etc/fstab'\n    exit\n    ```\n0.  Check for and install system updates, then install\n    [nginx](https://en.wikipedia.org/wiki/Nginx) and\n    [git](https://git-scm.com/):\n    ```\n    sudo apt-get update\n    sudo apt-get upgrade –y\n    sudo apt-get install -y nginx git\n    ```\n0.  Optionally install a text editor of your choice.  Debian comes\n    with [`vim`](https://www.vim.org/) and\n    [`nano`](https://www.nano-editor.org/) preinstalled; Emacs users\n    might feel more at home with the lightweight editors\n    [`mg`](https://github.com/hboetes/mg),\n    [`jove`](https://github.com/jonmacs/jove) or\n    [`zile`](https://www.gnu.org/software/zile/), or opt for\n    `emacs-nox` which is GNU Emacs without X Windows bindings.\n    ```\n    sudo apt-get install mg\n    ```\n0.  Install [node.js](https://nodejs.org/).  Code City depends on\n    version 12, which is more recent than the version included in\n    Debian 10, so we will obtain it via [NodeSource](\n    https://github.com/nodesource/distributions):\n    ```\n    sudo -i\n    curl -sL https://deb.nodesource.com/setup_12.x | bash -\n    apt-get install -y nodejs\n    exit\n    ```\n0.  Verify the correct version of node is installed:\n    ```\n    $ node –-version\n    v12.18.4\n    ```\n    (Actual version may be later than 12.18.)\n\n### Get TLS Certificates\n\nIn order to allow incoming HTTPS connections, you will need an\nTLS<sup>[[?]](https://en.wikipedia.org/wiki/Transport_Layer_Security)</sup>\nserver certificate<sup>[[?]](\nhttps://en.wikipedia.org/wiki/Public_key_certificate#TLS/SSL_server_certificate\n)</sup>.  There are two types:\n\n*   An ordinary certificate covers one or more specific domain names,\n    like `www.example.org`.\n*   A wildcard certificate includes one or more wildcard domains, like\n    `*.example.org`.\n\nYou will need to get a TLS certificate covering the [set of DNS entries\nyou [created earlier](#set-up-an-ip-address-and-domain-name).  If (as\nrecommended) you created a wildcard DNS entry, you will also need a\ncorresponding wildcard TLS certificate.\n\nThere are various ways to get a TLS certificate, but a free and easy\nway is to use [Certbot](https://certbot.eff.org/) to get one from\n[Let’s Encrypt](https://letsencrypt.org/).  That’s what we’ll do here.\n\n#### Getting a wildcard certificate\n\nTo use Certbot to get a wildcard certificate, you will need to use the\n[`dns-01` challenge](\nhttps://letsencrypt.org/docs/challenge-types/#dns-01-challenge), which\nrequires being able to create DNS TXT records<sup>[[?]](\nhttps://en.wikipedia.org/wiki/TXT_record)</sup> for your domain name.\nHere’s an example of how to do this if using Google Cloud DNS; see\n[full instructions on the certbot website](\nhttps://certbot.eff.org/lets-encrypt/debianbuster-nginx) if you use\nanother provider.\n\n1.  Install certbot and the required plug-ins:\n    ```\n    sudo apt-get install -y certbot python3-certbot-dns-google\n    ```\n0.  Obtain credentials from your DNS provider, to allow Certbot to\n    create TXT records, proving to Let’s Encrypt that you control your\n    domain.  It [should be possible to skip this step](\n    https://certbot-dns-google.readthedocs.io/en/stable/#credentials)\n    when using Google Cloud DNS and running Certbot on GCE instance,\n    but alas [due to a bug](\n    https://github.com/certbot/certbot/issues/7933) this doesn’t yet\n    work in Debian 10.\n    1.  Go to the [Service Accounts](\n        https://console.cloud.google.com/iam-admin/serviceaccounts)\n        tab of the IAM & Admin section of the GCP console.\n    0.  Find the service account under which your GCE instance runs;\n        unless you elected otherwise above, this will be the one named\n        “Compute Engine default service account”.  Click on the email\n        address for the key to open the details pane.\n    0.  Click on the keys tab.\n    0.  From the Add Key pop-up menu, select “Create new key”.\n        *   Choose Key Type: JSON.\n        *   Click “Create”.\n    0.  Your browser will download a file with a name of the form\n        <code>scp <em>projectID–XXXXXXXXXXXX</em>.json</code>.  Now,\n        transfer this file to your GCE instance using\n        [`scp`](https://en.wikipedia.org/wiki/Secure_copy) **on your\n        local machine**, e.g. <code>scp\n        <em>projectID–XXXXXXXXXXXX</em>.json\n        <em>example</em>.codecity.world:service-account.json</code>,\n        or by pasting it into a terminal window, as follows:\n        *   Open the `.json` file you downloaded in step 2.iv. in a\n            text editor, select the whole contents and copy it to the\n            clipboard.\n        *   **On your instance**, enter the command `cat - >\n            service-account.json `\n        *   Paste the contents of the `.json` into the SSH window.\n        *   Type `^D` to indicate end of file.\n    0.  This credentials file will be needed when initially obtaining\n        the TLS certificate as well as every few months when [Certbot\n        will automatically renew it](\n        https://certbot.eff.org/docs/using.html#automated-renewals),\n        so move it to a safe place and protect it from tampering:\n        ```\n        sudo mv service-account.json /etc/service-account.json\n        sudo chown root:root /etc/service-account.json\n        sudo chmod 600 /etc/service-account.json\n        ```\n0.  Request a certificate for both the base domain name for your\n    instance and the corresponding wildcard entry:\n    ```\n    sudo certbot certonly --dns-google \\\n         --dns-google-credentials /etc/service-account.json \\\n         --post-hook 'systemctl reload nginx' \\\n         -d 'example.codecity.world,*.example.codecity.world'\n    ```\n    If you have more than one DNS entry pointing at your instance,\n    just add further comma-separated entries to the list after the\n    `-d` directive.  (N.B.: No spaces between entries in this list!)\n    *   Enter your email address when prompted.\n    *   Agree the terms of service.\n    *   Optionally agree to share your email address with the EFF.\n\n#### Getting a non-wildcard certificate\n\nThis process is a little simpler and does not require the ability to\nmodify DNS TXT records.\n\n1.  Install certbot (only):\n    ```\n    sudo apt-get install -y certbot\n    ```\n\n0.  Request a certificate for the base domain name for your instance\n    (only):\n    ```\n    sudo certbot certonly --webroot --webroot-path /var/www/html \\\n         --post-hook 'systemctl reload nginx' \\\n         -d example.codecity.world\n    ```\n    *   Enter your email address at the prompt\n    *   Agree the terms of service.\n    *   Optionally agree to share your email address with the EFF.\n\n### Install Code City\n\n1.  Create an account for Code City to run under.  This is to isolate\n    it from any other users/services on the machine, and contain the\n    damage in the event that the server sandbox be compromised.  We’ll\n    call the account `codecity` here, but any username is fine:\n    ```\n    sudo useradd -rms /bin/bash codecity\n    ```\n0.  Become the code city account:\n    ```\n    sudo -iu codecity\n    ```\n0.  Clone the [Code City\n    repo](https://github.com/google/CodeCity).  (If you are a\n    project collaborator, see below for [instructions on how to use\n    SSH instad of HTTPS](#git-code-city-by-ssh-instead-of-https).)\n    ```\n    git clone https://github.com/google/CodeCity.git\n    ```\n0.  Install required NPMs:\n    ```\n    (cd CodeCity/server && npm ci --only=prod)\n    (cd CodeCity/login && npm ci --only=prod)\n    ```\n0.  Exit from the `codecity` account.  We’re done with it for now, and\n    we need to be able to sudo, which that account (deliberately) does\n    not have permission to do.\n    ```\n    exit\n    ```\n\n### Configure NGINX\n\nOn Debian, per-host `nginx` configuration files are stored in\n`/etc/nginx/sites-available` and enabled by symlinking them into\n`/etc/nginx-sites-enabled`.  There is a `default` config supplied by\nthe `nginx` package, which should be disabled (unless you have already\nmodified it to serve other virutal hosts).\n\n1.  Install the NGINX configuration file.  If you have a wildcard DNS\n    record and corresponding wildcard TLS certificate, use the\n    “subdomain” configuration:\n    ```\n    sudo cp ~codecity/CodeCity/etc/cc-subdomain.conf \\\n            /etc/nginx/sites-available/codecity\n    ```\n    Otherwise, use the “onedomain” configuration:\n    ```\n    sudo cp ~codecity/CodeCity/etc/cc-onedomain.conf \\\n            /etc/nginx/sites-available/codecity\n    ```\n0.  Edit /etc/nginx/sites-enabled to replace INSTANCENAME with the\n    name(s) of your instance.  (See comments for details.  You may use\n    another editor instead of nano if you wish!)\n    ```\n    sudo nano /etc/nginx/sites-available/codecity\n    ```\n0.  Enable the new configuration and reload (or restart) NGINX:\n    ```\n    sudo rm /etc/nginx/sites-enabled/default\n    sudo ln -s /etc/nginx/sites-available/codecity \\\n               /etc/nginx/sites-enabled/codecity\n    sudo systemctl reload-or-restart nginx\n    ```\n\n### Create an API Key for OAuth\n\nThe usual set-up for public Code City instances is to use [OAuth\n2.0](https://oauth.net/2/) via Google’s OAuth service for logins.\nThis step will set up the necessary credentials to allow users to log\nin to your instance using their Google (Gmail) account.  You can skip\nthis step if you intend to use a different login mechanism.\n\nThis must be done after installing nginx and CodeCity and obtaining a\nTLS certificate because it depends on `logo-auth.png` being served by\nnginx.\n\n1.  Optionally replace `~codecity/CodeCity/static/logo-auth.png` with\n    a logo representing your instance or organisation.  It should be a\n    120x120px PNG image.\n0.  Make sure you can access your desired logo using your web browser.\n    If you are using a wildcard DNS configuration, it should be\n    accessible via a URL like\n    <code>static.<em>example</em>.codecity.world/logo-auth.png</code>;\n    for a single-domain configuration it will instead be\n    <code><em>example</em>.codecity.world/static/logo-auth.png</code>.\n    Make a note of this URL.\n0.  Go to [APIs & Services > OAuth consent screen](\n    https://console.cloud.google.com/apis/credentials/consent).  Enter\n    details as follows:\n    *   Email address: select a suitable contact email address or\n        Google Group for users of your service.\n    *   Product name: this should include the name of your\n        organisation; it may optionally contain the name “Code City”;\n        it should not include “Google” or the like. N.B.: the same\n        details are used for all services offered via a given Google\n        Cloud Platform account.\n    *   Homepage URL: this could be your organisation’s homepage or\n        the URL of the front page for your instance (perhaps\n        <code><em>example</em>.codecity.world</code> or\n        <code>codecity.<em>yourdomain.tld</em></code>)\n    *   Product logo URL: Should point at the URL for your your logo,\n        as determined in step 2 above.\n    *   Privacy policy URL: Provide a link to your privacy policy.\n    *   Terms of service URL: may be left blank.\n0.  Go to the [APIs & Services > Credentials\n    console](https://console.cloud.google.com/apis/credentials).\n0.  Click “Create credentials”; choose OAuth client ID.  Enter details\n    as follows:\n    *   Application type: Web application\n    *   Name: a suitable full name for your instance, (e.g. “Code City\n        for Springfield Highschool”).\n    *   Authorized JavaScript origins: may be left blank.\n    *   Authorized redirect URIs: for wildcard DNS configurations this\n        will be of the form `https://login.example.codecity.world/`;\n        for single-domain configurations it will instead be\n        `https://example.codecity.world/login/`.\n0.  Click Save.\n0.  Now click on the newly-created client ID.  Make a note of the\n    Client ID (it will be a long string like\n    “00000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com”)\n    and the Client Secret (a shorter but similarly opaque jumble of\n    characters).  You will need these later.\n\nSee also the [complete GCP OAuth 2.0 documentation](\nhttps://support.google.com/cloud/answer/6158849) for more information.\n\n### Configure Code City\n\n1.  Become the code city account:\n    ```\n    sudo -iu codecity\n    ```\n0.  Create a config file for loginServer:\n    *   Run loginServer once to create an empty config file:\n        ```\n        (cd ~/CodeCity/login && ./loginServer)\n        ```\n        Open `~/CodeCity/login/loginServer.cfg` in the text editor of\n        your choice.\n    *   Set `connectUrl` to the URL for the connect server.  If using\n        a wildcard DNS entry for your instance, it will be the\n        `connect.` subdomain of your instance’s name; otherwise it\n        will be the `/connect` path on your instance.  For example:\n        *   With wildcard DNS: `https://connect.example.codecity.world/`\n        *   Without wildcard DNS:`https://example.codecity.world/connect/`\n    *   Set `staticUrl` to the URL nginx will serve static content on.\n        This works similarly to the previous entry, e.g.:\n        *   With wildcard DNS: `https://static.example.codecity.world/`\n        *   Without wildcard DNS:`https://example.codecity.world/static/`\n    *   Set `clientID` and `clientSecret` to the values obtained\n        earlier from [Google’s API Console](\n        https://console.developers.google.com/apis).\n    *   Set `cookieDomain` to your instance’s base domain name, e.g.:\n        `example.codecity.world`.\n    *   Set `password` to a secret, random string.  If you don’t have\n        a convenient way to generate one locally, you can copy a\n        [random string from random.org].\n    *   Optionally, set `emailRegexp` to a [JavaScript regexp]\n        matching email addresses which should be permitted to log in\n        to your instance—e.g., `^.*@myorganisation\\\\.org$`.\n0.  Create and edit a config file for connectServer:\n    *   Run connectServer once to create an empty config file:\n        ```\n        (cd ~/CodeCity/connect && ./connectServer)\n        ```\n        Open `~/CodeCity/connect/connectServer.cfg` in the text editor\n        of your choice.\n    *   Set `loginUrl` to the URL for the login server, e.g.:\n        *   With wildcard DNS: `https://login.example.codecity.world/`\n        *   Without wildcard DNS:`https://example.codecity.world/login/`\n    *   Set `staticUrl` and `password` to the _same_\n        values used in `loginServer.cfg`.\n0.  Modify the configuration for the in-core HTTP server:\n    *   Open the file `~/CodeCity/core/core_99_startup.js` in the text\n        editor of your choice.  Find the optional configuration\n        section near the top of the file.\n    *   Set `$.hosts.root.hostname` to your instance’s domain\n        name—e.g., <code>$.hosts.root.hostname =\n        '<em>example</em>.codecity.world';</code>\n    *   Set `$.hosts.root.pathToSubdomain = false;` if you are using a\n        wildcard DNS entry for your instance; otherwise set it to\n        `true`.\n    *   If you have more than one DNS entry for your instance, set\n        `$.hosts.root.hostRegExp` according to the instructions\n        provided.\n0.  Save the file, exit your editor and exit from the `codecity`\n    account.\n    ```\n    exit\n    ```\n\n[JavaScript regexp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n[random string from random.org]: https://www.random.org/strings/?num=1&len=20&digits=on&upperalpha=on&loweralpha=on&unique=on&format=html&rnd=new\n\n### Configure Systemd and Start Code City Servers\n\n1.  Install the systemd config files:\n    ```\n    sudo cp ~codecity/CodeCity/etc/*.service /etc/systemd/system\n    ```\n0.  Check the contents of `/etc/systemd/system/codecity.service`,\n    …`codecity-login.service` and …`codecity-connect.service`; verify\n    paths, usernames etc. all match the values created in previous\n    steps.\n0.  Enable Code City services with systemd:\n    ```\n    sudo systemctl enable --now codecity\n    ```\n0.  Verify you can connect to your new Code City instance by pointing\n    your web browser its domain name—e.g., `https://example.codecity.world`.\n\nCongratulations, you're done!\n\n## Appendix A: Creating a Service Account\n\nTo protect any other Google Cloud Platform services you run against\nthe consequences of your Code City instance being compromised, you can\nhave the GCE VM it runs on use only the limited permissions of a\ncustom service account, rather than the extensive permissions held by\nthe Compute Engine default service account.  To do this there are three\nsteps:\n\n1.  Creating one or more roles for the service account.\n0.  Creating a service account\n0.  Applying the service account to the GCE instance.\n\n### Create Role(s)\n\nYou should create one role for running CodeCity instances on GCE, and\noptionally create a second role if you intend to have your GCE\ninstance [obtain wildcard TLS certificates using certbot via the ACME\nHTTP-01 challenge](#getting-a-wildcard-certificate).\n\n1.  Go to the [Roles tab of IAM & Admin](\n    https://console.cloud.google.com/iam-admin/roles).\n0.  Create a role for running a Code City instance by clicking “+\n    Create Role” then enter details as follows:\n    *   Title: “CodeCity Instance”.\n    *   Description: “Base role for all CodeCity instances.  Created\n        on: …”.\n    *   ID: `instance`.\n    *   Add the following permissions by clicking “+ Add Permissions”\n        button, typing the name of the permission into the “Filter\n        table” field (*not* the “Filter permissions by role” field),\n        selecting required permission, and clicking Add:\n        *   `compute.globalOperations.get`\n        *   `compute.zoneOperations.get`\n        *   `logging.logEntries.create`\n    *   Click “Create”.\n0.  Optionally create a second role for obtaining wildcard certs by\n    again clicking “+ Create Role” and entering:\n    *   Title: “CodeCity Cert-via-DNS”\n    *   Description: “Add-on permission to allow an instance to update\n        its own wildcard letsencrypt SSL cert via an ACME dns-01\n        challenge.  Created on: …”.\n    *   ID: `dnscert`.\n    *   Add the following permisions:\n        *   `dns.changes.create`\n        *   `dns.changes.get`\n        *   `dns.managedZones.list`\n        *   `dns.resourceRecordSets.create`\n        *   `dns.resourceRecordSets.delete`\n        *   `dns.resourceRecordSets.list`\n        *   `dns.resourceRecordSets.update`\n    *   Click “Create”.\n\n### Create a Service Account\n\nNow you can create a service account for your instance.\n\n1.  Go to the [Service Accounts tab of IAM & Admin](\n    https://console.cloud.google.com/iam-admin/serviceaccounts).\n0.  Click “+ Create Servce Account” and enter details as follows:\n    *   Service account name: choose and appropriate name such as\n        “CodeCity instance” or “instance-<em>myInstanceName</em>”.\n    *   Service account ID: modify suggested ID if desired.\n    *   Service account description: “Service account for the\n        <em>example</em>.codecity.world instance” or similar.\n0.  Click “Create”.\n    *   Where it says “Select a role”, select “CodeCity Instance”.\n    *   If you intend to use certbot to obtain a wildcare DNS cert,\n        click “+ Add Another Role” and select “CodeCity Cert-via-DNS”.\n0.  Click “Continue”.\n0.  Click “Done.\n\n### Use the Service Account to run your GCE Instance\n\nIf you have not yet done so, simply [follow the instructions to create\na GCE instance for Code City](#create-a-gce-instance) and, when you\nget to the “Identity and API access” section of the creation wizard,\nselect the service account you created previously.\n\nOtherwise, if you have already created your GCE instance, configure it\nto use the newly-create service account as follows:\n\n1.  Go to the [VM instances tab](\n    https://console.cloud.google.com/compute/instances).\n0.  Select the VM instance you created previously.\n0.  Click the stop button at the top of the page to stop it, if it is\n    running.\n0.  Click the name of your instance to view its “VM instnace details”\n    page.\n0.  Click “Edit”.\n0.  Scroll down to “Service account” and select the service account\n    you created previously.\n\n## Appendix B: Remote Debugging\n\nIf you need to debug the server because it has stopped responding to\nnetwork activity, here’s how to do that:\n\n\n1.  SSH in to the GCE instance and enable the inspector on the running server:\n    *   <code>$ <strong>sudo kill -s SIGUSR1 `pidof codecity`</strong></code>\n0.  Look in /var/log/daemon.log for a message like:\n    ```\n    Feb 26 01:22:49 google codecity[19464]: Debugger listening on ws://127.0.0.1:9229/8df977b7-024d-464d-84c2-44321dd5b398\n    Feb 26 01:22:49 google codecity[19464]: For help, see: https://nodejs.org/en/docs/inspector\n    ```\n    Note the port number (in this case 9229).\n0.  SSH in to the GCE instance again, enabling port forwarding:\n    ```\n    ssh -L 9229:localhost:9229 google.codecity.world\n    ```\n    *   The initial 9229 can be replaced with a local port number of\n        your choice.\n    *   The `:localhost:` directive ensures that only processes\n        running on your local machine can make use of the port\n        forward.\n0.  Open the inspector in Chrome by going to\n    [`chrome://inspect`](chrome://inspect).\n\n(Based on [node.js debugging documentation](\nhttps://nodejs.org/en/docs/guides/debugging-getting-started/) and [a\nrelated blog post](\nhttps://hackernoon.com/debugging-node-without-restarting-processes-bd5d5c98f200).)\n\n\n## Appendix C: Additional Instructions for Code City Collaborators\n\n### GIT Code City by SSH instead of HTTPS\n\nDuring early development, the Code City repository was private so it\nwas necessary to do the `git clone` by SSH instead of HTTPS.  We\ncontinue to do this on our production instance to allow commits to the\n`prod` branch to be made from there if necessary.\n\nTo avoid putting SSH private keys on the instance, we use SSH agent\nforwarding.  This would mostly be automatic except that we also need\nto be able to use our personal credentials as the user `codecity`.\nThe solution is adapted [from Server Fault](\nhttps://serverfault.com/questions/107187).\n\n#### Preparation (do once)\n\n1.  Add your SSH public key (ideally, one from a hardware token or the\n    like) to [your GitHub account](https://github.com/settings/keys).\n0.  Verify that you can ssh to GitHub from your local workstation:\n    ```\n    ssh -T git@github.com\n    ```\n    Output should look like “<code>Hi <em>username</em>! You've\n    successfully authenticated, but GitHub does not provide shell\n    access.</code>”\n0.  Edit `~/.ssh/config` to add the following directive, if not\n    already present:\n    ```\n    ForwardAgent yes\n    ```\n    This will enable agent forwarding by default.\n\n#### When setting up a CodeCity GCE instance\n\nThese instructions replace step 3 of [Install & Configure Code\nCity](#install--configure-code-city).\n\n4.  Ensure that your SSH public key can be used to log in to the\n    instance.  This can be done in two ways:\n    *   Preferred: add it to [the Compute Engine metadata page](\n        https://pantheon.corp.google.com/compute/metadata/sshKeys).\n    *   Alternatively: add it to the instance at creation or by\n        editing the instance on [the GCE instances page](\n        https://console.cloud.google.com/compute/instances).\n    *   Alternatively: log into the instance initially using the\n        browser-based SSH available via the GCE console.  Use the text\n        editor of your choice to append your SSH public key to\n        `~/.ssh/authorized_keys`.\n0.  Ensure you can ssh to your instance from the command line of your\n    local machine.  Use `-A` to enable agent forwarding (`ssh -A\n    example.codecity.world`) or add `ForwardAgent yes` to your\n    `~/.ssh/config` file.\n0.  From your instance, verify that agent forwarding is working:\n    ```\n    ssh -T git@github.com\n    ```\n    (Expected output similar to step 2 above above.)\n0.  Install the acl package:\n    ```\n    sudo apt-get install -y acl\n    ```\n0.  On your instance, after creating the `codecity` user, add the\n    following to your `.bashrc` or `.bash_login`:\n    ```\n    setfacl -m codecity:x $(dirname \"$SSH_AUTH_SOCK\")\n    setfacl -m codecity:rw \"$SSH_AUTH_SOCK\"\n    ```\n0.  Modify the machine’s sudo config to tell sudo not to wipe\n    `SSH_AUTH_SOCK` from the environment:\n    ```\n    sudo visudo -f /etc/sudoers.d/ssh-agent-forwarding\n    ```\n    * Add the line\n    ```\n    Defaults env_keep+=SSH_AUTH_SOCK\n    ```\n    then save and exit.\n0.  When becoming the codecity user, be sure to use “`sudo -iu\n    codecity`” instead of “`sudo su - cc`”—the latter will clear the\n    needed `SSH_AUTH_SOCK` environment variable.\n0.  Install Code City using the SSH repository path:\n    ```\n    git clone git@github.com:google/CodeCity.git\n    ```\n\n#### Getting SSL Certificates\n\nGoogle-internal GCE instances are by default firewalled to prevent\ninbound access from the Internet; this causes Certbot’s ACME checks to\nfail.  The preferred solution is to use the DNS-01 challenge, even if\nno wildcard cert is required.\n"
  },
  {
    "path": "etc/apache.conf",
    "content": "# Template for Apache configuration.\n\n<VirtualHost *:80>\n\t# HTTP should redirect to HTTPS.\n\tRewriteEngine On\n\tRewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]\n</VirtualHost>\n\n<VirtualHost *:443>\n        # '.academy' should redirect to '.world'.\n        ServerName XXXXX.codecity.academy\n\n        RewriteEngine On\n        RewriteRule ^/?(.*) https://XXXXX.codecity.world/$1 [R,L]\n\n        SSLEngine on\n        Include /etc/letsencrypt/options-ssl-apache.conf\n        SSLCertificateFile /etc/letsencrypt/live/XXXXX.codecity.world/fullchain.pem\n        SSLCertificateKeyFile /etc/letsencrypt/live/XXXXX.codecity.world/privkey.pem\n</VirtualHost>\n\n<VirtualHost *:443>\n        # '.games' should redirect to '.world'.\n        ServerName XXXXX.codecity.games\n\n        RewriteEngine On\n        RewriteRule ^/?(.*) https://XXXXX.codecity.world/$1 [R,L]\n\n        SSLEngine on\n        Include /etc/letsencrypt/options-ssl-apache.conf\n        SSLCertificateFile /etc/letsencrypt/live/XXXXX.codecity.world/fullchain.pem\n        SSLCertificateKeyFile /etc/letsencrypt/live/XXXXX.codecity.world/privkey.pem\n</VirtualHost>\n\n<VirtualHost *:443>\n        ServerName XXXXX.codecity.world\n\n        Alias /static /home/cc/CodeCity/static\n        <Directory /home/cc/CodeCity/static>\n                Options Indexes Includes FollowSymLinks\n                AllowOverride All\n                Require all granted\n        </Directory>\n\n        ProxyPass /login http://localhost:7781/login\n        ProxyPassReverse /login http://localhost:7781/login\n\n        ProxyPass /connect http://localhost:7782/connect\n        ProxyPassReverse /connect http://localhost:7782/connect\n\n        ProxyPass /mobwrite http://localhost:7783/mobwrite\n        ProxyPassReverse /mobwrite http://localhost:7783/mobwrite\n\n        # Must be last, or else it will grab all requests.\n        ProxyPass /static !\n        ProxyPass / http://localhost:7780/\n        ProxyPassReverse / http://localhost:7780/\n\n        ErrorLog /home/cc/error.log\n        CustomLog /home/cc/access.log combined\n\n        SSLEngine on\n        Include /etc/letsencrypt/options-ssl-apache.conf\n        SSLCertificateFile /etc/letsencrypt/live/XXXXX.codecity.world/fullchain.pem\n        SSLCertificateKeyFile /etc/letsencrypt/live/XXXXX.codecity.world/privkey.pem\n</VirtualHost>\n"
  },
  {
    "path": "etc/cc-localhost.conf",
    "content": "# Nginx configuration for Code City on localhost.\n# Warning: This configuration is insecure, users can hijack each other's perms.\n#\n# The easiest way to use this file is to leave it unedited and instead\n# start nginx using bin/nginx-dev, which will dynamically create\n# suitable config files on the fly.\n\n# Configuration applying to all servers.\nerror_page 502 503 504 =503 /static/503.html;\n\n# Configuration applying to all proxy forwarding.\nproxy_set_header Host $http_host;\nproxy_set_header Forwarded $proxy_add_forwarded;  # See below.\nproxy_set_header CodeCity-pathToSubdomain \"?1\";\nproxy_pass_header Server;\nproxy_next_upstream_tries 1;\nproxy_max_temp_file_size 0;\nproxy_connect_timeout 10s;\nproxy_send_timeout 10s;\nproxy_read_timeout 10s;\n\nserver {\n  # Listen on port 8080 for both IPv6 and IPv4.\n  listen [::]:8080 ipv6only=off;\n\n  location / {\n    # Proxy to Code City port 7780.\n    proxy_pass http://127.0.0.1:7780/;\n  }\n\n  location /static/ {\n    # Static files.\n    autoindex on;\n    index index.html;\n    # Edit to be full path to CodeCity directory.\n    # E.g. /home/userid/src/CodeCity\n    root REPOSITORY;\n  }\n\n  location /login {\n    # Proxy to loginServer.js port 7781.\n    proxy_pass http://127.0.0.1:7781/login;\n  }\n\n  location /connect {\n    # Proxy to connectServer.js port 7782.\n    proxy_pass http://127.0.0.1:7782/connect;\n  }\n\n  location /mobwrite {\n    # Proxy to mobwrite_server.py port 7783.\n    proxy_pass http://127.0.0.1:7783/mobwrite;\n  }\n}\n\n# Configuration for generating Forwarded: header, based on example from\n# https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/\n#\n# Conceal the IP address of incoming connections by default, as it is\n# PII and we try to avoid giving users any chance to get their hands\n# on each other's PII.  To enable inclusion of actual IP addresses of\n# incoming connections in the Forwarded header, uncomment the first\n# two matchers below.\nmap $remote_addr $proxy_forwarded_for {\n    # IPv4 addresses can be sent as-is.\n#    ~^[0-9.]+$          \"for=$remote_addr\";\n\n    # IPv6 addresses need to be bracketed and quoted.\n#    ~^[0-9A-Fa-f:.]+$   \"for=\\\"[$remote_addr]\\\"\";\n\n    # Unix domain socket names cannot be represented in RFC 7239 syntax.\n    default             \"for=unknown\";\n}\n\n# Append host and proto.\nmap $proxy_forwarded_for $proxy_forwarded_elem {\n    default \"$proxy_forwarded_for;host=\\\"$http_host\\\";proto=$scheme\";\n}\n\nmap $http_forwarded $proxy_add_forwarded {\n    # If the incoming Forwarded header is syntactically valid, append to it.\n    \"~^(,[ \\\\t]*)*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?)*([ \\\\t]*,([ \\\\t]*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?)*)?)*$\" \"$http_forwarded, $proxy_forwarded_elem\";\n\n    # Otherwise, replace it.\n    default \"$proxy_forwarded_elem\";\n}\n"
  },
  {
    "path": "etc/cc-onedomain.conf",
    "content": "# Nginx configuration for Code City using a single domain.\n# Warning: This configuration is insecure, users can hijack each other's perms.\n\n# Configuration applying to all servers.\nerror_page 502 503 504 =503 /static/503.html;\n\n# Configuration applying to all proxy forwarding.\nproxy_set_header Host $http_host;\nproxy_set_header Forwarded $proxy_add_forwarded;  # See below.\nproxy_set_header CodeCity-pathToSubdomain \"?1\";\nproxy_pass_header Server;\nproxy_next_upstream_tries 1;\nproxy_max_temp_file_size 0;\nproxy_connect_timeout 10s;\nproxy_send_timeout 10s;\nproxy_read_timeout 10s;\n\n# Redirect all http traffic to https, except for ACME HTTP-01 challenges.\nserver {\n  # Listen on port 80 for both IPv6 and IPv4.\n  listen [::]:80 ipv6only=off;\n\n  location  / {\n    return 301 https://$host$request_uri;\n  }\n\n  # Serve ACME challenge files to enable automatic Certbot SSL\n  # certificate renewals using HTTP-01 challenges.\n  location /.well-known/ {\n    # Serve these from the usual Debain default path so it doesn't\n    # matter whether this config file is installed yet or not, and to\n    # avoid having certbot have to write to /home/codecity/\n    root /var/www/html;\n  }\n}\n\n# Code City configuration\nserver {\n  # Listen on port 443 for both IPv6 and IPv4.\n  listen [::]:443 ssl ipv6only=off;\n\n  # Replace INSTANCENAME with the domain name of your instance.  Make\n  # sure that the resulting filenames point at the certificate files\n  # created by certbot.\n  ssl_certificate /etc/letsencrypt/live/INSTANCENAME/fullchain.pem;\n  ssl_certificate_key /etc/letsencrypt/live/INSTANCENAME/privkey.pem;\n\n  # Canonicalise to a single domain.\n  #\n  # Replace INSTANCENAME (both places) with the domain name of your\n  # instance.  If you have more than one domain name for you instance,\n  # put the canonical one here.\n  if ( $host != INSTANCENAME ) {\n    return 301 https://INSTANCENAME$request_uri;\n  }\n\n  location / {\n    # Proxy to Code City port 7780.\n    proxy_pass http://127.0.0.1:7780/;\n  }\n\n  location /static/ {\n    # Static files.\n    autoindex on;\n    index index.html;\n    # If requried, edit to be full path to CodeCity directory.  Nginx\n    # will add /static/ automatically since that's the location.\n    # E.g.: /home/codecity/CodeCity;\n    root /home/codecity/CodeCity;\n  }\n\n  location /login {\n    # Proxy to loginServer.js port 7781.\n    proxy_pass http://127.0.0.1:7781/login;\n  }\n\n  location /connect {\n    # Proxy to connectServer.js port 7782.\n    proxy_pass http://127.0.0.1:7782/connect;\n  }\n\n  location /mobwrite {\n    # Proxy to mobwrite_server.py port 7783.\n    proxy_pass http://127.0.0.1:7783/mobwrite;\n  }\n}\n\n# Configuration for generating Forwarded: header, based on example from\n# https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/\n#\n# Conceal the IP address of incoming connections by default, as it is\n# PII and we try to avoid giving users any chance to get their hands\n# on each other's PII.  To enable inclusion of actual IP addresses of\n# incoming connections in the Forwarded header, uncomment the first\n# two matchers below.\nmap $remote_addr $proxy_forwarded_for {\n    # IPv4 addresses can be sent as-is.\n#    ~^[0-9.]+$          \"for=$remote_addr\"\n\n    # IPv6 addresses need to be bracketed and quoted.\n#    ~^[0-9A-Fa-f:.]+$   \"for=\\\"[$remote_addr]\\\"\";\n\n    # Unix domain socket names cannot be represented in RFC 7239 syntax.\n    default             \"for=unknown\";\n}\n\n# Append host and proto.\nmap $proxy_forwarded_for $proxy_forwarded_elem {\n    default \"$proxy_forwarded_for;host=\\\"$http_host\\\";proto=$scheme\";\n}\n\nmap $http_forwarded $proxy_add_forwarded {\n    # If the incoming Forwarded header is syntactically valid, append to it.\n    \"~^(,[ \\\\t]*)*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?)*([ \\\\t]*,([ \\\\t]*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?)*)?)*$\" \"$http_forwarded, $proxy_forwarded_elem\";\n\n    # Otherwise, replace it.\n    default \"$proxy_forwarded_elem\";\n}\n"
  },
  {
    "path": "etc/cc-subdomain.conf",
    "content": "# Nginx configuration for Code City using multiple subdomains.\n\n# Configuration applying to all servers.\n# Replace INSTANCENAME with the domain name of your instance; make\n# sure the result is prefixed with the 'static' subdomain.\n# E.g.: static.example.codecity.world\nerror_page 502 503 504 =503 https://static.INSTANCENAME/503.html;\n\n# Configuration applying to all proxy forwarding.\nproxy_set_header Host $http_host;\nproxy_set_header Forwarded $proxy_add_forwarded;  # See below.\nproxy_set_header CodeCity-pathToSubdomain \"?0\";\nproxy_pass_header Server;\nproxy_next_upstream_tries 1;\nproxy_max_temp_file_size 0;\nproxy_connect_timeout 10s;\nproxy_send_timeout 10s;\nproxy_read_timeout 10s;\n\n# Redirect all http traffic to https.\nserver {\n  # Listen on port 80 for both IPv6 and IPv4.\n  listen [::]:80 ipv6only=off;\n  return 301 https://$host$request_uri;\n}\n\n# Code City configuration\nserver {\n  # Listen on port 443 for both IPv6 and IPv4.\n  listen [::]:443 ssl ipv6only=off;\n\n  # Replace INSTANCENAME with the domain name of your instance.  Make\n  # sure that the resulting filenames point at the certificate files\n  # created by certbot.\n  ssl_certificate /etc/letsencrypt/live/INSTANCENAME/fullchain.pem;\n  ssl_certificate_key /etc/letsencrypt/live/INSTANCENAME/privkey.pem;\n\n  # # Canonicalise to a single domain.\n  # #\n  # # Replace regular expression with one that matches all non-canonical\n  # # domains.\n  # if ( $host ~ ^example\\.codecity\\.(academy|games)$ ) {\n  #   # Replace INSTANCENAME with the canonical domain name of your instance.\n  #   # E.g.: https://example.codecity.world$request_uri\n  #   return 301 https://INSTANCENAME$request_uri;\n  # }\n  # # Replace regular expression with one that matches all non-canonical\n  # # subdomains.\n  # if ( $host ~ ^(.*)\\.example\\.codecity\\.(academy|games)$ ) {\n  #   # Replace INSTANCENAME with the canonical domain name of your instance.\n  #   # E.g.: https://$1.example.codecity.world$request_uri\n  #   return 301 https://$1.INSTANCENAME$request_uri;\n  # }\n\n  location / {\n    # Proxy to Code City port 7780.\n    proxy_pass http://127.0.0.1:7780/;\n  }\n}\n\n# Login server.\nserver {\n  listen [::]:443 ssl;\n\n  # Replace INSTANCENAME with the domain name of your instance; make\n  # sure the result is prefixed with the 'login' subdomain.\n  # E.g.: login.example.codecity.world\n  server_name login.INSTANCENAME;\n\n  location / {\n    # Proxy to loginServer.js port 7781.\n    proxy_pass http://127.0.0.1:7781/;\n  }\n}\n\n# Connect server.\nserver {\n  listen [::]:443 ssl;\n\n  # Replace INSTANCENAME with the domain name of your instance; make\n  # sure the result is prefixed with the 'connect' subdomain.\n  # E.g.: connect.example.codecity.world\n  server_name connect.INSTANCENAME;\n\n  location / {\n    # Proxy to connectServer.js port 7782.\n    proxy_pass http://127.0.0.1:7782/;\n  }\n}\n\n# MobWrite server.\nserver {\n  listen [::]:443 ssl;\n\n  # Replace INSTANCENAME with the domain name of your instance; make\n  # sure the result is prefixed with the 'mobwrite' subdomain.\n  # E.g.: mobwrite.example.codecity.world\n  server_name mobwrite.INSTANCENAME;\n\n  location / {\n    # Proxy to mobwrite_server.py port 7783.\n    proxy_pass http://127.0.0.1:7783/mobwrite;\n  }\n}\n\n# Static file server.\nserver {\n  listen [::]:443 ssl;\n\n  # Replace INSTANCENAME with the domain name of your instance; make\n  # sure the result is prefixed with the 'static' subdomain.\n  # E.g.: static.example.codecity.world\n  server_name static.INSTANCENAME;\n\n  location / {\n    autoindex on;\n    index index.html;\n    # If required, edit to be full path to CodeCity static directory.\n    # E.g. /home/codecity/CodeCity/static\n    root /home/codecity/CodeCity/static;\n  }\n}\n\n# Configuration for generating Forwarded: header, based on example from\n# https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/\n#\n# Conceal the IP address of incoming connections by default, as it is\n# PII and we try to avoid giving users any chance to get their hands\n# on each other's PII.  To enable inclusion of actual IP addresses of\n# incoming connections in the Forwarded header, uncomment the first\n# two matchers below.\nmap $remote_addr $proxy_forwarded_for {\n    # IPv4 addresses can be sent as-is.\n#    ~^[0-9.]+$          \"for=$remote_addr\"\n\n    # IPv6 addresses need to be bracketed and quoted.\n#    ~^[0-9A-Fa-f:.]+$   \"for=\\\"[$remote_addr]\\\"\";\n\n    # Unix domain socket names cannot be represented in RFC 7239 syntax.\n    default             \"for=unknown\";\n}\n\n# Append host and proto.\nmap $proxy_forwarded_for $proxy_forwarded_elem {\n    default \"$proxy_forwarded_for;host=\\\"$http_host\\\";proto=$scheme\";\n}\n\nmap $http_forwarded $proxy_add_forwarded {\n    # If the incoming Forwarded header is syntactically valid, append to it.\n    \"~^(,[ \\\\t]*)*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?)*([ \\\\t]*,([ \\\\t]*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\\\"([\\\\t \\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E\\\\x80-\\\\xFF]|\\\\\\\\[\\\\t \\\\x21-\\\\x7E\\\\x80-\\\\xFF])*\\\"))?)*)?)*$\" \"$http_forwarded, $proxy_forwarded_elem\";\n\n    # Otherwise, replace it.\n    default \"$proxy_forwarded_elem\";\n}\n\n"
  },
  {
    "path": "etc/codecity-connect.service",
    "content": "[Unit]\nDescription=Code City Connect Server\nDocumentation=https://github.com/google/CodeCity\nAfter=network.target\n\n[Service]\nSyslogIdentifier=cc-connect\nWorkingDirectory=/home/codecity/CodeCity/connect\nUser=codecity\nGroup=codecity\nExecStart=@/home/codecity/CodeCity/connect/connectServer cc-connect\nRestart=on-failure\n"
  },
  {
    "path": "etc/codecity-login.service",
    "content": "[Unit]\nDescription=Code City Login Server\nDocumentation=https://github.com/google/CodeCity\nAfter=network.target\n\n[Service]\nSyslogIdentifier=cc-login\nWorkingDirectory=/home/codecity/CodeCity/login\nUser=codecity\nGroup=codecity\nExecStart=@/home/codecity/CodeCity/login/loginServer cc-login \nRestart=on-failure\n"
  },
  {
    "path": "etc/codecity-mobwrite.service",
    "content": "[Unit]\nDescription=Code City Login Server\nDocumentation=https://github.com/google/CodeCity\nAfter=network.target\n\n[Service]\nSyslogIdentifier=cc-mobwrite\nWorkingDirectory=/home/codecity/CodeCity/mobwrite\nUser=codecity\nGroup=codecity\nExecStart=@/usr/bin/python2 cc-mobwrite /home/codecity/CodeCity/mobwrite/mobwrite_server.py\nRestart=on-failure\n"
  },
  {
    "path": "etc/codecity.service",
    "content": "[Unit]\nDescription=Code City\nDocumentation=https://github.com/google/CodeCity\nAfter=network.target\nWants=codecity-login.service codecity-connect.service codecity-mobwrite.service\n\n[Service]\nSyslogIdentifier=codecity\nWorkingDirectory=/home/codecity/CodeCity/database\nUser=codecity\nGroup=codecity\nExecStart=@/home/codecity/CodeCity/server/codecity codecity codecity.cfg\nRestart=on-failure\n\n[Install]\nWantedBy=multi-user.target\n"
  },
  {
    "path": "etc/gcloud-snapshot",
    "content": "#!/bin/bash\n\n# Put this file in /etc/cron.daily/ to effect automatic daily snapshots.\n#\n# Must also have installed gcloud-snapshot.sh from:\n#\n#     https://github.com/jacksegal/google-compute-snapshot/\n#\n# and enabled the \"compute engine\" cloud API access scope for this\n# instance.\n\n/usr/local/sbin/gcloud-snapshot.sh -d 30\n"
  },
  {
    "path": "login/login.html",
    "content": "<!doctype html>\n\n<html lang=\"en\">\n<head>\n  <title>Code City Login</title>\n  <link href=\"<<<STATIC_URL>>>style/jfk.css\" rel=\"stylesheet\">\n  <style>\n    body {\n      text-align: center;\n    }\n    noscript {\n      font-size: small;\n      font-family: sans-serif;\n    }\n    #signin {\n      display: none;\n    }\n    .container {\n      display: table;\n      position: absolute;\n      top: 0;\n      left: 0;\n      height: 100%;\n      width: 100%;\n    }\n    .centered {\n      display: table-cell;\n      vertical-align: middle;\n    }\n  </style>\n</head>\n<body>\n  <noscript>JavaScript required</noscript>\n  <div class=\"container\">\n    <div class=\"centered\">\n      <div class=\"jfk-button jfk-button-submit\" role=\"button\" id=\"signin\">\n        Sign in\n      </div>\n    </div>\n  </div>\n  <script>\n    var button =  document.getElementById('signin');\n    button.style.display = 'inline-block';\n    button.addEventListener('click', function() {\n      parent.location = \"<<<OAUTH_URL>>>\";\n    });\n  </script>\n</body>\n</html>\n"
  },
  {
    "path": "login/loginServer",
    "content": "#!/usr/bin/env node\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Node.js server that provides Google auth services to Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n\n'use strict';\n\nconst crypto = require('crypto');\nconst forwardedParse = require('forwarded-parse');\nconst fs = require('fs').promises;\nconst {google} = require('googleapis');\nconst http = require('http');\nconst net = require('net');\nconst {URL, format: urlFormat} = require('url');\n\nconst oauth2Api = google.oauth2('v2');\n\n// Configuration constants.\nconst configFileName = 'loginServer.cfg';\n\n// Global variables\nlet CFG = null;\nconst /** !Object<string, !google.auth.OAuth2> */ clients = {};\n\nconst DEFAULT_CFG = {\n  // Internal port for this HTTP server.  Nginx hides this from users.\n  httpPort: 7781,\n  // URL of connect page (absolute or relative).\n  connectUrl: 'https://connect.example.codecity.world/',\n  // URL of static folder (absolute or relative).\n  staticUrl: 'https://static.example.codecity.world/',\n  // Google's API client ID.\n  clientId: '00000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' +\n      '.apps.googleusercontent.com',\n  // Google's API client secret.\n  clientSecret: 'yyyyyyyyyyyyyyyyyyyyyyyy',\n  // Root domain.\n  cookieDomain: 'example.codecity.world',\n  // Regexp on email addresses that must pass to allow access.\n  emailRegexp: '.*',\n  // Port number for the login service backend.\n  backendPort: 7776,\n  /* List of fields, from data object returned by\n   * oauth2Api.userinfo.v2.me.get, to pass along in the request the\n   * login service backend.\n   *\n   * Available fieldnames, and the types and meanings of their values:\n   * - id: string - the user's OAuth (GAIA) ID as a numeric string.\n   *   If salt is set (below), the .id will be salted and hashed with\n   *   sha512 before being sent to the login backend service.\n   * - email: string - the user's email address.\n   * - verified_email: boolean - has the user's email address been verified?\n   * - name: string - the user's full name.\n   * - given_name: string - the user's given name.\n   * - family_name: string - the user's family name.\n   * - picture: string - URL pointing to the user's profile picture.\n   * - hd: string - the hosted domain, for GSuite accounts.\n   */\n  backendFields: ['id'],\n  /* Random salt for OAuth IDs.  If set to '' the .id field received\n   * from the Oauth server will be hashed but not salted. If set to \n   * undefined (or not set) the .id wil be sent plaintext.\n   */\n  salt: 'zzzzzzzzzzzzzzzz'\n};\n\n/**\n * Serve an error to the given ServerResult.  Also log information\n * about the failed IncomingMessage to the console.\n * @param {!http.IncomingMessage} request The request which triggered the error.\n * @param {!http.ServerResponse} response The ServerResult to send error to.\n * @param {number} statusCode the HTTP response code to be served.\n * @param {string} message An additional message to include in the result.\n * @return {void}\n */\nfunction sendError(request, response, statusCode, message) {\n  console.log('%s %s (Host: %s): %d %s', request.method,\n              request.url.replace(/=[^&]*(?=&|$)/g, '=…'),\n              request.headers.host, statusCode, message);\n  response.writeHead(statusCode).end(message);\n}\n\n/**\n * Load a file from disk, add substitutions, and serve to the web.\n * @param {!IncomingMessage} request The request being answered.\n * @param {!http.ServerResponse} response The ServerResult to send the file to.\n * @param {string} filename Name of template file on disk.\n * @param {!Object} subs Object-map of replacement strings.\n */\nasync function serveFile(request, response, filename, subs) {\n  let /** string */ data;\n  try {\n    data = String(await fs.readFile(filename, 'utf8'));\n  } catch (err) {\n    sendError(request, response,\n              500, `Unable to load file ${filename}: ${err}`);\n    return;\n  }\n  // Inject substitutions.\n  for (const name in subs) {\n    data = data.replace(new RegExp(name, 'g'), subs[name]);\n  }\n  // Serve page to user.\n  response.statusCode = 200;\n  response.setHeader('Content-Type', 'text/html');\n  response.end(data);\n}\n\n/**\n * Send a string to the login service backend and return any data\n * received in response.\n * @param {string} query Data string to send to backend.\n * @return {!Promise<string>} a promise yeilding the data received.\n */\nasync function pingBackend(query) {\n  let result = '';\n  return new Promise((resolve, reject) => {\n    const socket = net.createConnection({port: CFG.backendPort});\n    socket.on('connect', () => {\n      socket.end(query);\n    });\n    socket.on('error', (error) => {\n      socket.destroy();\n      reject(error);\n    });\n    socket.on('data', (data) => {\n      result += String(data);\n    });\n    socket.on('end', () => {\n      resolve(result);\n    });\n  });\n}\n\n/**\n * Handles HTTP requests from web server.\n * @param {!Object} request HTTP server request object\n * @param {!Object} response HTTP server response object.\n */\nasync function handleRequest(request, response) {\n  if (request.connection.remoteAddress !== '127.0.0.1') {\n    sendError(request, response, 403,\n              `Connection from ${request.connection.remoteAddress} denied.`);\n    return;\n  }\n\n  // Determine what URL the client contacted us on.\n  let proto = 'http';  // What proto we are actually listening to.\n  let host = request.headers.host;  // Host header we actually received.\n  // See if the first reverse proxy knows better.\n  const forwarded = request.headers.forwarded;\n  if (forwarded) {\n    try {\n      const forwards = forwardedParse(forwarded);\n      if (forwards[0]) {\n        if (forwards[0].proto) proto = forwards[0].proto;\n        if (forwards[0].host) host = forwards[0].host;\n      }\n    } catch (e) {\n      sendError(request, response, 400,\n                `Forwarded header: ${e.name}: ${e.message} of \"${forwarded}\"`);\n      return;\n    }\n  }\n  const url = new URL(request.url, `${proto}://${host}`);\n  const loginUrl = urlFormat(url, {fragment: false, search: false});\n\n  // Get an authentication client for our interactions with Google.\n  if (!clients[loginUrl]) {\n    // Create client for login URL not seen before.\n    clients[loginUrl] = new google.auth.OAuth2(\n        CFG.clientId, CFG.clientSecret, loginUrl);\n  }\n  const oauth2Client = clients[loginUrl];\n\n  // No auth code?  Serve login.html.\n  const code = url.searchParams.get('code');\n  if (!code) {\n    // Compute Google's login URL, including deciding where to\n    // redirect to afterwards.\n    const options = {scope: 'email'};\n    if (url.searchParams.has('after')) {\n      options.state = url.searchParams.get('after');\n    } else if (url.searchParams.has('loginThenClose')) {\n      options.state = CFG.staticUrl + 'login-close.html';\n    } else {\n      options.state = CFG.connectUrl;\n    }\n    const subs = {\n      '<<<OAUTH_URL>>>': oauth2Client.generateAuthUrl(options),\n      '<<<STATIC_URL>>>': CFG.staticUrl\n    };\n    serveFile(request, response, 'login.html', subs);\n    return;\n  }\n\n  // Handle the result of an OAuth login.\n  let tokens;\n  try {\n    ({tokens} = await oauth2Client.getToken(code));\n  } catch (err) {\n    sendError(request, response, 500, `Google OAuth2 fail: ${err}`);\n    return;\n  }\n  // Now tokens contains an access_token and an optional\n  // refresh_token. Save them.\n  oauth2Client.setCredentials(tokens);\n  let data;\n  try {\n    ({data} = await oauth2Api.userinfo.v2.me.get({auth: oauth2Client}));\n  } catch (err) {\n    sendError(request, response, 500, `Google Userinfo fail: ${err}`);\n    return;\n  }\n\n  // Check email address is allowed.\n  const emailRegexp = new RegExp(CFG.emailRegexp || '.*');\n  if (!emailRegexp.test(data.email)) {\n    sendError(request, response, 403, `Login denied for ${data.email}`);\n    return;\n  }\n  // FYI: If present, data.hd contains the GSfE domai,\n  // e.g. 'students.gissv.org', or 'sjsu.edu'.  We aren't using it\n  // now, but this might be used to filter users.\n\n  // Convert the OAuth (GAIA) ID into one unique for Code City.  Use\n  // CFG.salt to salt the sha512hash.  If .salt === '', then .id will\n  // still be hashed but not salted.\n  // TODO(cpcallen): it would be more secure to append salt to id.\n  if (('id' in data) && CFG.salt !== undefined) {\n    data.id = crypto.createHash('sha512')\n        .update(CFG.salt + data.id).digest('hex');\n  }\n\n  // Contact login service backend if configured.\n  let cookie;\n  if (CFG.backendPort) {\n    // Construct object to be passed to login service backend.\n    const loginData = {};\n    for (const name of CFG.backendFields || ['id']) {\n      if (name in data) loginData[name] = data[name];\n    }\n\n    // Ping the login service backend.\n    try {\n      cookie = await pingBackend(JSON.stringify(loginData) + '\\n');\n    } catch (err) {\n      sendError(request, response, 500, `Login service backend fail: ${err}`);\n      return;\n    }\n  } else {\n    // Just use the (probably salted and hashed) id value like we used to.\n    cookie = data.id;\n  }\n  if (!cookie) {\n    sendError('Login service backend did not return a valid cookie');\n    return;\n  }\n\n  // Login successful.  Issue ID cookie.\n  if (!url.searchParams.has('state')) {\n    sendError(request, response, 500,\n              'Login successful but loginServer forgot where to redirect to.');\n    return;\n  }\n  const domain = CFG.cookieDomain ? `Domain=${CFG.cookieDomain}; ` : '';\n  const redirectUrl = url.searchParams.get('state');\n\n  response.writeHead(302, {  // Temporary redirect.\n    'Set-Cookie': `ID=${cookie}; HttpOnly; ${domain}Path=/`,\n    'Location': redirectUrl,\n  });\n  response.end('Login OK.  Redirecting.');\n  console.log('Accepted xxxx' + cookie.substring(cookie.length - 4));\n}\n\n/**\n * Read the JSON configuration file and return it.  If none is\n * present, write a stub and throw an error.\n */\nasync function readConfigFile(filename) {\n  let data;\n  try {\n    data = await fs.readFile(filename, 'utf8');\n  } catch (err) {\n    console.log(`Configuration file ${filename} not found.  ` +\n        'Creating new file.');\n    data = JSON.stringify(DEFAULT_CFG, null, 2) + '\\n';\n    await fs.writeFile(filename, data, 'utf8');\n  }\n  CFG = JSON.parse(data);\n  if (CFG.salt === DEFAULT_CFG.salt) {\n    throw Error(\n        `Configuration file ${filename} not configured.  ` +\n        'Please edit this file.');\n  }\n  if (!CFG.connectUrl.endsWith('/')) CFG.connectUrl += '/';\n  if (!CFG.staticUrl.endsWith('/')) CFG.staticUrl += '/';\n}\n\n/**\n * Read configuration and start up the HTTP server.\n */\nasync function startup() {\n  await readConfigFile(configFileName);\n\n  // Start an HTTP server.\n  const server = http.createServer(handleRequest);\n  server.listen(CFG.httpPort, 'localhost', () => {\n    console.log(`Login server listening on port ${CFG.httpPort}`);\n  });\n}\n\nstartup();\n"
  },
  {
    "path": "login/package.json",
    "content": "{\n  \"name\": \"codecity-login\",\n  \"version\": \"0.0.0\",\n  \"description\": \"Login server for the Code City project\",\n  \"main\": \"loginServer.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/google/CodeCity.git\"\n  },\n  \"author\": \"Google\",\n  \"license\": \"Apache-2.0\",\n  \"bugs\": {\n    \"url\": \"https://github.com/google/CodeCity/issues\"\n  },\n  \"homepage\": \"https://github.com/google/CodeCity#readme\",\n  \"dependencies\": {\n    \"forwarded-parse\": \"^2.1.1\",\n    \"googleapis\": \"^59.0.0\"\n  },\n  \"devDependencies\": {}\n}\n"
  },
  {
    "path": "minimal/core_01_minimal.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Minimal database for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n\nvar user = null;\nvar $ = {};\n\n// System object: $.system\n$.system = {};\n$.system.log = new 'CC.log';\n$.system.checkpoint = new 'CC.checkpoint';\n$.system.shutdown = new 'CC.shutdown';\n$.system.connectionListen = new 'CC.connectionListen';\n$.system.connectionUnlisten = new 'CC.connectionUnlisten';\n$.system.connectionWrite = new 'CC.connectionWrite';\n$.system.connectionClose = new 'CC.connectionClose';\n\n\n// Physical object prototype: $.physical\n$.physical = {};\n$.physical.name = 'Physical object prototype';\n$.physical.description = '';\n$.physical.location = null;\n$.physical.contents_ = null;\n\n$.physical.getContents = function() {\n  return this.contents_ || [];\n};\n\n$.physical.addContents = function(thing) {\n  var contents = this.getContents();\n  contents.indexOf(thing) === -1 && contents.push(thing);\n  this.contents_ = contents;\n};\n\n$.physical.removeContents = function(thing) {\n  var contents = this.getContents();\n  var index = contents.indexOf(thing);\n  if (index !== -1) {\n    contents.splice(index, 1);\n  }\n  this.contents_ = contents;\n};\n\n$.physical.moveTo = function(dest) {\n  var src = this.location;\n  src && src.removeContents && src.removeContents(this);\n  this.location = dest;\n  dest && dest.addContents && dest.addContents(this);\n};\n\n$.physical.look = function() {\n  user.tell(this.name);\n  user.tell(this.description);\n  var contents = this.getContents();\n  if (contents.length) {\n    var text = [];\n    for (var i = 0; i < contents.length; i++) {\n      text[i] = String(contents[i].name || contents[i]);\n    }\n    user.tell('Contents: ' + text.join(', '));\n  }\n};\n$.physical.look.dobj = 'this';\n\n\n// Thing prototype: $.thing\n$.thing = Object.create($.physical);\n$.thing.name = 'Thing prototype';\n\n$.thing.get = function() {\n  this.moveTo(user);\n  user.tell('You pick up ' + this.name + '.');\n  if (user.location) {\n    user.location.announce(user.name + ' picks up ' + this.name + '.');\n  }\n};\n$.thing.get.dobj = 'this';\n\n$.thing.drop = function() {\n  this.moveTo(user.location);\n  user.tell('You drop ' + this.name + '.');\n  if (user.location) {\n    user.location.announce(user.name + ' drops ' + this.name + '.');\n  }\n};\n$.thing.drop.dobj = 'this';\n\n\n// Room prototype: $.room\n$.room = Object.create($.physical);\n$.room.name = 'Room prototype';\n\n$.room.announce = function(text) {\n  var contents = this.getContents();\n  for (var i = 0; i < contents.length; i++) {\n    var thing = contents[i];\n    if (thing !== user && thing.tell) {\n      thing.tell(text);\n    }\n  }\n};\n\n\n// User prototype: $.user\n$.user = Object.create($.physical);\n$.user.name = 'User prototype';\n$.user.connection = null;\n\n$.user.say = function(text) {\n  user.tell('You say: ' + text);\n  if (user.location) {\n    user.location.announce(user.name + ' says: ' + text);\n  }\n};\n$.user.say.dobj = 'any';\n\n$.user.eval = function(code) {\n  user.tell(eval(code));\n};\n$.user.eval.dobj = 'any';\n\n$.user.tell = function(text) {\n  if (this.connection) {\n    this.connection.write(text);\n  }\n};\n\n$.user.quit = function() {\n  if (this.connection) {\n    this.connection.close();\n  }\n};\n$.user.quit.dobj = 'none';\n\n\n// Command parser.\n$.execute = function(command) {\n  var argstr = command.trim();\n  var verbstr = argstr;\n  var dobjstr = '';\n  var dobj = null;\n  var space = command.indexOf(' ');\n  if (space !== -1) {\n    verbstr = argstr.substring(0, space).trim();\n    dobjstr = argstr.substring(space).trim();\n  }\n  if (!verbstr) {\n    return;\n  }\n  if (dobjstr) {\n    if (dobjstr === 'me') {\n      dobj = user;\n    } else if (dobjstr === 'here') {\n      dobj = user.location;\n    } else {\n      var objects = [user].concat(user.getContents());\n      if (user.location && user.location.getContents) {\n        objects.push(user.location);\n        objects = objects.concat(user.location.getContents());\n      }\n      for (var i = 0; i < objects.length; i++) {\n        var obj = objects[i];\n        if (obj.name &&\n            obj.name.toLowerCase().startsWith(dobjstr.toLowerCase())) {\n          dobj = obj;\n          break;\n        }\n      }\n    }\n  }\n  // Collect all objects which could host the verb.\n  var hosts = [user, user.location, dobj];\n  for (var i = 0; i < hosts.length; i++) {\n    var host = hosts[i];\n    if (!host) {\n      continue;\n    }\n    // Check every verb on each object for a match.\n    for (var prop in host) {\n      var func = host[prop];\n      if (prop === verbstr && typeof func === 'function' && func.dobj) {\n        if (func.dobj === 'any' || (func.dobj === 'this' && dobj === host) ||\n            (func.dobj === 'none' && !dobj)) {\n          return host[prop](dobjstr);\n        }\n      }\n    }\n  }\n  user.tell('Command not understood.');\n};\n\n\n// Database of users so that connections can bind to a user.\n$.userDatabase = Object.create(null);\n\n\n$.connection = {};\n\n$.connection.onConnect = function() {\n  this.user = null;\n  this.buffer = '';\n  this.write('Welcome.  Type name of user to connect as (Alpha or Beta).');\n};\n\n$.connection.onReceive = function(text) {\n  this.buffer += text.replace(/\\r/g, '');\n  var lf;\n  while ((lf = this.buffer.indexOf('\\n')) !== -1) {\n    this.onReceiveLine(this.buffer.substring(0, lf));\n    this.buffer = this.buffer.substring(lf + 1);\n  }\n};\n\n$.connection.onReceiveLine = function(text) {\n  if (this.user) {\n    user = this.user;\n    $.execute(text);\n    return;\n  }\n  // Remainder of function handles login.\n  text = text.trim().toLowerCase();\n  if ($.userDatabase[text]) {\n    this.user = $.userDatabase[text];\n    if (this.user.connection) {\n      this.user.connection.close();\n      $.system.log('Rebinding connection to ' + this.user.name);\n    } else {\n      $.system.log('Binding connection to ' + this.user.name);\n    }\n    this.user.connection = this;\n    this.write('Connected as ' + this.user.name);\n    user = this.user;\n    $.execute('look here');\n    if (user.location) {\n      user.location.announce(user.name + ' connects.');\n    }\n  } else {\n    this.write('Unknown user.');\n  }\n};\n\n$.connection.onEnd = function() {\n  if (this.user) {\n    if (user.location) {\n      user.location.announce(user.name + ' disconnects.');\n    }\n    if (this.user.connection === this) {\n      $.system.log('Unbinding connection from ' + this.user.name);\n      this.user.connection = null;\n    }\n    this.user = null;\n  }\n};\n\n$.connection.write = function(text) {\n  $.system.connectionWrite(this, text + '\\n');\n};\n\n$.connection.close = function() {\n  $.system.connectionClose(this);\n};\n\n\n// Set up a room, two users, and a rock.\n(function () {\n  var hangout = Object.create($.room);\n  hangout.name = 'Hangout';\n  hangout.description = 'A place to hang out, chat, and program.';\n\n  var alpha = Object.create($.user);\n  alpha.name = 'Alpha';\n  $.userDatabase[alpha.name.toLowerCase()] = alpha;\n  alpha.description = 'Looks a bit Canadian.';\n  alpha.moveTo(hangout);\n\n  var beta = Object.create($.user);\n  beta.name = 'Beta';\n  $.userDatabase[beta.name.toLowerCase()] = beta;\n  beta.description = 'Mostly harmless.';\n  beta.moveTo(hangout);\n\n  var rock = Object.create($.thing);\n  rock.name = 'Rock';\n  rock.description = 'Suspiciously cube shaped, made of granite.';\n  rock.moveTo(hangout);\n\n  $.system.connectionListen(7777, $.connection);\n})();\n"
  },
  {
    "path": "minimal/minimal.cfg",
    "content": "{\n  \"databaseDirectory\": \"./\",\n  \"checkpointInterval\": 0,\n  \"checkpointAtShutdown\": false\n}\n"
  },
  {
    "path": "minimal/readme.txt",
    "content": "Minimal Database.\n\nThis database demonstrates a very minimal Code City instance.  It contains:\n\n* Two users (Alpha and Beta)\n* One room (Hangout)\n* One object (Rock)\n\nRun the database with:\n  node codecity.js minimal\nTelnet to port 7777\nType either 'Alpha' or 'Beta' to connect as one of the two users.\n\nOnce connected, the valid commands are:\n* say <some text>\n* eval <some code>\n* look [me|here|alpha|beta|hangout|rock]\n* get rock\n* drop rock\n* quit\n"
  },
  {
    "path": "mobwrite/mobwrite.cfg",
    "content": "; ---------------------\n; Settings for MobWrite\n; ---------------------\n\n; How long (in seconds) to compute a diff before giving up.\n; Set to 0 to compute indefinitely.\nDIFF_TIMEOUT = 0.1\n\n; Demo usage should limit the maximum size of any text.\n; Set to 0 to disable limit.\nMAX_CHARS = 100000\n\n; Delete any view which hasn't been accessed in a while.\n; Format: <number> {seconds|minutes|hours|days}\nTIMEOUT_VIEW = 30 minutes\n\n; Delete any text which hasn't been accessed in a while.\n; TIMEOUT_TEXT should be longer than the length of TIMEOUT_VIEW\nTIMEOUT_TEXT = 1 days\n\n; How verbose the log should be.\n; Choose from: CRITICAL, ERROR, WARNING, INFO, DEBUG\nLOGGING = DEBUG\n\n; Port to listen on.\nLOCAL_PORT = 7783\n\n; Restrict all Telnet connections to come from this location.\n; Set to \"\" to allow connections from anywhere.\nCONNECTION_ORIGIN = 127.0.0.1\n\n; Name of cookie that must be present, otherwise code 410 is returned.\n; This is in the form of a regexp.  Set to blank to disable feature.\nREQUIRED_COOKIE = ID\n"
  },
  {
    "path": "mobwrite/mobwrite_core.py",
    "content": "# Copyright 2009 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Core functions for a MobWrite client/server in Python.\n\"\"\"\n\n__author__ = \"fraser@google.com (Neil Fraser)\"\n\nimport datetime\nimport logging\nimport re\n\nimport diff_match_patch as dmp_module\n\n\nclass Configuration(dict):\n  def initConfig(self, filename):\n    \"\"\"Parse the config file and setup the preferences.\n\n    Args:\n      filename: Path to the config file.\n\n    Raises:\n      If the config is invalid, this function will thow an error.\n    \"\"\"\n    global MAX_CHARS, TIMEOUT_VIEW, TIMEOUT_TEXT\n\n    def readConfigFile(filename):\n      self.clear()\n      lineRegex = re.compile(\"^(\\w+)\\s*=\\s*(.+)$\")\n\n      # Attempt to open the file.\n      try:\n        f = open(filename)\n      except:\n        return\n\n      # Parse the file.\n      try:\n        for line in f:\n          line = line.strip()\n          # Comment lines start with a ;\n          if len(line) > 0 and not line.startswith(\";\"):\n            r = lineRegex.match(line)\n            if r:\n              self[r.group(1)] = r.group(2)\n      finally:\n        f.close()\n\n    def toTime(value):\n      (quantity, unit) = value.split(None, 1)\n      quantity = int(quantity)\n      if (unit == \"seconds\"):\n        delta = datetime.timedelta(seconds=quantity)\n      elif (unit == \"minutes\"):\n        delta = datetime.timedelta(minutes=quantity)\n      elif (unit == \"hours\"):\n        delta = datetime.timedelta(hours=quantity)\n      elif (unit == \"days\"):\n        delta = datetime.timedelta(days=quantity)\n      else:\n        raise \"Config: Unknown time value.\"\n      return delta\n\n    readConfigFile(filename)\n\n    # Set each of the configuration parameters.\n    # If a parameter is not present, a reasonable default is specified here.\n    # If a configuration is invalid, throw an error.\n    DMP.Diff_Timeout = float(self.get(\"DIFF_TIMEOUT\", 0.1))\n    MAX_CHARS = int(self.get(\"MAX_CHARS\", 100000))\n    TIMEOUT_VIEW = toTime(self.get(\"TIMEOUT_VIEW\", \"30 minutes\"))\n    TIMEOUT_TEXT = toTime(self.get(\"TIMEOUT_TEXT\", \"1 days\"))\n\n    logLevel = self.get(\"LOGGING\", \"INFO\")\n    if logLevel == \"CRITICAL\":\n      LOG.setLevel(logging.CRITICAL)\n    elif logLevel == \"ERROR\":\n      LOG.setLevel(logging.ERROR)\n    elif logLevel == \"WARNING\":\n      LOG.setLevel(logging.WARNING)\n    elif logLevel == \"INFO\":\n      LOG.setLevel(logging.INFO)\n    elif logLevel == \"DEBUG\":\n      LOG.setLevel(logging.DEBUG)\n    else:\n      raise \"Config: Unknown logging level.\"\n\n    LOG.info(\"Read %d settings from %s\" % (len(self), filename))\n\n\nclass TextObj:\n  # An object which stores a text.\n\n  # Object properties:\n  # .name - The unique name for this text, e.g 'proposal'\n  # .text - The text itself.\n\n  def __init__(self, *args, **kwargs):\n    # Setup this object\n    self.name = kwargs.get(\"name\")\n    self.text = None\n\n  def setText(self, newtext):\n    # Scrub the text before setting it.\n    if newtext != None:\n      # Normalize linebreaks to LF.\n      newtext = re.sub(r\"(\\r\\n|\\r|\\n)\", \"\\n\", newtext)\n      # Keep the text within the length limit.\n      if MAX_CHARS != 0 and len(newtext) > MAX_CHARS:\n        newtext = newtext[-MAX_CHARS:]\n        LOG.warning(\"Truncated text to %d characters.\" % MAX_CHARS)\n    if self.text != newtext:\n      self.text = newtext\n\n\nclass ViewObj:\n  # An object which contains one user's view of one text.\n\n  # Object properties:\n  # .username - The name for the user, e.g 'fraser'\n  # .filename - The name for the file, e.g 'proposal'\n  # .shadow - The last version of the text sent to client.\n  # .backup_shadow - The previous version of the text sent to client.\n  # .shadow_client_version - The client's version for the shadow (n).\n  # .shadow_server_version - The server's version for the shadow (m).\n  # .backup_shadow_server_version - the server's version for the backup\n  #     shadow (m).\n  # .edit_stack - List of unacknowledged edits sent to the client.\n  # .delta_ok - Did the previous delta match the text length.\n\n  def __init__(self, *args, **kwargs):\n    # Setup this object\n    self.username = kwargs[\"username\"]\n    self.filename = kwargs[\"filename\"]\n    self.shadow_client_version = kwargs.get(\"shadow_client_version\", 0)\n    self.shadow_server_version = kwargs.get(\"shadow_server_version\", 0)\n    self.backup_shadow_server_version = kwargs.get(\"backup_shadow_server_version\", 0)\n    self.shadow = kwargs.get(\"shadow\", u\"\")\n    self.backup_shadow = kwargs.get(\"backup_shadow\", u\"\")\n    self.edit_stack = []\n    self.delta_ok = True\n\n\nclass MobWrite:\n  def parseRequest(self, data):\n    \"\"\"Parse the raw MobWrite commands into a list of specific actions.\n    See: http://code.google.com/p/google-mobwrite/wiki/Protocol\n\n    Args:\n      data: A multi-line string of MobWrite commands.\n\n    Returns:\n      A list of actions, each action is a dictionary.  Typical action:\n      {\"username\":\"fred\",\n       \"filename\":\"report\",\n       \"mode\":\"delta\",\n       \"data\":\"=10+Hello-7=2\",\n       \"force\":False,\n       \"server_version\":3,\n       \"client_version\":3,\n       \"echo_username\":False\n      }\n    \"\"\"\n    # Passing a Unicode string is an easy way to cause numerous subtle bugs.\n    if type(data) != str:\n      LOG.critical(\"parseRequest data type is %s\" % type(data))\n      return []\n    if not (data.endswith(\"\\n\\n\") or data.endswith(\"\\r\\r\") or\n            data.endswith(\"\\n\\r\\n\\r\") or data.endswith(\"\\r\\n\\r\\n\")):\n      # There must be a linefeed followed by a blank line.\n      # Truncated data.  Abort.\n      LOG.warning(\"Truncated data: '%s'\" % data)\n      return []\n\n    # Parse the lines\n    actions = []\n    username = None\n    filename = None\n    server_version = None\n    echo_username = False\n    for line in data.splitlines():\n      if not line:\n        # Terminate on blank line.\n        break\n      if line.find(\":\") != 1:\n        # Invalid line.\n        continue\n      (name, value) = (line[:1], line[2:])\n\n      # Parse out a version number for file, delta or raw.\n      version = None\n      if (\"FfDdRr\".find(name) != -1):\n        div = value.find(\":\")\n        if div > 0:\n          try:\n            version = int(value[:div])\n          except ValueError:\n            LOG.warning(\"Invalid version number: %s\" % line)\n            continue\n          value = value[div + 1:]\n        else:\n          LOG.warning(\"Missing version number: %s\" % line)\n          continue\n\n      if name == \"u\" or name == \"U\":\n        # Remember the username.\n        username = value\n        # Client may request explicit usernames in response.\n        echo_username = (name == \"U\")\n\n      elif name == \"f\" or name == \"F\":\n        # Remember the filename and version.\n        filename = value\n        server_version = version\n\n      elif name == \"n\" or name == \"N\":\n        # Nullify this file.\n        filename = value\n        if username and filename:\n          action = {}\n          action[\"username\"] = username\n          action[\"filename\"] = filename\n          action[\"mode\"] = \"null\"\n          actions.append(action)\n\n      else:\n        # A delta or raw action.\n        action = {}\n        if name == \"d\" or name == \"D\":\n          action[\"mode\"] = \"delta\"\n        elif name == \"r\" or name == \"R\":\n          action[\"mode\"] = \"raw\"\n        else:\n          action[\"mode\"] = None\n        if name.isupper():\n          action[\"force\"] = True\n        else:\n          action[\"force\"] = False\n        action[\"server_version\"] = server_version\n        action[\"client_version\"] = version\n        action[\"data\"] = value\n        action[\"echo_username\"] = echo_username\n        if username and filename and action[\"mode\"]:\n          action[\"username\"] = username\n          action[\"filename\"] = filename\n          actions.append(action)\n\n    return actions\n\n\n  def applyPatches(self, viewobj, diffs, action):\n    \"\"\"Apply a set of patches onto the view and text objects.  This function must\n      be enclosed in a lock or transaction since the text object is shared.\n\n    Args:\n      viewobj: The user's view to be updated.\n      diffs: List of diffs to apply to both the view and the server.\n      action: Parameters for how forcefully to make the patch; may be modified.\n    \"\"\"\n    # Expand the fragile diffs into a full set of patches.\n    patches = DMP.patch_make(viewobj.shadow, diffs)\n\n    # First, update the client's shadow.\n    viewobj.shadow = DMP.diff_text2(diffs)\n    viewobj.backup_shadow = viewobj.shadow\n    viewobj.backup_shadow_server_version = viewobj.shadow_server_version\n\n    # Second, deal with the server's text.\n    textobj = viewobj.textobj\n    if textobj.text is None:\n      # A view is sending a valid delta on a file we've never heard of.\n      textobj.setText(viewobj.shadow)\n      action[\"force\"] = False\n      LOG.debug(\"Set content: '%s'\" % viewobj)\n    else:\n      if action[\"force\"]:\n        # Clobber the server's text if a change was received.\n        if patches:\n          mastertext = viewobj.shadow\n          LOG.debug(\"Overwrote content: '%s'\" % viewobj)\n        else:\n          mastertext = textobj.text\n      else:\n        (mastertext, results) = DMP.patch_apply(patches, textobj.text)\n        LOG.debug(\"Patched (%s): '%s'\" %\n            (\",\".join([\"%s\" % (x) for x in results]), viewobj))\n      textobj.setText(mastertext)\n\n# Global Diff/Match/Patch object.\nDMP = dmp_module.diff_match_patch()\n# Global logging object.\nLOG = logging.getLogger(\"mobwrite\")\n# Configuration object.\nCFG = Configuration()\n"
  },
  {
    "path": "mobwrite/mobwrite_core_test.py",
    "content": "#!/usr/bin/python2\n\n# Copyright 2006 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport unittest\n\nimport mobwrite_core\n\n# Force a module reload so to make debugging easier (at least in PythonWin).\nreload(mobwrite_core)\n\nclass MobWriteCoreTest(unittest.TestCase):\n\n  def setUp(self):\n    mobwrite_core.LOG.setLevel(logging.ERROR)\n    mobwrite_core.logging.basicConfig()\n\n  def tearDown(self):\n    mobwrite_core.logging.shutdown()\n\n  def testParseRequest(self):\n    mobwrite = mobwrite_core.MobWrite()\n\n    actions = mobwrite.parseRequest(\"\")\n    self.assertEquals([], actions)\n\n    actions = mobwrite.parseRequest(\"\"\"u:fred\nf:3:report\nd:2:=10+Hello-7=2\n\n\"\"\")\n    self.assertEquals([{\"username\":\"fred\",\n       \"filename\":\"report\",\n       \"mode\":\"delta\",\n       \"data\":\"=10+Hello-7=2\",\n       \"force\":False,\n       \"server_version\":3,\n       \"client_version\":2,\n       \"echo_username\":False\n      }], actions)\n\n    actions = mobwrite.parseRequest(\"\"\"U:fred\nf:3:report\nR:2:Hello World\n\n\"\"\")\n    self.assertEquals([{\"username\":\"fred\",\n       \"filename\":\"report\",\n       \"mode\":\"raw\",\n       \"data\":\"Hello World\",\n       \"force\":True,\n       \"server_version\":3,\n       \"client_version\":2,\n       \"echo_username\":True\n      }], actions)\n\n    actions = mobwrite.parseRequest(\"\"\"U:fred\nN:report\n\n\"\"\")\n    self.assertEquals([{\"username\":\"fred\",\n       \"filename\":\"report\",\n       \"mode\":\"null\",\n      }], actions)\n\n\nif __name__ == \"__main__\":\n  unittest.main()\n"
  },
  {
    "path": "mobwrite/mobwrite_server.py",
    "content": "#!/usr/bin/python2\n\n# Copyright 2006 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This file is MobWrite's server-side daemon.\n\nRuns in the background listening to a port, accepting synchronization sessions\nfrom clients.\n\"\"\"\n\n__author__ = \"fraser@google.com (Neil Fraser)\"\n\nimport datetime\nimport glob\nimport os\nimport re\nimport sys\nimport time\nimport thread\nimport urllib\nfrom BaseHTTPServer import BaseHTTPRequestHandler\nfrom BaseHTTPServer import HTTPServer\n\nimport mobwrite_core\n\n# Demo usage should limit the maximum number of connected views.\n# Set to 0 to disable limit.\nMAX_VIEWS = 10000\n\n# Dictionary of all text objects.\ntexts = {}\n\n# Lock to prevent simultaneous changes to the texts dictionary.\nlock_texts = thread.allocate_lock()\n\n\nclass TextObj(mobwrite_core.TextObj):\n  # A persistent object which stores a text.\n\n  # Object properties:\n  # .lock - Access control for writing to the text on this object.\n  # .views - Count of views currently connected to this text.\n  # .lasttime - The last time that this text was modified.\n\n  # Inherited properties:\n  # .name - The unique name for this text, e.g 'proposal'.\n  # .text - The text itself.\n\n  def __init__(self, *args, **kwargs):\n    # Setup this object\n    mobwrite_core.TextObj.__init__(self, *args, **kwargs)\n    self.views = 0\n    self.lasttime = datetime.datetime.now()\n    self.lock = thread.allocate_lock()\n\n    # lock_texts must be acquired by the caller to prevent simultaneous\n    # creations of the same text.\n    assert lock_texts.locked(), \"Can't create TextObj unless locked.\"\n    global texts\n    texts[self.name] = self\n\n  def setText(self, newText):\n    mobwrite_core.TextObj.setText(self, newText)\n    self.lasttime = datetime.datetime.now()\n\n  def cleanup(self):\n    # General cleanup task.\n    if self.views > 0:\n      return\n    terminate = False\n    # Lock must be acquired to prevent simultaneous deletions.\n    self.lock.acquire()\n    try:\n      if self.lasttime < datetime.datetime.now() - mobwrite_core.TIMEOUT_TEXT:\n        mobwrite_core.LOG.info(\"Expired text: '%s'\" % self)\n        terminate = True\n\n      if terminate:\n        # Terminate in-memory copy.\n        global texts\n        lock_texts.acquire()\n        try:\n          try:\n            del texts[self.name]\n          except KeyError:\n            mobwrite_core.LOG.error(\"Text object not in text list: '%s'\" % self)\n        finally:\n          lock_texts.release()\n    finally:\n      self.lock.release()\n\n\ndef fetch_textobj(name, view):\n  # Retrieve the named text object.  Create it if it doesn't exist.\n  # Add the given view into the text object's list of connected views.\n  # Don't let two simultaneous creations happen, or a deletion during a\n  # retrieval.\n  lock_texts.acquire()\n  try:\n    if texts.has_key(name):\n      textobj = texts[name]\n      mobwrite_core.LOG.debug(\"Accepted text: '%s'\" % name)\n    else:\n      textobj = TextObj(name=name)\n      mobwrite_core.LOG.debug(\"Creating text: '%s'\" % name)\n    textobj.views += 1\n  finally:\n    lock_texts.release()\n  return textobj\n\n\n# Dictionary of all view objects.\nviews = {}\n\n# Lock to prevent simultaneous changes to the views dictionary.\nlock_views = thread.allocate_lock()\n\nclass ViewObj(mobwrite_core.ViewObj):\n  # A persistent object which contains one user's view of one text.\n\n  # Object properties:\n  # .lasttime - The last time that a web connection serviced this object.\n  # .textobj - The shared text object being worked on.\n\n  # Inherited properties:\n  # .username - The name for the user, e.g 'fraser'\n  # .filename - The name for the file, e.g 'proposal'\n  # .shadow - The last version of the text sent to client.\n  # .backup_shadow - The previous version of the text sent to client.\n  # .shadow_client_version - The client's version for the shadow (n).\n  # .shadow_server_version - The server's version for the shadow (m).\n  # .backup_shadow_server_version - the server's version for the backup\n  #     shadow (m).\n  # .edit_stack - List of unacknowledged edits sent to the client.\n  # .delta_ok - Did the previous delta match the text length.\n\n  def __init__(self, *args, **kwargs):\n    # Setup this object\n    mobwrite_core.ViewObj.__init__(self, *args, **kwargs)\n    self.lasttime = datetime.datetime.now()\n    self.textobj = fetch_textobj(self.filename, self)\n\n    # lock_views must be acquired by the caller to prevent simultaneous\n    # creations of the same view.\n    assert lock_views.locked(), \"Can't create ViewObj unless locked.\"\n    global views\n    views[(self.username, self.filename)] = self\n\n  def cleanup(self):\n    # General cleanup task.\n    # Delete myself if I've been idle too long.\n    # Don't delete during a retrieval.\n    lock_views.acquire()\n    try:\n      if self.lasttime < datetime.datetime.now() - mobwrite_core.TIMEOUT_VIEW:\n        mobwrite_core.LOG.info(\"Idle out: '%s'\" % self)\n        global views\n        try:\n          del views[(self.username, self.filename)]\n        except KeyError:\n          mobwrite_core.LOG.error(\"View object not in view list: '%s'\" % self)\n        self.textobj.views -= 1\n    finally:\n      lock_views.release()\n\n  def nullify(self):\n    self.lasttime = datetime.datetime.min\n    self.cleanup()\n\n\ndef fetch_viewobj(username, filename):\n  # Retrieve the named view object.  Create it if it doesn't exist.\n  # Don't let two simultaneous creations happen, or a deletion during a\n  # retrieval.\n  lock_views.acquire()\n  try:\n    key = (username, filename)\n    if views.has_key(key):\n      viewobj = views[key]\n      viewobj.lasttime = datetime.datetime.now()\n      mobwrite_core.LOG.debug(\"Accepting view: '%s'\" % viewobj)\n    else:\n      if MAX_VIEWS != 0 and len(views) > MAX_VIEWS:\n        viewobj = None\n        mobwrite_core.LOG.critical(\"Overflow: Can't create new view.\")\n      else:\n        viewobj = ViewObj(username=username, filename=filename)\n        mobwrite_core.LOG.debug(\"Creating view: '%s'\" % viewobj)\n  finally:\n    lock_views.release()\n  return viewobj\n\n\nclass DaemonMobWrite(BaseHTTPRequestHandler, mobwrite_core.MobWrite):\n\n  def do_POST(self):\n    connection_origin = mobwrite_core.CFG.get(\"CONNECTION_ORIGIN\", \"\")\n    if connection_origin and self.client_address[0] != connection_origin:\n      raise IOError(\"Connection refused from %s (only %s allowed).\" %\n          (self.client_address[0], connection_origin))\n    mobwrite_core.LOG.info(\"Connection accepted from \" + self.client_address[0])\n\n    required_cookie = mobwrite_core.CFG.get(\"REQUIRED_COOKIE\", \"\")\n    if required_cookie and (('Cookie' not in self.headers) or\n        (not re.search(r'(^|;)\\s*%s=\\w' % required_cookie, self.headers['Cookie']))):\n      self.send_headers(410)\n      self.wfile.write(\"Required cookie not found.\\n\")\n      return\n\n    # Read the POST data.\n    content_length = int(self.headers['Content-Length'])\n    data = self.rfile.read(content_length)\n\n    div = data.find(\"q=\")\n    if div == -1:\n      self.send_headers(400)\n      self.wfile.write(\"'q=' parameter not found in data:\\n\")\n      self.wfile.write(data)\n      return\n\n    data = data[div + 2:]\n    data = urllib.unquote(data)\n    self.send_headers(200)\n    self.wfile.write(self.handleRequest(data))\n    self.wfile.write(\"\\n\")  # Terminating blank line.\n\n    # Goodbye\n    mobwrite_core.LOG.debug(\"Disconnecting.\")\n\n\n  def send_headers(self, code):\n    origin = self.headers['Origin']\n    self.send_response(code)\n    self.send_header('Content-type', 'text/plain')\n    self.send_header('Access-Control-Allow-Origin', origin)\n    self.send_header('Access-Control-Allow-Credentials', 'true')\n    self.end_headers()\n\n\n  def handleRequest(self, text):\n    actions = self.parseRequest(text)\n    return self.doActions(actions)\n\n\n  def doActions(self, actions):\n    output = []\n    viewobj = None\n    last_username = None\n    last_filename = None\n\n    for action_index in xrange(len(actions)):\n      # Use an indexed loop in order to peek ahead one step to detect\n      # username/filename boundaries.\n      action = actions[action_index]\n      username = action[\"username\"]\n      filename = action[\"filename\"]\n\n      # Fetch the requested view object.\n      if not viewobj:\n        viewobj = fetch_viewobj(username, filename)\n        if viewobj is None:\n          # Too many views connected at once.\n          # Send back nothing.  Pretend the return packet was lost.\n          return \"\"\n        viewobj.delta_ok = True\n        textobj = viewobj.textobj\n\n      if action[\"mode\"] == \"null\":\n        # Nullify the text.\n        mobwrite_core.LOG.debug(\"Nullifying: '%s'\" % viewobj)\n        textobj.lock.acquire()\n        try:\n          textobj.setText(None)\n        finally:\n          textobj.lock.release()\n        viewobj.nullify();\n        viewobj = None\n        continue\n\n      if (action[\"server_version\"] != viewobj.shadow_server_version and\n          action[\"server_version\"] == viewobj.backup_shadow_server_version):\n        # Client did not receive the last response.  Roll back the shadow.\n        mobwrite_core.LOG.warning(\"Rollback from shadow %d to backup shadow %d\" %\n            (viewobj.shadow_server_version, viewobj.backup_shadow_server_version))\n        viewobj.shadow = viewobj.backup_shadow\n        viewobj.shadow_server_version = viewobj.backup_shadow_server_version\n        viewobj.edit_stack = []\n\n      # Remove any elements from the edit stack with low version numbers which\n      # have been acked by the client.\n      x = 0\n      while x < len(viewobj.edit_stack):\n        if viewobj.edit_stack[x][0] <= action[\"server_version\"]:\n          del viewobj.edit_stack[x]\n        else:\n          x += 1\n\n      if action[\"mode\"] == \"raw\":\n        # It's a raw text dump.\n        data = urllib.unquote(action[\"data\"]).decode(\"utf-8\")\n        mobwrite_core.LOG.info(\"Got %db raw text: '%s'\" % (len(data), viewobj))\n        viewobj.delta_ok = True\n        # First, update the client's shadow.\n        viewobj.shadow = data\n        viewobj.shadow_client_version = action[\"client_version\"]\n        viewobj.shadow_server_version = action[\"server_version\"]\n        viewobj.backup_shadow = viewobj.shadow\n        viewobj.backup_shadow_server_version = viewobj.shadow_server_version\n        viewobj.edit_stack = []\n        if action[\"force\"] or textobj.text is None:\n          # Clobber the server's text.\n          textobj.lock.acquire()\n          try:\n            if textobj.text != data:\n              textobj.setText(data)\n              mobwrite_core.LOG.debug(\"Overwrote content: '%s'\" % viewobj)\n          finally:\n            textobj.lock.release()\n\n      elif action[\"mode\"] == \"delta\":\n        # It's a delta.\n        mobwrite_core.LOG.info(\"Got '%s' delta: '%s'\" % (action[\"data\"], viewobj))\n        if action[\"server_version\"] != viewobj.shadow_server_version:\n          # Can't apply a delta on a mismatched shadow version.\n          viewobj.delta_ok = False\n          mobwrite_core.LOG.warning(\"Shadow version mismatch: %d != %d\" %\n              (action[\"server_version\"], viewobj.shadow_server_version))\n        elif action[\"client_version\"] > viewobj.shadow_client_version:\n          # Client has a version in the future?\n          viewobj.delta_ok = False\n          mobwrite_core.LOG.warning(\"Future delta: %d > %d\" %\n              (action[\"client_version\"], viewobj.shadow_client_version))\n        elif action[\"client_version\"] < viewobj.shadow_client_version:\n          # We've already seen this diff.\n          pass\n          mobwrite_core.LOG.warning(\"Repeated delta: %d < %d\" %\n              (action[\"client_version\"], viewobj.shadow_client_version))\n        else:\n          # Expand the delta into a diff using the client shadow.\n          try:\n            diffs = mobwrite_core.DMP.diff_fromDelta(viewobj.shadow, action[\"data\"])\n          except ValueError:\n            diffs = None\n            viewobj.delta_ok = False\n            mobwrite_core.LOG.warning(\"Delta failure, expected %d length: '%s'\" %\n                (len(viewobj.shadow), viewobj))\n          viewobj.shadow_client_version += 1\n          if diffs != None:\n            # Textobj lock required for read/patch/write cycle.\n            textobj.lock.acquire()\n            try:\n              self.applyPatches(viewobj, diffs, action)\n            finally:\n              textobj.lock.release()\n\n      # Generate output if this is the last action or the username/filename\n      # will change in the next iteration.\n      if ((action_index + 1 == len(actions)) or\n          actions[action_index + 1][\"username\"] != username or\n          actions[action_index + 1][\"filename\"] != filename):\n        print_username = None\n        print_filename = None\n        if action[\"echo_username\"] and last_username != username:\n          # Print the username if the previous action was for a different user.\n          print_username = username\n        if last_filename != filename or last_username != username:\n          # Print the filename if the previous action was for a different user\n          # or file.\n          print_filename = filename\n        output.append(self.generateDiffs(viewobj, print_username,\n                                         print_filename, action[\"force\"]))\n        last_username = username\n        last_filename = filename\n        # Dereference the view object so that a new one can be created.\n        viewobj = None\n\n    return \"\".join(output)\n\n\n  def generateDiffs(self, viewobj, print_username, print_filename, force):\n    output = []\n    if print_username:\n      output.append(\"u:%s\\n\" %  print_username)\n    if print_filename:\n      output.append(\"F:%d:%s\\n\" % (viewobj.shadow_client_version, print_filename))\n\n    textobj = viewobj.textobj\n    mastertext = textobj.text\n\n    if viewobj.delta_ok:\n      if mastertext is None:\n        mastertext = \"\"\n      # Create the diff between the view's text and the master text.\n      diffs = mobwrite_core.DMP.diff_main(viewobj.shadow, mastertext)\n      mobwrite_core.DMP.diff_cleanupEfficiency(diffs)\n      text = mobwrite_core.DMP.diff_toDelta(diffs)\n      if force:\n        # Client sending 'D' means number, no error.\n        # Client sending 'R' means number, client error.\n        # Both cases involve numbers, so send back an overwrite delta.\n        viewobj.edit_stack.append((viewobj.shadow_server_version,\n            \"D:%d:%s\\n\" % (viewobj.shadow_server_version, text)))\n      else:\n        # Client sending 'd' means text, no error.\n        # Client sending 'r' means text, client error.\n        # Both cases involve text, so send back a merge delta.\n        viewobj.edit_stack.append((viewobj.shadow_server_version,\n            \"d:%d:%s\\n\" % (viewobj.shadow_server_version, text)))\n      viewobj.shadow_server_version += 1\n      mobwrite_core.LOG.info(\"Sent '%s' delta: '%s'\" % (text, viewobj))\n    else:\n      # Error; server could not parse client's delta.\n      # Send a raw dump of the text.\n      viewobj.shadow_client_version += 1\n      if mastertext is None:\n        mastertext = \"\"\n        viewobj.edit_stack.append((viewobj.shadow_server_version,\n            \"r:%d:\\n\" % viewobj.shadow_server_version))\n        mobwrite_core.LOG.info(\"Sent empty raw text: '%s'\" % viewobj)\n      else:\n        # Force overwrite of client.\n        text = mastertext\n        text = text.encode(\"utf-8\")\n        text = urllib.quote(text, \"!~*'();/?:@&=+$,# \")\n        viewobj.edit_stack.append((viewobj.shadow_server_version,\n            \"R:%d:%s\\n\" % (viewobj.shadow_server_version, text)))\n        mobwrite_core.LOG.info(\"Sent %db raw text: '%s'\" %\n            (len(text), viewobj))\n\n    viewobj.shadow = mastertext\n\n    for edit in viewobj.edit_stack:\n      output.append(edit[1])\n\n    return \"\".join(output)\n\ndef cleanup_thread():\n  # Every minute cleanup.\n  while True:\n    mobwrite_core.LOG.info(\"Running cleanup task.\")\n    for v in views.values():\n      v.cleanup()\n    for v in texts.values():\n      v.cleanup()\n\n    timeout = datetime.datetime.now() - mobwrite_core.TIMEOUT_TEXT\n\n    time.sleep(60)\n\n\ndef main():\n  mobwrite_core.CFG.initConfig(\"./mobwrite.cfg\")\n  # Start up a thread that does timeouts and cleanup.\n  thread.start_new_thread(cleanup_thread, ())\n\n  port = int(mobwrite_core.CFG.get(\"LOCAL_PORT\", 3017))\n  mobwrite_core.LOG.info(\"Listening on port %d...\" % port)\n  s = HTTPServer((\"\", port), DaemonMobWrite)\n  try:\n    s.serve_forever()\n  except KeyboardInterrupt:\n    mobwrite_core.LOG.info(\"Shutting down.\")\n    s.socket.close()\n\n\nif __name__ == \"__main__\":\n  mobwrite_core.logging.basicConfig()\n  main()\n  mobwrite_core.logging.shutdown()\n"
  },
  {
    "path": "server/code.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Utilities for manipulating JavaScript code.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\n/**\n * A collection of useful regular expressions.\n * @const\n */\nvar regexps = {};\n\n/**\n * Matches (globally) escape sequences found in string and regexp\n * literals, like '\\n' or '\\x20' or '\\u1234'.\n * @const\n */\nregexps.escapes = /\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g;\n\n/**\n * Matches a single-quoted string literal, like \"'this one'\" and\n * \"'it\\\\'s'\".\n * @const\n */\nregexps.singleQuotedString =\n    new RegExp(\"'(?:[^'\\\\\\\\\\\\r\\\\n\\\\u2028\\\\u2029]|\" +\n               regexps.escapes.source + \")*'\", 'g');\n\n/**\n * Matches a double-quoted string literal, like '\"this one\"' and\n * '\"it\\'s\"'.\n * @const\n */\nregexps.doubleQuotedString =\n    new RegExp('\"(?:[^\"\\\\\\\\\\\\r\\\\n\\\\u2028\\\\u2029]|' +\n               regexps.escapes.source + ')*\"', 'g');\n\n/**\n * Matches a string literal, like \"'this one' and '\"that one\"' as well\n * as \"the 'string literal' substring of this longer string\" too.\n * @const\n */\nregexps.string = new RegExp('(?:' + regexps.singleQuotedString.source + '|' +\n    regexps.doubleQuotedString.source + ')', 'g');\n\n/**\n * Matches exaclty a string literal, like \"'this one'\" but notably not\n * \" 'this one' \" (because it contains other characters not part of\n * the literal).\n * @const\n */\nregexps.stringExact = new RegExp('^' + regexps.string.source + '$');\n\n/**\n * RegExp matching a valid JavaScript identifier (strictly an\n * IdentifierName, which does not exclude ReservedWord).  Note that\n * this is fairly conservative, because ANY Unicode letter can appear\n * in an identifier - but the full regexp is absurdly complicated.\n * @const\n */\nregexps.identifier = /[A-Za-z_$][A-Za-z0-9_$]*/g;\n\n/**\n * RegExp matching exactly a valid JavaScript identifier.  See note\n * for .identifier, above.\n * @const\n */\nregexps.identifierExact = new RegExp('^' + regexps.identifier.source + '$');\n\n/**\n * Convert a string representation of a string literal to a string.\n * Basically does eval(s), but safely and only if s is a string literal.\n * @param {string} s A string consisting of exactly a string literal.\n * @return {string} The string value of the literal s.\n */\nvar parseString = function(s) {\n  if (!regexps.stringExact.test(s)) {\n    throw new TypeError(quote(s) + ' is not a string literal');\n  };\n  return s.slice(1, -1).replace(regexps.escapes, function(esc) {\n    switch (esc[1]) {\n      case \"'\":\n      case '\"':\n      case '/':\n      case '\\\\':\n        return esc[1];\n      case '0':\n        return '\\0';\n      case 'b':\n        return '\\b';\n      case 'f':\n        return '\\f';\n      case 'n':\n        return '\\n';\n      case 'r':\n        return '\\r';\n      case 't':\n        return '\\t';\n      case 'v':\n        return '\\v';\n      case 'u':\n      case 'x':\n        return String.fromCharCode(parseInt(esc.slice(2), 16));\n      default:\n        // RegExp in call to replace has accepted something we\n        // don't know how to decode.\n        throw new Error('unknown escape sequence \"' + esc + '\"??');\n    }\n  });\n};\n\n/**\n * Convert a string into a string literal.  We use single or double\n * quotes depending on which occurs less frequently in the string to\n * be escaped (prefering single quotes if it's a tie).  Strictly\n * speaking we only need to escape backslash, \\r, \\n, \\u2028 (line\n * separator), \\u2029 (paragraph separator) and whichever quote\n * character we're using, but for output readability we escape all the\n * control characters.\n *\n * TODO(cpcallen): Consider using optimised algorithm from Node.js's\n *     util.format (see strEscape function in\n *     https://github.com/nodejs/node/blob/master/lib/util.js).\n * @param {string} str The string to convert.\n * @return {string} The value s as a eval-able string literal.\n */\nvar quote = function(str) {\n  if (count(str, \"'\") > count(str, '\"')) {  // More 's.  Use \"s.\n    return '\"' + str.replace(quote.doubleRE, quote.replace) + '\"';\n  } else {  // Equal or more \"s.  Use 's.\n    return \"'\" + str.replace(quote.singleRE, quote.replace) + \"'\";\n  }\n};\n\n/**\n * Regexp for characters to be escaped in a single-quoted string.\n */\nquote.singleRE = /[\\x00-\\x1f\\\\\\u2028\\u2029']/g;\n\n/**\n * Regexp for characters to be escaped in a single-quoted string.\n */\nquote.doubleRE = /[\\x00-\\x1f\\\\\\u2028\\u2029\"]/g;\n\n/**\n * Replacer function (for either case)\n * @param {string} c Single UTF-16 code unit (\"character\") string to\n *     be replaced.\n * @return {string} Multi-character string containing escaped\n *     representation of c.\n */\nquote.replace = function(c) {\n  return quote.replacements[c];\n};\n\n/**\n * Map of replacements for quote function.\n */\nquote.replacements = {\n  '\\x00': '\\\\0',   '\\x01': '\\\\x01', '\\x02': '\\\\x02', '\\x03': '\\\\x03',\n  '\\x04': '\\\\x04', '\\x05': '\\\\x05', '\\x06': '\\\\x06', '\\x07': '\\\\x07',\n  '\\x08': '\\\\b',   '\\x09': '\\\\t',   '\\x0a': '\\\\n',   '\\x0b': '\\\\v',\n  '\\x0c': '\\\\f',   '\\x0d': '\\\\r',   '\\x0e': '\\\\x0e', '\\x0f': '\\\\x0f',\n  '\"': '\\\\\"', \"'\": \"\\\\'\", '\\\\': '\\\\\\\\',\n  '\\u2028': '\\\\u2028', '\\u2029': '\\\\u2029',\n};\n\n/**\n * Count non-overlapping occurrences of searchString in str.\n *\n * There are many possible implementations; using .split works pretty\n * well but this is slightly faster at time of writing.  See\n * https://jsperf.com/count-the-number-of-characters-in-a-string for\n * latest performance measurements.\n * @param {string} str The string to be searched.\n * @param {string} searchString The string to count occurrences of.\n * @return {number} The number of occurrences of searchString in str.\n */\nvar count = function(str, searchString) {\n  var index = 0;\n  for(var count = 0; ; count++) {\n    index = str.indexOf(searchString, index);\n    if (index === -1) return count;\n    index += searchString.length;\n  }\n};\n\nexports.quote = quote;\nexports.regexps = regexps;\nexports.parseString = parseString;\n\n// For unit testing only!\nexports.testOnly = {\n  count: count,\n}\n"
  },
  {
    "path": "server/codecity",
    "content": "#!/usr/bin/env node\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview A virtual world of collaborative coding.\n * @author fraser@google.com (Neil Fraser)\n */\n\n'use strict';\n\nconst crypto = require('crypto');\nconst fs = require('fs');\nconst path = require('path');\nconst Interpreter = require('./interpreter');\nconst Parser = require('./parser').Parser;\nconst Serializer = require('./serialize');\n\nvar CodeCity = {};\nCodeCity.databaseDirectory = '';\nCodeCity.interpreter = null;\nCodeCity.config = null;\n\n/**\n * Start a running instance of Code City.  May be called on a command line.\n * @param {string=} configFile Path and filename of configuration file.\n * If not present, look for the configuration file as a command line parameter.\n */\nCodeCity.startup = function(configFile) {\n  // process.argv is a list containing: ['node', 'codecity', 'db/google.cfg']\n  configFile = configFile || process.argv[2];\n  if (!configFile) {\n    console.error('Configuration file not found.\\n' +\n        'Usage: node %s <config file>', process.argv[1]);\n    process.exit(1);\n  }\n  var contents = CodeCity.loadFile(configFile);\n  CodeCity.config = CodeCity.parseJson(contents);\n\n  // Find the most recent database file.\n  var dir = CodeCity.config.databaseDirectory || './';\n  if (dir[0] === '/') {\n    CodeCity.databaseDirectory = dir;\n  } else {\n    CodeCity.databaseDirectory = path.join(path.dirname(configFile), dir);\n  }\n  if (!fs.existsSync(CodeCity.databaseDirectory)) {\n    console.error('Database directory not found: ' +\n        CodeCity.databaseDirectory);\n    process.exit(1);\n  }\n  // Find the most recent database file.\n  var checkpoint = CodeCity.allCheckpoints()[0];\n  // Load the interpreter.\n  if (checkpoint) {\n    var filename = path.join(CodeCity.databaseDirectory, checkpoint);\n    CodeCity.interpreter = CodeCity.loadCheckpoint(filename);\n  } else {\n    // Database not found, load one or more startup files instead.\n    console.log('Unable to find database file in %s, looking for startup ' +\n        'file(s) instead.', CodeCity.databaseDirectory);\n    CodeCity.interpreter = CodeCity.loadStartup(CodeCity.databaseDirectory);\n  }\n\n  // Checkpoint at regular intervals.\n  // TODO: Let the interval be configurable from the database.\n  var interval = CodeCity.config.checkpointInterval || 600;\n  CodeCity.config.checkpointInterval = interval;\n  if (interval > 0) {\n    setInterval(CodeCity.checkpoint, interval * 1000);\n  }\n\n  console.log('Load complete.  Starting Code City.');\n  CodeCity.interpreter.start();\n};\n\n/**\n * Create an Interpreter instance with desired options and initialise\n * it with custom builtins.\n * @return {!Interpreter}\n */\nCodeCity.makeInterpreter = function() {\n  var intrp = new Interpreter({\n    trimEval: true,\n    trimProgram: true,\n    methodNames: true,\n    stackLimit: 10000,\n  });\n  CodeCity.initSystemFunctions(intrp);\n  CodeCity.initLibraryFunctions(intrp);\n  return intrp;\n};\n\n/**\n * Create an Interpreter instance and deserialise a .city checkpoint\n * into it.\n * @param {string} filename The filename of the .city file to read.\n * @return {!Interpreter}\n */\nCodeCity.loadCheckpoint = function(filename) {\n  var intrp = CodeCity.makeInterpreter();\n  var flatpack = CodeCity.parseJson(CodeCity.loadFile(filename));\n  Serializer.deserialize(flatpack, intrp);\n  console.log('Checkpoint %s loaded.', filename);\n  return intrp;\n};\n\n/**\n * Create an Interpreter instance and load startup .js files into it.\n * @param {string} dir The directory containing startup files to be read.\n * @return {!Interpreter}\n */\nCodeCity.loadStartup = function(dir) {\n  var intrp = CodeCity.makeInterpreter();\n  var fileCount = 0;\n  var files = fs.readdirSync(dir);\n  for (var i = 0; i < files.length; i++) {\n    if (files[i].match(/^(core|db|test).*\\.js$/)) {\n      var filename = path.join(dir, files[i]);\n      var contents = CodeCity.loadFile(filename);\n      console.log('Loading startup file %s', filename);\n      intrp.createThreadForSrc(contents);\n      fileCount++;\n    }\n  }\n  if (fileCount === 0) {\n    console.error('Unable to find startup file(s) in %s', dir);\n    process.exit(1);\n  }\n  console.log('Loaded %d startup file(s) from %s', fileCount, dir);\n  return intrp;\n};\n\n/**\n * Open a file and read its contents.  Die if there's an error.\n * @param {string} filename\n * @return {string} File contents.\n */\nCodeCity.loadFile = function(filename) {\n  // Load the specified file from disk.\n  try {\n    return fs.readFileSync(filename, 'utf8').toString();\n  } catch (e) {\n    console.error('Unable to open file: %s', filename);\n    console.info(e);\n    process.exit(1);\n  }\n};\n\n/**\n * Parse text as JSON value.  Die if there's an error.\n * @param {string} text\n * @return {*} JSON value.\n */\nCodeCity.parseJson = function(text) {\n  // Convert from text to JSON.\n  try {\n    return JSON.parse(text);\n  } catch (e) {\n    console.error('Syntax error in parsing JSON');\n    console.info(e);\n    process.exit(1);\n  }\n};\n\n/**\n * Return a list of all currently saved checkpoints, ordered from most\n * to least recent.\n * @return {!Array<string>} Array of filenames for checkpoints.\n */\nCodeCity.allCheckpoints = function() {\n  var files = fs.readdirSync(CodeCity.databaseDirectory);\n  files = files.filter((file) => CodeCity.allCheckpoints.regexp_.test(file));\n  files.sort().reverse();\n  return files;\n};\n\nCodeCity.allCheckpoints.regexp_ =\n    /^\\d{4}-\\d\\d-\\d\\dT\\d\\d\\.\\d\\d\\.\\d\\d(\\.\\d{1,3})?Z?\\.city$/;\n\n\n/**\n * Delete as many checkpoints as needed until there's room to fit a new one.\n */\nCodeCity.deleteCheckpointsIfNeeded = function() {\n  var checkpoints = CodeCity.allCheckpoints();\n  var minFiles = Math.max(0, CodeCity.config.checkpointMinFiles || 0);\n  if (!checkpoints.length || checkpoints.length < minFiles) {\n    return;  // Not enough checkpoints saved.\n  }\n  // Look up size of last checkpoint.\n  var lastCheckpointSize =\n      CodeCity.fileSize(checkpoints[checkpoints.length - 1]);\n  var directorySize = checkpoints.reduce((sum, fileName) =>\n      sum + CodeCity.fileSize(fileName), 0);\n  // Budget for a possible 10% growth.\n  var estimateNext = directorySize + lastCheckpointSize * 1.1;\n  var maxSize = CodeCity.config.checkpointMaxDirectorySize * 1024 * 1024;\n  if (typeof maxSize !== 'number') {\n    maxSize = Infinity;\n  }\n  if (estimateNext < maxSize) {\n    return;  // There's room.\n  }\n  // Choose and delete one file.\n  var deleteFile = CodeCity.chooseCheckpointToDelete(checkpoints);\n  var fullPath = path.join(CodeCity.databaseDirectory, deleteFile);\n  console.log('Deleting checkpoint ' + fullPath);\n  fs.unlinkSync(fullPath);\n  // Do it again, until no delete is needed.\n  CodeCity.deleteCheckpointsIfNeeded();\n};\n\n/**\n * Given a list of checkpoint filenames, choose one to delete.\n * See https://neil.fraser.name/software/backup/\n * @param {!Array<string>} checkpoints Array of checkpoint filenames.\n * @return {string} Filename of checkpoint to delete.\n */\nCodeCity.chooseCheckpointToDelete = function(checkpoints) {\n  // Convert all filenames (e.g. '2018-11-09T18.49.50.548Z.city')\n  // into ISO-8601 format  (e.g. '2018-11-09T18:49:50.548Z'),\n  // then parse as milliseconds.\n  var checkpointTimes = checkpoints.map((name) =>\n      Date.parse(name.slice(0, -5).replace('.', ':').replace('.', ':')));\n  var currentTime = Date.now();\n  var totalTime = currentTime - checkpointTimes[checkpointTimes.length - 1];\n  var interval = CodeCity.config.checkpointInterval * 1000;\n  // Planning to delete one checkpoint.\n  var checkpointCount = checkpoints.length - 1;\n  // Compute ideal times.\n  var missing = Math.max(totalTime / interval - checkpointCount, 0);\n  var decayRate = (missing + 1) ** (1 / checkpointCount);\n  var idealTimes = new Array(checkpointTimes.length);\n  for (var n = 0; n < checkpointTimes.length; n++) {\n    idealTimes[n] = currentTime - (interval * (n + decayRate ** n - 1));\n  }\n\n  // Choose one backup for deletion.\n  // Compute the cumulative error from the right side.  Store in array.\n  var rightDiff = new Array(checkpointTimes.length);\n  var accumulator = 0;\n  for (var n = checkpointTimes.length - 1; n >= 1; n--) {\n    accumulator += Math.abs(checkpointTimes[n] - idealTimes[n]);\n    rightDiff[n] = accumulator;\n  }\n  // Compute the cumulative error from the left side (with backups shifted by\n  // one position, as would happen after a deletion).\n  // Use rightDiff array to compute total error for each possible deletion.\n  accumulator = 0;\n  var minDiff = Infinity;\n  var minIndex = 0;\n  for (var n = 1; n < checkpointTimes.length - 1; n++) {\n    accumulator += Math.abs(checkpointTimes[n - 1] - idealTimes[n]);\n    var diff = accumulator + rightDiff[n + 1];\n    if (diff < minDiff) {\n      // Smallest total error yet.  Save this candidate.\n      minDiff = diff;\n      minIndex = n;\n    }\n  }\n  return checkpoints[minIndex];\n};\n\n/**\n * Find the size of a file in the current database directory.\n * @param {string} fileName Name of file.\n * @return {number} Number of bytes in file.\n */\nCodeCity.fileSize = function(fileName) {\n  var fullPath = path.join(CodeCity.databaseDirectory, fileName);\n  return fs.statSync(fullPath).size;\n};\n\n/**\n * Save the database to disk.\n * @param {boolean} sync True if Code City intends to shutdown afterwards.\n * False if Code City is running this in the background.\n */\nCodeCity.checkpoint = function(sync) {\n  console.log('Checkpointing...');\n  CodeCity.deleteCheckpointsIfNeeded();\n  try {\n    CodeCity.interpreter.pause();\n    var json = Serializer.serialize(CodeCity.interpreter);\n  } finally {\n    sync || CodeCity.interpreter.start();\n  }\n  // JSON.stringify(json) would work, but adding linebreaks so that every\n  // object is on its own line makes the output more readable.\n  var text = [];\n  for (var i = 0; i < json.length; i++) {\n    text.push(JSON.stringify(json[i]));\n  }\n  text = '[' + text.join(',\\n') + ']';\n\n  var filename = (new Date()).toISOString().replace(/:/g, '.') + '.city';\n  filename = path.join(CodeCity.databaseDirectory, filename);\n  var tmpFilename = filename + '.partial';\n  try {\n    fs.writeFileSync(tmpFilename, text);\n    fs.renameSync(tmpFilename, filename);\n    console.log('Checkpoint ' + filename + ' complete.');\n  } catch (e) {\n    console.error('Checkpoint failed!  ' + e);\n  } finally {\n    // Attempt to remove partially-written checkpoint if it still exists.\n    try {\n      fs.unlinkSync(tmpFilename);\n    } catch (e) {\n    }\n  }\n};\n\n/**\n * Shutdown Code City.  Checkpoint the database before terminating.\n * Optional parameter is exit code (if numeric) or signal to (re-)kill\n * process with (if string).  Re-killing after checkpointing allows\n * systemd to accurately determine cause of death.  Defaults to 0.\n * @param {string|number=} code Exit code or signal.\n */\nCodeCity.shutdown = function(code) {\n  if (CodeCity.config.checkpointAtShutdown !== false) {\n    CodeCity.checkpoint(true);\n  }\n  if (typeof code === 'string') {\n    process.kill(process.pid, code);\n  } else {\n    process.exit(code || 0);\n  }\n};\n\n/**\n * Print one line to the log.  Allows for interpolated strings.\n * @param {...*} var_args Arbitrary arguments for console.log.\n */\nCodeCity.log = function(var_args) {\n  console.log.apply(console, arguments);\n};\n\n/**\n * Initialize user-callable system functions.\n * These are not part of any JavaScript standard.\n * BUG(#280): provide (new) NativeFunction wrappers.\n * @param {!Interpreter} intrp The Interpreter instance to initialize.\n */\nCodeCity.initSystemFunctions = function(intrp) {\n  intrp.createNativeFunction('CC.log', CodeCity.log, false);\n  intrp.createNativeFunction('CC.checkpoint', CodeCity.checkpoint, false);\n  intrp.createNativeFunction('CC.shutdown', function(code) {\n    CodeCity.shutdown(Number(code));\n  }, false);\n};\n\n/**\n * Initialize user-callable library functions.\n * These are not part of any JavaScript standard.\n * @param {!Interpreter} intrp The Interpreter instance to initialize.\n */\nCodeCity.initLibraryFunctions = function(intrp) {\n  new intrp.NativeFunction({\n    id: 'CC.acorn.parse', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var code = args[0];\n      var perms = state.scope.perms;\n      if (typeof code !== 'string') {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'argument to parse must be a string');\n      }\n      try {\n        var ast = Parser.parse(code);\n      } catch (e) {\n        throw intrp.errorNativeToPseudo(e, perms);\n      }\n      return intrp.nativeToPseudo(ast, perms);\n    }\n  });\n\n  new intrp.NativeFunction({\n    id: 'CC.acorn.parseExpressionAt', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var code = args[0];\n      var offset = args[1];\n      var perms = state.scope.perms;\n      if (typeof code !== 'string') {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'first argument to parseExpressionAt must be a string');\n      }\n      if (typeof offset !== 'number') {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'second argument to parseExpressionAt must be a number');\n      }\n      try {\n        var ast = Parser.parseExpressionAt(code, offset);\n      } catch (e) {\n        throw intrp.errorNativeToPseudo(e, perms);\n      }\n      return intrp.nativeToPseudo(ast, perms);\n    }\n  });\n\n  new intrp.NativeFunction({\n    id: 'CC.hash', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var hash = String(args[0]);\n      var data = args[1];\n      var perms = state.scope.perms;\n      var hashes = crypto.getHashes();\n      if (!hashes.includes(hash)) {\n        throw new intrp.Error(perms, intrp.RANGE_ERROR,\n            'first argument to hash must be one of:\\n' +\n            hashes.map(function(h) {return \"    '\" + h + \"'\\n\";}).join(''));\n      }\n      if (typeof data !== 'string') {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'second argument to hash must be a string');\n      }\n      try {\n        return String(crypto.createHash(hash).update(data).digest('hex'));\n      } catch (e) {\n        throw intrp.errorNativeToPseudo(e, perms);\n      }\n    }\n  });\n};\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Main program.\n\n// If this file is executed form a command line, startup Code City.\n// Otherwise, if it is required as a library, do nothing.\nif (require.main === module) {\n  CodeCity.startup();\n\n  // SIGTERM and SIGINT shut down server.\n  process.once('SIGTERM', CodeCity.shutdown.bind(null, 'SIGTERM'));\n  process.once('SIGINT', CodeCity.shutdown.bind(null, 'SIGINT'));\n\n  // SIGHUP forces checkpoint.\n  process.on('SIGHUP', CodeCity.checkpoint.bind(null, false));\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Exports\n\nmodule.exports = CodeCity;\n"
  },
  {
    "path": "server/compile",
    "content": "#!/bin/bash\n\n# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Run the Closure Compiler, in --checks-only mode, on the Code City\n# server (and optionally server unit tests as well).\n\n\n# Compile tests, which also compile server:\nreadonly ENTRY_POINT=tests/run.js\n\n# Aternatively, compile server alone:\n# readonly ENTRY_POINT=codecity.js\n\n# List of arguments to feed to compiler - flags and filenames.\nargs=(-O=ADVANCED_OPTIMIZATIONS\n      --checks-only\n\n      --module_resolution=NODE\n      --process_common_js_modules\n      --assume_function_wrapper\n      --dependency_mode=PRUNE\n\n      --externs=externs/node.js\n      --externs=externs/WeakRef.js\n\n      --hide_warnings_for=node_modules/acorn\n      node_modules/acorn/package.json\n      node_modules/acorn/**.mjs\n\n      iterable_weakmap.js\n      iterable_weakset.js\n      registry.js\n      parser.js\n      interpreter.js\n      serialize.js\n      code.js\n      selector.js\n      dumper.js\n      codecity\n      priorityqueue.js\n      dump\n\n      tests/*.js\n)\n\n\n# Set current directory to the one containing this script.\ncd \"$(dirname \"${BASH_SOURCE[0]}\")\"\n\n# Temporarily symlink extern declarations for node builtins into\n# node_modules/, and add their .js and package.json files to args.\ndeclare -a builtins\nfor path in externs/*; do\n  if [[ -d \"${path}\" && -f \"${path}/package.json\" ]]; then\n    builtins+=(\"$(basename \"${path}\")\")\n  fi\ndone\nfor builtin in \"${builtins[@]}\"; do\n  link=\"node_modules/${builtin}\"\n  if [[ -e \"${link}\" ]]; then\n    if [[ -L \"${link}\" ]]; then\n\trm \"${link}\"  # Remove old symlink.\n    else\n      echo \"$0: aborting because ${link} already exists and is not a symlink\" \\\n\t  1>&2\n      exit 1\n    fi\n  fi\n  ln -s \"../externs/${builtin}\" \"${link}\"\n  args+=(\"${link}\"/{*.js,package.json})\ndone\n\ngoogle-closure-compiler \"${args[@]}\" --entry_point=\"${ENTRY_POINT}\"\nreturn=\"$?\"\n\n# Remove extern symlinks.\nfor builtin in \"${builtins[@]}\"; do\n  link=\"node_modules/${builtin}\"\n  if [[ ! -L \"${link}\" ]]; then\n      echo \"$0: aborting because ${link} is no longer a symlink\" 1>&2\n      exit 1\n  fi\n  rm \"${link}\"\ndone\n\nexit ${return}\n"
  },
  {
    "path": "server/config.txt",
    "content": "Documentation for config file options:\n\n  \"databaseDirectory\": string\n    Relative path from this config file to the database directory.\n    Defaults to \"./\" (current directory).\n\n  \"checkpointInterval\": number\n    Number of seconds between regular checkpoints.\n    If 0, then no regular checkpoints.\n    Defaults to 600 (10 minutes).\n    TODO: Move this configuration option into the database.\n\n  \"checkpointAtShutdown\": boolean\n    If true, save a checkpoint when the server shuts down.\n    If false, don't save a checkpoint, which results in lost data.\n    Defaults to true.\n\n  \"checkpointMinFiles\": number\n    Minimum number of checkpoint files in a directory.  While there are\n    fewer than this number, then no checkpoints will be deleted.\n    Defaults to 0.\n\n  \"checkpointMaxDirectorySize\": number\n    Maximum number of megabytes allowed for checkpoints in checkpoint\n    directory.  If this value is exceeded and checkpointMinFiles is also\n    satisfied, then one or more old checkpoints will be deleted to make\n    room for the next checkpoint.\n    Defaults to Infinity.\n"
  },
  {
    "path": "server/dump",
    "content": "#!/usr/bin/env node\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Infrastructure to save the state of an Interpreter as\n *     eval-able JS.  Mainly a wrapper around Dumper, handling\n *     the application of a dupmp configuration.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nvar code = require('./code');\nvar CodeCity = require('./codecity');\nvar Do = require('./dumper').Do;\nvar Dumper = require('./dumper').Dumper;\nvar DumperOptions = require('./dumper').DumperOptions;\nvar Writable = require('./dumper').Writable;\nvar fs = require('fs');\nvar Interpreter = require('./interpreter');\nvar path = require('path');\nvar Selector = require('./selector');\n\n/**\n * Dump an Interpreter using a given dump specification.\n * @param {!Interpreter} intrp1 An interpreter initialised exactly as\n *     the one the ouptut JS will be executed by.\n * @param {!Interpreter} intrp2 An interpreter containing state\n *     modifications (relative to intrp1) to be dumped.\n * @param {!Array<!ConfigItem>} config The dump specification.\n * @param {string=} directory A directory relative to which\n *     non-absolute filenames in config should be written.  If none is\n *     supplied then they will be treated as relative to the current\n *     directory.\n * @param {boolean=} verbose Print message describing what is being done.\n */\nvar dump = function(intrp1, intrp2, config, directory, verbose) {\n  var dumper = new Dumper(intrp1, intrp2, {verbose: verbose});\n  if (verbose) console.log('Dumper initialised.');\n\n  // Skip everything that's explicitly mentioned in the config, so\n  // that paths won't get dumped until it's their turn.\n  for (var item, i = 0; (item = config[i]); i++) {\n    if (!item.contents) continue;\n    for (var entry, j = 0; (entry = item.contents[j]); j++) {\n      dumper.skip(entry.selector);\n    }\n  }\n  var /** string */ header = '';\n  // Dump the specified paths, in order.\n  for (var item, i = 0; (item = config[i]); i++) {\n    if ('options' in item) {  // An OptionsItem.\n      dumper.setOptions(item.options);\n      continue;\n    }\n    // A FileItem.\n    var filename = item.filename;\n    if (verbose) console.log('Dumping to %s...', filename);\n    if (directory !== undefined && !path.isAbsolute(filename)) {\n      filename = path.normalize(path.join(directory, filename));\n    }\n    var outputStream = new SyncWriter(filename);\n    dumper.setOptions({output: outputStream});\n\n    for (var selector, j = 0; (selector = item.prune[j]); j++) {\n      dumper.prune(selector);\n    }\n    for (var selector, j = 0; (selector = item.pruneRest[j]); j++) {\n      dumper.pruneRest(selector);\n    }\n\n    if (item.header !== undefined) header = item.header;\n    var fileHeader = header;\n    for (var key in item.headerSubs) {\n      fileHeader = fileHeader.replace(key, item.headerSubs[key]);\n    }\n    if (fileHeader) dumper.write(fileHeader);\n\n    if (item.contents) {\n      for (var entry, j = 0; (entry = item.contents[j]); j++) {\n        if (verbose) console.log('Dumping: %s', entry.selector);\n        dumper.unskip(entry.selector);\n        dumper.dumpBinding(entry.selector, entry.do);\n        dumper.write('\\n');\n      }\n    }\n    if (item.rest) {\n      if (verbose) console.log('Dumping rest.');\n      dumper.dump();\n    }\n    outputStream.end();\n  }\n};\n\n/**\n * Convert a dump plan from an !Array<!SpecConfigItem> to\n * !Array<!ConfigItem>, with validataion and a few conversions:\n *\n * - Whereas as in the input, paths will will be represented by\n *   selector strings, in the corresponding output the properties will\n *   be Selectors.  The SpecConfigEntry path: will become .selector in\n *   the corresponding COnfigEntry.\n *\n * - Whereas the input will specify do: values as strings\n *   (e.g. \"RECURSE\"), the output will have Do enum values\n *   (e.g. Do.RECURSE) instead.\n *\n * - A plain selector string ss, appearing in the contents: array of a\n *   SpecFileItem, will be replaced by the ContentEntry\n *   {selector: new Selector(ss), do: Do.RECURSE, reorder: false}.\n *\n * - All optional boolean-valued properties will be normalised to\n *   exist, defaulting to false.\n *\n * @param {*} spec The dump plan to be validated.  If this is not an\n *     !Array<!SpecEntry>, TypeError will be thrown.\n * @return {!Array<!ConfigItem>}\n */\nvar configFromSpec = function(spec) {\n  var /** !Array<!ConfigItem> */ config = [];\n\n  /** @type {function(string, number=)} */\n  function reject(message, j) {\n    var prefix = 'spec[' + i + ']';\n    if (j !== undefined) prefix = prefix + '.contents[' + j + ']';\n    if (message[0] !== '.') prefix = prefix + ' ';\n    throw new TypeError(prefix + message);\n  }\n\n  if (!Array.isArray(spec)) {\n    throw new TypeError('spec must be an array of SpecConfigItems');\n  }\n  for (var i = 0; i < spec.length; i++) {\n    var item = spec[i];\n\n    if (typeof item !== 'object' || item === null) {\n      reject('not a SpecConfigItem object');\n    }\n    if ('filename' in item) {  // It's a SpecFileItem.\n      var /** (string|undefined) */ header;\n      var /** !Object<string, string> */ headerSubs = {};\n      var /** !Array<!Selector> */ prune = [];\n      var /** !Array<!Selector> */ pruneRest = [];\n      var /** !Array<!ContentEntry> */ contents = [];\n\n      if (typeof item.filename !== 'string') {\n        // TODO(cpcallen): add better filename validity check?\n        reject('.filename is not a string');\n      } else if (!Array.isArray(item.contents) && item.contents !== undefined) {\n        reject('.contents is not an array');\n      } else if (typeof item.rest !== 'boolean' && item.rest !== undefined) {\n        reject('.rest is not a boolean');\n      }\n      if (item.header instanceof Array) {\n        header = item.header.join('\\n');\n      } else if (typeof item.header === 'string' || item.header === undefined) {\n        header = item.header;\n      } else {\n        reject('.header is not string or array of strings');\n      }\n      if (item.headerSubs instanceof Object) {\n        for (var key in item.headerSubs) {\n          var value = item.headerSubs[key];\n          if (value instanceof Array) {\n            headerSubs[key] = value.join('\\n');\n          } else if (typeof value === 'string') {\n            headerSubs[key] = value;\n          } else {\n            reject('.headerSubs.' + key + ' is not a string');\n          }\n        }\n      } else if (item.headerSubs !== undefined) {\n        reject('.headerSubs is not an object');\n      }\n      if ('prune' in item) {\n        if (!Array.isArray(item.prune)) {\n          reject('.prune is not an array');\n        }\n        for (var j = 0; j < item.prune.length; j++) {\n          prune.push(new Selector(item.prune[j]));\n        }\n      }\n      if ('pruneRest' in item) {\n        if (!Array.isArray(item.pruneRest)) {\n          reject('.pruneRest is not an array');\n        }\n        for (j = 0; j < item.pruneRest.length; j++) {\n          pruneRest.push(new Selector(item.pruneRest[j]));\n        }\n      }\n      if ('contents' in item) {\n        for (j = 0; j < item.contents.length; j++) {\n          var entry = item.contents[j];\n\n          if (typeof entry === 'string') {\n            var selector = new Selector(entry);\n            contents.push({selector: selector, do: Do.RECURSE, reorder: false});\n            continue;\n          } else if (typeof entry !== 'object' || entry === null) {\n            reject('not a SpecContentEntry object', j);\n          } else if (typeof entry.path !== 'string') {\n            reject('.path not a vaid selector string', j);\n          } else if (!Do.hasOwnProperty(entry.do)) {\n            reject('.do: ' + entry.do + ' is not a valid Do value', j);\n          } else if (typeof entry.reorder !== 'boolean' &&\n                     entry.reorder !== undefined) {\n            reject('.reorder must be boolean or omitted', j);\n          }\n          contents.push({\n            selector: new Selector(entry.path),\n            do: Do[entry.do],\n            reorder: Boolean(entry.reorder),\n          });\n        }\n      } else if (!item.rest) {\n        reject('must specify one of .contents or .rest');\n      }\n\n      config.push({\n        filename: item.filename,\n        header: header,\n        headerSubs: headerSubs,\n        prune: prune,\n        pruneRest: pruneRest,\n        contents: contents,  // Possibly empty.\n        rest: Boolean(item.rest),\n      });\n    } else if ('options' in item) {  // It's a SpecOptionsItem.\n      if (typeof item.options !== 'object') {\n        reject('.options is not a DumperOptions object');\n        // TODO(cpcallen): additional type checks?\n      }\n      config.push({options: item.options});\n    } else {\n      reject('is neither a SpecFileItem nor a SpecOptionsItem');\n    }\n  }\n  return config;\n};\n\n/**\n * A synchronous writable stream, with an API that is a simplified\n * subset of stream.Writable.\n * @constructor\n * @struct\n * @implements Writable\n * @param {string} filename The file to write to.\n */\nvar SyncWriter = function(filename) {\n  /** @type {number|null} */\n  this.fd = fs.openSync(filename, 'w', 0o600);\n};\n\n/**\n * Write string to file.\n * @override\n * @param {string} s String to write.\n * @returns {void}\n */\nSyncWriter.prototype.write = function(s) {\n  if (this.fd === null) throw Error('stream already ended');\n  fs.writeSync(this.fd, s);\n};\n\n/**\n * Close file.\n * @returns {void}\n */\nSyncWriter.prototype.end = function() {\n  if (this.fd === null) throw Error('stream already ended');\n  fs.closeSync(this.fd);\n  this.fd = null;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Data types used to specify a dump configuration.\n///////////////////////////////////////////////////////////////////////////////\n// For internal use; strict types:\n\n/**\n * A processed-and-ready-to-use configuration entry.\n * @typedef {!OptionsItem|!FileItem}\n */\nvar ConfigItem;\n\n/**\n * A processed-and-ready-to-use configuration entry setting general\n * options.\n * @typedef {{copyright: (string|!Array<string>|undefined),\n *            options: !DumperOptions}}\n */\nvar OptionsItem;\n\n/**\n * A processed-and-ready-to-use configuration entry for a single\n * output file.\n * @typedef {{filename: string,\n *            header: (string|undefined),\n *            headerSubs: !Object<string, string>,\n *            prune: !Array<!Selector>,\n *            pruneRest: !Array<!Selector>,\n *            contents: !Array<!ContentEntry>,\n *            rest: boolean}}\n */\nvar FileItem;\n\n/**\n * The type of the values of .contents entries of a ConfigEntry.\n *\n * - selector: is a Selector identifying the variable or property\n *   binding this entry applies to.\n *\n * - do: is a Do value speciifying how much of selector to dump.\n *\n * - reorder: is a boolean specifying whether it is acceptable to\n *   allow property or set/map entry entries to be created (by the\n *   output JS) in a different order than they apear in the\n *   interpreter instance being serialised.  If false, output may\n *   contain placeholder entries like:\n *\n *       var obj = {};\n *       obj.foo = undefined;  // placeholder\n *       obj.bar = function() { ... };\n *\n *   to allow obj.foo to be defined later while still preserving\n *   property order.\n * \n * @typedef {{selector: !Selector,\n *            do: Do,\n *            reorder: boolean}}\n */\nvar ContentEntry = function() {};\n\n//////////////////////////////////////////////////////////////////////\n// For dump_spec.json use; loose, JSON-compatible types:\n\n/** @typedef {!SpecOptionsItem|!SpecFileItem} */\nvar SpecConfigItem;\n\n/**\n * An OptionsItem, but with Selectors represented by selector strings.\n *\n * @typedef {{options: !DumperOptions}}\n */\nvar SpecOptionsItem;\n\n/**\n * A FileItem represented as plain old JavaScript object (i.e., as\n * ouptut by JSON.parse):\n *\n * - Do values are reprsesented by the coresponding strings (e.g.,\n *   \"RECURSE\" instead of Do.RECURSE).\n * - For convenience, header: and the values of headerSubs: may be an\n *   arrays of strings, which will be joined with newlines.\n * - Contents entries can be just a selector string, which will be\n *   treated as Do.RECURSE.\n *\n * @typedef {{filename: string,\n *            header: (string|!Array<string>|undefined),\n *            headerSubs: (!Object<string, (!Array<string>|string)>|undefined),\n *            prune: (!Array<string>|undefined),\n *            pruneRest: (!Array<string>|undefined),\n *            contents: (!Array<string|!SpecContentEntry>|undefined),\n *            rest: (boolean|undefined)}}\n */\nvar SpecFileItem;\n\n/**\n * Like a ContentEntry, but with a string instead of a Do value.\n * @typedef {{path: string,\n *            do: string,\n *            reorder: (boolean|undefined)}}\n */\nvar SpecContentEntry;\n\n///////////////////////////////////////////////////////////////////////////////\n// Main program.\n///////////////////////////////////////////////////////////////////////////////\n\nif (require.main === module) {\n  if (process.argv.length < 4) {\n    console.log(\n        'usage: dump <.city file> <dump_spec.json> <output directory>');\n    process.exit(1);\n  }\n\n  var cityFile = process.argv[2];\n  var planFile = process.argv[3];\n  var dir = process.argv[4];\n\n  var intrp = CodeCity.loadCheckpoint(cityFile);\n  var specText = fs.readFileSync(planFile);\n  const spec = JSON.parse(String(specText));\n  var config = configFromSpec(spec);\n  dump(CodeCity.makeInterpreter(), intrp, config, dir, /*verbose:*/ true);\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Exports.\n///////////////////////////////////////////////////////////////////////////////\n\nexports.configFromSpec = configFromSpec;\nexports.Do = Do;\nexports.dump = dump;\n"
  },
  {
    "path": "server/dumper.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview The Dumper class (and related helpers) to diff the\n *     state of (parts or all of) two Interpreter objects, outputing\n *     eval-able JS code to convert the one into the other.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nvar code = require('./code');\nvar Interpreter = require('./interpreter');\nvar PriorityQueue = require('./priorityqueue').PriorityQueue;\nvar Selector = require('./selector');\nvar util = require('util');\n\n///////////////////////////////////////////////////////////////////////////////\n// Dumper.\n\n/**\n * Dumper compares the state of two Interpreter instances, for the\n * purpose of generating eval-able JS that would update part or all(*)\n * of the first to the same state as the second.  This can be used to\n * dump the state of an Interpreter by comparing it against a pristine\n * Interpreter instance, or to produce a software patch by comparing a\n * long-running Interpreter against a previous version of itself or\n * against the target to which the patch will be applied.\n *\n * (*) Limitations: since there is no way to construct arbitrary stack\n * frames by evaling JS source code, it is not at present possible to\n * dump the state of threads.  This could be rectified in future by\n * providing host functions for creating/modifying the stack frames\n * associated with Thread objects.\n *\n * @constructor\n * @struct\n * @param {!Interpreter} intrp1 An interpreter initialised exactly as\n *     the one the ouptut JS will be executed by.\n * @param {!Interpreter} intrp2 An interpreter containing state\n *     modifications (relative to intrp1) to be dumped.\n * @param {!DumperOptions=} options Additional options.\n */\nvar Dumper = function(intrp1, intrp2, options) {\n  this.intrp1 = intrp1;\n  this.intrp2 = intrp2;\n  // Copy DEFAULT_OPTIONS then apply supplied options.\n  /** @type {!DumperOptions} */\n  this.options = {};\n  this.setOptions(DEFAULT_OPTIONS);\n  if (options) this.setOptions(options);\n\n  /** @const {!Map<!Interpreter.Scope,!ScopeDumper>} */\n  this.scopeDumpers = new Map();\n  /** @const {!Map<!Interpreter.prototype.Object,!ObjectDumper>} */\n  this.objDumpers2 = new Map();\n  /**\n   * Map of Arguments objects to the ScopeDumpers for the scopes to\n   * which they belong.\n   * @const {!Map<!Interpreter.prototype.Arguments,!ScopeDumper>}\n   */\n  this.argumentsScopeDumpers = new Map();\n  /**\n   * Which scope are we presently outputting code in the context of?\n   * @type {!Interpreter.Scope}\n   */\n  this.scope = intrp2.global;\n  /** @type {!Interpreter.Owner} Perms at present point in output. */\n  this.perms = intrp2.ROOT;\n  /**\n   * Map from objects from intrp1 to corresponding objects in intrp2.\n   * @type {!Map<?Interpreter.prototype.Object, ?Interpreter.prototype.Object>}\n   */\n  this.objs1to2 = new Map();\n  /**\n   * Current indentation.\n   * @type {string}\n   */\n  this.indent = '';\n\n  this.diffBuiltins_();\n\n  // Create and initialise ScopeDumper for global scope.\n  /** @const !ScopeDumper */\n  this.global = this.getScopeDumper_(intrp2.global);\n  for (var v in intrp1.global.vars) {\n    var val1 = intrp1.global.get(v);\n    var val2 = intrp2.global.get(v);\n    var val1in2;\n    if (val1 instanceof intrp1.Object) {\n      if (!(val2 instanceof intrp2.Object)) {\n        throw new TypeError('Primitive / object mistmatch');\n      }\n      val1in2 = this.objs1to2.get(val1);\n    } else {\n      val1in2 = val1;\n    }\n    if (Object.is(val1in2, val2)) {\n      this.global.setDone(v, (typeof val2 === 'object') ? Do.DONE : Do.RECURSE);\n      if (val2 instanceof intrp2.Object) {\n        this.getObjectDumper_(val2)\n            .updateRef(this, new Components(this.global, v));\n        // Other initialialisation will be taken care of below.\n      }\n    }\n  }\n\n  // Survey objects accessible via global scope to find their outer scopes.\n  this.survey_();\n};\n\n/**\n * Diff the values of buit-ins.\n * @private\n * @return {void}\n */\nDumper.prototype.diffBuiltins_ = function() {\n  // Initialise intrpObjs.\n  var builtins = this.intrp1.builtins.keys();\n  for (var i = 0; i < builtins.length; i++) {\n    var builtin = builtins[i];\n    var obj1 = this.intrp1.builtins.get(builtin);\n    var obj2 = this.intrp2.builtins.get(builtin);\n    if (!(obj2 instanceof this.intrp2.Object)) {\n      continue;  // Skip primitive-valued builtins.\n    } else if (obj1 === undefined) {\n      throw new Error('Builtin not found in intrp1 Interpreter');\n    } else if (!(obj1 instanceof this.intrp1.Object)) {\n      throw new Error(\"Builtin wasn't an object originally\");\n    }\n    // TODO(cpcallen): add check for inconsistent duplicate\n    // registrations - e.g., if parseInt and Number.parseInt were\n    // the same in intrp2 but different in intrp1.\n    this.objs1to2.set(obj1, obj2);\n  }\n\n  // Create and initialise ObjectDumpers for builtin objects.\n  for (var i = 0; i < builtins.length; i++) {\n    builtin = builtins[i];\n    obj2 = this.intrp2.builtins.get(builtin);\n    if (!(obj2 instanceof this.intrp2.Object)) continue;  // Skip primitives.\n    var objDumper = this.getObjectDumper_(obj2);\n    obj1 = this.intrp1.builtins.get(builtin);\n    // Record pre-set prototype.\n    objDumper.proto =\n        (obj1.proto === null) ? null : this.objs1to2.get(obj1.proto);\n    if (obj2.proto === objDumper.proto) {\n      objDumper.setDone(Selector.PROTOTYPE,\n                        (obj2.proto === null) ? Do.RECURSE : Do.DONE);\n    }\n    // Record pre-set owner.\n    var owner = /** @type{?Interpreter.Owner} */(\n        (obj1.owner === null) ? null : this.objs1to2.get(\n            /** @type{?Interpreter.prototype.Object} */(obj1.owner)));\n    if (obj2.owner === owner) {\n      objDumper.setDone(Selector.OWNER,\n                        (obj2.owner === null) ? Do.RECURSE : Do.DONE);\n    }\n    // Record pre-set property values/attributes.\n    var keys = obj1.ownKeys(this.intrp1.ROOT);\n    for (var j = 0; j < keys.length; j++) {\n      var key = keys[j];\n      var pd1 = obj1.getOwnPropertyDescriptor(key, this.intrp1.ROOT);\n      var pd2 = obj2.getOwnPropertyDescriptor(key, this.intrp2.ROOT);\n      var attrs = {\n        writable: pd1.writable,\n        enumerable: pd1.enumerable,\n        configurable: pd1.configurable\n      };\n      objDumper.attributes[key] = attrs;\n      var value = pd1.value instanceof this.intrp2.Object ?\n          this.objs1to2.get(pd1.value) : pd1.value;\n      objDumper.checkProperty(key, value, attrs, pd2);\n    }\n  }\n};\n\n/**\n * Dump everything that has not already been dumped so far.  The\n * generated source text is written to the current output buffer.\n * Notably, this will also dump any listening sockets.\n * @return {void}\n */\nDumper.prototype.dump = function() {\n  // Dump all remaining bindings.\n  this.global.dump(this);\n\n  // Dump listening Servers.\n  for (var key in this.intrp2.listeners_) {\n    var port = Number(key);\n    var server = this.intrp2.listeners_[port];\n    var args = [port, server.proto];\n    if (server.timeLimit) args.push(server.timeLimit);\n    this.write(this.exprForCall_('CC.connectionListen', args), ';');\n  }\n};\n\n/**\n * Generate JS source text to declare and optionally initialise a\n * particular binding (as specified by a Selector).  The generated\n * source text is written to the current output buffer.\n *\n * E.g., if foo = [42, 69, 105], then:\n *\n * myDumper.dumpBinding(new Selector('foo'), Do.DECL)\n * // Writes: 'var foo;\\n'\n * myDumper.dumpBinding(new Selector('foo'), Do.SET)\n * // Writes: 'foo = [];\\n'\n * myDumper.dumpBinding(new Selector('foo[0]'), Do.SET)\n * // Writes: 'foo[0] = 42;\\n'\n * myDumper.dumpBinding(new Selector('foo'), Do.RECURSE)\n * // Writs: 'foo[1] = 69;\\nfoo[2] = 105;\\n'\n *\n * This is mainly a wrapper around Object/ScopeDumper.p.dumpBinding\n * and ObjectDumper.p.dump.\n *\n * @param {!Selector} selector The selector for the binding to be dumped.\n * @param {!Do} todo How much to dump.  Must be >= Do.DECL.\n * @return {void}\n */\nDumper.prototype.dumpBinding = function(selector, todo) {\n  var c = this.getComponentsForSelector_(selector);\n  var done = c.dumper.dumpBinding(this, c.part, todo);\n  if (todo >= Do.RECURSE && done < Do.RECURSE) {\n    var value = c.dumper.getValue(this, c.part);\n    if (value instanceof this.intrp2.Object) {\n      var objDone = this.getObjectDumper_(value).dump(this, selector);\n      if (objDone === ObjectDumper.Done.DONE_RECURSIVELY) {\n        if (c.dumper.getDone(c.part) < Do.RECURSE) {\n          c.dumper.setDone(c.part, Do.RECURSE);\n        }\n      }\n    }\n  }\n};\n\n/**\n * Get a source text representation of a given value.  The source text\n * will vary depending on the state of the dump; for instance, if the\n * value is an object that has not yet apepared in the dump it will be\n * represented by an expression creating the object - but if it has\n * appeared before, then it will instead be represented by an\n * expression referenceing the previously-constructed object.\n *\n * This method is mostly a wrapper around the other .exprFor<Foo>_\n * methods (but notably not .exprForBuiltin_ and .exprForCall_, which\n * are wrappers around this method); see them for examples of expected\n * output.\n *\n * @private\n * @param {Interpreter.Value} value Arbitrary JS value from this.intrp2.\n * @param {!Components=} ref Location in which value will be stored.\n * @param {boolean=} callable Return the expression suitably\n *     parenthesised to be used as the callee of a CallExpression.\n * @param {string=} funcName If supplied, and if value is an anonymous\n *     UserFuncion, then the returned expression is presumed to appear\n *     on the right hand side of an assignment statement such that the\n *     resulting Function object has its .name property automatically\n *     set to this value.\n * @return {string} An eval-able representation of the value.\n */\nDumper.prototype.exprFor_ = function(value, ref, callable, funcName) {\n  var intrp2 = this.intrp2;\n  if (!(value instanceof intrp2.Object)) {\n    return this.exprForPrimitive_(value);\n  }\n\n  // Return existing reference to object (if already created).\n  var objDumper = this.getObjectDumper_(value);\n  var selector;  // Existing selector for value, if any.\n  if (objDumper.proto !== undefined && objDumper.ref) {\n    selector = objDumper.getSelector();\n  }\n  if (ref) objDumper.updateRef(this, ref);  // Safe new ref if specified.\n  if (selector) return this.exprForSelector_(selector);\n\n  // Object not yet referenced.  Is it a builtin?\n  var key = intrp2.builtins.getKey(value);\n  if (key) {\n    var quoted = code.quote(key);\n    return callable ? '(new ' + quoted + ')' : 'new ' + quoted;\n  }\n\n  // Seems to be a new object.  Check it really doesn't exist already\n  // and that it will be referenceable.\n  if (objDumper.proto !== undefined) {\n    throw new Error('object already exists but is not referenced');\n  } else if (!objDumper.ref) {\n    throw new Error('refusing to create non-referable object');\n  }\n\n  var expr;\n  if (value instanceof intrp2.Function) {\n    expr = this.exprForFunction_(value, objDumper, funcName);\n  } else if (value instanceof intrp2.Array) {\n    expr = this.exprForArray_(value, objDumper);\n  } else if (value instanceof intrp2.Date) {\n    expr = this.exprForDate_(value, objDumper);\n  } else if (value instanceof intrp2.RegExp) {\n    expr = this.exprForRegExp_(value, objDumper);\n  } else if (value instanceof intrp2.Error) {\n    expr = this.exprForError_(value, objDumper);\n  } else if (value instanceof intrp2.WeakMap) {\n    expr = this.exprForWeakMap_(value, objDumper);\n  } else {\n    expr = this.exprForObject_(value, objDumper);\n  }\n  // Do we need to set [[Prototype]]?  Not if it's already correct.\n  if (value.proto === objDumper.proto) {\n    objDumper.setDone(Selector.PROTOTYPE,\n                      (value.proto === null) ? Do.RECURSE : Do.DONE);\n  }\n  // Do we need to set [[Owner]]?  Not if it's already correct.\n  if (value.owner === this.perms) {\n    objDumper.setDone(Selector.OWNER,\n                      (value.owner === null) ? Do.RECURSE : Do.DONE);\n  }\n  return expr;\n};\n\n/**\n * Get a source text representation of a given Array object.  For the\n * moment the return value is always '[]', but the specified arrDumper\n * is modified to reflect what further work will need to be done to\n * finsh dumping the array object.\n * TODO(cpcallen): Return a more interesting array literal when possible.\n * @private\n * @param {!Interpreter.prototype.Array} arr Array object to be recreated.\n * @param {!ObjectDumper} arrDumper ObjectDumper for arr.\n * @return {string} An eval-able representation of arr.\n */\nDumper.prototype.exprForArray_ = function(arr, arrDumper) {\n  arrDumper.proto = this.intrp2.ARRAY;\n  var root = this.intrp2.ROOT;\n  var lastIndex = arr.get('length', root) - 1;\n  arrDumper.attributes['length'] =\n      {writable: true, enumerable: false, configurable: false};\n  if (lastIndex < 0 || arr.getOwnPropertyDescriptor(String(lastIndex), root)) {\n    // No need to set .length if it will be set via setting final index.\n    arrDumper.setDone('length', Do.RECURSE);\n  } else {\n    // Length exists; don't worry about it when preserving propery order.\n    arrDumper.setDone('length', Do.DECL);\n  }\n  return '[]';\n};\n\n/**\n * Get a source text representation of a given builtin, for the\n * purposes of calling it.  Usually the return value will be a string\n * like 'Object.defineProperty', but if the builtin in question hasn't\n * yet been assigned to an object it will instead return a string like\n * \"(new 'Object.defineProperty')\" to invoke the new hack to obtain\n * it.  This is a trivial wrapper around exprFor_ for a common use\n * case.\n * @private\n * @param {string} builtin The name of the builtin.\n * @return {string} An eval-able representation of obj.\n */\nDumper.prototype.exprForBuiltin_ = function(builtin) {\n  return this.exprFor_(this.intrp2.builtins.get(builtin), undefined, true);\n};\n\n/**\n * Get a source text representation of a call to a given builtin\n * function.  The array of arguments can contain either\n * Interpreter.Values or Selectors, which will be passed to .exprFor_\n * and .exprForSelector_, respectively.\n * @private\n * @param {string} builtin The name of the builtin function to call.\n * @param {!Array<!Selector|Interpreter.Value>=} args Arguments to the  call.\n * @return {string} An eval-able representation of a builtin function call.\n */\nDumper.prototype.exprForCall_ = function(builtin, args) {\n  var dumper = this;\n  return this.exprForBuiltin_(builtin) + '(' +\n      Array.from(args || []).map(function (argument) {\n        if (argument instanceof Selector) {\n          return dumper.exprForSelector_(argument);\n        } else {\n          return dumper.exprFor_(argument);\n        }\n      }).join(', ') + ')';\n};\n\n/**\n * Get a source text representation of a given Date object.  The\n * return value will usually be a string of the form \"new\n * Date('1975-07-27T23:59:59.000Z')\" (but the new hack will be invoked\n * if the Data constructor has not yet been initialised).\n * @private\n * @param {!Interpreter.prototype.Date} date Date object to be recreated.\n * @param {!ObjectDumper} dateDumper ObjectDumper for date.\n * @return {string} An eval-able representation of date.\n */\nDumper.prototype.exprForDate_ = function(date, dateDumper) {\n  dateDumper.proto = this.intrp2.DATE;\n  return 'new ' + this.exprForCall_('Date', [date.date.toISOString()]);\n};\n\n/**\n * Get a source text representation of a given Error object.  The\n * return value will usually be a string of the form \"new\n * RangeError()\" or \"new TypeError('message')\" (but the new hack will\n * be invoked if the Data constructor has not yet been initialised).\n * Only the built-in Error constructors will be used; for custom error\n * stub-types errDumper will be left in a state that will ensure that\n * {proto} is subsequently set appropriately.\n * @private\n * @param {!Interpreter.prototype.Error} err Error object to be recreated.\n * @param {!ObjectDumper} errDumper ObjectDumper for err.\n * @return {string} An eval-able representation of err.\n */\nDumper.prototype.exprForError_ = function(err, errDumper) {\n  errDumper.proto = err.proto;\n  var constructor;\n  if (err.proto === this.intrp2.EVAL_ERROR) {\n    constructor = 'EvalError';\n  } else if (err.proto === this.intrp2.RANGE_ERROR) {\n    constructor = 'RangeError';\n  } else if (err.proto === this.intrp2.REFERENCE_ERROR) {\n    constructor = 'ReferenceError';\n  } else if (err.proto === this.intrp2.SYNTAX_ERROR) {\n    constructor = 'SyntaxError';\n  } else if (err.proto === this.intrp2.TYPE_ERROR) {\n    constructor = 'TypeError';\n  } else if (err.proto === this.intrp2.URI_ERROR) {\n    constructor = 'URIError';\n  } else if (err.proto === this.intrp2.PERM_ERROR) {\n    constructor = 'PermissionError';\n  } else {\n    constructor = 'Error';\n    errDumper.proto = this.intrp2.ERROR;\n  }\n  // Try to set .message in the constructor call.\n  var message = err.getOwnPropertyDescriptor('message', this.intrp2.ROOT);\n  var args = [];\n  if (message && typeof message.value === 'string') {\n    args.push(message.value);\n    var attr = errDumper.attributes['message'] =\n        {writable: true, enumerable: false, configurable: true};\n    errDumper.checkProperty('message', message.value, attr , message);\n  }\n  // The .stack property is always created, and we always want to\n  // overwrite (or delete) it.\n  errDumper.attributes['stack'] =\n      {writable: true, enumerable: false, configurable: true};\n  var stack = err.getOwnPropertyDescriptor('stack', this.intrp2.ROOT);\n  if (stack) {\n    errDumper.setDone('stack', Do.DECL);\n  } else {\n    errDumper.scheduleDeletion('stack');\n  }\n  return 'new ' + this.exprForCall_(constructor, args);\n};\n\n/**\n * Get a source text representation of a given Function object.  The\n * returned string is just this.obj.toString(), which will be a string\n * of the form \"function name(arg0, arg1, ...) { body; }\", formatted\n * with whitespace and line breaks as it was in the original source.\n * Most of this method is therefore devoted to ensuring that\n * funcDumper is modified to reflect what further work will need to be\n * done to finsh dumping the function object.\n * TODO(cpcallen): Dump FunctionDeclarations as such, rather than\n * converting them into FunctionExpressions.\n * @private\n * @param {!Interpreter.prototype.Function} func Function object to be\n *     recreated.\n * @param {!ObjectDumper} funcDumper ObjectDumper for func.\n * @param {string=} funcName If supplied, and if value is an anonymous\n *     UserFunction, then the returned expression is presumed to appear\n *     on the right hand side of an assignment statement such that the\n *     resulting Function object has its .name property automatically\n *     set to this value if a name does not appear in the function body.\n * @return {string} An eval-able representation of func.\n */\nDumper.prototype.exprForFunction_ = function(func, funcDumper, funcName) {\n  if (!(func instanceof this.intrp2.UserFunction)) {\n    throw Error('Unable to dump non-UserFunction');\n  }\n  // TODO(cpcallen): Should throw, rather than merely warn.\n  for (var scope = func.scope; scope !== this.scope; scope = scope.outerScope) {\n    var vars = Object.getOwnPropertyNames(scope.vars);\n    if (scope.type === Interpreter.Scope.Type.FUNEXP && scope === func.scope ||\n        vars.length === 0) {\n      continue;\n    }\n    this.warn(util.format('CLOSURE: type: %s, vars: %s',\n                          scope.type, vars.join(', ')));\n  }\n\n  // Record stuff that gets done automatically by evaluating a\n  // function expression, like setting its __proto__ and .prototype.\n  funcDumper.proto = this.intrp2.FUNCTION;  // TODO(ES6): generators, etc.?\n  // The .length property will be set implicitly (and is immutable).\n  funcDumper.attributes['length'] =\n      {writable: false, enumerable: false, configurable: false};\n  funcDumper.setDone('length', Do.RECURSE);\n  // The .name property is often set automatically.\n  // TODO(ES6): Handle prefix?\n  if (func.node['id']) {\n    funcName = func.node['id']['name'];\n  }\n  if (funcName) {\n    var attr = funcDumper.attributes['name'] =\n        {writable: false, enumerable: false, configurable: true};\n    var pd = func.getOwnPropertyDescriptor('name', this.intrp2.ROOT);\n    if (pd) {\n      funcDumper.checkProperty('name', funcName, attr, pd);\n    } else {\n      funcDumper.scheduleDeletion('name');\n    }\n  }\n  // The .prototype property will automatically be created, so we\n  // don't need to \"declare\" it.  (Fortunately it's non-configurable,\n  // so we don't need to worry that it might need to be deleted.)\n  funcDumper.setDone('prototype', Do.DECL);\n  // Better still, we might be able to use the automatically-created\n  // .prototype object - if the current value is an ordinary Object\n  // and it isn't a built-in or already instantiated.  (N.B.: we don't\n  // care about its {proto}; that can be modified later.)\n  attr = funcDumper.attributes['prototype'] =\n      {writable: true, enumerable: false, configurable: false};\n  pd = func.getOwnPropertyDescriptor('prototype', this.intrp2.ROOT);\n  var prototype = pd.value;\n  if (!this.intrp2.builtins.getKey(prototype) &&\n      prototype instanceof this.intrp2.Object &&\n      Object.getPrototypeOf(prototype) === this.intrp2.Object.prototype) {\n    var prototypeFuncDumper = this.getObjectDumper_(prototype);\n    if (prototypeFuncDumper.proto === undefined) {\n      // We can use automatic .prototype object.\n      // Mark .prototype as Do.SET or Do.ATTR as appropriate.\n      funcDumper.checkProperty('prototype', prototype, attr, pd);\n      // Mark prototype object as existing and referenceable.\n      prototypeFuncDumper.proto = this.intrp2.OBJECT;\n      prototypeFuncDumper\n          .updateRef(this, new Components(funcDumper, 'prototype'));\n      // Do we need to set .prototype's [[Prototype]]?\n      if (prototype.proto === prototypeFuncDumper.proto) {\n        prototypeFuncDumper.setDone(Selector.PROTOTYPE,\n            (prototype.proto === null) ? Do.RECURSE : Do.DONE);\n      }\n      // Do we need to set .prototype's [[Owner]]?\n      if (prototype.owner === this.perms) {\n        prototypeFuncDumper.setDone(Selector.OWNER,\n            (prototype.owner === null) ? Do.RECURSE : Do.DONE);\n      }\n      // It gets a .constructor property.  Check to see if it will\n      // need to be overwritten.\n      attr = prototypeFuncDumper.attributes['constructor'] =\n          {writable: true, enumerable: false, configurable: true};\n      pd = prototype.getOwnPropertyDescriptor('constructor', this.intrp2.ROOT);\n      prototypeFuncDumper.checkProperty('constructor', func, attr, pd);\n    }\n  }\n  return func.toString();\n};\n\n/**\n * Get a source text representation of a given Object.  For now the\n * return value will always be either the string '{}' or one of the\n * form 'Object.create(prototype)' (and/or invoking the new hack if\n * required).\n * TODO(cpcallen): return a more interesting object literal when possible.\n * @private\n * @param {!Interpreter.prototype.Object} obj Object to be recreated.\n * @param {!ObjectDumper} objDumper ObjectDumper for obj.\n * @return {string} An eval-able representation of obj.\n */\nDumper.prototype.exprForObject_ = function(obj, objDumper) {\n  switch (obj.proto) {\n    case null:\n      objDumper.proto = null;\n      return this.exprForCall_('Object.create', [null]);\n    case this.intrp2.OBJECT:\n      objDumper.proto = this.intrp2.OBJECT;\n      return '{}';\n    default:\n      if (this.getObjectDumper_(obj.proto).proto !== undefined) {\n        // Record prototype connection.\n        objDumper.proto = obj.proto;\n        this.getObjectDumper_(obj.proto)\n            .updateRef(this, new Components(objDumper, Selector.PROTOTYPE));\n        return this.exprForCall_('Object.create', [obj.proto]);\n      } else {\n        // Can't set [[Prototype]] yet.  Do it later.\n        objDumper.proto = this.intrp2.OBJECT;\n        return '{}';\n      }\n  }\n};\n\n/**\n * Get a source text representation of a given primitive value (not\n * including symbols).  Correctly handles having Infinity, NaN and/or\n * undefiend shadowed by binding in the current scope.  In general\n * this is just the obvious literal, but note:\n *\n * - Strings will be single- or double-quoted depending on which is\n *   more concise.\n * - If Infinity, NaN or undefined is shadowed an alternative\n *   expression evaluating to the desired value will be returned\n *   instead.  (N.B.: true, false and null are literals so cannot be\n *   shadowed.)\n * @private\n * @param {undefined|null|boolean|number|string} value Primitive JS value.\n * @return {string} An eval-able representation of the value.\n */\nDumper.prototype.exprForPrimitive_ = function(value) {\n  switch (typeof value) {\n    case 'undefined':\n      if (this.isShadowed_('undefined')) return '(void 0)';\n      // FALL THROUGH\n    case 'boolean':\n      return String(value);\n    case 'number':\n      // All finite values (except -0) will convert back to exactly\n      // equal number, but Infinity and NaN could be shadowed.  See\n      // https://stackoverflow.com/a/51218373/4969945\n      if (Object.is(value, -0)) {\n        return '-0';\n      } else if (Number.isFinite(value)) {\n        return String(value);\n      } else if (Number.isNaN(value)) {\n        if (this.isShadowed_('NaN')) {\n          return '(0/0)';\n        }\n        return 'NaN';\n      } else {  // value is Infinity or -Infinity.\n        if (this.isShadowed_('Infinity')) {\n          return (value > 0) ? '(1/0)' : '(-1/0)';\n        }\n        return String(value);\n      }\n    case 'string':\n      return code.quote(value);\n    default:\n      if (value === null) {\n        return 'null';\n      } else {\n        throw TypeError('exprForPrimitive_ called on non-primitive value');\n      }\n  }\n};\n\n/**\n * Get a source text representation of a given RegExp object.  The\n * returned value will be a string containing a regexp literal, like\n * '/foobar/gi'.\n * @private\n * @param {!Interpreter.prototype.RegExp} re RegExp to be recreated.\n * @param {!ObjectDumper} reDumper ObjectDumper for re.\n * @return {string} An eval-able representation of re.\n */\nDumper.prototype.exprForRegExp_ = function(re, reDumper) {\n  reDumper.proto = this.intrp2.REGEXP;\n  // Some properties are implicitly pre-set.\n  var props = ['source', 'global', 'ignoreCase', 'multiline'];\n  for (var prop, i = 0; (prop = props[i]); i++) {\n    reDumper.attributes[prop] =\n        {writable: false, enumerable: false, configurable: false};\n    reDumper.setDone(prop, Do.RECURSE);\n  }\n  reDumper.attributes['lastIndex'] =\n      {writable: true, enumerable: false, configurable: false};\n  if (Object.is(re.get('lastIndex', this.intrp2.ROOT), 0)) {\n    // Can skip setting .lastIndex iff it is 0.\n    reDumper.setDone('lastIndex', Do.RECURSE);\n  } else {\n    reDumper.setDone('lastIndex', Do.DECL);\n  }\n  return re.regexp.toString();\n};\n\n/**\n * Get a source text representation of a given selector.  In general,\n * given Selector s and Dumper d, d.exprForSelector_(s) will be the\n * same as s.toExpr() except when the output needs to call a builtin\n * function like Object.getPrototypeOf that is not available via its\n * usual name - e.g. if Object.getPrototypeOf has not yet been dumped\n * then the selector foo.bar{proto} might be represented as \"(new\n * 'Object.getPrototypeOf')(foo.bar)\" instead of\n * \"Object.getPrototypeOf(foo.bar)\".\n * @private\n * @param {Selector=} selector Selector to obtain value of.\n * @return {string} An eval-able representation of the value.\n */\nDumper.prototype.exprForSelector_ = function(selector) {\n  var dumper = this;\n  return selector.toString(function(part, out) {\n    if (part === Selector.PROTOTYPE) {\n      out.unshift(dumper.exprForBuiltin_('Object.getPrototypeOf'), '(');\n      out.push(')');\n    } else if (part === Selector.OWNER) {\n      out.unshift(dumper.exprForBuiltin_('Object.getOwnerOf'), '(');\n      out.push(')');\n    } else {\n      throw new TypeError('Invalid part in parts array');\n    }\n  });\n};\n\n/**\n * Get a source text representation of a given WeakMap object.  The\n * return value will usually be the string \"new WeakMap()\" (but the\n * new hack will be invoked if the WeakMap constructor has not yet\n * been initialised).\n * @private\n * @param {!Interpreter.prototype.WeakMap} weakMap WeakMap object to\n *     be recreated.\n * @param {!ObjectDumper} weakMapDumper ObjectDumper for weakmap.\n * @return {string} An eval-able representation of weakmap.\n */\nDumper.prototype.exprForWeakMap_ = function(weakMap, weakMapDumper) {\n  weakMapDumper.proto = this.intrp2.WEAKMAP;\n  return 'new ' + this.exprForCall_('WeakMap');\n};\n\n/**\n * Given a Selector and optionally a Scope, get the corresponding\n * Components.\n * @private\n * @param {!Selector} selector A selector for the binding in question.\n * @param {!Interpreter.Scope=} scope Scope which selector is relative to.\n *     Defaults to current scope.\n * @return {!Components} The dumper and part corresponding to selector.\n */\nDumper.prototype.getComponentsForSelector_ = function(selector, scope) {\n  if (!scope) scope = this.scope;\n  if (selector.length < 1) throw new RangeError('Zero-length selector??');\n  var /** !SubDumper */ dumper = this.getScopeDumper_(scope);\n  var /** Interpreter.Value */ v;\n  for (var i = 0; i < selector.length - 1; i++) {\n    v = dumper.getValue(this, selector[i]);\n    if (!(v instanceof this.intrp2.Object)) {\n      var s = new Selector(selector.slice(0, i + 1));\n      throw TypeError(\"Can't select part of primitive \" + s + ' === ' + v);\n    }\n    dumper = this.getObjectDumper_(v);\n  }\n  return new Components(dumper, selector[selector.length - 1]);\n};\n\n/**\n * Given a Selector or selector string and optionally a Scope, get the\n * SubDumper for the value object identified.  This is intended to be\n * used only for testing.\n * @param {!Selector|string} selector A Selector or selector string\n *     referring to an object.\n * @param {!Interpreter.Scope=} scope Scope which ss is relative to.\n *     Defaults to current scope.\n * @return {!ObjectDumper} The ObjectDumper for the referred-to object.\n */\nDumper.prototype.getDumperFor = function(selector, scope) {\n  if (typeof selector === 'string') selector = new Selector(selector);\n  if (!scope) scope = this.scope;\n  var /** !SubDumper */ dumper = this.getScopeDumper_(scope);\n  var /** Interpreter.Value */ v;\n  for (var i = 0; i < selector.length; i++) {\n    v = dumper.getValue(this, selector[i]);\n    if (!(v instanceof this.intrp2.Object)) {\n      var s = new Selector(selector.slice(0, i + 1));\n      throw TypeError(\"Can't select part of primitive \" + s + ' === ' + v);\n    }\n    dumper = this.getObjectDumper_(v);\n  }\n  if (!(dumper instanceof ObjectDumper)) throw new TypeError('corrupt state');\n  return dumper;\n};\n\n/**\n * Get interned ObjectDumper for sope.\n * @private\n * @param {!Interpreter.prototype.Object} obj The object to get the dumper for.\n * @return {!ObjectDumper} The ObjectDumper for obj.\n */\nDumper.prototype.getObjectDumper_ = function(obj) {\n  if (this.objDumpers2.has(obj)) return this.objDumpers2.get(obj);\n  var objDumper = new ObjectDumper(obj);\n  this.objDumpers2.set(obj, objDumper);\n  return objDumper;\n};\n\n/**\n * Get interned ScopeDumper for sope.\n * @private\n * @param {!Interpreter.Scope} scope The scope to get info for.\n * @return {!ScopeDumper} The ScopeDumper for scope.\n */\nDumper.prototype.getScopeDumper_ = function(scope) {\n  if (this.scopeDumpers.has(scope)) return this.scopeDumpers.get(scope);\n  var scopeDumper = new ScopeDumper(scope);\n  this.scopeDumpers.set(scope, scopeDumper);\n  return scopeDumper;\n};\n\n/**\n * Returns true if a given name is shadowed in the current scope.\n * TODO(cpcallen): Use .reachable on the global Scope's ScopeDumper.\n * @private\n * @param {string} name Variable name that might be shadowed.\n * @param {!Interpreter.Scope=} scope Scope in which name is defined.\n *     Defaults to the global scope.\n * @return {boolean} True iff name is bound in a scope between the\n *     current scope (this.scope) (inclusive) and scope (exclusive).\n */\nDumper.prototype.isShadowed_ = function(name, scope) {\n  if (!scope) scope = this.intrp2.global;\n  for (var s = this.scope; s !== scope; s = s.outerScope) {\n    if (s === null) {\n      throw Error(\"Looking for name '\" + name + \"' from non-enclosing scope??\");\n    }\n    if (s.hasBinding(name)) return true;\n  }\n  return false;\n};\n\n/**\n * Mark a particular binding (as specified by a Selector) with a\n * certain done value.\n * @private\n * @param {!Selector} selector The selector for the binding to be deferred.\n * @param {!Do} done Do status to mark binding with.\n */\nDumper.prototype.markBinding_ = function(selector, done) {\n  var c = this.getComponentsForSelector_(selector);\n  var was = c.dumper.getDone(c.part);\n  if (was !== done) c.dumper.setDone(c.part, done);\n};\n\n/**\n * Mark a particular binding (as specified by a Selector) to pruned,\n * which will have the effect of trying to ensure it does not exist in\n * the state reconstructed by the dump output.\n * TODO(cpcallen): actually delete pruned properties if necessary.\n * @param {!Selector} selector The selector for the binding to be pruned.\n */\nDumper.prototype.prune = function(selector) {\n  var c = this.getComponentsForSelector_(selector);\n  c.dumper.prune(c.part);\n};\n\n/**\n * Set the .prune flag on the ObjectDumper for the object identified\n * by the given Selector to true.\n * TODO(cpcallen): actually delete pruned properties if necessary.\n * @param {!Selector} selector The selector for the binding to be pruned.\n */\nDumper.prototype.pruneRest = function(selector) {\n  selector = new Selector(selector.concat(['']));  // N.B. ugly hack!\n  var c = this.getComponentsForSelector_(selector);\n  if (!(c.dumper instanceof ObjectDumper)) throw new TypeError();\n  c.dumper.pruneRest = true;\n};\n\n/**\n * Set options for this dumper.  Can be called to change options\n * between calls to .dumpbBinding.  Will update existing settings with\n * new values, so only changed options need to be supplied.\n * @param {!DumperOptions} options The new options to apply.\n * @return {void}\n */\nDumper.prototype.setOptions = function(options) {\n  for (var key in DEFAULT_OPTIONS) {\n    if (key in options) this.options[key] = options[key];\n  }\n};\n\n/**\n * Mark a particular binding (as specified by a Selector) to be\n * skipped, which will have the effect of preventing any further\n * dumping of it until it is unskipped.\n * @param {!Selector} selector The selector for the binding to be skipped.\n */\nDumper.prototype.skip = function(selector) {\n  var c = this.getComponentsForSelector_(selector);\n  c.dumper.skip(c.part);\n};\n\n/**\n * Survey the global Scope and recursively everything accessible via\n * its bindings, to prepare for dumping.\n *\n * This is done useing Dijkstra's Algorithm to create a least-cost\n * spanning tree starting from the global scope, with distance\n * measured by Selector badness.\n *\n * @private\n * @return {void}\n */\nDumper.prototype.survey_ = function() {\n  var /** !Set<!SubDumper> */ visited = new Set();\n  var /** !PriorityQueue<!SubDumper> */ queue = new PriorityQueue();\n  // TODO(cpcallen): Remove badness; this info is already stored in queue.\n  var /** !Map<!SubDumper,number> */ badness = new Map();\n\n  // Start building spanning tree from the global scope.\n  var globalScopeDumper = this.getScopeDumper_(this.intrp2.global);\n  var /* @const */ globalBadness = 0;\n  badness.set(globalScopeDumper, globalBadness);\n  queue.insert(globalScopeDumper, globalBadness);\n\n  while (queue.length) {\n    var /** !SubDumper */ dumper = queue.deleteMin();\n    if (visited.has(dumper)) throw new Error('surveying same dumper twice??');\n    visited.add(dumper);\n    var baseBadness = badness.get(dumper);\n    badness.delete(dumper);\n\n    var /** !Array<!OutwardEdge> */ adjacent = dumper.survey(this);\n    for (var j = 0; j < adjacent.length; j++) {\n      var edge = adjacent[j];\n      if (edge instanceof ScopeDumper) {\n        if (visited.has(edge)) continue;\n        badness.set(edge, Infinity);\n        queue.set(edge, Infinity);\n      }\n      if (!(edge.value instanceof this.intrp2.Object)) continue;\n      var objectDumper = this.getObjectDumper_(edge.value);\n      if (visited.has(objectDumper)) continue;\n      var newBadness = baseBadness + Selector.partBadness(edge.part);\n      // If we've not seen objectDumper before, .get will return\n      // undefined and the following test will return false.\n      // (Undefined is effectivly a 'bigger infinity' here!)\n      if (newBadness >= badness.get(objectDumper)) continue;\n      objectDumper.preferredRef = new Components(dumper, edge.part);\n      badness.set(objectDumper, newBadness);\n      queue.set(objectDumper, newBadness);\n    }\n  }\n};\n\n/**\n * Mark a particular binding (as specified by a Selector) as no longer\n * to be skipped.\n * @param {!Selector} selector The selector for the binding to be skipped.\n */\nDumper.prototype.unskip = function(selector) {\n  var c = this.getComponentsForSelector_(selector);\n  c.dumper.unskip(c.part);\n};\n\n/**\n * Log a warning about something suspicious that happened while\n * dumping.  By default this prints to the console and .write()s a\n * comment to the file being output, but it can be overridden on\n * individual instances.\n * @param {string} warning Warning to output or log.\n */\nDumper.prototype.warn = function(warning) {\n  if (this.options.verbose) console.log(warning);\n  warning = warning.replace(/^(?!$)/gm, this.indent + '// ')\n      .slice(this.indent.length);  // Remove indent from first line.\n  this.write(warning);\n};\n\n/**\n * Write strings to current output file.  (May be buffered.)  The\n * arguments will be concatenated into a single string, which will be\n * pefixed with the current indentation and have a trailing newline\n * added if necessary.  No indentation will be added to the second and\n * subsequent lines of a multi-line write, however, to preserve\n * indentation in function bodies / multi-line string literals / etc.\n * @param {...string} var_args Strings to output.\n */\nDumper.prototype.write = function(var_args) {\n  if (this.options.output) {\n    var line = this.indent + Array.prototype.join.call(arguments, '');\n    if (!line.endsWith('\\n')) line += '\\n';\n    this.options.output.write(line);\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// SubDumper\n\n/**\n * Common interface and functionality for ScopeDumper and ObjectDumper.\n * @abstract @constructor\n * @struct\n */\nvar SubDumper = function() {\n  /** @type {?Set<Selector.Part>} */\n  this.skip_ = null;\n  /** @type {?Set<Selector.Part>} */\n  this.prune_ = null;\n};\n\n/**\n * Generate JS source text to create and/or initialize a single\n * binding (varialbe in a scope, or property / internal slot of an\n * object).\n * @abstract\n * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs.\n * @param {Selector.Part} part The part to dump.  Must be simple string.\n * @param {!Do} todo How much to do.  Must be >= Do.DECL; > Do.SET ignored.\n * @return {!Do} How much has been done on the specified binding.\n */\nSubDumper.prototype.dumpBinding = function(dumper, part, todo) {};\n\n/**\n * Return the current 'done' status of a binding.\n * @abstract\n * @param {Selector.Part} part The part to get status for.\n * @return {!Do} The done status of the binding.\n */\nSubDumper.prototype.getDone = function(part) {};\n\n/**\n * Return the value of the given part in intrp2 (i.e., the intended\n * final value, provided that it isn't going to be pruned.)\n * @abstract\n * @param {!Dumper} dumper Dumper to which this SubDumper belongs.\n * @param {Selector.Part} part The binding part to get the value of.\n * @return {Interpreter.Value} The value of that part.\n */\nSubDumper.prototype.getValue = function(dumper, part) {};\n\n/**\n * Update the current 'done' status of a binding.  Will throw a\n * RangeError if caller attempts to un-do or re-do a previously-done\n * action.\n * @param {Selector.Part} part The part to set status for.\n * @param {!Do} done The new done status of the binding.\n */\nSubDumper.prototype.setDone = function(part, done) {};\n\n/**\n * Mark a particular binding (as specified by a Part) to be pruned,\n * which will have the effect of trying to ensure it does not exist in\n * the state reconstructed by the dump output.\n * TODO(cpcallen): actually delete pruned properties if necessary.\n * @param {Selector.Part} part The binding to be pruned.\n */\nSubDumper.prototype.prune = function(part) {\n  if (!this.prune_) this.prune_ = new Set();\n  this.prune_.add(part);\n};\n\n/**\n * Return true the specified part is presently reachable - i.e., could\n * be set or read by an expression in the currently-dumped scope.\n * @abstract\n * @param {!Dumper} dumper Dumper to which this SubDumper belongs.\n * @param {Selector.Part=} part The binding whose reachability is of\n *     interest.  Ignored, since all object bindings are always\n *     reachable if the object is.\n * @return {boolean}\n */\nSubDumper.prototype.reachable = function(dumper, part) {};\n\n/**\n * Mark a particular binding (as specified by a Part) to be skipped,\n * which will have the effect of preventing any further dumping of it\n * until it is unskipped.\n * @param {Selector.Part} part The binding to be skipped.\n */\nSubDumper.prototype.skip = function(part) {\n  if (!this.skip_) this.skip_ = new Set();\n  this.skip_.add(part);\n};\n\n/**\n * Survey the scope or object associated with this SubDumper in\n * preparation for dumping.\n *\n * Returns a list of OutwardEdges representing outward edges\n * from this node of the object graph.: the properties (and internal\n * slots) of this object.  Exceptionally, because Scopes are not\n * Interpreter Objects (and there is no Selector.Part corresponding to\n * the enclosing scope slot of a UserFunction object), the\n * ObjectDumper for a UserFunction will also include a bare\n * ScopeDumper in its returned array.\n *\n * @abstract\n * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs.\n * @return {!Array<OutwardEdge>}\n */\nSubDumper.prototype.survey = function(dumper) {};\n\n/**\n * Mark a particular binding (as specified by a Selector) as no longer\n * to be skipped.\n * @param {Selector.Part} part The binding to be unskipped.\n */\nSubDumper.prototype.unskip = function(part) {\n  if (!this.skip_) return;\n  this.skip_.delete(part);\n  if (this.skip_.size === 0) this.skip_ = null;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// ScopeDumper\n\n/**\n * ScopeDumper encapsulates all machinery to dump an Interpreter.Scope\n * to eval-able JS, including maintaining all the dump-state info\n * required to keep track of what variable bindings have and haven't\n * yet been dumped.\n * @constructor @extends {SubDumper}\n * @struct\n * @param {!Interpreter.Scope} scope The scope to keep state for.\n */\nvar ScopeDumper = function(scope) {\n  SubDumper.call(this);\n  this.scope = scope;\n  /** @private @const {!Object<string, Do>} Done status of each variable. */\n  this.doneVar_ = Object.create(null);\n  /** @const {!Set<!ScopeDumper>} Set of inner scopes. */\n  this.innerScopes = new Set();\n  /** @const {!Set<!ObjectDumper>} Set of inner functions. */\n  this.innerFunctions = new Set();\n};\nObject.setPrototypeOf(ScopeDumper, SubDumper);\nObject.setPrototypeOf(ScopeDumper.prototype, SubDumper.prototype);\n\n/**\n * Generate JS source text to create and/or initialize a single\n * variable binding.\n * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs.\n * @return {void}\n */\nScopeDumper.prototype.dump = function(dumper) {\n  if (dumper.scope !== this.scope) {\n    throw new Error(\"Can't dump scope other than current scope\");\n  }\n  // Dump variable bindings.\n  for (var name in this.scope.vars) {\n    if (this.getDone(name) >= Do.RECURSE) continue;  // Skip already-done.\n    // Dump binding itself.\n    var done = this.dumpBinding(dumper, name, Do.RECURSE);\n    // Attempt to recursively dump the value object, if there is one.\n    if (done >= Do.RECURSE) continue;\n    var value = this.getValue(dumper, name);\n    if (!(value instanceof dumper.intrp2.Object)) continue;\n    var valueDumper = dumper.getObjectDumper_(value);\n    var objDone = valueDumper.dump(dumper, new Selector(name));\n    if (objDone === ObjectDumper.Done.DONE_RECURSIVELY) {\n      this.setDone(name, Do.RECURSE);\n    }\n  }\n};\n\n/**\n * Generate JS source text to create and/or initialize a single\n * variable binding.\n * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs.\n * @param {Selector.Part} part The part to dump.  Must be simple string.\n * @param {!Do} todo How much to do.  Must be >= Do.DECL; > Do.SET ignored.\n * @return {!Do} How much has been done on the specified binding.\n */\nScopeDumper.prototype.dumpBinding = function(dumper, part, todo) {\n  if (dumper.scope !== this.scope) {\n    throw new Error(\"Can't create binding other than in current scope\");\n  } else if (typeof part !== 'string') {\n    throw new TypeError('Invalid part (not a variable name)');\n  } else if (!this.scope.hasBinding(part)) {\n    throw new ReferenceError(\"Can't dump non-existent variable \" + part);\n  } else if (this.prune_ && this.prune_.has(part)) {\n    return Do.RECURSE;  // Don't dump this binding at all.\n  } else if (this.skip_ && this.skip_.has(part)) {\n    return this.getDone(part);  // Do nothing but don't lie about it.\n  }\n  var done = this.getDone(part);\n  var output = [];\n  if (todo < Do.DECL || done >= todo || done > Do.SET) return done;\n  if (done < Do.DECL) {\n    output.push('var ');\n    done = Do.DECL;\n  }\n  if (done < Do.SET) {\n    output.push(part);\n    if (todo >= Do.SET) {\n      var ref = new Components(this, part);\n      var value = this.scope.get(part);\n      output.push(' = ', dumper.exprFor_(value, ref, false, part));\n      done = (value instanceof dumper.intrp2.Object) ? Do.DONE : Do.RECURSE;\n    }\n    output.push(';');\n  }\n  this.setDone(part, done);\n  dumper.write.apply(dumper, output);\n  return done;\n};\n\n/**\n * Return the current 'done' status of a variable binding.\n * @param {Selector.Part} part The part get status for.  Must be simple string.\n * @return {!Do} The done status of the binding.\n */\nScopeDumper.prototype.getDone = function(part) {\n  if (typeof part !== 'string') {\n    throw new TypeError('Invalid part (not a variable name)');\n  }\n  var done = this.doneVar_[part];\n  return done === undefined ? Do.UNSTARTED : done;\n};\n\n/**\n * Update the current 'done' status of a variable binding.  Will throw\n * a RangeError if caller attempts to un-do a previously-done action.\n * @param {Selector.Part} part The part set status for.  Must be simple string.\n * @param {!Do} done The new done status of the binding.\n */\nScopeDumper.prototype.setDone = function(part, done) {\n  if (typeof part !== 'string') {\n    throw new TypeError('Invalid part (not a variable name)');\n  }\n  var old = this.getDone(part);\n\n  // Invariant checks.\n  if (done <= old) {\n    var fault = (done === old) ? 'Refusing redundant' : \"Can't undo previous\";\n    throw new RangeError(fault + ' work on variable ' + part);\n  }\n  this.doneVar_[part] = done;\n};\n\n/**\n * Return the value of the given variable in this.scope (i.e., the\n * value in intrp2, and the intended final value - provided that it\n * isn't going to be pruned.)\n * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs.\n * @param {Selector.Part} part The binding part to get the value of.\n * @return {Interpreter.Value} The value of that part.\n */\nScopeDumper.prototype.getValue = function(dumper, part) {\n  if (typeof part !== 'string') throw new TypeError('Invalid first part??');\n  if (!this.scope.hasBinding(part)) {\n    throw new ReferenceError(part + ' is not defined');\n  }\n  return this.scope.get(part);\n};\n\n/**\n * Return true iff the given binding (which must be a variable name)\n * is currently reachable.  Specifically, this will return true if:\n *\n * 1. this.scope is the current value dumper.scope, since we can\n *    always access existing bindings and create new ones in the\n *    current scope.\n * 2. this.scope is an outer scope of dumper.scope and par \n *    is not shadowed in dumper.scope or any intervening one.\n *\n * BUG(cpcallen): Only #1 is implemented at the moment.\n *\n * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs.\n * @param {Selector.Part=} part Variable name whose reachability is of\n *     interest.\n * @return {boolean}\n */\nScopeDumper.prototype.reachable = function(dumper, part) {\n  return this.scope === dumper.scope;\n};\n\n/**\n * Visit a Scope to prepare for dumping.  In particular:\n *\n * - If this.scope.outerScope is set, record this as one of it's inner\n *   scopes, so that when we go to dump that scope later we know we\n *   need to dump this one inside it.\n *\n * - Find any Arguments object attached to this scope and record the\n *   relationship in the dumper.argumentsScopeDumpers map.\n *\n * - Collect and return an array of {part, value} tuples, where each\n *   represents a variable in this scope.\n *\n * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs.\n * @return {!Array<OutwardEdge>}\n */\nScopeDumper.prototype.survey = function(dumper) {\n  var /** !Array<OutwardEdge> */ adjacent = [];\n\n  // Record parent scope.\n  if (this.scope !== dumper.intrp2.global) {\n    if (this.scope.outerScope === null) {\n      throw new TypeError('Non-global scope has null outer scope');\n    }\n    var outerScopeDumper = dumper.getScopeDumper_(this.scope.outerScope);\n    // Record this as inner scope of this.outerScope.\n    outerScopeDumper.innerScopes.add(this);\n    // Don't forget to survey the outerScope, too:\n    adjacent.push(outerScopeDumper);\n  }\n  // Record arguments object attached to this scope if it's a function scope.\n  if (this.scope.type === Interpreter.Scope.Type.FUNCTION &&\n      this.scope.hasImmutableBinding('arguments')) {\n    var argsObject = this.scope.get('arguments');\n    if (!(argsObject instanceof dumper.intrp2.Arguments)) {\n      // BUG(cpcallen): what about function(arguments) {...}?\n      throw new TypeError('arguments not an Arguments object');\n    } else if (dumper.argumentsScopeDumpers.has(argsObject)) {\n      // BUG(cpcallen): what about (function(arguments) {...})(\n      //     (function() {return arguments;})()); ?\n      throw new Error('Arguments object belongs to more than one scope');\n    }\n    dumper.argumentsScopeDumpers.set(argsObject, this);\n  }\n\n  // Collect Components for other objects reachable from this one.\n  for (var name in this.scope.vars) {\n    adjacent.push({part: name, value: this.scope.get(name)});\n  }\n\n  return adjacent;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// ObjectDumper\n\n/**\n * ObjectDumper encapsulates all machinery to dump an\n * Interpreter.prototype.Object to eval-able JS, including maintaining\n * all the dump-state info required to keep track of what properties\n * (etc.) have and haven't yet been dumped.\n * @constructor @extends {SubDumper}\n * @struct\n * @param {!Interpreter.prototype.Object} obj The object to keep state for.\n */\nvar ObjectDumper = function(obj) {\n  SubDumper.call(this);\n  /** @type {!Interpreter.prototype.Object} */\n  this.obj = obj;\n  /**\n   * Preferred reference to this object.  E.g., for Object.prototype\n   * this would be {dumper: <dumper for Object>, part: 'prototype'}.\n   * @type {?Components}\n   */\n  this.preferredRef = null;\n  /**\n   * A valid-at-this-point-in-the-dump referrence to this object.\n   * @type {?Components} Reference to this object, once created.\n   */\n  this.ref = null;\n  /**\n   * If true, then .dump() will not dump any ordinary (property /\n   * member / entry) bindings.  This means that only bindings dumped\n   * by calls to .dumpBinding() will be dumped.  (Prototype and owner\n   * bindings will still be dumped unless they are individually\n   * .prune()ed.)\n   * @type {boolean}\n   */\n  this.pruneRest = false;\n  /** @type {!ObjectDumper.Done} How much has object been dumped? */\n  this.done = ObjectDumper.Done.NO;\n  /** @private @type {!Do} Has prototype been set? */\n  this.doneProto_ = Do.DECL;  // Never need to 'declare' the [[Prototype]] slot!\n  /**\n   * Current value of [[Prototype]] slot of obj at this point in dump.\n   * Typically initially Object.prototype (or similar); will be ===\n   * obj.proto when complete.  Used to check for unwritable inherited\n   * properties when attempting to set properties by assignment.\n   * Should only be undefined if object has not yet been created.\n   * @type {?Interpreter.prototype.Object|undefined}\n   */\n  this.proto = undefined;\n  /** @private @type {!Do} Has owner been set? */\n  this.doneOwner_ = Do.DECL;  // Never need to 'declare' that object has owner!\n  /** @private @const {!Object<string, Do>} Done status of each property. */\n  this.doneProp_ = Object.create(null);\n  /**\n   * Map of property name -> property descriptor, where property\n   * descriptor is a map of attribute names (writable, enumerable,\n   * configurable, more tbd) to boolean values describing the present\n   * attributes of the property at the current point in the dump; this\n   * is updated as code that modifies them is generated.  (We do not\n   * store values here.)\n   * @type {!Object<string, !Object<string, boolean>>}\n   */\n  this.attributes = Object.create(null);\n  /** @type {?Array<string>} Properties to delete. */\n  this.toDelete = null;\n};\nObject.setPrototypeOf(ObjectDumper, SubDumper);\nObject.setPrototypeOf(ObjectDumper.prototype, SubDumper.prototype);\n\n/**\n * Updates done state of property binding after defining/assigning a\n * property.  This computes the new done value, calls .setDone(key,\n * done) and returns the new value.\n * @param {string} key The property key just updated.\n * @param {Interpreter.Value} value The value just assigned to the property.\n * @param {!Object<string, boolean>} attr The property's current attributes.\n * @param {!Interpreter.Descriptor|undefined} pd Property descriptor\n *     returned by calling this.obj.getOwnPropertyDescriptor(key, ...).\n * @return {!Do} New done state.\n */\nObjectDumper.prototype.checkProperty = function(key, value, attr, pd) {\n  var done;\n  if (!Object.is(value, pd.value)) {\n    done = Do.DECL;\n  } else if (attr.writable === pd.writable &&\n      attr.enumerable === pd.enumerable &&\n      attr.configurable === pd.configurable) {\n    done = (typeof value === 'object') ? Do.ATTR : Do.RECURSE;\n  } else {\n    done = Do.SET;\n  }\n  this.setDone(key, done);\n  return done;\n};\n\n/**\n * Recursively dumps all bindings of the object (and objects reachable\n * via it).\n * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs.\n * @param {!Selector=} objSelector Selector refering to this object.\n *     Optional; defaults to whatever selector was used to create the\n *     object.\n * @param {!Array<(!SubDumper)>=} visiting List of Scope/Object dumpers\n *     currently being recursively dumped.  Used only when\n *     recursing.\n * @param {!Set<(!SubDumper)>=} visited Set of Scope/Object dumpers\n *     currently that have already been visited.  Used only when\n *     recursing.\n * @return {!ObjectDumper.Done|?ObjectDumper.Pending} Done status for\n *     object, or or null if there is an outstanding dump or\n *     dumpBinding invocaion for this object, or a (bindings,\n *     dependencies) pair if a recursive call encountered such an\n *     outstanding invocation.\n */\nObjectDumper.prototype.dump = function(\n    dumper, objSelector, visiting, visited) {\n  if (!visiting) visiting = [];\n  if (!visited) visited = new Set();\n  if (!objSelector) objSelector = this.getSelector();\n  if (!objSelector) throw new Error(\"can't dump unreferencable object\");\n  if (this.proto === undefined) {\n    throw new Error(\"can't dump uncreated object \" + this.getSelector(true));\n  }\n  if (visited.has(this)) return null;\n  if (this.done === ObjectDumper.Done.DONE_RECURSIVELY) return this.done;\n  visiting.push(this);\n  visited.add(this);\n\n  // Delete properties that shouldn't exist.\n  if (this.toDelete) {\n    var sel = new Selector(objSelector);\n    for (var key, i = 0; (key = this.toDelete[i]); i++) {\n      sel.push(key);\n      dumper.write('delete ', dumper.exprForSelector_(sel), ';');\n      sel.pop();\n    }\n    this.toDelete = null;\n  }\n  // Dump bindings: prototype, owner, and properties.\n  // TODO(cpcallen): Also dump set/map entries, etc.\n  // Optimistically assume success until we find otherwise.\n  var /** !ObjectDumper.Done */ done = ObjectDumper.Done.DONE_RECURSIVELY;\n  var /** ?ObjectDumper.Pending */ pending = null;\n  var keys = this.obj.ownKeys(dumper.intrp2.ROOT);\n  var parts = [Selector.PROTOTYPE, Selector.OWNER];\n  if (!this.pruneRest) parts = parts.concat(keys);\n  for (i = 0; i < parts.length; i++) {\n    var part = parts[i];\n    if (this.prune_ && this.prune_.has(part)) {\n      // TODO(cpcallen): delete binding if necessary.\n      continue;\n    } else if (this.skip_ && this.skip_.has(part) ||\n        dumper.options.skipBindings.includes(part)) {\n      // Can't finish an object with skipped parts.\n      done = /** @type {!ObjectDumper.Done} */(\n          Math.min(done, ObjectDumper.Done.NO));\n      continue;\n    }\n    // Attempt to dump the binding itself.\n    var bindingSelector = new Selector(objSelector.concat(part));\n    var bindingDone =\n        this.dumpBinding(dumper, part, Do.DONE, objSelector, bindingSelector);\n    if (bindingDone === Do.RECURSE) {  // Nothing more to do for part.\n      continue;\n    } else if (bindingDone < Do.DONE) {  // Object can't be done.\n      done = /** @type {!ObjectDumper.Done} */(\n          Math.min(done, ObjectDumper.Done.NO));\n    }\n    if (bindingDone < Do.SET) continue;  // Can't recurse if no object yet!\n\n    // Attempt to recursively dump the value object, if there is one.\n    var value = this.getValue(dumper, part);\n    if (!(value instanceof dumper.intrp2.Object)) continue;\n    var valueDumper = dumper.getObjectDumper_(value);\n    if (dumper.options.treeOnly &&\n        (this !== valueDumper.preferredRef.dumper ||\n         part !== valueDumper.preferredRef.part)) {\n      // Refuse to recurse into objects outside of the spanning tree.\n      done = /** @type {!ObjectDumper.Done} */(\n          Math.min(done, ObjectDumper.Done.DONE));\n      continue;\n    }\n    valueDumper.updateRef(dumper, new Components(this, part));\n    var objDone =\n        valueDumper.dump(dumper, bindingSelector, visiting, visited);\n    if (objDone === null || objDone instanceof ObjectDumper.Pending) {\n      // Circular structure detected.\n      if (!pending) {\n        pending = new ObjectDumper.Pending(bindingSelector, valueDumper);\n      } else {\n        pending.add(bindingSelector, valueDumper);\n      }\n      if (objDone instanceof ObjectDumper.Pending) {\n        // Circular dependency detected amongst objects being recursively\n        // dumped.  Record details of circularity.  Add this binding.\n        pending.merge(objDone);\n      }\n    } else if (objDone === ObjectDumper.Done.DONE_RECURSIVELY) {\n      // Successful recursive dump.  Upgrade binding accordingly.\n      this.setDone(part, Do.RECURSE);\n    }\n  }\n\n  if (this.done < ObjectDumper.Done.DONE && done >= ObjectDumper.Done.DONE) {\n    // Dump extensibility.\n    if (!this.obj.isExtensible(dumper.intrp2.ROOT)) {\n      dumper.write(\n          dumper.exprForCall_('Object.preventExtensions', [objSelector]),\n          ';');\n    }\n    this.done = ObjectDumper.Done.DONE;  // Set now to allow cycles to complete.\n  }\n\n  visiting.pop();\n  // If all parts of circular dependency are DONE, mark all as\n  // RECURSE / DONE_RECURSIVELY.\n  // TODO(cpcallen): Clean up this code.\n  if (done) {\n    if (pending) {\n      if (pending.dependencies.some(\n          function(dep) {return !dep.done || visiting.includes(dep);})) {\n        done = /** @type {!ObjectDumper.Done} */(\n            Math.min(done, ObjectDumper.Done.DONE));\n      } else {\n        var /** !Selector */ binding;\n        for (i = 0; (binding = pending.bindings[i]); i++) {\n          dumper.markBinding_(binding, Do.RECURSE);\n        }\n        for (var dep, i = 0; (dep = pending.dependencies[i]); i++) {\n          dep.done = ObjectDumper.Done.DONE_RECURSIVELY;\n        }\n        pending = null;\n      }\n    }\n  }\n  this.done = done;\n  return pending || done;\n};\n\n/**\n * Generate JS source text to create and/or initialize a single\n * binding (property or internal slot) of the object.\n * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs.\n * @param {Selector.Part} part The binding part to dump.\n * @param {!Do} todo How much to do.  Must be >= Do.DECL; > Do.ATTR ignored.\n * @param {!Selector=} objSelector Selector refering to this object.\n *     Optional; will be created using getSelector if not supplied.\n * @param {!Selector=} bindingSelector Selector refering to part.\n *     Optional; will be created by appending part to objSelector.\n * @return {!Do} The done status of the specified binding.\n */\nObjectDumper.prototype.dumpBinding = function(\n    dumper, part, todo, objSelector, bindingSelector) {\n  if (!objSelector) objSelector = this.getSelector();\n  if (!objSelector) {\n    throw new Error(\"can't dump unreferencable object\");\n  } else if (this.proto === undefined) {\n    throw new Error(\"can't dump uncreated object \" + this.getSelector(true));\n  } else if (this.prune_ && this.prune_.has(part)) {\n    return Do.RECURSE;  // Don't dump requested binding at all.\n  } else if (this.skip_ && this.skip_.has(part)) {\n    return this.getDone(part);  // Do nothing but don't lie about it.\n  }\n\n  if (!bindingSelector) {\n    bindingSelector = new Selector(objSelector.concat(part));\n  }\n  var partRef = new Components(this, part);\n  if (part === Selector.PROTOTYPE) {\n    return this.dumpPrototype_(dumper, todo, partRef,\n                               objSelector, bindingSelector);\n  } else if (part === Selector.OWNER) {\n    return this.dumpOwner_(dumper, todo, partRef,\n                           objSelector, bindingSelector);\n  } else if (typeof part === 'string') {\n    return this.dumpProperty_(dumper, part, todo, partRef,\n                              objSelector, bindingSelector);\n  } else {\n    throw new Error('Invalid part');\n  }\n};\n\n/**\n * Generate JS source text to set the object's [[Owner]].\n * @private\n * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs.\n * @param {!Do} todo How much to do.  Must be >= Do.DECL; > Do.SET ignored.\n * @param {!Components} partRef A reference to this object's [[Owner]] slot.\n * @param {!Selector} objSelector Selector refering to this object.\n * @param {!Selector} bindingSelector Selector refering to this\n *     object's [[Owner]] slot.\n * @return {!Do} The done status of the object's [[Owner]] slot.\n */\nObjectDumper.prototype.dumpOwner_ = function(\n    dumper, todo, partRef, objSelector,bindingSelector) {\n  var value = /** @type {?Interpreter.prototype.Object} */(this.obj.owner);\n  if (todo >= Do.SET && this.doneOwner_ < Do.SET) {\n    // Record owner connection.\n    if (value !== null) {\n      dumper.getObjectDumper_(value)\n          .updateRef(dumper, new Components(this, Selector.OWNER));\n    }\n    dumper.write(\n        dumper.exprForCall_('Object.setOwnerOf', [objSelector, value]),\n        ';');\n    this.doneOwner_ = (value === null) ? Do.RECURSE: Do.DONE;\n  }\n  return this.doneOwner_;\n};\n\n/**\n * Generate JS source text to create and/or initialize a single\n * property of the object.  The output will consist of:\n *\n * - An assignment statement to create the property and/or set its\n *   value, if necessary and possible.\n * - A call to Object.defineProperty, to set the property's attributes\n *   (and value, if the value couldn't be set by assignement), if\n *   necessary.\n * @private\n * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs.\n * @param {string} key The property to dump.\n * @param {!Do} todo How much to do.\n * @param {!Components} partRef A reference to this object's property [key].\n * @param {!Selector} objSelector Selector refering to this object.\n * @param {!Selector} bindingSelector Selector refering to key.\n * @return {!Do} The done status of the specified property.\n */\nObjectDumper.prototype.dumpProperty_ = function(\n    dumper, key, todo, partRef, objSelector, bindingSelector) {\n  var pd = this.obj.getOwnPropertyDescriptor(key, dumper.intrp2.ROOT);\n  if (!pd) {\n    throw new RangeError(\"can't dump nonexistent property \" + bindingSelector);\n  }\n\n  // Do this binding, if requested.\n  var done = this.getDone(key);\n  if (todo >= Do.DECL && todo > done && done < Do.ATTR) {\n    var attr = this.attributes[key];\n    // If only \"declaring\" property, set it to undefined.\n    var value = (todo === Do.DECL) ? undefined : pd.value;\n\n    // Output assignment statement if useful.\n    if (done < Do.SET && this.isWritable(dumper, key)) {\n      if (!attr) {\n        attr = this.attributes[key] =\n            {writable: true, enumerable: true, configurable: true};\n      }\n      // Will this assignemnt set the .name of an anonymous function?\n      // TODO(ES6): Handle prefix?\n      var funcName = dumper.intrp1.options.methodNames ? key : undefined;\n      dumper.write(dumper.exprForSelector_(bindingSelector), ' = ',\n                   dumper.exprFor_(value, partRef, false, funcName), ';');\n      done = this.checkProperty(key, value, attr, pd);\n    }\n\n    // Output defineProperty call if useful.\n    if (todo > done && done < Do.ATTR) {\n      if (!attr) {\n        attr = this.attributes[key] =\n            {writable: false, enumerable: false, configurable: false};\n      } else if (!attr.configurable) {\n        dumper.warn(\n            \"Can't redefine non-configurable property \" + bindingSelector);\n        return done;\n      }\n      var items = [];\n      if (attr.writable !== (pd.writable || todo < Do.SET)) {\n        attr.writable = pd.writable || todo < Do.SET;\n        items.push('writable: ' + attr.writable);\n      }\n      if (attr.enumerable !== (pd.enumerable || todo < Do.SET)) {\n        attr.enumerable = pd.enumerable || todo < Do.SET;\n        items.push('enumerable: ' + attr.enumerable);\n      }\n      if (attr.configurable !== (pd.configurable || todo < Do.SET)) {\n        attr.configurable = pd.configurable || todo < Do.SET;\n        items.push('configurable: ' + attr.configurable);\n      }\n      if (todo >= Do.SET && done < Do.SET) {\n        // TODO(cpcallen): supply selector here?\n        items.push('value: ' + dumper.exprFor_(value));\n      }\n      dumper.write(dumper.exprForBuiltin_('Object.defineProperty'), '(',\n                   dumper.exprForSelector_(objSelector), ', ',\n                   dumper.exprFor_(key), ', {', items.join(', '), '});');\n      done = this.checkProperty(key, value, attr, pd);\n    }\n  }\n  return done;\n};\n\n/**\n * Generate JS source text to set the object's [[Prototype]].\n * @private\n * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs.\n * @param {!Do} todo How much to do.  Must be >= Do.DECL; > Do.SET ignored.\n * @param {!Components} partRef A reference to this object's [[Owner]] slot.\n * @param {!Selector} objSelector Selector refering to this object.\n * @param {!Selector} bindingSelector Selector refering to this\n *     object's [[Prototype]] slot.\n * @return {!Do} The done status of the object's [[Prototype]] slot.\n */\nObjectDumper.prototype.dumpPrototype_ = function(\n    dumper, todo, partRef, objSelector, bindingSelector) {\n  var value = this.obj.proto;\n  if (todo >= Do.SET && this.doneProto_ < Do.SET) {\n    // Record prototype connection.\n    this.proto = value;\n    if (value !== null) {\n      dumper.getObjectDumper_(value)\n          .updateRef(dumper, new Components(this, Selector.PROTOTYPE));\n    }\n    dumper.write(\n        dumper.exprForCall_('Object.setPrototypeOf', [objSelector, value]),\n        ';');\n    this.doneProto_ = (value === null) ? Do.RECURSE: Do.DONE;\n  }\n  return this.doneProto_;\n};\n\n/**\n * Return the current 'done' status of an object binding.\n * @param {Selector.Part} part The part to get status for.\n * @return {!Do} The done status of the binding.\n */\nObjectDumper.prototype.getDone = function(part) {\n  if (part === Selector.PROTOTYPE) {\n    return this.doneProto_;\n  } else if (part === Selector.OWNER) {\n    return this.doneOwner_;\n  } else if (typeof part === 'string') {\n    var done = this.doneProp_[part];\n    return done === undefined ? Do.UNSTARTED : done;\n  } else {\n    throw new TypeError('Invalid part');\n  }\n};\n\n/**\n * Return a Selector for this object.  If preferred is true, the\n * preferred selector will be returned; this is the least-badness\n * Selecgtor in intrp2 for this.obj, but may not yet be a valid\n * selector at the current point in the dump.  Otherwise, the selector\n * returned will be the best known valid selector.  An Error will be\n * thrown if no valid selector exists.\n * @param {boolean=} preferred Return preferred selector?\n * @return {!Selector} A selector for this.obj.\n */\nObjectDumper.prototype.getSelector = function(preferred) {\n  var /** !SubDumper */ sd = this;\n  var /** !Array<Selector.Part> */ parts = [];\n  while (sd instanceof ObjectDumper) {\n    var /** ?Components */ next = preferred ? sd.preferredRef : sd.ref;\n    if (!next) throw new Error('unreferenced object while building Selector');\n    sd = next.dumper;\n    parts.unshift(next.part);\n  }\n  if (!(sd instanceof ScopeDumper)) {\n    throw new TypeError('unknown SubDumper subclass');\n  } else  if (sd.scope.type !== Interpreter.Scope.Type.GLOBAL) {\n    throw new Error('refusing to create Selector for non-global scope');\n  }\n  return new Selector(parts);\n};\n\n/**\n * Return the value of the given part of this.obj (i.e., the value\n * in intrp2, and the intended final value provided that it isn't\n * going to be pruned.)\n * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs.\n * @param {Selector.Part} part The binding part to get the value of.\n * @return {Interpreter.Value} The value of that part.\n */\nObjectDumper.prototype.getValue = function(dumper, part) {\n  if (typeof part === 'string') {\n    return this.obj.get(part, dumper.intrp2.ROOT);\n  } else if (part === Selector.PROTOTYPE) {\n    return this.obj.proto;\n  } else if (part === Selector.OWNER) {\n    return /** @type{?Interpreter.prototype.Object} */(this.obj.owner);\n  } else {\n    throw new Error('unknown part type');\n  }\n};\n\n/**\n * Return true iff the specifed property can be created or set by\n * assignment - i.e., that it exists and is writable, or doesn't exist\n * and does not inherit from a non-writable property on the prototype\n * chain.\n *\n * N.B. this not checking writability on intrp1 or intrp2, but on the\n * notional state of the interpreter at this point in the dump (i.e.,\n * somewhere in between the two), as recorded on the relevant\n * ObjectDumper .attibutes and .proto properties.\n *\n * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs.\n * @param {string} key The property key to check for writability of.\n * @return {boolean} True iff the property can be set by assignment.\n */\nObjectDumper.prototype.isWritable = function(dumper, key) {\n  // Invariant checks.\n  if (this.proto === undefined) {\n    throw new Error('Checking writability of property on non-created object');\n  } else if ((key in this.attributes) !== (this.getDone(key) >= Do.DECL)) {\n    throw new Error('Attribute / done mismatch');\n  }\n  if (key in this.attributes) {\n    return this.attributes[key].writable;\n  } else {\n    if (this.proto === null) {\n      return true;\n    } else {\n      return dumper.getObjectDumper_(this.proto).isWritable(dumper, key);\n    }\n  }\n};\n\n/**\n * Return true iff this.object is currently reachable.\n * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs.\n * @param {Selector.Part=} part The binding whose reachability is of\n *     interest.  Ignored, since all object bindings are always\n *     reachable if the object is.\n * @return {boolean}\n */\nObjectDumper.prototype.reachable = function(dumper, part) {\n  return Boolean(this.ref) && this.ref.dumper.reachable(dumper, this.ref.part);\n};\n\n/**\n * Record that the (ressurected) object will have a property, not on\n * the original, that needs to be deleted.\n * @param {string} key The property key to delete.\n */\nObjectDumper.prototype.scheduleDeletion = function(key) {\n  if (this.toDelete) {\n    this.toDelete.push(key);\n  } else {\n    this.toDelete = [key];\n  }\n};\n\n/**\n * Update the current 'done' status of a property.  Will throw a\n * RangeError if caller attempts to un-do or re-do a previously-done\n * action.\n * @param {Selector.Part} part The part to set status for.\n * @param {!Do} done The new done status of the binding.\n */\nObjectDumper.prototype.setDone = function(part, done) {\n  var old = this.getDone(part);\n\n  // Invariant checks.\n  if (done <= old) {\n    var fault = (done === old) ? 'Refusing redundant' : \"Can't undo previous\";\n    var description = this.getSelector(/*preferred=*/true);\n    throw new RangeError(fault + ' work on ' + part + ' of ' + description);\n  }\n  // Do set.\n  if (part === Selector.PROTOTYPE) {\n    this.doneProto_ = done;\n  } else if (part === Selector.OWNER) {\n    this.doneOwner_ = done;\n  } else if (typeof part === 'string') {\n    this.doneProp_[part] = done;\n  }\n};\n\n/**\n * Visit an Object to prepare for dumping.  In particular:\n *\n * - If this.object is a UserFunction, record it on it's .scope's\n *   ScopeDumper's list of inner functions, so that when we go to dump\n *   that scope later we know all the functions that need to be\n *   declared within it.\n *\n * - Collect and return an array of {part, value}, where each\n *   represents a property or internal slot of this.object.  If\n *   this.object is a UserFunction, the returned array will also\n *   contain a bare ScopeDumper object representing the\n *   function's enclosing scope.\n *\n * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs.\n * @return {!Array<OutwardEdge>}\n */\nObjectDumper.prototype.survey = function(dumper) {\n  var /** !Array<OutwardEdge> */ adjacent = [];\n\n  if (this.obj instanceof dumper.intrp2.UserFunction) {\n    // Record this this function as inner to scope, and survey scope.\n    var scopeDumper = dumper.getScopeDumper_(this.obj.scope);\n    scopeDumper.innerFunctions.add(this);\n    adjacent.push(scopeDumper);\n  }\n\n  adjacent.push({part: Selector.PROTOTYPE, value: this.obj.proto});\n  var ownerObj = /** @type {!Interpreter.prototype.Object} */(this.obj.owner);\n  adjacent.push({part: Selector.OWNER, value: ownerObj});\n  var keys = this.obj.ownKeys(dumper.intrp2.ROOT);\n  for (var i = 0; i < keys.length; i++) {\n    var key = keys[i];\n    var value = this.obj.get(key, dumper.intrp2.ROOT);\n    adjacent.push({part: key, value: value});\n  }\n\n  return adjacent;\n};\n\n/**\n * Record a new reference to the object, if it is 'better' than the\n * existing one.  'Better' means, in order of priority:\n *\n * - Ignore references from self entirely.\n * - Prefer any reference over no reference.\n * - Prefer references from reachable objects over ones from\n *   unreachable objects.\n * - If both existing (this.ref) and proposed (ref) .dumpers are reachable:\n *   - Prefer .preferredRef over others, otherwise\n *   - Prefer reference with lowest overall badness.\n * - If neither .dumper is reachable, prefer reference with lowest overall\n *   badness when using .dumpers's .preferredRef instead.\n *\n * @param {!Dumper} dumper The Dumper to which this ObjectDumber belongs.\n * @param {!Components} ref The new reference.\n * @return {void}\n */\nObjectDumper.prototype.updateRef = function(dumper, ref) {\n  if (ref.dumper === this) return;  // Ignore references from self entirely.\n  if (!this.ref) {  // Prefer any reference over no reference.\n    this.ref = ref;\n    return;\n  }\n  if (this.ref.isReachable(dumper)) {\n    if (ref.isReachable(dumper)) {  // Both existing and new refs reachable.\n      if (this.preferredRef) {  // Prefer .preferredRef over others.\n        if (this.preferredRef.equals(this.ref)) {\n          return;\n        } else if(this.preferredRef.equals(ref)) {\n          this.ref = ref;\n          return;\n        }\n      }\n      // Otherwise, prefer ref with lowest overall badness.\n      var oldBadness = this.getSelector().badness();\n      var newBadness = Selector.partBadness(ref.part);\n      if (ref.dumper instanceof ObjectDumper) {\n        newBadness += ref.dumper.getSelector().badness();\n      }\n      if (newBadness < oldBadness) this.ref = ref;\n    }\n  } else {\n    if (ref.isReachable(dumper)) {  // Existing ref unreachable but new ref is!\n      this.ref = ref;\n    } else {  // Neither existing nor new refs reachable.\n      var oldBadness =\n          Selector.partBadness(this.ref.part) + \n          (this.ref.dumper instanceof ObjectDumper ?\n           this.ref.dumper.getSelector(/*preferred=*/true).badness() :\n           0);\n      var newBadness =\n          Selector.partBadness(ref.part) + \n          (ref.dumper instanceof ObjectDumper ?\n           ref.dumper.getSelector(/*preferred=*/true).badness() :\n           0);\n      if (newBadness < oldBadness) this.ref = ref;\n    }\n  }\n};\n\n/**\n * Tri-state \"done\" flag for ObjectDumper.  A bit like Do, but for the\n * whole object rather than a single binding.\n * @enum {number}\n */\nObjectDumper.Done = {\n  /** Object not fully dumped. */\n  NO: 0,\n\n  /**\n   * Object is done (has all own properties fully defined including\n   * attributes, has correct [[Owner]] and [[Prototype]], is\n   * non-extensible if applicable, etc.).\n   */\n  DONE: 1,\n\n  /** This object and all objects accessible from it are done. */\n  DONE_RECURSIVELY: 2,\n};\n\n/**\n * A record of pending bindings returned by the .dump and .dumpBinding\n * methods when they encounter a circular dependency while trying to\n * recursively dump some objects.\n *\n * E.g., given objects a and b, if a.b === b, and b.a === a, then\n * either both a and b can be both be fully recursivley dumped or\n * neither is.  When attempting to dump a, the dumpProperty(<a.b>)\n * will try to dump b, which will ensure that b.a is done and return a\n * Pending object indicating that <b.a> being recursively done is\n * awaiting completion of a.\n *\n * @constructor\n * @struct\n * @param {!Selector} binding A binding awaiting recursive completion\n *     of its value object.\n * @param {!ObjectDumper} valueDumper The ObjectDumper for the object\n *     which is the value of binding.\n */\nObjectDumper.Pending = function(binding, valueDumper) {\n  if (!binding) throw new Error('no binding');\n  if (!valueDumper) throw new Error('no valueDumper');\n  /** !Array<!Selector> */\n  this.bindings = [binding];\n  /** !Array<!ObjectDumper> */\n  this.dependencies = [valueDumper];\n};\n\n/**\n * Add a new (binding, dependency) pair to this Pending object.\n * @param {!Selector} binding A binding awaiting recursive completion\n *     of its value object.\n * @param {!ObjectDumper} valueDumper The ObjectDumper for the object\n *     which is the value of binding.\n */\nObjectDumper.Pending.prototype.add = function(binding, valueDumper) {\n  if (!binding) throw new Error('no binding');\n  if (!valueDumper) throw new Error('no valueDumper');\n  this.bindings.push(binding);\n  this.dependencies.push(valueDumper);\n};\n\n/**\n * Merge another pending list into this one.\n * @param {!ObjectDumper.Pending} that Another Pending list.\n */\nObjectDumper.Pending.prototype.merge = function(that) {\n  this.bindings = this.bindings.concat(that.bindings);\n  this.dependencies = this.dependencies.concat(that.dependencies);\n};\n\n/** @override */\nObjectDumper.Pending.prototype.toString = function() {\n  return '{bindings: [' + this.bindings.join(', ') + '], ' +\n      'dependencies: [' + this.dependencies.map(function(od) {\n        return String(od.getSelector(/*preferred=*/true));\n      }).join(', ') + ']}';\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Helper Classes.\n\n/**\n * A {SubDumper, Selector.Part} tuple.\n *\n * N.B.: the usage of 'components' here is analagous to that term's\n * usage in interpreter.js but not identical: there is is a [scope,\n * variable] tuple; here it is a {ScopeDumper/ObjectDumper,\n * Selector.Part} tuple.\n *\n * @constructor\n * @struct\n * @param {!SubDumper} dumper\n * @param {Selector.Part} part\n */\nvar Components = function(dumper, part) {\n  /** @const {!SubDumper} */ this.dumper = dumper;\n  /** @const {Selector.Part} */ this.part = part;\n};\n\n/**\n * Return true iff this and that represent the same binding.\n * @param {!Components} that Another Components to compare this with.\n * @return {boolean}\n */\nComponents.prototype.equals = function(that) {\n  return this.dumper === that.dumper && this.part === that.part;\n};\n\n/**\n * Return true iff this reference is currently reachable.\n * @param {!Dumper} dumper Dumper to which this Components belongs.\n * @return {boolean}\n */\nComponents.prototype.isReachable = function(dumper) {\n  return this.dumper.reachable(dumper, this.part);\n};\n\n/**\n * Custom util.inspect implementation, to make debug/test output more\n * readable.\n * @param {number} depth\n * @param {util.inspect.Options} opts\n * @return {string}\n */\nComponents.prototype[util.inspect.custom] = function(depth, opts) {\n  var /** string */ dumper;\n  if (this.dumper instanceof ScopeDumper) {\n    dumper = util.format('<%s scope>', this.dumper.scope.type);\n  } else if (this.dumper instanceof ObjectDumper) {\n    try {\n      dumper = this.dumper.getSelector(/*preferred=*/true).toString();\n    } catch (e) {\n      dumper = '<unknown>';\n    }\n  }\n  return util.format('[%s.%s]', dumper, this.part);\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Type declarations: Do, etc.\n\n/**\n * Possible things to do (or have done) with a variable / property /\n * etc. binding.  N.B.: values meaning \"don't do this one (yet)\"\n * are negative, \"nothing done\" is zero (and therefore falsey), and\n * \"some work has been done\" are positive.\n *\n * Code should not depend on the numeric values of the enum options,\n * but it is permissiible to depend on the options being in numeric\n * order of ascending completion - i.e., Do.x implies Do.y if Do.x >=\n * Do.y.\n *\n * @enum {number}\n */\nvar Do = {\n  /**\n   * Nothing has been done about this binding yet.  Only valid as a\n   * 'done' value, not as a 'do' value.\n   */\n  UNSTARTED: 0,\n\n  /**\n   * Ensure that the specified binding exists, but do not yet set it\n   * to its final value.  If the binding is a variable, it has been /\n   * will be declared; if it is a property, it has been / will be\n   * created but not (yet) set to a value other than undefined (nor\n   * made non-configurable).\n   */\n  DECL: 1,\n\n  /**\n   * Ensure that the specified binding exists and has been set to its\n   * final value (if primitive) or an object of the correct class (if\n   * non-primitive).\n   *\n   * For property bindings, the property attributes will generally not\n   * (yet) be set, and if a new object was created to be the value of\n   * the specified binding it will generally not (yet) have its\n   * properties or internal set/map data set (but immutable internal\n   * data, such as function code, will have been set at creation).\n   */\n  SET: 2,\n\n  /**\n   * Ensure theat the specified binding has been set to its final\n   * value, and additionally that the final property attributes\n   * (enumerable, writable and/or configurable) are set.  DONE is\n   * provided as an alias for bindings (like variables,\n   * [[Prototype]] and [[Owner]] that don't have attributes; for\n   * those, SET should automatically be promoted to DONE.\n   */\n  ATTR: 3,\n  DONE: 3,\n\n  /**\n   * Ensure the specified path is has been set to its final value (and\n   * marked immuable, if applicable) and that the same has been done\n   * recursively to all bindings reachable via path.\n   */\n  RECURSE: 4,\n};\n\n/**\n * Options object for Dumper.\n * @record\n */\nvar DumperOptions = function() {};\n/**\n * The stream that this.write() will write to.  Setting it to null\n * (the default) will cause cause .write() to do nothing, causing\n * dumped code to be lost.\n * @type {?Writable|undefined}\n */\nDumperOptions.prototype.output;\n/**\n * Skip the named bindings.\n * @type {!Array<Selector.Part>|undefined}\n */\nDumperOptions.prototype.skipBindings;\n/**\n * If true, limit recursive dumping to the spaning tree defined by the\n * preferred selectors.\n *\n * E.g.: Noting that Object{proto}, Fucntion{proto} and\n * Function.prototype are the same object.  If treeOnly is true (the\n * default), then:\n *\n * * Dumping Object recursively would set Object{proto} but not visit\n *   Function.prototype at all, while\n * * Dumping Function recursively would set Function{proto} but\n *   recurse into Function.prototype.\n *\n * On the other hand, if treeOnly is false, then dumping Object\n * recursively would recurse into Object{proto} (i.e.,\n * Function.prototype by a different name), and dumping Function might\n * choose ot recurse via Function{proto} rather than\n * Function.prototype.\n *\n * @type {boolean|undefined}\n */\nDumperOptions.prototype.treeOnly;\n/**\n * Print status information and warnings to the console?\n * @type {boolean|undefined}\n */\nDumperOptions.prototype.verbose;\n\n/**\n * Default options for Dumper.\n * @const @type {!DumperOptions}\n */\nvar DEFAULT_OPTIONS = {\n  output: null,\n  skipBindings: [],\n  treeOnly: true,\n  verbose: false,\n};\n\n/**\n * A value representing an outward edge (from an unspecified object)\n * on the object graph.\n *\n * - Outward edges that are properties or internal slots are\n *   represented as a {Selector.Part, Interpreter.Value} tuple.\n * - Outward edges that are the enclosing scope of a UserFunction are\n *   represented by a bare ScopeDumper.\n * @typedef {{part: Selector.Part, value: Interpreter.Value}|!ScopeDumper}\n */\nvar OutwardEdge;\n\n/**\n * A writable stream.  Could be a stream.Writable, but we don't check\n * the return value of .write to see if it's safe to keep writing, so\n * caller might prefer to supply a synchronous implementation instead!\n * @interface\n */\nvar Writable = function() {};\n\n/**\n * Write a string to the writable stream.\n * @param {string} s\n */\nWritable.prototype.write = function(s) {};\n\n///////////////////////////////////////////////////////////////////////////////\n// Exports.\n\nexports.Do = Do;\nexports.Dumper = Dumper;\nexports.DumperOptions = DumperOptions;\nexports.Writable = Writable;\n\n// For unit testing only!\nexports.testOnly = {\n  Components: Components,\n  ObjectDumper: ObjectDumper,\n  ScopeDumper: ScopeDumper,\n};\n"
  },
  {
    "path": "server/externs/WeakRef.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Closure Compiler externs for the new ES2020 WeakRef and\n *     FinalizationRegistry API https://tc39.es/ecma262/#sec-managing-memory\n * @author cpcallen@google.com (Christopher Allen)\n * @externs\n */\n\n// Closure Compiler (as of google-closue-compiler@20210406.0.0) now\n// knows about WeakRef, but it doesn't yet know about FinalizationRegistry.\n\n/**\n * @constructor\n * @struct\n * @param {function(HELDVALUE)} cleanupCallback\n * @template TARGET, HELDVALUE, TOKEN\n * @nosideeffects\n */\n// TODO(cpcallen): Make TARGET and TOKEN bounded to {!Object} once\n// closure-compiler supports bounded generic types.\nvar FinalizationRegistry = function(cleanupCallback) {};\n\n/**\n * @param {TARGET} target\n * @param {HELDVALUE} heldValue\n * @param {TOKEN=} unregisterToken\n * @return {void}\n */\nFinalizationRegistry.prototype.register =\n    function(target, heldValue, unregisterToken) {};\n\n/**\n * @param {TOKEN} unregisterToken\n * @return {void}\n */\nFinalizationRegistry.prototype.unregister = function(unregisterToken) {};\n"
  },
  {
    "path": "server/externs/buffer/buffer.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's buffer module to\n *     satisfy Closure Compiler dependencies.  This is mostly an\n *     excerpt from contrib/nodejs/buffer.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// TODO(cpcallen): Use official externs directly.\n\n/** @constructor @struct */\nvar Buffer = function() {};\n\nexports.Buffer = Buffer;\n"
  },
  {
    "path": "server/externs/buffer/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('buffer')\",\n  \"main\": \"buffer.js\",\n  \"name\": \"buffer\",\n}\n"
  },
  {
    "path": "server/externs/crypto/crypto.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's crypto module to satisfy\n *     Closure Compiler dependencies.  This is mostly an excerpt from\n *     contrib/nodejs/fs.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// TODO(cpcallen): Use official externs directly.\n\nvar Buffer = require('buffer').Buffer;\nvar stream = require('stream');\n\n/** @const */\nvar crypto = {};\n\n/**\n * @param {string} algorithm\n * @return {crypto.Hash}\n */\ncrypto.createHash = function(algorithm) {};\n\n/**\n * @constructor\n * @struct\n * @extends stream.Transform\n * @param {string} algorithm\n * @param {Object=} options\n */\ncrypto.Hash = function(algorithm, options) {};\n\n/**\n * @param {string|Buffer} data\n * @param {string=} input_encoding\n * @return {crypto.Hash}\n */\ncrypto.Hash.prototype.update = function(data, input_encoding) {};\n\n/**\n * @param {string=} encoding\n * @return {string}\n */\ncrypto.Hash.prototype.digest = function(encoding) {};\n\n/**\n * @return {!Array<string>}\n */\ncrypto.getHashes = function() {};\n\nmodule.exports = crypto;\n"
  },
  {
    "path": "server/externs/crypto/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('crypto')\",\n  \"main\": \"crypto.js\",\n  \"name\": \"crypto\",\n}\n"
  },
  {
    "path": "server/externs/events/events.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's events module to\n *     satisfy Closure Compiler dependencies.\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n/** @const */\nvar events = {};\n\n/** @type {symbol} */\nevents.errorMonitor;\n\n/** @constructor @struct */\nevents.EventEmitter = function() {};\n\n/**\n * @param {string|symbol} event\n * @param {function(...)} listener\n * @return {events.EventEmitter}\n */\nevents.EventEmitter.prototype.on = function(event, listener) {};\n\n/**\n * @param {string|symbol} event\n * @param {function(...)} listener\n * @return {events.EventEmitter}\n */\nevents.EventEmitter.prototype.once = function(event, listener) {};\n\n/**\n * @param {string|symbol} event\n * @param {function(...)} listener\n * @return {events.EventEmitter}\n */\nevents.EventEmitter.prototype.removeListener = function(event, listener) {};\n\nmodule.exports = events;\n"
  },
  {
    "path": "server/externs/events/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('events')\",\n  \"main\": \"events.js\",\n  \"name\": \"events\",\n}\n"
  },
  {
    "path": "server/externs/fs/fs.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's fs module to satisfy\n *     Closure Compiler dependencies.  This is mostly an excerpt from\n *     contrib/nodejs/fs.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// TODO(cpcallen): Use official externs directly.\n\nvar Buffer = require('buffer').Buffer;\nvar stream = require('stream');\n\n/** @const */\nvar fs = {};\n\n/**\n * @param {string} path\n * @param {number=} mode\n */\nfs.accessSync = function(path, mode) {};\n\n/**\n * @param {number} fd\n * @return {void}\n */\nfs.closeSync = function(fd) {};\n\n/**\n * @param {string} path\n * @param {{flags: (string|undefined),\n *          encoding: (string|undefined),\n *          fd: (number|undefined),\n *          mode: (number|undefined),\n *          bufferSize: (number|undefined)}=} options\n * @return {fs.ReadStream}\n */\nfs.createReadStream = function(path, options) {};\n\n/**\n * @constructor\n * @struct\n * @extends stream.ReadableStream\n */\nfs.ReadStream = function () {};\n\n/**\n * @param {string} path\n * @param {{flags: (string|undefined),\n *          encoding: (string|undefined),\n *          mode: (number|undefined)}=} options\n * @return {fs.WriteStream}\n */\nfs.createWriteStream = function(path, options) {};\n\n/**\n * @constructor\n * @struct\n * @extends stream.WritableStream\n */\nfs.WriteStream = function () {};\n\n/**\n * @param {string} path\n * @return {boolean}\n */\nfs.existsSync = function(path) {};\n\n/**\n * @param {string} path\n * @param {string} flags\n * @param {number=} mode\n * @return {number}\n */\nfs.openSync = function(path, flags, mode) {};\n\n/**\n * @param {string} path\n * @return {Array<string>}\n */\nfs.readdirSync = function(path) {};\n\n/**\n * @param {string} filename\n * @param {string=} encoding\n * @return {string|Buffer}\n */\nfs.readFileSync = function(filename, encoding) {};\n\n/**\n * @param {string} oldPath\n * @param {string} newPath\n * @return {void}\n */\nfs.renameSync = function(oldPath, newPath) {};\n\n/**\n * @param {string} path\n * @return {fs.Stats}\n */\nfs.statSync = function(path) {};\n\n/**\n * @param {string} path\n * @return {void}\n */\nfs.unlinkSync = function(path) {};\n\n/**\n * @param {string} filename\n * @param {*} data\n * @param {string=} encoding\n * @return {void}\n */\nfs.writeFileSync = function(filename, data, encoding) {};\n\n/**\n * @param {number} fd\n * @param {string} string\n * @param {number=} position\n * @param {string=} encoding\n * @return {number}\n */\nfs.writeSync = function(fd, string, position, encoding) {};\n                        \n/** @constructor @struct */\nfs.Stats = function () {};\n\n/** @return {boolean} */\nfs.Stats.prototype.isFile;\n\n/** @return {boolean} */\nfs.Stats.prototype.isDirectory;\n\n/** @return {boolean} */\nfs.Stats.prototype.isBlockDevice;\n\n/** @return {boolean} */\nfs.Stats.prototype.isCharacterDevice;\n\n/** @return {boolean} */\nfs.Stats.prototype.isSymbolicLink;\n\n/** @return {boolean} */\nfs.Stats.prototype.isFIFO;\n\n/** @return {boolean} */\nfs.Stats.prototype.isSocket;\n\n/** @type {number} */\nfs.Stats.prototype.dev = 0;\n\n/** @type {number} */\nfs.Stats.prototype.ino = 0;\n\n/** @type {number} */\nfs.Stats.prototype.mode = 0;\n\n/** @type {number} */\nfs.Stats.prototype.nlink = 0;\n\n/** @type {number} */\nfs.Stats.prototype.uid = 0;\n\n/** @type {number} */\nfs.Stats.prototype.gid = 0;\n\n/** @type {number} */\nfs.Stats.prototype.rdev = 0;\n\n/** @type {number} */\nfs.Stats.prototype.size = 0;\n\n/** @type {number} */\nfs.Stats.prototype.blkSize = 0;\n\n/** @type {number} */\nfs.Stats.prototype.blocks = 0;\n\n/** @type {Date} */\nfs.Stats.prototype.atime;\n\n/** @type {Date} */\nfs.Stats.prototype.mtime;\n\n/** @type {Date} */\nfs.Stats.prototype.ctime;\n\nmodule.exports = fs;\n"
  },
  {
    "path": "server/externs/fs/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('fs')\",\n  \"main\": \"fs.js\",\n  \"name\": \"fs\",\n}\n"
  },
  {
    "path": "server/externs/http/http.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's http module to\n *     satisfy Closure Compiler dependencies.  This is mostly an\n *     adaptation of contrib/nodejs/http.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// TODO(cpcallen): Use official externs directly.\n\nvar Buffer = require('buffer').Buffer;\nvar events = require('events');\nvar net = require('net');\nvar stream = require('stream');\n\n/** @const */\nvar http = {};\n\n/**\n * @typedef {function(http.IncomingMessage, http.ServerResponse)}\n */\nhttp.requestListener;\n\n/**\n * @param {http.requestListener=} listener\n * @return {http.Server}\n */\nhttp.createServer;\n\n/**\n * @constructor\n * @struct\n * @extends events.EventEmitter\n * @param {http.requestListener=} listener\n */\nhttp.Server = function(listener) {};\n\n/**\n * @param {(number|string)} portOrPath\n * @param {(string|Function)=} hostnameOrCallback\n * @param {Function=} callback\n */\nhttp.Server.prototype.listen;\n\n/**\n * @return {void}\n */\nhttp.Server.prototype.close;\n\n/**\n * @constructor\n * @struct\n * @extends stream.Readable\n */\nhttp.IncomingMessage = function() {};\n\n/**\n * @type {?string}\n * */\nhttp.IncomingMessage.prototype.method;\n\n/**\n * @type {?string}\n */\nhttp.IncomingMessage.prototype.url;\n\n/**\n * @type {Object}\n * */\nhttp.IncomingMessage.prototype.headers;\n\n/**\n * @type {Object}\n * */\nhttp.IncomingMessage.prototype.trailers;\n\n/**\n * @type {string}\n */\nhttp.IncomingMessage.prototype.httpVersion;\n\n/**\n * @type {string}\n */\nhttp.IncomingMessage.prototype.httpVersionMajor;\n\n/**\n * @type {string}\n */\nhttp.IncomingMessage.prototype.httpVersionMinor;\n\n/**\n * @type {*}\n */\nhttp.IncomingMessage.prototype.connection;\n\n/**\n * @type {?number}\n */\nhttp.IncomingMessage.prototype.statusCode;\n\n/**\n * @type {net.Socket}\n */\nhttp.IncomingMessage.prototype.socket;\n\n/**\n * @param {number} msecs\n * @param {function()} callback\n * @return {void}\n */\nhttp.IncomingMessage.prototype.setTimeout;\n\n/**\n * @constructor\n * @struct\n * @extends events.EventEmitter\n * @private\n */\nhttp.ServerResponse = function() {};\n\n/**\n * @return {void}\n */\nhttp.ServerResponse.prototype.writeContinue;\n\n/**\n * @param {number} statusCode\n * @param {*=} reasonPhrase\n * @param {*=} headers\n */\nhttp.ServerResponse.prototype.writeHead;\n\n/**\n * @type {number}\n */\nhttp.ServerResponse.prototype.statusCode;\n\n/**\n * @param {string} name\n * @param {string} value\n * @return {void}\n */\nhttp.ServerResponse.prototype.setHeader;\n\n/**\n * @param {string} name\n * @return {string|undefined} value\n */\nhttp.ServerResponse.prototype.getHeader;\n\n/**\n * @param {string} name\n * @return {void}\n */\nhttp.ServerResponse.prototype.removeHeader;\n\n/**\n * @param {string|Array|Buffer} chunk\n * @param {string=} encoding\n * @return {void}\n */\nhttp.ServerResponse.prototype.write;\n\n/**\n * @param {Object} headers\n * @return {void}\n */\nhttp.ServerResponse.prototype.addTrailers;\n\n/**\n * @param {(string|Array|Buffer)=} data\n * @param {string=} encoding\n * @return {void}\n */\nhttp.ServerResponse.prototype.end;\n\n/**\n * @constructor\n * @struct\n * @extends events.EventEmitter\n * @private\n */\nhttp.ClientRequest = function() {};\n\n/**\n * @param {string|Array|Buffer} chunk\n * @param {string=} encoding\n * @return {void}\n */\nhttp.ClientRequest.prototype.write;\n\n/**\n * @param {(string|Array|Buffer)=} data\n * @param {string=} encoding\n * @return {void}\n */\nhttp.ClientRequest.prototype.end;\n\n/**\n * @return {void}\n */\nhttp.ClientRequest.prototype.abort;\n\n/**\n * @param {string|!Object} urlOrOptions\n * @param {!Object|function(!http.IncomingMessage)=} optionsOrCallback\n * @param {function(!http.IncomingMessage)=} callback\n * @return {http.ClientRequest}\n */\nhttp.request = function(urlOrOptions, optionsOrCallback, callback) {};\n\n/**\n * @param {string|!Object} urlOrOptions\n * @param {!Object|function(!http.IncomingMessage)=} optionsOrCallback\n * @param {function(!http.IncomingMessage)=} callback\n * @return {http.ClientRequest}\n */\nhttp.get = function(urlOrOptions, optionsOrCallback, callback) {};\n\n/**\n * @constructor\n * @struct\n * @extends events.EventEmitter\n */\nhttp.Agent = function() {};\n\n/**\n * @type {number}\n */\nhttp.Agent.prototype.maxSockets;\n\n/**\n * @type {number}\n */\nhttp.Agent.prototype.sockets;\n\n/**\n * @type {Array.<http.ClientRequest>}\n */\nhttp.Agent.prototype.requests;\n\n/**\n * @type {http.Agent}\n */\nhttp.globalAgent;\n\nmodule.exports = http;\n"
  },
  {
    "path": "server/externs/http/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('http')\",\n  \"main\": \"http.js\",\n  \"name\": \"http\",\n}\n"
  },
  {
    "path": "server/externs/https/https.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's https module to\n *     satisfy Closure Compiler dependencies.  This is mostly an\n *     adaptation of contrib/nodejs/https.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// TODO(cpcallen): Use official externs directly.\n\nvar Buffer = require('buffer').Buffer;\nvar http = require('http');\nvar tls = require('tls');\n\n/** @const */\nvar https = {};\n\n/**\n * @constructor\n * @struct\n * @extends tls.Server\n */\nhttps.Server = function() {};\n\n/**\n * @param {...*} var_args\n * @return {void}\n */\nhttps.Server.prototype.listen;\n\n/**\n * @param {function()=} callback\n * @return {void}\n */\nhttps.Server.prototype.close;\n\n/**\n * @param {tls.CreateOptions} options\n * @param {function(http.IncomingMessage, http.ServerResponse)=} requestListener\n * @return {!https.Server}\n */\nhttps.createServer;\n\n/**\n * @typedef {{host: ?string, hostname: ?string, port: ?number, method: ?string, path: ?string, headers: ?Object.<string,string>, auth: ?string, agent: ?(https.Agent|boolean), pfx: ?(string|Buffer), key: ?(string|Buffer), passphrase: ?string, cert: ?(string|Buffer), ca: ?Array.<string>, ciphers: ?string, rejectUnauthorized: ?boolean}}\n */\nhttps.ConnectOptions;\n\n/**\n * @param {string|!Object} urlOrOptions\n * @param {!Object|function(!http.IncomingMessage)=} optionsOrCallback\n * @param {function(!http.IncomingMessage)=} callback\n * @return {http.ClientRequest}\n */\nhttps.request = function(urlOrOptions, optionsOrCallback, callback) {};\n\n/**\n * @param {string|!Object} urlOrOptions\n * @param {!Object|function(!http.IncomingMessage)=} optionsOrCallback\n * @param {function(!http.IncomingMessage)=} callback\n * @return {http.ClientRequest}\n */\nhttps.get = function(urlOrOptions, optionsOrCallback, callback) {};\n\n/**\n * @constructor\n * @struct\n * @extends http.Agent\n */\nhttps.Agent = function() {};\n\n/**\n * @type {https.Agent}\n */\nhttps.globalAgent;\n\nmodule.exports = https;\n"
  },
  {
    "path": "server/externs/https/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('https')\",\n  \"main\": \"https.js\",\n  \"name\": \"https\",\n}\n"
  },
  {
    "path": "server/externs/net/net.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's net module to\n *     satisfy Closure Compiler dependencies.\n * @author cpcallen@google.com (Christopher Allen)\n */\n\nvar Buffer = require('buffer').Buffer;\nvar events = require('events');\n\nvar net = {};\n\n/**\n * @typedef {{allowHalfOpen: ?boolean}}\n */\nvar createOptions;\n\n/**\n * @param {(createOptions|function(...))=} options\n * @param {function(...)=} connectionListener\n * @return {net.Server}\n */\nnet.createServer = function(options, connectionListener) {};\n\n/**\n * @typedef {{port: (number|undefined),\n *            host: (string|undefined),\n *            localAddress: (string|undefined),\n *            path: (string|undefined),\n *            allowHalfOpen: (boolean|undefined)}}\n */\nvar connectOptions;\n\n/**\n * @param {connectOptions|number|string} arg1\n * @param {(function(...)|string)=} arg2\n * @param {function(...)=} arg3\n * @return {!net.Socket}\n */\nnet.createConnection = function(arg1, arg2, arg3) {};\n\n///////////////////////////////////////////////////////////////////////////////\n// net.Server\n\n/**\n * @constructor\n * @struct\n * @param {createOptions=} options\n * @extends {events.EventEmitter}\n */\nnet.Server = function(options) {};\n\n/**\n * @return {{port: number, family: string, address: string}}\n */\nnet.Server.prototype.address = function() {};\n\n/**\n * @param {function(...)=} callback\n * @return {void}\n */\nnet.Server.prototype.close = function(callback) {};\n\n/**\n *\n * @param {number|*} port\n * @param {(string|number|function(...))=} host\n * @param {(number|function(...))=} backlog\n * @param {function(...)=} callback\n * @return {void}\n */\nnet.Server.prototype.listen = function(port, host, backlog, callback) {};\n\n///////////////////////////////////////////////////////////////////////////////\n// net.Socket\n\n/**\n * @constructor\n * @struct\n * @param {{fd: ?*, type: ?string, allowHalfOpen: ?boolean}=} options\n * @extends events.EventEmitter\n */\nnet.Socket = function(options) {};\n\n/**\n * @param {string|Buffer} data\n * @param {(string|function(...))=} encoding\n * @param {function(...)=} callback\n * @return {void}\n */\nnet.Socket.prototype.write = function(data, encoding, callback) {};\n\n/**\n * @param {(string|Buffer)=} data\n * @param {(string|function(...))=} encoding\n * @param {function(...)=} callback\n * @return {void}\n */\nnet.Socket.prototype.end = function(data, encoding, callback) {};\n\nmodule.exports = net;\n"
  },
  {
    "path": "server/externs/net/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('net')\",\n  \"main\": \"net.js\",\n  \"name\": \"net\",\n}\n"
  },
  {
    "path": "server/externs/node.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Closure Compiler externs for node.js, mostly\n *     excerpted from contrib/nodejs/globals.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n * @externs\n */\n\n// TODO(cpcallen): Use official externs directly.\n\n/** @const {string} */\nvar __filename;\n\n/** @const {string} */\nvar __dirname;\n\n/** @type {!Object} */\nvar exports;\n\n/** @param {boolean=} full */\nvar gc = function(full) {};\n\n/** @type {!Object} */\nvar module;\n\n/**\n * @param {string} name\n * @return {?}\n */\nfunction require(name) {}\n\n/** @type {!Object} */\nrequire.main;\n\n/**\n * @param {string} request\n * @param {!Object=} options\n * @return {string}\n */\nrequire.resolve = function(request, options) {};\n\n///////////////////////////////////////////////////////////////////////////////\n// process\n\n/** @const */\nvar process = {};\n\n/** @type {string} */\nprocess.arch;\n\n/** @type {!Array<string>} */\nprocess.argv;\n\n/** @return {string} */\nprocess.cwd = function () {};\n\n/** @type {!Object<string, string>} */\nprocess.env;\n\n/** @param {number=} code */\nprocess.exit = function (code) {};\n\n/**\n * @param {!Array<number>=} time\n * @return {!Array<number>}\n */\nprocess.hrtime = function(time) {};\n\n/**\n * @param {number} pid\n * @param {string|number} signal\n */\nprocess.kill = function (pid, signal) {};\n\n/**\n * This is actually inherited from EventEmitter\n *     (===require('events')), but redefined here since\n *     closure-compiler won't let us require() that definition in an\n *     externs file.\n * @param {string|symbol} event\n * @param {function(...)} listener\n */\nprocess.on = function(event, listener) {};\n\n/**\n * Also inherited from EventEmitter.\n * @param {string|symbol} event\n * @param {function(...)} listener\n */\nprocess.once = function(event, listener) {};\n\n/** @type {number} */\nprocess.pid;\n\n/** @type {string} */\nprocess.platform;\n\n/** @type {string} */\nprocess.version;\n\n/** @type {!Object<string>} */\nprocess.versions;\n"
  },
  {
    "path": "server/externs/path/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('path')\",\n  \"main\": \"path.js\",\n  \"name\": \"path\",\n}\n"
  },
  {
    "path": "server/externs/path/path.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's fs module to satisfy\n *     Closure Compiler dependencies.  This is mostly an excerpt from\n *     contrib/nodejs/fs.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// TODO(cpcallen): Use official externs directly.\n\n/** @const */\nvar path = {};\n\n/**\n * @param {string} path\n * @return {string}\n */\npath.dirname = function(path) {};\n\n/**\n * @param {string} path\n * @return {string}\n */\npath.extname = function(path) {};\n\n/**\n * @param {string} p\n * @return {boolean}\n */\npath.isAbsolute = function(p) {};\n\n/**\n * @param {...string} var_args\n * @return {string}\n */\npath.join = function(var_args) {};\n\n/**\n * @param {string} p\n * @return {string}\n */\npath.normalize = function(p) {};\n\n\nmodule.exports = path;\n"
  },
  {
    "path": "server/externs/stream/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('stream')\",\n  \"main\": \"stream.js\",\n  \"name\": \"stream\",\n}\n"
  },
  {
    "path": "server/externs/stream/stream.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's stream module to\n *     satisfy Closure Compiler dependencies.  This is mostly an\n *     adaptation of contrib/nodejs/stream.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// TODO(cpcallen): Use official externs directly.\n\nvar events = require('events');\nvar Buffer = require('buffer').Buffer;\n\n/** @const */\nvar stream = {};\n\n/**\n * @constructor\n * @struct\n * @extends events.EventEmitter\n * @param {Object=} options\n */\nstream.Stream = function(options) {};\n\n/**\n * @param {stream.Writable} dest\n * @param {{end: boolean}=} pipeOpts\n * @return {stream.Writable}\n */\nstream.Stream.prototype.pipe;\n\n/**\n * @constructor\n * @struct\n * @extends stream.Stream\n * @param {Object=} options\n */\nstream.Readable = function(options) {};\n\n/**\n * @type {boolean}\n * @deprecated\n */\nstream.Readable.prototype.readable;\n\n/**\n * @protected\n * @param {string|Buffer|null} chunk\n * @return {boolean}\n */\nstream.Readable.prototype.push;\n\n/**\n * @param {string|Buffer|null} chunk\n * @return {boolean}\n */\nstream.Readable.prototype.unshift;\n\n/**\n * @param {string} enc\n * @return {void}\n */\nstream.Readable.prototype.setEncoding;\n\n/**\n * @param {number=} n\n * @return {Buffer|string|null}\n */\nstream.Readable.prototype.read;\n\n/**\n * @protected\n * @param {number} n\n * @return {void}\n */\nstream.Readable.prototype._read;\n\n/**\n * @param {stream.Writable=} dest\n * @return {stream.Readable}\n */\nstream.Readable.prototype.unpipe;\n\n/**\n * @return {void}\n */\nstream.Readable.prototype.resume;\n\n/**\n * @return {void}\n */\nstream.Readable.prototype.pause;\n\n/**\n * @param {stream.Stream} stream\n * @return {stream.Readable}\n */\nstream.Readable.prototype.wrap;\n\n/**\n * @constructor\n * @struct\n * @extends stream.Readable\n */\nstream.ReadableStream = function() {};\n\n/**\n * @type {boolean}\n */\nstream.ReadableStream.prototype.readable;\n\n/**\n * @param {string=} encoding\n * @return {void}\n */\nstream.ReadableStream.prototype.setEncoding;\n\n/**\n * @return {void}\n */\nstream.ReadableStream.prototype.destroy;\n\n/**\n * @constructor\n * @struct\n * @extends stream.Stream\n * @param {Object=} options\n */\nstream.Writable = function(options) {};\n\n/**\n * @deprecated\n * @type {boolean}\n */\nstream.Writable.prototype.writable;\n\n/**\n * @param {string|Buffer} chunk\n * @param {string=} encoding\n * @param {function(*=)=} cb\n * @return {boolean}\n */\nstream.Writable.prototype.write;\n\n/**\n * @protected\n * @param {string|Buffer} chunk\n * @param {string} encoding\n * @param {function(*=)} cb\n * @return {void}\n */\nstream.Writable.prototype._write;\n\n/**\n * @param {string|Buffer=} chunk\n * @param {string=} encoding\n * @param {function(*=)=} cb\n * @return {void}\n */\nstream.Writable.prototype.end;\n\n/**\n * @constructor\n * @struct\n * @extends stream.Writable\n */\nstream.WritableStream = function() {};\n\n/**\n * @return {void}\n */\nstream.WritableStream.prototype.drain;\n\n/**\n * @type {boolean}\n */\nstream.WritableStream.prototype.writable;\n\n/**\n * @param {string|Buffer} buffer\n * @param {string=} encoding\n * @return {void}\n */\nstream.WritableStream.prototype.write;\n\n/**\n * @param {string|Buffer=} buffer\n * @param {string=} encoding\n * @param {function(*=)=} cb\n * @return {void}\n */\nstream.WritableStream.prototype.end;\n\n/**\n * @return {void}\n */\nstream.WritableStream.prototype.destroy;\n\n/**\n * @return {void}\n */\nstream.WritableStream.prototype.destroySoon;\n\n/**\n * @constructor\n * @struct\n * @extends stream.Readable\n */\nstream.Duplex = function(options) {};\n\n/**\n * @type {boolean}\n */\nstream.Duplex.prototype.allowHalfOpen;\n\n\n/**\n * @constructor\n * @struct\n * @extends stream.Duplex\n * @param {Object=} options\n */\nstream.Transform = function(options) {};\n\n/**\n * @protected\n * @param {string|Buffer} chunk\n * @param {string} encoding\n * @param {function(*=)} cb\n * @return {void}\n */\nstream.Transform._transform;\n\n/**\n * @protected\n * @param {function(*=)} cb\n * @return {void}\n */\nstream.Transform._flush;\n\n/**\n * @constructor\n * @struct\n * @extends stream.Transform\n * @param {Object=} options\n */\nstream.PassThrough = function(options) {};\n\nmodule.exports = stream;\n"
  },
  {
    "path": "server/externs/tls/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('tls')\",\n  \"main\": \"tls.js\",\n  \"name\": \"tls\",\n}\n"
  },
  {
    "path": "server/externs/tls/tls.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's tls module to\n *     satisfy Closure Compiler dependencies.  This is mostly an\n *     excerpt of contrib/nodejs/tls.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// TODO(cpcallen): Use official externs directly.\n\nvar Buffer = require('buffer').Buffer;\nvar events = require('events');\nvar net = require('net');\nvar stream = require('stream');\n\n/**\n * @const\n */\nvar tls = {};\n\n/**\n * @constructor\n * @struct\n * @extends stream.Stream\n */\ntls.CreateOptions = function () {};\n\n/** @type {boolean} */\ntls.CreateOptions.prototype.honorCipherOrder;\n\n/** @type {boolean} */\ntls.CreateOptions.prototype.requestCert;\n\n/** @type {boolean} */\ntls.CreateOptions.prototype.rejectUnauthorized;\n\n/** @type {Array|Buffer} */\ntls.CreateOptions.prototype.NPNProtocols;\n\n/** @type {function(string)} */\ntls.CreateOptions.prototype.SNICallback;\n\n/** @type {string} */\ntls.CreateOptions.prototype.sessionIdContext;\n\n/**\n *\n * @param {tls.CreateOptions} options\n * @param {function(...)=} secureConnectionListener\n * @return {tls.Server}\n */\ntls.createServer;\n\n/**\n * @typedef {{host: string, port: number, socket: *, pfx: (string|Buffer), key: (string|Buffer), passphrase: string, cert: (string|Buffer), ca: Array.<string>, rejectUnauthorized: boolean, NPNProtocols: Array.<string|Buffer>, servername: string}}\n */\ntls.ConnectOptions;\n\n/**\n *\n * @param {number|tls.ConnectOptions} port\n * @param {(string|tls.ConnectOptions|function(...))=} host\n * @param {(tls.ConnectOptions|function(...))=} options\n * @param {function(...)=} callback\n * @return {void}\n */\ntls.connect = function(port, host, options, callback) {};\n\n// Don't need this yet, and don't have externs for crypto yet.\n// /**\n//  * @param {crypto.Credentials=} credentials\n//  * @param {boolean=} isServer\n//  * @param {boolean=} requestCert\n//  * @param {boolean=} rejectUnauthorized\n//  * @return {tls.SecurePair}\n//  */\n// tls.createSecurePair;\n\n/**\n * @constructor\n * @struct\n * @extends events.EventEmitter\n */\ntls.SecurePair = function() {};\n\n/**\n * @constructor\n * @struct\n * @extends net.Server\n */\ntls.Server = function() {};\n\n/**\n * @param {string} hostname\n * @param {string|Buffer} credentials\n * @return {void}\n */\ntls.Server.prototype.addContext = function(hostname, credentials) {};\n\n/**\n * @constructor\n * @struct\n * @extends stream.Duplex\n */\ntls.CleartextStream = function() {};\n\n/**\n * @type {boolean}\n */\ntls.CleartextStream.prototype.authorized;\n\n/**\n * @type {?string}\n */\ntls.CleartextStream.prototype.authorizationError;\n\n/**\n * @return {Object.<string,(string|Object.<string,string>)>}\n */\ntls.CleartextStream.prototype.getPeerCertificate;\n\n/**\n * @return {{name: string, version: string}}\n */\ntls.CleartextStream.prototype.getCipher;\n\n/**\n * @return {{port: number, family: string, address: string}}\n */\ntls.CleartextStream.prototype.address;\n\n/**\n * @type {string}\n */\ntls.CleartextStream.prototype.remoteAddress;\n\n/**\n * @type {number}\n */\ntls.CleartextStream.prototype.remotePort;\n\nmodule.exports = tls;\n"
  },
  {
    "path": "server/externs/util/package.json",
    "content": "{\n  \"description\": \"Fake package.json for require('util')\",\n  \"main\": \"util.js\",\n  \"name\": \"util\",\n}\n"
  },
  {
    "path": "server/externs/util/util.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Fake implementation of node.js's fs module to satisfy\n *     Closure Compiler dependencies.  This is mostly an excerpt from\n *     contrib/nodejs/fs.js from\n *     https://github.com/google/closure-compiler.git\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// TODO(cpcallen): Use official externs directly.\n\n/** @const */\nvar util = {};\n\n/**\n * @param {*} object\n * @param {?util.inspect.Options=} options\n * @return {string}\n */\nutil.inspect = function(object, options) {};\n\n/**\n * @const {symbol}\n */\nutil.inspect.custom;\n\n/**\n * @typedef {{showHidden: (boolean|undefined),\n *            depth: (number|null|undefined),\n *            colors: (boolean|undefined),\n *            customInspect: (boolean|undefined),\n *            showProxy: (boolean|undefined),\n *            maxArrayLength: (number|undefined),\n *            maxStringLength: (number|undefined),\n *            breakLength: (number|undefined),\n *            compact: (boolean|number|undefined),\n *            sorted: (boolean|!Function|undefined)}}\n */\nutil.inspect.Options;\n\n/**\n * @param {string} format\n * @param {...*} var_args\n * @return {string}\n */\nutil.format = function(format, var_args) {};\n\nmodule.exports = util;\n"
  },
  {
    "path": "server/interpreter.js",
    "content": "/**\n * @license\n * Copyright 2013 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Interpreting JavaScript in JavaScript.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nvar events = require('events');\nvar IterableWeakMap = require('./iterable_weakmap');\nvar net = require('net');\nvar http = require('http');\nvar https = require('https');\nvar parser = require('./parser');\nvar Registry = require('./registry');\n\nvar Node = parser.Node;\nvar Parser = parser.Parser;\n\n/**\n * Version number for the serialisation format.  MUST be incremented\n * when any change is made to the implementation of Interpreter and\n * related classes (in this file and others) which would change how\n * the runtime state is represented on disk.\n * @type {number}\n */\nvar SERIALIZATION_VERSION = 1;\n\n/**\n * Create a new interpreter.\n * @constructor\n * @struct\n * @param {!Interpreter.Options=} options\n */\nvar Interpreter = function(options) {\n  /** @type {!Interpreter.Options} */\n  this.options = options || {};\n  /**\n   * Serialisation version for this Interpreter instance.  Will be set\n   * to SERIALIZATION_VERSION, but not here, because there exist .city\n   * files that have no .serlizationVersion in them, and loading one\n   * won't overwrite what we set here.  Instead, set it in\n   * .preSerialize, and check in in .postDeserialize.\n   * @type {number|undefined}\n   */\n  this.serializationVersion = undefined;\n  // Install .Object, .Function, etc.\n  this.installTypes();\n  /**\n   * Registry of builtins - e.g. Object, Function.prototype, Array.pop, etc.\n   * @const {!Registry<?Interpreter.Value>}\n   */\n  this.builtins = new Registry;\n  /**\n   * For cycle detection in Array.prototype.toString; see spec bug\n   * github.com/tc39/ecma262/issues/289.  (Also used in\n   * Error.prototype.toString, which has same issue.)  Since these\n   * functions are atomic (i.e., take place entirely within the\n   * duration of a single call to .step) and do not call user code\n   * which could suspend, it's fine that it's not per-Thread.\n   * @private @const {!Set<!Interpreter.prototype.Object>}\n   */\n  this.toStringVisited_ = new Set;\n\n  /**\n   * The interpreter's global scope.\n   * @const {!Interpreter.Scope}\n   */\n  this.global = new Interpreter.Scope(Interpreter.Scope.Type.GLOBAL,\n      /** @type {?} */ (undefined), null, undefined);\n\n  // Declare properties that wil be initialised by initBuiltins_.\n  /** @type {!Interpreter.prototype.Object} */ this.OBJECT;\n  /** @type {!Interpreter.Owner} */ this.ROOT;\n  /** @type {!Interpreter.prototype.Function} */ this.FUNCTION;\n  /** @type {!Interpreter.prototype.Array} */ this.ARRAY;\n  /** @type {!Interpreter.prototype.Object} */ this.STRING;\n  /** @type {!Interpreter.prototype.Object} */ this.BOOLEAN;\n  /** @type {!Interpreter.prototype.Object} */ this.NUMBER;\n  /** @type {!Interpreter.prototype.Object} */ this.DATE;\n  /** @type {!Interpreter.prototype.Object} */ this.REGEXP;\n  /** @type {!Interpreter.prototype.Error} */ this.ERROR;\n  /** @type {!Interpreter.prototype.Error} */ this.EVAL_ERROR;\n  /** @type {!Interpreter.prototype.Error} */ this.RANGE_ERROR;\n  /** @type {!Interpreter.prototype.Error} */ this.REFERENCE_ERROR;\n  /** @type {!Interpreter.prototype.Error} */ this.SYNTAX_ERROR;\n  /** @type {!Interpreter.prototype.Error} */ this.TYPE_ERROR;\n  /** @type {!Interpreter.prototype.Error} */ this.URI_ERROR;\n  /** @type {!Interpreter.prototype.Error} */ this.PERM_ERROR;\n  /** @type {!Interpreter.prototype.Object} */ this.WEAKMAP;\n  /** @type {!Interpreter.prototype.Object} */ this.THREAD;\n  /** @type {!Interpreter.Owner} */ this.ANYBODY;\n\n  // Create builtins and (minimally) initialize global scope:\n  this.initBuiltins_();\n\n  /** @private @const {!Array<!Interpreter.Thread>} */\n  this.threads_ = [];\n  /** @private @type {?Interpreter.Thread} */\n  this.thread_ = null;\n  /** @private @type {number|undefined} */\n  this.threadTimeLimit_ = undefined;\n  /** @private (Type is whatever is returned by setTimeout()) */\n  this.runner_ = null;\n  /** @type {boolean} */\n  this.done = true;  // True if no non-ZOMBIE threads exist.\n\n  // TODO(cpcallen): rename this to .listeners\n  /** @const {!Object<number, !Interpreter.prototype.Server>} */\n  this.listeners_ = Object.create(null);\n\n  // TODO(cpcallen): This is an ugly hack to allow the serialiser to\n  // know the names of step functions in an otherwise-empty\n  // interpreter.  Find a better way to do this.\n  /** @const {!Object<string, !Interpreter.StepFunction>} */\n  this.stepFuncs = stepFuncs_;\n\n  // Bring interpreter up to PAUSED status, setting up timers etc.\n  /** @type {!Interpreter.Status} */\n  this.status = Interpreter.Status.STOPPED;\n  /** @private @type {number} */\n  this.previousTime_ = 0;\n  /** @private @type {number} */\n  this.cumulativeTime_ = 0;\n  /** @private @type {!Array<number>} */\n  this.hrStartTime_;  // Initialised by pause.\n\n  this.pause();\n};\n\n/**\n * Return a monotonically increasing count of milliseconds since this\n * Interpreter was last brought to PAUSED or RUNNING status from\n * STOPPED.  This excludes time when Node was suspended by the host OS\n * (say, because the machine was asleep).\n * @return {number} Elapsed time in milliseconds.\n */\nInterpreter.prototype.uptime = function() {\n  var t = process.hrtime(this.hrStartTime_);\n  return t[0] * 1000 + t[1] / 1000000;\n};\n\n/**\n * Return a monotonically increasing count of milliseconds since this\n * Interpreter instance was created.  In the event of an interpreter\n * being serialized / deserialized, this count will continue from\n * where it left off before serialization.\n * @return {number} Elapsed total time in milliseconds.\n */\nInterpreter.prototype.now = function() {\n  return this.uptime() + this.previousTime_;\n};\n\n/**\n * Create a new thread and add it to .threads_, and create a companion\n * user-visible wrapper object and return it.\n * @param {!Interpreter.Owner} owner Owner of new thread.\n * @param {!Interpreter.State} state Initial state\n * @param {number=} runAt Time at which thread should begin execution\n *     (default: now).\n * @param {number=} timeLimit Maximum runtime without suspending (in ms).\n * @return {!Interpreter.prototype.Thread} Userland Thread object.\n */\nInterpreter.prototype.createThread = function(owner, state, runAt, timeLimit) {\n  var id = this.threads_.length;\n  var thread =\n      new Interpreter.Thread(id, state, runAt || this.now(), timeLimit);\n  this.threads_[this.threads_.length] = thread;\n  this.go_();\n  return new this.Thread(thread, owner);\n};\n\n/**\n * Create a new thread to execute arbitrary JavaScript code.  Thread\n * will have specified owner, but code will be evaluated directly in\n * global scope and will consequently runs wit whatever permissions\n * the global scope has.\n * @param {string} src JavaScript source code to parse and run.\n * @param {number=} timeLimit Maximum runtime without suspending (in ms).\n * @return {!Interpreter.prototype.Thread} Userland Thread object.\n */\nInterpreter.prototype.createThreadForSrc = function(src, timeLimit) {\n  if (typeof src !== 'string') throw new TypeError('src must be a string');\n  if (this.options.trimProgram) {\n    src = src.trim();\n  }\n  var ast = this.compile_(src);\n  this.populateScope_(ast, this.global);\n  var state = new Interpreter.State(ast, this.global);\n  return this.createThread(this.ROOT, state, undefined, timeLimit);\n};\n\n/**\n * Create a new thread to execute a particular function call.\n * @param {!Interpreter.Owner} owner Owner of new thread; also becomes\n *     caller perms of function.\n * @param {!Interpreter.prototype.Function} func Function to call.\n * @param {?Interpreter.Value} thisVal value of 'this' in function call.\n * @param {!Array<?Interpreter.Value>} args Arguments to pass.\n * @param {number=} runAt Time at which thread should begin execution\n *     (default: now).\n * @param {number=} timeLimit Maximum runtime without suspending (in ms).\n * @return {!Interpreter.prototype.Thread} Userland Thread object.\n */\nInterpreter.prototype.createThreadForFuncCall = function(\n    owner, func, thisVal, args, runAt, timeLimit) {\n  var state = Interpreter.State.newForCall(func, thisVal, args, owner);\n  return this.createThread(owner, state, runAt, timeLimit);\n};\n\n/**\n * Schedule the next runnable thread.  Returns 0 if a READY thread\n * successfuly scheduled (or if the current thread was already\n * runnable, which can happen when interpreter has just been\n * deserialised); otherwise returns earliest .runAt time\n * amongst SLEEPING threads (if any), or Number.MAX_VALUE if there are\n * none.  If there are additionally no BLOCKED threads left (i.e.,\n * there are no non-ZOMBIE theads at all) it will also set .done to\n * true.\n * @return {number} See description.\n */\nInterpreter.prototype.schedule = function() {\n  if (this.thread_ && this.thread_.status === Interpreter.Thread.Status.READY) {\n    return 0;  // Nothing to do.  Don't reset .threadTimeLimit_!\n  }\n  var now = this.now();\n  var runAt = Number.MAX_VALUE;\n  var threads = this.threads_;\n  // Assume all remaining threads are ZOMBIEs until proven otherwise.\n  this.done = true;\n  this.thread_ = null;\n  // .threads_ will be very sparse, so use for-in loop.\n  for (var i in threads) {\n    i = Number(i);  // Make Closure Compiler happy.\n    if (!threads.hasOwnProperty(i)) {\n      continue;\n    }\n    switch (threads[i].status) {\n      case Interpreter.Thread.Status.ZOMBIE:\n        // Remove zombie from threads.\n        delete threads[i];\n        continue;\n      case Interpreter.Thread.Status.BLOCKED:\n        // Ignore blocked threads except noting existence.\n        this.done = false;\n        continue;\n      case Interpreter.Thread.Status.SLEEPING:\n        if (threads[i].runAt > now) {\n          runAt = Math.min(runAt, threads[i].runAt);\n          this.done = false;\n          continue;\n        }\n        // Done sleeping; wake thread.\n        threads[i].status = Interpreter.Thread.Status.READY;\n        // fall through\n      case Interpreter.Thread.Status.READY:\n        // Is this this most-overdue thread found so far?\n        if (threads[i].runAt < runAt) {\n          this.thread_ = threads[i];\n          runAt = this.thread_.runAt;\n        }\n        this.done = false;\n        break;\n      default:\n        throw new Error('Unknown thread state');\n    }\n  }\n  this.threadTimeLimit_ = (this.thread_ && this.thread_.timeLimit) ?\n      now + this.thread_.timeLimit : undefined;\n  return runAt < now ? 0 : runAt;\n};\n\n/**\n * Execute one step of the interpreter.  Schedules the next runnable\n * thread if required.\n * @return {boolean} True if a step was executed, false if no more\n *     READY threads.\n */\nInterpreter.prototype.step = function() {\n  /* NOTE: Beware that an async (user) Function might reject\n   * immediately, unwinding the stack before the Call step function\n   * returns.\n   */\n  if (this.status !== Interpreter.Status.PAUSED) {\n    throw new Error('Can only step paused interpreter');\n  }\n  if (!this.thread_ ||\n      this.thread_.status !== Interpreter.Thread.Status.READY) {\n    if (this.schedule() > 0) {\n      return false;\n    }\n  }\n  if (!this.thread_) throw new Error('Scheduling failed');  // Satisfy compiler.\n  this.step_(this.thread_, this.thread_.stateStack_);\n  return true;\n};\n\n/**\n * Execute the interpreter to program completion.  Vulnerable to\n * infinite loops.  Alternates between waking any past-due SLEEPING\n * threads and running the most-overdue READY thread until there are\n * no more READY threads, then returns an integer as follows:\n *\n * - If there are SLEEPING threads, then a positive number that is the\n *   smallest .runAt value of any sleeping thread.\n * - If there are no SLEEPING threads, but there are BLOCKED threads\n *   then a negative number is returned.\n * - If only ZOMBIE threads remain, then zero is returned.\n * @return {number} See description.\n */\nInterpreter.prototype.run = function() {\n  /* NOTE: Beware that an async (user) Function might reject\n   * immediately, unwinding the stack before the Call step function\n   * returns.\n   */\n  if (this.status === Interpreter.Status.STOPPED) {\n    throw new Error(\"Can't run stopped interpreter\");\n  }\n  var t;\n  while ((t = this.schedule()) === 0) {\n    var thread = this.thread_;\n    var stack = thread.stateStack_;\n    while (thread.status === Interpreter.Thread.Status.READY) {\n      this.step_(thread, stack);\n    }\n  }\n  if (t === Number.MAX_VALUE) {\n    return this.done ? 0 : -1;\n  }\n  return t;\n};\n\n/**\n * Actually execute one step of the interpreter.  Presumes thread is\n * the currently-scheduled thread, is runnable, etc.\n * @private\n * @param {!Interpreter.Thread} thread The current thread.\n * @param {!Array<!Interpreter.State>} stack The current thread's state stack.\n */\nInterpreter.prototype.step_ = function(thread, stack) {\n  var state = stack[stack.length - 1];\n  var node = state.node;\n  try {\n    var nextState = state.stepFunc.call(this, thread, stack, state, node);\n  } catch (e) {\n    this.throw_(thread, e, state.scope.perms);\n    nextState = undefined;\n  }\n  if (nextState) {\n    stack[stack.length] = nextState;\n  }\n  if (stack.length === 0) {\n    thread.status = Interpreter.Thread.Status.ZOMBIE;\n  }\n};\n\n/**\n * If interpreter status is RUNNING, use setTimeout to arrange for\n * .run() to be called repeatedly until there are no more sleeping\n * threads.\n * @private\n */\nInterpreter.prototype.go_ = function() {\n  // Ignore calls to .go_ when PAUSED or STOPPED\n  if (this.status !== Interpreter.Status.RUNNING) {\n    return;\n  }\n  // Kill any existing runner and restart.\n  if (this.runner_) clearTimeout(this.runner_);\n  var intrp = this;\n  this.runner_ = setTimeout(function runner() {\n    // Invariant check: pausing or stopping interpreter should cancel\n    // timeout, so we should never get here while it is not RUNNING.\n    if (intrp.status !== Interpreter.Status.RUNNING) {\n      throw new Error('Un-cancelled runner on non-RUNNING interpreteter');\n    }\n    // N.B.: .run may indirectly call .go_ or even .pause or .stop\n    // (e.g. via native function calling .createThread, .pause, etc.).\n    var r = intrp.run();\n    if (intrp.runner_) {\n      // Clear any outstanding timeout.  This might be the\n      // just-completed one that called this invocation of runner, but\n      // it might be a new one created by a reentrant call to .go_\n      // (e.g. via .run -> [native function] -> .createThread).\n      clearTimeout(intrp.runner_);\n      intrp.runner_ = null;\n    }\n    if (r > 0 && intrp.status === Interpreter.Status.RUNNING) {\n      // No more code to run right now, but there is an outstanding\n      // userland timeout, so set up a future reinvocation of runner\n      // when it's time for that to run.\n      intrp.runner_ = setTimeout(runner, r - intrp.now());\n    }\n  });\n};\n\n/**\n * Set the interpreter status to RUNNING and kick it into action if\n * there is anything to do.\n */\nInterpreter.prototype.start = function() {\n  if (this.status !== Interpreter.Status.RUNNING) {\n    // Take care of STOPPED -> PAUSED transition if required.\n    this.pause();\n  }\n  this.status = Interpreter.Status.RUNNING;\n  this.go_();\n};\n\n/**\n * Set the interpreter status to PAUSED.  If it was previously\n * STOPPED, begin listening on any listened ports.  If it was\n * previously RUNNING, ensure the interpreter takes no further action\n * of its own.\n *\n * Call this function before serializing a RUNNING or PAUSED\n * interpreter to ensure correct timer restoration when deserializing.\n * (No need to call it if instance is already STOPPED.)\n */\nInterpreter.prototype.pause = function() {\n  switch (this.status) {\n    case Interpreter.Status.RUNNING:\n      clearTimeout(this.runner_);\n      this.runner_ = null;\n      this.cumulativeTime_ = this.now();  // Save elapsed time.\n      break;\n    case Interpreter.Status.PAUSED:\n      // No state change; just update elapsed time.\n      this.cumulativeTime_ = this.now();\n      break;\n    case Interpreter.Status.STOPPED:\n      // Re-listen to any previously listened ports:\n      for (var port in this.listeners_) {\n        var intrp = this;\n        var server = this.listeners_[Number(port)];\n        server.listen(function(error) {\n          if (!error) return;\n          // Something went wrong while re-listening.  Maybe port in use.\n          intrp.log('net', 'Re-listen on port %s failed: %s: %s', server.port,\n                    error.name, error.message);\n          // Report this to userland by calling .onError on proto\n          // (with this === proto) - for lack of a better option.\n          if (!server.owner) return;\n          var func = server.proto.get('onError', server.owner);\n          if (!(func instanceof intrp.Function)) return;\n          var userError = intrp.errorNativeToPseudo(error, server.owner);\n          // TODO(cpcallen:perms): Is server.owner the correct owner\n          // for this thread?  Note that this will typically be root,\n          // and .onError will therefore get caller perms === root,\n          // which is probably dangerous.\n          intrp.createThreadForFuncCall(\n              server.owner, func, server.proto, [userError],\n              undefined, server.timeLimit);\n        });\n      }\n      // Reset .uptime() to start counting from *NOW*, and .now() to\n      // continue from where it was before the interpreter was stopped.\n      this.previousTime_ = this.cumulativeTime_;\n      this.hrStartTime_ = process.hrtime();\n  }\n  this.status = Interpreter.Status.PAUSED;\n};\n\n/**\n * Set the interpreter status to STOPPED, stop listening on any port\n * (but do not close any open sockets), and ensure the interpreter\n * takes no further action of its own.\n */\nInterpreter.prototype.stop = function() {\n  if (this.status === Interpreter.Status.STOPPED) {\n    return;\n  }\n  // Do RUNNING -> PAUSED transition if required; update elapsed time.\n  this.pause();\n  // Unlisten to network sockets.\n  for (var port in this.listeners_) {\n    this.listeners_[Number(port)].unlisten();\n  }\n  this.status = Interpreter.Status.STOPPED;\n};\n\n/**\n * Prepare an interpreter to be seralized.\n */\nInterpreter.prototype.preSerialize = function() {\n  // As noted in constructor: set .seralizationVersion only just\n  // before serialising, so as to avoid mistaking old, un-versioned\n  // .city files for the current version.\n  this.serializationVersion = SERIALIZATION_VERSION;\n};\n\n/**\n * Prepare an interpreter to run after being deseralized.\n */\nInterpreter.prototype.postDeserialize = function() {\n  // Check to make sure deseralised interpreter is compatible with the\n  // current implementation.\n  if (this.serializationVersion !== SERIALIZATION_VERSION) {\n    throw new Error('version error: seralized interpreter was version ' +\n        this.serializationVersion + '; current version is ' +\n        SERIALIZATION_VERSION);\n  }\n  // Checkpointed interpreter was probably paused, but because we're\n  // restoring from a checkpoint the resurrected interpreter is\n  // actually stopped (i.e., with no listening sockets, and with\n  // questionable timer state information).\n  this.status = Interpreter.Status.STOPPED;\n};\n\n/**\n * Convert source code into a ready-to-execute parse tree.\n * @private\n * @param {string} src The source code to be compiled.\n * @param {!Interpreter.Owner=} perms Re-throw parse errors as\n *     user errors owned by perms.  (Default: re-throw parse\n *     errors as internal (native) errors.)\n * @return {!Node} node Root AST node.\n */\nInterpreter.prototype.compile_ = function(src, perms) {\n  try {\n    var ast = Parser.parse(src);\n  } catch (e) {  // Acorn threw a SyntaxError.  Rethrow as a trappable error?\n    throw perms ? this.errorNativeToPseudo(e, perms) : e;\n  }\n\n  (function analyse(node) {\n    for (var name in node) {  // Recursively analyse subtrees.\n      var prop = node[name];\n      if (prop && typeof prop !== 'object') continue;\n      if (Array.isArray(prop)) {\n        for (var i = 0; i < prop.length; i++) {\n          if (prop[i] && prop[i] instanceof Node) {\n            analyse(prop[i]);\n          }\n        }\n      } else {\n        if (prop instanceof Node) {\n          analyse(prop);\n        }\n      }\n    }\n    // Populate props on this node.\n    node['stepFunc'] = stepFuncs_[node['type']];\n  })(ast);\n\n  ast['source'] = new Interpreter.Source(src);\n  return ast;\n};\n\n/**\n * Create and register the builtin classes and functions specified in\n * the ECMAScript specification plus our extensions.  Add a few items\n * (e.g., eval) to the global scope that can't be added any other way.\n * @private\n */\nInterpreter.prototype.initBuiltins_ = function() {\n  // Initialize uneditable global properties.\n  this.global.createImmutableBinding('NaN', NaN);\n  this.global.createImmutableBinding('Infinity', Infinity);\n  this.global.createImmutableBinding('undefined', undefined);\n\n  // Create the objects which will become Object.prototype and\n  // Function.prototype, which are needed to bootstrap everything else.\n  this.OBJECT = new this.Object(null, null);\n  this.builtins.set('Object.prototype', this.OBJECT);\n\n  // Create the object that will own all of the system objects.\n  var root = new this.Object(null, this.OBJECT);\n  this.ROOT = /** @type {!Interpreter.Owner} */ (root);\n  this.builtins.set('CC.root', root);\n  this.global.perms = this.ROOT;\n  // Retroactively apply root ownership to Object.prototype:\n  this.OBJECT.owner = this.ROOT;\n\n  // NativeFunction constructor adds new function to the map of builtins.\n  this.FUNCTION = new this.NativeFunction({\n    id: 'Function.prototype', name: '', length: 0, proto: this.OBJECT,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {/* do nothing */}\n  });\n\n  // Initialize global objects.\n  this.initObject_();\n  this.initFunction_();\n  this.initArray_();\n  this.initString_();\n  this.initBoolean_();\n  this.initNumber_();\n  this.initDate_();\n  this.initRegExp_();\n  this.initError_();\n  this.initMath_();\n  this.initJSON_();\n  this.initWeakMap_();\n  this.initPerms_();\n\n  // Initialize ES standard global functions.\n  var eval_ = new this.NativeFunction({\n    id: 'eval', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var code = args[0];\n      var perms = state.scope.perms;\n      if (intrp.options.trimEval) {\n        code = code.trim();\n      }\n      if (typeof code !== 'string') {  // eval()\n        // Eval returns the argument if the argument is not a string.\n        // eval(Array) -> Array\n        return code;\n      }\n      var ast = intrp.compile_(code, perms);\n      // Change node type from Program to EvalProgram_.\n      ast['type'] = 'EvalProgram_';\n      ast['stepFunc'] = stepFuncs_['EvalProgram_'];\n      // Create new scope and update it with definitions in eval().\n      var outerScope = state.info_.directEval ? state.scope : intrp.global;\n      var scope =\n          new Interpreter.Scope(Interpreter.Scope.Type.EVAL, perms, outerScope);\n      intrp.populateScope_(ast, scope);\n      thread.stateStack_[thread.stateStack_.length] =\n          new Interpreter.State(ast, scope);\n      thread.value = undefined;  // In case no ExpressionStatements evaluated.\n      return Interpreter.FunctionResult.AwaitValue;\n    }\n  });\n  // eval is a special case; it must be added to the global scope at\n  // startup time (rather than by a \"var eval = new 'eval';\" statement\n  // in es5.js) because assigning to eval is illegal in strict mode.\n  // This also means that it is effectively immutable despite being\n  // created with createMutableBinding.\n  this.global.createMutableBinding('eval', eval_);\n\n  this.createNativeFunction('isFinite', isFinite, false);\n  this.createNativeFunction('isNaN', isNaN, false);\n  this.createNativeFunction('parseFloat', parseFloat, false);\n  this.createNativeFunction('parseInt', parseInt, false);\n\n  var strFunctions = [\n    [escape, 'escape'], [unescape, 'unescape'],\n    [decodeURI, 'decodeURI'], [decodeURIComponent, 'decodeURIComponent'],\n    [encodeURI, 'encodeURI'], [encodeURIComponent, 'encodeURIComponent']\n  ];\n  var intrp = this;\n  for (var i = 0; i < strFunctions.length; i++) {\n    var wrapper = (function(nativeFunc) {\n      return function(str) {\n        try {\n          return nativeFunc(str);\n        } catch (e) {\n          // decodeURI('%xy') will throw an error.  Catch and rethrow.\n          throw intrp.errorNativeToPseudo(e, intrp.thread_.perms());\n        }\n      };\n    })(strFunctions[i][0]);\n    this.createNativeFunction(strFunctions[i][1], wrapper, false);\n  }\n\n  // Initialize CC-specific globals.\n  this.initThread_();\n  this.initNetwork_();\n};\n\n/**\n * Initialize the Object class.\n * @private\n */\nInterpreter.prototype.initObject_ = function() {\n  // Object constructor.\n  new this.NativeFunction({\n    id: 'Object', length: 1,\n    /** @type {!Interpreter.NativeConstructImpl} */\n    construct: function(intrp, thread, state, args) {\n      var value = args[0];\n      if (value instanceof intrp.Object) {\n        return value;\n      } else if (typeof value === 'boolean' || typeof value === 'number' ||\n          typeof value === 'string') {\n        // No boxed primitives in Code City.\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'boxed primitives not supported');\n      } else if (value === undefined || value === null) {\n        return new intrp.Object(state.scope.perms);\n      } else {\n        throw new TypeError('Unknown value type??');\n      }\n    },\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return this.construct.call(this, intrp, thread, state, args);\n    }\n  });\n\n  // Static methods on Object.\n  this.createNativeFunction('Object.is', Object.is, false);\n\n  new this.NativeFunction({\n    id: 'Object.getOwnPropertyNames', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      // N.B.: we use ES6 definition; ES5.1 would throw TypeError if\n      // passed a non-object.\n      var obj = intrp.toObject(args[0], perms);\n      return intrp.createArrayFromList(obj.ownKeys(perms), perms);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.keys', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(args[0], perms);\n      var keys = obj.ownKeys(perms);\n      var enumerableKeys = [];\n      for (var i = 0; i < keys.length; i++) {\n        var key = keys[i];\n        var pd = obj.getOwnPropertyDescriptor(key, perms);\n        if (pd.enumerable) enumerableKeys.push(key);\n      }\n      return intrp.createArrayFromList(enumerableKeys, perms);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.create', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var proto = args[0];\n      // Support for the second argument is the responsibility of a polyfill.\n      if (proto === null) {\n        return new intrp.Object(state.scope.perms, null);\n      }\n      if (!(proto === null || proto instanceof intrp.Object)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'Object prototype may only be an Object or null');\n      }\n      return new intrp.Object(state.scope.perms, proto);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.defineProperty', length: 3,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var obj = args[0];\n      var key = args[1];\n      var attr = args[2];\n      var perms = state.scope.perms;\n      if (!(obj instanceof intrp.Object)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'Object.defineProperty called on non-object');\n      }\n      key = String(key);\n      if (!(attr instanceof intrp.Object)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'Property description must be an object');\n      }\n      // Can't just use pseudoToNative since descriptors can inherit properties.\n      var desc = new Descriptor;\n      if (attr.has('configurable', perms)) {\n        desc.configurable = Boolean(attr.get('configurable', perms));\n      }\n      if (attr.has('enumerable', perms)) {\n        desc.enumerable = Boolean(attr.get('enumerable', perms));\n      }\n      if (attr.has('writable', perms)) {\n        desc.writable = Boolean(attr.get('writable', perms));\n      }\n      if (attr.has('value', perms)) {\n        desc.value = attr.get('value', perms);\n      }\n      obj.defineProperty(key, desc, perms);\n      return obj;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.getOwnPropertyDescriptor', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var obj = args[0];\n      var prop = args[1];\n      var perms = state.scope.perms;\n      if (!(obj instanceof intrp.Object)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'Object.getOwnPropertyDescriptor called on non-object');\n      }\n      prop = String(prop);\n      var pd = obj.getOwnPropertyDescriptor(prop, perms);\n      if (!pd) {\n        return undefined;\n      }\n      var descriptor = new intrp.Object(perms);\n      descriptor.set('configurable', pd.configurable, perms);\n      descriptor.set('enumerable', pd.enumerable, perms);\n      descriptor.set('writable', pd.writable, perms);\n      descriptor.set('value', pd.value, perms);\n      return descriptor;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.getPrototypeOf', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      // N.B.: This conforms to ES6.  ES5.1 would throw TypeError for\n      // Object.getPrototypeOf(<boolean, string or number>)\n      var o = intrp.toObject(args[0], state.scope.perms);\n      return o.proto;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.setPrototypeOf', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var obj = args[0];\n      var proto = args[1];\n      var perms = state.scope.perms;\n      if (obj === null || obj === undefined) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'Object.setPrototypeOf called on null or undefined');\n      }\n      if (proto !== null && !(proto instanceof intrp.Object)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'Object prototype may only be an Object or null');\n      }\n      if (obj instanceof intrp.Object) {\n        // obj.setPrototypeOf handles security and circularity checks.\n        if (!obj.setPrototypeOf(proto, perms)) {\n          throw new intrp.Error(perms, intrp.TYPE_ERROR,\n              'setPrototypeOf failed');\n        }\n      }\n      return obj;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.isExtensible', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var obj = args[0];\n      if (!(obj instanceof intrp.Object)) {\n        return false;  // ES6 §19.1.2.11.  ES5.1 would throw TypeError.\n      }\n      return obj.isExtensible(state.scope.perms);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.preventExtensions', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var obj = args[0];\n      var perms = state.scope.perms;\n      if (!(obj instanceof intrp.Object)) {\n        return obj;  // ES6 §19.1.2.15.  ES5.1 would throw TypeError.\n      }\n      if (!obj.preventExtensions(perms)) {\n        // Can only happen once we have Proxy objects.\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            obj.toString() + \" can't be made non-extensible.\");\n      }\n      return obj;\n    }\n  });\n\n  // Properties of the Object prototype object.\n  this.createNativeFunction('Object.prototype.toString',\n                            this.Object.prototype.toString, false);\n  this.createNativeFunction('Object.prototype.toLocaleString',\n                            this.Object.prototype.toLocaleString, false);\n  this.createNativeFunction('Object.prototype.valueOf',\n                            this.Object.prototype.valueOf, false);\n\n\n  new this.NativeFunction({\n    id: 'Object.prototype.hasOwnProperty', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var key = args[0];\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      return Boolean(obj.getOwnPropertyDescriptor(String(key), perms));\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.prototype.propertyIsEnumerable', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var key = String(args[0]);\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var desc = obj.getOwnPropertyDescriptor(key, perms);\n      if (desc === undefined) {\n        return false;\n      }\n      return desc.enumerable;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.prototype.isPrototypeOf', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var v = args[0];\n      if (!(v instanceof intrp.Object)) return false;\n      var o = intrp.toObject(thisVal, state.scope.perms);\n      while (true) {\n        v = v.proto;\n        if (v === null) return false;  // No parent; reached the top.\n        if (o === v) return true;\n      }\n    }\n  });\n};\n\n/**\n * Initialize the Function class.\n * @private\n */\nInterpreter.prototype.initFunction_ = function() {\n  var intrp = this;\n  var wrapper;\n  // Function constructor.\n  new this.NativeFunction({\n    id: 'Function', length: 1,\n    /** @type {!Interpreter.NativeConstructImpl} */\n    construct: function(intrp, thread, state, args) {\n      args = args.slice();  // Copy, so we can .pop safely.\n      var body = args.length ? String(args.pop()) : '';\n      // Concatenate formal parameter names.  Let Acorn verify they\n      // are valid Identifiers.\n      var argsStr = args.map(function(arg) {return String(arg);}).join(',');\n      // Acorn needs to parse body in the context of a function or\n      // else 'return' statements will be syntax errors.  The name\n      // \"anonymous\" and extra line breaks were standardised in ES2019\n      // via https://tc39.es/Function-prototype-toString-revision/\n      var source = '(function anonymous(' + argsStr + '\\n) {\\n' + body + '\\n})';\n      var ast = intrp.compile_(source, state.scope.perms);\n      if (ast['body'].length !== 1) {\n        // Function('a', 'return a + 6;}; {alert(1);');\n        // TODO: there must be a cleaner way to detect this!\n        throw new intrp.Error(state.scope.perms, intrp.SYNTAX_ERROR,\n            'Invalid code in function body');\n      }\n      // Interestingly, the scope for constructed functions is the global\n      // scope, even if they were constructed in some other scope.\n      return new intrp.UserFunction(ast['body'][0]['expression'],\n          intrp.global, new Interpreter.Source(source), state.scope.perms);\n    },\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return this.construct.call(this, intrp, thread, state, args);\n    }\n  });\n\n  // Properties of the Function prototype object.\n  new this.NativeFunction({\n    id: 'Function.prototype.toString', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var func = thisVal;\n      if (!(func instanceof intrp.Function)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'Function.prototype.toString is not generic');\n      }\n      // TODO(cpcallen:perms): Perm check here?  Or in toString?\n      return func.toString();\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Function.prototype.apply', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var func = thisVal;\n      var thisArg = args[0];\n      var argArray = args[1];\n      var perms = state.scope.perms;\n      if (!(func instanceof intrp.Function)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            func + ' is not a function');\n      } else if (argArray === null || argArray === undefined) {\n        var argList = [];\n      } else {\n        argList = intrp.createListFromArrayLike(argArray, perms);\n      }\n      // Rewrite state.info_, as a short-circuit optimisation in case\n      // we get called again due to FunctionResult.CallAgain, and also\n      // to produce more useful callers() output / stack traces.\n      var info = state.info_;\n      info.func = func;\n      info.this = thisArg;\n      info.args = argList;\n      info.construct = false;\n      // But just go and do the first .call directly.\n      return func.call(intrp, thread, state, thisArg, argList);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Function.prototype.bind', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var target = thisVal;\n      if (!(target instanceof intrp.Function)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            target + ' is not a function');\n      }\n      var thisArg = args[0];\n      var argList = args.slice(1);\n      var perms = state.scope.perms;\n      var f = new intrp.BoundFunction(target, thisArg, argList, perms);\n      var len = 0;\n      if (target.has('length', perms)) {\n        var targetLen = target.get('length', perms);\n        if (typeof targetLen === 'number') {\n          len = Math.max(0, targetLen - argList.length);\n        }\n      }\n      f.defineProperty('length', Descriptor.c.withValue(len), perms);\n      var targetName = target.get('name', perms);\n      if (typeof targetName !== 'string') {\n        targetName = '';\n      }\n      f.setName(targetName, 'bound');\n      return f;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Function.prototype.call', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var func = thisVal;\n      if (!(func instanceof intrp.Function)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            func + ' is not a function');\n      }\n      var thisArg = args[0];\n      var argList = args.slice(1);\n      // Rewrite state.info_, as a short-circuit optimisation in case\n      // we get called again due to FunctionResult.CallAgain, and also\n      // to produce more useful callers() output / stack traces.\n      var info = state.info_;\n      info.func = func;\n      info.this = thisArg;\n      info.args = argList;\n      info.construct = false;\n      // But just go and do the first .call directly.\n      return func.call(intrp, thread, state, thisArg, argList);\n    }\n  });\n};\n\n/**\n * Initialize the Array class.\n * @private\n */\nInterpreter.prototype.initArray_ = function() {\n  // Array prototype.\n  this.ARRAY = new this.Array(this.ROOT, this.OBJECT);\n  this.builtins.set('Array.prototype', this.ARRAY);\n\n  // Array constructor.\n  new this.NativeFunction({\n    id: 'Array', length: 1,\n    /** @type {!Interpreter.NativeConstructImpl} */\n    construct: function(intrp, thread, state, args) {\n      var len = args[0];\n      var perms = state.scope.perms;\n      // TODO(ES6): Need to do GetPrototypeFromConstructor, ArrayCreate, etc.\n      var arr = new intrp.Array(perms);\n      if (args.length === 0) {  // ES6 §22.1.1.1\n        // Nothing to do.\n      } else if (args.length === 1) {\n        if (typeof len !== 'number') {\n          arr.defineProperty('0', Descriptor.wec.withValue(len), perms);\n          var intLen = 1;\n        } else {  // ES6 §22.1.1.2\n          intLen = Interpreter.toUint32(len);\n          if (intLen !== len) {\n            throw new intrp.Error(perms, intrp.RANGE_ERROR,\n                 'Invalid array length');\n          }\n        }\n        arr.set('length', intLen, perms);\n      } else {  // ES6 §22.1.1.3\n        arr.set('length', args.length, perms);\n        for (var k = 0; k < args.length; k++) {\n          arr.defineProperty(\n              String(k), Descriptor.wec.withValue(args[k]), perms);\n        }\n      }\n      return arr;\n    },\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return this.construct.call(this, intrp, thread, state, args);\n    }\n  });\n\n  // Static methods on Array.\n  new this.NativeFunction({\n    id: 'Array.isArray', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return args[0] instanceof intrp.Array;\n    }\n  });\n\n  // Properties of the Array prototype object.\n  new this.NativeFunction({\n    id: 'Array.prototype.concat', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var arr = new intrp.Array(perms);\n      var n = 0;\n\n      var doConcat = function(item) {\n        // TODO(ES6): IsConcatSpreadable?\n        if (item instanceof intrp.Array) {  // Add elements of item.\n          var len = Interpreter.toLength(item.get('length', perms));\n          if (len + n > Number.MAX_SAFE_INTEGER) {\n            throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Concatenating ' +\n                len + ' elements on an array-like of length ' + n +\n                ' is disallowed, as the total surpasses 2**53-1');\n          }\n          for (var k = 0; k < len; n++, k++) {\n            var kP = String(k);\n            if (item.has(kP, perms)) {\n              arr.defineProperty(String(n),\n                  Descriptor.wec.withValue(item.get(kP, perms)), perms);\n            }\n          }\n        } else {  // Add item as single element, rather than spread.\n          if (n >= Number.MAX_SAFE_INTEGER) {\n            throw new intrp.Error(perms, intrp.TYPE_ERROR,\n                'Concatenating onto an array-like of length ' + n +\n                ' is disallowed, as the total surpasses 2**53-1');\n          }\n          arr.defineProperty(\n              String(n++), Descriptor.wec.withValue(item), perms);\n        }\n      };\n\n      doConcat(thisVal);\n      for (var i = 0; i < args.length; i++) {\n        doConcat(args[i]);\n      }\n      arr.set('length', n, perms);\n      return arr;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.includes', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var searchElement = args[0];\n      var fromIndex = args[1];\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      if (len === 0) return false;\n      var n = (fromIndex === undefined ? 0 : Interpreter.toInteger(fromIndex));\n      if (n >= len) return false;\n      var k = (n >= 0) ? n : Math.max(len - Math.abs(n), 0);\n      for (; k < len; k++) {\n        if (obj.has(String(k), perms)) {\n          var v = obj.get(String(k), perms);\n          if (v === searchElement ||\n              (Number.isNaN(/** @type{?} */(v)) &&\n               Number.isNaN(/** @type{?} */(searchElement)))) {\n            return true;\n          }\n        }\n      }\n      return false;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.indexOf', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var searchElement = args[0];\n      var fromIndex = args[1];\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      if (len === 0) return -1;\n      var n = (fromIndex === undefined ? 0 : Interpreter.toInteger(fromIndex));\n      if (n >= len) return -1;\n      var k = (n >= 0) ? n : Math.max(len - Math.abs(n), 0);\n      for (; k < len; k++) {\n        if (obj.has(String(k), perms) &&\n            obj.get(String(k), perms) === searchElement) {\n          return k;\n        }\n      }\n      return -1;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.lastIndexOf', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var searchElement = args[0];\n      var fromIndex = args[1];\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      if (len === 0) return -1;\n      var n = (fromIndex === undefined) ? len - 1 :\n          Interpreter.toInteger(fromIndex);\n      var k = (n >= 0) ? Math.min(n, len - 1) : len - Math.abs(n);\n      for (; k >= 0 ; k--) {\n        if (obj.has(String(k), perms) &&\n            obj.get(String(k), perms) === searchElement) {\n          return k;\n        }\n      }\n      return -1;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.pop', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      if (len === 0) {\n        obj.set('length', 0, perms);\n        return undefined;\n      }\n      var newLen = len - 1;\n      var element = obj.get(String(newLen), perms);\n      obj.deleteProperty(String(newLen), perms);\n      obj.set('length', newLen, perms);\n      return element;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.push', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      var argCount = args.length;\n      if (len + args.length > Number.MAX_SAFE_INTEGER) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Pushing ' + argCount +\n              ' elements on an array-like of length ' + len +\n              ' is disallowed, as the total surpasses 2**53-1');\n      }\n      for (var i = 0; i < argCount; i++) {\n        obj.set(String(len++), args[i], perms);\n      }\n      obj.set('length', len, perms);\n      return len;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.reverse', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      var middle = Math.floor(len / 2);\n      for (var lower = 0; lower < middle; lower++) {\n        var upper = len - lower - 1;\n        var upperP = String(upper);\n        var lowerP = String(lower);\n        var lowerExists = obj.has(lowerP, perms);\n        if (lowerExists) {\n          var lowerValue = obj.get(lowerP, perms);\n        }\n        var upperExists = obj.has(upperP, perms);\n        if (upperExists) {\n          var upperValue = obj.get(upperP, perms);\n        }\n        if (lowerExists && upperExists) {\n          obj.set(lowerP, upperValue, perms);\n          obj.set(upperP, lowerValue, perms);\n        } else if (!lowerExists && upperExists) {\n          obj.set(lowerP, upperValue, perms);\n          obj.deleteProperty(upperP, perms);\n        } else if (lowerExists && !upperExists) {\n          obj.deleteProperty(lowerP, perms);\n          obj.set(upperP, lowerValue, perms);\n        }  // else neither exist, and no action required.\n      }\n      // ES spec would have us return obj, which would be a boxed\n      // primitive (Boolean, Number or String object) if thisVal was a\n      // number, boolean or the empty string.  We decline to do that.\n      // (Note that nonempty strings will already have thrown\n      // TypeError due to non-writable properties.)\n      return thisVal;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.shift', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      if (len === 0) {\n        obj.set('length', 0, perms);\n        return undefined;\n      }\n      var first = obj.get('0', perms);\n      for (var k = 1; k < len; k++) {\n        var from = String(k);\n        var to = String(k - 1);\n        if (obj.has(from, perms)) {\n          obj.set(to, obj.get(from, perms), perms);\n        } else {\n          obj.deleteProperty(to, perms);\n        }\n      }\n      obj.deleteProperty(String(len - 1), perms);\n      obj.set('length', len - 1, perms);\n      return first;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.slice', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var start = args[0];\n      var end = args[1];\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      var relativeStart = Interpreter.toInteger(start);\n      var k = (relativeStart < 0) ? Math.max(len + relativeStart, 0) :\n          Math.min(relativeStart, len);\n      var relativeEnd = (end === undefined) ? len : Interpreter.toInteger(end);\n      var final = (relativeEnd < 0) ? Math.max(len + relativeEnd, 0) :\n          Math.min(relativeEnd, len);\n      // TODO(cpcallen): ArraySpeciesCreate should take count as an argument.\n      // var count = Math.max(final - k, 0);\n      var arr = new intrp.Array(perms);\n      for (var n = 0; k < final; k++, n++) {\n        var kP = String(k);\n        if (obj.has(kP, perms)) {\n          arr.defineProperty(\n              String(n), Descriptor.wec.withValue(obj.get(kP, perms)), perms);\n        }\n      }\n      arr.set('length', n, perms);\n      return arr;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.splice', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var start = args[0];\n      var deleteCount = args[1];\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      var relativeStart = Interpreter.toInteger(start);\n      var actualStart = relativeStart < 0 ? Math.max(len + relativeStart, 0) :\n          Math.min(relativeStart, len);\n      if (args.length === 0) {\n        var insertCount = 0;\n        var actualDeleteCount = 0;\n      } else if (args.length === 1) {\n        insertCount = 0;\n        actualDeleteCount = len - actualStart;\n      } else {\n        insertCount = args.length - 2;\n        var dc = Interpreter.toInteger(deleteCount);\n        actualDeleteCount = Math.min(Math.max(dc, 0), len - actualStart);\n      }\n      if (len + insertCount - actualDeleteCount > Number.MAX_SAFE_INTEGER) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Splicing ' +\n            insertCount - actualDeleteCount +\n            ' elements on an array-like of length ' + len +\n            ' is disallowed, as the total surpasses 2**53-1');\n      }\n      var arr = new intrp.Array(perms);\n      for (var k = 0; k < actualDeleteCount; k++) {\n        var from = String(actualStart + k);\n        if (obj.has(from, perms)) {\n          arr.defineProperty(\n              String(k), Descriptor.wec.withValue(obj.get(from, perms)), perms);\n        }\n      }\n      arr.set('length', actualDeleteCount, perms);\n      var itemCount = Math.max(args.length - 2, 0);\n      if (itemCount < actualDeleteCount) {\n        for (k = actualStart; k < len - actualDeleteCount; k++) {\n          from = String(k + actualDeleteCount);\n          var to = String(k + itemCount);\n          if (obj.has(from, perms)) {\n            obj.set(to, obj.get(from, perms), perms);\n          } else {\n            obj.deleteProperty(to, perms);\n          }\n        }\n        for (k = len; k > len - actualDeleteCount + itemCount; k--) {\n          obj.deleteProperty(String(k - 1), perms);\n        }\n      } else if (itemCount > actualDeleteCount) {\n        for (k = len - actualDeleteCount; k > actualStart; k--) {\n          from = String(k + actualDeleteCount - 1);\n          to = String(k + itemCount - 1);\n          if (obj.has(from, perms)) {\n            obj.set(to, obj.get(from, perms), perms);\n          } else {\n            obj.deleteProperty(to, perms);\n          }\n        }\n      }\n      for (var j = 2, k = actualStart; j < args.length; j++, k++) {\n        obj.set(String(k), args[j], perms);\n      }\n      obj.set('length', len - actualDeleteCount + itemCount, perms);\n      return arr;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.toString', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var join = obj.get('join', perms);\n      if (join instanceof intrp.Function) {\n        var func = join;\n      } else {\n        func = /** @type {!Interpreter.prototype.Function} */ (\n            intrp.builtins.get('Object.prototype.toString'));\n      }\n      var newState = Interpreter.State.newForCall(func, thisVal, [], perms);\n      thread.stateStack_.push(newState);\n      return Interpreter.FunctionResult.AwaitValue;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Array.prototype.unshift', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      var obj = intrp.toObject(thisVal, perms);\n      var len = Interpreter.toLength(obj.get('length', perms));\n      var argCount = args.length;\n      if (argCount > 0) {\n        if (len + args.length > Number.MAX_SAFE_INTEGER) {\n          throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Unshifting ' +\n              argCount + ' elements on an array-like of length ' + len +\n              ' is disallowed, as the total surpasses 2**53-1');\n        }\n        for (var k = len; k > 0; k--) {\n          var from = String(k - 1);\n          var to = String(k);\n          if (obj.has(from, perms)) {\n            obj.set(to, obj.get(from, perms), perms);\n          } else {\n            obj.deleteProperty(to, perms);\n          }\n        }\n        for (var j = 0; j < argCount; j++) {\n          obj.set(String(j), args[j], perms);\n        }\n      }\n      obj.set('length', len + argCount, perms);\n      return len + argCount;\n    }\n  });\n};\n\n/**\n * Initialize the String class.\n * @private\n */\nInterpreter.prototype.initString_ = function() {\n  var intrp = this;\n  var wrapper;\n  // String prototype.  It's a String object (but the only one!)\n  this.STRING = new this.Object(this.ROOT);\n  this.builtins.set('String.prototype', this.STRING);\n  this.STRING.class = 'String';\n\n  // String constructor.  ES6 §21.1.1.1.\n  new this.NativeFunction({\n    id: 'String', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      // We don't handle symbols, so String(x) should just return\n      // ToString(x) (ES6 §7.1.12) if x is primitive, or\n      // ToString(ToPrimitive(x, hint String)) if not.  Note that\n      // ToPrimitive (ES6 §7.1.1) is guaranteed to return a primitive\n      // or throw.\n      var value = args.length > 0 ? args[0] : '';\n      var perms = state.scope.perms;\n      if (!(value instanceof intrp.Object)) {\n        return String(value);\n      }\n      var step = Number(state.info_.funcState) || 0;\n      if (step > 0 && !(state.value instanceof intrp.Object)) {\n        // Call of .toString or .valueOf by previous visit returned a\n        // primitive.  Convert to string and return.\n        return String(state.value);\n      }\n      switch(step) {\n        case 0:  // Try calling toString.\n          var method = value.get('toString', perms);\n          if (method instanceof intrp.Function) {\n            thread.stateStack_[thread.stateStack_.length] =\n                Interpreter.State.newForCall(method, value, [], perms);\n            state.info_.funcState = 1;\n            return Interpreter.FunctionResult.CallAgain;\n          }\n          // FALL THROUGH\n        case 1:  // toString call complete (or skipped); try calling valueOf.\n          method = value.get('valueOf', perms);\n          if (method instanceof intrp.Function) {\n            thread.stateStack_[thread.stateStack_.length] =\n                Interpreter.State.newForCall(method, value, [], perms);\n            state.info_.funcState = 2;\n            return Interpreter.FunctionResult.CallAgain;\n          }\n          // FALL THROUGH\n        case 2:  // valueOf complete (or skipped); throw TypeError.\n          throw new intrp.Error(perms, intrp.TYPE_ERROR,\n             'Cannot convert object to primitive value');\n        default:\n          throw new Error('Invalid funcStep in String??');\n      }\n    },\n    /** @type {!Interpreter.NativeConstructImpl} */\n    construct: function(intrp, thread, state, args) {\n      throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n         'String objects not supported.');\n    }\n  });\n\n  /**\n   * The thisStringValue specification method from ES6 §21.1.3.\n   * Converts value arg to string or throws TypeError.\n   * @param {!Interpreter} intrp The interpreter.\n   * @param {?Interpreter.Value} value The this value passed into function.\n   * @param {string} name Name of built-in function (for TypeError message).\n   * @param {!Interpreter.Owner} perms Who called built-in?\n   * @return {string}\n   */\n  var thisStringValue = function(intrp, value, name, perms) {\n    if (typeof value === 'string') {  // String primitive.\n      return value;\n    } else if (value === intrp.STRING) {  // The only String object.\n      return '';\n    }\n    throw new intrp.Error(perms, intrp.TYPE_ERROR,\n        name + \" requires that 'this' be a String\");\n  };\n\n  // Static methods on String.\n  this.createNativeFunction('String.fromCharCode', String.fromCharCode, false);\n\n  // Properties of the String prototype object.\n  // Methods with exclusively primitive arguments.\n  var functions = ['charAt', 'charCodeAt', 'concat', 'endsWith', 'includes',\n      'indexOf', 'lastIndexOf', 'slice', 'startsWith', 'substr', 'substring',\n      'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase',\n      'trim'];\n  for (var i = 0; i < functions.length; i++) {\n    this.createNativeFunction('String.prototype.' + functions[i],\n                              String.prototype[functions[i]], false);\n  }\n\n  wrapper = function(compareString /*, locales, options*/) {\n    // Messing around with arguments so that function's length is 1.\n    var locales = arguments.length > 1 ?\n        intrp.pseudoToNative(arguments[1]) : undefined;\n    var options = arguments.length > 2 ?\n        intrp.pseudoToNative(arguments[2]) : undefined;\n    return this.localeCompare(compareString, locales, options);\n  };\n  this.createNativeFunction('String.prototype.localeCompare', wrapper, false);\n\n  wrapper = function(separator, limit) {\n    if (separator instanceof intrp.RegExp) {\n      separator = separator.regexp;\n    }\n    var jsList = this.split(separator, limit);\n    return intrp.createArrayFromList(jsList, intrp.thread_.perms());\n  };\n  this.createNativeFunction('String.prototype.split', wrapper, false);\n\n  wrapper = function(regexp) {\n    if (regexp instanceof intrp.RegExp) {\n      regexp = regexp.regexp;\n    }\n    var m = this.match(regexp);\n    return m && intrp.createArrayFromList(m, intrp.thread_.perms());\n  };\n  this.createNativeFunction('String.prototype.match', wrapper, false);\n\n  wrapper = function(regexp) {\n    if (regexp instanceof intrp.RegExp) {\n      regexp = regexp.regexp;\n    }\n    return this.search(regexp);\n  };\n  this.createNativeFunction('String.prototype.search', wrapper, false);\n\n  wrapper = function(substr, newSubstr) {\n    // Support for function replacements is the responsibility of a polyfill.\n    if (substr instanceof intrp.RegExp) {\n      substr = substr.regexp;\n    }\n    return String(this).replace(substr, newSubstr);\n  };\n  this.createNativeFunction('String.prototype.replace', wrapper, false);\n\n  wrapper = function(count) {\n    try {\n      return this.repeat(count);\n    } catch (e) {\n      // 'abc'.repeat(-1) will throw an error.  Catch and rethrow.\n      throw intrp.errorNativeToPseudo(e, intrp.thread_.perms());\n    }\n  };\n  this.createNativeFunction('String.prototype.repeat', wrapper, false);\n\n  new this.NativeFunction({\n    id: 'String.prototype.toString', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return thisStringValue(intrp, thisVal,\n          'String.prototype.toString', state.scope.perms);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'String.prototype.valueOf', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return thisStringValue(intrp, thisVal,\n          'String.prototype.valueOf', state.scope.perms);\n    }\n  });\n};\n\n/**\n * Initialize the Boolean class.\n * @private\n */\nInterpreter.prototype.initBoolean_ = function() {\n  // Boolean prototype.  It's a Boolean object (but the only one!)\n  this.BOOLEAN = new this.Object(this.ROOT);\n  this.builtins.set('Boolean.prototype', this.BOOLEAN);\n  this.BOOLEAN.class = 'Boolean';\n\n  // Boolean constructor.\n  new this.NativeFunction({\n    id: 'Boolean', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return Boolean(args[0]);\n    },\n    /** @type {!Interpreter.NativeConstructImpl} */\n    construct: function(intrp, thread, state, args) {\n      throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n          'Boolean objects not supported.');\n    }\n  });\n\n  /**\n   * The thisBooleanValue specification method from ES6 §19.3.3.\n   * Converts value arg to boolean or throws TypeError.\n   * @param {!Interpreter} intrp The interpreter.\n   * @param {?Interpreter.Value} value The this value passed into function.\n   * @param {string} name Name of built-in function (for TypeError message).\n   * @param {!Interpreter.Owner} perms Who called built-in?\n   * @return {boolean}\n   */\n  var thisBooleanValue = function(intrp, value, name, perms) {\n    if (typeof value === 'boolean') {  // Boolean primitive.\n      return value;\n    } else if (value === intrp.BOOLEAN) {  // The only Boolen object.\n      return false;\n    }\n    throw new intrp.Error(perms, intrp.TYPE_ERROR,\n        name + \" requires that 'this' be a Boolean\");\n  };\n\n  // Instance methods on Boolean.\n  new this.NativeFunction({\n    id: 'Boolean.prototype.toString', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return String(thisBooleanValue(intrp, thisVal,\n          'Boolean.prototype.toString', state.scope.perms));\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Boolean.prototype.valueOf', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return thisBooleanValue(intrp, thisVal,\n          'Boolean.prototype.valueOf', state.scope.perms);\n    }\n  });\n};\n\n/**\n * Initialize the Number class.\n * @private\n */\nInterpreter.prototype.initNumber_ = function() {\n  var intrp = this;\n  var wrapper;\n  // Number prototype.  It's a Number object (but the only one!)\n  this.NUMBER = new this.Object(this.ROOT);\n  this.builtins.set('Number.prototype', this.NUMBER);\n  this.NUMBER.class = 'Number';\n\n  // Number constructor.\n  new this.NativeFunction({\n    id: 'Number', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return Number(args.length ? args[0] : 0);\n    },\n    /** @type {!Interpreter.NativeConstructImpl} */\n    construct: function(intrp, thread, state, args) {\n      throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n          'Number objects not supported.');\n    }\n  });\n\n  /**\n   * The thisNumberValue specification method from ES6 §20.1.3.\n   * Converts value arg to number or throws TypeError.\n   * @param {!Interpreter} intrp The interpreter.\n   * @param {?Interpreter.Value} value The this value passed into function.\n   * @param {string} name Name of built-in function (for TypeError message).\n   * @param {!Interpreter.Owner} perms Who called built-in?\n   * @return {number}\n   */\n  var thisNumberValue = function(intrp, value, name, perms) {\n    if (typeof value === 'number') {  // Number primitive.\n      return value;\n    } else if (value === intrp.NUMBER) {  // The only Boolen object.\n      return 0;\n    }\n    throw new intrp.Error(perms, intrp.TYPE_ERROR,\n        name + \" requires that 'this' be a Number\");\n  };\n\n  // Static methods on Number.\n  this.createNativeFunction('Number.isFinite', Number.isFinite, false);\n  this.createNativeFunction('Number.isInteger', Number.isInteger, false);\n  this.createNativeFunction('Number.isNaN', Number.isNaN, false);\n  this.createNativeFunction('Number.isSafeInteger', Number.isSafeInteger,\n                            false);\n\n  // Properties of the Number prototype object.\n  wrapper = function(fractionDigits) {\n    try {\n      return this.toExponential(fractionDigits);\n    } catch (e) {\n      // Throws if fractionDigits isn't within 0-20.\n      throw intrp.errorNativeToPseudo(e, intrp.thread_.perms());\n    }\n  };\n  this.createNativeFunction('Number.prototype.toExponential', wrapper, false);\n\n  wrapper = function(digits) {\n    try {\n      return this.toFixed(digits);\n    } catch (e) {\n      // Throws if digits isn't within 0-20.\n      throw intrp.errorNativeToPseudo(e, intrp.thread_.perms());\n    }\n  };\n  this.createNativeFunction('Number.prototype.toFixed', wrapper, false);\n\n  wrapper = function(precision) {\n    try {\n      return this.toPrecision(precision);\n    } catch (e) {\n      // Throws if precision isn't within range (depends on implementation).\n      throw intrp.errorNativeToPseudo(e, intrp.thread_.perms());\n    }\n  };\n  this.createNativeFunction('Number.prototype.toPrecision', wrapper, false);\n\n  wrapper = function(/*locales, options*/) {\n    // Messing around with arguments so that function's length is 0.\n    var locales = arguments.length > 0 ?\n        intrp.pseudoToNative(arguments[0]) : undefined;\n    var options = arguments.length > 1 ?\n        intrp.pseudoToNative(arguments[1]) : undefined;\n    return this.toLocaleString(locales, options);\n  };\n  this.createNativeFunction('Number.prototype.toLocaleString', wrapper, false);\n\n  new this.NativeFunction({\n    id: 'Number.prototype.toString', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var x = thisNumberValue(\n          intrp, thisVal, 'Number.prototype.toString', state.scope.perms);\n      var radix = args[0];\n      try {\n        // Throws if radix isn't within 2-36.  Cast requried because\n        // Closure Compiler thinks radix should be a number.\n        return Number.prototype.toString.call(x, /** @type {?} */(radix));\n      } catch (e) {\n        throw intrp.errorNativeToPseudo(e, intrp.thread_.perms());\n      }\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Number.prototype.valueOf', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return thisNumberValue(intrp, thisVal,\n          'Number.prototype.valueOf', state.scope.perms);\n    }\n  });\n};\n\n/**\n * Initialize the Date class.\n * @private\n */\nInterpreter.prototype.initDate_ = function() {\n  var intrp = this;\n  var wrapper;\n  // Date prototype.  As of ES6 this is just an ordinary object.  (In\n  // ES5 it had [[Class]] Date.)\n  this.DATE = new this.Object(this.ROOT);\n  this.builtins.set('Date.prototype', this.DATE);\n  // Date constructor.\n  wrapper = function(value, var_args) {\n    if (!intrp.calledWithNew()) {\n      // Called as Date().\n      // Calling Date() as a function returns a string, no arguments are heeded.\n      return Date();\n    }\n    // Called as new Date().\n    var args = [null].concat(Array.from(arguments));\n    var date = new (Function.prototype.bind.apply(Date, args))();\n    return new intrp.Date(date, intrp.thread_.perms());\n  };\n  this.createNativeFunction('Date', wrapper, true);\n\n  // Static methods on Date.\n  this.createNativeFunction('Date.now', Date.now, false);\n  this.createNativeFunction('Date.parse', Date.parse, false);\n  this.createNativeFunction('Date.UTC', Date.UTC, false);\n\n  // Instance methods on Date.\n  new this.NativeFunction({\n    id: 'Date.prototype.toString', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var date = thisVal;\n      if (!(date instanceof intrp.Date)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'Date.prototype.toString is not generic');\n      }\n      // TODO(cpcallen:perms): Perm check here?  Or in toString?\n      return date.toString();\n    }\n  });\n\n  var functions = ['getDate', 'getDay', 'getFullYear', 'getHours',\n      'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime',\n      'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear',\n      'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth',\n      'getUTCSeconds', 'getYear',\n      'setDate', 'setFullYear', 'setHours', 'setMilliseconds',\n      'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate',\n      'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes',\n      'setUTCMonth', 'setUTCSeconds', 'setYear',\n      'toDateString', 'toISOString', 'toJSON', 'toGMTString',\n      'toTimeString', 'toUTCString'];\n  for (var i = 0; i < functions.length; i++) {\n    wrapper = (function(nativeFunc) {\n      return function(var_args) {\n        return this.date[nativeFunc].apply(this.date, arguments);\n      };\n    })(functions[i]);\n    this.createNativeFunction('Date.prototype.' + functions[i], wrapper, false);\n  }\n  functions = ['toLocaleDateString', 'toLocaleString', 'toLocaleTimeString'];\n  for (var i = 0; i < functions.length; i++) {\n    wrapper = (function(nativeFunc) {\n      return function(/*locales, options*/) {\n        // Messing around with arguments so that function's length is 0.\n        var locales = arguments.length > 0 ?\n            intrp.pseudoToNative(arguments[0]) : undefined;\n        var options = arguments.length > 1 ?\n            intrp.pseudoToNative(arguments[1]) : undefined;\n        return this.date[nativeFunc].call(this.date, locales, options);\n      };\n    })(functions[i]);\n    this.createNativeFunction('Date.prototype.' + functions[i], wrapper, false);\n  }\n};\n\n/**\n * Initialize Regular Expression object.\n * @private\n */\nInterpreter.prototype.initRegExp_ = function() {\n  var intrp = this;\n  var wrapper;\n  // RegExp prototype.  As of ES6 this is just an ordinary object.\n  // (In ES5 it had [[Class]] RegExp.)\n  this.REGEXP = new this.Object(this.ROOT);\n  this.builtins.set('RegExp.prototype', this.REGEXP);\n\n  // RegExp constructor.\n  new this.NativeFunction({\n    id: 'RegExp', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var pattern = args[0];\n      var flags = args[1];\n      if (pattern instanceof intrp.RegExp && flags === undefined) {\n        // Per ES6 §21.2.3.1 step 4.b, (now\n        // https://tc39.es/ecma262/#sec-regexp-constructor step 2.b),\n        // check pattern.constructor to see if it's RegExp.\n        var patternConstructor = pattern.get('constructor', state.scope.perms);\n        if (patternConstructor === this) return pattern;\n      }\n      return this.construct.call(this, intrp, thread, state, args);\n    },\n    /** @type {!Interpreter.NativeConstructImpl} */\n    construct: function(intrp, thread, state, args) {\n      var pattern = args[0];\n      var flags = args[1];\n      var perms = state.scope.perms;\n      if (pattern instanceof intrp.RegExp) {\n        pattern = pattern.regexp.source;\n        // ES5.1 required that TypeError be thown here if flags !==\n        // undefined, but ES6 and later do not.\n      }\n      // TODO(ES6): ES6 §21.2.3.1 step 6 (now\n      // https://tc39.es/ecma262/#sec-regexp-constructor step 5).\n      pattern = (pattern === undefined ? '' : String(pattern));\n      flags = (flags === undefined ? '' : String(flags));\n      // TODO(ES6): also accept [uy]; ES8: [s], soon: [p].\n      if (!/^(?:([gim])(?!.*\\1))*$/.test(flags)) {  // Reject repeated flags.\n        throw new intrp.Error(perms, intrp.SYNTAX_ERROR,\n            \"Invalid flags supplied to RegExp constructor '\" + flags + \"'\");\n      }\n      return new intrp.RegExp(new RegExp(pattern, flags), perms);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'RegExp.prototype.toString', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var regexp= thisVal;\n      if (!(regexp instanceof intrp.RegExp)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'RegExp.prototype.toString is not generic');\n      }\n      // TODO(cpcallen:perms): Perm check here?  Or in toString?\n      return regexp.toString();\n    }\n  });\n\n  wrapper = function(str) {\n    if (!(this instanceof intrp.RegExp) ||\n        !(this.regexp instanceof RegExp)) {\n      throw new intrp.Error(intrp.thread_.perms(), intrp.TYPE_ERROR,\n          'Method RegExp.prototype.exec called on incompatible receiver' +\n              this);\n    }\n    return this.regexp.test(str);\n  };\n  this.createNativeFunction('RegExp.prototype.test', wrapper, false);\n\n  wrapper = function(str) {\n    var perms = intrp.thread_.perms();\n    if (!(this instanceof intrp.RegExp)) {\n      throw new intrp.Error(perms, intrp.TYPE_ERROR,\n          'Method RegExp.prototype.exec called on incompatible receiver ' +\n          this);\n    }\n    str = String(str);\n    // Get lastIndex from wrapped regex, since this is settable.\n    this.regexp.lastIndex = this.get('lastIndex', perms);\n    var match = this.regexp.exec(str);\n    this.set('lastIndex', this.regexp.lastIndex, perms);\n\n    if (match) {\n      var result = new intrp.Array(perms);\n      for (var i = 0; i < match.length; i++) {\n        result.set(String(i), match[i], perms);\n      }\n      // match has additional properties.\n      result.set('index', match.index, perms);\n      result.set('input', match.input, perms);\n      return result;\n    }\n    return null;\n  };\n  this.createNativeFunction('RegExp.prototype.exec', wrapper, false);\n};\n\n/**\n * Initialize the Error class.\n * @private\n */\nInterpreter.prototype.initError_ = function() {\n  var intrp = this;\n\n  var createErrorClass = function(name, protoKey) {\n    var protoproto = name === 'Error' ? intrp.OBJECT : intrp.ERROR;\n    var proto = new intrp.Error(intrp.ROOT, protoproto);\n    intrp.builtins.set(name + '.prototype', proto);\n    new intrp.NativeFunction({\n      id: name, name: name, length: 1,\n      /** @type {!Interpreter.NativeConstructImpl} */\n      construct: function(intrp, thread, state, args) {\n        var message = (args[0] === undefined) ? undefined : String(args[0]);\n        var perms = state.scope.perms;\n        // Use intrp[protoKey] instead of proto because\n        // deserialisation will set up intrp.ERROR et al correctly but\n        // can't modify values of variables in native closures.\n        /** @suppress {checkTypes} */\n        var err = new intrp.Error(perms, intrp[protoKey], message);\n        err.makeStack(thread.callers(perms).slice(1), perms);\n        return err;\n      },\n      /** @type {!Interpreter.NativeCallImpl} */\n      call: function(intrp, thread, state, thisVal, args) {\n        return this.construct.call(this, intrp, thread, state, args);\n      }\n    });\n    return proto;\n  };\n\n  intrp.ERROR = createErrorClass('Error', 'ERROR');  // Must be first!\n  intrp.EVAL_ERROR = createErrorClass('EvalError', 'EVAL_ERROR');\n  intrp.RANGE_ERROR = createErrorClass('RangeError', 'RANGE_ERROR');\n  intrp.REFERENCE_ERROR = createErrorClass('ReferenceError', 'REFERENCE_ERROR');\n  intrp.SYNTAX_ERROR = createErrorClass('SyntaxError', 'SYNTAX_ERROR');\n  intrp.TYPE_ERROR = createErrorClass('TypeError', 'TYPE_ERROR');\n  intrp.URI_ERROR = createErrorClass('URIError', 'URI_ERROR');\n  intrp.PERM_ERROR = createErrorClass('PermissionError', 'PERM_ERROR');\n\n  this.createNativeFunction('Error.prototype.toString',\n                            this.Error.prototype.toString, false);\n};\n\n/**\n * Initialize Math object.\n * @private\n */\nInterpreter.prototype.initMath_ = function() {\n  var numFunctions = ['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2',\n      'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor',\n      'fround', 'hypot', 'imul', 'log', 'log10', 'log1p', 'log2', 'max', 'min',\n      'pow', 'random', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh',\n      'trunc'];\n  for (var i = 0; i < numFunctions.length; i++) {\n    this.createNativeFunction('Math.' + numFunctions[i], Math[numFunctions[i]],\n                              false);\n  }\n};\n\n/**\n * Initialize JSON object.\n * @private\n */\nInterpreter.prototype.initJSON_ = function() {\n  var intrp = this;\n  var wrapper;\n  wrapper = function(text) {\n    try {\n      var nativeObj = JSON.parse(String(text));\n    } catch (e) {\n      throw intrp.errorNativeToPseudo(e, intrp.thread_.perms());\n    }\n    return intrp.nativeToPseudo(nativeObj, intrp.thread_.perms());\n  };\n  this.createNativeFunction('JSON.parse', wrapper, false);\n\n  wrapper = function(value, replacer, space) {\n    var nativeObj = intrp.pseudoToNative(value);\n    var perms = intrp.thread_.perms();\n    if (replacer instanceof intrp.Function) {\n      throw new intrp.Error(perms, intrp.TYPE_ERROR,\n          'Function replacer on JSON.stringify not supported');\n    } else if (replacer instanceof intrp.Array) {\n      replacer = intrp.createListFromArrayLike(replacer, perms);\n      replacer = replacer.filter(function(word) {\n        // Spec says we should also support boxed primitives here.\n        return typeof word === 'string' || typeof word === 'number';\n      });\n    } else {\n      replacer = null;\n    }\n    // Spec says we should also support boxed primitives here.\n    if (typeof space !== 'string' && typeof space !== 'number') {\n      space = undefined;\n    }\n    try {\n      var str = JSON.stringify(nativeObj, replacer, space);\n    } catch (e) {\n      throw intrp.errorNativeToPseudo(e, perms);\n    }\n    return str;\n  };\n  this.createNativeFunction('JSON.stringify', wrapper, false);\n};\n\n/**\n * Initialize the WeakMap class.\n * @private\n */\nInterpreter.prototype.initWeakMap_ = function() {\n  // WeakMap prototype.\n  this.WEAKMAP = new this.Object(this.ROOT);\n  this.builtins.set('WeakMap.prototype', this.WEAKMAP);\n\n  // WeakMap constructor.\n  new this.NativeFunction({\n    id: 'WeakMap', length: 0,  // N.B. length is correct; arg is optional!\n    /** @type {!Interpreter.NativeConstructImpl} */\n    construct: function(intrp, thread, state, args) {\n      // TODO(cpcallen): Support iterable argument to populate map.\n      return new intrp.WeakMap(state.scope.perms);\n    }\n  });\n\n  // Properties of the WeakMap prototype object.\n\n  /**\n   * A narrowing of Interpreter.NativeCallImpl for decorated WeakMap\n   * .call implementations.\n   * @typedef {function(this: Interpreter.prototype.NativeFunction,\n   *                    !Interpreter,\n   *                    !Interpreter.Thread,\n   *                    !Interpreter.State,\n   *                    !Interpreter.prototype.WeakMap,\n   *                    !Array<?Interpreter.Value>)\n   *               : (?Interpreter.Value|!Interpreter.FunctionResult)}\n   */\n  var WeakMapCallImpl;\n  \n  /**\n   * Decorator to add standard permission and type checks for WeakMap\n   * prototype methods.\n   * @param {!WeakMapCallImpl} func Function to decorate.\n   * @param {string=} name Name of decorated function (default:\n   *     func.name).  (N.B. needed because 'delete' is a reserve word.\n   * @return {!Interpreter.NativeCallImpl} The decorated function.)\n   */\n  var withChecks = function(func, name) {\n    name = (name === undefined ? func.name : name);\n    return function call(intrp, thred, state, thisVal, args) {\n      // TODO(cpcallen:perms): add controls()-type and/or\n      // object-readability check(s) here.\n      if (!(thisVal instanceof intrp.WeakMap)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'Method WeakMap.prototype.' + name +\n            ' called on incompatible receiver ' + String(thisVal));\n      } else if (!(args[0] instanceof intrp.Object)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'Invalid value used as weak map key');\n      }\n      return func.apply(this, arguments);\n    };\n  };\n\n  new this.NativeFunction({\n    id: 'WeakMap.prototype.delete', length: 1,\n    call: withChecks(function(intrp, thread, state, thisVal, args) {\n      return thisVal.weakMap.delete(args[0]);\n    }, 'delete')\n  });\n\n  new this.NativeFunction({\n    id: 'WeakMap.prototype.get', length: 1,\n    call: withChecks(function get(intrp, thread, state, thisVal, args) {\n      return thisVal.weakMap.get(args[0]);\n    })\n  });\n\n  new this.NativeFunction({\n    id: 'WeakMap.prototype.has', length: 1,\n    call: withChecks(function has(intrp, thread, state, thisVal, args) {\n      return thisVal.weakMap.has(args[0]);\n    })\n  });\n\n  new this.NativeFunction({\n    id: 'WeakMap.prototype.set', length: 2,\n    call: withChecks(function set(intrp, thread, state, thisVal, args) {\n      thisVal.weakMap.set(args[0], args[1]);\n      return thisVal;\n    })\n  });\n};\n\n/**\n * Initialize the thread system API.\n * @private\n */\nInterpreter.prototype.initThread_ = function() {\n  // Thread prototype.\n  this.THREAD = new this.Object(this.ROOT);\n  this.builtins.set('Thread.prototype', this.THREAD);\n\n  /* Thread constructor.  Usage:\n   *\n   *     var thread = new Thread(func, delay, thisArg, ...args);\n   *\n   * - func is function to run in thread.  (Maybe in future we will\n   *   accept src to eval, but not for now.)\n   * - delay is time to wait (in ms) before starting thread.\n   * - thisArg is the 'this' value to use for the call (as if via .apply).\n   * - ...args are additional arguments to pass to func.\n   */\n  new this.NativeFunction({\n    id: 'Thread', length: 1,\n    /** @type {!Interpreter.NativeConstructImpl} */\n    construct: function(intrp, thread, state, args) {\n      var func = args[0];\n      var delay = Number(args[1]) || 0;\n      var thisArg = args[2];\n      args = args.slice(3);\n      var perms = state.scope.perms;\n      if (!(func instanceof intrp.Function)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            func + ' is not a function');\n      }\n      return intrp.createThreadForFuncCall(\n          perms, func, thisArg, args, intrp.now() + delay, thread.timeLimit);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Thread.current', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return thread.wrapper;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Thread.kill', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var t = args[0];\n      var perms = state.scope.perms;\n      if (!(t instanceof intrp.Thread)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR, t + ' is not a Thread');\n      }\n      // TODO(cpcallen:perms): add security check here.\n      var id = t.thread.id;\n      if (intrp.threads_[id]) {\n        intrp.threads_[id].status = Interpreter.Thread.Status.ZOMBIE;\n      }\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Thread.suspend', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var delay = Number(args[0]) || 0;\n      if (delay < 0) {\n        delay = 0;\n      }\n      thread.runAt = intrp.now() + delay;\n      return Interpreter.FunctionResult.Sleep;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Thread.callers', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = state.scope.perms;\n      var frames = thread.callers(state.scope.perms);\n      var callers = [];\n      for (var i = 1, frame; (frame = frames[i]); i++) {\n        var caller = new intrp.Object(perms);\n        // Copy properties of frame to caller.\n        for (var key in frame) {\n          if (!frame.hasOwnProperty(key)) continue;\n          var value = frame[key];\n          if (typeof value === 'function' || typeof value === 'object' &&\n              !(value instanceof intrp.Object) && value !== null) {\n            throw new TypeError('Unexpected native object');\n          }\n          caller.defineProperty(key, Descriptor.wec.withValue(value), perms);\n        }\n        callers.push(caller);\n      }\n      return intrp.createArrayFromList(callers, perms);\n    }\n  });\n\n  // Properties of the Thread prototype object.\n\n  /**\n   * A narrowing of Interpreter.NativeCallImpl for decorated Thread\n   * .call implementations.\n   * @typedef {function(this: Interpreter.prototype.NativeFunction,\n   *                    !Interpreter,\n   *                    !Interpreter.Thread,\n   *                    !Interpreter.State,\n   *                    !Interpreter.prototype.Thread,\n   *                    !Array<?Interpreter.Value>)\n   *               : (?Interpreter.Value|!Interpreter.FunctionResult)}\n   */\n  var ThreadCallImpl;\n\n  /**\n   * Decorator to add standard permission and type checks for Thread\n   * prototype methods.\n   * @param {!ThreadCallImpl} func Function to decorate.\n   * @return {!Interpreter.NativeCallImpl} The decorated function.)\n   */\n  var withChecks = function(func) {\n    name = (name === undefined) ? func.name : name;\n    return function call(intrp, thred, state, thisVal, args) {\n      // TODO(cpcallen:perms): add controls()-type and/or\n      // object-readability check(s) here.\n      if (!(thisVal instanceof intrp.Thread)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'Method Thread.prototype.' + name +\n            ' called on incompatible receiver ' + String(thisVal));\n      }\n      return func.apply(this, arguments);\n    };\n  };\n\n  new this.NativeFunction({\n    id: 'Thread.prototype.getTimeLimit', length: 0,\n    call: withChecks(function getTimeLimit(\n        intrp, thread, state, thisVal, args) {\n      return thisVal.thread.timeLimit;\n    })\n  });\n\n  // BUG(cpcallen): this only sets the time limit for future slices;\n  // until suspend is called the current Thread will run with its\n  // existing limit.\n  new this.NativeFunction({\n    id: 'Thread.prototype.setTimeLimit', length: 1,\n    call: withChecks(function setTimeLimit(\n        intrp, thread, state, thisVal, args) {\n      var limit = args[0];\n      var perms = state.scope.perms;\n      var old = thisVal.thread.timeLimit || Number.MAX_VALUE;\n      if (typeof limit !== 'number' || Number.isNaN(limit)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'new limit must be a number (and not NaN)');\n      } else if (limit <= 0) {\n        throw new intrp.Error(perms, intrp.RANGE_ERROR,\n            'new limit must be > 0');\n      } else if (limit > old) {\n        throw new intrp.Error(perms, intrp.RANGE_ERROR,\n            'new limit must be <= previous limit');\n      }\n      thisVal.thread.timeLimit = limit;\n    })\n  });\n};\n\n/**\n * Initialize the permissions model API.\n * @private\n */\nInterpreter.prototype.initPerms_ = function() {\n  // Create object, never available to userland, to be used to\n  // rpresent the permissions of \"a generic user\" when such a thing is\n  // needed (e.g., for internal toString implementations, which have\n  // no information about caller perms but need to access properties\n  // on the object - something which can't be done with the null\n  // permissions).\n  var anybody = new this.Object(null, this.OBJECT);\n  this.ANYBODY = /** @type {!Interpreter.Owner} */ (anybody);\n\n  new this.NativeFunction({\n    id: 'perms', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      return /** @type {!Interpreter.prototype.Object} */ (state.scope.perms);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'setPerms', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var perms = args[0];\n      if (!(perms instanceof intrp.Object)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'New perms must be an object');\n      }\n      // TODO(cpcallen:perms): throw if current perms does not\n      // control new perms.\n      state.scope.perms = /** @type {!Interpreter.Owner} */ (perms);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.getOwnerOf', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var obj = args[0];\n      if (!(obj instanceof intrp.Object)) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            \"Can't get owner of non-object\");\n      }\n      return /** @type {?Interpreter.prototype.Object} */(obj.owner);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'Object.setOwnerOf', length: 0,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var obj = args[0];\n      var owner = args[1];\n      var perms = state.scope.perms;\n      if (!(obj instanceof intrp.Object)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            \"Can't set owner of non-object\");\n      }\n      if (!(owner instanceof intrp.Object) && owner !== null) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            'New owner must be an object or null');\n      }\n      // TODO(cpcallen:perms): throw if current perms does not\n      // control obj and (new) owner.\n      obj.owner = /** @type {?Interpreter.Owner} */(owner);\n      return obj;\n    }\n  });\n};\n\n/**\n * Initialize the networking subsystem API.\n * @private\n */\nInterpreter.prototype.initNetwork_ = function() {\n  new this.NativeFunction({\n    id: 'CC.connectionListen', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var port = args[0];\n      var proto = args[1];\n      var timeLimit = Number(args[2]) || thread.timeLimit;\n      var perms = state.scope.perms;\n      if (port !== (port >>> 0) || port > 0xffff) {\n        throw new intrp.Error(perms, intrp.RANGE_ERROR, 'invalid port');\n      } else if (port in intrp.listeners_) {\n        throw new intrp.Error(perms, intrp.RANGE_ERROR,\n            'port already listened');\n      }\n      if (!(proto instanceof intrp.Object)) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n           'prototype argument to connectionListen must be an object');\n      }\n      // TODO(cpcallen): do validity check on timeLimit.  It should\n      // probaly not be larger than current limit (unless root).\n      var server = new intrp.Server(perms, port, proto, timeLimit);\n      intrp.listeners_[port] = server;\n      var rr = intrp.getResolveReject(thread, state);\n      server.listen(function(error) {\n        if (!error) {\n          rr.resolve();\n        } else {\n          rr.reject(intrp.errorNativeToPseudo(error, perms), perms);\n        }\n      });\n      return Interpreter.FunctionResult.Block;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'CC.connectionUnlisten', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var port = args[0];\n      var perms = state.scope.perms;\n      if (port !== (port >>> 0) || port > 0xffff) {\n        throw new intrp.Error(perms, intrp.RANGE_ERROR, 'invalid port');\n      } else if (!(port in intrp.listeners_)) {\n        throw new intrp.Error(perms, intrp.RANGE_ERROR, 'port not listening');\n      }\n      if (!(intrp.listeners_[port].server_ instanceof net.Server)) {\n        throw new Error('no net.Serfer object for port %s??', port);\n      }\n      var rr = intrp.getResolveReject(thread, state);\n      intrp.listeners_[port].unlisten(function() {\n        // Socket (and all open connections on it) now closed.\n        delete intrp.listeners_[/** @type {number} */(port)];\n        rr.resolve();\n      });\n      return Interpreter.FunctionResult.Block;\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'CC.connectionWrite', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var obj = args[0];\n      var data = args[1];\n      if (!(obj instanceof intrp.Object) || !obj.socket) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'object is not connected');\n      } else if (typeof data !== 'string') {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'data is not a string');\n      }\n      obj.socket.write(data);\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'CC.connectionClose', length: 2,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var obj = args[0];\n      if (!(obj instanceof intrp.Object) || !obj.socket) {\n        throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n            'object is not connected');\n      }\n      obj.socket.end();\n    }\n  });\n\n  new this.NativeFunction({\n    id: 'CC.xhr', length: 1,\n    /** @type {!Interpreter.NativeCallImpl} */\n    call: function(intrp, thread, state, thisVal, args) {\n      var url = String(args[0]);\n      var perms = state.scope.perms;\n      if (url.match(/^http:\\/\\//)) {\n        var req = http.get(url);\n      } else if (url.match(/^https:\\/\\//)) {\n        req = https.get(url);\n      } else {\n        throw new intrp.Error(perms, intrp.SYNTAX_ERROR,\n            'Unrecognized URL \"' + url + '\"');\n      }\n      intrp.log('net', 'XHR for %s: connect', url);\n      var rr = intrp.getResolveReject(thread, state);\n      req.on('response', function(res) {\n        intrp.log('net', 'XHR for %s: response', url);\n        if (res.statusCode !== 200) {\n          var err = new intrp.Error(perms, intrp.ERROR,\n              'HTTP request failed: ' + res.statusCode + ' ' +\n              res.statusMessage);\n          err.set('statusCode', Number(res.statusCode), perms);\n          err.set('statusMessage', String(res.statusMessage), perms);\n          res.resume();\n          rr.reject(err, perms);\n          return;\n        }\n        var body = '';\n        res.on('data', function(data) {\n          body += String(data);\n        });\n        res.on('end', function() {\n          intrp.log('net', 'XHR for %s: end', url);\n          rr.resolve(body);\n        });\n      }).on('error', function(e) {\n        intrp.log('net', 'XHR for %s: %s', url, e);\n        rr.reject(intrp.errorNativeToPseudo(e, perms), perms);\n      });\n      return Interpreter.FunctionResult.Block;\n    }\n  });\n};\n\n/**\n * The ToInteger function from ES6 §7.1.4.  The abstract operation\n * ToInteger converts argument to an integral numeric value.\n * @param {?Interpreter.Value} value\n * @return {number} An integer if the value can be converted to such;\n *     0 otherwise.\n */\nInterpreter.toInteger = function toInteger(value) {\n  var number = Number(value);\n  if (isNaN(number)) {\n    return 0;\n  } else if (number === 0 || !isFinite(number)) {\n    return number;\n  }\n  return Math.trunc(number);\n};\n\n/**\n * The ToUint32 function from ES6 §7.1.6.  The abstract operation\n * ToUint32 converts argument to one of 2**32 integer values in the\n * range 0 through 2**32−1, inclusive.\n * @param {?Interpreter.Value} value\n * @return {number} A non-negative integer less than 2**32.\n */\nInterpreter.toUint32 = function toUint32(value) {\n  return Interpreter.toInteger(value) >>> 0;\n};\n\n/**\n * The ToLength function from ES6 §7.1.15.  Note that this does NOT\n * enforce the actual array length limit of 2**32-1, but deals with\n * lengths up to 2**53-1, which is correct for the polymorphic\n * Array.prototype methods.\n * @param {?Interpreter.Value} value\n * @return {number} A non-negative integer less than 2**53.\n */\nInterpreter.toLength = function toLength(value) {\n  var len = Interpreter.toInteger(value);\n  if (len <= 0) return 0;\n  return Math.min(len, Number.MAX_SAFE_INTEGER);  // Handles len === Infinity.\n};\n\n/**\n * Create a new native function.  Function will be owned by root.\n * @param {string} id ID to register new function in builtins registry.\n * @param {!Function} nativeFunc Any JavaScript function.\n * @param {boolean} legalConstructor True if the function can be used as a\n *     constructor (e.g. Array), false if not (e.g. escape).\n * @return {!Interpreter.prototype.Function} New function.\n*/\nInterpreter.prototype.createNativeFunction = function(\n    id, nativeFunc, legalConstructor) {\n  if (nativeFunc instanceof this.Object) {\n    throw new TypeError('createNativeFunction passed non-native function??');\n  }\n  // Make sure impl function has an id for serialization.\n  if (!nativeFunc.id) nativeFunc.id = id;\n  return new this.OldNativeFunction(nativeFunc, legalConstructor, {id: id});\n};\n\n/**\n * Converts from a native JS object or value to a JS interpreter\n * object.  Can handle JSON-style values plus regexps and errors (of\n * all standard native types), and handles additional properties on\n * arrays, regexps and errors (just as for plain objects).  Ignores\n * prototype and inherited properties.  Efficiently handles\n * sparse arrays.  Does NOT handle cyclic structures.\n * @param {*} nativeObj The native JS object to be converted.\n * @return {?Interpreter.Value} The equivalent JS interpreter object.\n * @param {!Interpreter.Owner} owner Owner for new object.\n */\nInterpreter.prototype.nativeToPseudo = function(nativeObj, owner) {\n  if ((typeof nativeObj !== 'object' && typeof nativeObj !== 'function') ||\n      nativeObj === null) {\n    // It's a primitive; just return it.\n    return /** @type {boolean|number|string|undefined|null} */ (nativeObj);\n  } else if (nativeObj instanceof this.Object) {\n    throw new TypeError('nativeToPseudo called on a pseudo-object??');\n  }\n\n  var pseudoObj;\n  switch (Object.prototype.toString.apply(nativeObj)) {\n    case '[object Array]':\n      pseudoObj = new this.Array(owner);\n      break;\n    case '[object RegExp]':\n      pseudoObj = new this.RegExp(/** @type {!RegExp} */(nativeObj), owner);\n      break;\n    case '[object Error]':\n      var proto;\n      if (nativeObj instanceof EvalError) {\n        proto = this.EVAL_ERROR;\n      } else if (nativeObj instanceof RangeError) {\n        proto = this.RANGE_ERROR;\n      } else if (nativeObj instanceof ReferenceError) {\n        proto = this.REFERENCE_ERROR;\n      } else if (nativeObj instanceof SyntaxError) {\n        proto = this.SYNTAX_ERROR;\n      } else if (nativeObj instanceof TypeError) {\n        proto = this.TYPE_ERROR;\n      } else if (nativeObj instanceof URIError) {\n        proto = this.URI_ERROR;\n      } else {\n        proto = this.ERROR;\n      }\n      pseudoObj = new this.Error(owner, proto);\n      break;\n    default:\n      pseudoObj = new this.Object(owner);\n  }\n\n  // Cast to satisfy type-checker; it might be a lie: nativeObj could\n  // be an object (i.e., non-primitive) but not an Object (i.e.,\n  // inherits from Object.prototype).  Fortunately we don't care.\n  var keys = Object.getOwnPropertyNames(/** @type {!Object} */(nativeObj));\n  for (var i = 0; i < keys.length; i++) {\n    var key = keys[i];\n    var desc = Object.getOwnPropertyDescriptor(nativeObj, key);\n    var pd = new Descriptor(desc.writable, desc.enumerable, desc.configurable);\n    pd.value = this.nativeToPseudo(desc.value, owner);\n    pseudoObj.defineProperty(key, pd, owner);\n  }\n  return pseudoObj;\n};\n\n/**\n * Converts from a JS interpreter object to native JS object.\n * Can handle JSON-style values, plus cycles.\n *\n * TODO(cpcallen): Audit this to ensure that it can safely accept any\n * user object (especially because it is used by our implementations\n * of JSON.stringify, String.prototype.localeCompare, etc.)\n *\n * TODO(cpcallen:perms): Audit all callers of this to ensure that they\n * do not allow circumvention of access control.\n * @param {?Interpreter.Value} pseudoObj The JS interpreter object to\n *     be converted.\n * @param {!Object=} cycles Cycle detection (used only in recursive calls).\n * @return {*} The equivalent native JS object or value.\n */\nInterpreter.prototype.pseudoToNative = function(pseudoObj, cycles) {\n  // BUG(cpcallen:perms): Kludge.  Incorrect except when doing .step\n  // or run.  Should be an argument instead, forcing caller to decide.\n  try {\n    var perms = this.thread_.perms();\n  } catch (e) {\n    perms = this.ROOT;\n  }\n  if (typeof pseudoObj === 'boolean' ||\n      typeof pseudoObj === 'number' ||\n      typeof pseudoObj === 'string' ||\n      pseudoObj === null || pseudoObj === undefined) {\n    // It's a primitive; just return it.\n    return pseudoObj;\n  } else if (!(pseudoObj instanceof this.Object)) {\n    throw new TypeError('pseudoToObject called on wrong type??');\n  } else if (pseudoObj instanceof this.RegExp) {  // Regular expression.\n    return pseudoObj.regexp;\n  } else if (pseudoObj instanceof this.Function) {  // Function.\n    return undefined;\n  }\n\n  if (!cycles) {\n    cycles = {pseudo: [], native: []};\n  }\n  var i = cycles.pseudo.indexOf(pseudoObj);\n  if (i !== -1) {\n    return cycles.native[i];\n  }\n  cycles.pseudo[cycles.pseudo.length] = pseudoObj;\n  var nativeObj = pseudoObj instanceof this.Array ? [] : {};\n  cycles.native[cycles.native.length] = nativeObj;\n  var keys = pseudoObj.ownKeys(perms);\n  for (i = 0; i < keys.length; i++) {\n    var key = keys[i];\n    var pd = pseudoObj.getOwnPropertyDescriptor(key, perms);\n    Object.defineProperty(nativeObj, key, {\n      writable: pd.writable,\n      enumerable: pd.enumerable,\n      configurable: pd.configurable,\n      value: this.pseudoToNative(pd.value, cycles)\n    });\n  }\n  cycles.pseudo.pop();\n  cycles.native.pop();\n  return nativeObj;\n};\n\n/**\n * CreateArrayFromList from ES6 §7.3.16\n *\n * Converts from a native array to an Interpreter.prototype.Array.\n * Does NOT recursively convert the type of the array's contents.\n * @param {!Array<?Interpreter.Value>} elements The native array to be\n *     converted.\n * @param {!Interpreter.Owner} owner Owner for new object.\n * @return {!Interpreter.prototype.Array} The equivalent interpreter array.\n */\nInterpreter.prototype.createArrayFromList = function(elements, owner) {\n  if (!Array.isArray(elements) || (elements instanceof this.Object)) {\n    throw new TypeError('CreateArrayFromList called on wrong type??');\n  }\n  var array = new this.Array(owner);\n  for (var n = 0; n < elements.length; n++) {\n    array.defineProperty(\n        String(n), Descriptor.wec.withValue(elements[n]), owner);\n  }\n  return array;\n};\n\n/**\n * CreateListFromArrayLike from ES6 §7.3.17.\n *\n * This function converts from an Interpreter.prototype.Array (or\n * array-like I.p.Object) to a native array.  This is an evolution of\n * the algorithm from ES5.1 §15.3.4.3 (Function.prototype.apply).  It\n * does NOT recursively convert the type of the array's contents.\n *\n * TODO(ES6): Add elementTypes param and associated type checks.\n * @param {?Interpreter.Value} obj The interpreter array or array-like\n *     object to be converted.  Error thrown if non-object.\n * @param {!Interpreter.Owner} perms Who is trying convert it?\n * @return {!Array<?Interpreter.Value>} The equivalent native JS array.\n */\nInterpreter.prototype.createListFromArrayLike = function(obj, perms) {\n  if (!(obj instanceof this.Object)) {\n    throw new this.Error(perms, this.TYPE_ERROR,\n        'CreateListFromArrayLike called on non-object');\n  }\n  var len = Interpreter.toLength(obj.get('length', perms));\n  var list = [];\n  for (var i = 0; i < len; i++) {\n    list[i] = obj.get(String(i), perms);\n  }\n  return list;\n};\n\n/**\n * Converts from a native Error to a JS interpreter Error.  Unlike\n * pseudoToNative, this fucntion only converts type and .message.\n * @param {!Error} err Native Error value to be converted.\n * @param {?Interpreter.Owner} owner Owner for new (pseudo) Error object.\n * @return {!Interpreter.prototype.Error}\n */\nInterpreter.prototype.errorNativeToPseudo = function(err, owner) {\n  var proto;\n  if (err instanceof this.Object) {\n    throw new TypeError('errorNativeToPseudo called on wrong type??');\n  }\n\n  if (err instanceof EvalError) {\n    proto = this.EVAL_ERROR;\n  } else if (err instanceof RangeError) {\n    proto = this.RANGE_ERROR;\n  } else if (err instanceof ReferenceError) {\n    proto = this.REFERENCE_ERROR;\n  } else if (err instanceof SyntaxError) {\n    proto = this.SYNTAX_ERROR;\n  } else if (err instanceof TypeError) {\n    proto = this.TYPE_ERROR;\n  } else if (err instanceof URIError) {\n    proto = this.URI_ERROR;\n  } else {\n    proto = this.ERROR;\n  }\n  return new this.Error(owner, proto, err.message);\n};\n\n/**\n * Implements the ToObject specification method from ES5.1 §9.9 / ES6\n * §7.1.13, but returning temporary Box objects instead of boxed\n * Boolean, Number or String instances.\n * @param {?Interpreter.Value} value The value to be converted to an Object.\n * @param {!Interpreter.Owner} perms Who is trying convert it?\n * @return {!Interpreter.ObjectLike}\n */\nInterpreter.prototype.toObject = function(value, perms) {\n  if (value === null || value === undefined) {\n    throw new this.Error(perms, this.TYPE_ERROR,\n        \"Can't convert \" + value + ' to Object');\n  } else if (typeof value === 'boolean' || typeof value === 'number' ||\n      typeof value === 'string') {\n    return new this.Box(value);\n  }\n  return value;\n};\n\n/**\n * Retrieves a value from the scope chain.\n * @param {!Interpreter.Scope} scope Scope to read from.\n * @param {string} name Name of variable.\n * @return {?Interpreter.Value} Value (may be undefined).\n */\nInterpreter.prototype.getValueFromScope = function(scope, name) {\n  for (var s = scope; s; s = s.outerScope) {\n    if (name in s.vars) {\n      return s.vars[name];\n    }\n  }\n  throw new this.Error(this.thread_.perms(), this.REFERENCE_ERROR,\n      name + ' is not defined');\n};\n\n/**\n * Sets a value to the current scope.\n * @param {!Interpreter.Scope} scope Scope to write to.\n * @param {string} name Name of variable.\n * @param {?Interpreter.Value} value Value.\n */\nInterpreter.prototype.setValueToScope = function(scope, name, value) {\n  for (var s = scope; s; s = s.outerScope) {\n    if (name in s.vars) {\n      try {\n        s.vars[name] = value;\n      } catch (e) {  // Trying to set immutable binding.\n        // TODO(cpcallen:perms): we have a scope here, but scope.perms\n        // is probably not the right value for owner of new error.\n        throw new this.Error(this.thread_.perms(), this.TYPE_ERROR,\n            'Assignment to constant variable ' + name);\n      }\n      return;\n    }\n  }\n  throw new this.Error(this.thread_.perms(), this.REFERENCE_ERROR,\n      name + ' is not defined');\n};\n\n/**\n * Populate a scope with declarations from given node.\n * @param {!Node} node AST node (program or function).\n * @param {!Interpreter.Scope} scope Scope dictionary to populate.\n * @param {!Interpreter.Source=} source Original source code.  If not\n *     supplied, will use node['source'] instead.\n * @private\n */\nInterpreter.prototype.populateScope_ = function(node, scope, source) {\n  if (!source) {\n    if (!node['source']) throw new Error('Source not found');\n    source = node['source'];\n  }\n  // Obtain list of bound names for node.  We cache this on the AST\n  // node to save time when repeatedly calling the same function.\n  var boundNames = getBoundNames(node);\n  for (var name in boundNames) {\n    var boundValue = boundNames[name];\n    var value = boundValue ?\n        new this.UserFunction(boundValue, scope, source, scope.perms)\n        : undefined;\n    if (!scope.hasBinding(name)) scope.createMutableBinding(name, value);\n    if (value) this.setValueToScope(scope, name, value);\n  }\n};\n\n/**\n * Is the current state directly being called with as a construction with 'new'.\n * @return {boolean} True if 'new foo()', false if 'foo()'.\n */\nInterpreter.prototype.calledWithNew = function() {\n  return this.thread_.stateStack_[this.thread_.stateStack_.length - 1]\n      .info_.construct;\n};\n\n/**\n * Implements IsUnresolvableReference from ES5 §8.7 / ES6 §6.2.3.\n * @param {!Interpreter.Scope} scope Current scope dictionary.\n * @param {!Array} ref Reference tuple.\n * @param {!Interpreter.Owner} perms Who is trying to get it?\n * @return {boolean} True iff refernece is unresolvable.\n */\nInterpreter.prototype.isUnresolvableReference = function(scope, ref, perms) {\n  // Property references never unresolvable.\n  return ref[0] === null;\n};\n\n/**\n * Gets the value of a referenced name from the scope or object referred to.\n * @param {!Array} ref Reference tuple.\n * @param {!Interpreter.Owner} perms Who is trying to get it?\n * @return {?Interpreter.Value} Value (may be undefined).\n */\nInterpreter.prototype.getValue = function(ref, perms) {\n  var base = ref[0];\n  var name = ref[1];\n  if (base === null) {  // Unresolvable reference.\n    throw new this.Error(perms, this.REFERENCE_ERROR, name + ' is not defined');\n  } else if (base instanceof Interpreter.Scope) {  // An environment reference.\n    return base.get(name);\n  } else {  // A property reference.\n    return this.toObject(base, perms).get(name, perms);\n  }\n};\n\n/**\n * Sets value of a referenced name to the scope or object referred to.\n * @param {!Array} ref Reference tuple.\n * @param {?Interpreter.Value} value Value.\n * @param {!Interpreter.Owner} perms Who is trying to set it?\n */\nInterpreter.prototype.setValue = function(ref, value, perms) {\n  var base = ref[0];\n  var name = ref[1];\n  if (base === null) {  // Unresolvable reference.\n    throw new this.Error(perms, this.REFERENCE_ERROR, name + ' is not defined');\n  } else if (base instanceof Interpreter.Scope) {  // An environment reference.\n    var err = base.set(name, value);\n    if (err) {\n      throw this.errorNativeToPseudo(err, perms);\n    }\n  } else {  // A property reference.\n    this.toObject(ref[0], perms).set(name, value, perms);\n  }\n};\n\n/**\n * Check to see if the current thread has run too long.  Called at the\n * top of loops and before making function calls.\n * @private\n * @param {!Interpreter.Owner} perms Perm to use to create Error object.\n */\nInterpreter.prototype.checkTimeLimit_ = function(perms) {\n  if (this.threadTimeLimit_ && this.now() > this.threadTimeLimit_) {\n    throw new this.Error(perms, this.RANGE_ERROR, 'Thread ran too long');\n  }\n};\n\n\n/**\n * Carry out the mechanics of throwing an exception.\n *\n * This is intended only to be called from exception handlers in\n * .step() and .run(), and from async function's reject() callback.\n * Elsewhere, just throw.\n * @param {!Interpreter.Thread} thread in which throw is occurring.\n * @param {?Interpreter.Value} e Exception being thrown.\n * @param {!Interpreter.Owner} perms Perm to use to obtain (e.g.)\n *     function names, etc.\n */\nInterpreter.prototype.throw_ = function(thread, e, perms) {\n  if (e instanceof this.Error) {\n    // Userland Error object thrown; make sure it has a .stack.\n    // BUG(cpcallen): this will set .stack on Error.prototype, etc.\n    e.makeStack(thread.callers(perms), perms);\n  } else if (e instanceof Error) {\n    // Uh oh.  This is an internal error in the interpreter.  Kill\n    // thread and rethrow.\n    thread.status = Interpreter.Thread.Status.ZOMBIE;\n    throw e;\n  } else if (!(e instanceof this.Object) && e !== null &&\n      (typeof e === 'object' || typeof e === 'function')) {\n    // WTF: not a native exception, not an interpreter object and not\n    // a primitive, but just some random (internal) object.\n    throw new TypeError('Unexpected exception value ' + String(e));\n  }\n  this.unwind_(thread, Interpreter.CompletionType.THROW, e, undefined);\n};\n\n/**\n * Unwind the stack to the innermost relevant enclosing TryStatement,\n * For/ForIn/WhileStatement or Call.  If this results in\n * the stack being completely unwound the thread will be terminated\n * and an appropriate error being logged.\n *\n * N.B. Normally unwind should be called from the current stack frame\n * (i.e., do NOT do stack.pop() before calling unwind) because the\n * target label of a break statement can be the statement itself\n * (e.g., `foo: break foo;`).\n * @private\n * @param {!Interpreter.Thread} thread The thread whose stack is to be unwound.\n * @param {!Interpreter.CompletionType} type Completion type.\n * @param {?Interpreter.Value=} value Value computed, returned or thrown.\n * @param {string=} label Target label for break or return.\n */\nInterpreter.prototype.unwind_ = function(thread, type, value, label) {\n  if (type === Interpreter.CompletionType.NORMAL) {\n    throw new TypeError('Should not unwind for NORMAL completions');\n  }\n  for (var stack = thread.stateStack_; stack.length > 0; stack.pop()) {\n    var state = stack[stack.length - 1];\n    switch (state.node['type']) {\n      case 'TryStatement':\n        state.info_ = {type: type, value: value, label: label};\n        return;\n      case 'Call':\n        switch (type) {\n          case Interpreter.CompletionType.BREAK:\n          case Interpreter.CompletionType.CONTINUE:\n            throw new Error('Unsynatctic break/continue not rejected by Acorn');\n          case Interpreter.CompletionType.RETURN:\n            state.value = value;\n            return;\n        }\n        break;\n    }\n    if (type === Interpreter.CompletionType.BREAK) {\n      if (label ? (state.labels && state.labels.includes(label)) :\n          (state.isLoop || state.isSwitch)) {\n        // Top of stack is now target of break.  But we are breaking\n        // out of this statement, so pop to discard it.\n        stack.pop();\n        return;\n      }\n    } else if (type === Interpreter.CompletionType.CONTINUE) {\n      if (label ? (state.labels && state.labels.includes(label)) :\n          state.isLoop) {\n        return;\n      }\n    }\n  }\n\n  // Unhandled completion.  Terminate thread.\n  thread.status = Interpreter.Thread.Status.ZOMBIE;\n\n  if (type === Interpreter.CompletionType.THROW) {\n    // Log exception and stack trace.\n    if (value instanceof this.Error) {\n      this.log('unhandled', 'Unhandled %s', value);\n      var stackTrace = value.get('stack', this.ROOT);\n      if (stackTrace) {\n        this.log('unhandled', stackTrace);\n      }\n    } else {\n      var native = this.pseudoToNative(value);\n      this.log('unhandled', 'Unhandled exception with value: %o', native);\n    }\n  } else {\n    throw new Error('Unsynatctic break/continue/return not rejected by Acorn');\n  }\n};\n\n/**\n * Get a {resovle, reject} tuple for the specified thread and state,\n * which is presumed to be about to block on an async function call.\n *\n * The resolve function takes a single argument and, when called, will\n * unblock the thread and save its argument in state.value.\n *\n * The reject function takes a single argument and, when called, will\n * unblock the thread and unwind the stack as if its argument had been\n * thrown.\n *\n * Only one of these may be called, and only once, or an internal\n * Error will be thrown.\n * @param {!Interpreter.Thread} thread The thread to be controlled.\n * @param {!Interpreter.State} state The state in which thread to block.\n * @return {{resolve: function(?Interpreter.Value=):void,\n *           reject: function(?Interpreter.Value, !Interpreter.Owner):void}}\n */\nInterpreter.prototype.getResolveReject = function(thread, state) {\n  var /** boolean */ done = false;\n\n  /**\n   * Throw an internal error if previously invoked or if the thread\n   * does not appear to be in a plausible state.\n   */\n  var check = function() {\n    if (done) {\n      throw new Error('Async resolved or rejected more than once??');\n    }\n    done = true;\n    if (thread.status !== Interpreter.Thread.Status.BLOCKED ||\n        thread.stateStack_[thread.stateStack_.length - 1] !== state) {\n      throw new Error('Thread state corrupt at async resolve/reject??');\n    }\n  };\n\n  var intrp = this;\n  return {\n    resolve: function resolve(value) {\n      check();\n      state.value = value;\n      thread.status = Interpreter.Thread.Status.READY;\n      intrp.go_();\n    },\n    reject: function reject(value, perms) {\n      check();\n      thread.status = Interpreter.Thread.Status.READY;\n      intrp.throw_(thread, value, perms);\n      intrp.go_();\n    }\n  };\n};\n\n/**\n * Log something.\n * @param {string} category About what topic is this log?\n * @param {...*} var_args\n */\nInterpreter.prototype.log = function(category, var_args) {\n  if (this.options.noLog && this.options.noLog.includes(category)) {\n    return;\n  }\n  console.log.apply(console, Array.prototype.slice.call(arguments, 1));\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Nested types & constants (not fully-fledged classes)\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * The Completion Specification Type, from ES5.1 §8.9\n * @typedef {{type: Interpreter.CompletionType,\n *            value: ?Interpreter.Value,\n *            label: (string|undefined)}}\n */\nInterpreter.Completion;\n\n/**\n * Completion Value Types.\n * @enum {number}\n */\nInterpreter.CompletionType = {\n  NORMAL: 0,\n  BREAK: 1,\n  CONTINUE: 2,\n  RETURN: 3,\n  THROW: 4\n};\n\n/**\n * Special sentinel values returned by the call or construct method of\n * a (pseudo)Function to indicate that a return value is not\n * immediately available (e.g., in the case of a user function that\n * needs to be evaluated, or an async function that blocks).\n * @constructor\n * @struct\n */\nInterpreter.FunctionResult = function() {};\n/**\n * Please evaluate whatever state(s) have been pushed onto the stack,\n * and use their completion value as the return value of the function.\n * @const\n */\nInterpreter.FunctionResult.AwaitValue = new Interpreter.FunctionResult;\n/**\n * Please mark this thread as blocked awaiting eternal event (e.g.,\n * async callback).\n * @const\n */\nInterpreter.FunctionResult.Block = new Interpreter.FunctionResult;\n/**\n * Please invoke .call or .construct again the next time this state is\n * encountered.\n * @const\n */\nInterpreter.FunctionResult.CallAgain = new Interpreter.FunctionResult;\n/**\n * Please mark this thread as sleeping until its .runAt time.\n * @const\n */\nInterpreter.FunctionResult.Sleep = new Interpreter.FunctionResult;\n\n/**\n * Options object for Interpreter constructor.\n * @typedef {{\n *     noLog: (!Array<string>|undefined),\n *     trimEval: (boolean|undefined),\n *     trimProgram: (boolean|undefined),\n *     stackLimit: (number|undefined),\n * }}\n */\nInterpreter.Options;\n\n/**\n * Interpreter statuses.\n * @enum {number}\n */\nInterpreter.Status = {\n  /**\n   * Won't run code.  Any listening sockets are unlistened.  No time\n   * passes (as measured by .uptime() and .now(), which underly\n   * setTimeout etc.)\n   */\n  STOPPED: 0,\n\n  /**\n   * Will run code *only* if .step() or .run() is called.  Will listen\n   * on network sockets (including re-listening on any that were\n   * unlistened because the interpreter was stopped).  Time will pass\n   * (as measured by .uptime() and .now()).\n   */\n  PAUSED: 1,\n\n  /**\n   * Will run code automatically in response to thread creation,\n   * timeouts and network activity.\n   */\n  RUNNING: 2\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Nested (but not fully inner) classes: Scope, State, Thread, etc.\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Typedef for the functions used to implement NativeFunction.call.\n * @typedef {function(this: Interpreter.prototype.NativeFunction,\n *                    !Interpreter,\n *                    !Interpreter.Thread,\n *                    !Interpreter.State,\n *                    ?Interpreter.Value,\n *                    !Array<?Interpreter.Value>)\n *               : (?Interpreter.Value|!Interpreter.FunctionResult)}\n */\nInterpreter.NativeCallImpl;\n\n/**\n * Typedef for the functions used to implement NativeFunction.construct.\n * @typedef {function(this: Interpreter.prototype.NativeFunction,\n *                    !Interpreter,\n *                    !Interpreter.Thread,\n *                    !Interpreter.State,\n *                    !Array<?Interpreter.Value>)\n *               : (?Interpreter.Value|!Interpreter.FunctionResult)}\n */\nInterpreter.NativeConstructImpl;\n\n/**\n * An iterator over the properties of an ObjectLike and its\n * prototypes, following the usual for-in loop rules.\n * @constructor\n * @struct\n * @param {!Interpreter.ObjectLike} obj Object or Box whose properties\n *     are to be iterated over.\n * @param {!Interpreter.Owner} perms Who is doing the iteration?\n */\nInterpreter.PropertyIterator = function(obj, perms) {\n  if (obj === undefined) {  // Deserializing\n    return;\n  }\n  /** @private @type {?Interpreter.ObjectLike} */\n  this.obj_ = obj;\n  /** @private @const {!Interpreter.Owner} */\n  this.perms_ = perms;\n  /** @private @type {!Array<string>} */\n  this.keys_ = this.obj_.ownKeys(this.perms_);\n  /** @private @type {number} */\n  this.i_ = 0;\n  /** @private @const {!Set<string>} */\n  this.visited_ = new Set();\n};\n\n/**\n * Return the next key in the iteration, skipping non-enumerable keys\n * or keys already seen earlier in the prototype chain (even if they\n * were non-enumerable).  Returns undefined when iteration is done.\n * @return {string|undefined}\n */\nInterpreter.PropertyIterator.prototype.next = function() {\n  while (true) {\n    if (this.i_ >= this.keys_.length) {\n      this.obj_ = this.obj_.proto;\n      if (this.obj_ === null) {\n        // Done iteration.\n        return undefined;\n      }\n      this.keys_ = this.obj_.ownKeys(this.perms_);\n      this.i_ = 0;\n    }\n    var key = this.keys_[this.i_++];\n    var pd = this.obj_.getOwnPropertyDescriptor(key, this.perms_);\n    // Skip deleted or already-visited properties.\n    if (!pd || this.visited_.has(key)) {\n      continue;\n    }\n    this.visited_.add(key);\n    if (pd.enumerable) {\n      return key;\n    }\n  }\n};\n\n/**\n * Class for a scope.  Implements Lexical Environments and the\n * Environment Record specification type from E5.1 §10.2 / ES6 §8.1.\n * @constructor\n * @struct\n * @param {!Interpreter.Scope.Type} type What variety of scope is it?\n * @param {!Interpreter.Owner} perms The permissions with which code\n *     in the current scope is executing.\n * @param {?Interpreter.Scope} outerScope The enclosing scope (\"outer\n *     lexical environment reference\", in ECMAScript spec parlance)\n * @param {?Interpreter.Value=} thisVal Value of 'this' in scope.\n *     (Default: copy value from outerScope.  N.B.: passing undefined\n *     is NOT treated the same as passing no value!)\n */\nInterpreter.Scope = function(type, perms, outerScope, thisVal) {\n  /** @type {!Interpreter.Scope.Type} */\n  this.type = type;\n  /** @type {!Interpreter.Owner} */\n  this.perms = perms;\n  /** @type {?Interpreter.Scope} */\n  this.outerScope = outerScope;\n  /** @type {?Interpreter.Value} */\n  this.this = (outerScope && arguments.length < 4) ? outerScope.this : thisVal;\n  /** @const {!Object<string, ?Interpreter.Value>} */\n  this.vars = Object.create(null);\n};\n\n/**\n * Returns true iff this scope has a binding for the given name.\n *\n * Based on HasBinding for declarative environment records,\n * from ES5.1 §10.2.1.1.1 / ES6 §8.1.1.1.1.\n * @param {string} name Name of variable.\n * @return {boolean} True iff name is bound in this scope.\n */\nInterpreter.Scope.prototype.hasBinding = function(name) {\n  return name in this.vars;\n};\n\n/**\n * Returns true iff this scope has an immutable binding for the given\n * name.\n *\n * @param {string} name Name of variable.\n * @return {boolean} True iff name is immutably bound in this scope.\n */\nInterpreter.Scope.prototype.hasImmutableBinding = function(name) {\n  var pd = Object.getOwnPropertyDescriptor(this.vars, name);\n  return Boolean(pd && !pd.writable);\n};\n\n/**\n * Creates a mutable binding in this scope and initialises it to\n * undefined or the provided value.\n *\n * Based on CreateMutableBinding for declarative environment records,\n * from ES5.1 §10.2.1.1.2 / ES6 §8.1.1.1.2.\n * @param {string} name Name of variable.\n * @param {?Interpreter.Value=} value Initial value (default: undefined).\n */\nInterpreter.Scope.prototype.createMutableBinding = function(name, value) {\n  if (name in this.vars) {\n    throw new Error(name + ' already has binding in this scope??');\n  }\n  this.vars[name] = value;\n};\n\n/**\n * Creates an immutable binding in this scope and initialises it\n * to the provided value.\n *\n * Based on CreateImmutableBinding for declarative environment records,\n * from ES5.1 §10.2.1.1.7 / ES6 §8.1.1.1.3.\n * @param {string} name Name of variable.\n * @param {?Interpreter.Value} value Initial value.\n */\nInterpreter.Scope.prototype.createImmutableBinding = function(name, value) {\n  if (name in this.vars) {\n    throw new Error(name + ' already has binding in this scope??');\n  }\n  Object.defineProperty(this.vars, name, Descriptor.ec.withValue(value));\n};\n\n/**\n * Updates a mutable binding in this scope to the the provided value.\n *\n * Based on SetMutableBinding for declarative environment records,\n * from ES5.1 §10.2.1.1.3 / ES6 §8.1.1.1.5.\n * @param {string} name Name of variable.\n * @param {?Interpreter.Value} value New value to set it to.\n * @return {!Error|undefined} If an error occurs, a (native) Error\n *     object is returned.  It shoud be converted into a user error\n *     (e.g., by errorNativeToPseudo) and thrown.  (This is done\n *     because Scope is not an inner class of interpreter, and thus\n *     this method has no access to the Error constructor or error\n *     prototypes.)\n */\nInterpreter.Scope.prototype.set = function(name, value) {\n  try {\n    this.vars[name] = value;\n  } catch (e) {  // Trying to set immutable binding.\n    return TypeError('Assignment to constant variable ' + name);\n  }\n};\n\n/**\n * Returns the value of a binding in this scope.\n *\n * Based on GetBindingValue for declarative environment records, from\n * ES5.1 §10.2.1.1.4 / ES6 §8.1.1.1.6.\n * @param {string} name Name of variable.\n * @return {?Interpreter.Value} The current value of the named variable\n *     in this scope.\n */\nInterpreter.Scope.prototype.get = function(name) {\n  return this.vars[name];\n};\n\n/**\n * Searches through this scope and its outer scopes to find a binding\n * for name, and returns the scope containing that binding or null if\n * name is not bound.\n *\n * Based on the Identifier Resolution algorithm of ES5.1 §10.3.1, or\n * equivalently the ResolveBinding specification function from ES6\n * §8.3.1.\n * @param {string} name Name of variable.\n * @return {?Interpreter.Scope} The scope that binds name, or null if none.\n */\nInterpreter.Scope.prototype.resolve = function(name) {\n  for (var s = this; s; s = s.outerScope) {\n    if (name in s.vars) return s;\n  }\n  return null;\n};\n\n/**\n * Scope types.  These correspond roughly to the list of environment\n * record types in ES6 §8.1.1 (declarative, object, function, global),\n * but omit ones we do not use (e.g., object), and distinguish between\n * different uses of declarative environment records (e.g., for\n * binding the name of a named function expression vs. binding the\n * name of the exception in a catch clause).\n * @enum {string}\n */\nInterpreter.Scope.Type = {\n  /** The global scope. */\n  GLOBAL: 'global',\n  /** A function invocation scope. */\n  FUNCTION: 'function',\n  /** A scope to contain the name of a named function expression. */\n  FUNEXP: 'funexp',\n  /** An eval body scope. */\n  EVAL: 'eval',\n  /** A catch clause scope. */\n  CATCH: 'catch',\n  /** For use as a dummy - e.g. the caller scope in createThreadForFuncCall */\n  DUMMY: 'dummy',\n};\n\n/**\n * Source is an encapsulated hunk of source text.  Source objects can\n * be sliced to obtain a Source object representing a substring of the\n * original source text.  Such sliced objects \"remember\" their\n * position within the original source text.\n * @constructor\n * @struct\n * @param {string} src Some source text\n * @param {number=} offset_ For internal use only.\n */\nInterpreter.Source = function(src, offset_) {\n  if (src === undefined) return;  // Deserializing.\n  /** @private @type {string} */\n  this.src_ = src;\n  /** @private @type {number} */\n  this.offset_ = offset_ || 0;\n  Object.freeze(this);\n};\n\n/**\n * Return the contents of a Source object as an ordinary string.\n * @return {string}\n */\nInterpreter.Source.prototype.toString = function() {\n  return this.src_;\n};\n\n/**\n * Return a Source object representing a substring of this Source\n * object.\n * @param {number} start Offset of first character of slice, as an absolute\n *     position within the original source text.\n * @param {number} end Offset of character following last character of\n *     slice, as an absolute position within the original source text.\n * @return {!Interpreter.Source} The sliced source.\n */\nInterpreter.Source.prototype.slice = function(start, end) {\n  if (start < this.offset_ || start > this.offset_ + this.src_.length) {\n    throw new RangeError('Source slice start out of range');\n  }\n  if (end < this.offset_ || end > this.offset_ + this.src_.length) {\n    throw new RangeError('Source slice end out of range');\n  }\n  if (start > end) {\n    throw new RangeError('Source slice start past end');\n  }\n  return new Interpreter.Source(\n      this.src_.slice(start - this.offset_, end - this.offset_),\n      start);\n};\n\n/**\n * Return the (1-based) line and column numbers of a given position\n * within the Source object.\n * @param {number} pos Position whose line number we are interested\n *     in, as an absolute position within the original source text.\n * @return {{line: number, col: number}} {line, col} tuple for the\n *     position pos, relative to the start of this particular slice.\n */\nInterpreter.Source.prototype.lineColForPos = function(pos) {\n  if (pos < this.offset_ || pos > this.offset_ + this.src_.length) {\n    throw new RangeError('Source position out of range');\n  }\n  var lines = this.src_.slice(0, pos - this.offset_).split('\\n');\n  return {line: lines.length, col: lines[lines.length - 1].length + 1};\n};\n\n/**\n * Class for a state.\n * @constructor\n * @struct\n * @param {!Node} node AST node for the state.\n * @param {!Interpreter.Scope} scope Scope dictionary for the state.\n * @param {boolean=} wantRef Does parent state want reference (rather\n *     than evaluated value)?  (Default: false.)\n */\nInterpreter.State = function(node, scope, wantRef) {\n  /** @const {!Node} */\n  this.node = node;\n  /** @const {!Interpreter.Scope} */\n  this.scope = scope;\n  /** @const {!Interpreter.StepFunction} */\n  this.stepFunc = node['stepFunc'];\n  /** @private @const {boolean} */\n  this.wantRef_ = wantRef || false;\n  /** @type {?Interpreter.Value} */\n  this.value = undefined;\n  /** @type {?Array} */\n  this.ref = null;\n  /** @type {?Array<string>} */\n  this.labels = null;\n  /** @type {boolean} */\n  this.isLoop = false;\n  /** @type {boolean} */\n  this.isSwitch = false;\n\n  /** @private @type {number} */\n  this.step_ = 0;\n  /** @private @type {number} */\n  this.n_ = 0;\n  /** @private @type {?Interpreter.Value|undefined} */\n  this.tmp_ = undefined;\n  /** @private @type {?Interpreter.CallInfo|\n   *                  ?Interpreter.ForInInfo|\n   *                  ?Interpreter.SwitchInfo|\n   *                  ?Interpreter.Completion}\n   */\n  this.info_ = null;\n};\n\n/**\n * Create a new State pre-configured to begin executing a function call.\n * @param {!Interpreter.prototype.Function} func Function to call.\n * @param {?Interpreter.Value} thisVal value of 'this' in function call.\n * @param {!Array<?Interpreter.Value>} args Arguments to pass.\n * @param {!Interpreter.Owner} perms Who is doing the call?\n * @return {!Interpreter.State} The newly-created state.\n */\nInterpreter.State.newForCall = function(func, thisVal, args, perms) {\n  // Dummy node (used only for type).\n  var node = new Node;\n  node['type'] = 'Call';\n  node['stepFunc'] = stepFuncs_['Call'];\n  // Dummy outer scope (used ony for perms, which will be caller perms).\n  var scope = new Interpreter.Scope(Interpreter.Scope.Type.DUMMY, perms, null);\n\n  var state = new Interpreter.State(node, scope);\n  state.info_ = {func: func,\n                 this: thisVal,\n                 arguments: args,\n                 directEval: false,\n                 construct: false,\n                 funcState: undefined};\n  return state;\n};\n\n/**\n * Information about a single call stack frame.\n * @typedef{(!{func: !Interpreter.prototype.Function,\n *             this: ?Interpreter.Value,\n *             callerPerms: !Interpreter.Owner}|\n *           !{func: !Interpreter.prototype.Function,\n *             this: ?Interpreter.Value,\n *             callerPerms: !Interpreter.Owner,\n *             line: number,\n *             col: number}|\n *           !{program: string}|\n *           !{program: string,\n *             line: number,\n *             col: number}|\n *           !{eval: string}|\n *           !{eval: string,\n *             line: number,\n *             col: number})}\n */\nvar FrameInfo;\n\n/**\n * If this state represents a call stack frame, or otherwise should be\n * reported in the output of callers() or in the .stack of an Error\n * object, return an object containing information about it;\n * otherwise return undefined.\n * @return {!FrameInfo|undefined}\n */\nInterpreter.State.prototype.frame = function() {\n  switch (this.node['type']) {\n    case 'Call':\n      var info = /** @type{!Interpreter.CallInfo} */(this.info_);\n      if (!info.func) throw new Error('No function for Call??');\n      return {\n        func: info.func,\n        this: info.this,\n        callerPerms: this.scope.perms,  // BUG(cpcallen:perms): wrong for bind.\n      };\n    case 'Program':\n      var source = this.node['source'];\n      if (!source) throw new Error('No source for Program??');\n      return {program: String(source)};\n    case 'EvalProgram_':\n      source = this.node['source'];\n      if (!source) throw new Error('No source for EvalProgram_??');\n      return {eval: String(source)};\n    default:\n      return undefined;\n  }\n};\n\n/**\n * Class for a thread of execution.\n *\n * Note that this is an internal class; it has a companion wrapper\n * class - Interpreter.prototype.Thread a.k.a. intrp.Thread - which\n * serves as a user-visible wrapper for this class.  The two are\n * separate for performance reasons only.\n * @constructor\n * @struct\n * @param {number} id Thread ID.  Should correspond to index of this\n *     thread in .threads_ array.\n * @param {!Interpreter.State} state Starting state for thread.\n * @param {number} runAt Time at which to start running thread.\n * @param {number=} timeLimit Maximum runtime without suspending (in ms).\n */\nInterpreter.Thread = function(id, state, runAt, timeLimit) {\n  /** @type {number} */\n  this.id = id;\n  // Say it's sleeping for now.  May be woken immediately.\n  /** @type {!Interpreter.Thread.Status} */\n  this.status = Interpreter.Thread.Status.SLEEPING;\n  /** @private @type {!Array<!Interpreter.State>} */\n  this.stateStack_ = [state];\n  /** @type {number} */\n  this.runAt = runAt;\n  /** @type {number} */\n  this.timeLimit = timeLimit || 0;\n  /** @type {?Interpreter.prototype.Thread} */\n  this.wrapper = null;\n  /** @type {?Interpreter.Value} */\n  this.value = undefined;\n};\n\n/**\n * Returns the original source code for current state.\n * @param {number=} index Optional index in stack to look from.\n * @return {?Interpreter.Source} Source code or null if none.\n */\nInterpreter.Thread.prototype.getSource = function(index) {\n  index = (index === undefined) ? this.stateStack_.length - 1 : index;\n  for (var i = index; i >= 0; i--) {\n    var source = this.stateStack_[i].node['source'];\n    if (source) return source;\n  }\n  return null;\n};\n\n/**\n * Return information about the call stack.\n * @param {!Interpreter.Owner} perms Who wants callers info?\n * @return {!Array<!FrameInfo>} The thread's call stack.\n */\nInterpreter.Thread.prototype.callers = function(perms) {\n  var frames = [];\n  var pos;\n  var lc;\n  for (var i = this.stateStack_.length - 1; i >= 0; i--) {\n    var state = this.stateStack_[i];\n    var node = state.node;\n    if (pos !== undefined && 'source' in node) {\n      lc = node['source'].lineColForPos(pos);\n    }\n    var frame;\n    if ((frame = state.frame())) {\n      // TODO(cpcallen:perms): Only include line/column info if func\n      // is readable by perms - otherwise it leaks some information\n      // about a supposedly-unreadable function.\n      if (lc) {\n        frame.line = lc.line;\n        frame.col = lc.col;\n      }\n      lc = pos = undefined;\n      frames[frames.length++] = frame;\n    }\n    if ((frame || frames.length === 0) && pos === undefined) {\n      pos = node['start'];\n    }\n  }\n  // TODO(cpcallen): add thread-initiator info.\n  return frames;\n};\n\n/**\n * Returns the permissions with which currently-executing code is\n * running (equivalent to a unix EUID, but in the form of a\n * user/group/etc. object).  It is an error to call this function on a\n * thread that is a zombie.\n * @deprecated\n * @return {!Interpreter.Owner}\n */\nInterpreter.Thread.prototype.perms = function() {\n  if (this.status === Interpreter.Thread.Status.ZOMBIE) {\n    throw new Error('Zombie thread has no perms');\n  }\n  return this.stateStack_[this.stateStack_.length - 1].scope.perms;\n};\n\n/**\n * Legal thread statuses.\n * @enum {number}\n */\nInterpreter.Thread.Status = {\n  /** Execution of the thread has terminated. */\n  ZOMBIE: 0,\n  /** The thread is ready to run (or is running). */\n  READY: 1,\n  /** The thread is blocked, awaiting an external event (e.g. callback). */\n  BLOCKED: 2,\n  /** The thread is sleeping, awaiting arrival of its .runAt time. */\n  SLEEPING: 3,\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Inner classes of Interpreter: Declarations.\n///////////////////////////////////////////////////////////////////////////////\n// Types representing JS objects - Object, Function, Array, etc.\n/**\n * Typedef for JS values.\n * @typedef {!Interpreter.prototype.Object|boolean|number|string|undefined|null}\n */\nInterpreter.Value;\n\n/**\n * Interface for owners.  Anything that is an Owner is really just a\n * normal !Interpreter.prototype.Object, but since since no concrete\n * class @implements this interface we force oruselves to cast back\n * and forth, helping to catch type errors.\n * @interface\n */\nInterpreter.Owner = function() {};\n\n/**\n * An interface for object-like entities: either actual\n * Interpreter.prototype.Objects or by non-user-visible boxed\n * primitives.\n * @interface\n */\nInterpreter.ObjectLike = function() {};\n\n/** @type {?Interpreter.prototype.Object} */\nInterpreter.ObjectLike.prototype.proto;\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {!Interpreter.Descriptor|undefined}\n */\nInterpreter.ObjectLike.prototype.getOwnPropertyDescriptor =\n    function(key, perms) {};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Descriptor} desc\n * @param {!Interpreter.Owner} perms\n */\nInterpreter.ObjectLike.prototype.defineProperty =\n    function(key, desc, perms) {};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {boolean}\n */\nInterpreter.ObjectLike.prototype.has = function(key, perms) {};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {?Interpreter.Value}\n */\nInterpreter.ObjectLike.prototype.get = function(key, perms) {};\n\n/**\n * @param {string} key\n * @param {?Interpreter.Value} value\n * @param {!Interpreter.Owner} perms\n */\nInterpreter.ObjectLike.prototype.set = function(key, value, perms) {};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {boolean}\n */\nInterpreter.ObjectLike.prototype.deleteProperty = function(key, perms) {};\n\n/** @param {!Interpreter.Owner} perms @return {!Array<string>} */\nInterpreter.ObjectLike.prototype.ownKeys = function(perms) {};\n\n/** @return {string} */\nInterpreter.ObjectLike.prototype.toString = function() {};\n\n/** @return {?Interpreter.Value} */\nInterpreter.ObjectLike.prototype.valueOf = function() {};\n\n/**\n * @constructor\n * @struct\n * @implements {Interpreter.ObjectLike}\n * @param {?Interpreter.Owner=} owner\n * @param {?Interpreter.prototype.Object=} proto\n */\nInterpreter.prototype.Object = function(owner, proto) {\n  /** @type {?Interpreter.Owner} */\n  this.owner;\n  /** @type {?Interpreter.prototype.Object} */\n  this.proto;\n  /** @const {!Object<?Interpreter.Value>} */\n  this.properties;\n  // TODO(cpcallen): this is kind of ugly, because connected Objects\n  // have their shape mutated by the on('connect') handler in Server.\n  // Consider rewriting it so that there is a WeakMap on Interpreter\n  // instances mapping objects to their corresponding Socket.\n  /** @type {!net.Socket|undefined} */\n  this.socket;\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/** @type {?Interpreter.prototype.Object} */\nInterpreter.prototype.Object.prototype.proto = null;\n\n/** @type {string} */\nInterpreter.prototype.Object.prototype.class = '';\n\n/**\n * @param {?Interpreter.prototype.Object} proto\n * @param {!Interpreter.Owner} perms\n * @return {boolean}\n */\nInterpreter.prototype.Object.prototype.setPrototypeOf = function(proto, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/** @param {!Interpreter.Owner} perms @return {boolean} */\nInterpreter.prototype.Object.prototype.isExtensible = function(perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/** @param {!Interpreter.Owner} perms @return {boolean} */\nInterpreter.prototype.Object.prototype.preventExtensions = function(perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {!Interpreter.Descriptor|undefined}\n */\nInterpreter.prototype.Object.prototype.getOwnPropertyDescriptor = function(\n    key, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Descriptor} desc\n * @param {!Interpreter.Owner=} perms\n */\nInterpreter.prototype.Object.prototype.defineProperty = function(\n    key, desc, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {boolean}\n */\nInterpreter.prototype.Object.prototype.has = function(key, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {?Interpreter.Value}\n */\nInterpreter.prototype.Object.prototype.get = function(key, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {?Interpreter.Value} value\n * @param {!Interpreter.Owner} perms\n */\nInterpreter.prototype.Object.prototype.set = function(key, value, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {boolean}\n */\nInterpreter.prototype.Object.prototype.deleteProperty = function(key, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/** @param {!Interpreter.Owner} perms @return {!Array<string>} */\nInterpreter.prototype.Object.prototype.ownKeys = function(perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/** @return {string} */\nInterpreter.prototype.Object.prototype.toString = function() {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/** @return {?Interpreter.Value} */\nInterpreter.prototype.Object.prototype.valueOf = function() {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Object}\n * @param {?Interpreter.Owner=} owner\n * @param {?Interpreter.prototype.Object=} proto\n */\nInterpreter.prototype.Function = function(owner, proto) {\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @param {?Interpreter.Value} value\n * @param {!Interpreter.Owner} perms\n * @return {boolean}\n */\nInterpreter.prototype.Function.prototype.hasInstance = function(value, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} name\n * @param {string=} prefix\n */\nInterpreter.prototype.Function.prototype.setName = function(name, prefix) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {!Interpreter} intrp The interpreter.\n * @param {!Interpreter.Thread} thread The current thread.\n * @param {!Interpreter.State} state The current state.\n * @param {?Interpreter.Value} thisVal The this value passed into function.\n * @param {!Array<?Interpreter.Value>} args The arguments to the call.\n * @return {?Interpreter.Value|!Interpreter.FunctionResult}\n */\nInterpreter.prototype.Function.prototype.call = function(\n    intrp, thread, state, thisVal, args) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {!Interpreter} intrp The interpreter.\n * @param {!Interpreter.Thread} thread The current thread.\n * @param {!Interpreter.State} state The current state.\n * @param {!Array<?Interpreter.Value>} args The arguments to the call.\n * @return {?Interpreter.Value|!Interpreter.FunctionResult}\n */\nInterpreter.prototype.Function.prototype.construct = function(\n    intrp, thread, state, args) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Function}\n * @param {!Node} node\n * @param {!Interpreter.Scope} scope Enclosing scope.\n * @param {!Interpreter.Source} source\n * @param {?Interpreter.Owner=} owner\n * @param {?Interpreter.prototype.Object=} proto\n */\nInterpreter.prototype.UserFunction = function(\n    node, scope, source, owner, proto) {\n  /** @type {!Node} */\n  this.node;\n  /** @type {!Interpreter.Scope} */\n  this.scope;\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @param {!Interpreter.Owner} owner\n * @param {?Interpreter.Value} thisVal\n * @param {!Array<?Interpreter.Value>} args\n * @return {!Interpreter.Scope}\n * @private\n */\nInterpreter.prototype.UserFunction.prototype.instantiateDeclarations_ =\nfunction(owner, thisVal, args) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Function}\n * @param {!Interpreter.prototype.Function} func\n * @param {?Interpreter.Value} thisVal\n * @param {!Array<?Interpreter.Value>} args\n * @param {?Interpreter.Owner=} owner\n */\nInterpreter.prototype.BoundFunction = function(func, thisVal, args, owner) {\n  /** @type {!Interpreter.prototype.Function} */\n  this.boundFunc;\n  /** @type {?Interpreter.Value} */\n  this.thisVal;\n  /** @type {!Array<?Interpreter.Value>} */\n  this.args;\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Function}\n * @param {!NativeFunctionOptions=} options\n */\nInterpreter.prototype.NativeFunction = function(options) {\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.NativeFunction}\n * @param {!Function} impl\n * @param {boolean} legalConstructor\n * @param {!NativeFunctionOptions=} options\n */\nInterpreter.prototype.OldNativeFunction =\n    function(impl, legalConstructor, options) {\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Object}\n * @param {?Interpreter.Owner=} owner\n * @param {?Interpreter.prototype.Object=} proto\n */\nInterpreter.prototype.Array = function(owner, proto) {\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Object}\n * @param {!Date} date\n * @param {?Interpreter.Owner=} owner\n * @param {?Interpreter.prototype.Object=} proto\n */\nInterpreter.prototype.Date = function(date, owner, proto) {\n  /** @type {!Date} */\n  this.date;\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Object}\n * @param {!RegExp=} re\n * @param {?Interpreter.Owner=} owner\n * @param {?Interpreter.prototype.Object=} proto\n */\nInterpreter.prototype.RegExp = function(re, owner, proto) {\n  /** @type {!RegExp} */\n  this.regexp;\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Object}\n * @param {?Interpreter.Owner=} owner\n * @param {?Interpreter.prototype.Object=} proto\n * @param {string=} message\n * @param {!Array<!FrameInfo>=} callers\n */\nInterpreter.prototype.Error = function(owner, proto, message, callers) {\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @param {!Array<!FrameInfo>} callers\n * @param {!Interpreter.Owner} perms\n */\nInterpreter.prototype.Error.prototype.makeStack = function(callers, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Object}\n * @param {?Interpreter.Owner=} owner\n * @param {?Interpreter.prototype.Object=} proto\n */\nInterpreter.prototype.Arguments = function(owner, proto) {\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Object}\n * @param {?Interpreter.Owner=} owner\n * @param {?Interpreter.prototype.Object=} proto\n */\nInterpreter.prototype.WeakMap = function(owner, proto) {\n  /** @type {!IterableWeakMap} */\n  this.weakMap;\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @extends {Interpreter.prototype.Object}\n * @param {!Interpreter.Thread} thread\n * @param {!Interpreter.Owner} owner\n * @param {?Interpreter.prototype.Object=} proto\n */\nInterpreter.prototype.Thread = function(thread, owner, proto) {\n  /** @type {!Interpreter.Thread} */\n  this.thread;\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Other types, not representing JS objects.\n/**\n * @constructor\n * @struct\n * @implements {Interpreter.ObjectLike}\n * @param {(boolean|number|string)} prim\n */\nInterpreter.prototype.Box = function(prim) {\n  /** @private @type {(undefined|null|boolean|number|string)} */\n  this.primitive_;\n  /** @type {!Interpreter.prototype.Object} */\n  this.proto;\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {!Interpreter.Descriptor|undefined}\n */\nInterpreter.prototype.Box.prototype.getOwnPropertyDescriptor = function(\n    key, perms) {\n  throw new Error('Inner class method not callable on prototype');\n}\n/**\n * @param {string} key\n * @param {!Interpreter.Descriptor} desc\n * @param {!Interpreter.Owner} perms\n */\nInterpreter.prototype.Box.prototype.defineProperty = function(\n    key, desc, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {boolean}\n */\nInterpreter.prototype.Box.prototype.has = function(key, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {?Interpreter.Value}\n */\nInterpreter.prototype.Box.prototype.get = function(key, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @param {?Interpreter.Value} value\n */\nInterpreter.prototype.Box.prototype.set = function(key, value, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {string} key\n * @param {!Interpreter.Owner} perms\n * @return {boolean}\n */\nInterpreter.prototype.Box.prototype.deleteProperty = function(key, perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @param {!Interpreter.Owner} perms\n * @return {!Array<string>}\n */\nInterpreter.prototype.Box.prototype.ownKeys = function(perms) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/** @return {string} String value. */\nInterpreter.prototype.Box.prototype.toString = function() {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/** @return {?Interpreter.Value} Value. */\nInterpreter.prototype.Box.prototype.valueOf = function() {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/**\n * @constructor\n * @struct\n * @param {!Interpreter.Owner} owner\n * @param {number} port\n * @param {!Interpreter.prototype.Object} proto\n * @param {number=} timeLimit\n */\nInterpreter.prototype.Server = function(owner, port, proto, timeLimit) {\n  /** @type {!Interpreter.Owner} */\n  this.owner;\n  /** @type {number} */\n  this.port;\n  /** @type {!Interpreter.prototype.Object} */\n  this.proto;\n  /** @type {number} */\n  this.timeLimit;\n  /** @private @type {!net.Server} */\n  this.server_;\n  throw new Error('Inner class constructor not callable on prototype');\n};\n\n/** @param {!function(!Error=)=} callback */\nInterpreter.prototype.Server.prototype.listen = function(callback) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n/** @param {!function()=} callback */\nInterpreter.prototype.Server.prototype.unlisten = function(callback) {\n  throw new Error('Inner class method not callable on prototype');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Inner classes of Interpreter: Implementations.\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Install the actual Object, Function, Array, RegExp, Error,\n * etc. constructors on an Interpreter instance.  Should\n * be called just once, from the Interpreter constructor.\n */\nInterpreter.prototype.installTypes = function() {\n  var intrp = this;  // The interpreter instance to which these classes belong.\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Types representing JS objects - Object, Function, Array, etc.\n  /**\n   * Class for an object.\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.Object}\n   * @param {?Interpreter.Owner=} owner Owner object or null.\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   */\n  intrp.Object = function(owner, proto) {\n    if (proto === undefined) {\n      proto = intrp.OBJECT;\n    }\n    if (owner === undefined) {\n      owner = null;\n    }\n    this.owner = owner;\n    this.proto = proto;\n    this.properties = Object.create((proto === null) ? null : proto.properties);\n  };\n\n  /** @type {?Interpreter.prototype.Object} */\n  intrp.Object.prototype.proto = null;\n  /** @type {string} */\n  intrp.Object.prototype.class = 'Object';\n\n  /**\n   * The [[SetPrototypeOf]] internal method from ES6 §9.1.2, with\n   * substantial adaptations for Code City including added perms\n   * checks.\n   *\n   * N.B.: Note that instead of returning false, this implementation\n   * will throw a more specific error in the event that the set fails.\n   * approriate error upon failure.\n   * @param {?Interpreter.prototype.Object} proto The new prototype or null.\n   * @param {!Interpreter.Owner} perms Who is trying set the prototype?\n   * @return {boolean} True iff the set succeeded.\n   */\n  intrp.Object.prototype.setPrototypeOf = function(proto, perms) {\n    if (perms === null) throw new TypeError(\"null can't check extensibility\");\n    // TODO(cpcallen:perms): add \"controls\"-type perm check.\n    if (proto === this.proto) {  // Doing nothing always succeeds.\n      return true;\n    } else if (!this.isExtensible(perms)) {\n      throw new intrp.Error(perms, intrp.TYPE_ERROR,\n          \"Can't set prototype of non-extensible object\");\n    }\n    for (var p = proto; p !== null; p = p.proto) {\n      if (p === this) {\n        throw new intrp.Error(perms, intrp.TYPE_ERROR,\n            \"An object's prototype chain can't include the object itself\");\n      }\n    }\n    Object.setPrototypeOf(this.properties, proto && proto.properties);\n    this.proto = proto;\n    return true;\n  };\n\n  /**\n   * The [[IsExtensible]] internal method from ES6 §9.1.3, with\n   * substantial adaptations for Code City including added perms\n   * checks.\n   * @param {!Interpreter.Owner} perms Who is trying to check?\n   * @return {boolean} Is the object extensible?\n   */\n  intrp.Object.prototype.isExtensible = function(perms) {\n    if (perms === null) throw new TypeError(\"null can't check extensibility\");\n    // TODO(cpcallen:perms): add check for (object) readability.\n    return Object.isExtensible(this.properties);\n  };\n\n  /**\n   * The [[PreventExtensions]] internal method from ES6 §9.1.4, with\n   * substantial adaptations for Code City including added perms\n   * checks.\n   * @param {!Interpreter.Owner} perms Who is trying to prevent extensions?\n   * @return {boolean} Is the object extensible afterwards?\n   */\n  intrp.Object.prototype.preventExtensions = function(perms) {\n    if (perms === null) throw new TypeError(\"null can't prevent extensibions\");\n    // TODO(cpcallen:perms): add \"controls\"-type perm check.\n    Object.preventExtensions(this.properties);\n    return true;\n  };\n\n  /**\n   * The [[GetOwnOwnProperty]] internal method from ES5.1 §8.12.1,\n   * with substantial adaptations for Code City including added perms\n   * checks (but no support for getter or setters).\n   * @param {string} key Key (name) of property to get.\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {!Interpreter.Descriptor|undefined} The property\n   *     descriptor, or undefined if no such property exists.\n   */\n  intrp.Object.prototype.getOwnPropertyDescriptor = function(key, perms) {\n    if (perms === null) {\n      throw new TypeError(\"null can't getOwnPropertyDescriptor\");\n    }\n    // TODO(cpcallen:perms): add check for (property) readability.\n    var pd = Object.getOwnPropertyDescriptor(this.properties, key);\n    // TODO(cpcallen): can we eliminate this pointless busywork while\n    // still maintaining type safety?\n    return pd && new Descriptor(pd.writable, pd.enumerable, pd.configurable)\n        .withValue(/** @type {?Interpreter.Value} */ (pd.value));\n  };\n\n  /**\n   * The [[DefineOwnProperty]] internal method from ES5.1 §8.12.9,\n   * with substantial adaptations for Code City including added perms\n   * checks (but no support for getter or setters).\n   * @param {string} key Key (name) of property to set.\n   * @param {!Interpreter.Descriptor} desc The property descriptor.\n   * @param {!Interpreter.Owner=} perms Who is trying to set it?  If\n   *     omitted, defaults to this.owner but skips perm check.  (This\n   *     is intended to be used only when constructing.)\n   */\n  intrp.Object.prototype.defineProperty = function(key, desc, perms) {\n    if (perms !== undefined) {\n      if (perms === null) throw new TypeError(\"null can't defineProperty\");\n      // TODO(cpcallen:perms): add \"controls\"-type perm check.\n    }\n    try {\n      Object.defineProperty(this.properties, key, desc);\n    } catch (e) {\n      throw intrp.errorNativeToPseudo(e, perms || this.owner);\n    }\n  };\n\n  /**\n   * The [[HasProperty]] internal method from ES5.1 §8.12.6, with\n   * substantial adaptations for Code City including added perms\n   * checks.\n   * @param {string} key Key (name) of property to get.\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {boolean} The value of the property, or undefined.\n   */\n  intrp.Object.prototype.has = function(key, perms) {\n    if (perms === null) throw new TypeError(\"null can't has\");\n    // TODO(cpcallen:perms): add check for (object) readability.\n    return key in this.properties;\n  };\n\n  /**\n   * The [[Get]] internal method from ES5.1 §8.12.3, with substantial\n   * adaptations for Code City including added perms checks (but no\n   * support for getters).\n   * @param {string} key Key (name) of property to get.\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {?Interpreter.Value} The value of the property, or undefined.\n   */\n  intrp.Object.prototype.get = function(key, perms) {\n    if (perms === null) throw new TypeError(\"null can't get\");\n    // TODO(cpcallen:perms): add check for (property) readability.\n    return this.properties[key];\n  };\n\n  /**\n   * The [[Set]] internal method from ES5.1 §8.12.5, with substantial\n   * adaptations for Code City including added perms checks (but no\n   * support for setters).\n   * @param {string} key Key (name) of property to set.\n   * @param {!Interpreter.Owner} perms Who is trying to set it?\n   * @param {?Interpreter.Value} value The new value of the property.\n   */\n  intrp.Object.prototype.set = function(key, value, perms) {\n    if (perms === null) throw new TypeError(\"null can't set\");\n    // TODO(cpcallen:perms): add \"controls\"-type perm check.\n    try {\n      this.properties[key] = value;\n    } catch (e) {\n      throw intrp.errorNativeToPseudo(e, perms);\n    }\n\n  };\n\n  /**\n   * The [[Delete]] internal method from ES5.1 §8.12.7, with\n   * substantial adaptations for Code City including added perms\n   * checks (but no support for getters).\n   * @param {string} key Key (name) of property to get.\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {boolean} True iff successful.\n   */\n  intrp.Object.prototype.deleteProperty = function(key, perms) {\n    if (perms === null) throw new TypeError(\"null can't delete\");\n    // TODO(cpcallen:perms): add \"controls\"-type perm check.\n    try {\n      delete this.properties[key];\n    } catch (e) {\n      throw intrp.errorNativeToPseudo(e, perms);\n    }\n    return true;\n  };\n\n  /**\n   * The [[OwnPropertyKeys]] internal method from ES6 §9.1.12, with\n   * substantial adaptations for Code City including added perms\n   * checks.\n   *\n   * TODO(cpcallen:perms): decide whether null user can read\n   * properties.  (At the moment this is forbidden redundantly by type\n   * signature an runtime check; one or both should be removed.)\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {!Array<string>} An array of own property keys.\n   */\n  intrp.Object.prototype.ownKeys = function(perms) {\n    if (perms === null) throw new TypeError(\"null can't ownPropertyKeys\");\n    // TODO(cpcallen:perms): add check for (object) readability.\n    return Object.getOwnPropertyNames(this.properties);\n  };\n\n  /**\n   * Convert this object into a string.\n   * @return {string} String value.\n   * @override\n   */\n  intrp.Object.prototype.toString = function() {\n    var c;\n    // TODO(cpcallen:perms): perms check here?\n    if (this instanceof intrp.Object) {\n      c = this.class;\n    } else {\n      c = ({\n        undefined: 'Undefined',\n        null: 'Null',\n        boolean: 'Boolean',\n        number: 'Number',\n        string: 'String',\n      })[typeof this];\n    }\n    return '[object ' + c + ']';\n  };\n\n  /**\n   * Return the object value.\n   * @return {?Interpreter.Value} Value.\n   * @override\n   */\n  intrp.Object.prototype.valueOf = function() {\n    return this;\n  };\n\n  /**\n   * Class for a function.\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.Function}\n   * @param {?Interpreter.Owner=} owner Owner object (default: null).\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   */\n  intrp.Function = function(owner, proto) {\n    intrp.Object.call(/** @type {?} */ (this), owner,\n        (proto === undefined ? intrp.FUNCTION : proto));\n  };\n\n  intrp.Function.prototype = Object.create(intrp.Object.prototype);\n  intrp.Function.prototype.constructor = intrp.Function;\n  intrp.Function.prototype.class = 'Function';\n\n  /**\n   * Convert this function into a string.\n   * @override\n   * @this {!Interpreter.prototype.Function}\n   */\n  intrp.Function.prototype.toString = function() {\n    // Just do the simplest possible (spec-compliant) thing here.\n    return 'function () { [native code] }';\n  };\n\n  /**\n   * The [[HasInstance]] internal method from §15.3.5.3 of the ES5.1 spec.\n   * @param {?Interpreter.Value} value The value to be checked for\n   *     being an instance of this function.\n   * @param {!Interpreter.Owner} perms Who wants to know?  Used in\n   *     readability check of .constructor property and as owner of\n   *     any Errors thrown.\n   * @return {boolean}\n   * @override\n   */\n  intrp.Function.prototype.hasInstance = function(value, perms) {\n    if (!(value instanceof intrp.Object)) {\n      return false;\n    }\n    var prot = this.get('prototype', perms);\n    if (!(prot instanceof intrp.Object)) {\n      throw new intrp.Error(perms, intrp.TYPE_ERROR,\n          \"Function has non-object prototype '\" + prot +\n          \"' in instanceof check\");\n    }\n    for (var v = value.proto; v !== null; v = v.proto) {\n      if (v === prot) {\n        return true;\n      }\n    }\n    return false;\n  };\n\n  /**\n   * Add a .name property to this function object.  Implements\n   * SetFunctionName from ES6 §9.2.11.\n   *\n   * N.B.: The setting is not subject to any perms checks, so it must\n   * not be possible for a user to cause this internal method to be\n   * invoked on any function object owned by another user.  Typically\n   * this will be enforced by only invoking this method at the time\n   * the function is constructed, or immediately afterwards by a\n   * lexically-enclosing expression having first used tested the\n   * expression which resulted in the function value with\n   * isAnonymousFunctionDefinition (q.v.).\n   *\n   * TODO(ES6): allow name to be type Symbol.\n   * @param {string} name Name of function.\n   * @param {string=} prefix Prefix for function name (e.g. 'get', 'bound').\n   * @override\n   */\n  intrp.Function.prototype.setName = function(name, prefix) {\n    if (prefix) {\n      name = prefix + ' ' + name;\n    }\n    this.defineProperty('name', Descriptor.c.withValue(name));\n  };\n\n  /**\n   * The [[Call]] internal method defined by §13.2.1 of the ES5.1 spec.\n   * Generic functions (neither native nor user) can't be called.\n   * @param {!Interpreter} intrp The interpreter.\n   * @param {!Interpreter.Thread} thread The current thread.\n   * @param {!Interpreter.State} state The current state.\n   * @param {?Interpreter.Value} thisVal The this value passed into function.\n   * @param {!Array<?Interpreter.Value>} args The arguments to the call.\n   * @return {?Interpreter.Value}\n   * @override\n   */\n  intrp.Function.prototype.call = function(\n      intrp, thread, state, thisVal, args) {\n    throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n        \"Class constructor \" + this + \" cannot be invoked without 'new'\");\n  };\n\n  /**\n   * The [[Construct]] internal method defined by §13.2.2 of the ES5.1\n   * spec.\n   * Generic functions (neither native nor user) can't be constructed.\n   * @param {!Interpreter} intrp The interpreter.\n   * @param {!Interpreter.Thread} thread The current thread.\n   * @param {!Interpreter.State} state The current state.\n   * @param {!Array<?Interpreter.Value>} args The arguments to the call.\n   * @return {?Interpreter.Value}\n   * @override\n   */\n  intrp.Function.prototype.construct = function(\n      intrp, thread, state, args) {\n    throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR,\n        this + ' is not a constructor');\n  };\n\n  /**\n   * Class for a user-defined function.\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.UserFunction}\n   * @param {!Node} node AST node for function body.\n   * @param {!Interpreter.Scope} scope Enclosing scope.\n   * @param {!Interpreter.Source} source Source from which AST was parsed.\n   * @param {?Interpreter.Owner=} owner Owner object (default: null).\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   */\n  intrp.UserFunction = function(node, scope, source, owner, proto) {\n    if (!node) {  // Deserializing\n      return;\n    }\n    intrp.Function.call(/** @type {?} */ (this), owner, proto);\n    this.node = node;\n    this.scope = scope;\n    if (node['id']) {\n      this.setName(node['id']['name']);\n    }\n    var length = node['params'].length;\n    this.defineProperty('length', Descriptor.none.withValue(length));\n    // Record the source on the function node's body node.  Store it\n    // on the AST (rather than on the UserFunction instance) because\n    // each time a function expression is evaluated a new UserFunction\n    // is created, but they all have identical source code.  Store it\n    // on the body node (rather than on the function node) because the\n    // function node never appears on the stateStack_ when the\n    // function is being executed.\n    if (!node['body']['source']) {\n      node['body']['source'] = source.slice(node['start'], node['end']);\n    }\n    // Add .prototype property pointing at a new plain Object.\n    var protoObj = new intrp.Object(this.owner);\n    this.defineProperty('prototype', Descriptor.w.withValue(protoObj));\n    protoObj.defineProperty('constructor', Descriptor.wc.withValue(this));\n  };\n\n  intrp.UserFunction.prototype = Object.create(intrp.Function.prototype);\n  intrp.UserFunction.prototype.constructor = intrp.UserFunction;\n\n  /**\n   * Convert this function into a string.\n   * @override\n   */\n  intrp.UserFunction.prototype.toString = function() {\n    // TODO(cpcallen:perms): perms check here?\n    return String(this.node['body']['source']);\n  };\n\n  /**\n   * The [[Call]] internal method defined by §13.2.1 of the ES5.1 spec.\n   * N.B.: This function (or any called from or overriding it) must\n   * not use state.info_.funcState, as that it used by\n   * Userfunction.prototype.construct, which calls us.\n   * @override\n   */\n  intrp.UserFunction.prototype.call = function(\n      intrp, thread, state, thisVal, args) {\n    if (this.owner === null) {\n      throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR,\n          'Functions with null owner are not executable');\n    }\n    var scope = this.instantiateDeclarations_(this.owner, thisVal, args);\n    state.value = undefined;  // Default value if no explicit return.\n    thread.stateStack_[thread.stateStack_.length] =\n        new Interpreter.State(this.node['body'], scope);\n    return Interpreter.FunctionResult.AwaitValue;\n  };\n\n  /**\n   * The [[Construct]] internal method defined by §13.2.2 of the ES5.1\n   * spec.\n   * @override\n   */\n  intrp.UserFunction.prototype.construct = function(\n      intrp, thread, state, args) {\n    if (!state.info_.funcState) {  // First visit.\n      if (this.owner === null) {\n        throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR,\n            'Functions with null owner are not constructable');\n      }\n      // TODO(cpcallen:perms): Is it really OK to construct if caller\n      // can't read .prototype?\n      var proto = this.get('prototype', this.owner);\n      // Per ES5.1 §13.2.2 step 7: if .prototype is primitive, use\n      // Object.prototype instead.\n      if (!(proto instanceof intrp.Object)) {\n        proto = intrp.OBJECT;\n      }\n      state.info_.funcState = new intrp.Object(state.scope.perms, proto);\n      this.call(intrp, thread, state, state.info_.funcState, args);\n      return Interpreter.FunctionResult.CallAgain;\n    } else {  // Construction done.  Check result.\n      // Per ES5.1 §13.2.2 steps 9, 10: if constructor returns\n      // primitive, return constructed object instead.\n      if (!(state.value instanceof intrp.Object)) {\n        return /** @type {?Interpreter.Value} */ (state.info_.funcState);\n      }\n      return state.value;\n    }\n  };\n\n  /**\n   * A simplified version of the FunctionDeclarationInstantiation\n   * specification function from ES6 §9.2.12 (see also Declaration\n   * Binding Instantiation in ES5.1 §10.5).\n   *\n   * Creates a new Scope and sets up the bindings of the function's\n   * parameters and variables.\n   * @param {!Interpreter.Owner} owner Owner for new Scope.\n   * @param {?Interpreter.Value} thisVal The value of 'this' for the call.\n   * @param {!Array<?Interpreter.Value>} args The arguments to the call.\n   * @return {!Interpreter.Scope} The initialised scope\n   * @private\n   */\n  intrp.UserFunction.prototype.instantiateDeclarations_ = function(\n      owner, thisVal, args) {\n    // Aside: we need to pass owner, rather than\n    // this.scope.perms, for the new scope perms because (1) we want\n    // to be able to change the owner of a function after it's\n    // created, and (2) functions created using the Function\n    // constructor have this.scope set to the global scope, which is\n    // owned by root!\n    var scope = new Interpreter.Scope(\n        Interpreter.Scope.Type.FUNCTION, owner, this.scope, thisVal);\n    // Add all arguments to the scope.\n    var params = this.node['params'];\n    for (var i = 0; i < params.length; i++) {\n      var paramName = params[i]['name'];\n      var paramValue = args.length > i ? args[i] : undefined;\n      scope.createMutableBinding(paramName, paramValue);\n    }\n    var body = this.node['body'];\n    if (!('arguments' in getBoundNames(body)) &&\n        hasArgumentsOrEval(body)) {\n      // Build arguments object.\n      var argsObj = new intrp.Arguments(owner);\n      argsObj.defineProperty(\n          'length', Descriptor.wc.withValue(args.length), owner);\n      for (i = 0; i < args.length; i++) {\n        argsObj.defineProperty(\n            String(i), Descriptor.wec.withValue(args[i]), owner);\n      }\n      scope.createImmutableBinding('arguments', argsObj);\n    }\n    // Populate local variables and other inner declarations.\n    intrp.populateScope_(body, scope);\n    return scope;\n  };\n\n  /**\n   * Class for bound functions.  See ES5 §15.3.4.5 / ES6 §9.4.1.\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.BoundFunction}\n   * @param {!Interpreter.prototype.Function} func Function to be bound.\n   * @param {?Interpreter.Value} thisVal The this value passed into function.\n   * @param {!Array<?Interpreter.Value>} args Arguments to prefix to the call.\n   * @param {?Interpreter.Owner=} owner Owner object (default: null).\n   */\n  intrp.BoundFunction = function(func, thisVal, args, owner) {\n    if (!func) return;  // Deserializing\n    intrp.Function.call(/** @type {?} */ (this), owner, func.proto);\n    /** @type {!Interpreter.prototype.Function} */\n    this.boundFunc = func;\n    /** @type {?Interpreter.Value} */\n    this.thisVal = thisVal;\n    /** @type {!Array<?Interpreter.Value>} */\n    this.args = args;\n  };\n\n  intrp.BoundFunction.prototype = Object.create(intrp.Function.prototype);\n  intrp.BoundFunction.prototype.constructor = intrp.BoundFunction;\n\n  /**\n   * The [[Call]] internal method for bound functions, defined by\n   * ES5.1 §15.3.4.5.1 / ES6 §9.4.1.1.\n   *\n   * BUG(cpcallen:perms): the target function will see callerPerms\n   * being whoever called the bound function, but should see\n   * callerPerms being the owner of the bound function.\n   * @override\n   */\n  intrp.BoundFunction.prototype.call = function(\n      intrp, thread, state, thisVal, args) {\n    // TODO(cpcallen:perms): Consider carefully whose perms should be\n    // used where!\n    if (this.owner === null) {\n      throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR,\n          'Functions with null owner are not executable');\n    }\n    var argList = this.args.concat(args);\n    // Rewrite state.info_, as a short-circuit optimisation in case\n    // we get called again due to FunctionResult.CallAgain, and also\n    // to produce more useful callers() output / stack traces.\n    var info = state.info_;\n    info.func = this.boundFunc;\n    info.this = this.thisVal;\n    info.args = argList;\n    info.construct = false;\n    // But just go and do the first .call directly.\n    return this.boundFunc.call(intrp, thread, state, this.thisVal, argList);\n  };\n\n  /**\n   * The [[Construct]] internal method for bound functions, defined by\n   * ES5.1 §15.3.4.5.2 / ES6 §9.4.1.2.\n   *\n   * BUG(cpcallen:perms): the target function will see callerPerms\n   * being whoever called the bound function, but should see\n   * callerPerms being the owner of the bound function.\n   * @override\n   */\n  intrp.BoundFunction.prototype.construct = function(\n      intrp, thread, state, args) {\n    // TODO(cpcallen:perms): Consider carefully whose perms should be\n    // used where!\n    if (this.owner === null) {\n      throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR,\n          'Functions with null owner are not constructable');\n    }\n    var argList = this.args.concat(args);\n    // Rewrite state.info_, as a short-circuit optimisation in case\n    // we get called again due to FunctionResult.CallAgain, and also\n    // to produce more useful callers() output / stack traces.\n    var info = state.info_;\n    info.func = this.boundFunc;\n    info.this = this.thisVal;\n    info.args = argList;\n    info.construct = true;\n    // But just go and do the first .construct directly.\n    return this.boundFunc.construct(intrp, thread, state, argList);\n  };\n\n  /**\n   * Class for a native function.  Options are as follows:\n   *\n   * If options.name is a non-empty string, the new function object's\n   * .name property will be set to this value.  Otherwise, if\n   * options.id is a non-empty string, the part following the last '.'\n   * will be used instead.\n   *\n   * If options.length is supplied, the new object's .length will be\n   * set to this value.\n   *\n   * If options.id is a non-empty string, the new native function\n   * object will be registered as a builtin with that id value.\n   *\n   * The options.call and .construct will be used for the [[Call]] and\n   * [[Construct]] specifications methods respectively.  If omitted,\n   * the function will not be callable / constructable.\n   *\n   * The new object will be owned by options.owner (default:\n   * intrp.ROOT), and have prototype options.proto (default:\n   * intrp.FUNCTION - i.e., Function.prototype).\n   *\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.NativeFunction}\n   * @param {!NativeFunctionOptions=} options Options object for\n   *     constructing native function.\n   */\n  intrp.NativeFunction = function(options) {\n    options = options || {};\n    var owner = (options.owner !== undefined ? options.owner : intrp.ROOT);\n    // Invoke super constructor.\n    intrp.Function.call(/** @type {?} */ (this), owner, options.proto);\n    // Set .name if name or id supplied, and save original name internally.\n    // N.B.: Function.prototype gets .name === ''.\n    /** The initial value of the .name property.  @type {string|undefined} */\n    this.name = undefined;\n    if (options.name !== undefined) {\n      this.name = options.name;\n    } else if (options.id) {\n      this.name = options.id.replace(/^.*\\./, '');\n    }\n    if (this.name !== undefined) this.setName(this.name);\n    // Set .length if length supplied.\n    if (options.length !== undefined) {\n      this.defineProperty('length', Descriptor.none.withValue(options.length),\n                          owner);\n    }\n    // Register as builtin if id supplied.\n    if (options.id) {\n      intrp.builtins.set(options.id, this);\n    }\n    // Install [[Call]] and [[Construct]] methods, making sure they\n    // are labelled for serialization (if possible and not already).\n    var serialId = options.id || options.name;\n    if (options.call) {\n      this.call = options.call;\n      if (serialId && !('id' in this.call)) {\n        this.call.id = serialId + ' [[Call]]';\n      }\n    }\n    if (options.construct) {\n      this.construct = options.construct;\n      if (serialId && !('id' in this.construct)) {\n        this.construct.id = serialId + ' [[Construct]]';\n      }\n    }\n  };\n\n  intrp.NativeFunction.prototype = Object.create(intrp.Function.prototype);\n  intrp.NativeFunction.prototype.constructor = intrp.NativeFunction;\n\n  /**\n   * Convert this function into a string.  This implements\n   * https://tc39.es/Function-prototype-toString-revision/#proposal-sec-function.prototype.tostring\n   * (now adopted) as it applies to \"Well-known Intrinsic Object[s]\"\n   * as well as any other NativeFunction constructed with specified\n   * name or id.\n   * @override\n   */\n  intrp.NativeFunction.prototype.toString = function() {\n    if (this.name === undefined) {\n      return intrp.Function.prototype.toString.call(this);\n    }\n    // TODO(cpcallen): include formal parameter names?\n    return 'function ' + this.name + '() { [native code] }';\n  };\n\n  /**\n   * Class for an old native function.\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.OldNativeFunction}\n   * @param {!Function} impl Old-style native function implementation\n   * @param {boolean} legalConstructor True if the function can be used as a\n   *     constructor (e.g. Array), false if not (e.g. escape).\n   * @param {!NativeFunctionOptions=} options Options object for\n   *     constructing the underlying NativeFunction.\n   */\n  intrp.OldNativeFunction = function(impl, legalConstructor, options) {\n    if (!impl) return;  // Deserializing\n    intrp.NativeFunction.call(/** @type {?} */ (this), options);\n    /** @type {!Function} */\n    this.impl = impl;\n    /** @type {boolean} */\n    this.illegalConstructor = !legalConstructor;\n  };\n\n  intrp.OldNativeFunction.prototype =\n      Object.create(intrp.NativeFunction.prototype);\n  intrp.OldNativeFunction.prototype.constructor = intrp.OldNativeFunction;\n\n  /** @override */\n  intrp.OldNativeFunction.prototype.call = function(\n      intrp, thread, state, thisVal, args) {\n    if (this.owner === null) {\n      throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR,\n          'Functions with null owner are not executable');\n    }\n    return this.impl.apply(thisVal, args);\n  };\n\n  /** @override */\n  intrp.OldNativeFunction.prototype.construct = function(\n      intrp, thread, state, args) {\n    if (this.illegalConstructor) {\n      // Pass to super, which will complain about non-callability:\n      intrp.Function.prototype.construct.call(\n          /** @type {?} */ (this), intrp, thread, state, args);\n    }\n    if (this.owner === null) {\n      throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR,\n          'Functions with null owner are not constructable');\n    }\n    return this.impl.apply(undefined, args);\n  };\n\n  /**\n   * Class for an array\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.Array}\n   * @param {?Interpreter.Owner=} owner Owner object or null.\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   */\n  intrp.Array = function(owner, proto) {\n    if (proto === undefined) {\n      proto = intrp.ARRAY;\n    }\n    intrp.Object.call(/** @type {?} */ (this), owner, proto);\n    this.properties = [];\n    Object.setPrototypeOf(this.properties,\n                          (proto === null) ? null : proto.properties);\n  };\n\n  intrp.Array.prototype = Object.create(intrp.Object.prototype);\n  intrp.Array.prototype.constructor = intrp.Array;\n  intrp.Array.prototype.class = 'Array';\n\n  /**\n   * Convert array-like objects into a string.\n   * @override\n   */\n  intrp.Array.prototype.toString = function() {\n    // BUG(cpcallen): toString should access properties on this with\n    // the caller's permissions - but at present there is no way to\n    // determine who it was called by, so use intrp.ANYBODY instead.\n    var visited = intrp.toStringVisited_;\n    if (visited.has(this)) {\n      return '';\n    }\n    visited.add(this);\n    try {\n      var strs = [];\n      var len = this.get('length', intrp.ANYBODY);\n      for (var i = 0; i < this.properties.length; i++) {\n        var value = this.get(String(i), intrp.ANYBODY);\n        if (value === null || value === undefined) {\n          strs[i] = '';\n        } else {\n          strs[i] = String(value);\n        }\n      }\n    } finally {\n      visited.delete(this);\n    }\n    return strs.join(',');\n  };\n\n  /**\n   * Class for a date.\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.Date}\n   * @param {!Date} date Date value for this Date object.\n   * @param {?Interpreter.Owner=} owner Owner object or null.\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   */\n  intrp.Date = function(date, owner, proto) {\n    if (!date) return;  // Deserializing\n    intrp.Object.call(/** @type {?} */ (this), owner,\n        (proto === undefined ? intrp.DATE : proto));\n    /** @type {!Date} */\n    this.date = date;\n  };\n\n  intrp.Date.prototype = Object.create(intrp.Object.prototype);\n  intrp.Date.prototype.constructor = intrp.Date;\n  intrp.Date.prototype.class = 'Date';\n\n  /**\n   * Return the date as a string.\n   * @override\n   */\n  intrp.Date.prototype.toString = function() {\n    // TODO(cpcallen:perms): perms check here?\n    return this.date.toString();\n  };\n\n  /**\n   * Return the date as a numeric value.\n   * @override\n   */\n  intrp.Date.prototype.valueOf = function() {\n    return this.date.valueOf();\n  };\n\n  /**\n   * Class for a regexp\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.RegExp}\n   * @param {!RegExp=} re The RegExp value for this RegExp object.\n   * @param {?Interpreter.Owner=} owner Owner object or null.\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   */\n  intrp.RegExp = function(re, owner, proto) {\n    if (!re) return;  // Deserializing\n    intrp.Object.call(/** @type {?} */ (this), owner,\n        (proto === undefined ? intrp.REGEXP : proto));\n    /** @type {!RegExp} */\n    this.regexp = re;\n    // lastIndex is settable, all others are read-only attributes\n    this.defineProperty('lastIndex', Descriptor.w.withValue(re.lastIndex));\n    this.defineProperty('source', Descriptor.none.withValue(re.source));\n    this.defineProperty('global', Descriptor.none.withValue(re.global));\n    this.defineProperty('ignoreCase', Descriptor.none.withValue(re.ignoreCase));\n    this.defineProperty('multiline', Descriptor.none.withValue(re.multiline));\n  };\n\n  intrp.RegExp.prototype = Object.create(intrp.Object.prototype);\n  intrp.RegExp.prototype.constructor = intrp.RegExp;\n  intrp.RegExp.prototype.class = 'RegExp';\n\n  /**\n   * Return the regexp as a string.\n   * @override\n   */\n  intrp.RegExp.prototype.toString = function() {\n    // TODO(cpcallen:perms): perms check here?\n    if (!(this.regexp instanceof RegExp)) {\n      // TODO(cpcallen): ES5.1 §15.10.6.4 doesn't say what happens\n      // when this is applied to a non-RegExp.  ES6 §21.2.5.14 does -\n      // and the results are possibly weird, e.g. returning\n      // \"/undefined/undefined\" or the like...  :-/\n      return '//';\n    }\n    return this.regexp.toString();\n  };\n\n  /**\n   * Class for an error object\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.Error}\n   * @param {?Interpreter.Owner=} owner Owner object or null.\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   * @param {string=} message Optional message to be attached to error object.\n   */\n  intrp.Error = function(owner, proto, message) {\n    intrp.Object.call(/** @type {?} */ (this), owner,\n        (proto === undefined ? intrp.ERROR : proto));\n    if (message !== undefined) {\n      this.defineProperty('message', Descriptor.wc.withValue(message));\n    }\n  };\n\n  intrp.Error.prototype = Object.create(intrp.Object.prototype);\n  intrp.Error.prototype.constructor = intrp.Error;\n  intrp.Error.prototype.class = 'Error';\n\n  /**\n   * Return the error as a string.\n   * @override\n   */\n  intrp.Error.prototype.toString = function() {\n    // BUG(cpcallen): toString should access properties on this with\n    // the caller's permissions - but at present there is no way to\n    // determine who it was called by, so use intrp.ANYBODY instead.\n    var visited = intrp.toStringVisited_;\n    if (visited.has(this)) {\n      return '';\n    }\n    visited.add(this);\n    try {\n      var name = this.get('name', intrp.ANYBODY);\n      var message = this.get('message', intrp.ANYBODY);\n      name = (name === undefined) ? 'Error' : String(name);\n      message = (message === undefined) ? '' : String(message);\n      if (name) {\n        return message ? (name + ': ' + message) : name;\n      }\n      return message;\n    } finally {\n      visited.delete(this);\n    }\n  };\n\n  /**\n   * Create a .stack property on the error from the given call stack\n   * information, if it does not already have one.  The stack property\n   * will be created with the permissions of the owner of the Error\n   * object.\n   *\n   * BUG(cpcallen): because this is called before unwinding the stack\n   * when an intrp.Error is thrown, and because .stack is set\n   * unconditionally (without perm check), any user can set .stack on\n   * any Error object that doesn't already have one (including\n   * e.g. Error.prototype) just by throwing it.\n   * @param {!Array<!FrameInfo>} callers List of call stack frames,\n   *     as returned by Thread.prototype.callers.\n   * @param {!Interpreter.Owner} perms Whose perms should be used to\n   *     obtain (e.g.) function names, etc.?\n   * @override\n   */\n  intrp.Error.prototype.makeStack = function(callers, perms) {\n    if (this.has('stack', intrp.ROOT)) {\n      return;  // Do not overwrite existing .stack\n    }\n    var stack = [];\n    for (var i = 0; i < callers.length; i++) {\n      var /** string */ line = '    ';\n      var frame = callers[i];\n      if ('func' in frame) {\n        var /** !Interpreter.prototype.Function */ func = frame.func;\n        var /** string */ name;\n        try {\n          var pd = func.getOwnPropertyDescriptor('name', perms);\n          if (pd) {\n            name = String(pd.value);\n          } else {\n            name = 'anonymous function';\n          }\n        } catch (e) {\n          name = 'unreadable function';\n        }\n      } else if ('eval' in frame) {\n        name = '\"' + frame.eval + '\"';\n      } else if ('program' in frame) {\n        name = '\"' + frame.program + '\"';\n      }\n      if ('line' in frame) {\n        line += 'at ' + name + ' ' + frame.line + ':' + frame.col;\n      } else {\n        line += 'in ' + name;\n      }\n      stack.push(line);\n    }\n    this.defineProperty('stack', Descriptor.wc.withValue(stack.join('\\n')));\n  };\n\n  /**\n   * Class for an arguments object.  See ES5 §10.6 / ES6 §9.4.4.\n   *\n   * N.B.: Does not support mapped properties because we are always in\n   * strict mode.  Does not implement the special always-throw getters\n   * for .callee and .caller, because we do not support getters.\n   * What's left is basically an ordinary object with a special\n   * [[Class]].\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.Arguments}\n   * @param {?Interpreter.Owner=} owner Owner object or null.\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   */\n  intrp.Arguments = function(owner, proto) {\n    intrp.Object.call(/** @type {?} */ (this), owner, proto);\n  };\n\n  intrp.Arguments.prototype = Object.create(intrp.Object.prototype);\n  intrp.Arguments.prototype.constructor = intrp.Arguments;\n  intrp.Arguments.prototype.class = 'Arguments';\n\n  /**\n   * The WeakMap class from ES6.\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.WeakMap}\n   * @param {?Interpreter.Owner=} owner Owner object or null.\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   */\n  intrp.WeakMap = function(owner, proto) {\n    intrp.Object.call(/** @type {?} */ (this), owner,\n        (proto === undefined ? intrp.WEAKMAP : proto));\n    /** @type {!IterableWeakMap} */\n    this.weakMap = new IterableWeakMap;\n  };\n\n  intrp.WeakMap.prototype = Object.create(intrp.Object.prototype);\n  intrp.WeakMap.prototype.constructor = intrp.WeakMap;\n  intrp.WeakMap.prototype.class = 'WeakMap';\n\n  /**\n   * Class for the user-visible representation of an Interpreter.Thread.\n   *\n   * Note that there should be at most one of these wrappers for each\n   * Interpreter.Thread, and this constructor enforces this.\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.Thread}\n   * @param {!Interpreter.Thread} thread Thread represented by this object.\n   * @param {!Interpreter.Owner} owner Owner of this thread.\n   * @param {?Interpreter.prototype.Object=} proto Prototype object or null.\n   */\n  intrp.Thread = function(thread, owner, proto) {\n    if (!thread) return;  // Deserializing\n    if (thread.wrapper) {\n      throw new Error('Duplicate Thread wrapper??');\n    }\n    intrp.Object.call(/** @type {?} */ (this), owner,\n        (proto === undefined ? intrp.THREAD : proto));\n    /** @type {!Interpreter.Thread} */\n    this.thread = thread;\n    this.thread.wrapper = this;\n    this.defineProperty('id', Descriptor.none.withValue(thread.id), owner);\n  };\n\n  intrp.Thread.prototype = Object.create(intrp.Object.prototype);\n  intrp.Thread.prototype.constructor = intrp.Thread;\n  intrp.Thread.prototype.class = 'Thread';\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Other types, not representing JS objects.\n  /**\n   * Class for a boxed primitive.  Does not @extend\n   * Interpreter.prototype.Object, because we do not want to expose\n   * these to the users.  They're just used internally to simplify the\n   * implementation of various bits of code that are specified by\n   * ES5.1 or ES6 to do ToObject().\n   *\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.Box}\n   * @param {(boolean|number|string)} prim Primitive to box\n   */\n  intrp.Box = function(prim) {\n    /** @private @type {(undefined|null|boolean|number|string)} */\n    this.primitive_ = prim;\n    if (typeof prim === 'boolean') {\n      /** @type {!Interpreter.prototype.Object} */\n      this.proto = intrp.BOOLEAN;\n    } else if (typeof prim === 'number') {\n      this.proto = intrp.NUMBER;\n    } else if (typeof prim === 'string') {\n      this.proto = intrp.STRING;\n    } else {\n      throw new Error('Invalid type in Box');\n    }\n  };\n\n  /**\n   * The [[GetOwnOwnProperty]] internal method from ES5.1 §8.12.1, as\n   * applied to temporary Boolean, Number and String class objects.\n   * @param {string} key Key (name) of property to get.\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {!Interpreter.Descriptor|undefined} The property\n   *     descriptor, or undefined if no such property exists.\n   * @override\n   */\n  intrp.Box.prototype.getOwnPropertyDescriptor = function(key, perms) {\n    var pd = Object.getOwnPropertyDescriptor(this.primitive_, key);\n    // TODO(cpcallen): can we eliminate this pointless busywork while\n    // still maintaining type safety?\n    return pd && new Descriptor(pd.writable, pd.enumerable, pd.configurable)\n        .withValue(/** @type {?Interpreter.Value} */ (pd.value));\n  };\n\n  /**\n   * The [[DefineOwnProperty]] internal method from ES5.1 §8.12.9, as\n   * applied to temporary Boolean, Number and String class objects.\n   * @param {string} key Key (name) of property to set.\n   * @param {!Interpreter.Descriptor} desc The property descriptor.\n   * @param {!Interpreter.Owner} perms Who is trying to set it?\n   * @override\n   */\n  intrp.Box.prototype.defineProperty = function(key, desc, perms) {\n    throw new intrp.Error(perms, intrp.TYPE_ERROR, \"Cannot create property '\" +\n        key + \"' on \" + typeof this.primitive_ + \" '\" + this.primitive_ + \"'\");\n  };\n\n  /**\n   * The [[HasProperty]] internal method from ES5.1 §8.12.6, as\n   * applied to temporary Boolean, Number and String class objects.\n   * @param {string} key Key (name) of property to get.\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {boolean} The value of the property, or undefined.\n   * @override\n   */\n  intrp.Box.prototype.has = function(key, perms) {\n    // Important: we want to ignore any extra properties on (e.g.) the\n    // native String.prototype, but be sure to find ones on\n    // intrp.String.prototype.\n    if (Object.getOwnPropertyDescriptor(this.primitive_, key)) {\n      return true;\n    }\n    // Defer to prototype.\n    return this.proto.has(key, perms);\n  };\n\n  /**\n   * The [[Get]] internal method from ES5.1 §8.12.3, as applied to\n   * temporary Boolean, Number and String class objects.\n   * @param {string} key Key (name) of property to get.\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {?Interpreter.Value} The value of the property, or undefined.\n   * @override\n   */\n  intrp.Box.prototype.get = function(key, perms) {\n    // Important: we want to ignore any extra properties on (e.g.) the\n    // native String.prototype, but be sure to find ones on\n    // intrp.String.prototype.\n    var pd = Object.getOwnPropertyDescriptor(this.primitive_, key);\n    if (pd) {\n      return /** @type {string|number} */(pd.value);\n    }\n    // Defer to prototype.\n    return this.proto.get(key, perms);\n  };\n\n  /**\n   * The [[Set]] internal method from ES5.1 §8.12.5, as\n   * applied to temporary Boolean, Number and String class objects.\n   * @param {string} key Key (name) of property to set.\n   * @param {!Interpreter.Owner} perms Who is trying to set it?\n   * @param {?Interpreter.Value} value The new value of the property.\n   * @override\n   */\n  intrp.Box.prototype.set = function(key, value, perms) {\n    throw new intrp.Error(perms, intrp.TYPE_ERROR, \"Cannot set property '\" +\n        key + \"' on \" + typeof this.primitive_ + \" '\" + this.primitive_ + \"'\");\n  };\n\n  /**\n   * The [[Delete]] internal method from ES5.1 §8.12.7, as applied to\n   * temporary Boolean, Number and String class objects.\n   * @param {string} key Key (name) of property to get.\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {boolean} True iff successful.\n   */\n  intrp.Box.prototype.deleteProperty = function(key, perms) {\n    // Attempting to delete property from primitive value.  Succeeds\n    // only if property doesn't exist.\n    if (Object.getOwnPropertyDescriptor(this.primitive_, key)) {\n      throw new intrp.Error(perms, intrp.TYPE_ERROR,\n          \"Cannot delete property '\" + key + \"' on \" + typeof this.primitive_ +\n          \" '\" + this.primitive_ + \"'\");\n    }\n    return true;\n  };\n\n  /**\n   * The [[OwnPropertyKeys]] internal method from ES6 §9.1.12, as\n   * applied to temporary Boolean, Number and String class objects.\n   * @param {!Interpreter.Owner} perms Who is trying to get it?\n   * @return {!Array<string>} An array of own property keys.\n   */\n  intrp.Box.prototype.ownKeys = function(perms) {\n    // Cast necessitated by compiler bug:\n    // https://github.com/google/closure-compiler/issues/2878\n    return Object.getOwnPropertyNames(/** @type {?} */(this.primitive_));\n  };\n\n  /**\n   * Convert this boxed primitive into a string.\n   * @return {string} String value.\n   * @override\n   */\n  intrp.Box.prototype.toString = function() {\n    return String(this.primitive_);\n  };\n\n  /**\n   * Return the boxed primitive value.\n   * @return {?Interpreter.Value} Value.\n   * @override\n   */\n  intrp.Box.prototype.valueOf = function() {\n    return this.primitive_;\n  };\n\n  /**\n   * Server is an (owner, port, proto, (extra info)) tuple representing a\n   * listening server.  It encapsulates node's net.Server type, with\n   * some additional info needed to implement the connectionListen()\n   * API.  In its present form it is not suitable for exposure as a\n   * userland pseduoObject, but it is intended to be easily adaptable\n   * for that if desired.\n   * @constructor\n   * @struct\n   * @extends {Interpreter.prototype.Server}\n   * @param {!Interpreter.Owner} owner Owner object or null.\n   * @param {number} port Port to listen on.\n   * @param {!Interpreter.prototype.Object} proto Prototype object for\n   *     new connections.\n   * @param {number=} timeLimit Maximum runtime without suspending (in ms).\n   */\n  intrp.Server = function(owner, port, proto, timeLimit) {\n    // Special excepetion: port === undefined when deserializing, in\n    // violation of usual type rules.\n    if ((port !== (port >>> 0) || port > 0xffff) && port !== undefined) {\n      throw new RangeError('invalid port ' + port);\n    }\n    /** @type {!Interpreter.Owner} */\n    this.owner = owner;\n    /** @type {number} */\n    this.port = port;\n    /** @type {!Interpreter.prototype.Object} */\n    this.proto = proto;\n    /** @type {number} */\n    this.timeLimit = timeLimit || 0;\n    /** @type {!net.Server} */\n    this.server_ = new net.Server({allowHalfOpen: true});\n\n    // Create the net.Server instance and set up event handlers but\n    // don't yet start it listening.\n    var server = this;  // So we can refer to it in handlers below.\n    this.server_.on('connection', function(socket) {\n      intrp.log('net', 'Connection on :%s from %s:%s',\n                server.port, socket.remoteAddress, socket.remotePort);\n      // TODO(cpcallen): Add localhost test here, like this - only\n      // also allow IPV6 connections:\n      // if (socket.remoteAddress != '127.0.0.1') {\n      //   // Reject connections other than from localhost.\n      //   intrp.log('net', 'Rejecting connection from ' +\n      //       socket.remoteAddress);\n      //   socket.end('Connection rejected.');\n      //   return;\n      // }\n\n      // Create new object from proto and call onConnect.\n      var obj = new intrp.Object(server.owner, server.proto);\n      obj.socket = socket;\n      var func = obj.get('onConnect', server.owner);\n      if (func instanceof intrp.Function && server.owner !== null) {\n        // TODO(cpcallen:perms): Is server.owner the correct owner for\n        // the thread?  Note that this will typically be root, and\n        // .onConnect will therefore get caller perms === root, which\n        // is probably dangerous.  Here and several places below.\n        intrp.createThreadForFuncCall(\n            server.owner, func, obj, [], undefined, server.timeLimit);\n      }\n\n      // Handle socket closing completely.\n      socket.on('close', function() {\n        intrp.log('net', 'Connection on :%s from %s:%s closed',\n                  server.port, socket.remoteAddress, socket.remotePort);\n        var func = obj.get('onClose', server.owner);\n        if (func instanceof intrp.Function && server.owner !== null) {\n          intrp.createThreadForFuncCall(\n              server.owner, func, obj, [], undefined, server.timeLimit);\n        }\n      });\n\n      // Handle incoming data from clients.  N.B. that data is a\n      // node buffer object, so we must convert it to a string\n      // before passing it to user code.\n      socket.on('data', function(data) {\n        var func = obj.get('onReceive', server.owner);\n        if (func instanceof intrp.Function && server.owner !== null) {\n          intrp.createThreadForFuncCall(\n              server.owner, func, obj, [String(data)],\n              undefined, server.timeLimit);\n        }\n      });\n\n      // Handle far end closing connection.\n      socket.on('end', function() {\n        intrp.log('net', 'Connection on :%s from %s:%s ended',\n                  server.port, socket.remoteAddress, socket.remotePort);\n        var func = obj.get('onEnd', server.owner);\n        if (func instanceof intrp.Function && server.owner !== null) {\n          intrp.createThreadForFuncCall(\n              server.owner, func, obj, [], undefined, server.timeLimit);\n        }\n      });\n\n      // Handle errors.\n      socket.on('error', function(error) {\n        intrp.log('net', 'Socket error on :%s from %s:%s: %s: %s',\n                  server.port, socket.remoteAddress, socket.remotePort,\n                  error.name, error.message);\n        var func = obj.get('onError', server.owner);\n        if (func instanceof intrp.Function && server.owner !== null) {\n          var userError = intrp.errorNativeToPseudo(error, server.owner);\n          intrp.createThreadForFuncCall(\n              server.owner, func, obj, [userError],\n              undefined, server.timeLimit);\n        }\n      });\n\n      // TODO(cpcallen): save new object somewhere we can find it\n      // later (when we want to obtain list of connected objects).\n    });\n\n    this.server_.on('listening', function() {\n      var addr = this.address();\n      intrp.log('net', 'Listening on %s %s:%s',\n                addr.family, addr.address, addr.port);\n    });\n\n    this.server_.on('error', function(error) {\n      intrp.log('net', 'Error on :%s: %s: %s',\n                server.port, error.name, error.message);\n    });\n\n    this.server_.on('close', function() {\n      intrp.log('net', 'Stopped listening on :%s', server.port);\n    });\n  };\n\n  /**\n   * Start a Server object listening on its assigned port.\n   * @param {!function(!Error=)=} callback\n   *     Callback that will be called once listening has begun, or with\n   *     an Error argument if listening fails.\n   */\n  intrp.Server.prototype.listen = function(callback) {\n    // Invariant checks.\n    if (this.port === undefined ||\n        !(this.proto instanceof intrp.Object) ||\n        !(this.server_ instanceof net.Server)) {\n      throw new Error('invalid Server state');\n    }\n    if (intrp.listeners_[this.port] !== this) {\n      throw new Error('Listening on server not listed in .listeners_??');\n    }\n\n    // Set up callbacks.  Fiddly, because we want to temporarily hook\n    // the error handler but be sure to unhook it whether the listen\n    // call succeeds or fails.\n    var /** boolean */ done = false;\n    /** @type {function(this:net.Server, !Error=)} */\n    function hook(error) {\n      if (done) throw new Error('unexpected multiple callbacks');\n      done = true;\n      this.removeListener(events.errorMonitor, hook);\n      if (callback) callback(error);\n    };\n    this.server_.on(events.errorMonitor, hook);\n    this.server_.listen(this.port, hook);\n  };\n\n  /**\n   * Stop a Server object listening on its assigned port.\n   * @param {!function()=} callback Callback that will be called after\n   *     listening has ceased.\n   */\n  intrp.Server.prototype.unlisten = function(callback) {\n    // Invariant checks.\n    if (this.port === undefined ||\n        !(this.proto instanceof intrp.Object) ||\n        !(this.server_ instanceof net.Server)) {\n      throw new Error('invalid Server state');\n    }\n    this.server_.close(callback);\n  };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Miscellaneous internal classes not used for storing state and not exported\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Type for options object for constructing a NativeFunction.\n * @typedef {{name: (string|undefined),\n *            length: (number|undefined),\n *            id: (string|undefined),\n *            call: (Interpreter.NativeCallImpl|undefined),\n *            construct: (Interpreter.NativeConstructImpl|undefined),\n *            owner: (!Interpreter.Owner|undefined),\n *            proto: (?Interpreter.prototype.Object|undefined)}}\n */\nvar NativeFunctionOptions;\n\n/**\n * Type for property descriptors, as used by\n * Interpreter.prototype.Object.prototype.defineProperty and\n * ...getOwnPropertyDescriptor.\n * @record\n */\nInterpreter.Descriptor = function() {};\n\n/** @type {(?Interpreter.Value|undefined)} */\nInterpreter.Descriptor.prototype.value;\n\n/** @type {boolean|undefined} */\nInterpreter.Descriptor.prototype.writable;\n\n/** @type {boolean|undefined} */\nInterpreter.Descriptor.prototype.enumerable;\n\n/** @type {boolean|undefined} */\nInterpreter.Descriptor.prototype.configurable;\n\n/**\n * Convenience class for creating Interpreter.Descriptors, with\n * commonly-used examples and a function to easily create new\n * descriptors from a prototype.\n * @constructor\n * @struct\n * @implements {Interpreter.Descriptor}\n * @param {boolean=} writable Is the property writable?\n * @param {boolean=} enumerable Is the property enumerable?\n * @param {boolean=} configurable Is the property configurable?\n */\nvar Descriptor = function(writable, enumerable, configurable) {\n  if (writable !== undefined) this.writable = writable;\n  if (enumerable !== undefined) this.enumerable = enumerable;\n  if (configurable !== undefined) this.configurable = configurable;\n};\n\n/* Type declaration for the properties that\n * intrp.Object.prototype.defineProperty expects to see on a\n * descriptor.  We use \"|undefined)\", but what we really mean is \"|not\n * defined)\" because unfortunately Closure Compiler's type system has\n * no way to represent the latter.\n */\n/** @type {(?Interpreter.Value|undefined)} */\nDescriptor.prototype.value;\n/** @type {boolean|undefined} */\nDescriptor.prototype.writable;\n/** @type {boolean|undefined} */\nDescriptor.prototype.enumerable;\n/** @type {boolean|undefined} */\nDescriptor.prototype.configurable;\n\n/**\n * Returns a new descriptor with the same properties as this one, with\n * the addition of a value: member with the given value.\n * @param {?Interpreter.Value} value Value for the new descriptor.\n * @return {!Descriptor}\n */\nDescriptor.prototype.withValue = function(value) {\n  var desc = /** @type{!Descriptor} */(Object.create(this));\n  desc.value = value;\n  return desc;\n};\n\n/** @const */ Descriptor.wec = new Descriptor(true, true, true);\n/** @const */ Descriptor.ec = new Descriptor(false, true, true);\n/** @const */ Descriptor.wc = new Descriptor(true, false, true);\n/** @const */ Descriptor.we = new Descriptor(true, true, false);\n/** @const */ Descriptor.w = new Descriptor(true, false, false);\n/** @const */ Descriptor.e = new Descriptor(false, true, false);\n/** @const */ Descriptor.c = new Descriptor(false, false, true);\n/** @const */ Descriptor.none = new Descriptor(false, false, false);\n\n///////////////////////////////////////////////////////////////////////////////\n// Static Analysis Functions\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Get the list of BoundNames for an AST sub-tree.\n * @param {!Node} node AST node (program or function).\n * @return {!Object<string, (!Node|undefined)>} A map of\n *     bound names.  The keys are var and function declarations\n *     appearing in the subtree rooted at node; the values are\n *     undefined for VariableDeclarations or a FunctionDeclaration\n *     node for FunctionDeclarations.\n */\nvar getBoundNames = function(node) {\n  if (!node['boundNames']) {\n    performStaticAnalysis(node);\n  }\n  return node['boundNames'];\n};\n\n/**\n * Check if an AST contains Identifiers named \"arguments\" or \"eval\".\n * @param {!Node} node AST node (program or function).\n * @return boolean True iff tree rooted at node contains an Identifier\n *     named \"arguments\" or \"eval\", not including any\n *     FunctionDeclaration or FunctionExpression subtrees.\n */\nvar hasArgumentsOrEval = function(node) {\n  if (node['hasArgumentsOrEval'] === undefined) {\n    performStaticAnalysis(node);\n  }\n  return node['hasArgumentsOrEval'];\n};\n\n/**\n * The IsAnonymousFunctionDefinition specification method from ES6 §14.1.9\n * @param {!Node} node The node to be tested.\n * @return {boolean} True if node is an anonymous function expression.\n */\nvar isAnonymousFunctionDefinition = function(node) {\n  return node['type'] === 'FunctionExpression' && !node['id'];\n};\n\n/**\n * The IsIdentifierRef specification method from ES6 §12.2.1.4 and §12.3.1.4\n * @param {!Node} node The node to be tested.\n * @return {boolean} True if node is an identifier.\n */\nvar isIdentifierRef = function(node) {\n  return node['type'] === 'Identifier';\n};\n\n/**\n * Returns true iff node is a MemberExpression.\n * @param {!Node} node The node to be tested.\n * @return {boolean} True if node is an identifier.\n */\nvar isMemberRef = function(node) {\n  return node['type'] === 'MemberExpression';\n};\n\n/**\n * Walk an AST (or sub-tree), collecting bound names by looking for\n * VariableDeclaration and FunctionDeclaration nodes, and checking for\n * Identifiers named \"arguments\" or \"eval\".\n *\n * The BoundNames will be stored on node['boundNames'] as an\n * !Object<string, (!Node|undefined)>, where the keys are\n * the names of VariableDeclaration and FunctionDeclarations, and the\n * values are undefined for VariableDeclarations or a\n * FunctionDeclaration node for FunctionDeclarations.\n *\n * If any Identifier named \"arguments\" or \"eval\" is seen, and\n * node['hasArgumentsOrEval'] will be set to true; otherwise it will\n * be set to false.\n *\n * @param {!Node} node AST node (program or function).\n * @return {void}\n */\nvar performStaticAnalysis = function(node) {\n  /** !Object<string, (!Node|undefined)> */\n  var boundNames = node['boundNames'] = Object.create(null);\n  var hasArgumentsOrEval = false;\n  walk(node);\n  node['hasArgumentsOrEval'] = hasArgumentsOrEval;\n\n  /**\n   * Recursively Walk an AST sub-tree, populating boundNames as we go.\n   * @param {!Node} node AST node (program or function).\n   * Nested function writes to boundNames and hasArgumentsOrEval.\n   * @return {void}\n   * TODO(cpcallen): Limit recursion to only AST nodes that can\n   *     contain declarations (e.g. no ExpressionStatements?)\n   */\n  function walk(node) {\n    if (node['type'] === 'VariableDeclaration') {\n      for (var i = 0; i < node['declarations'].length; i++) {\n        // VariableDeclarations can't overwrite previous\n        // FunctionDeclarations (but initializer might at run time).\n        var name = node['declarations'][i]['id']['name'];\n        if (!(name in boundNames)) {\n          boundNames[name] = undefined;\n        }\n      }\n    } else if (node['type'] === 'Identifier') {\n      name = node['name'];\n      if (name === 'arguments' || name === 'eval') {\n        hasArgumentsOrEval = true;\n      }\n    } else if (node['type'] === 'FunctionDeclaration') {\n      // FunctionDeclarations overwrite any previous decl of the same name.\n      name = node['id']['name'];\n      boundNames[name] = node;\n      return;  // Do not recurse into function.\n    } else if (node['type'] === 'FunctionExpression') {\n      return;  // Do not recurse into function.\n    }\n    // Visit node's children.\n    for (var key in node) {\n      var prop = node[key];\n      if (prop && typeof prop === 'object') {\n        if (Array.isArray(prop)) {\n          for (var i = 0; i < prop.length; i++) {\n            if (prop[i] && prop[i] instanceof Node) {\n              walk(prop[i]);\n            }\n          }\n        } else {\n          if (prop instanceof Node) {\n            walk(prop);\n          }\n        }\n      }\n    }\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Step Functions: one to handle each node type.\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Typedef for step functions.\n *\n * TODO(cpcallen): It should be possible to declare individual\n * functions below using this typedef (instead of listing full type\n * details for each once\n * https://github.com/google/closure-compiler/issues/2857 is fixed.\n * @typedef {function(this: Interpreter,\n *                    !Interpreter.Thread,\n *                    !Array<!Interpreter.State>,\n *                    !Interpreter.State,\n *                    !Node)\n *               : (!Interpreter.State|undefined)}\n */\nInterpreter.StepFunction;\n\n/**\n * 'Map' of node types to their corresponding step functions.  Note\n * that a Map is much slower than a null-parent object (v8 in 2017).\n * @const {!Object<string, !Interpreter.StepFunction>}\n */\nvar stepFuncs_ = Object.create(null);\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ArrayExpression'] = function(thread, stack, state, node) {\n  var n = state.n_;\n  if (!state.tmp_) {  // Create Array object\n    state.tmp_ = new this.Array(state.scope.perms);\n  } else {  // Save most recently-evaluated element.\n    state.tmp_.set(String(n), state.value, state.scope.perms);\n    n++;\n  }\n  var /** !Array<!Node> */ elements = node['elements'];\n  // Skip any elided elements - they're not defined, not undefined.\n  while (n < elements.length && ! elements[n]) {\n    n++;\n  }\n  // Evaluate next element, if we've not run past end.\n  if (n < elements.length) {\n    state.n_ = n;\n    return new Interpreter.State(elements[n], state.scope);\n  }\n  state.tmp_.set('length', elements.length, state.scope.perms);\n  stack.pop();\n  stack[stack.length - 1].value = state.tmp_;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['AssignmentExpression'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Get Reference to left.\n    state.step_ = 1;\n    // Get Reference for left subexpression.\n    return new Interpreter.State(node['left'], state.scope, true);\n  }\n  if (!state.ref) throw new TypeError('left subexpression not an LVALUE??');\n  if (state.step_ === 1) {  // Evaluate right.\n    if (node['operator'] !== '=') {\n      state.tmp_ = this.getValue(state.ref, state.scope.perms);\n    }\n    state.step_ = 2;\n    return new Interpreter.State(node['right'], state.scope);\n  }\n  // state.step_ === 2: Got operand(s); do assignment.\n  var rightValue = state.value;\n  var value = state.tmp_;\n  switch (node['operator']) {\n    // Regular assignment is special due to function naming & destructuring.\n    case '=':\n      value = rightValue;\n      // Set name if anonymous function expression.\n      if (isAnonymousFunctionDefinition(node['right']) &&\n          (isIdentifierRef(node['left']) ||\n           (this.options.methodNames && isMemberRef(node['left'])))) {\n        var func = /** @type {!Interpreter.prototype.Function} */(value);\n        // TODO(ES6): Check that func does not already have a 'name'\n        // own property before calling setName?  (Spec requires, but\n        // unclear why since we know RHS is anonymous.  Proxies?)\n        func.setName(state.ref[1]);\n      }\n      break;\n    // All the rest are simple and similar.\n    case '+=':   value +=   rightValue; break;\n    case '-=':   value -=   rightValue; break;\n    case '*=':   value *=   rightValue; break;\n    case '/=':   value /=   rightValue; break;\n    case '%=':   value %=   rightValue; break;\n    case '<<=':  value <<=  rightValue; break;\n    case '>>=':  value >>=  rightValue; break;\n    case '>>>=': value >>>= rightValue; break;\n    case '&=':   value &=   rightValue; break;\n    case '^=':   value ^=   rightValue; break;\n    case '|=':   value |=   rightValue; break;\n    default:\n      throw new SyntaxError(\n          'Unknown assignment expression: ' + node['operator']);\n  }\n  this.setValue(state.ref, value, state.scope.perms);\n  stack.pop();\n  stack[stack.length - 1].value = value;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['BinaryExpression'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Evaluate left.\n    state.step_ = 1;\n    return new Interpreter.State(node['left'], state.scope);\n  }\n  if (state.step_ === 1) {  // Save left; evaluate right.\n    state.step_ = 2;\n    state.tmp_ = state.value;\n    return new Interpreter.State(node['right'], state.scope);\n  }\n  // state.step_ === 2: Got operands; do binary operation.\n  var leftValue = state.tmp_;\n  var rightValue = state.value;\n  var /** ?Interpreter.Value */ value;\n  switch (node['operator']) {\n    case '==':  value = leftValue ==  rightValue; break;\n    case '!=':  value = leftValue !=  rightValue; break;\n    case '===': value = leftValue === rightValue; break;\n    case '!==': value = leftValue !== rightValue; break;\n    case '>':   value = leftValue >   rightValue; break;\n    case '>=':  value = leftValue >=  rightValue; break;\n    case '<':   value = leftValue <   rightValue; break;\n    case '<=':  value = leftValue <=  rightValue; break;\n    case '+':   value = leftValue +   rightValue; break;\n    case '-':   value = leftValue -   rightValue; break;\n    case '*':   value = leftValue *   rightValue; break;\n    case '/':   value = leftValue /   rightValue; break;\n    case '%':   value = leftValue %   rightValue; break;\n    case '&':   value = leftValue &   rightValue; break;\n    case '|':   value = leftValue |   rightValue; break;\n    case '^':   value = leftValue ^   rightValue; break;\n    case '<<':  value = leftValue <<  rightValue; break;\n    case '>>':  value = leftValue >>  rightValue; break;\n    case '>>>': value = leftValue >>> rightValue; break;\n    case 'in':\n      if (!(rightValue instanceof this.Object)) {\n      throw new this.Error(state.scope.perms, this.TYPE_ERROR,\n            \"'in' expects an object, not '\" + rightValue + \"'\");\n      }\n      value = rightValue.has(String(leftValue), state.scope.perms);\n      break;\n    case 'instanceof':\n      if (!(rightValue instanceof this.Function)) {\n        throw new this.Error(state.scope.perms, this.TYPE_ERROR,\n            'Right-hand side of instanceof is not a function');\n      }\n      value = rightValue.hasInstance(leftValue, state.scope.perms);\n      break;\n    default:\n      throw new SyntaxError('Unknown binary operator: ' + node['operator']);\n  }\n  stack.pop();\n  stack[stack.length - 1].value = value;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['BlockStatement'] = function(thread, stack, state, node) {\n  var n = state.n_;\n  var /** ?Node */ statement = node['body'][n];\n  if (statement) {\n    state.n_ = n + 1;\n    return new Interpreter.State(statement, state.scope);\n  }\n  stack.pop();\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['BreakStatement'] = function(thread, stack, state, node) {\n  if (!thread) throw new Error('No thread in BreakStatement??');\n  this.unwind_(thread, Interpreter.CompletionType.BREAK, undefined,\n      node['label'] ? node['label']['name'] : undefined\n  );\n};\n\n/**\n * Extra info used by CallExpression, NewExpression and Call step\n * functions:\n * - func: the function to be called or constructed.\n * - this: the value of 'this' for the call.\n * - arguments: (evaluated) arguments to the call.\n * - directEval: is this a direct call to the global eval function?\n * - construct: is this a [[Construct]] call (rather than default [[Call]])?\n * - funcState: place for NativeFunction impls to save additional state info.\n * TODO(cpcallen): give funcState a narrower type.\n * @typedef {{func: ?Interpreter.prototype.Function,\n *            this: ?Interpreter.Value,\n *            arguments: !Array<?Interpreter.Value>,\n *            directEval: boolean,\n *            construct: boolean,\n *            funcState: *}}\n */\nInterpreter.CallInfo;\n\n/**\n * CallExpression AND NewExpression: the initial part that evaluates\n * the arguments etc.\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['CallExpression'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Evaluate callee.\n    // Special hack for Code City's \"new 'foo'\" syntax.\n    if (node['type'] === 'NewExpression' &&\n        node['callee']['type'] === 'Literal' &&\n        typeof node['callee']['value'] === 'string' &&\n        node['arguments'].length === 0) {\n      var builtin = node['callee']['value'];\n      if (!this.builtins.has(builtin)) {\n        throw new this.Error(state.scope.perms, this.REFERENCE_ERROR,\n            builtin + ' is not a builtin');\n      }\n      stack.pop();\n      stack[stack.length - 1].value = this.builtins.get(builtin);\n      return;\n    }\n    state.step_ = 1;\n    // Get reference for callee, because we need to get value of 'this'.\n    return new Interpreter.State(node['callee'], state.scope, true);\n  }\n  if (state.step_ === 1) {  // Evaluated callee, possibly got a reference.\n    // Determine value of the function.\n    state.step_ = 2;\n    var info = {func: null,\n                this: undefined,  // Since we have no global object.\n                arguments: [],\n                directEval: false,\n                construct: state.node['type'] === 'NewExpression',\n                funcState: undefined};\n    if (state.ref) {  // Callee was MemberExpression or Identifier.\n      state.tmp_ = this.getValue(state.ref, state.scope.perms);\n      if (state.ref[0] instanceof Interpreter.Scope) {\n        // (Globally or locally) named function - maybe named 'eval'?\n        info.directEval = (state.ref[1] === 'eval');\n      } else {\n        // Method call; save 'this' value.\n        info.this = state.ref[0];\n      }\n    } else {  // Callee already fully evaluated.\n      state.tmp_ = state.value;\n    }\n    state.info_ = info;\n    state.n_ = 0;\n  }\n  if (state.step_ === 2) {  // Evaluating arguments.\n    if (state.n_ !== 0) {  // Save previous arg.\n      state.info_.arguments[state.info_.arguments.length] = state.value;\n    }\n    if (node['arguments'][state.n_]) {  // Evaluate next arg.\n      return new Interpreter.State(node['arguments'][state.n_++], state.scope);\n    }\n    // All args evaluated.  Check info_.func is actually a function.\n    state.step_ = 3;  // N.B: SEE NOTE 1 ABOVE!\n    if (!(state.tmp_ instanceof this.Function)) {\n      throw new this.Error(state.scope.perms, this.TYPE_ERROR,\n          state.tmp_ + ' is not a function');\n    }\n    state.info_.func = state.tmp_;\n  }\n  // state.step_ === 3: Done evaluating arguments; do function call.\n  // Dummy Node (used only for type and position).\n  var callNode = new Node;\n  callNode['type'] = 'Call';\n  callNode['stepFunc'] = stepFuncs_['Call'];\n  callNode['start'] = node['start'];\n  // New State for Call (or Construct).\n  var callState = new Interpreter.State(callNode, state.scope);\n  callState.info_ = state.info_;\n  // Replace this CallExpression State with the new Call State.\n  stack[stack.length - 1] = callState;\n  // We know exactly which step function will get called next, so go\n  // straight there:\n  return stepFuncs_['Call'].call(this, thread, stack, callState, callNode);\n};\n\n/**\n * Call: the latter part of CallExpression / NewExpression, when the\n * actual call/construct takes place.\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['Call'] = function(thread, stack, state, node) {\n  /* NOTE: Beware that, because\n   *\n   *  - an async function might not *actually* be async, and thus\n   *  - its .call function might call its reject before returning, and\n   *  - reject will unwind the stack, and\n   *  - Interpreter#step and Interpreter#run will push any State\n   *    returned by a step function such as this one,\n   *\n   * this Call step function MUST NOT return a State after\n   * calling .call (or .construct), or the thread might end up in some\n   * nonsensical, corrupt configuration.\n   *\n   * (It's fine to return a State if it *hasn't* called .call or\n   * .construct - for example, on a subsequent invocation - though\n   * there is no obvious reason to do so.)\n   */\n  if (state.step_ === 0) {  // Done evaluating arguments; do function call.\n    state.step_ = 1;\n    if (this.options.stackLimit && stack.length > this.options.stackLimit) {\n      throw new this.Error(state.scope.perms, this.RANGE_ERROR,\n          'Maximum call stack size exceeded');\n    }\n    var func = state.info_.func;\n    var args = state.info_.arguments;\n    // Abort call if out of time, unless it's a call to Thread.suspend().\n    if (func !== this.builtins.get('Thread.suspend')) {\n      try {\n        this.checkTimeLimit_(state.scope.perms);\n      } catch (e) {\n        stack.pop();  // Remove not-called function from stack trace.\n        throw e;\n      }\n    }\n    var r =\n        state.info_.construct ?\n        func.construct(this, thread, state, args) :\n        func.call(this, thread, state, state.info_.this, args);\n    if (r instanceof Interpreter.FunctionResult) {\n      switch (r) {\n        case Interpreter.FunctionResult.AwaitValue:\n          return;\n        case Interpreter.FunctionResult.Block:\n          thread.status = Interpreter.Thread.Status.BLOCKED;\n          return;\n        case Interpreter.FunctionResult.CallAgain:\n          state.step_ = 0;\n          return;\n        case Interpreter.FunctionResult.Sleep:\n          thread.status = Interpreter.Thread.Status.SLEEPING;\n          return;\n        default:\n          throw new Error('Unknown FunctionResult??');\n      }\n    }\n    state.value = r;\n  }\n  // state.step_ === 1: Execution done; handle return value.\n  stack.pop();\n  // Previous stack frame may not exist if this is a setTimeout function.\n  if (stack.length > 0) {\n    stack[stack.length - 1].value = state.value;\n  }\n};\n\n/**\n * ConditionalExpression AND IfStatement.  The only difference is the\n * latter does not return a value to the parent state.\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ConditionalExpression'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Evaluate test.\n    state.step_ = 1;\n    return new Interpreter.State(node['test'], state.scope);\n  }\n  // state.step_ === 1: Test evaluated; result is in .value\n  var value = Boolean(state.value);\n  stack.pop();\n  if (value && node['consequent']) {\n    // Execute 'if' block.\n    return new Interpreter.State(node['consequent'], state.scope);\n  }\n  if (!value && node['alternate']) {\n    // Execute 'else' block.\n    return new Interpreter.State(node['alternate'], state.scope);\n  }\n  // eval('1;if(false){2}') -> undefined\n  thread.value = undefined;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ContinueStatement'] = function(thread, stack, state, node) {\n  this.unwind_(thread, Interpreter.CompletionType.CONTINUE, undefined,\n      node['label'] ? node['label']['name'] : undefined);\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['DebuggerStatement'] = function(thread, stack, state, node) {\n  // Do nothing.  May be overridden by developers.\n  stack.pop();\n};\n\n/**\n * DoWhileStatement AND WhileStatement.  The only difference is the\n * former skips evaluating the test expression the first time through.\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['DoWhileStatement'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Decide whether to skip first test.\n    state.step_ = 1;\n    if (node['type'] === 'DoWhileStatement') {\n      // First iteration of do/while executes without checking test.\n      state.value = true;\n      state.step_ = 2;\n    }\n  }\n  if (state.step_ === 1) {  // Evaluate condition.\n    // Terminate loop if out of time.\n    this.checkTimeLimit_(state.scope.perms);\n    state.step_ = 2;\n    return new Interpreter.State(node['test'], state.scope);\n  }\n  // state.step_ === 2: Check result of evaluation.\n  if (!state.value) {  // Done, exit loop.\n    stack.pop();\n  } else if (node['body']) {  // Execute the body.\n    state.step_ = 1;\n    state.isLoop = true;\n    return new Interpreter.State(node['body'], state.scope);\n  }\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['EmptyStatement'] = function(thread, stack, state, node) {\n  stack.pop();\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['EvalProgram_'] = function(thread, stack, state, node) {\n  var n = state.n_;\n  var /** ?Node */ expression = node['body'][n];\n  if (expression) {\n    state.n_ = n + 1;\n    return new Interpreter.State(expression, state.scope);\n  }\n  stack.pop();\n  stack[stack.length - 1].value = thread.value;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ExpressionStatement'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Evaluate expression.\n    state.step_ = 1;\n    return new Interpreter.State(node['expression'], state.scope);\n  }\n  // state.step_ === 1: Handle completion value.\n  stack.pop();\n  // Save this value to interpreter.value for use as a return value if\n  // this code is inside an eval function.\n  //\n  // TODO(cpcallen): This is suspected to not be strictly correct\n  // compared to how the ES5.1 spec defines completion values.  Add\n  // tests to prove it one way or the other.\n  thread.value = state.value;\n};\n\n/**\n * Extra info used by ForInStatement step function.\n * @typedef {{iter: !Interpreter.PropertyIterator,\n              key: string}}\n */\nInterpreter.ForInInfo;\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ForInStatement'] = function(thread, stack, state, node) {\n  while (true) {\n    switch (state.step_) {\n      case 0:  // Initial set-up.\n        // First, variable initialization is illegal in strict mode.\n        if (node['left']['declarations'] &&\n            node['left']['declarations'][0]['init']) {\n          throw new this.Error(state.scope.perms, this.SYNTAX_ERROR,\n              'for-in loop variable declaration may not have an initializer.');\n        }\n        state.step_ = 1;\n        state.isLoop = true;  // TODO(cpcallen): remove or declare.\n        // Second, look up the object.  Only do so once, ever.\n        return new Interpreter.State(node['right'], state.scope);\n      case 1:  // Check right, create PropertyIterator.\n        if (state.value === null || state.value === undefined) {\n          // No iterations to do; exit loop.\n          stack.pop();\n          return;\n        }\n        var obj = this.toObject(state.value, state.scope.perms);\n        var iter = new Interpreter.PropertyIterator(obj, state.scope.perms);\n        state.info_ = {iter: iter, key: ''};\n        // FALL THROUGH\n      case 2:  // Find the property name for this iteration; do node.left.\n        // Terminate loop if out of time.\n        this.checkTimeLimit_(state.scope.perms);\n        var key = state.info_.iter.next();\n        if (key === undefined) {\n          // Done; exit loop.\n          stack.pop();\n          return;\n        }\n        state.info_.key = key;\n        // Get (or create) a Reference to node.left:\n        var /** ?Node */ left = node['left'];\n        if (left['type'] !== 'VariableDeclaration') {\n          state.step_ = 3;\n          // Arbitrary left side, e.g.: for (foo().bar in y).\n          // Get Reference to whatever left side turns out to be.\n          return new Interpreter.State(left, state.scope, true);\n        }\n        // Inline variable declaration: for (var x in y)\n        var lhsName = left['declarations'][0]['id']['name'];\n        state.ref = [state.scope.resolve(lhsName), lhsName];\n        // FALL THROUGH\n      case 3:  // Got .ref to variable to set.  Set it next key.\n        if (!state.ref) throw new TypeError('loop variable not an LVALUE??');\n        this.setValue(state.ref, state.info_.key, state.scope.perms);\n        // Execute the body if there is one, followed by next iteration.\n        state.step_ = 2;\n        if (node['body']) {\n          return new Interpreter.State(node['body'], state.scope);\n        }\n    }\n  }\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ForStatement'] = function(thread, stack, state, node) {\n  // If we've just evaluated node.test, and result was false, terminate loop.\n  if (state.step_ === 2 && !state.value) {\n    stack.pop();\n    return;\n  }\n  while (true) {\n    switch (state.step_) {\n      case 0:  // Eval init expression.\n        state.step_ = 1;\n        state.isLoop = true;  // TODO(cpcallen): remove or declare.\n        if (node['init']) {\n          return new Interpreter.State(node['init'], state.scope);\n        }\n        // FALL THROUGH\n      case 1:  // Eval test expression.\n        // Terminate loop if out of time.\n        this.checkTimeLimit_(state.scope.perms);\n        state.step_ = 2;\n        if (node['test']) {\n          return new Interpreter.State(node['test'], state.scope);\n        }\n        // FALL THROUGH\n      case 2:  // Eval body.\n        state.step_ = 3;\n        return new Interpreter.State(node['body'], state.scope);\n      case 3:  // Eval update expression.\n        state.step_ = 1;\n        if (node['update']) {\n          return new Interpreter.State(node['update'], state.scope);\n        }\n    }\n  }\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['FunctionDeclaration'] = function(thread, stack, state, node) {\n  // This was found and handled when the scope was populated.\n  stack.pop();\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['FunctionExpression'] = function(thread, stack, state, node) {\n  var source = thread.getSource();\n  if (!source) {\n    throw new Error(\"No source found when evaluating function expression??\");\n  }\n  var scope = state.scope;\n  var perms = scope.perms;\n  // If the function expression has a name, create an outer scope to\n  // bind that name.  See ES5.1 §13 / ES6 §14.1.20.\n  var name = node['id'] && node['id']['name'];\n  if (name) {\n    scope = new Interpreter.Scope(Interpreter.Scope.Type.FUNEXP, perms, scope);\n  }\n  var func = new this.UserFunction(node, scope, source, perms);\n  if (name) scope.createImmutableBinding(name, func);\n  stack.pop();\n  stack[stack.length - 1].value = func;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['Identifier'] = function(thread, stack, state, node) {\n  var /** string */ name = node['name'];\n  if (state.wantRef_) {\n    stack.pop();\n    stack[stack.length - 1].ref = [state.scope.resolve(name), name];\n  } else {\n    var value = this.getValueFromScope(state.scope, name);\n    stack.pop();  // Must be after call to getValueFromScope, which might throw.\n    stack[stack.length - 1].value = value;\n  }\n};\n\nstepFuncs_['IfStatement'] = stepFuncs_['ConditionalExpression'];\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['LabeledStatement'] = function(thread, stack, state, node) {\n  // Note that a statement might have multiple labels.\n  var /** !Array<string> */ labels = state.labels || [];\n  labels[labels.length] = node['label']['name'];\n  var nextState = new Interpreter.State(node['body'], state.scope);\n  nextState.labels = labels;\n  // No need to hit LabelStatement node again on the way back up the stack.\n  stack.pop();\n  return nextState;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['Literal'] = function(thread, stack, state, node) {\n  var /** (null|boolean|number|string|!RegExp) */ literal = node['value'];\n  var /** ?Interpreter.Value */ value;\n  if (literal instanceof RegExp) {\n    value = new this.RegExp(literal, state.scope.perms);\n  } else {\n    value = literal;\n  }\n  stack.pop();\n  stack[stack.length - 1].value = value;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['LogicalExpression'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Eval left.\n    state.step_ = 1;\n    return new Interpreter.State(node['left'], state.scope);\n  }\n  // state.step_ == 1: Check for short-circuit; optionally eval right.\n  stack.pop();\n  var /** string */ op = node['operator'];\n  if (op !== '&&' && op !== '||') {\n    throw new SyntaxError(\"Unknown logical operator '\" + op + \"'\");\n  } else if ((op === '&&' && !state.value) || (op === '||' && state.value)) {\n    // Short circuit.  Return left value.\n    stack[stack.length - 1].value = state.value;\n  } else {\n    // Tail-eval right.\n    return new Interpreter.State(node['right'], state.scope);\n  }\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['MemberExpression'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Evaluate LHS (object).\n    state.step_ = 1;\n    return new Interpreter.State(node['object'], state.scope);\n  } else if (state.step_ === 1) {  // Evaluate RHS (property key) if necessary.\n    state.tmp_ = state.value;\n    if (node['computed']) {  // obj[foo] -- Compute value of 'foo'.\n      state.step_ = 2;\n      return new Interpreter.State(node['property'], state.scope);\n    }\n  }\n  // TODO(cpcallen): add test for order of following two specification\n  // method calls from the algorithm in ES6 §2.3.2.1.\n  // Step 7: bv = RequireObjectCoercible(baseValue).\n  var /** ?Interpreter.Value */ base = state.tmp_;\n  var /** !Interpreter.Owner */ perms = state.scope.perms;\n  if (base === null || base === undefined) {\n    throw new this.Error(perms, this.TYPE_ERROR,\n        \"Can't convert \" + base + ' to Object');\n  }\n  // Step 9: propertyKey = ToPropertyKey(propertyNameValue).\n  var /** string */ key =\n      node['computed'] ? String(state.value) : node['property']['name'];\n  stack.pop();  // Must be after last throw new this.Error...\n  if (state.wantRef_) {\n    stack[stack.length - 1].ref = [base, key];\n  } else {\n    // toObject guaranteed not to throw because of earlier check.\n    stack[stack.length - 1].value = this.toObject(base, perms).get(key, perms);\n  }\n};\n\nstepFuncs_['NewExpression'] = stepFuncs_['CallExpression'];\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ObjectExpression'] = function(thread, stack, state, node) {\n  var n = state.n_;\n  if (!state.tmp_) {  // First execution.  Create object.\n    state.tmp_ = new this.Object(state.scope.perms);\n  } else {  // Save just-evaluated property value in object.\n    // Determine property name.\n    var /** ?Node */ keyNode = node['properties'][n]['key'];\n    if (keyNode['type'] === 'Identifier') {\n      var /** string */ key = keyNode['name'];\n    } else if (keyNode['type'] === 'Literal') {\n      key = keyNode['value'];\n    } else {\n      throw new SyntaxError('Unknown object structure: ' + keyNode['type']);\n    }\n    var value = state.value;\n    var perms = state.scope.perms;\n    // Set name if anonymous function expression.\n    if (isAnonymousFunctionDefinition(node['properties'][n]['value'])) {\n      var func = /** @type {!Interpreter.prototype.Function} */(value);\n      // TODO(ES6): Check that func does not already have a 'name' own\n      // property before calling setName?  (Spec requires, but unclear\n      // why since we know RHS is anonymous.  Proxies?)\n      func.setName(key);\n    }\n    // Set the property computed in the previous execution.\n    state.tmp_.defineProperty(key, Descriptor.wec.withValue(value), perms);\n    state.n_ = ++n;\n  }\n  var /** ?Node */ property = node['properties'][n];\n  if (property) {\n    if (property['kind'] !== 'init') {\n      throw new this.Error(state.scope.perms, this.SYNTAX_ERROR,\n          'Only plain properties are supported - not getters or setters');\n    }\n    return new Interpreter.State(property['value'], state.scope);\n  }\n  stack.pop();\n  stack[stack.length - 1].value = state.tmp_;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['Program'] = function(thread, stack, state, node) {\n  var n = state.n_;\n  var /** ?Node */ expression = node['body'][n];\n  if (expression) {\n    state.n_ = n + 1;\n    return new Interpreter.State(expression, state.scope);\n  }\n  stack.pop();\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ReturnStatement'] = function(thread, stack, state, node) {\n  if (node['argument'] && state.step_ === 0) {\n    state.step_ = 1;\n    return new Interpreter.State(node['argument'], state.scope);\n  }\n  this.unwind_(\n      thread, Interpreter.CompletionType.RETURN, state.value, undefined);\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['SequenceExpression'] = function(thread, stack, state, node) {\n  var n = state.n_;\n  var /** !Node */ expression = node['expressions'][n++];\n  if (n >= node['expressions'].length) {\n    stack.pop();\n  }\n  state.n_ = n;\n  return new Interpreter.State(expression, state.scope);\n};\n\n/**\n * Extra info used by SwitchStatement step function.\n * @typedef {{default: number}}\n */\nInterpreter.SwitchInfo;\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['SwitchStatement'] = function(thread, stack, state, node) {\n  // First check return value to see if case test succeeded.\n  if (state.step_ === 2 && state.value === state.tmp_) {\n    state.step_ = 3;\n  }\n  switch (state.step_) {\n    case 0:  // Start by evaluating discriminant.\n      state.step_ = 1;\n      return new Interpreter.State(node['discriminant'], state.scope);\n    case 1:  // Got evaluated discriminant.  Save it.\n      state.tmp_ = state.value;\n      state.isSwitch = true;\n      state.info_ = {default: -1};\n      state.n_ = -1;\n      state.step_ = 2;\n      // FALL THROUGH\n    case 2:  // Find case with non-empty test and evaluate test expression.\n      var /** Array<!Node> */ cases = node['cases'];\n      var /** number */ len = cases.length;\n      var n = state.n_ + 1;\n      if (n < len && !cases[n]['test']) {  // Found default case. Record & skip.\n        state.info_.default = n++;\n      }\n      if (n < len) {  // Found non-empty test expression.  Evaluate.\n        state.n_ = n;\n        return new Interpreter.State(cases[n]['test'], state.scope);\n      }\n      // Ran out of cases to test.\n      if (state.info_.default === -1) {  // And there's no default.  Terminate.\n        stack.pop();\n        return;\n      }\n      // Use default case.\n      state.n_ = state.info_.default;\n      // FALL THROUGH\n    case 3:  // Found correct case.  Prep for executing consequents.\n      state.tmp_ = 0;  // Begin with the 0th consequent of current case.\n      state.step_ = 4;\n      // FALL THROUGH\n    case 4:  // Execute case[n_].consequent[tmp_] (or next available).\n      cases = node['cases'];\n      len = cases.length;\n      for (n = state.n_; n < len; n++) {\n        var /** ?Node */ conseq = cases[n]['consequent'];\n        if (conseq && conseq[state.tmp_]) {\n          state.n_ = n;\n          return new Interpreter.State(conseq[state.tmp_++], state.scope);\n        }\n        state.tmp_ = 0;  // Done this case; fall through 0th statement of next.\n      }\n      stack.pop();  // All done.\n  }\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ThisExpression'] = function(thread, stack, state, node) {\n  stack.pop();\n  stack[stack.length - 1].value = state.scope.this;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['ThrowStatement'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Evaluate value to throw.\n    state.step_ = 1;\n    return new Interpreter.State(node['argument'], state.scope);\n  }\n  throw state.value;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['TryStatement'] = function(thread, stack, state, node) {\n  switch (state.step_) {\n    case 0:  // Evaluate 'try' block.\n      state.step_ = 1;\n      return new Interpreter.State(node['block'], state.scope);\n    case 1:  // Back from 'try' block.  Run catch?\n      state.step_ = 2;\n      var /** ?Node */ handler = node['handler'];\n      var cv = /** ?Interpreter.Completion */ (state.info_);\n      if (handler && cv && cv.type === Interpreter.CompletionType.THROW) {\n        state.info_ = null;  // This error is being handled, don't rethrow.\n        // Execute catch clause with varible bound to exception value.\n        var scope = new Interpreter.Scope(\n            Interpreter.Scope.Type.CATCH, state.scope.perms, state.scope);\n        scope.createMutableBinding(handler['param']['name'], cv.value);\n        return new Interpreter.State(handler['body'], scope);\n      }\n      // FALL THROUGH\n    case 2:  // Done 'try' and 'catch'.  Do 'finally'?\n      if (node['finalizer']) {\n        state.step_ = 3;\n        return new Interpreter.State(node['finalizer'], state.scope);\n      }\n      // FALL TRHOUGH\n    case 3:\n      // Regardless of whether we are exiting normally or about to\n      // resume unwinding the stack, we are done with this\n      // TryStatement and do not want to examine it again.\n      stack.pop();\n      if (state.info_) {\n        // There was no catch handler, or the catch/finally threw an\n        // error.  Resume unwinding the stack in search of\n        // TryStatement / Call / target of break or continue.\n        this.unwind_(\n            thread, state.info_.type, state.info_.value, state.info_.label);\n      }\n  }\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['UnaryExpression'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Evaluate (or get reference) to argument.\n    state.step_ = 1;\n    // Get argument - need Reference if operator is 'delete' or 'typeof:\n    var wr = (node['operator'] === 'delete') || (node['operator'] === 'typeof');\n    return new Interpreter.State(node['argument'], state.scope, wr);\n  }\n  var value = state.value;\n  if (node['operator'] === '-') {\n    value = -value;\n  } else if (node['operator'] === '+') {\n    value = +value;\n  } else if (node['operator'] === '!') {\n    value = !value;\n  } else if (node['operator'] === '~') {\n    value = ~value;\n  } else if (node['operator'] === 'delete') {\n    if (state.ref) {\n      if (state.ref[0] instanceof Interpreter.Scope) {\n        // Whoops; this should have been caught by Acorn (because strict).\n        throw new Error('Uncaught illegal deletion of unqualified identifier');\n      }\n      var obj = this.toObject(state.ref[0], state.scope.perms);\n      value = obj.deleteProperty(state.ref[1], state.scope.perms);\n    } else {\n      // Attempted to deleted some expression that wasn't a reference\n      // to a variable or property.  Skip delete; return true.\n      value = true;\n    }\n  } else if (node['operator'] === 'typeof') {\n    if (state.ref) {\n      var perms = state.scope.perms;\n      if (this.isUnresolvableReference(state.scope, state.ref, perms)) {\n        value = undefined;\n      } else {\n        value = this.getValue(state.ref, perms);\n      }\n    }\n    value = (value instanceof this.Function) ? 'function' : typeof value;\n  } else if (node['operator'] === 'void') {\n    value = undefined;\n  } else {\n    throw new SyntaxError('Unknown unary operator: ' + node['operator']);\n  }\n  stack.pop();\n  stack[stack.length - 1].value = value;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['UpdateExpression'] = function(thread, stack, state, node) {\n  if (state.step_ === 0) {  // Get Reference to argument.\n    state.step_ = 1;\n    return new Interpreter.State(node['argument'], state.scope, true);\n  }\n  if (!state.ref) throw new TypeError('argument not an LVALUE??');\n  var value = Number(this.getValue(state.ref, state.scope.perms));\n  var prefix = Boolean(node['prefix']);\n  var /** ?Interpreter.Value */ rval;\n  if (node['operator'] === '++') {\n    rval = (prefix ? ++value : value++);\n  } else if (node['operator'] === '--') {\n    rval = (prefix ? --value : value--);\n  } else {\n    throw new SyntaxError('Unknown update expression: ' + node['operator']);\n  }\n  this.setValue(state.ref, value, state.scope.perms);\n  stack.pop();\n  stack[stack.length - 1].value = rval;\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['VariableDeclaration'] = function(thread, stack, state, node) {\n  var declarations = node['declarations'];\n  var n = state.n_;\n  var decl = declarations[n];\n  if (state.step_ === 1) {  // Initialise variable with evaluated init value.\n    var name = decl['id']['name'];\n    var value = state.value;\n    if (isAnonymousFunctionDefinition(decl['init'])) {\n      var func = /** @type {!Interpreter.prototype.Function} */(value);\n      // TODO(ES6): Check that func does not already have a 'name' own\n      // property before calling setName?  (Spec requires, but unclear\n      // why since we know RHS is anonymous.  Proxies?)\n      func.setName(name);\n    }\n    // Note that this is setting the value, not defining the variable.\n    // Variable definition is done when scope is populated.\n    this.setValueToScope(state.scope, name, value);\n    decl = declarations[++n];\n  }\n  while (decl) {\n    // Skip any declarations that are not initialized.  They have already\n    // been defined as undefined in populateScope_.\n    if (decl['init']) {\n      state.n_ = n;\n      state.step_ = 1;\n      return new Interpreter.State(decl['init'], state.scope);\n    }\n    decl = declarations[++n];\n  }\n  stack.pop();\n};\n\n/**\n * @this {!Interpreter}\n * @param {!Interpreter.Thread} thread\n * @param {!Array<!Interpreter.State>} stack\n * @param {!Interpreter.State} state\n * @param {!Node} node\n * @return {!Interpreter.State|undefined}\n */\nstepFuncs_['WithStatement'] = function(thread, stack, state, node) {\n  throw new this.Error(state.scope.perms, this.SYNTAX_ERROR,\n      'Strict mode code may not include a with statement');\n};\n\nstepFuncs_['WhileStatement'] = stepFuncs_['DoWhileStatement'];\n\n// Give each step function a serialisation id.\nfor (var name in stepFuncs_) {\n  stepFuncs_[name].id = 'Step Function: ' + name;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Exports\n///////////////////////////////////////////////////////////////////////////////\n\nexports = module.exports = Interpreter;\n\nexports.testOnly = {\n  getBoundNames: getBoundNames,\n  hasArgumentsOrEval: hasArgumentsOrEval,\n};\n"
  },
  {
    "path": "server/iterable_weakmap.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview A WeakMap that's iterable.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\n/**\n * A (WeakRef<KEY>, value) tuple in an IterableWeakMap.\n * @template KEY, VALUE\n */\nclass Cell {\n  /**\n   * @param {!WeakRef<KEY>} ref A WeakRef to the key for this cell.\n   * @param {VALUE} value The value for this cell.\n   */\n  constructor(ref, value) {\n    /** @type {!WeakRef<KEY>} */\n    this.ref = ref;\n    /** @type {VALUE} */\n    this.value = value;\n  }\n}\n\n/**\n * A WeakMap implementing the full Map interface, including iterability.\n * @struct\n * @implements {Iterable<!Array<KEY|VALUE>>}\n * @template KEY, VALUE\n */\n// TODO(cpcallen): Make KEY a bounded to {!Object} once\n// Closure Compiler supports bounded generic types\nclass IterableWeakMap extends WeakMap {\n  /**\n   * @param {!Iterable<!Array<KEY|VALUE>>|!Array<!Array<KEY|VALUE>>=} iterable\n   */\n  constructor(iterable = undefined) {\n    super();\n    /** @private @const @type {!Set<!WeakRef<KEY>>} */\n    this.refs_ = new Set();\n    /**\n     * @private @const\n     * @type {!FinalizationRegistry<VALUE, !WeakRef<VALUE>, !WeakRef<VALUE>>}\n     */\n    this.finalisers_ = new FinalizationRegistry(ref => {\n      this.refs_.delete(ref);\n    });\n\n    if (iterable === null || iterable === undefined) {\n      return;\n    }\n    const adder = this.set;\n    if (typeof adder !== 'function') {\n      throw new TypeError(\"'\" + this.set + \"' returned for property 'set' \" +\n          'of object ' + this + ' is not a function');\n    }\n    for (const /** ?Array<KEY|VALUE>> */ entry of iterable) {\n      if (typeof entry !== 'object' && typeof entry !== 'function' ||\n          entry === null) {\n        throw new TypeError(\n            'Iterator value ' + entry + ' is not an entry object');\n      }\n      adder.call(this, entry[0], entry[1]);\n    }\n  }\n\n  /**\n   * Remove all entries from the map.\n   * @return {void}\n   * @override\n   */\n  clear() {\n    for (const ref of this.refs_) {\n      const key = ref.deref();\n      if (key !== undefined) this.delete(key);\n    }\n    this.refs_.clear();  // Remove anything GCed but not finalised.\n  }\n\n  /**\n   * Remove a single entry from the map.\n   * @param {KEY} key The key to be deleted.\n   * @return {boolean} Was anything deleted?\n   * @override\n   */\n  delete(key) {\n    const cell = super.get(key);\n    if (cell) {\n      this.refs_.delete(cell.ref);\n      this.finalisers_.unregister(cell.ref);\n    }\n    return super.delete(key);\n  }\n\n  /**\n   * Return a iterator over [key, value] pairs of the map.\n   * @return {!IteratorIterable<!Array<KEY|VALUE>>}\n   */\n  *entries() {\n    for (const ref of this.refs_) {\n      const key = ref.deref();\n      if (key === undefined) {  // key was garbage collected.  Remove ref.\n        this.refs_.delete(ref);\n      } else {\n        yield [key, super.get(key).value];\n      }\n    }\n  }\n\n  /**\n   * Execute the provided callback for each entry in the map, calling\n   * it with thisArg as its this value and arguments key, value and\n   * this map.\n   * @this {MAP}\n   * @param {function(this:THIS, VALUE, KEY, IterableWeakMap<KEY, VALUE>)}\n   *     callback\n   * @param {THIS=} thisArg\n   * @return {void}\n   * @template MAP, THIS\n   */\n  forEach(callback, thisArg = undefined) {\n    for (const [key, value] of this) {\n      callback.call(thisArg, value, key, this);\n    }\n  }\n\n  /**\n   * Return the value corresponding to a given key.\n   * @param {KEY} key The key whose corresponding value is desired.\n   * @return {VALUE} The value corresponging to key, or undefined if not found.\n   * @override\n   */\n  get(key) {\n    const cell = super.get(key);\n    return cell && cell.value;\n  }\n\n  /**\n   * Return an iterator over the keys of the map.\n   * @return {!IteratorIterable<KEY>}\n   */\n  *keys() {\n    for (const [key, value] of this) {\n      yield key;\n    }\n  }\n\n  /**\n   * Add or update the value associated with key in the map.\n   * @this {THIS}\n   * @param {KEY} key The key to add or update.\n   * @param {VALUE} value The new value to associate with key.\n   * @return {THIS}\n   * @override\n   * @template THIS\n   */\n  set(key, value) {\n    if (super.has(key)) {\n      super.get(key).value = value;\n    } else {\n      const ref = new WeakRef(key);\n      const cell = new Cell(ref, value);\n      super.set(key, cell);\n      this.refs_.add(ref);\n      this.finalisers_.register(key, ref, ref);\n    }\n    return this;\n  }\n\n  /**\n   * @return {number}\n   */\n  get size() {\n    return this.refs_.size;\n  }\n\n  /**\n   * Return an iterator over the value of the map.\n   * @return {!IteratorIterable<VALUE>}\n   */\n  *values() {\n    for (const [key, value] of this) {\n      yield value;\n    }\n  }\n}\n\nIterableWeakMap.prototype[Symbol.iterator] = IterableWeakMap.prototype.entries;\n\nmodule.exports = IterableWeakMap;\n"
  },
  {
    "path": "server/iterable_weakset.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview A WeakSet that's iterable.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\n/**\n * A WeakSet implementing the full Set interface, including iterability.\n * @struct\n * @extends {WeakSet}\n * @implements {Iterable<!Array<VALUE>>}\n * @template VALUE\n */\n// TODO(cpcallen): Make VALUE bounded to {!Object} once\n// Closure Compiler supports bounded generic types.\nclass IterableWeakSet {\n  /**\n   * @param {!Iterable<!Array<VALUE>>|!Array<!Array<VALUE>>=} iterable\n   */\n  constructor(iterable = undefined) {\n    /** @private @const @type {!Set<!WeakRef<VALUE>>} */\n    this.refs_ = new Set();\n    /** @private @const @type {!WeakMap<VALUE, !WeakRef<VALUE>>}} */\n    this.map_ = new WeakMap();\n    /**\n     * @private @const\n     * @type {!FinalizationRegistry<VALUE, !WeakRef<VALUE>, !WeakRef<VALUE>>}\n     */\n    this.finalisers_ = new FinalizationRegistry(ref => {\n      this.refs_.delete(ref);\n    });\n\n    if (iterable === null || iterable === undefined) {\n      return;\n    }\n    const adder = this.add;\n    if (typeof adder !== 'function') {\n      throw new TypeError(\"'\" + this.add + \"' returned for property 'add' \" +\n          'of object ' + this + ' is not a function');\n    }\n    for (const /** !VALUE */ value of iterable) {\n      if (typeof value !== 'object' && typeof value !== 'function' ||\n          value === null) {\n        throw new TypeError('Iterator value ' + value + ' is not an object');\n      }\n      adder.call(this, value);\n    }\n  }\n\n  /**\n   * Add the value to the set.\n   * @this {THIS}\n   * @param {VALUE} value The value to add.\n   * @return {THIS}\n   * @override\n   * @template THIS\n   */\n  add(value) {\n    if (!this.map_.has(value)) {\n      const ref = new WeakRef(value);\n      this.map_.set(value, ref);\n      this.refs_.add(ref);\n      this.finalisers_.register(value, ref, ref);\n    }\n    return this;\n  }\n\n  /**\n   * Remove all entries from the set.\n   * @return {void}\n   * @override\n   */\n  clear() {\n    for (const ref of this.refs_) {\n      const key = ref.deref();\n      if (key !== undefined) this.delete(key);\n    }\n    this.refs_.clear();  // Remove anything GCed but not finalised.\n  }\n\n  /**\n   * Remove a single entry from the set.\n   * @param {VALUE} value The value to be deleted.\n   * @return {boolean} Was anything deleted?\n   * @override\n   */\n  delete(value) {\n    const ref = this.map_.get(value);\n    if (ref) {\n      this.refs_.delete(ref);\n      this.finalisers_.unregister(ref);\n    }\n    return this.map_.delete(value);\n  }\n\n  /**\n   * Return a iterator over [value, value] pairs of the set.\n   * @return {!IteratorIterable<!Array<VALUE>>}\n   */\n  *entries() {\n    for (const value of this) {\n      yield [value, value];\n    }\n  }\n\n  /**\n   * Execute the provided callback for each entry in the set, calling\n   * it with thisArg as its this value and argument value (twice) and\n   * this set.\n   * @this {SET}\n   * @param {function(this:THIS, VALUE, VALUE, SET)} callback\n   * @param {THIS=} thisArg\n   * @return {void}\n   * @template SET, THIS\n   */\n  forEach(callback, thisArg = undefined) {\n    for (const value of this) {\n      callback.call(thisArg, value, value, this);\n    }\n  }\n\n  /**\n   * Return true iff value is a member of this set.\n   * @param {VALUE} value\n   * @return {boolean}\n   */\n  has(value) {\n    return this.map_.has(value);\n  }\n\n  /**\n   * @return {number}\n   */\n  get size() {\n    return this.refs_.size;\n  }\n\n  /**\n   * Return an iterator over the value of the set.\n   * @return {!IteratorIterable<VALUE>}\n   */\n  *values() {\n    for (const ref of this.refs_) {\n      const value = ref.deref();\n      if (value === undefined) {  // value was garbage collected.  Remove ref.\n        this.refs_.delete(ref);\n      } else {\n        yield value;\n      }\n    }\n  }\n}\n\nIterableWeakSet.prototype[Symbol.iterator] = IterableWeakSet.prototype.values;\nIterableWeakSet.prototype.keys = IterableWeakSet.prototype.values;\n\nmodule.exports = IterableWeakSet;\n"
  },
  {
    "path": "server/package.json",
    "content": "{\n  \"name\": \"codecity-server\",\n  \"version\": \"0.0.0\",\n  \"description\": \"Server for the Code City project\",\n  \"main\": \"codecity.js\",\n  \"dependencies\": {\n    \"acorn\": \"^8.1.1\"\n  },\n  \"devDependencies\": {\n    \"google-closure-compiler\": \"^20210406.0.0\"\n  },\n  \"scripts\": {\n    \"compile\": \"./compile\",\n    \"test\": \"tests/run\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/google/CodeCity.git\"\n  },\n  \"author\": \"Google\",\n  \"license\": \"Apache-2.0\",\n  \"bugs\": {\n    \"url\": \"https://github.com/google/CodeCity/issues\"\n  },\n  \"homepage\": \"https://github.com/google/CodeCity#readme\"\n}\n"
  },
  {
    "path": "server/parser.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Parser for Code City interpreter.\n * @author cpcallen@google.com (Christopher Allen)\n */\n\nvar acorn = require('acorn');\n\n///////////////////////////////////////////////////////////////////////////////\n// Externs for Acorn.\n///////////////////////////////////////////////////////////////////////////////\n// These are supplied here because Closure Compiler doesn't appear to\n// provide any good way to specify externs for a Node module, and the\n// mechanisms used to provide separate externs for Node's built-in\n// modules don't work with NPMs.\n//\n// Trivial 'initialisers' are provided for acorn.Node and acorn.Parser\n// to satisfy the compiler's requirement that constructors be\n// initialised at declaration.\n\n/**\n * @constructor\n * @param {!acorn.Parser} parser\n * @param {?} pos\n * @param {?} loc\n */\nacorn.Node = acorn.Node;\n\n/**\n * @constructor\n * @param {!Object} options Parse options.\n * @param {string} input The text to be parsed.\n * @param {number=} startPos Character offset to start parsing at.\n */\nacorn.Parser = acorn.Parser;\n\n/**\n * @return {!Node}\n */\nacorn.Parser.prototype.startNode;\n\n/**\n * @param {?} pos\n * @param {?} loc\n * @return {!Node}\n */\nacorn.Parser.prototype.startNodeAt;\n\n/**\n * @param {string} input\n * @param {!Object=} options\n */\nacorn.Parser.parse;\n\n/**\n * @param {string} input\n * @param {number} pos\n * @param {!Object=} options\n */\nacorn.Parser.parseExpressionAt;\n\n///////////////////////////////////////////////////////////////////////////////\n// Custom Parser subclass for Code City.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @const {!Object} Default options for Parser. */\nvar PARSE_OPTIONS = {ecmaVersion: 5, strict: true};\n\n/**\n * A subclass of acorn.Node, which has a constructor that can be\n * called without arguments (and in particular without the Parser\n * argument).\n *\n * This is mainly to facilitate deserialisation, but is also used\n * directly to create a fake (but but correctly typed) AST node for\n * 'eval'.\n *\n * @constructor\n * @extends {acorn.Node}\n * @param {!acorn.Parser=} parser\n * @param {?=} pos\n * @param {?=} loc\n */\nvar Node = function(parser, pos, loc) {\n  acorn.Node.call(this, parser || {options: PARSE_OPTIONS}, pos, loc);\n};\nObject.setPrototypeOf(Node, acorn.Node);\nObject.setPrototypeOf(Node.prototype, acorn.Node.prototype);\n\n/**\n * A subclass of acorn.Parser that:\n *\n * - Supports a strict option which, if true, forces strict mode.\n * - Defaults to using Interpreter.PARSE_OPTIONS if no options are\n *   supplied.\n * - Uses the overridden Node constructor above to create nodes.\n *\n * See https://github.com/acornjs/acorn/tree/master/acorn#interface\n * for details on how to use it, valid option values, etc.\n *\n * @constructor\n * @extends {acorn.Parser}\n * @param {!Object|undefined} options Parse options.  Defaults to\n *     Interpreter.PARSE_OPTIONS\n * @param {string} input The text to be parsed.\n * @param {number=} startPos Character offset to start parsing at.\n */\nvar Parser = function(options, input, startPos) {\n  if (!options) options = PARSE_OPTIONS;\n  acorn.Parser.call(this, options, input, startPos);\n  if (options.strict) this.strict = true;\n};\nObject.setPrototypeOf(Parser, acorn.Parser);\nObject.setPrototypeOf(Parser.prototype, acorn.Parser.prototype);\n\n/** @override */\nParser.prototype.startNode = function() {\n  return new Node(this, this.start, this.startLoc);\n};\n\n/** @overide */\nParser.prototype.startNodeAt = function(pos, loc) {\n  return new Node(this, pos, loc);\n};\n\n// Redeclare static methods because Closure Compiler isn't too smart\n// about static method inheritance in ES5.\n/** @override */ Parser.parse;\n/** @override */ Parser.parseExpressionAt;\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Exports\n///////////////////////////////////////////////////////////////////////////////\n\nexports.Parser = Parser;\nexports.PARSE_OPTIONS = PARSE_OPTIONS;\nexports.Node = Node;\n"
  },
  {
    "path": "server/priorityqueue.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview A priority queue implemented using a heap.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\n// Rant: I can't believe I have to write this myself, but a fairly\n// extensive search of GitHub and NPM did not turn up an existing\n// package that:\n//\n// - Allowed arbitrary JS values (including objects) in the queue,\n// - Does comparison by ===, SameValueZero or SameValue (Object.is)\n//   rather than using deepEquals or something equally foolish,\n// - Provided a decreasePriority method.\n\n/**\n * Returns the parent index of a given index in a heap.\n * @private\n * @param {number} i Index to get parent of.\n * @return {number} Index of parent, or -1 if i is 0.\n */\nfunction parent(i) {\n  if (i <= 0) return -1;\n  return Math.floor((i - 1) / 2);\n}\n\n/**\n * Returns the child indices of a given index in a heap.\n * @private\n * @param {number} i Index to get children of.\n * @return !Array<number> Two-element array of indicies of the chilren.\n */\nfunction children(i) {\n  return [(i * 2) + 1, (i * 2) + 2];\n}\n\n/**\n * A priority queue.\n * @stuct\n * @template T\n */\nclass PriorityQueue {\n  constructor() {\n   /** @private @const {!Array<{value: T, priority: number}>} */\n    this.heap_ = [];\n    /** @private @const {!Map<T,number>} */\n    this.indices_ = new Map();\n  }\n\n  /**\n   * Remove the minimum\n   * @return {T} The minimum-priority item just removed.\n   */\n  deleteMin() {\n    if (this.heap_.length === 0) {\n      throw RangeError('queue is empty');\n    }\n    const value = this.heap_[0].value;\n    this.indices_.delete(value);\n    if (this.heap_.length > 1) {\n      this.heap_[0] = this.heap_.pop();\n      // percolateDown_ will update indices_.\n      this.percolateDown_(0);\n    } else {\n      this.heap_.pop();\n    }\n    return value;\n  }\n\n  /**\n   * Insert an item in the queue.\n   * @param {T} value The item to be inserted.\n   * @param {number} priority The priority value to insert it with.\n   * @return {void}\n   */\n  insert(value, priority) {\n    this.set.call(this, value, priority);\n  }\n\n  /** @return {number} */\n  get length() {\n    return this.heap_.length;\n  }\n\n  /**\n   * Move the entry at .heap_[i] towards the leaves of the heap as\n   * required to retain heap ordering.\n   * @private\n   * @param {number} i Index of node to percolate up.\n   */\n  percolateDown_(i) {\n    const entry = this.heap_[i];\n    while (true) {\n      const [l, r] = children(i);\n      if (l >= this.heap_.length) break;  // No children.\n      let c = l;\n      if (r < this.heap_.length &&  // Two children.  Pick smallest.\n          this.heap_[r].priority < this.heap_[l].priority) {\n        c = r;\n      }\n      if (entry.priority <= this.heap_[c].priority) break;\n      this.heap_[i] = this.heap_[c];\n      this.indices_.set(this.heap_[c].value, i);\n      i = c;\n    }\n    this.heap_[i] = entry;\n    this.indices_.set(entry.value, i);\n  }\n\n  /**\n   * Move the entry at .heap_[i] towards the root of the heap as\n   * required to retain heap ordering.\n   * @private\n   * @param {number} i Index of node to percolate up.\n   */\n  percolateUp_(i) {\n    const entry = this.heap_[i];\n    while (i > 0) {\n      const p = parent(i);\n      if (this.heap_[p].priority <= entry.priority) break;\n      this.heap_[i] = this.heap_[p];\n      this.indices_.set(this.heap_[p].value, i);\n      i = p;\n    }\n    this.heap_[i] = entry;\n    this.indices_.set(entry.value, i);\n  }\n\n  /**\n   * Reduce the priority of a given value.\n   * @param {T} value The item to be modified.\n   * @param {number} priority The new priority value.  Must not be\n   *     greater than the existing value.\n   * @return {void}\n   */\n  reducePriority(value, priority) {\n    return this.set.call(this, value, priority);\n  }\n\n  /**\n   * Insert an item into the queue or update its priority.  If the\n   * value is already in the queue then priority must not be greater\n   * than the previous priority or RangeError will be thrown.\n   * @param {T} value The item to be inserted/updated.\n   * @param {number} priority The (new) priority for value.\n   * @return {void}\n   */\n  set(value, priority) {\n    let i = this.indices_.get(value);\n    if (i === undefined) {\n      i = this.heap_.length;\n      this.heap_.push({value, priority});\n    } else if (this.heap_[i].priority < priority) {\n      throw new RangeError('attempting to increase priority');\n    } else {\n      this.heap_[i].priority = priority;\n    }\n    // percolateUp will set/update this.indices_ entry for value.\n    this.percolateUp_(i);\n  }\n}\n\nexports.PriorityQueue = PriorityQueue;\nexports.testOnly = {parent, children};\n"
  },
  {
    "path": "server/registry.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview The Registry class, for e.g. registering built-ins.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst util = require('util');\n\n/**\n * Class for a registry providing a bijective[1] mapping between\n * string-valued keys and arbitrary values.\n *\n * N.B.: a Map is used for reverse lookups; as Maps use the\n * sameValueZero algorithm to compare keys[2] it is not possible to\n * register both 0 and -0, but NaN will work correctly.\n *\n * [1] This means no key may have more than one value, and no value\n *     may have more than one key.\n * [2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality\n *\n * @constructor\n * @template T\n */\nclass Registry {\n  constructor() {\n    /** @private @const @type {!Object<string, T>} */\n    this.values_ = Object.create(null);\n    /** @private @const @type {!Map<T, string>} */\n    this.keys_ = new Map();\n  }\n\n  /**\n   * Return an array of [key, value] pairs of the registry.\n   * @return {!Array<!Array<string|T>>}\n   */\n  entries() {\n    return Object.entries(this.values_);\n  }\n\n  /**\n   * Look up a registered value.  Throws an error if the given key has\n   * not been registered.\n   * @param {string} key The key to get the registered value for.\n   * @return {T} The registered value.\n   */\n  get(key) {\n    if (!this.has(key)) {\n      throw new Error('Key \"' + key + '\" not registered');\n    }\n    return this.values_[key];\n  }\n\n  /**\n   * Look up the key for a registered value.  Returns undefined if the\n   * given value has not been registered.\n   * @param {T} value The value to get the key for.\n   * @return {string|undefined} The key for value, or undefined if\n   *     value never registered.\n   */\n  getKey(value) {\n    return this.keys_.get(value);\n  }\n\n  /**\n   * Check if a key exists in the registry.\n   * @param {string} key The key to check.\n   * @return {boolean} True iff key has previously been registered.\n   */\n  has(key) {\n    return key in this.values_;\n  }\n\n  /**\n   * Return an array of keys of the registry.\n   * @return {!Array<string>}\n   */\n  keys() {\n    return Object.keys(this.values_);\n  }\n\n  /**\n   * Register a value.  Throws an error if the given key has already\n   * been used for a previous registration.\n   * @param {string} key The key to register value with.\n   * @param {T} value The value to be registered.\n   */\n  set(key, value) {\n    if (key in this.values_) {\n      throw new Error('Key \"' + key + '\" already in use');\n    }\n    if (this.keys_.has(value)) {\n      throw new Error(util.format('Value %O already registered', value));\n    }\n    this.values_[key] = value;\n    this.keys_.set(value, key);\n  }\n\n  /**\n   * Return an array of values of the registry.\n   * @return {!Array<T>}\n   */\n  values() {\n    return Object.values(this.values_);\n  }\n\n}\n\nmodule.exports = Registry;\n"
  },
  {
    "path": "server/repl",
    "content": "#!/usr/bin/env node\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Read Eval Print Loop (REPL) for JavaScript Interpreter.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst readline = require('readline');\nconst Interpreter = require('./interpreter');\nconst fs = require('fs');\n\nconst intrp = new Interpreter;\nintrp.createThreadForSrc(fs.readFileSync('startup/es5.js', 'utf8'));\nintrp.run();\nintrp.createThreadForSrc(fs.readFileSync('startup/es6.js', 'utf8'));\nintrp.run();\nintrp.createThreadForSrc(fs.readFileSync('startup/es7.js', 'utf8'));\nintrp.run();\nintrp.createThreadForSrc(fs.readFileSync('startup/esx.js', 'utf8'));\nintrp.run();\nintrp.createThreadForSrc(fs.readFileSync('startup/cc.js', 'utf8'));\nintrp.run();\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout,\n  removeHistoryDuplicates: true,\n});\n\nrl.prompt();\nrl.on('line', function(line) {\n  try {\n    let thread;\n    try {\n      thread = intrp.createThreadForSrc(line).thread;\n    } catch (e) {\n      console.log('%s: %s', e.name, e.message);\n      return;\n    }\n    intrp.run();\n    const value = thread.value;\n    if (value instanceof intrp.Function) {\n      console.log(value.toString());\n    } else {\n      console.log('%o', intrp.pseudoToNative(thread.value));\n    }\n  } finally {\n    rl.prompt();\n  }\n}).on('close', function() {\n  process.exit(0);\n});\n"
  },
  {
    "path": "server/selector.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview CSS-style selectors for JS objects.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nvar code = require('./code');\n\n/**\n * Type for all \"special\" selector parts (ones which do not represent\n * named variables / properties).\n * @constructor\n * @struct\n */\nvar SpecialPart = function(type) {\n  this.type = type;\n};\n\n/** @override */\nSpecialPart.prototype.toString = function() {\n  return '{' + this.type + '}';\n};\n\n/**\n * A Selector is just an array of Parts, which happens to have\n * Selector.prototype (with various useful convenience methods) in its\n * prototype chain.\n * @constructor\n * @extends {Array<Selector.Part>}\n * @param {string|!Array<Selector.Part>|!Selector} s A Selector, parts\n *     array or selector string.\n */\nvar Selector = function(s) {\n  var /** !Array<Selector.Part> */ parts;\n  if (typeof s === 'string') {\n    // Parse selector text.\n    parts = parse(s);\n  } else if (Array.isArray(s)) {\n    parts = [];\n    // Validate & copy parts array.\n    if (typeof s.length < 1) throw new RangeError('Zero-length parts array??');\n    if (s.length < 1) throw new RangeError('Zero-length parts array??');\n    if (typeof s[0] !== 'string' || !code.regexps.identifierExact.test(s[0])) {\n      throw new TypeError('Parts array must begin with an identifier');\n    }\n    parts[0] = s[0];\n    for (var i = 1; i < s.length; i++) {\n      if (typeof s[i] !== 'string' && !(s[i] instanceof SpecialPart)) {\n        throw new TypeError('Invalid part in parts array');\n      } else if ((s[i] instanceof SpecialPart) &&\n          s[i] !== Selector.PROTOTYPE && s[i] !== Selector.OWNER) {\n        throw new TypeError('Invalid SpecialPart in parts array');\n      }\n      parts[i] = s[i];\n    }\n  } else {\n    throw new TypeError('Not a selector or parts array');\n  }\n  Object.setPrototypeOf(parts, Selector.prototype);\n  return parts;\n};\n\nObject.setPrototypeOf(Selector.prototype, Array.prototype);\n\n/**\n * Return a \"badness\" score, inversely proportional to how desirable a\n * particular selector is amongst other selectors referring to the\n * same binding.  In general, longer selectors are more bad, but\n * selectors containing special parts are especially bad.\n * TODO(cpcallen): reintroduce penalty for non-builtins?\n * @return {number};\n */\nSelector.prototype.badness = function() {\n  var penalties = 0;\n  for (var i = 0; i < this.length; i++) {\n    penalties += Selector.partBadness(this[i]);\n  }\n  return penalties;\n};\n\n/**\n * Returns true iff the selector represents an object owner\n * binding.\n * @return {boolean} Is selector for owner?\n */\nSelector.prototype.isOwner = function() {\n  return this.length > 1 && this[this.length - 1] === Selector.OWNER;\n};\n\n/**\n * Returns true iff the selector represents an object property\n * binding.\n * @return {boolean} Is selector for a property?\n */\nSelector.prototype.isProp = function() {\n  return this.length > 1 && typeof this[this.length - 1] === 'string';\n};\n\n/**\n * Returns true iff the selector represents an object prototype\n * binding.\n * @return {boolean} Is selector for prototype?\n */\nSelector.prototype.isProto = function() {\n  return this.length > 1 && this[this.length - 1] === Selector.PROTOTYPE;\n};\n\n/**\n * Returns true iff the selector represents a top-level variable\n * binding.\n * @return {boolean} Is selector for a variable?\n */\nSelector.prototype.isVar = function() {\n  return this.length === 1 && typeof this[0] === 'string';\n};\n\n/**\n * Return the selector as an evaluable expression yeilding the\n * selected value.\n * @return {string} The selector as a string.\n */\nSelector.prototype.toExpr = function() {\n  return this.toString(function(part, out) {\n    if (part === Selector.PROTOTYPE) {\n      out.unshift('Object.getPrototypeOf(');\n      out.push(')');\n    } else if (part === Selector.OWNER) {\n      out.unshift('Object.getOwnerOf(');\n      out.push(')');\n    } else {\n      throw new TypeError('Invalid part in parts array');\n    }\n  });\n};\n\n/**\n * Return an expression setting the selected value to the value of the\n * supplied expression.\n * @param {string} valueExpr A JS expression that evaluates to the new\n *     value to be assigned to the selected location.  It must not\n *     contain any non-parenthesized operators with lower precedence\n *     than '=' - specifically, the yield and comma operators.\n * @return {string} The selector as a string.\n */\nSelector.prototype.toSetExpr = function(valueExpr) {\n  var lastPart = this[this.length - 1];\n  if (!(lastPart instanceof SpecialPart)) {\n    return this.toExpr() + ' = ' + valueExpr;\n  }\n  var objExpr = new Selector(this.slice(0, -1)).toExpr();\n  if (lastPart === Selector.PROTOTYPE) {\n    return 'Object.setPrototypeOf(' + objExpr + ', ' + valueExpr + ')';\n  } else if (lastPart === Selector.OWNER) {\n    return 'Object.setOwnerOf(' + objExpr + ', ' + valueExpr + ')';\n  } else {\n    throw new TypeError('Invalid part in parts array');\n  }\n};\n\n/**\n * Return the selector string corresponding to this selector.\n * @param {function(!SpecialPart, !Array<string>)=} specialHandler\n *     Optional function to handle stringifying SpecialParts.\n * @return {string} The selector as a string.\n */\nSelector.prototype.toString = function(specialHandler) {\n  var /** !Array<string> */ out = [this[0]];\n  for (var i = 1; i < this.length; i++) {\n    var part = this[i];\n    if (part instanceof SpecialPart) {\n      if (specialHandler) {\n        specialHandler(part, out);\n      } else {\n        out.push(String(part));\n      }\n    } else if (code.regexps.identifierExact.test(part)) {\n      out.push('.', part);\n    } else if (String(Number(part)) === part) {\n      // String represents a number with same string representation.\n      out.push('[', part, ']');\n    } else {\n      out.push('[', code.quote(part), ']');\n    }\n  }\n  return out.join('');\n};\n\n/**\n * Return a \"badness\" score for a single Selector.Part, inversely\n * proportional to how desirable the part is as part of selector\n * amongst other selectors referring to the same binding.\n * @return {number};\n */\nSelector.partBadness = function(part) {\n  if (part instanceof SpecialPart) {\n    return 100;  // We don't like SpecialParts.\n  } else if (code.regexps.identifierExact.test(part)) {\n    return 10 + part.length;  // We like identifiers.\n  } else if (String(Number(part)) === part) {\n    return 25 + part.length;  // Numbers are OK.\n  } else {\n    return 30 + part.length;  // Quoted strings are less desirable.\n  }\n};\n\n/**\n * Special singleton Part for refering to an object's prototype.\n */\nSelector.PROTOTYPE = new SpecialPart('proto');\n\n/**\n * Special singleton Part for refering to an object's owner.\n */\nSelector.OWNER = new SpecialPart('owner');\n\n/**\n * A Selector fundamentally an array of Parts, and Parts are either\n * strings (representing variable or property names) or SpecialParts\n * (representing everything else, like {proto} or {owner}).\n * @typedef {string|!SpecialPart}\n */\nSelector.Part;\n\n/**\n * Parse a selector into an array of Parts.\n * @return !Array\n */\nvar parse = function(selector) {\n  var tokens = tokenize(selector);\n  var parts = [];\n  /** @enum {number} */\n  var State = {\n    START: 0, GOOD: 1, DOT: 2, BRACKET: 3, BRACKET_DONE: 4,\n    BRACE: 5, BRACE_DONE: 6\n  };\n  var state = State.START;\n  for (var i = 0; i < tokens.length; i++) {\n    var token = tokens[i];\n    if (token.type === 'whitespace') continue;\n    switch (state) {\n      case State.START:\n        if (token.type !== 'id') {\n          throw new SyntaxError('Selector must start with an identifier');\n        }\n        parts.push(token.raw);\n        state = State.GOOD;\n        break;\n\n      case State.GOOD:\n        if (token.type === '.') {\n          state = State.DOT;\n        } else if (token.type === '[') {\n          state = State.BRACKET;\n        } else if (token.type === '{') {\n          state = State.BRACE;\n        } else if (token.type === '^') {\n          // state remains unchanged.\n          parts.push(Selector.PROTOTYPE);\n        } else {\n          throw new SyntaxError(\n              'Invalid token ' + code.quote(token.raw)  + ' in selector');\n        }\n        break;\n\n      case State.DOT:\n        if (token.type !== 'id') {\n          throw new SyntaxError(\n              '\".\" must be followed by identifier in selector');\n        }\n        parts.push(token.raw);\n        state = State.GOOD;\n        break;\n\n      case State.BRACKET:\n        if (token.type === 'number') {\n          parts.push(String(token.raw));\n        } else if (token.type === 'str') {\n          parts.push(String(token.value));\n        } else {\n          throw new SyntaxError('\"[\" must be followed by numeric or string ' +\n              'literal in selector');\n        }\n        state = State.BRACKET_DONE;\n        break;\n\n      case State.BRACKET_DONE:\n        if (token.type !== ']') {\n          throw new SyntaxError(\n              'Invalid token ' + code.quote(token.raw)  + ' after subscript');\n        }\n        state = State.GOOD;\n        break;\n\n      case State.BRACE:\n        if (token.type === 'id' && token.raw === 'proto') {\n          parts.push(Selector.PROTOTYPE);\n        } else if (token.type === 'id' && token.raw === 'owner') {\n          parts.push(Selector.OWNER);\n        } else {\n          throw new SyntaxError('\"{\" must be followed by \"proto\" or \"owner\"');\n        }\n        state = State.BRACE_DONE;\n        break;\n\n      case State.BRACE_DONE:\n        if (token.type !== '}') {\n          throw new SyntaxError(\n              'Invalid token ' + code.quote(token.raw)  + ' after special');\n        }\n        state = State.GOOD;\n        break;\n\n      default:\n        throw new Error('Invalid State in parse??');\n    }\n  }\n  if (state !== State.GOOD) {\n    throw new SyntaxError('Incomplete selector ' + selector);\n  }\n  return parts;\n};\n\n/** @typedef {{type: string,\n *             raw: string,\n *             valid: boolean,\n *             index: number,\n *             value: (string|number|undefined)}}\n */\nvar Token;\n\n/**\n * Tokenizes a selector string.  Throws a SyntaxError if any text is\n * found which does not form a valid token.\n * @param {string} selector A selector string.\n * @return {!Array<!Token>} An array of tokens.\n */\nvar tokenize = function(selector) {\n  var REs = {\n    whitespace: /\\s+/y,\n    '.': /\\./y,\n    id: new RegExp(code.regexps.identifier, 'y'),\n    number: /\\d+/y,\n    '[': /\\[/y,\n    ']': /\\]/y,\n    '{': /\\{/y,\n    '}': /\\}/y,\n    '^': /\\^/y,\n    str: new RegExp(code.regexps.string, 'y'),\n  };\n\n  var tokens = [];\n  NEXT_TOKEN: for (var index = 0; index < selector.length; ) {\n    for (var tokenType in REs) {\n      if (!REs.hasOwnProperty(tokenType)) continue;\n      var re = REs[tokenType];\n      re.lastIndex = index;\n      var m = re.exec(selector);\n      if (!m) continue;  // No match.  Try next regexp.\n      tokens.push({\n        type: tokenType,\n        raw: m[0],\n        valid: true,\n        index: index,\n      });\n      index = re.lastIndex;\n      continue NEXT_TOKEN;\n    }\n    // No token matched.\n    throw new SyntaxError('invalid selector ' + selector);\n  }\n\n  // Postprocess token list to get values.\n  for(var i = 0; i < tokens.length; i++) {\n    var token = tokens[i];\n    if (token.type === 'number') {\n      token.value = Number(token.raw);\n    } else if (token.type === 'str') {\n      token.value = code.parseString(token.raw);\n    }\n  }\n  return tokens;\n};\n\nmodule.exports = Selector;\n"
  },
  {
    "path": "server/serialize.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Saving and restoring the state of the interpreter.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nvar Interpreter = require('./interpreter');\nvar IterableWeakMap = require('./iterable_weakmap');\nvar IterableWeakSet = require('./iterable_weakset');\nvar net = require('net');\nvar Node = require('./parser').Node;\nvar Registry = require('./registry');\n\nvar Serializer = {};\n\n/** \n * A record of a single serializalbe type, including a type tag, a\n * constructor function to call when deserializing an instance, and an\n * optional list of properties to exclude when serializing.\n *\n * @typedef {{\n *   tag: string,\n *   constructor: !Function,\n *   prune: (!Array<string>|undefined),\n * }}\n */\nvar TypeInfo;\n\n/**\n * A configuration object containing an array of TypeInfo objects and\n * indexes by tag an prototype object.\n *\n * @typedef {{\n *   types: !Array<!TypeInfo>,\n *   byTag: !Object<!TypeInfo>,\n *   byProto: !Map<?Object,!TypeInfo>,\n * }}\n */\nvar Config;\n\n/**\n * Create a configuration object for serializing or desieralizing a\n * particular Interpreter instance.\n *\n * @param {!Interpreter} intrp The interpreter instance being serialized\n *     (needed for inner classes).\n * @return {!Config} The configuration object.\n */\nSerializer.getConfig_ = function(intrp) {\n  var /** !Array<!TypeInfo> */ types = [\n    // Generic JavaScript types, not including those requring special\n    // construction (like Functions, Dates, RegExps, etc.)\n    {tag: 'Object', constructor: Object},\n    {tag: 'Array', constructor: Array},\n    {tag: 'Map', constructor: Map},\n    {tag: 'Set', constructor: Set},\n    \n    // Custom types, not Interpreter-specific.\n    {tag: 'IterableWeakMap', constructor: IterableWeakMap,\n     prune: ['refs_', 'finalisers_']},\n    {tag: 'IterableWeakSet', constructor: IterableWeakSet,\n     prune: ['refs_', 'map_', 'finalisers_']},\n    {tag: 'Registry', constructor: Registry},\n    \n    // Interpreter-specific types.\n    {tag: 'Interpreter', constructor: Interpreter, prune: [\n      'hrStartTime_',\n      'previousTime_',\n      'runner_',\n      'Object',\n      'Function',\n      'UserFunction',\n      'BoundFunction',\n      'NativeFunction',\n      'OldNativeFunction',\n      'Array',\n      'Date',\n      'RegExp',\n      'Error',\n      'Arguments',\n      'WeakMap',\n      'Thread',\n      'Box',\n      'Server',\n    ]},\n    {tag: 'Scope', constructor: Interpreter.Scope},\n    {tag: 'State', constructor: Interpreter.State},\n    {tag: 'Thread', constructor: Interpreter.Thread},\n    {tag: 'PropertyIterator', constructor: Interpreter.PropertyIterator},\n    {tag: 'Source', constructor: Interpreter.Source},\n    {tag: 'PseudoObject', constructor: intrp.Object, prune: ['socket']},\n    {tag: 'PseudoFunction', constructor: intrp.Function},\n    {tag: 'PseudoUserFunction', constructor: intrp.UserFunction},\n    {tag: 'PseudoBoundFunction', constructor: intrp.BoundFunction},\n    {tag: 'PseudoNativeFunction', constructor: intrp.NativeFunction},\n    {tag: 'PseudoOldNativeFunction', constructor: intrp.OldNativeFunction},\n    {tag: 'PseudoArray', constructor: intrp.Array},\n    {tag: 'PseudoDate', constructor: intrp.Date},\n    {tag: 'PseudoRegExp', constructor: intrp.RegExp},\n    {tag: 'PseudoError', constructor: intrp.Error},\n    {tag: 'PseudoArguments', constructor: intrp.Arguments},\n    {tag: 'PseudoWeakMap', constructor: intrp.WeakMap},\n    {tag: 'PseudoThread', constructor: intrp.Thread},\n    {tag: 'Box', constructor: intrp.Box},\n    {tag: 'Server', constructor: intrp.Server, prune: ['server_']},\n    {tag: 'Node', constructor: Node},\n  ];\n  var /** !Object<string,!TypeInfo> */ byTag = Object.create(null);\n  var /** !Map<!Object,!TypeInfo> */ byProto = new Map();\n  for (var type, i = 0; type = types[i]; i++) {\n    byTag[type.tag] = type;\n    byProto.set(type.constructor.prototype, type);\n  }\n  return {types: types, byTag: byTag, byProto: byProto};\n};\n\n/**\n * Deserialize the provided JSON-compatible object into an interpreter.\n * @param {!Object} JSON-compatible object.\n * @param {!Interpreter} intrp JS-Interpreter instance.\n */\nSerializer.deserialize = function(json, intrp) {\n  function decodeValue(value) {\n    if (value && typeof value === 'object') {\n      var data;\n      if ((data = value['#'])) {\n       // Object reference: {'#': 42}\n       value = objectList[data];\n        if (!value) {\n          throw new ReferenceError('Object reference not found: ' + data);\n        }\n        return value;\n      }\n      if ((data = value['Number'])) {\n        // Special number: {'Number': 'Infinity'}\n        return Number(data);\n      }\n      if ((data = value['Value'])) {\n        // Special value: {'Value': 'undefined'}\n        if (value['Value'] === 'undefined') {\n          return undefined;\n        }\n      }\n    }\n    return value;\n  }\n\n  // Get configuration.\n  var config = Serializer.getConfig_(intrp);\n  \n  if (!Array.isArray(json)) {\n    throw new TypeError('Top-level JSON is not a list.');\n  }\n\n  // Require native functions to be present.  Can't just create fresh\n  // new interpreter instance because client code may want to add\n  // custom builtins.\n  if (!intrp.global) {\n    throw new Error(\n        'Interpreter must be initialized prior to deserialization.');\n  }\n\n  // Find all native functions to get id => func mappings.\n  var functionHash = Object.create(null);\n  // Builtins.\n  var builtins = Array.from(intrp.builtins.values());\n  var implProps = ['impl', 'call', 'construct'];\n  for (var i = 0; i < builtins.length; i++) {\n    var builtin = builtins[i];\n    for (var j = 0; j < implProps.length; j++) {\n      var func = builtin[implProps[j]];\n      if (func) functionHash[func.id] = func;\n    }\n  }\n  // Step functions.\n  for (var stepName in intrp.stepFuncs) {\n    var stepFunc = intrp.stepFuncs[stepName];\n    functionHash[stepFunc.id] = stepFunc;\n  }\n\n  // First pass: Create object stubs for every object.  We don't need\n  // to (re)create object #0, because that's the interpreter proper.\n  var objectList = [intrp];\n  for (var i = 1; i < json.length; i++) {\n    var jsonObj = json[i];\n    var obj;\n    var tag = jsonObj['type'];\n    // Default case handles most types; sepcial cases handle only\n    // those that can't be correctly created by an unparameterized\n    // construction \"new Constructor()\".\n    switch (tag) {\n      case 'Function':\n        obj = functionHash[jsonObj['id']];\n        if (!obj) {\n          throw new RangeError('Function ID not found: ' + jsonObj['id']);\n        }\n        break;\n      case 'Date':\n        obj = new Date(jsonObj['data']);\n        if (isNaN(obj)) {\n          throw new TypeError('Invalid date: ' + jsonObj['data']);\n        }\n        break;\n      case 'RegExp':\n        obj = RegExp(jsonObj['source'], jsonObj['flags']);\n        break;\n      case 'State':\n        // TODO(cpcallen): this is just a little performance kludge so\n        // that the State constructor doesn't need a conditional in it.\n        // Find a more general solution to constructors requiring args.\n        obj = new Interpreter.State(/** @type {?} */({}),\n            /** @type {?} */(undefined));\n        break;\n      default:\n        if (config.byTag[tag]) {\n          obj = new config.byTag[tag].constructor();\n        } else {\n          throw new TypeError('Unknown type tag \"' + tag + '\"');\n        }\n    }\n    objectList[i] = obj;\n  }\n  // Second pass: Populate properties for every object.\n  for (var i = 0; i < json.length; i++) {\n    var jsonObj = json[i];\n    var tag = jsonObj['type'];\n    var typeInfo = config.byTag[tag];\n    var obj = objectList[i];\n    // Set prototype, if specified.\n    if (jsonObj['proto']) {\n      Object.setPrototypeOf(obj, decodeValue(jsonObj['proto']));\n    }\n    // Repopulate properties.\n    var prune = (typeInfo && typeInfo.prune) || [];\n    var props = jsonObj['props'];\n    if (props) {\n      var nonConfigurable = jsonObj['nonConfigurable'] || [];\n      var nonEnumerable = jsonObj['nonEnumerable'] || [];\n      var nonWritable = jsonObj['nonWritable'] || [];\n      var keys = Object.getOwnPropertyNames(props);\n      for (var j = 0; j < keys.length; j++) {\n        var key = keys[j];\n        if (prune.includes(key)) continue;\n        Object.defineProperty(obj, key,\n            {configurable: !nonConfigurable.includes(key),\n             enumerable: !nonEnumerable.includes(key),\n             writable: !nonWritable.includes(key),\n             value: decodeValue(props[key])});\n      }\n    }\n    // Repopulate sets.\n    if (obj instanceof Set || obj instanceof IterableWeakSet) {\n      var data = jsonObj['data'];\n      if (data) {\n        for (var j = 0; j < data.length; j++) {\n          obj.add(decodeValue(data[j]));\n        }\n      }\n    }\n    // Repopulate maps.\n    if (obj instanceof Map || obj instanceof IterableWeakMap) {\n      var entries = jsonObj['entries'];\n      if (entries) {\n        for (var j = 0; j < entries.length; j++) {\n          var key = decodeValue(entries[j][0]);\n          var value = decodeValue(entries[j][1]);\n          obj.set(key, value);\n        }\n      }\n    }\n    if (jsonObj['isExtensible'] === false) {  // N.B. normally omitted if true.\n      Object.preventExtensions(obj);\n    }\n  }\n  // Finally: fixup interpreter state, post-deserialization.\n  intrp.postDeserialize();\n};\n\n/**\n * Serialize the provided interpreter.\n * @param {!Interpreter} intrp JS-Interpreter instance.\n * @return {!Object} JSON-compatible object.\n */\nSerializer.serialize = function(intrp) {\n  // First: prepare interpreter for serialization.\n  intrp.preSerialize();\n  \n  function encodeValue(value) {\n    if (value && (typeof value === 'object' || typeof value === 'function')) {\n      var ref = objectRefs.get(value);\n      if (ref === undefined) {\n        throw new RangeError('object not found in table');\n      }\n      return {'#': ref};\n    }\n    if (value === undefined) {\n      return {'Value': 'undefined'};\n    }\n    if (typeof value === 'number') {\n      if (value === Infinity) {\n        return {'Number': 'Infinity'};\n      } else if (value === -Infinity) {\n        return {'Number': '-Infinity'};\n      } else if (Number.isNaN(value)) {\n        return {'Number': 'NaN'};\n      } else if (Object.is(value, -0)) {\n        return {'Number': '-0'};\n      }\n    }\n    return value;\n  }\n\n  // Get configuration.\n  var config = Serializer.getConfig_(intrp);\n\n  // Find all objects.\n  var objectList = Serializer.getObjectList_(intrp, config);\n  // Build reverse-lookup cache.\n  var /** !Map<Object,number> */ objectRefs = new Map();\n  for (var i = 0; i < objectList.length; i++) {\n    objectRefs.set(objectList[i], i);\n  }\n  // Serialize every object.\n  var json = [];\n  for (var i = 0; i < objectList.length; i++) {\n    var jsonObj = Object.create(null);\n    json.push(jsonObj);\n    var obj = objectList[i];\n    // TODO: Add a flag on the '#' prop.  On for debugging, off for production.\n    if (true) {\n      jsonObj['#'] = i;\n    }\n    var proto = Object.getPrototypeOf(obj);\n    var typeInfo = config.byProto.get(proto);\n    // Default case handles most types; sepcial cases handle only\n    // those that have extra intenal slots.\n    switch (proto) {\n      case Function.prototype:\n        jsonObj['type'] = 'Function';\n        jsonObj['id'] = obj.id;\n        if (!obj.id) {\n          throw new Error('Native function has no ID: ' + obj);\n        }\n        continue;  // No need to index properties.\n      case Date.prototype:\n        jsonObj['type'] = 'Date';\n        jsonObj['data'] = obj.toJSON();\n        continue;  // No need to index properties.\n      case RegExp.prototype:\n        jsonObj['type'] = 'RegExp';\n        jsonObj['source'] = obj.source;\n        jsonObj['flags'] = obj.flags;\n        continue;  // No need to index properties.\n      case Map.prototype:\n        jsonObj['type'] = 'Map';\n        if (obj.size) {\n          jsonObj['entries'] =\n              Array.from(/** @type {?} */(obj),function(entry) {\n                var key = encodeValue(entry[0]);\n                var value = encodeValue(entry[1]);\n                return [key, value];\n              });\n        }\n        break;\n      case Set.prototype:\n        jsonObj['type'] = 'Set';\n        if (obj.size) {\n          jsonObj['data'] = Array.from(obj.values(), encodeValue);\n        }\n        break;\n      case IterableWeakMap.prototype:\n        jsonObj['type'] = 'IterableWeakMap';\n        if (obj.size) {\n          jsonObj['entries'] =\n              Array.from(/** @type {?} */(obj), function(entry) {\n                var key = encodeValue(entry[0]);\n                var value = encodeValue(entry[1]);\n                return [key, value];\n              });\n        }\n        continue;  // Mustn't index internal properties for IterableWeakMap\n      case IterableWeakSet.prototype:\n        jsonObj['type'] = 'IterableWeakSet';\n        if (obj.size) {\n          jsonObj['data'] = Array.from(obj.values(), encodeValue);\n        }\n        continue;  // Mustn't index internal properties for IterableWeakSet\n      case Registry.prototype:\n        jsonObj['type'] = 'Registry';\n        break;\n      default:\n        if (typeInfo) {\n          jsonObj['type'] = typeInfo.tag;\n        } else {\n          jsonObj['type'] = Array.isArray(obj) ? 'Array' : 'Object';\n          jsonObj['proto'] = encodeValue(proto);\n        }\n    }\n    var props = Object.create(null);\n    var nonConfigurable = [];\n    var nonEnumerable = [];\n    var nonWritable = [];\n    var prune = (typeInfo && typeInfo.prune) || [];\n    var keys = Object.getOwnPropertyNames(obj);\n    for (var j = 0; j < keys.length; j++) {\n      var key = keys[j];\n      if (prune.includes(key)) continue;\n      // Skip [[Socket]] slot on connected objects.\n      // TODO(cpcallen): this is pretty kludgy.  Try to find a better way.\n      if (obj instanceof intrp.Object && key === 'socket') continue;\n\n      props[key] = encodeValue(obj[key]);\n      var descriptor = Object.getOwnPropertyDescriptor(obj, key);\n      if (!descriptor.configurable) {\n        nonConfigurable.push(key);\n      }\n      if (!descriptor.enumerable) {\n        nonEnumerable.push(key);\n      }\n      if (!descriptor.writable) {\n        nonWritable.push(key);\n      }\n    }\n    if (Object.getOwnPropertyNames(keys).length) {\n      jsonObj['props'] = props;\n    }\n    if (nonConfigurable.length) {\n      jsonObj['nonConfigurable'] = nonConfigurable;\n    }\n    if (nonEnumerable.length) {\n      jsonObj['nonEnumerable'] = nonEnumerable;\n    }\n    if (nonWritable.length) {\n      jsonObj['nonWritable'] = nonWritable;\n    }\n    if (!Object.isExtensible(obj)) {\n      jsonObj['isExtensible'] = false;\n    }\n  }\n  return json;\n};\n\n/**\n * Recursively search node to find all non-primitives.\n *\n * TODO(cpcallen): use a Registry instead of Array for objectList;\n *     this would allow more readable references by using paths\n *     instead of numerical indices.\n * @param {*} node JavaScript value to search.\n * @param {!Config} config Configuation object.\n * @return {!Array<!Object>} objectList Array of all objects found via node.\n */\nSerializer.getObjectList_ = function(node, config) {\n  var seen = new Set();\n  Serializer.objectHunt_(node, config, seen);\n  return Array.from(seen.keys());\n};\n\n/**\n * Recursively search node find all non-primitives.\n *\n * @param {*} node JavaScript value to search.\n * @param {!Config} config Configuation object.\n * @param {!Set<?Object>} seen Set of objects found so far.\n */\nSerializer.objectHunt_ = function(node, config, seen) {\n  if (!node || (typeof node !== 'object' && typeof node !== 'function')) {\n    // node is primitive.  Nothing to do.\n    return;\n  }\n  var obj = /** @type {!Object} */(node);\n  if (seen.has(obj)) return;\n  var proto = Object.getPrototypeOf(obj);\n  seen.add(obj);\n  if (typeof obj === 'object') {  // Recurse.\n    var typeInfo = config.byProto.get(proto);\n    var prune = (typeInfo && typeInfo.prune) || [];\n    // Properties.\n    var keys = Object.getOwnPropertyNames(obj);\n    for (var i = 0; i < keys.length; i++) {\n      var key = keys[i];\n      if (prune.includes(key)) continue;\n      Serializer.objectHunt_(obj[key], config, seen);\n    }\n    // Set members.\n    if (obj instanceof Set || obj instanceof IterableWeakSet) {\n      obj.forEach(function(value) {\n        Serializer.objectHunt_(value, config, seen);\n      });\n    }\n    // Map entries.\n    if (obj instanceof Map || obj instanceof IterableWeakMap) {\n      obj.forEach(function(value, key) {\n        Serializer.objectHunt_(key, config, seen);\n        Serializer.objectHunt_(value, config, seen);\n      });\n    }\n  }\n};\n\nmodule.exports = Serializer;\n"
  },
  {
    "path": "server/startup/cc.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Initialisation code to expose CC-specific extensions\n *     not exposed by server/startup/esx.js for testing.\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n///////////////////////////////////////////////////////////////////////////////\n// Namespace for CodeCity-specific extensions.\n//\nvar CC = {};\n\n///////////////////////////////////////////////////////////////////////////////\n// Permissions API.\n//\nCC.root = new 'CC.root';\nvar perms = new 'perms';\nvar setPerms = new 'setPerms';\n\n///////////////////////////////////////////////////////////////////////////////\n// Networking API.\n//\nCC.connectionListen = new 'CC.connectionListen';\nCC.connectionUnlisten = new 'CC.connectionUnlisten';\nCC.connectionWrite = new 'CC.connectionWrite';\nCC.connectionClose = new 'CC.connectionClose';\nCC.xhr = new 'CC.xhr';\n"
  },
  {
    "path": "server/startup/es5.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Polyfills to bring the server's partial JavaScript\n * implementation up to ECMAScript 5.1 (or close to it).\n * @author fraser@google.com (Neil Fraser)\n */\n\n// Global functions.\nvar parseInt = new 'parseInt';\nvar parseFloat = new 'parseFloat';\nvar isNaN = new 'isNaN';\nvar isFinite = new 'isFinite';\nvar escape = new 'escape';\nvar unescape = new 'unescape';\nvar decodeURI = new 'decodeURI';\nvar decodeURIComponent = new 'decodeURIComponent';\nvar encodeURI = new 'encodeURI';\nvar encodeURIComponent = new 'encodeURIComponent';\n// As a special case, eval is not included in this list: it must be\n// set in the global scope by the interpreter because binding eval in\n// strict mode is illegal.\n\n// Global objects.\nvar Object = new 'Object';\nvar Function = new 'Function';\nvar Array = new 'Array';\nvar String = new 'String';\nvar Boolean = new 'Boolean';\nvar Number = new 'Number';\nvar Date = new 'Date';\nvar RegExp = new 'RegExp';\nvar Error = new 'Error';\nvar EvalError = new 'EvalError';\nvar RangeError = new 'RangeError';\nvar ReferenceError = new 'ReferenceError';\nvar SyntaxError = new 'SyntaxError';\nvar TypeError = new 'TypeError';\nvar URIError = new 'URIError';\nvar Math = {};\nvar JSON = {};\n\n// Bootstrap the defineProperty function in two steps.\nObject.defineProperty = new 'Object.defineProperty';\nObject.defineProperty(Object, 'defineProperty', {enumerable: false});\n\n(function() {\n  // Hack to work around restriction that the 'new hack' only works on\n  // literal strings.  Note name must not contain any double quotes or\n  // backslashes, because we have no easy way to escape them yet!\n  var builtin = function(name) {\n    return eval('new \"' + name + '\"');\n  };\n\n  var classes = ['Object', 'Function', 'Array', 'String', 'Boolean', 'Number',\n                 'Date', 'RegExp', 'Error', 'EvalError', 'RangeError',\n                 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError'];\n  // Prototypes of global constructors.\n  for (var i = 0; i < classes.length; i++) {\n    var constructor = builtin(classes[i]);\n    Object.defineProperty(constructor, 'prototype', {\n                          configurable: false,\n                          enumerable: false,\n                          writable: false,\n                          value: builtin(classes[i] + '.prototype')\n                          });\n    Object.defineProperty(constructor.prototype, 'constructor', {\n                          configurable: true,\n                          enumerable: false,\n                          writable: true,\n                          value: constructor\n                          });\n  }\n  // Configure Error and its subclasses.\n  var errors = ['Error', 'EvalError', 'RangeError', 'ReferenceError',\n                'SyntaxError', 'TypeError', 'URIError'];\n  for (var i = 0; i < errors.length; i++) {\n    var constructor = builtin(errors[i]);\n    Object.defineProperty(constructor.prototype, 'name', {\n                          configurable: true,\n                          enumerable: false,\n                          writable: true,\n                          value: errors[i]\n                          });\n  }\n  Object.defineProperty(Error.prototype, 'message', {\n                        configurable: true,\n                        enumerable: false,\n                        writable: true,\n                        value: ''\n                        });\n\n  // Struct is a list of tuples:\n  //     [Object, 'Object', [static methods], [instance methods]]\n\n  var struct = [\n    [Object, 'Object',\n     ['getOwnPropertyNames', 'keys', 'getOwnPropertyDescriptor',\n      'getPrototypeOf', 'isExtensible', 'preventExtensions'],\n     ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',\n      'propertyIsEnumerable', 'isPrototypeOf']],\n    [Function, 'Function',\n     [],\n     ['apply', 'bind', 'call', 'toString']],\n    [Array, 'Array',\n     ['isArray'],\n     ['toString', 'pop', 'push', 'shift', 'unshift', 'reverse', 'splice',\n      'slice', 'concat', 'indexOf', 'lastIndexOf']],\n    [String, 'String',\n     ['fromCharCode'],\n     ['trim', 'toLowerCase', 'toUpperCase', 'toLocaleLowerCase',\n      'toLocaleUpperCase', 'charAt', 'charCodeAt', 'substring', 'slice',\n      'substr', 'indexOf', 'lastIndexOf', 'concat', 'localeCompare', 'split',\n      'match', 'search', 'replace', 'toString', 'valueOf']],\n    [Boolean, 'Boolean',\n     [],\n     ['toString', 'valueOf']],\n    [Number, 'Number',\n     [],\n     ['toExponential', 'toFixed', 'toLocaleString', 'toPrecision', 'toString',\n      'valueOf']],\n    [Date, 'Date',\n     ['now', 'parse', 'UTC'],\n     ['toString', 'getDate', 'getDay', 'getFullYear', 'getHours',\n      'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime',\n      'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear',\n      'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth',\n      'getUTCSeconds', 'getYear', 'setDate', 'setFullYear', 'setHours',\n      'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime',\n      'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds',\n      'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear',\n      'toDateString', 'toISOString', 'toJSON', 'toGMTString', 'toTimeString',\n      'toUTCString', 'toLocaleDateString', 'toLocaleString',\n      'toLocaleTimeString']],\n    [RegExp, 'RegExp',\n     [],\n     ['toString', 'test', 'exec']],\n    [Error, 'Error',\n     [],\n     ['toString']],\n    [Math, 'Math',\n     ['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor',\n      'log', 'max', 'min', 'pow', 'random', 'round', 'sin', 'sqrt', 'tan'],\n     []],\n    [JSON, 'JSON',\n     ['parse', 'stringify'],\n     []]\n  ];\n  for (var i = 0; i < struct.length; i++) {\n    var obj = struct[i][0];\n    var objName = struct[i][1];\n    var staticMethods = struct[i][2];\n    var instanceMethods = struct[i][3];\n    for (var j = 0; j < staticMethods.length; j++) {\n      var member = staticMethods[j];\n      Object.defineProperty(obj, member,\n          {configurable: true,\n           enumerable: false,\n           writable: true,\n           value: builtin(objName + '.' + member)});\n    }\n    for (var j = 0; j < instanceMethods.length; j++) {\n      var member = instanceMethods[j];\n      Object.defineProperty(obj.prototype, member,\n          {configurable: true,\n           enumerable: false,\n           writable: true,\n           value: builtin(objName + '.prototype.' + member)});\n    }\n  }\n})();\n\nObject.defineProperty(Number, 'MAX_VALUE', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 1.7976931348623157e+308\n                      });\nObject.defineProperty(Number, 'MIN_VALUE', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 5e-324\n                      });\nObject.defineProperty(Number, 'NaN', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: NaN\n                      });\nObject.defineProperty(Number, 'NEGATIVE_INFINITY', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: -Infinity\n                      });\nObject.defineProperty(Number, 'POSITIVE_INFINITY', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: Infinity\n                      });\n\nObject.defineProperty(Math, 'E', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 2.718281828459045\n                      });\nObject.defineProperty(Math, 'LN2', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 0.6931471805599453\n                      });\nObject.defineProperty(Math, 'LN10', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 2.302585092994046\n                      });\nObject.defineProperty(Math, 'LOG2E', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 1.4426950408889634\n                      });\nObject.defineProperty(Math, 'LOG10E', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 0.4342944819032518\n                      });\nObject.defineProperty(Math, 'PI', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 3.141592653589793\n                      });\nObject.defineProperty(Math, 'SQRT1_2', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 0.7071067811865476\n                      });\nObject.defineProperty(Math, 'SQRT2', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 1.4142135623730951\n                      });\n\nObject.defineProperty(RegExp.prototype, 'global', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: undefined\n                      });\nObject.defineProperty(RegExp.prototype, 'ignoreCase', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: undefined\n                      });\nObject.defineProperty(RegExp.prototype, 'multiline', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: undefined\n                      });\nObject.defineProperty(RegExp.prototype, 'source', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: '(?:)'\n                      });\n\n///////////////////////////////////////////////////////////////////////////////\n// Object polyfills\n///////////////////////////////////////////////////////////////////////////////\n\n// Add a polyfill to handle create's second argument.\nObject.create = function create(proto, props) {\n  var obj = (new 'Object.create')(proto);\n  props && Object.defineProperties(obj, props);\n  return obj;\n};\nObject.defineProperty(Object, 'create', {enumerable: false});\n\nObject.defineProperties = function defineProperties(obj, props) {\n  if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {\n    throw new TypeError('Object.defineProperties called on type ' + typeof obj +\n                        ', not type object or function');\n  }\n  var keys = Object.keys(props);\n  for (var i = 0; i < keys.length; i++) {\n    Object.defineProperty(obj, keys[i], props[keys[i]]);\n  }\n  return obj;\n};\nObject.defineProperty(Object, 'defineProperties', {enumerable: false});\n\nObject.isFrozen = function isFrozen(obj) {\n  // TODO: replace this with builtin version.\n  // Per ES5.1, §15.2.3.12\n  if (obj === null || !(typeof obj === 'object' || typeof obj === 'function')) {\n    throw new TypeError('Primitive is already immutable');\n  }\n  var keys = Object.getOwnPropertyNames(obj);\n  for (var i = 0; i < keys.length; i++) {\n    var key = keys[i];\n    var pd = Object.getOwnPropertyDescriptor(obj, key);\n    // Assume no accessor properties.\n    if (pd.configurable || pd.writable) return false;\n  }\n  if (Object.isExtensible) return false;\n  return true;\n};\nObject.defineProperty(Object, 'isFrozen', {enumerable: false});\n\nObject.isSealed = function isSealed(obj) {\n  // TODO: replace this with builtin version.\n  // Per ES5.1, §15.2.3.12\n  if (obj === null || !(typeof obj === 'object' || typeof obj === 'function')) {\n    throw new TypeError('Primitive is already immutable');\n  }\n  var keys = Object.getOwnPropertyNames(obj);\n  for (var i = 0; i < keys.length; i++) {\n    var key = keys[i];\n    var pd = Object.getOwnPropertyDescriptor(obj, key);\n    if (pd.configurable) return false;\n  }\n  if (Object.isExtensible) return false;\n  return true;\n};\nObject.defineProperty(Object, 'isSealed', {enumerable: false});\n\nObject.freeze = function freeze(obj) {\n  // TODO: replace this with builtin version.\n  // Per ES5.1, §15.2.3.9\n  if (obj === null || !(typeof obj === 'object' || typeof obj === 'function')) {\n    throw new TypeError('Primitive is already immutable');\n  }\n  var keys = Object.getOwnPropertyNames(obj);\n  for (var i = 0; i < keys.length; i++) {\n    var key = keys[i];\n    // Assume no accessor properties.\n    Object.defineProperty(obj, key, {writable: false, configurable: false});\n  }\n  Object.preventExtensions(obj);\n};\nObject.defineProperty(Object, 'freeze', {enumerable: false});\n\nObject.seal = function seal(obj) {\n  // TODO: replace this with builtin version.\n  // Per ES5.1, §15.2.3.8\n  if (obj === null || !(typeof obj === 'object' || typeof obj === 'function')) {\n    throw new TypeError('Primitive is already immutable');\n  }\n  var keys = Object.getOwnPropertyNames(obj);\n  for (var i = 0; i < keys.length; i++) {\n    var key = keys[i];\n    // Assume no accessor properties.\n    Object.defineProperty(obj, key, {configurable: false});\n  }\n  Object.preventExtensions(obj);\n};\nObject.defineProperty(Object, 'seal', {enumerable: false});\n\n///////////////////////////////////////////////////////////////////////////////\n// Array.prototype polyfills\n///////////////////////////////////////////////////////////////////////////////\n\nArray.prototype.every = function every(callback/*, thisArg*/) {\n  // Polyfill copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/ever\n  if (this === null || this === undefined) {\n    throw new TypeError('Array.prototype.every called on ' + this);\n  } else if (typeof callback !== 'function') {\n    throw new TypeError('callback is type ' + typeof callback +\n        ', not type function');\n  }\n  var o = Object(this);\n  var len = o.length >>> 0;\n  var thisArg = arguments[1];\n  for (var k = 0; k < len; k++) {\n    if (k in o && !callback.call(thisArg, o[k], k, o)) return false;\n  }\n  return true;\n};\nObject.defineProperty(Array.prototype, 'every', {enumerable: false});\n\nArray.prototype.filter = function filter(callback/*, thisArg*/) {\n  // Polyfill copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\n  if (this === null || this === undefined) {\n    throw new TypeError('Array.prototype.filter called on ' + this);\n  } else if (typeof callback !== 'function') {\n    throw new TypeError('callback is type ' + typeof callback +\n        ', not type function');\n  }\n  var o = Object(this);\n  var len = o.length >>> 0;\n  var res = [];\n  var thisArg = arguments[1];\n  for (var i = 0; i < len; i++) {\n    if (i in o) {\n      var val = o[i];\n      if (callback.call(thisArg, val, i, o)) res.push(val);\n    }\n  }\n  return res;\n};\nObject.defineProperty(Array.prototype, 'filter', {enumerable: false});\n\nArray.prototype.forEach = function forEach(callback/*, thisArg*/) {\n  // Polyfill copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\n  if (this === null || this === undefined) {\n    throw new TypeError('Array.prototype.forEach called on ' + this);\n  } else if (typeof callback !== 'function') {\n    throw new TypeError('callback is type ' + typeof callback +\n        ', not type function');\n  }\n  var o = Object(this);\n  var len = o.length >>> 0;\n  var thisArg = arguments[1];\n  for (var k = 0; k < len; k++) {\n    if (k in o) callback.call(thisArg, o[k], k, o);\n  }\n};\nObject.defineProperty(Array.prototype, 'forEach', {enumerable: false});\n\n(function() {\n  // For cycle detection in array to string and error conversion; see\n  // spec bug github.com/tc39/ecma262/issues/289.\n  var visited = [];\n\n  Array.prototype.join = function join(separator) {\n    // This implements Array.prototype.join from ES5 §15.4.4.5, with\n    // the addition of cycle detection as discussed in\n    // https://github.com/tc39/ecma262/issues/289.\n    //\n    // Variable names reflect those in the spec.\n    //\n    // N.B. This function is defined in a closure!\n    var isObj = (typeof this === 'object' || typeof this === 'function') &&\n        this !== null;\n    if (isObj) {\n      if (visited.indexOf(this) !== -1) {\n        return '';\n      }\n      visited.push(this);\n    }\n    try {\n      // TODO(cpcallen): setPerms(callerPerms());\n      var len = this.length >>> 0;\n      var sep = (separator === undefined) ? ',' : String(separator);\n      if (!len) {\n        return '';\n      }\n      var r = '';\n      for (var k = 0; k < len; k++) {\n        if (k > 0) r += sep;\n        var element = this[k];\n        if (element !== undefined && element !== null) {\n          r += String(element);\n        }\n      }\n      return r;\n    } finally {\n      if (isObj) visited.pop();\n    }\n  };\n})();\nObject.defineProperty(Array.prototype, 'join', {enumerable: false});\n\nArray.prototype.map = function map(callback/*, thisArg*/) {\n  // Polyfill copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map\n  if (this === null || this === undefined) {\n    throw new TypeError('Array.prototype.map called on ' + this);\n  } else if (typeof callback !== 'function') {\n    throw new TypeError('callback is type ' + typeof callback +\n        ', not type function');\n  }\n  var o = Object(this);\n  var len = o.length >>> 0;\n  var A = new Array(len);\n  var thisArg = arguments[1];\n  for (var k = 0; k < len; k++) {\n    if (k in o) A[k] = callback.call(thisArg, o[k], k, o);\n  }\n  return A;\n};\nObject.defineProperty(Array.prototype, 'map', {enumerable: false});\n\nArray.prototype.reduce = function reduce(callback /*, initialValue*/) {\n  // Polyfill copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\n  if (this === null || this === undefined) {\n    throw new TypeError('Array.prototype.reduce called on ' + this);\n  } else if (typeof callback !== 'function') {\n    throw new TypeError('callback is type ' + typeof callback +\n        ', not type function');\n  }\n  var o = Object(this);\n  var len = o.length >>> 0;\n  var k = 0;\n  var value;\n  if (arguments.length > 1) {\n    value = arguments[1];\n  } else {\n    while (k < len && !(k in o)) k++;\n    if (k >= len) {\n      throw new TypeError('Reduce of empty array with no initial value');\n    }\n    value = o[k++];\n  }\n  for (; k < len; k++) {\n    if (k in o) value = callback(value, o[k], k, o);\n  }\n  return value;\n};\nObject.defineProperty(Array.prototype, 'reduce', {enumerable: false});\n\nArray.prototype.reduceRight = function reduceRight(callback /*, initialValue*/) {\n  // Polyfill copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight\n  if (this === null || this === undefined) {\n    throw new TypeError('Array.prototype.reduceRight called on ' + this);\n  } else if (typeof callback !== 'function') {\n    throw new TypeError('callback is type ' + typeof callback +\n        ', not type function');\n  }\n  var o = Object(this);\n  var len = o.length >>> 0;\n  var k = len - 1;\n  var value;\n  if (arguments.length > 1) {\n    value = arguments[1];\n  } else {\n    while (k >= 0 && !(k in o)) k--;\n    if (k < 0) {\n      throw new TypeError('Reduce of empty array with no initial value');\n    }\n    value = o[k--];\n  }\n  for (; k >= 0; k--) {\n    if (k in o) value = callback(value, o[k], k, o);\n  }\n  return value;\n};\nObject.defineProperty(Array.prototype, 'reduceRight', {enumerable: false});\n\nArray.prototype.some = function some(callback/*, thisArg*/) {\n  // Polyfill copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/some\n  if (this === null || this === undefined) {\n    throw new TypeError('Array.prototype.some called on ' + this);\n  } else if (typeof callback !== 'function') {\n    throw new TypeError('callback is type ' + typeof callback +\n        ', not type function');\n  }\n  var o = Object(this);\n  var len = o.length >>> 0;\n  var thisArg = arguments[1];\n  for (var i = 0; i < len; i++) {\n    if (i in o && callback.call(thisArg, o[i], i, o)) {\n      return true;\n    }\n  }\n  return false;\n};\nObject.defineProperty(Array.prototype, 'some', {enumerable: false});\n\nArray.prototype.sort = function sort(comparefn) {\n  // Polylfill adapted from:\n  // https://github.com/v8/v8/blob/8e43b9c01d60ddb5e58ec8de9d34616ea1bb905f/src/js/array.js\n  // TODO(cpcallen): as of ES2020, Array.prototype.sort must be stable.\n  var obj = this;\n  // Let obj = ToObject(this)\n  if (typeof(obj) !== 'object' && typeof(obj) !== 'function' || obj === null) {\n    throw new TypeError(\"Can't convert \" + obj + ' to Object');\n  }\n  // Let len = ToLength(obj.length)\n  var len = Number(obj.length);\n  if (isNaN(len) || len < 0) len = 0;\n  if (len !== 0 && isFinite(len)) len = Math.trunc(len);\n  len = Math.min(len, Number.MAX_SAFE_INTEGER);\n  // Make sure comparefn is usable.\n  if (comparefn === undefined) {\n    comparefn = function (x, y) {\n      x = String(x);\n      y = String(y);\n      if (x === y) return 0;\n      else return x < y ? -1 : 1;\n    };\n  } else if(typeof(comparefn) !== 'function') {\n    throw new TypeError(\n        'The comparison function must be either a function or undefined');\n  }\n\n  if (len < 2) return obj;\n\n  // The ES spec says that the sort order is implementation-defined if\n  // the array (or array-like) being sorted is sparse and prototype\n  // properties can be seen through the holes.\n  //\n  // Previously V8 (for compatibility with JSC) also sorted properties\n  // inherited from the prototype chain on non-Array objects.  It did\n  // this by copying them to this object and sorting only own\n  // properties.  Newer versions of V8 don't seem to do this any more,\n  // so for simplicity we sort only own properties.\n  //\n  // We do this by first moving all non-undefined properties to the\n  // front of the array and move the undefineds after that.  This\n  // moves holes to the end.\n  //\n  // TODO(cpcallen): this is slow.  Do it (as V8 did, before moving to\n  // a torque-based implementation) using a native function.\n  var undefCount = 0;\n  for (var i = 0, j = 0; j < len; j++) {\n    if (Object.prototype.hasOwnProperty.call(obj, j)) {\n      if (obj[j] === undefined) {\n        undefCount++;\n      } else {\n        obj[i++] = obj[j];\n      }\n    }\n  }\n  var definedCount = i;\n  for (; undefCount; undefCount--) {\n    obj[i++] = undefined;\n  }\n  for (; i < len; i++) {\n    delete obj[i];\n  }\n      \n  Array.prototype.sort.quicksort_(obj, 0, definedCount, comparefn);\n  return obj;\n};\nObject.defineProperty(Array.prototype, 'sort', {enumerable: false});\n\n// Helper functions.\nArray.prototype.sort.insertionSort_ = function insertionSort_(\n    a, from, to, comparefn) {\n  // For short (length <= 10) arrays, insertion sort is used for efficiency.\n  for (var i = from + 1; i < to; i++) {\n    var element = a[i];\n    for (var j = i - 1; j >= from; j--) {\n      var tmp = a[j];\n      var order = comparefn(tmp, element);\n      if (order > 0) {\n        a[j + 1] = tmp;\n      } else {\n        break;\n      }\n    }\n    a[j + 1] = element;\n  }\n};\nObject.defineProperty(Array.prototype.sort, 'insertionSort_',\n                      {enumerable: false});\n\nArray.prototype.sort.getThirdIndex_ = function getThirdIndex_(\n    a, from, to, comparefn) {\n  var t_array = [];\n  // Use both 'from' and 'to' to determine the pivot candidates.\n  var increment = 200 + ((to - from) & 15);\n  var j = 0;\n  from += 1;\n  to -= 1;\n  for (var i = from; i < to; i += increment) {\n    t_array[j] = [i, a[i]];\n    j++;\n  }\n  t_array.sort(function(a, b) {\n    return comparefn(a[1], b[1]);\n  });\n  var third_index = t_array[t_array.length >> 1][0];\n  return third_index;\n};\nObject.defineProperty(Array.prototype.sort, 'getThirdIndex_',\n                      {enumerable: false});\n\nArray.prototype.sort.quicksort_ = function quicksort_(a, from, to, comparefn) {\n  /* In-place QuickSort algorithm.\n   */\n  var third_index = 0;\n  while (true) {\n    // Insertion sort is faster for short arrays.\n    if (to - from <= 10) {\n      Array.prototype.sort.insertionSort_(a, from, to, comparefn);\n      return;\n    }\n    if (to - from > 1000) {\n      third_index = Array.prototype.sort.getThirdIndex_(a, from, to, comparefn);\n    } else {\n      third_index = from + ((to - from) >> 1);\n    }\n    // Find a pivot as the median of first, last and middle element.\n    var v0 = a[from];\n    var v1 = a[to - 1];\n    var v2 = a[third_index];\n    var c01 = comparefn(v0, v1);\n    if (c01 > 0) {\n      // v1 < v0, so swap them.\n      var tmp = v0;\n      v0 = v1;\n      v1 = tmp;\n    } // v0 <= v1.\n    var c02 = comparefn(v0, v2);\n    if (c02 >= 0) {\n      // v2 <= v0 <= v1.\n      var tmp = v0;\n      v0 = v2;\n      v2 = v1;\n      v1 = tmp;\n    } else {\n      // v0 <= v1 && v0 < v2\n      var c12 = comparefn(v1, v2);\n      if (c12 > 0) {\n        // v0 <= v2 < v1\n        var tmp = v1;\n        v1 = v2;\n        v2 = tmp;\n      }\n    }\n    // v0 <= v1 <= v2\n    a[from] = v0;\n    a[to - 1] = v2;\n    var pivot = v1;\n    var low_end = from + 1;   // Upper bound of elements lower than pivot.\n    var high_start = to - 1;  // Lower bound of elements greater than pivot.\n    a[third_index] = a[low_end];\n    a[low_end] = pivot;\n\n    // From low_end to i are elements equal to pivot.\n    // From i to high_start are elements that haven't been compared yet.\n    partition: for (var i = low_end + 1; i < high_start; i++) {\n      var element = a[i];\n      var order = comparefn(element, pivot);\n      if (order < 0) {\n        a[i] = a[low_end];\n        a[low_end] = element;\n        low_end++;\n      } else if (order > 0) {\n        do {\n          high_start--;\n          if (high_start == i) break partition;\n          var top_elem = a[high_start];\n          order = comparefn(top_elem, pivot);\n        } while (order > 0);\n        a[i] = a[high_start];\n        a[high_start] = element;\n        if (order < 0) {\n          element = a[i];\n          a[i] = a[low_end];\n          a[low_end] = element;\n          low_end++;\n        }\n      }\n    }\n    if (to - high_start < low_end - from) {\n      quicksort_(a, high_start, to, comparefn);\n      to = low_end;\n    } else {\n      quicksort_(a, from, low_end, comparefn);\n      from = high_start;\n    }\n  }\n};\nObject.defineProperty(Array.prototype.sort, 'quicksort_', {enumerable: false});\n\nArray.prototype.toLocaleString = function toLocaleString() {\n  var out = [];\n  for (var i = 0; i < this.length; i++) {\n    out[i] = (this[i] === null || this[i] === undefined) ?\n        '' : this[i].toLocaleString();\n  }\n  return out.join(',');\n};\nObject.defineProperty(Array.prototype, 'toLocaleString', {enumerable: false});\n\n///////////////////////////////////////////////////////////////////////////////\n// String.prototype polyfills\n///////////////////////////////////////////////////////////////////////////////\n\n// String.prototype.length is always 0.\nObject.defineProperty(String.prototype, 'length', {value: 0});\n\nString.prototype.replace = function replace(substr, newSubstr) {\n  // Polyfill to handle String.prototype.replace's second argument being\n  // a function.\n  if (typeof newSubstr !== 'function') {\n    // string.replace(string|regexp, string)\n    return (new 'String.prototype.replace').call(this, substr, newSubstr);\n  }\n  var str = this;\n  if (substr instanceof RegExp) {  // string.replace(regexp, function)\n    var subs = [];\n    var m = substr.exec(str);\n    while (m) {\n      m.push(m.index, str);\n      var inject = newSubstr.apply(undefined, m);\n      subs.push([m.index, m[0].length, inject]);\n      m = substr.global ? substr.exec(str) : null;\n    }\n    for (var i = subs.length - 1; i >= 0; i--) {\n      str = str.substring(0, subs[i][0]) + subs[i][2] +\n          str.substring(subs[i][0] + subs[i][1]);\n    }\n  } else {                         // string.replace(string, function)\n    var i = str.indexOf(substr);\n    if (i !== -1) {\n      var inject = newSubstr(str.substr(i, substr.length), i, str);\n      str = str.substring(0, i) + inject +\n          str.substring(i + substr.length);\n    }\n  }\n  return str;\n};\nObject.defineProperty(String.prototype, 'replace', {enumerable: false});\n"
  },
  {
    "path": "server/startup/es6.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Polyfills to bring the server's partial JavaScript\n * implementation to include some features of ECMAScript 2015 (ES6).\n * @author fraser@google.com (Neil Fraser)\n */\n\n// Global objects.\nvar WeakMap = new 'WeakMap';\n\n(function() {\n  // Hack to work around restriction that the 'new hack' only works on\n  // literal strings.  Note name must not contain any double quotes or\n  // backslashes, because we have no easy way to escape them yet!\n  var builtin = function(name) {\n    return eval('new \"' + name + '\"');\n  };\n\n  var classes = ['WeakMap'];\n  // Prototypes of global constructors.\n  for (var i = 0; i < classes.length; i++) {\n    var constructor = builtin(classes[i]);\n    Object.defineProperty(constructor, 'prototype', {\n                          configurable: false,\n                          enumerable: false,\n                          writable: false,\n                          value: builtin(classes[i] + '.prototype')\n                          });\n    Object.defineProperty(constructor.prototype, 'constructor', {\n                          configurable: true,\n                          enumerable: false,\n                          writable: true,\n                          value: constructor\n                          });\n  }\n\n  // Struct is a list of tuples:\n  //     [Object, 'Object', [static methods], [instance methods]]\n\n  var struct = [\n    [Object, 'Object', ['is', 'setPrototypeOf'], []],\n    [String, 'String', [], ['endsWith', 'includes', 'repeat', 'startsWith']],\n    [Number, 'Number', ['isFinite', 'isInteger', 'isNaN', 'isSafeInteger'], []],\n    [Math, 'Math', ['acosh', 'asinh', 'atanh', 'cbrt', 'clz32', 'cosh', 'expm1',\n                    'fround', 'hypot', 'imul', 'log10', 'log1p', 'log2', 'sign',\n                    'sinh', 'tanh', 'trunc'], []],\n    [WeakMap, 'WeakMap', [], ['delete', 'get', 'has', 'set']],\n  ];\n  for (var i = 0; i < struct.length; i++) {\n    var obj = struct[i][0];\n    var objName = struct[i][1];\n    var staticMethods = struct[i][2];\n    var instanceMethods = struct[i][3];\n    for (var j = 0; j < staticMethods.length; j++) {\n      var member = staticMethods[j];\n      Object.defineProperty(obj, member,\n          {configurable: true,\n           enumerable: false,\n           writable: true,\n           value: builtin(objName + '.' + member)});\n    }\n    for (var j = 0; j < instanceMethods.length; j++) {\n      var member = instanceMethods[j];\n      Object.defineProperty(obj.prototype, member,\n          {configurable: true,\n           enumerable: false,\n           writable: true,\n           value: builtin(objName + '.prototype.' + member)});\n    }\n  }\n})();\n\n///////////////////////////////////////////////////////////////////////////////\n// Object constructor polyfills\n///////////////////////////////////////////////////////////////////////////////\n\nObject.assign = function assign(target, varArgs) {\n  // The length property of the assign method is 2.\n  if (target === null || target === undefined) {\n    throw new TypeError('Cannot convert undefined or null to object');\n  }\n  target = Object(target);\n\n  for (var i = 1; i < arguments.length; i++) {\n    var src = arguments[i];\n    if (src !== null && src !== undefined) {\n      var keys = Object.keys(src);\n      for (var j = 0; j < keys.length; j++) {\n        var key = keys[j];\n        target[key] = src[key];\n      }\n    }\n  }\n  return target;\n};\nObject.defineProperty(Array, 'assign', {enumerable: false});\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Array constructor polyfills\n///////////////////////////////////////////////////////////////////////////////\n\nArray.from = function(arrayLike/*, mapFn, thisArg */) {\n  // Polyfill adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\n  // The length property of the from method is 1.  \n  var isCallable = function (fn) {\n    return typeof fn === 'function' || Object.prototype.toString.call(fn) === '[object Function]';\n  };\n  var toInteger = function (value) {\n    var number = Number(value);\n    if (isNaN(number)) { return 0; }\n    if (number === 0 || !isFinite(number)) { return number; }\n    return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));\n  };\n  var toLength = function (value) {\n    var len = toInteger(value);\n    return Math.min(Math.max(len, 0), Number.MAX_SAFE_INTEGER);\n  };\n\n  // 1. Let C be the this value.\n  var C = this;\n\n  // 2. Let items be ToObject(arrayLike).\n  var items = Object(arrayLike);\n\n  // 3. ReturnIfAbrupt(items).\n  if (arrayLike == null) {\n    throw new TypeError('Array.from requires an array-like object - not null or undefined');\n  }\n\n  // 4. If mapfn is undefined, then let mapping be false.\n  var mapFn = arguments.length > 1 ? arguments[1] : void undefined;\n  var T;\n  if (typeof mapFn !== 'undefined') {\n    // 5. else\n    // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.\n    if (!isCallable(mapFn)) {\n      throw new TypeError('Array.from: when provided, the second argument must be a function');\n    }\n\n    // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.\n    if (arguments.length > 2) {\n      T = arguments[2];\n    }\n  }\n\n  // 10. Let lenValue be Get(items, \"length\").\n  // 11. Let len be ToLength(lenValue).\n  var len = toLength(items.length);\n\n  // 13. If IsConstructor(C) is true, then\n  // 13. a. Let A be the result of calling the [[Construct]] internal method\n  // of C with an argument list containing the single item len.\n  // 14. a. Else, Let A be ArrayCreate(len).\n  var A = isCallable(C) ? Object(new C(len)) : new Array(len);\n\n  // 16. Let k be 0.\n  var k = 0;\n  // 17. Repeat, while k < len… (also steps a - h)\n  var kValue;\n  while (k < len) {\n    kValue = items[k];\n    if (mapFn) {\n      A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);\n    } else {\n      A[k] = kValue;\n    }\n    k += 1;\n  }\n  // 18. Let putStatus be Put(A, \"length\", len, true).\n  A.length = len;\n  // 20. Return A.\n  return A;\n};\nObject.defineProperty(Array, 'from', {enumerable: false});\n\n///////////////////////////////////////////////////////////////////////////////\n// Array.prototype polyfills\n///////////////////////////////////////////////////////////////////////////////\n\nArray.prototype.find = function find(callback/*, thisArg*/) {\n  // Polyfill copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/find\n  if (this === null || this === undefined) {\n    throw new TypeError('Array.prototype.find called on ' + this);\n  } else if (typeof callback !== 'function') {\n    throw new TypeError('callback is type ' + typeof callback +\n                        ', not type function');\n  }\n  var o = Object(this);\n  var len = o.length >>> 0;\n  var thisArg = arguments[1];\n  for (var k = 0; k < len; k++) {\n    var kValue = o[k];\n    if (callback.call(thisArg, kValue, k, o)) {\n      return kValue;\n    }\n  }\n  return undefined;\n};\nObject.defineProperty(Array.prototype, 'find', {enumerable: false});\n\nArray.prototype.findIndex = function findIndex(callback/*, thisArg*/) {\n  // Polyfill copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\n  if (this === null || this === undefined) {\n    throw new TypeError('Array.prototype.findIndex called on ' + this);\n  } else if (typeof callback !== 'function') {\n    throw new TypeError('callback is type ' + typeof callback +\n                        ', not type function');\n  }\n  var o = Object(this);\n  var len = o.length >>> 0;\n  var thisArg = arguments[1];\n  for (var k = 0; k < len; k++) {\n    var kValue = o[k];\n    if (callback.call(thisArg, kValue, k, o)) {\n      return k;\n    }\n  }\n  return -1;\n};\nObject.defineProperty(Array.prototype, 'findIndex', {enumerable: false});\n\n(function() {\n  function toInteger(value) {\n    var number = Number(value);\n    if (isNaN(number)) {\n      return 0;\n    } else if (number === 0 || !isFinite(number)) {\n      return number;\n    }\n    return Math.trunc(number);\n  }\n\n  function toLength(value) {\n    var len = toInteger(value);\n    if (len <= 0) {\n      return 0;\n    }\n    return Math.min(len, Number.MAX_SAFE_INTEGER);  // Handles len === Infinity.\n  }\n\n  // For cycle detection in array to string and error conversion; see\n  // spec bug github.com/tc39/ecma262/issues/289.\n  var visited = [];\n\n  Array.prototype.join = function join(separator) {\n    // This implements Array.prototype.join from ES6 §22.1.3.12, with\n    // the addition of cycle detection as discussed in\n    // https://github.com/tc39/ecma262/issues/289.\n    //\n    // The only difference from the ES5 version of the spec is that\n    // .length is normalised using the specification function\n    // ToLength rather than ToUint32.\n    //\n    // Variable names reflect those in the spec.\n    //\n    // N.B. This function is defined in a closure!\n    var isObj = (typeof this === 'object' || typeof this === 'function') &&\n        this !== null;\n    if (isObj) {\n      if (visited.indexOf(this) !== -1) {\n        return '';\n      }\n      visited.push(this);\n    }\n    try {\n      // TODO(cpcallen): setPerms(callerPerms());\n      var len = toLength(this.length);\n      var sep = (separator === undefined) ? ',' : String(separator);\n      if (!len) {\n        return '';\n      }\n      var r = '';\n      for (var k = 0; k < len; k++) {\n        if (k > 0) {\n          r += sep;\n        }\n        var element = this[k];\n        if (element !== undefined && element !== null) {\n          r += String(element);\n        }\n      }\n      return r;\n    } finally {\n      if (isObj) {\n        visited.pop();\n      }\n    }\n  };\n})();\nObject.defineProperty(Array.prototype, 'join', {enumerable: false});\n\n///////////////////////////////////////////////////////////////////////////////\n// Number polyfills\n///////////////////////////////////////////////////////////////////////////////\n\nObject.defineProperty(Number, 'EPSILON',\n    {configurable: false,\n     enumerable: false,\n     writable: false,\n     value: Math.pow(2, -52)});\n\nObject.defineProperty(Number, 'MAX_SAFE_INTEGER',\n    {configurable: false,\n     enumerable: false,\n     writable: false,\n     // Fortunately 2**53 is also safe as long as you don't increment it!:\n     value: Math.pow(2, 53) - 1 });\n\nObject.defineProperty(Number, 'MIN_SAFE_INTEGER',\n    {configurable: false,\n     enumerable: false,\n     writable: false,\n     value: -Number.MAX_SAFE_INTEGER});\n"
  },
  {
    "path": "server/startup/es7.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Polyfills to bring the server's partial JavaScript\n * implementation to include some features of ECMAScript 2016 (ES7).\n * @author fraser@google.com (Neil Fraser)\n */\n\n///////////////////////////////////////////////////////////////////////////////\n// Array.prototype methods\n///////////////////////////////////////////////////////////////////////////////\n\nArray.prototype.includes = new 'Array.prototype.includes';\nObject.defineProperty(Array.prototype, 'includes', {enumerable: false});\n"
  },
  {
    "path": "server/startup/es8.js",
    "content": "/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Polyfills to bring the server's partial JavaScript\n * implementation to include some features of ECMAScript 2017 (ES8).\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n///////////////////////////////////////////////////////////////////////////////\n// Object constructor polyfills\n///////////////////////////////////////////////////////////////////////////////\n\nObject.getOwnPropertyDescriptors = function getOwnPropertyDescriptors(obj) {\n  var ownKeys = Object.getOwnPropertyNames(obj);\n  var descriptors = {};\n  for (var i = 0; i < ownKeys.length; i++) {\n    var key = ownKeys[i];\n    var descriptor = Object.getOwnPropertyDescriptor(obj, key);\n    if (descriptor !== undefined) {\n      descriptors[key] = descriptor;\n    }\n  }\n  return descriptors;\n};\nObject.defineProperty(Object, 'getOwnPropertyDescriptors', {enumerable: false});\n"
  },
  {
    "path": "server/startup/esx.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Initialisation code to set up CodeCity JavaScript\n *     extensions.\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n// Global objects.\nvar Thread = new 'Thread';\nvar PermissionError = new 'PermissionError';\n\n(function() {\n  // Hack to work around restriction that the 'new hack' only works on\n  // literal strings.  Note name must not contain any double quotes or\n  // backslashes, because we have no easy way to escape them yet!\n  var builtin = function(name) {\n    return eval('new \"' + name + '\"');\n  };\n\n  var classes = ['PermissionError', 'Thread'];\n  // Prototypes of global constructors.\n  for (var i = 0; i < classes.length; i++) {\n    var constructor = builtin(classes[i]);\n    Object.defineProperty(constructor, 'prototype', {\n                          configurable: false,\n                          enumerable: false,\n                          writable: false,\n                          value: builtin(classes[i] + '.prototype')\n                          });\n    Object.defineProperty(constructor.prototype, 'constructor', {\n                          configurable: true,\n                          enumerable: false,\n                          writable: true,\n                          value: constructor\n                          });\n  }\n\n  // Configure Error subclasses.\n  var errors = ['PermissionError'];\n  for (var i = 0; i < errors.length; i++) {\n    var constructor = builtin(errors[i]);\n    Object.defineProperty(constructor.prototype, 'name', {\n                          configurable: true,\n                          enumerable: false,\n                          writable: true,\n                          value: errors[i]\n                          });\n  }\n\n  // Struct is a list of tuples:\n  //     [Object, 'Object', [static methods], [instance methods]]\n\n  var struct = [\n    [Object, 'Object', ['getOwnerOf', 'setOwnerOf'], []],\n    [Thread, 'Thread',\n     ['current', 'kill', 'suspend', 'callers'],\n     ['getTimeLimit', 'setTimeLimit']],\n  ];\n  for (var i = 0; i < struct.length; i++) {\n    var obj = struct[i][0];\n    var objName = struct[i][1];\n    var staticMethods = struct[i][2];\n    var instanceMethods = struct[i][3];\n    for (var j = 0; j < staticMethods.length; j++) {\n      var member = staticMethods[j];\n      Object.defineProperty(obj, member,\n          {configurable: true,\n           enumerable: false,\n           writable: true,\n           value: builtin(objName + '.' + member)});\n    }\n    for (var j = 0; j < instanceMethods.length; j++) {\n      var member = instanceMethods[j];\n      Object.defineProperty(obj.prototype, member,\n          {configurable: true,\n           enumerable: false,\n           writable: true,\n           value: builtin(objName + '.prototype.' + member)});\n    }\n  }\n})();\n\n///////////////////////////////////////////////////////////////////////////////\n// Array.prototype polyfills\n///////////////////////////////////////////////////////////////////////////////\n\n(function() {\n  function toInteger(value) {\n    var number = Number(value);\n    if (isNaN(number)) {\n      return 0;\n    } else if (number === 0 || !isFinite(number)) {\n      return number;\n    }\n    return Math.trunc(number);\n  }\n\n  function toLength(value) {\n    var len = toInteger(value);\n    if (len <= 0) return 0;\n    return Math.min(len, Number.MAX_SAFE_INTEGER);  // Handles len === Infinity.\n  };\n\n  // For cycle detection in array to string and error conversion; see\n  // spec bug github.com/tc39/ecma262/issues/289.\n  var visitedByThread = new WeakMap;\n\n  Array.prototype.join = function join(separator) {\n    // This implements Array.prototype.join from ES6 §22.1.3.12,\n    // with the addition of cycle detection as discussed in\n    // https://github.com/tc39/ecma262/issues/289.\n    //\n    // The only difference from the ES6 version is that the cycle\n    // detection mechanism is thread-aware, so multiple parallel\n    // invocations of .join will not interfere with each other.\n    //\n    // Variable names reflect those in the spec.\n    //\n    // N.B. This function is defined in a closure!\n    var isObj = (typeof this === 'object' || typeof this === 'function') &&\n        this !== null;\n    if (isObj) {\n      if (visitedByThread.has(Thread.current())) {\n        var visited = visitedByThread.get(Thread.current());\n      } else {\n        visited = [];\n        visitedByThread.set(Thread.current(), visited);\n      }\n      if (visited.includes(this)) {\n        return '';\n      }\n      visited.push(this);\n    }\n    try {\n      // TODO(cpcallen): setPerms(callerPerms());\n      var len = toLength(this.length);\n      var sep = (separator === undefined) ? ',' : String(separator);\n      if (!len) {\n        return '';\n      }\n      var r = '';\n      for (var k = 0; k < len; k++) {\n        if (k > 0) r += sep;\n        var element = this[k];\n        if (element !== undefined && element !== null) {\n          r += String(element);\n        }\n      }\n      return r;\n    } finally {\n      if (isObj) visited.pop();\n      if (!visited.length) {\n        visitedByThread.delete(Thread.current());\n      }\n    }\n  };\n})();\nObject.defineProperty(Array.prototype, 'join', {enumerable: false});\n\n///////////////////////////////////////////////////////////////////////////////\n// Threads API; parts are roughly conformant with HTML Living\n// Standard, plus our local extensions.\n//\nvar suspend = new 'Thread.suspend';\n\nvar setTimeout = function setTimeout(func, delay) {\n  /* setTimeout(func, delay[, ...args]) -> thread\n   *\n   * Arguments:\n   *   func <Function>: A function to call when the timer elapses.\n   *   delay <number>: Time to wait (in ms) before calling the callback.\n   *   ...args <any>: Optional arguments to pass to func.\n   *\n   * Returns:\n   *   <Thread>, which may be passed to clearTimeout() to cancel.\n   */\n  // TODO(cpcallen:perms): setPerms(callerPerms());\n  var args = Array.prototype.slice.call(arguments, 2);\n  args = [undefined, func, delay, undefined].concat(args);\n  return new (Thread.bind.apply(Thread, args));\n  // The parens around Thread.bind.apply(...) are mandatory: we want to\n  // \"new\" the function returned by bind, not apply (which is not a\n  // constructor).\n  return new (Thread.bind.apply(Thread, args))();\n};\n\nvar clearTimeout = function clearTimeout(thread) {\n  /* clearTimeout(thread)\n   *\n   * Arguments:\n   *   thread <Thread>: The Thread object whose execution to be cancelled.\n   *\n   * Note that attempts to cancel the current thread (or any non-Thread\n   * value) is silently ignored.\n   */\n  // TODO(cpcallen:perms): setPerms(callerPerms());\n  if (!(thread instanceof Thread) || thread === Thread.current()) {\n    return;\n  }\n  Thread.kill(thread);\n};\n"
  },
  {
    "path": "server/tests/code_test.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Tests for utilities for manipulating JavaScript code.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst {quote, parseString, testOnly} = require('../code');\nconst {T} = require('./testing');\nconst util = require('util');\n\n// Unpack test-only exports:\nconst {count} = testOnly;\n\n/**\n * Unit tests for the count function.\n * @param {!T} t The test runner object.\n */\nexports.testCount = function(t) {\n  t.expect(\"count('bobob', 'b')\", count('bobob', 'b'), 3);\n  t.expect(\"count('bobob', 'bo')\", count('bobob', 'bo'), 2);\n  t.expect(\"count('bobob', 'bob')\", count('bobob', 'bob'), 1);\n  t.expect(\"count('bobobob', 'bob')\", count('bobobob', 'bob'), 2);\n};\n\n/**\n * Unit tests for the quote function.\n * @param {!T} t The test runner object.\n */\nexports.testQuote = function(t) {\n  const cases = [\n    ['foo', \"'foo'\"],\n    ['\"Hi\", he said.', \"'\\\"Hi\\\", he said.'\"],\n    [\"Don't.\", '\"Don\\'t.\"'],\n    ['\\'\"', \"'\\\\'\\\"'\"],\n    ['\\0\\/\\b\\n\\r\\t\\v\\\\\\x05\\u2028\\u2029',\n         \"'\\\\0/\\\\b\\\\n\\\\r\\\\t\\\\v\\\\\\\\\\\\x05\\\\u2028\\\\u2029'\"],\n  ];\n  for (const tc of cases) {\n    const r = quote(tc[0]);\n    t.expect(util.format('quote(%o)', tc[0]), r, tc[1]);\n    t.expect(util.format('eval(quote(%o))', tc[0]), eval(r), tc[0]);\n  }\n};\n\n/**\n * Unit tests for the parseString function.\n * @param {!T} t The test runner object.\n */\nexports.testParseString = function(t) {\n  const cases = [\n    `'foo'`,\n    `'\"Hi\", he said.'`,\n    `\"\\\\\"Hi\\\\\", he said.\"`,\n    `'Don\\\\'t.'`,\n    `\"Don't.\"`,\n    `'\\\\0 \\\\' \\\\\" \\\\/ \\\\b \\\\n \\\\r \\\\t \\\\v \\\\\\\\ \\\\x00 \\\\xfF \\\\u09aF'`,\n  ];\n  for (const tc of cases) {\n    const r = parseString(tc);\n    t.expect(util.format('parseString(%o)', tc), r, eval(tc));\n  }\n\n  const badCases = [\n    `'foo`,\n    `\"\"Hi\", he said.\"`,\n    `'Don't.'`,\n    `'\\\\j'`,\n    `'\\\\x0'`,\n    `'\\\\u123'`,\n    `'\\\\x1g'`,\n    `'\\\\x1G'`,\n    `'\\\\u1g00'`,\n    `'\\\\u1G00'`,\n    `'\\r'`,\n    `'\\n'`,\n    `'\\u2028'`,\n    `'\\u2029'`,\n    // Pathological cases that previously caused exponential\n    // backtracking.\n    `'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,\n    `\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,\n  ];\n  for (const tc of badCases) {\n    try {\n      const r = parseString(tc);\n      t.fail(util.format('parseString(%o)', tc), \"Didn't throw.\");\n    } catch (e) {\n      t.pass(util.format('parseString(%o)', tc));\n    }\n  }\n};\n"
  },
  {
    "path": "server/tests/db/core_01_$.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Initialize the $ object in the database.\n * @author fraser@google.com (Neil Fraser)\n */\n\nvar $ = {};\n"
  },
  {
    "path": "server/tests/db/core_01_$.system.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Initialize the system object in the database.\n * @author fraser@google.com (Neil Fraser)\n */\n\n$.system = {};\n\n$.system.log = new 'CC.log';\n$.system.checkpoint = new 'CC.checkpoint';\n$.system.shutdown = new 'CC.shutdown';\n"
  },
  {
    "path": "server/tests/db/test.cfg",
    "content": "{\n  \"databaseDirectory\": \"./\",\n  \"checkpointInterval\": 0,\n  \"checkpointAtShutdown\": true\n}\n"
  },
  {
    "path": "server/tests/db/test_00_start.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Mock up a basic console.\n * @author fraser@google.com (Neil Fraser)\n */\n\nvar console = {};\nconsole.log = $.system.log;\nconsole.assert = function(value, message) {\n  if (value) {\n    console.goodCount++;\n  } else {\n    $.system.log('FAIL:\\t%s', message);\n    console.badCount++;\n  }\n};\n\n// Counters for unit test results.\nconsole.goodCount = 0;\nconsole.badCount = 0;\n\nvar tests = {};\n"
  },
  {
    "path": "server/tests/db/test_01_es5.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test the ES5 functions of the server.\n * @author fraser@google.com (Neil Fraser)\n */\n\n\n// Run some tests of the various constructors and their associated\n// literals and prototype objects.\ntests.builtinClasses = function() {\n  var classes = [\n    {\n      constructor: Object,\n      literal: {},\n      prototypeProto: null,\n      classStr: '[object Object]',\n    },\n    {\n      constructor: Function,\n      literal: function(){},\n      prototypeType: 'function',\n      classStr: '[object Function]',\n    },\n    {\n      constructor: Array,\n      literal: [],\n      classStr: '[object Array]',\n    },\n    {\n      constructor: RegExp,\n      literal: /foo/,\n      classStr: '[object RegExp]',\n      prototypeClass: '[object Object]' // Was 'RegExp' in ES5.1.\n    },\n    {\n      constructor: Date,\n      classStr: '[object Date]',\n      prototypeClass: '[object Object]', // Was 'RegExp' in ES5.1.\n      functionNotConstructor: true  // Date() doesn't construct.\n    },\n    {\n      constructor: Error,\n      classStr: '[object Error]',\n    },\n    {\n      constructor: EvalError,\n      prototypeProto: Error.prototype,\n      classStr: '[object Error]',\n    },\n    {\n      constructor: RangeError,\n      prototypeProto: Error.prototype,\n      classStr: '[object Error]',\n    },\n    {\n      constructor: ReferenceError,\n      prototypeProto: Error.prototype,\n      classStr: '[object Error]',\n    },\n    {\n      constructor: SyntaxError,\n      prototypeProto: Error.prototype,\n      classStr: '[object Error]',\n    },\n    {\n      constructor: TypeError,\n      prototypeProto: Error.prototype,\n      classStr: '[object Error]',\n    },\n    {\n      constructor: URIError,\n      prototypeProto: Error.prototype,\n      classStr: '[object Error]',\n    },\n    {\n      constructor: Boolean,\n      literal: true,\n      literalType: 'boolean',\n      noInstance: true,\n      classStr: '[object Boolean]',\n    },\n    {\n      constructor: Number,\n      literal: 42,\n      literalType: 'number',\n      noInstance: true,\n      classStr: '[object Number]',\n    },\n    {\n      constructor: String,\n      literal: \"hello\",\n      literalType: 'string',\n      noInstance: true,\n      classStr: '[object String]',\n    }\n  ];\n  for (var i = 0, tc; (tc = classes[i]); i++) {\n    var c = tc.constructor;\n    var prototypeType = (tc.prototypeType || 'object');\n    // Check constructor is a function:\n    console.assert(typeof c === 'function', c + ' isFunction');\n    // Check constructor's proto is Function.prototype\n    console.assert(Object.getPrototypeOf(c) === Function.prototype,\n        c + ' protoIsFunctionPrototype');\n    // Check prototype is of correct type:\n    console.assert(typeof c.prototype === prototypeType,\n        c + ' prototypeIs');\n    // Check prototype has correct class:\n    console.assert(\n        Object.prototype.toString.apply(c.prototype) ===\n        tc.prototypeClass || tc.classStr,\n        c + ' prototypeClassIs');\n    // Check prototype has correct proto:\n    console.assert(\n        Object.getPrototypeOf(c.prototype) ===\n        (tc.prototypeProto === undefined ? Object.prototype : tc.prototypeProto),\n        c + ' prototypeProtoIs');\n    // Check prototype's .constructor is constructor:\n    console.assert(c.prototype.constructor === c,\n        c + ' prototypeConstructorIs');\n\n    if (!tc.noInstance) {\n      // Check instance's type:\n      console.assert(typeof new c === prototypeType, c + ' instanceIs');\n      // Check instance's proto:\n      console.assert(Object.getPrototypeOf(new c) === c.prototype,\n          c + ' instancePrototypeIs');\n      // Check instance's class:\n      console.assert(Object.prototype.toString.apply(new c) === tc.classStr,\n          c + ' instanceClassIs');\n      // Check instance is instanceof its contructor:\n      console.assert((new c) instanceof c, c + ' instanceIsInstanceof');\n      if (!tc.functionNotConstructor) {\n        // Recheck instances when constructor called as function:\n        // Recheck instance's type:\n        console.assert(typeof c() === prototypeType, c + ' returnIs');\n        // Recheck instance's proto:\n        console.assert(Object.getPrototypeOf(c()) === c.prototype,\n            c + ' returnPrototypeIs');\n        // Recheck instance's class:\n        console.assert(Object.prototype.toString.apply(c()) === tc.classStr,\n            c + ' returnClassIs');\n        // Recheck instance is instanceof its contructor:\n        console.assert(c() instanceof c, c + ' returnIsInstanceof');\n      }\n    }\n    if (tc.literal) {\n      var literalType = (tc.literalType || prototypeType);\n      // Check literal's type:\n      console.assert(typeof tc.literal === literalType, c + ' literalIs');\n      // Check literal's proto:\n      console.assert(Object.getPrototypeOf(tc.literal) === c.prototype,\n          c + ' literalPrototypeIs');\n      // Check literal's class:\n      console.assert(\n          Object.prototype.toString.apply(tc.literal) === tc.classStr,\n          c + ' literalClassIs');\n      // Primitives can never be instances.\n      if (literalType === 'object' || literalType === 'function') {\n        // Check literal is instanceof its constructor.\n        console.assert(tc.literal instanceof c, c + ' literalIsInstanceof');\n      }\n    }\n  }\n};\n\n// Run some tests of switch statements with fallthrough.\ntests.switchFallthrough = function() {\n  var expected = [28, 31, 30, 12, 8];\n  for (var i = 0; i < expected.length; i++) {\n    var x = 0;\n    switch (i) {\n      case 1:\n        x += 1;\n        // fall through\n      case 2:\n        x += 2;\n        // fall through\n      default:\n        x += 16;\n        // fall through\n      case 3:\n        x += 4;\n        // fall through\n      case 4:\n        x += 8;\n        // fall through\n    }\n    console.assert(x === expected[i], 'switch fallthrough ' + i);\n  }\n};\n\n// Run some tests of switch statements.\ntests.switchBreak = function() {\n  var expected = [30, 20, 20, 30, 40];\n  for (var i = 0; i < expected.length; i++) {\n    var x;\n    foo: {\n      switch (i) {\n        case 1:\n          x = 10;\n          // fall through\n        case 2:\n          x = 20;\n          break;\n        default:\n          x = 50;\n          // fall through\n        case 3:\n          x = 30;\n          break foo;\n        case 4:\n          x = 40;\n      }\n    }\n    console.assert(x === expected[i], 'switch ' + i);\n  }\n};\n\n// Run some tests of evaluation of binary expressions, as defined in\n// §11.5--11.11 of the ES5.1 spec.\ntests.binary = function() {\n  var cases = [\n    // Addition / concatenation:\n    [\"1 + 1\", 2],\n    [\"'1' + 1\", '11'],\n    [\"1 + '1'\", '11'],\n\n    // Subtraction:\n    [\"'1' - 1\", 0],\n\n    // Multiplication:\n    [\"'5' * '5'\", 25],\n\n    [\"-5 * 0\", -0],\n    [\"-5 * -0\", 0],\n\n    [\"1 * NaN\", NaN],\n    [\"Infinity * NaN\", NaN],\n    [\"-Infinity * NaN\", NaN],\n\n    [\"Infinity * Infinity\", Infinity],\n    [\"Infinity * -Infinity\", -Infinity],\n    [\"-Infinity * -Infinity\", Infinity],\n    [\"-Infinity * Infinity\", -Infinity],\n    // FIXME: add overflow/underflow cases\n\n    // Division:\n    [\"35 / '7'\", 5],\n\n    [\"1 / 1\", 1],\n    [\"1 / -1\", -1],\n    [\"-1 / -1\", 1],\n    [\"-1 / 1\", -1],\n\n    [\"1 / NaN\", NaN],\n    [\"NaN / NaN\", NaN],\n    [\"NaN / 1\", NaN],\n\n    [\"Infinity / Infinity\", NaN],\n    [\"Infinity / -Infinity\", NaN],\n    [\"-Infinity / -Infinity\", NaN],\n    [\"-Infinity / Infinity\", NaN],\n\n    [\"Infinity / 0\", Infinity],\n    [\"Infinity / -0\", -Infinity],\n    [\"-Infinity / -0\", Infinity],\n    [\"-Infinity / 0\", -Infinity],\n\n    [\"Infinity / 1\", Infinity],\n    [\"Infinity / -1\", -Infinity],\n    [\"-Infinity / -1\", Infinity],\n    [\"-Infinity / 1\", -Infinity],\n\n    [\"1 / Infinity\", 0],\n    [\"1 / -Infinity\", -0],\n    [\"-1 / -Infinity\", 0],\n    [\"-1 / Infinity\", -0],\n\n    [\"0 / 0\", NaN],\n    [\"0 / -0\", NaN],\n    [\"-0 / -0\", NaN],\n    [\"-0 / 0\", NaN],\n\n    [\"1 / 0\", Infinity],\n    [\"1 / -0\", -Infinity],\n    [\"-1 / -0\", Infinity],\n    [\"-1 / 0\", -Infinity],\n    // FIXME: add overflow/underflow cases\n\n    // Remainder:\n    [\"20 % 5.5\", 3.5],\n    [\"20 % -5.5\", 3.5],\n    [\"-20 % -5.5\", -3.5],\n    [\"-20 % 5.5\", -3.5],\n\n    [\"1 % NaN\", NaN],\n    [\"NaN % NaN\", NaN],\n    [\"NaN % 1\", NaN],\n\n    [\"Infinity % 1\", NaN],\n    [\"-Infinity % 1\", NaN],\n    [\"1 % 0\", NaN],\n    [\"1 % -0\", NaN],\n    [\"Infinity % 0\", NaN],\n    [\"Infinity % -0\", NaN],\n    [\"-Infinity % -0\", NaN],\n    [\"-Infinity % 0\", NaN],\n\n    [\"0 % 1\", 0],\n    [\"-0 % 1\", -0],\n    // FIXME: add overflow/underflow cases\n\n    // Left shift:\n    [\"10 << 2\", 40],\n    [\"10 << 28\", -1610612736],\n    [\"10 << 33\", 20],\n    [\"10 << 34\", 40],\n\n    // Signed right shift:\n    [\"10 >> 4\", 0],\n    [\"10 >> 33\", 5],\n    [\"10 >> 34\", 2],\n    [\"-11 >> 1\", -6],\n    [\"-11 >> 2\", -3],\n\n    // Signed right shift:\n    [\"10 >>> 4\", 0],\n    [\"10 >>> 33\", 5],\n    [\"10 >>> 34\", 2],\n    [\"-11 >>> 0\", 0xfffffff5],\n    [\"-11 >>> 1\", 0x7ffffffa],\n    [\"-11 >>> 2\", 0x3ffffffd],\n    [\"4294967338 >>> 0\", 42],\n\n    // Bitwise:\n    [\"0x3 | 0x5\", 0x7],\n    [\"0x3 ^ 0x5\", 0x6],\n    [\"0x3 & 0x5\", 0x1],\n\n    [\"NaN | 0\", 0],\n    [\"-0 | 0\", 0],\n    [\"Infinity | 0\", 0],\n    [\"-Infinity | 0\", 0],\n\n    // Comparisons:\n    //\n    // (This is mainly about making sure that the binary operators are\n    // hooked up to the abstract relational comparison algorithm\n    // correctly; that algorithm is tested separately to make sure\n    // details of comparisons are correct.)\n    [\"1 < 2\", true],\n    [\"2 < 2\", false],\n    [\"3 < 2\", false],\n\n    [\"1 <= 2\", true],\n    [\"2 <= 2\", true],\n    [\"3 <= 2\", false],\n\n    [\"1 > 2\", false],\n    [\"2 > 2\", false],\n    [\"3 > 2\", true],\n\n    [\"1 >= 2\", false],\n    [\"2 >= 2\", true],\n    [\"3 >= 2\", true],\n\n    // (Ditto for abstract equality comparison algorithm.)\n    [\"1 == 1\", true],\n    [\"2 == 1\", false],\n    [\"2 == 2\", true],\n    [\"1 == 2\", false],\n\n    [\"1 == '1'\", true],\n\n    [\"1 != 1\", false],\n    [\"2 != 1\", true],\n    [\"2 != 2\", false],\n    [\"1 != 2\", true],\n\n    [\"1 != '1'\", false],\n\n    // (Ditto for abstract strict equality comparison algorithm.)\n    [\"1 === 1\", true],\n    [\"2 === 1\", false],\n    [\"2 === 2\", true],\n    [\"1 === 2\", false],\n\n    [\"1 === '1'\", false],\n\n    [\"1 !== 1\", false],\n    [\"2 !== 1\", true],\n    [\"2 !== 2\", false],\n    [\"1 !== 2\", true],\n\n    [\"1 !== '1'\", true],\n  ];\n\n  // Object.is is part of ES6, not ES5, so provide a helper function.\n  // Copied from:\n  // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n  function is(x, y) {\n    // SameValue algorithm\n    if (x === y) { // Steps 1-5, 7-10\n      // Steps 6.b-6.e: +0 != -0\n      return x !== 0 || 1 / x === 1 / y;\n    } else {\n     // Step 6.a: NaN == NaN\n     return x !== x && y !== y;\n    }\n  }\n\n  for (var i = 0, tc; (tc = cases[i]); i++) {\n    var actual = eval(tc[0]);\n    var expected = tc[1];\n    console.assert(is(actual, expected), tc[0] +\n                   ' Actual: ' + actual  + ' Expected: ' + expected);\n  }\n};\n\n// Run some tests of the Abstract Relational Comparison Algorithm, as defined\n// in §11.8.5 of the ES5.1 spec and as embodied by the '<' operator.\ntests.arca = function() {\n  var cases = [\n    ['0, NaN', undefined],\n    ['NaN, NaN', undefined],\n    ['NaN, 0', undefined],\n\n    ['1, 1', false],\n    ['0, -0', false],\n    ['-0, 0', false],\n\n    ['Infinity, Number.MAX_VALUE', false],\n    ['Number.MAX_VALUE, Infinity', true],\n    ['-Infinity, -Number.MAX_VALUE', true],\n    ['-Number.MAX_VALUE, -Infinity', false],\n\n    ['1, 2', true],\n    ['2, 1', false],\n\n    // String comparisons:\n    ['\"\", \"\"', false],\n    ['\"\", \" \"', true],\n    ['\" \", \"\"', false],\n    ['\" \", \" \"', false],\n    ['\"foo\", \"foobar\"', true],\n    ['\"foo\", \"bar\"', false],\n    ['\"foobar\", \"foo\"', false],\n    ['\"10\", \"9\"', true],\n    ['\"10\", 9', false],\n\n    // \\ufb00 vs. \\U0001f019: this test fails if we do simple\n    // lexicographic comparison of UTF-8 or UTF-32.  The latter\n    // character is a larger code point and sorts later in UTF8,\n    // but in UTF16 it gets replaced by two surrogates, both of\n    // which are smaller than \\uf000.\n    ['\"ﬀ\", \"🀙\"', false],\n\n    // Mixed:\n    ['11, \"2\"', false],  // Numeric\n    ['2, \"11\"', true],   // Numeric\n    ['\"11\", \"2\"', true], // String\n  ];\n  function arca(a, b) {\n    return ((a < b) || (a >= b)) ? (a < b) : undefined;\n  }\n  for (var i = 0, tc; (tc = cases[i]); i++) {\n    console.assert(tc[1] === eval('arca(' + tc[0] + ')'), 'ARCA: ' + tc[0]);\n  }\n};\n\n// Run some tests of the Abstract Equality Comparison Algorithm and\n// the Abstract Strict Equality Comparison Algorithm, as defined in\n// §11.9.3 and §11.9.6 respectively of the ES5.1 spec and as embodied\n// by the '==' and '===' operators.\ntests.aeca_aseca = function() {\n  var cases = [\n    ['false, false', true, true],  // Numeric\n    ['false, true', false, false], // Numeric\n    ['true, true', true, true],    // Numeric\n    ['true, false', false, false], // Numeric\n\n    // Numeric comparisons:\n    ['0, NaN', false, false],\n    ['NaN, NaN', false, false],\n    ['NaN, 0', false, false],\n\n    ['1, 1', true, true],\n    ['0, -0', true, true],\n    ['-0, 0', true, true],\n\n    ['Infinity, Number.MAX_VALUE', false, false],\n    ['Number.MAX_VALUE, Infinity', false, false],\n    ['Infinity, -Number.MAX_VALUE', false, false],\n    ['-Number.MAX_VALUE, -Infinity', false, false],\n\n    ['1, 2', false, false],\n    ['2, 1', false, false],\n\n    // String comparisons:\n    ['\"\", \"\"', true, true],\n    ['\"\", \" \"', false, false],\n    ['\" \", \"\"', false, false],\n    ['\" \", \" \"', true, true],\n    ['\"foo\", \"foobar\"', false, false],\n    ['\"foo\", \"bar\"', false, false],\n    ['\"foobar\", \"foo\"', false, false],\n    ['\"10\", \"9\"', false, false],\n\n    // Null / undefined:\n    ['undefined, undefined', true, true],\n    ['undefined, null', true, false],\n    ['null, null', true, true],\n    ['null, undefined', true, false],\n\n    // Objects:\n    ['Object.prototype, Object.prototype', true, true],\n    ['{}, {}', false, false],\n\n    // Mixed:\n    ['\"10\", 10', true, false],   // Numeric\n    ['10, \"10\"', true, false],   // Numeric\n    ['\"10\", 9', false, false],   // Numeric\n    ['\"10\", \"9\"', false, false], // String\n    ['\"10\", \"10\"', true, true],  // String\n\n    ['false, 0', true, false],  // Numeric\n    ['false, 1', false, false], // Numeric\n    ['true, 1', true, false],   // Numeric\n    ['true, 0', false, false],  // Numeric\n    ['0, false', true, false],  // Numeric\n    ['1, false', false, false], // Numeric\n    ['1, true', true, false],   // Numeric\n    ['0, true', false, false],  // Numeric\n\n    ['null, false', false, false],\n    ['null, 0', false, false],\n    ['null, \"\"', false, false],\n    ['false, null', false, false],\n    ['0, null', false, false],\n    ['\"\", null', false, false],\n\n    ['{}, false', false, false],\n    ['{}, 0', false, false],\n    ['{}, \"\"', false, false],\n    ['{}, null', false, false],\n    ['{}, undefined', false, false],\n  ];\n  function aeca(a, b) {\n    return a == b;\n  }\n  function aseca(a, b) {\n    return a === b;\n  }\n  for (var i = 0, tc; (tc = cases[i]); i++) {\n    console.assert(tc[1] === eval('aeca(' + tc[0] + ')'), 'AECA: ' + tc[0]);\n    console.assert(tc[2] === eval('aseca(' + tc[0] + ')'), 'ASECA: ' + tc[0]);\n  }\n};\n\ntests.isFinite = function() {\n  console.assert(!isFinite(Infinity), 'isFinite Infinity');\n  console.assert(!isFinite(NaN), 'isFinite NaN');\n  console.assert(!isFinite(-Infinity), 'isFinite -Infinity');\n  console.assert(isFinite(0), 'isFinite 0');\n  console.assert(isFinite(2e64), 'isFinite 2e64');\n  console.assert(isFinite('0'), 'isFinite \"0\"');\n  console.assert(isFinite(null), 'isFinite null');\n};\n\ntests.isNaN = function() {\n  console.assert(isNaN(NaN), 'isNaN NaN');\n  console.assert(isNaN(0 / 0), 'isNaN 0 / 0');\n  console.assert(isNaN('NaN'), 'isNaN \"NaN\"');\n  console.assert(isNaN(undefined), 'isNaN undefined');\n  console.assert(isNaN({}), 'isNaN {}');\n  console.assert(isNaN('blabla'), 'isNaN \"blabla\"');\n  console.assert(!isNaN(true), 'isNaN true');\n  console.assert(!isNaN(null), 'isNaN null');\n  console.assert(!isNaN(37), 'isNaN 37');\n  console.assert(!isNaN('37'), 'isNaN \"37\"');\n  console.assert(!isNaN('37.37'), 'isNaN \"37.37\"');\n  console.assert(!isNaN(''), 'isNaN \"\"');\n  console.assert(!isNaN(' '), 'isNaN \" \"');\n};\n\ntests.basicMath = function() {\n  console.assert(1 + 1 === 2, 'onePlusOne');\n  console.assert(2 + 2 === 4,'twoPlusTwo');\n  console.assert(6 * 7 === 42, 'sixTimesSeven');\n  console.assert((3 + 12 / 4) * (10 - 3) === 42, 'simpleFourFunction');\n};\n\ntests.basicVariables = function() {\n  var x = 43;\n  console.assert(x === 43, 'variableDecl');\n  x = 44;\n  console.assert(x === 44, 'simpleAssignment');\n};\n\ntests.ternary = function() {\n  console.assert((true ? 'then' : 'else') === 'then', 'condTrue');\n  console.assert((false ? 'then' : 'else') === 'else', 'condFalse');\n};\n\ntests.ifElse = function() {\n  var ifTrue;\n  if (true) {\n    ifTrue = 'then';\n  } else {\n    ifTrue = 'else';\n  }\n  console.assert(ifTrue === 'then', 'ifTrue');\n  var ifFalse;\n  if (false) {\n    ifFalse = 'then';\n  } else {\n    ifFalse = 'else';\n  }\n  console.assert(ifFalse === 'else', 'ifFalse');\n};\n\ntests.propertyAssignment = function() {\n  var o = {};\n  o.foo = 45;\n  console.assert(o.foo == 45, 'propertyAssignment');\n};\n\ntests.propertyOnPrimitive = function() {\n  console.assert('foo'.length === 3, 'propertyOnPrimitiveGet');\n  try {\n    'foo'.bar = 42;\n    console.assert('foo'.length === 3, 'propertyOnPrimitiveSet');\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'propertyOnPrimitiveSetError');\n  }\n};\n\ntests.increment = function() {\n  var postincrement = 45;\n  postincrement++;\n  console.assert(postincrement++ === 46, 'postincrement');\n  var preincrement = 45;\n  ++preincrement;\n  console.assert(++preincrement === 47, 'preincrement');\n};\n\ntests.concat = function() {\n  console.assert('foo' + 'bar' === 'foobar', 'concat');\n};\n\ntests.plusEquals = function() {\n  var plusequalsLeft = 40;\n  var plusequalsRight = 8;\n  plusequalsLeft += plusequalsRight;\n  console.assert(plusequalsLeft === 48, 'plusequalsLeft');\n  console.assert(plusequalsRight === 8, 'plusequalsRight');\n};\n\ntests.simpleFunctionExpression = function() {\n  var value;\n  var f = function() {\n    value = 49;\n  };\n  f();\n  console.assert(value === 49, 'simpleFunctionExpression');\n};\n\ntests.funExpWithParameter = function() {\n  var value;\n  var f = function(x) {\n    value = x;\n  };\n  f(50);\n  console.assert(value === 50, 'fExpWithParameter');\n};\n\ntests.functionReturn = function() {\n  console.assert('functionWithReturn', (function(x) { return x; })(51), 51);\n  console.assert('functionWithoutReturn', (function() {})(), undefined);\n  var multipleReturn = function() {\n    try {\n      return true;\n    } finally {\n      return false;\n    }\n  };\n  console.assert(multipleReturn() === false, 'multipleReturn');\n};\n\ntests.throwCatch = function() {\n  var f = function() {\n    throw 26;\n  };\n  var result;\n  try {\n    f();\n  } catch (e) {\n    result = e * 2;\n  }\n  console.assert(result === 52, 'throwCatch');\n};\n\ntests.throwCatchFalsey = function() {\n  var result;\n  try {\n    throw null;\n  } catch (e) {\n    result = 'caught ' + String(e);\n  }\n  console.assert(result === 'caught null', 'throwCatchFalsey');\n};\n\ntests.seqExpr = function() {\n  console.assert((51, 52, 53) === 53, 'seqExpr');\n};\n\ntests.labeledStatement = function() {\n  foo: var x = 54;\n  console.assert(x === 54, 'labeledStatement');\n};\n\ntests.whileLoop = function() {\n  var a = 0;\n  while (a < 55) {\n    a++;\n  }\n  console.assert(a === 55, 'whileLoop');\n};\n\ntests.whileFalse = function() {\n  var a = 56;\n  while (false) {\n    a++;\n  }\n  console.assert(a === 56, 'whileFalse');\n};\n\ntests.doWhileFalse = function() {\n  var a = 56;\n  do {\n    a++;\n  } while (false);\n  console.assert(a === 57, 'doWhileFalse');\n};\n\ntests.breakDoWhile = function() {\n  var a = 57;\n  do {\n    a++;\n    break;\n    a++;\n  } while (false);\n  console.assert(a === 58, 'breakDoWhile');\n};\n\ntests.selfBreak = function() {\n  console.assert(eval('foo: break foo;') === undefined, 'selfBreak');\n};\n\ntests.breakWithFinally = function() {\n  var a = 6;\n  foo: {\n    try {\n      a *= 10;\n      break foo;\n    } finally {\n      a--;\n    }\n  }\n  console.assert(a === 59, 'breakWithFinally');\n};\n\ntests.continueWithFinally = function() {\n  var a = 59;\n  do {\n    try {\n      continue;\n    } finally {\n      a++;\n    }\n  } while (false);\n  console.assert(a === 60, 'continueWithFinally');\n};\n\ntests.breakWithFinallyContinue = function() {\n  var a = 0;\n  while (a++ < 60) {\n    try {\n      break;\n    } finally {\n      continue;\n    }\n  }\n  console.assert(a === 61, 'breakWithFinallyContinue');\n};\n\ntests.returnWithFinallyContinue = function() {\n  var f = function() {\n    var i = 0;\n    while (i++ < 61) {\n      try {\n        return 42;\n      } finally {\n        continue;\n      }\n    }\n    return i;\n  };\n  console.assert(f() === 62, 'returnWithFinallyContinue');\n};\n\ntests.or = function() {\n  console.assert((63 || 'foo') === 63, 'orTrue');\n  console.assert((false || 64) === 64, 'orFalse');\n  var r = 0;\n  true || (r++);\n  console.assert(r === 0, 'orShortcircuit');\n};\n\ntests.and = function() {\n  console.assert((({}) && 65) === 65, 'andTrue');\n  console.assert((0 && 65) === 0, 'andFalse');\n  var r = 0;\n  false && (r++);\n  console.assert(r === 0, 'andShortcircuit');\n};\n\ntests.forTriangular = function() {\n  var t = 0;\n  for (var i = 0; i < 12; i++) {\n    t += i;\n  }\n  console.assert(t === 66, 'forTriangular');\n};\n\ntests.forIn = function() {\n  var x = 0, a = {a: 60, b:3, c:4};\n  for (var i in a) { x += a[i]; }\n  console.assert(x === 67, 'forIn');\n};\n\ntests.forInMemberExp = function() {\n  var x = 1, o = {foo: 'bar'}, a = {a:2, b:2, c:17};\n  for (o.foo in a) { x *= a[o.foo]; }\n  console.assert(x === 68, 'forInMemberExp');\n};\n\ntests.forInMembFunc = function() {\n  var x = 0, o = {};\n  var f = function() { x += 20; return o; };\n  var a = {a:2, b:3, c:4};\n  for (f().foo in a) { x += a[o.foo]; }\n  console.assert(x === 69, 'forInMembFunc');\n};\n\ntests.forInNullUndefined = function() {\n  var x = 0, o = {};\n  var f = function() { x++; return o; };\n  for (f().foo in null) { x++; }\n  for (f().foo in undefined) { x++; }\n  console.assert(x === 0, 'forInNullUndefined');\n};\n\ntests.switchDefaultFirst = function() {\n  var r;\n  switch ('not found') {\n    default:\n      r = 'OK';\n      break;\n    case 'decoy':\n      r = 'fail';\n  };\n  console.assert(r === 'OK', 'switchDefaultFirst');\n}\n\ntests.switchDefaultOnly = function() {\n  var r;\n  switch ('not found') {\n    default:\n      r = 'OK';\n      break;\n  };\n  console.assert(r === 'OK', 'switchDefaultOnly');\n}\n\ntests.switchEmptyToEnd = function() {\n  switch ('foo') {\n    default:\n      console.assert(false, 'switchEmptyToEnd');\n    case 'foo':\n    case 'bar':\n  }\n};\n\ntests.thisInMethod = function() {\n  var o = {\n    f: function() { return this.foo; },\n    foo: 70\n  };\n  console.assert(o.f() === 70, 'thisInMethod');\n};\n\ntests.thisInFormerMethod = function() {\n  var o = { f: function() { return this; }};\n  var g = o.f;\n  console.assert(g() === undefined, 'thisInFormerMethod');\n};\n\ntests.testThis = function() {\n  console.assert(this === tests, 'testThis');\n  console.assert(eval('this') === tests, 'evalThis');\n  console.assert(tests.testThis.globalThis === undefined, 'globalThis');\n};\n\ntests.testThis.globalThis = this;\n\ntests.strictBoxedThis = function() {\n  // Run a test to ensure that 'this' is a primitive in methods invoked on\n  // primitives.  (This also tests that interpreter is running in strict mode;\n  // in sloppy mode this will be boxed.)\n  try {\n    Object.prototype.foo = function() { return typeof this; };\n    console.assert('foo'.foo() === 'string', 'strictBoxedThis');\n  } finally {\n    console.assert(delete Object.prototype.foo, 'strictBoxedThisDelete');\n  }\n};\n\ntests.emptyArrayLength = function() {\n  console.assert([].length === 0, 'emptyArrayLength');\n};\n\ntests.arrayElidedLength = function() {\n  console.assert([1,,3,,].length === 4, 'arrayElidedLength');\n};\n\ntests.arrayElidedNotDefinedNotUndefined = function() {\n  var a = [,undefined,null,0,false];\n  console.assert(!(0 in a) && (1 in a) && (2 in a) && (3 in a) && (4 in a),\n                 'arrayElidedNotDefinedNotUndefined');\n};\n\ntests.arrayLengthPropertyDescriptor = function() {\n  var a = [1, 2, 3];\n  var pd = Object.getOwnPropertyDescriptor(a, 'length');\n  console.assert((pd.value === 3), 'arrayLengthPropertyDescriptorValue');\n  console.assert(pd.writable && !pd.enumerable && !pd.configurable,\n                 'arrayLengthPropertyDescriptor');\n};\n\ntests.arrayLength = function() {\n  var a;\n  function checkLen(exp, desc) {\n    if (a.length !== exp) {\n      var msg = 'a.length === ' + a.length + ' (expected: ' + exp + ')';\n      console.assert(false, desc ? msg + ' ' + desc : msg);\n    }\n  }\n\n  // Empty array has length == 0\n  a = [];\n  checkLen(0, 'on empty array');\n\n  // Adding non-numeric properties does not increase length:\n  a['zero'] = 0;\n  checkLen(0, 'after setting non-index property on []');\n\n  // Adding numeric properties >= length does increase length:\n  for (var i = 0; i < 5; i++) {\n    a[i] = i;\n    checkLen(i + 1, 'after setting a[' + i + ']');\n  }\n\n  // .length works propery even for large, sparse arrays, and even\n  // if values are undefined:\n  for (i = 3; i <= 31; i++) {\n    var idx = (1 << i) >>> 0;  // >>> 0 converts int32 to uint32\n    a[idx] = undefined;\n    checkLen(idx + 1, 'after setting a[' + idx + ']');\n  }\n\n  // Adding numeric properties < length does not increase length:\n  a[idx - 1] = 'not the largest';\n  checkLen(idx + 1, 'after setting non-largest element');\n\n  // Verify behaviour around largest possible index:\n  a[0xfffffffd] = null;\n  checkLen(0xfffffffe);\n  a[0xfffffffe] = null;\n  checkLen(0xffffffff);\n  a[0xffffffff] = null;  // Not an index.\n  checkLen(0xffffffff);  // Unchanged.\n  a[0x100000000] = null; // Not an index.\n  checkLen(0xffffffff);  // Unchanged.\n\n  function checkIdx(idx, exp, desc) {\n    var r = a.hasOwnProperty(idx);\n    var msg = 'a.hasOwnProperty(' + idx + ') === ' + r;\n    console.assert(r === exp, desc ? msg + ' ' + desc : msg);\n  }\n\n  // Setting length to existing value should have no effect:\n  a.length = 0xffffffff;\n  checkIdx(0xfffffffd, true);\n  checkIdx(0xfffffffe, true);\n  checkIdx(0xffffffff, true);\n  checkIdx(0x100000000, true);\n\n  // Setting length one less than maximum should remove largest\n  // index, but leave properties with keys too large to be indexes:\n  a.length = 0xfffffffe;\n  checkIdx(0xfffffffd, true);\n  checkIdx(0xfffffffe, false);\n  checkIdx(0xffffffff, true);\n  checkIdx(0x100000000, true);\n\n  // Setting length to zero should remove all index properties:\n  a.length = 0;\n  for (var key in a) {\n    if (!a.hasOwnProperty(key)) {\n      continue;\n    }\n    console.assert(String(key >>> 0) !== key || (key >>> 0) === 0xffffffff,\n                   'Setting a.length = 0 failed to remove property ' + key);\n  }\n\n  // Make sure we didn't wipe everything!\n  console.assert(Object.getOwnPropertyNames(a).length === 4,\n                 'Setting .length = 0 removed some non-index properties');\n};\n\ntests.arrayLengthWithNonWritableProps = function() {\n  var a = [];\n  Object.defineProperty(a, 0,\n      {value: 'hi', writable: false, configurable: true});\n  a.length = 0;\n  console.assert(a[0] === undefined && a.length === 0,\n                 'arrayLengthWithNonWritableProps');\n};\n\ntests.arrayLengthWithNonConfigurableProps = function() {\n  var a = [];\n  Object.defineProperty(a, 0,\n      {value: 'hi', writable: false, configurable: false});\n  try {\n    a.length = 0;\n    console.assert(false, 'arrayLengthWithNonConfigurableProps');\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n                   'arrayLengthWithNonConfigurableProps');\n  }\n};\n\ntests.compValEmptyBlock = function() {\n  console.assert(eval('{}') === undefined, 'compValEmptyBlock');\n};\n\ntests.unaryVoid = function() {\n  var x = 70;\n  console.assert((undefined === void x++) && x === 71, 'unaryVoid');\n};\n\ntests.unaryPlusMinus = function() {\n  console.assert(+'72' === 72, 'unaryPlus');\n  console.assert(-73 === -73, 'unaryPlus');\n};\n\ntests.unaryComplement = function() {\n  console.assert(~0xffffffb5 === 74, 'unaryComplement');\n};\n\ntests.unaryNot = function() {\n  console.assert(!false && (!true === false), 'unaryNot');\n};\n\ntests.unaryTypeof = function() {\n  console.assert(typeof undefined === 'undefined', 'unaryTypeofUndefined');\n  console.assert(typeof null === 'object', 'unaryTypeofNull');\n  console.assert(typeof false === 'boolean', 'unaryTypeofBoolean');\n  console.assert(typeof 0 === 'number', 'unaryTypeofNumber');\n  console.assert(typeof '' === 'string', 'unaryTypeofString');\n  console.assert(typeof {} === 'object', 'unaryTypeofObject');\n  console.assert(typeof [] === 'object', 'unaryTypeofArray');\n  console.assert(typeof function() {} === 'function', 'unaryTypeofFunction');\n  console.assert(typeof undeclaredVar === 'undefined', 'unaryTypeofUndeclared');\n};\n\ntests.binaryIn = function() {\n  var o = {foo: 'bar'};\n  console.assert('foo' in o && !('bar' in o), 'binaryIn');\n};\n\ntests.binaryInParent = function() {\n  var p = {foo: 'bar'};\n  var o = Object.create(p);\n  console.assert('foo' in o && !('bar' in o), 'binaryInParent');\n};\n\ntests.binaryInArrayLength = function() {\n  console.assert('length' in [], 'binaryInArrayLength');\n};\n\ntests.binaryInStringLength = function() {\n  try {\n    'length' in '';\n    console.assert(false, 'binaryInStringLength');\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'binaryInStringLengthError');\n  }\n};\n\ntests.instanceofBasics = function() {\n  function F(){}\n  var f = new F;\n  console.assert(f instanceof F, 'instanceofBasics1');\n  console.assert(f instanceof Object, 'instanceofBasics2');\n  console.assert(!(f.prototype instanceof F), 'instanceofBasics3');\n};\n\ntests.instanceofNonObjectLHS = function() {\n  function F() {}\n  F.prototype = null;\n  console.assert(!(42 instanceof F), 'instanceofNonObjectLHS');\n};\n\ntests.instanceofNonFunctionRHS = function() {\n  try {\n    ({}) instanceof 0;\n    console.assert(false, 'instanceofNonFunctionRHS');\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'instanceofNonFunctionRHSError');\n  }\n};\n\ntests.instanceofNonObjectPrototype = function() {\n  function F() {};\n  F.prototype = 'hello';\n  try {\n    ({}) instanceof F;\n    console.assert(false, 'instanceofNonObjectPrototype');\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'instanceofNonObjectPrototypeError');\n  }\n};\n\ntests.nullUndefinedProps = function() {\n  try {\n    undefined.foo;\n    console.assert(false, \"undefined.foo didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'undefined.foo wrong error');\n  }\n  try {\n    var c = 0;\n    undefined.foo = c++;\n    console.assert(false, \"undefined.foo = ... didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'undefined.foo = ... wrong error');\n    console.assert(c === 0, 'undefined.foo = ... evaluated RHS');\n  }\n  try {\n    null.foo;\n    console.assert(false, \"null.foo didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'null.foo wrong error');\n  }\n  try {\n    c = 0;\n    null.foo = c++;\n    console.assert(false, \"null.foo = ... didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'null.foo = ... wrong error');\n    console.assert(c === 0, 'null.foo = ... evaluated RHS');\n  }\n};\n\ntests.deleteProp = function() {\n  var o = {foo: 'bar'};\n  console.assert(delete o.quux, 'deleteProp1');\n  console.assert('foo' in o, 'deleteProp2');\n  console.assert(delete o.foo, 'deleteProp3');\n  console.assert(!('foo' in o), 'deleteProp4');\n  console.assert(delete o.foo, 'deleteProp5');\n};\n\ntests.deleteNonexistentFromPrimitive = function() {\n  console.assert(delete false.nonexistent, 'deleteNonexistentFromPrimitive');\n  console.assert(delete (42).toString, 'deleteInheritedFromPrimitive');\n};\n\n// This \"actually\" tries to delete the non-configurable own .length\n// property from the auto-boxed String instance created by step 4a of\n// algorithm in §11.4.1 of the ES 5.1 spec.  We have to use a string\n// here, because only String instances have own properties (and yes:\n// they are all non-configurable, so delete *always* fails).\ntests.deleteOwnFromPrimitive = function() {\n  try {\n    delete 'hello'.length;\n    console.assert(false, 'deleteOwnFromPrimitive');\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'deleteOwnFromPrimitive');\n  }\n};\n\ntests.funcDecl = function() {\n  var v;\n  function f() {\n    v = 75;\n  }\n  f();\n  console.assert(v === 75, 'funcDecl');\n};\n\ntests.namedFunctionExpression = function() {\n  var f = function half(x) {\n    if (x < 100) {\n      return x;\n    }\n    return half(x / 2);\n  };\n  console.assert(f(152) === 76, 'namedFunctionExpression');\n\n  f = function foo() {return foo;};\n  console.assert(f() === f, 'namedFunExpNameBinding');\n\n  f = function foo() {};\n  console.assert(typeof foo === 'undefined', 'namedFunExpBindingNoLeak');\n\n  try {\n    (function foo() {foo = null;})();\n    console.assert(false, \"namedFunExpNameBindingImmutable didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n      'namedFunExpNameBindingImmutable wrong error');\n  }\n\n  f = function foo(foo) {\n    foo += 0.1;  // Verify mutability.\n    return foo;\n  };\n  console.assert(f(76) === 76.1, 'nameFunExpNameBindingShadowedByParam');\n\n  f = function foo() {\n    var foo;\n    foo = 76.2;  // Verify mutability.\n    return foo;\n  };\n  console.assert(f(76) === 76.2, 'nameFunExpNameBindingShadowedByVar');\n};\n\ntests.closureIndependence = function() {\n  function makeAdder(x) {\n    return function(y) { return x + y; };\n  }\n  var plus3 = makeAdder(3);\n  var plus4 = makeAdder(4);\n  console.assert(plus3(plus4(70)) === 77, 'closureIndependence');\n};\n\ntests.internalObjectToString = function() {\n  var o = {};\n  o[{}] = null;\n  for(var key in o) {\n  }\n  console.assert(key === '[object Object]', 'internalObjectToString');\n};\n\ntests.internalFunctionToString = function() {\n  var o = {}, s, f = function(){};\n  o[f] = null;\n  for(var key in o) {\n    s = key;\n  }\n  console.assert(/^function.*\\(.*\\).*{[^]*}$/.test(s), 'internalFunctionToString');\n};\n\ntests.internalNativeFuncToString = function() {\n  var o = {}, s, f = Object.create;\n  o[f] = null;\n  for(var key in o) {\n    s = key;\n  }\n  console.assert(/^function.*\\(.*\\).*{[^]*}$/.test(s), 'internalNativeFuncToString');\n};\n\ntests.internalArrayToString = function() {\n  var o = {};\n  o[[1, 2, 3]] = null;\n  for(var key in o) {\n  }\n  console.assert(key === '1,2,3', 'internalArrayToString');\n};\n\ntests.internalDateToString = function() {\n  var o = {};\n  o[new Date(0)] = null;\n  for(var key in o) {\n  }\n  console.assert(key === (new Date(0)).toString(), 'internalDateToString');\n};\n\ntests.internalRegExpToString = function() {\n  var o = {};\n  o[/foo/g] = null;\n  for(var key in o) {\n  }\n  console.assert(key === '/foo/g', 'internalRegExpToString');\n};\n\ntests.internalErrorToString = function() {\n  var o = {};\n  o[Error('oops')] = null;\n  for(var key in o) {\n  }\n  console.assert(key === 'Error: oops', 'internalErrorToString');\n};\n\ntests.internalArgumentsToString = function() {\n  var o = {};\n  (function() {\n    o[arguments] = null;\n  })();\n  for(var key in o) {\n  }\n  console.assert(key === '[object Arguments]', 'internalArgumentsToString');\n};\n\ntests.debugger = function() {\n  console.assert(eval('debugger') === undefined, 'debugger');\n};\n\ntests.newExpression = function() {\n  function T(x, y) { this.sum += x + y; };\n  T.prototype = { sum: 70 };\n  var t = new T(7, 0.7);\n  console.assert(t.sum === 77.7, 'newExpression');\n};\n\ntests.newExpressionReturnObj = function() {\n  function T() { return {}; };\n  T.prototype = { p: 'the prototype' };\n  console.assert((new T).p === undefined, 'newExpressionReturnObj');\n};\n\ntests.newExpressionReturnObj = function() {\n  function T() { return 0; };\n  T.prototype = { p: 'the prototype' };\n  console.assert((new T).p === 'the prototype', 'newExpressionReturnObj');\n};\n\ntests.regexpSimple = function() {\n  console.assert(/foo/.test('foobar'), 'regexpSimple');\n};\n\ntests.evalSeeEnclosing = function() {\n  var n = 77.77;\n  console.assert(eval('n') === 77.77, 'evalSeeEnclosing');\n};\n\ntests.evalIndirectNoSeeEnclosing = function() {\n  var n = 77.77, gEval = eval;\n  try {\n    gEval('n');\n    console.assert(false, 'evalIndirectNoSeeEnclosing');\n  } catch (e) {\n    console.assert(e.name === 'ReferenceError', 'evalIndirectNoSeeEnclosing');\n  }\n  try {\n    (function() { return eval; })()('n');\n    console.assert(false, 'evalIndirectNoSeeEnclosing2');\n  } catch (e) {\n    console.assert(e.name === 'ReferenceError', 'evalIndirectNoSeeEnclosing2');\n  }\n};\n\ntests.evalIndirectSeeGlobal = function() {\n  var gEval = eval;\n  console.assert(gEval('typeof Array') === 'function', 'evalIndirectSeeGlobal');\n};\n\ntests.evalModifyEnclosing = function() {\n  var n = 77.77;\n  eval('n = 77.88');\n  console.assert(n === 77.88, 'evalModifyEnclosing');\n};\n\ntests.evalNoLeakingDecls = function() {\n  eval('var n = 88.88');\n  console.assert(typeof n === 'undefined', 'evalNoLeakingDecls');\n};\n\ntests.evalEmptyBlock = function() {\n  // A bug in eval would cause it to return the value of the\n  // previously-evaluated ExpressionStatement if the eval program did\n  // not contain any ExpressionStatements.\n  'fail';\n  console.assert(eval('{}') === undefined, 'evalEmptyBlock');\n};\n\ntests.callEvalOrder = function() {\n  var r = \"\";\n  function log(x) {\n    r += x;\n    return function () {};\n  };\n  (log('f'))(log('a'), log('b'), log('c'));\n  console.assert(r === 'fabc', 'callEvalOrder');\n};\n\ntests.callEvalArgsBeforeCallability = function() {\n  try {\n    var invalid = undefined;\n    function t() { throw {name: 'args'}; };\n    invalid(t());\n    console.assert(false, 'callEvalArgsBeforeCallability');\n  } catch(e) {\n    console.assert(e.name === 'args', 'callEvalArgsBeforeCallability');\n  }\n};\n\ntests.callNonCallable = function() {\n  function check(v) {\n    try {\n      v();\n      console.assert(false, 'callNonCallable' + v);\n    } catch(e) {\n      console.assert(e.name === 'TypeError', 'callNonCallable' + v);\n    }\n  }\n  check(undefined);\n  check(null);\n  check(false);\n  check(42);\n  check('hello');\n  check(Object.create(Function.prototype));\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Object and Object.prototype\n\ntests.ObjectDefinePropertyNoArgs = function() {\n  try {\n    Object.defineProperty();\n    console.assert(false, \"Object.defineProperty() didn't throw\");\n  } catch (e) {\n    console.assert(\n        e.name === 'TypeError', 'Object.defineProperty() wrong error');\n  }\n};\n\ntests.ObjectDefinePropertyNonObject = function() {\n  try {\n    Object.defineProperty('not an object', 'foo', {});\n    console.assert(false, \"Object.defineProperty non-object didn't throw\");\n  } catch (e) {\n    console.assert(\n        e.name === 'TypeError', 'Object.defineProperty non-object wrong error');\n  }\n};\n\ntests.ObjectDefinePropertyBadDescriptor = function() {\n  var o = {};\n  try {\n    Object.defineProperty(o, 'foo', 'not an object');\n    console.assert(false, \"Object.defineProperty bad descriptor didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.defineProperty bad descriptor wrong error');\n  }\n};\n\ntests.ObjectDefineProperty = function() {\n  // This also tests iteration over (non-)enumerable properties.\n  var o = { foo: 70 }, r = 0;\n  Object.defineProperty(o, 'bar', {\n    writable: true,\n    enumerable: true,\n    configurable: true,\n    value: 8\n  });\n  Object.defineProperty(o, 'baz', {\n    value: 13\n  });\n  for (var k in o) {\n    r += o[k];\n  }\n  console.assert(r === 78, 'Object.defineProperty');\n};\n\ntests.ObjectGetPrototypeOfNullUndefined = function() {\n  try {\n    Object.getPrototypeOf(null);\n    console.assert(false, \"Object.getPrototypeOf null didn't throw\");\n  } catch (e) {\n    console.assert(\n        e.name === 'TypeError', 'Object.getPrototypeOf null wrong error');\n  }\n  try {\n    Object.getPrototypeOf(undefined);\n    console.assert(false, \"Object.getPrototypeOf undefined didn't throw\");\n  } catch (e) {\n    console.assert(\n        e.name === 'TypeError', 'Object.getPrototypeOf undefined wrong error');\n  }\n};\n\ntests.ObjectGetPrototypeOfPrimitives = function() {\n  // This tests for ES6 behaviour.\n  console.assert(Object.getPrototypeOf(true) === Boolean.prototype,\n      'Object.getPrototypeOf boolean');\n  console.assert(Object.getPrototypeOf(1337) === Number.prototype,\n      'Object.getPrototypeOf number');\n  console.assert(Object.getPrototypeOf('hi') === String.prototype,\n      'Object.getPrototypeOf string');\n};\n\ntests.ObjectCreateNoArgs = function() {\n  try {\n    Object.create();\n    console.assert(false, \"Object.create() didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'Object.create() wrong error');\n  }\n};\n\ntests.ObjectCreateNonObject = function() {\n  try {\n    Object.create(42);\n    console.assert(false, \"Object.create non-object didn't throw\");\n  } catch (e) {\n    console.assert(\n        e.name === 'TypeError', 'Object.create non-object wrong error');\n  }\n};\n\ntests.ObjectCreateNull = function() {\n  var o = Object.create(null);\n  console.assert(Object.getPrototypeOf(o) === null, 'Object.create null');\n};\n\ntests.ObjectCreate = function() {\n  var o = Object.create({foo: 79});\n  delete o.foo;\n  console.assert(o.foo === 79, 'Object.create');\n};\n\ntests.ObjectGetOwnPropertyDescriptorNoArgs = function() {\n  try {\n    Object.getOwnPropertyDescriptor();\n    console.assert(false, \"Object.getOwnPropertyDescriptor() didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.getOwnPropertyDescriptor() wrong error');\n  }\n};\n\ntests.ObjectGetOwnPropertyDescriptorNonObject = function() {\n  try {\n    Object.getOwnPropertyDescriptor('not an object', 'foo');\n    console.assert(\n        false, \"Object.getOwnPropertyDescriptor non-object didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.getOwnPropertyDescriptor non-object wrong error');\n  }\n};\n\ntests.ObjectGetOwnPropertyDescriptorBadKey = function() {\n  var o = {};\n  console.assert(Object.getOwnPropertyDescriptor(o, 'foo') === undefined,\n      'Object.getOwnPropertyDescriptor bad key');\n};\n\ntests.ObjectGetOwnPropertyDescriptor = function() {\n  var o = {}, r = 0;\n  Object.defineProperty(o, 'foo', { value: 'bar' });\n  var desc = Object.getOwnPropertyDescriptor(o, 'foo');\n  console.assert(desc.value === o.foo, 'Object.getOwnPropertyDescriptor value');\n  console.assert(!desc.writable, 'Object.getOwnPropertyDescriptor writable');\n  console.assert(\n      !desc.enumerable, 'Object.getOwnPropertyDescriptor enumerable');\n  console.assert(\n      !desc.configurable, 'Object.getOwnPropertyDescriptor configurable');\n};\n\ntests.ObjectGetOwnPropertyNamesNoArgs = function() {\n  try {\n    Object.getOwnPropertyNames();\n    console.assert(false, \"Object.getOwnPropertyNames() didn't throw\");\n  } catch (e) {\n    console.assert(\n        e.name === 'TypeError', 'Object.getOwnPropertyNames() wrong error');\n  }\n};\n\ntests.ObjectGetOwnPropertyNamesString = function() {\n  var i, r = 0, names = Object.getOwnPropertyNames('foo');\n  for (i = 0; i < names.length; i++) {\n    if (names[i] === 'length') {\n      r += 10;\n    } else {\n      r += Number(names[i]) + 1;\n    }\n  }\n  console.assert(r === 16, 'Object.getOwnPropertyNames(string)');\n};\n\ntests.ObjectGetOwnPropertyNamesNumber = function() {\n  console.assert( Object.getOwnPropertyNames(42).length === 0,\n                 'Object.getOwnPropertyNames(number)');\n};\n\ntests.ObjectGetOwnPropertyNamesBoolean = function() {\n  console.assert(Object.getOwnPropertyNames(true).length === 0,\n                 'Object.getOwnPropertyNames(boolean)');\n};\n\ntests.ObjectGetOwnPropertyNamesNull = function() {\n  try {\n    Object.getOwnPropertyNames(null);\n    console.assert(false, \"Object.getOwnPropertyNames(null) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.getOwnPropertyNames(null) wrong error');\n  }\n};\n\ntests.ObjectGetOwnPropertyNamesUndefined = function() {\n  try {\n    Object.getOwnPropertyNames(undefined);\n    console.assert(false, \"Object.getOwnPropertyNames(undefined) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.getOwnPropertyNames(undefined) wrong error');\n  }\n};\n\ntests.ObjectGetOwnPropertyNames = function() {\n  var o = Object.create({baz: 999});\n  o.foo = 42;\n  Object.defineProperty(o, 'bar', { value: 38 });\n  var keys = Object.getOwnPropertyNames(o);\n  var r = 0;\n  for (var i = 0; i < keys.length; i++) {\n    r += o[keys[i]];\n  }\n  console.assert(r === 80, 'Object.getOwnPropertyNames');\n};\n\ntests.ObjectDefinePropertiesNoArgs = function() {\n  try {\n    Object.defineProperties();\n    console.assert(false, \"Object.defineProperties() didn't throw\");\n  } catch (e) {\n    console.assert(\n        e.name === 'TypeError', 'Object.defineProperties() wrong error');\n  }\n};\n\ntests.ObjectDefinePropertiesNonObject = function() {\n  try {\n    Object.defineProperties('not an object', {});\n    console.assert(false, \"Object.defineProperties non-object didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.defineProperties non-object wrong error');\n  }\n};\n\ntests.ObjectDefinePropertiesNonObjectProps = function() {\n  try {\n    Object.defineProperties({}, undefined);\n    console.assert(\n        false, \"Object.defineProperties non-object props didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.defineProperties non-object props wrong error');\n  }\n};\n\ntests.ObjectDefinePropertiesBadDescriptor = function() {\n  var o = {};\n  try {\n    Object.defineProperties(o, { foo: 'not an object' });\n    console.assert(\n        false, \"Object.defineProperties bad descriptor didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.defineProperties bad descriptor wrong error');\n  }\n};\n\ntests.ObjectDefineProperty = function() {\n  var o = { foo: 50 }, r = 0;\n  Object.defineProperty(o, 'bar', {\n    writable: true,\n    enumerable: true,\n    configurable: true,\n    value: 0\n  });\n  o.bar = 20;\n  console.assert(o.bar === 20, 'Object.defineProperty +WEC');\n  Object.defineProperty(o, 'baz', {\n    writable: true,\n    enumerable: true,\n    configurable: false\n  });\n  console.assert(o.baz === undefined, 'Object.defineProperty +WE-C 1');\n  Object.defineProperty(o, 'baz', {\n    value: 8\n  });\n  console.assert(o.baz === 8, 'Object.defineProperty +WE-C 2');\n  Object.defineProperty(o, 'quux', {\n    enumerable: false,\n    value: 13\n  });\n  console.assert(o.baz === 8, 'Object.defineProperty -WEC');\n  for (var k in o) {\n    r += o[k];\n  }\n  console.assert(r === 78, 'Object.defineProperty enumerability');\n  console.assert(Object.getOwnPropertyNames(o).length === 4,\n      'Object.defineProperty result .length wrong');\n};\n\ntests.ObjectCreateWithProperties = function() {\n  var o = Object.create({ foo: 70 }, {\n      bar: {\n          writable: true,\n          enumerable: true,\n          configurable: true,\n          value: 10 },\n      baz: { value: 999 }});\n  var r = 0;\n  for (var k in o) {\n    r += o[k];\n  }\n  r += Object.getOwnPropertyNames(o).length;\n  console.assert(r === 82, 'Object.create(..., properties)');\n};\n\ntests.ObjectPrototypeToString = function() {\n  console.assert(({}).toString() === '[object Object]',\n      'Object.prototype.toString');\n};\n\ntests.ObjectPrototypeHasOwnProperty = function() {\n  var o = Object.create({baz: 999});\n  o.foo = 42;\n  Object.defineProperty(o, 'bar', { value: 41, enumerable: true });\n  var r = 0;\n  for (var key in o) {\n    if (!o.hasOwnProperty(key)) continue;\n    r += o[key];\n  }\n  console.assert(r === 83, 'Object.prototype.hasOwnProperty');\n};\n\ntests.ObjectPrototypeIsPrototypeOf = function() {\n  var pfx = 'Object.prototype.isPrototypeOf';\n  console.assert(!Boolean.prototype.isPrototypeOf(false),\n                 'Boolean.prototype.isPrototypeOf(false)');\n  console.assert(!Number.prototype.isPrototypeOf(0),\n                 'Number.prototype.isPrototypeOf(0)');\n  console.assert(!String.prototype.isPrototypeOf(''),\n                 \"String.prototype.isPrototypeOf('')\");\n  console.assert(!Object.prototype.isPrototypeOf.call(false, false),\n                 pfx + '.call(false, false)');\n  console.assert(!Object.prototype.isPrototypeOf.call(0, 0),\n                 pfx + '.call(0, 0)');\n  console.assert(!Object.prototype.isPrototypeOf.call('', ''),\n                pfx + \".call('', '')\");\n  console.assert(!Object.prototype.isPrototypeOf.call(null, null),\n                 pfx + '.call(null, null)');\n  console.assert(!Object.prototype.isPrototypeOf.call(undefined, undefined),\n                 pfx + '.call(undefined, undefined)');\n  try {\n    Object.prototype.isPrototypeOf.call(null, Object.create(null));\n    console.assert(false, pfx + \".call(null, ...) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n                   pfx + '.call(null, ...) wrong error');\n  }\n  try {\n    Object.prototype.isPrototypeOf.call(undefined, Object.create(undefined));\n    console.assert(false, pfx + \".call(undefined, ...) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n                   pfx + '.call(undefined, ...) wrong error');\n  }\n\n  var g = {};\n  var p = Object.create(g);\n  var o = Object.create(p);\n  console.assert(!o.isPrototypeOf(o), pfx + ' self');\n  console.assert(!Object.prototype.isPrototypeOf(Object.create(null)),\n                 pfx + ' unrelated');\n  console.assert(!o.isPrototypeOf({}), pfx + ' siblings');\n  console.assert(g.isPrototypeOf(o), pfx + ' grandchild');\n  console.assert(p.isPrototypeOf(o), pfx + ' child');\n  console.assert(!o.isPrototypeOf(p), pfx + ' parent');\n  console.assert(!o.isPrototypeOf(g), pfx + ' grandparent');\n};\n\ntests.ObjectPrototypePropertyIsEnumerable = function() {\n  try {\n    Object.prototype.propertyIsEnumerable.call(null, '');\n    console.assert(\n        false, \"Object.prototype.propertyIsEnumerable(null) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.prototype.propertyIsEnumerable(null) wrong error');\n  }\n  try {\n    Object.prototype.propertyIsEnumerable.call(undefined, '');\n    console.assert(\n        false, \"Object.prototype.propertyIsEnumerable(undefined) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.prototype.propertyIsEnumerable(undefined) wrong error');\n  }\n  var OppIE = Object.prototype.propertyIsEnumerable;\n  console.assert(OppIE.call('foo', '0'),\n                 'Object.prototype.propertyIsEnumerable primitive true');\n  console.assert(!OppIE.call('foo', 'length'),\n                 'Object.prototype.propertyIsEnumerable primitive false');\n  var o = {foo: 'foo'};\n  Object.defineProperty(o, 'bar', {value: 'bar', enumerable: false});\n  console.assert(o.propertyIsEnumerable('foo'),\n                 'Object.prototype.propertyIsEnumerable true');\n  console.assert(!o.propertyIsEnumerable('bar'),\n                 'Object.prototype.propertyIsEnumerable false 1');\n  console.assert(!o.propertyIsEnumerable('baz'),\n                 'Object.prototype.propertyIsEnumerable false 2');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Function and Function.prototype\n\ntests.FunctionConstructor = function() {\n  var f = new Function;\n  console.assert(f() === undefined, 'new Function() returns callable');\n  console.assert(f.length === 0, 'new Function() .length');\n  var actual = String(f);\n  var expected = 'function anonymous(\\n) {\\n\\n}';\n  console.assert(actual === expected, 'new Function() .toString() ' +\n      'Actual: \"' + actual + '\" Expected: \"' + expected + '\"');\n\n  f = new Function('return 42;');\n  console.assert(f() === 42, 'new Function simple returns callable');\n  console.assert(f.length === 0, 'new Function simple .length');\n  actual = String(f);\n  expected = 'function anonymous(\\n) {\\nreturn 42;\\n}';\n  console.assert(actual === expected, 'new Function simple .toString() ' +\n      'Actual: \"' + actual + '\" Expected: \"' + expected + '\"');\n\n  f = new Function('a, b', 'c', 'return a + b * c;');\n  console.assert(f(2, 3, 10) === 32, 'new Function with args returns callable');\n  console.assert(f.length === 3, 'new Function with args .length');\n  actual = String(f);\n  expected = 'function anonymous(a, b,c\\n) {\\nreturn a + b * c;\\n}';\n  console.assert(actual === expected, 'new Function with args .toString() ' +\n      'Actual: \"' + actual + '\" Expected: \"' + expected + '\"');\n};\n\ntests.FunctionPrototypeHasNoPrototype = function() {\n  console.assert(Function.prototype.hasOwnProperty('prototype') === false,\n      'Function.prototype has no .prototype');\n};\n\ntests.FunctionPrototypeToStringApplyNonFunctionThrows = function() {\n  try {\n    Function.prototype.toString.apply({});\n    console.assert(\n        false, \"Function.prototype.toString.apply non-function didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Function.prototype.toString().apply non-function wrong error');\n  }\n};\n\ntests.FunctionPrototypeApplyNonFuncThrows = function() {\n  try {\n    var o = {};\n    o.apply = Function.prototype.apply;\n    o.apply();\n    console.assert(false, \"Function.prototype.apply non-function didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Function.prototype.apply non-function wrong error');\n  }\n};\n\ntests.FunctionPrototypeApplyThis = function() {\n  var o = {};\n  function f() { return this; }\n  console.assert(f.apply(o, []) === o, 'Function.prototype.apply this');\n};\n\ntests.FunctionPrototypeApplyArgsUndefinedOrNull = function() {\n  var n = 0;\n  function f() { n += arguments.length; }\n  f.apply(undefined, undefined);\n  f.apply(undefined, null);\n  console.assert(n === 0, 'Function.prototype.apply(undefined) or null');\n};\n\ntests.FunctionPrototypeApplyArgsNonObject = function() {\n  try {\n    (function() {}).apply(undefined, 'not an object');\n    console.assert(\n        false, \"Function.prototype.apply(..., non-object) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Function.prototype.apply(...., non-object) wrong error');\n  }\n};\n\ntests.FunctionPrototypeApplyArgsSparse = function() {\n  var f = function(a, b, c) {\n    if (!(1 in arguments)) {\n      throw Error(\"Argument 1 missing\");\n    }\n    return a + c;\n  };\n  console.assert(f.apply(undefined, [1, , 3]) === 4,\n      'Function.prototype.apply(..., sparse)');\n};\n\ntests.FunctionPrototypeApplyArgsArraylike = function() {\n  var n = (function(a, b, c) {\n       return a + b + c;\n     }).apply(undefined, {0: 1, 1: 2, 2: 3, length: 3});\n  console.assert(n === 6, 'Function.prototype.apply(..., array-like)');\n};\n\ntests.FunctionPrototypeApplyArgsNonArraylike = function() {\n  console.assert(isNaN((function(a, b, c) {\n    return a + b + c;\n  }).apply(undefined, {0: 1, 1: 2, 2: 4})),\n      'Function.prototype.apply(..., non-array-like)');\n};\n\ntests.FunctionPrototypeCallNonFuncThrows = function() {\n  try {\n    var o = {};\n    o.call = Function.prototype.call;\n    o.call();\n    console.assert(false, \"Function.prototype.call non-func didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Function.prototype.call non-func wrong error');\n  }\n};\n\ntests.FunctionPrototypeCallThis = function() {\n  var o = {};\n  function f() { return this; }\n  console.assert(f.call(o) === o, 'Function.prototype.call this');\n};\n\ntests.FunctionPrototypeCallNoArgs = function() {\n  function f() { return arguments.length; }\n  console.assert(f.call(undefined) === 0, 'Function.prototype.call no args');\n};\n\ntests.FunctionPrototypeCall = function() {\n  var f = function(a, b, c) {\n    if (!(1 in arguments)) {\n      throw Error(\"Argument 1 missing\");\n    }\n    return a + c;\n  };\n  console.assert(f.call(undefined, 1, 2, 3) === 4, 'Function.prototype.call');\n};\n\ntests.FunctionPrototypeBindNonFuncThrows = function() {\n  try {\n    var o = {};\n    o.bind = Function.prototype.bind;\n    o.bind();\n    console.assert(false, \"Function.prototype.bind non-func didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Function.prototype.bind non-func wrong error');\n  }\n};\n\ntests.FunctionPrototypeBindThis = function() {\n  var o = {};\n  function f() { return this; }\n  console.assert(f.bind(o)() === o, 'Function.prototype.bind this');\n};\n\ntests.FunctionPrototypeBindNoArgs = function() {\n  function f() { return arguments.length; }\n  console.assert(f.bind(undefined)() === 0, 'Function.prototype.bind no args');\n};\n\ntests.FunctionPrototypeBind = function() {\n  var d = 4;\n  var f = function(a, b, c) {\n    return a + b + c + d;\n  };\n  console.assert(f.bind(undefined, 1).bind(undefined, 2)(3) === 10,\n      'Function.prototype.bind');\n};\n\ntests.FunctionPrototypeBindCallBF = function() {\n  var constructed;\n  function Foo() {constructed = (this instanceof Foo)}\n  var f = Foo.bind();\n  f();\n  console.assert(constructed === false,\n      'Function.prototype.bind: calling bound function calls target');\n};\n\ntests.FunctionPrototypeBindConstructBF = function() {\n  var constructed;\n  function Foo() {constructed = (this instanceof Foo)}\n  var f = Foo.bind();\n  new f;\n  console.assert(constructed === true,\n      'Function.prototype.bind: constructing bound function constructs target');\n};\n\ntests.FunctionPrototypeCallBindConstructBF = function() {\n  var invoked;\n  function Foo() {invoked = true;}\n  var f = Foo.call.bind(Foo);\n  try {\n    new f;\n    console.assert(false, \"Calling bound call function didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Calling bound call function threw wrong error');\n  }\n  console.assert(!invoked, 'Calling bound call function invoked call target');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Array and Array.prototype\n\ntests.ArrayNoArgs = function() {\n  var a = new Array;\n  console.assert(Array.isArray(a), 'new Array() returns array');\n  console.assert(a.length === 0, '(new Array().length');\n};\n\ntests.ArrayNumericArg = function() {\n  var a = new Array(42);\n  console.assert(Array.isArray(a), 'new Array(number) returns array');\n  console.assert(!(0 in a), 'new Array(number) has no first item');\n  console.assert(!(41 in a), 'new Array(number) has no last item');\n  console.assert(a.length === 42, 'new Array(number).length');\n};\n\ntests.ArrayNonNumericArg = function() {\n  var a = new Array('foo');\n  console.assert(Array.isArray(a), 'new Array(non-number) returns array');\n  console.assert(a.length === 1, 'new Array(non-number).length');\n  console.assert(a[0] ==='foo', 'new Array(non-number)[0]');\n};\n\ntests.ArrayMultipleArgs = function() {\n  var a = new Array(1, 2, 3);\n  console.assert(Array.isArray(a), 'new Array(multiple...) return array');\n  console.assert(a.length === 3, 'new Array(multiple...).ength');\n  console.assert(String(a) ==='1,2,3', 'new Array(multiple...).toString()');\n};\n\ntests.ArrayIsArrayArrayPrototype = function() {\n  console.assert(\n      Array.isArray(Array.prototype), 'Array.isArray Array.prototype');\n};\n\ntests.ArrayIsArrayArrayInstance = function() {\n  console.assert(Array.isArray(new Array), 'Array.isArray Array instance');\n};\n\ntests.ArrayIsArrayArrayLiteral = function() {\n  console.assert(Array.isArray([]), 'Array.isArray Array literal');\n};\n\ntests.ArrayIsArrayArrayLike = function() {\n  console.assert(!Array.isArray({0: 'foo', 1: 'bar', length: 2}),\n      'Array.isArray(array-like)');\n};\n\ntests.ArrayPrototypeConcat = function() {\n  var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n  var c = a.concat();\n  console.assert(a.length === 6 && c.length === 6 && c !== a &&\n      String(c) === String(a), 'Array.prototype.concat()');\n\n  var o = {0: 'quux', 1: 'quuux', length: 2};\n  c = [].concat(['foo', 'bar'], 'baz', undefined, o);\n  console.assert(c.length === 5 && '3' in c && c[3] === undefined &&\n      String(c) === 'foo,bar,baz,,[object Object]',\n      'Array.prototype.concat(...)');\n\n  o = {0: 'foo', 1: 'bar', length: 2};\n  c = Array.prototype.concat.call(o, 'baz', [, 'quux', 'quuux']);\n  console.assert(c.length === 5 &&\n      String(c) === '[object Object],baz,,quux,quuux',\n      'Array.prototype.concat.call(object, ...)');\n};\n\ntests.ArrayPrototypeIndexOf = function() {\n  console.assert([1, 2, 3, 2, 1].indexOf(2) === 1, 'Array.prototype.indexOf');\n  console.assert([1, 2, 3, 2, 1].indexOf(4) === -1,\n      'Array.prototype.indexOf not found');\n  console.assert([1, 2, 3, 2, 1].indexOf(2, 2) === 3,\n      'Array.prototype.indexOf(..., +)');\n  console.assert([1, 2, 3, 2, 1].indexOf(1, -3) === 4,\n      'Array.prototype.indexOf(..., -)');\n  console.assert(['x', NaN, 'y'].indexOf(NaN) === -1,\n      'Array.prototype.indexOf NaN');\n\n  var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5};\n  console.assert(Array.prototype.indexOf.call(o, 2) === 1,\n      'Array.prototype.indexOf.call(array-like, ...)');\n};\n\ntests.ArrayPrototypeJoin = function() {\n  console.assert([1, 2, 3].join('-') === '1-2-3', 'Array.prototype.join');\n};\n\ntests.ArrayPrototypeLastIndexOf = function() {\n  console.assert([1, 2, 3, 2, 1].lastIndexOf(2) === 3,\n      'Array.prototype.lastIndexOf');\n  console.assert([1, 2, 3, 2, 1].lastIndexOf(4) === -1,\n      'Array.prototype.lastIndexOf not found');\n  console.assert([1, 2, 3, 2, 1].lastIndexOf(2, 2) === 1,\n      'Array.prototype.lastIndexOf(..., +)');\n  console.assert([1, 2, 3, 2, 1].lastIndexOf(1, -3) === 0,\n      'Array.prototype.lastIndexOf(..., -)');\n\n  var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5};\n  console.assert(Array.prototype.lastIndexOf.call(o, 2) === 3,\n      'Array.prototype.lastIndexOf.call(array-like, ...)');\n};\n\ntests.ArrayPrototypeJoinCycleDetection = function() {\n  var a = [1, , 3];\n  a[1] = a;\n  a.join('-');\n  // Didn't crash!\n  console.assert(true, 'Array.prototype.join cycle detection');\n};\n\ntests.ArrayPrototypePop = function() {\n  var a = ['foo', 'bar', 'baz'];\n  var r = a.pop();\n  console.assert(a.length === 2 && r === 'baz', 'Array.prototype.pop');\n\n  a = [];\n  r = a.pop();\n  console.assert(\n      a.length === 0 && r === undefined, 'Array.prototype.pop empty array');\n\n  var o = {0: 'foo', 1: 'bar', 2: 'baz', length: 3};\n  r = Array.prototype.pop.apply(o);\n  console.assert(\n      o.length === 2 && r === 'baz', 'Array.prototype.pop.apply(array-like)');\n\n  o = {length: 0};\n  r = Array.prototype.pop.apply(o);\n  console.assert(o.length === 0 && r === undefined,\n      'Array.prototype.pop.apply(empty array-like)');\n\n  o = {5000000000000000: 'foo',\n       5000000000000001: 'quux',\n       length: 5000000000000002};\n  r = Array.prototype.pop.apply(o);\n  console.assert(o.length === 5000000000000001 && o[5000000000000000] === 'foo',\n      'Array.prototype.pop.apply(huge array-like)');\n};\n\ntests.ArrayPrototypePush = function() {\n  var a = [];\n  console.assert(a.push('foo') === 1 && a.push('bar') === 2 &&\n      a.length === 2 && a[0] === 'foo' && a[1] === 'bar',\n      'Array.prototype.push');\n\n  var o = {length: 0};\n  console.assert(Array.prototype.push.call(o, 'foo') === 1 &&\n      Array.prototype.push.call(o, 'bar') === 2 &&\n      o.length === 2 && o[0] === 'foo' && o[1] === 'bar',\n      'Array.prototype.push.call(array-like, ...)');\n\n  var o = {length: 5000000000000000};\n  console.assert(Array.prototype.push.call(o, 'foo') === 5000000000000001 &&\n      Array.prototype.push.call(o, 'bar') === 5000000000000002 &&\n      o[5000000000000000] === 'foo' && o[5000000000000001] === 'bar' &&\n      o.length === 5000000000000002,\n      'Array.prototype.push.call(huge array-like, ...)');\n};\n\ntests.ArrayPrototypeReverse = function () {\n  var a = [1, 2, 3];\n  console.assert(a.reverse() === a && a.length === 3 && String(a) === '3,2,1',\n      'Array.prototype.reverse odd-length');\n\n  a = [1, 2, , 4];\n  console.assert(a.reverse() === a && a.length === 4 && String(a) === '4,,2,1',\n      'Array.prototype.reverse even-length');\n\n  a = [];\n  console.assert(a.reverse() === a && a.length === 0,\n      'Array.prototype.reverse empty');\n\n  var o = {0: 1, 1: 2, 2: 3, length: 3};\n  console.assert(Array.prototype.reverse.call(o) === o &&\n      o.length === 3 && Array.prototype.slice.apply(o).toString() === '3,2,1',\n      'Array.prototype.reverse.call(odd-length array-like)');\n\n  o = {0: 1, 1: 2, 3: 4, length: 4};\n  console.assert(Array.prototype.reverse.call(o) === o &&\n      o.length === 4 && Array.prototype.slice.apply(o).toString() === '4,,2,1',\n      'Array.prototype.reverse.call(even-length array-like)');\n\n  o = {length: 0};\n  console.assert(Array.prototype.reverse.call(o) === o && o.length === 0,\n      'Array.prototype.reverse.call(empty array-like)');\n};\n\ntests.ArrayPrototypeShift = function() {\n  var a = ['foo', 'bar', 'baz'];\n  var r = a.shift();\n  console.assert(a.length === 2 && a[0] === 'bar' && a[1] === 'baz' &&\n      r === 'foo', 'Array.prototype.shift');\n\n  a = [];\n  r = a.shift();\n  console.assert(\n      a.length === 0 && r === undefined, 'Array.prototype.shift empty array');\n\n  var o = {0: 'foo', 1: 'bar', 2: 'baz', length: 3};\n  r = Array.prototype.shift.apply(o);\n  console.assert(o.length === 2 && o[0] === 'bar' && o[1] === 'baz' &&\n      r === 'foo', 'Array.prototype.shift.apply(array-like)');\n\n  o = {length: 0};\n  r = Array.prototype.shift.apply(o);\n  console.assert(o.length === 0 && r === undefined,\n      'Array.prototype.shift.apply(empty array-like)');\n\n  // SKIP until more efficient shift implementation available.\n  console.log('SKIP:\\tArray.prototype.shift.apply(huge array-like)');\n  // o = {5000000000000000: 'foo',\n  //      5000000000000001: 'quux',\n  //      length: 5000000000000002};\n  // r = Array.prototype.shift.apply(o);\n  // console.assert(o.length === 5000000000000001 && o[5000000000000000] === 'quux',\n  //     'Array.prototype.shift.apply(huge array-like)');\n};\n\ntests.ArrayPrototypeSlice = function() {\n  var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n  var s = a.slice();\n  console.assert(a.length === 6 && s.length === 6 && String(s) === String(a),\n      'Array.prototype.slice()');\n\n  s = a.slice(-2);\n  console.assert(a.length === 6 && s.length === 2 && String(s) === 'quux,quuux',\n      'Array.prototype.slice(-)');\n\n  s = a.slice(1, 4);\n  console.assert(a.length === 6 && s.length === 3 && !('2' in s) &&\n      String(s) === 'bar,baz,', 'Array.prototype.slice(+, +)');\n\n  s = a.slice(1, -2);\n  console.assert(a.length === 6 && s.length === 3 && !('2' in s) &&\n      String(s) === 'bar,baz,', 'Array.prototype.slice(+, +)');\n\n  var o = {0: 'foo', 1: 'bar', 2: 'baz', 4: 'quux', 5: 'quuux', length: 6};\n  s = Array.prototype.slice.call(o, 1, -2);\n  console.assert(o.length === 6 && s.length === 3 && !('2' in s) &&\n      String(s) === 'bar,baz,', 'Array.prototype.slice.call(array-like, -, +)');\n\n  o = {\n    5000000000000000: 'foo', 5000000000000001: 'bar',\n    5000000000000002: 'baz', 5000000000000004: 'quux',\n    5000000000000005: 'quuux', length: 5000000000000006\n  };\n  s = Array.prototype.slice.call(o, -5, -2);\n  console.assert(o.length === 5000000000000006 &&\n      s.length === 3 && !('2' in s) && String(s) === 'bar,baz,',\n      'Array.prototype.slice.call(huge array-like, -, -)');\n};\n\ntests.ArrayPrototypeSort = function() {\n  console.assert([5, 2, 3, 1, 4].sort().join() === '1,2,3,4,5',\n      'Array.prototype.sort()');\n\n  // TODO(cpcallen):\n  console.assert(['z', undefined, 10, , 'aa', null, 'a', 5, NaN, , 1].sort()\n      .map(String).join() === '1,10,5,NaN,a,aa,null,z,undefined,,',\n      'Array.prototype.sort() compaction');\n  \n  console.assert([99, 9, 10, 11, 1, 0, 5].sort(function(a, b) {return a - b;})\n      .join() === '0,1,5,9,10,11,99',\n      'Array.prototype.sort(comparefn)');\n\n  // TODO(cpcallen):\n  console.assert(['z', undefined, 10, , 'aa', null, 'a', 5, NaN, , 1].sort(\n      function(a, b) {\n        // Try to put undefineds first - should not succeed.\n        if (a === undefined) return b === undefined ? 0 : -1;\n        if (b === undefined) return 1;\n        // Reverse order of ususal sort.\n        a = String(a);\n        b = String(b);\n        if (a > b) return -1;\n        if (b > a) return 1;\n        return 0;\n      }).map(String).join() === 'z,null,aa,a,NaN,5,10,1,undefined,,',\n      'Array.prototype.sort(comparefn) compaction');\n};\n\ntests.ArrayPrototypeSplice = function() {\n  var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n  var s = a.splice();\n  console.assert(a.length === 6 && String(a) === 'foo,bar,baz,,quux,quuux' &&\n      s.length === 0 && String(s) === '', 'Array.prototype.splice()');\n\n  a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n  s = a.splice(-2);\n  console.assert(a.length === 4 && String(a) === 'foo,bar,baz,' &&\n      s.length === 2 && String(s) === 'quux,quuux',\n      'Array.prototype.splice(-)');\n\n  a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n  s = a.splice(1, 3, 'bletch');\n  console.assert(a.length === 4 && String(a) === 'foo,bletch,quux,quuux' &&\n      s.length === 3 && String(s) === 'bar,baz,',\n      'Array.prototype.splice(+, +, ...)');\n\n  var o = {0: 'foo', 1: 'bar', 2: 'baz', 4: 'quux', 5: 'quuux', length: 6};\n  s = Array.prototype.splice.call(o, 0, 100, 'bletch');\n  console.assert(!Array.isArray(o) && o.length === 1 &&\n      Object.keys(o).length === 2 && o[0] === 'bletch' &&\n      s.length === 6 && !('3' in s) && String(s) === 'foo,bar,baz,,quux,quuux',\n      'Array.prototype.splice.call(array-like, 0, large, ...)');\n\n  o = {\n    5000000000000000: 'foo', 5000000000000001: 'bar',\n    5000000000000002: 'baz', 5000000000000004: 'quux',\n    5000000000000005: 'quuux', length: 5000000000000006\n  };\n  s = Array.prototype.splice.call(o, -2, -999, 'bletch', 'qux');\n  console.assert(!Array.isArray(o) && o.length === 5000000000000008 &&\n      o[5000000000000004] === 'bletch' && o[5000000000000005] === 'qux' &&\n      o[5000000000000006] === 'quux' && o[5000000000000007] === 'quuux' &&\n      Array.isArray(s) && s.length === 0,\n      'Array.prototype.splice.call(huge array-like, -, -)');\n};\n\ntests.ArrayPrototypeToStringCycleDetection = function() {\n  var a = [1, , 3];\n  a[1] = a;\n  a.toString();\n  // Didn't crash!\n  console.assert(true, 'Array.prototype.toString cycle detection');\n};\n\ntests.ArrayPrototypeUnshift = function() {\n  var a = [];\n  console.assert(a.unshift('foo') === 1 && a.unshift('bar') === 2 &&\n      a.length === 2 && a[0] === 'bar' && a[1] === 'foo',\n      'Array.prototype.unshift');\n\n  var o = {length: 0};\n  console.assert(Array.prototype.unshift.call(o, 'foo') === 1 &&\n      Array.prototype.unshift.call(o, 'bar') === 2 &&\n      o.length === 2 && o[0] === 'bar' && o[1] === 'foo',\n      'Array.prototype.unshift.call(array-like, ...)');\n\n  // SKIP until more efficient unshift implementation available.\n  console.log('SKIP:\\tArray.prototype.unshift.apply(huge array-like, ...)');\n  // var o = {length: 5000000000000000};\n  // console.assert(Array.prototype.unshift.call(o, 'foo') === 5000000000000001 &&\n  //     Array.prototype.unshift.call(o, 'bar') === 5000000000000002 &&\n  //     o[5000000000000000] === 'foo' && o[5000000000000001] === 'bar' &&\n  //     o.length === 5000000000000002,\n  //     'Array.prototype.unshift.call(huge array-like, ...)');\n};\n\ntests.ArrayLegalIndexLength = function() {\n  var cases = [\n    // [value, asIndex, asLength]\n    [false, 0, 0],\n    [true, 0, 1],\n\n    [0, 1, 0],\n    [1, 2, 1],\n    [0xfffffffe, 0xffffffff, 0xfffffffe],\n    [0xffffffff, 0, 0xffffffff],\n    [0x100000000, 0, NaN],\n    [4.5, 0, NaN],\n    [-1, 0, NaN],\n\n    ['0', 1, 0],\n    ['1', 2, 1],\n    ['0xfffffffe', 0, 0xfffffffe],\n    ['0xffffffff', 0, 0xffffffff],\n    ['0x100000000', 0, NaN],\n    ['4294967294', 4294967295, 0xfffffffe],\n    ['4294967295', 0, 0xffffffff],\n    ['4294967296', 0, NaN],\n    ['4.5', 0, NaN],\n    ['-1', 0, NaN],\n\n    ['hello', 0, NaN],\n    [null, 0, 0],  // wat\n    [undefined, 0, NaN],\n    [[], 0, 0],  // wat!\n    [{}, 0, NaN],\n  ];\n  for (var i = 0, tc; (tc = cases[i]); i++) {\n    var a = [];\n    a[tc[0]] = true;\n    console.assert(a.length === tc[1],\n                   'Array legal index ' + JSON.stringify(tc[0]));\n    var a = [];\n    try {\n      a.length = tc[0];\n      if (isNaN(tc[2])) {\n        console.assert(false,\n            \"Array illegal .length didn't throw \" + JSON.stringify(tc[0]));\n      }\n    } catch (e) {\n      console.assert(e.name === 'RangeError',\n           'Array illegal .length wrong error ' + JSON.stringify(tc[0]));\n    }\n  }\n};\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Boolean and Boolean.prototype\n\ntests.Boolean = function() {\n  console.assert(Boolean(undefined) === false, 'Boolean undefined');\n  console.assert(Boolean(null) === false, 'Boolean null');\n  console.assert(Boolean(false) === false, 'Boolean false');\n  console.assert(Boolean(true) === true, 'Boolean true');\n  console.assert(Boolean(NaN) === false, 'Boolean NaN');\n  console.assert(Boolean(0) === false, 'Boolean 0');\n  console.assert(Boolean(1) === true, 'Boolean 1');\n  console.assert(Boolean('') === false, 'Boolean empty string');\n  console.assert(Boolean('foo') === true, 'Boolean non-empty string');\n  console.assert(Boolean({}) === true, 'Boolean object');\n  console.assert(Boolean([]) === true, 'Boolean array');\n  console.assert(Boolean(function() {}) === true, 'Boolean function');\n};\n\ntests.BooleanPrototypeToString = function () {\n  console.assert(Boolean.prototype.toString() === 'false',\n      'Boolean.prototype.toString()');\n  console.assert(Boolean.prototype.toString.call(true) === 'true',\n      'Boolean.prototype.toString.call(true)');\n  console.assert(Boolean.prototype.toString.call(false) === 'false',\n                 'Boolean.prototype.toString.call(false)');\n  try {\n    Boolean.prototype.toString.call({});\n    console.assert(false, \"Boolean.prototype.toString.call({}) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Boolean.prototype.toString.call({}) wrong error');\n  }\n};\n\ntests.BooleanPrototypeValueOf = function () {\n  console.assert(Boolean.prototype.valueOf() === false,\n      'Boolean.prototype.valueOf()');\n  console.assert(Boolean.prototype.valueOf.call(true) === true,\n      'Boolean.prototype.valueOf.call(true)');\n  console.assert(Boolean.prototype.valueOf.call(false) === false,\n                 'Boolean.prototype.valueOf.call(false)');\n  try {\n    Boolean.prototype.valueOf.call({});\n    console.assert(false, \"Boolean.prototype.valueOf.call({}) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Boolean.prototype.valueOf.call({}) wrong error');\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Number and Number.prototype\n\ntests.Number = function() {\n  console.assert(Number() === 0, 'Number()');\n  console.assert(isNaN(Number(undefined)), 'Number undefined');\n  console.assert(Number(null) === 0, 'Number null');\n  console.assert(Number(true) === 1, 'Number true');\n  console.assert(Number(false) === 0, 'Number false');\n  console.assert(Number('42') === 42, \"Number '42'\");\n  console.assert(isNaN(Number('Hello')), 'Number non-empty string');\n  console.assert(Number('') === 0, 'Number empty string');\n  console.assert(Number(3.1) === 3.1, 'Number number');\n  console.assert(isNaN(Number({})), 'Number object');\n  console.assert(Number([]) === 0, 'Number []');\n  console.assert(Number([42]) === 42, 'Number [42]');\n  console.assert(isNaN(Number([1,2,3])), 'Number [1,2,3]');\n  console.assert(isNaN(Number(function() {})), 'Number function');\n  console.assert(isNaN(Number.NaN), 'Number NaN');\n  console.assert(!isFinite(Number.POSITIVE_INFINITY), 'Number  +Infinity');\n  console.assert(!isFinite(Number.NEGATIVE_INFINITY), 'Number  -Infinity');\n  console.assert(Number.POSITIVE_INFINITY === -Number.NEGATIVE_INFINITY,\n      'Number infinities');\n};\n\ntests.NumberPrototypeToString = function () {\n  console.assert(Number.prototype.toString() === '0',\n      'Number.prototype.toString()');\n  console.assert(Number.prototype.toString.call(84) === '84',\n      'Number.prototype.toString.call(85)');\n  try {\n    Number.prototype.toString.call({});\n    console.assert(false, \"Number.prototype.toString.call({}) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Number.prototype.toString.call({}) wrong error');\n  }\n};\n\n// Run some tests of Number.toString(radix) with various different\n// radix arguments.\ntests.NumberPrototypeToStringRadix = function() {\n  var cases = [\n    [42, , '42'],\n    [42, 16, '2a'],\n    // Old versions of Node incorrectly reports '-132.144444'.\n    [-42.4, 5, '-132.2'],\n    [42, '2', '101010'],\n    [-3.14, , '-3.14'],\n    [999999999999999999999999999, undefined, '1e+27'],\n    [NaN, undefined, 'NaN'],\n    [Infinity, , 'Infinity'],\n    [-Infinity, , '-Infinity'],\n  ];\n  for (var i = 0, tc; (tc = cases[i]); i++) {\n    console.assert(Number.prototype.toString.call(tc[0], tc[1]) === tc[2],\n        'Number.prototype.toString.call(' + tc[0] + ', ' + tc[1] + ')');\n  }\n};\n\ntests.NumberPrototypeValueOf = function () {\n  console.assert(Number.prototype.valueOf() === 0,\n      'Number.prototype.valueOf()');\n  console.assert(Number.prototype.valueOf.call(85) === 85,\n      'Number.prototype.valueOf.call(85)');\n  try {\n    Number.prototype.valueOf.call({});\n    console.assert(false, \"Number.prototype.valueOf.call({}) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Number.prototype.valueOf.call({}) wrong error');\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// String and String.prototype\n\ntests.String = function() {\n  console.assert(String() === '', 'String()');\n  console.assert(String(undefined) === 'undefined', 'String undefined');\n  console.assert(String(null) === 'null', 'String null');\n  console.assert(String(true) === 'true', 'String true');\n  console.assert(String(false) === 'false', 'String false');\n  console.assert(String(0) === '0', 'String 0');\n  console.assert(String(-0) === '0', 'String -0');\n  console.assert(String(Infinity) === 'Infinity', 'String +Infinity');\n  console.assert(String(-Infinity) === '-Infinity', 'String -Infinity');\n  console.assert(String(NaN) === 'NaN', 'String NaN');\n  console.assert(String({}) === '[object Object]', 'String object');\n  console.assert(String([1, 2, 3,,5]) === '1,2,3,,5', 'String array');\n};\n\ntests.StringPrototypeLength = function() {\n  console.assert(String.prototype.length === 0, 'String.prototype.length');\n};\n\ntests.StringPrototypeReplaceStringString = function() {\n  console.assert('xxxx'.replace('xx', 'y') === 'yxx',\n      'String.prototype.replace(string, string)');\n};\n\ntests.StringPrototypeReplaceRegExpString = function() {\n  console.assert('xxxx'.replace(/(X)\\1/ig, 'y') === 'yy',\n      'String.prototype.replace(regexp, string)');\n};\n\ntests.StringPrototypeReplaceStringFunction = function() {\n  var str = 'xxxx'.replace('xx', function () {\n      return '[' + Array.prototype.join.apply(arguments) + ']';\n  });\n  console.assert(str === '[xx,0,xxxx]xx',\n      'String.prototype.replace(string, function)');\n};\n\ntests.StringPrototypeReplaceRegExpFunction = function() {\n  var str = 'xxxx'.replace(/(X)\\1/ig, function () {\n      return '[' + Array.prototype.join.apply(arguments) + ']';\n  });\n  console.assert(str === '[xx,x,0,xxxx][xx,x,2,xxxx]',\n      'String.prototype.replace(regexp, function)');\n};\n\ntests.StringPrototypeSearch = function() {\n  console.assert('hello'.search('H') === -1,\n      'String.prototype.search(string) not found');\n  console.assert('hello'.search('ll') === 2,\n      'String.prototype.search(string) found');\n  console.assert('hello'.search(/H/) === -1,\n      'String.prototype.search(regexp) not found');\n  console.assert('hello'.search(/(.)\\1/) === 2,\n      'String.prototype.search(regexp) found');\n};\n\ntests.StringPrototypeToString = function () {\n  console.assert(String.prototype.toString() === '',\n      'String.prototype.toString()');\n  console.assert(String.prototype.toString.call('a string') === 'a string',\n      \"String.prototype.toString.call('a string')\");\n  try {\n    String.prototype.toString.call({});\n    console.assert(false, \"String.prototype.toString.call({}) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'String.prototype.toString.call({}) wrong error');\n  }\n};\n\ntests.StringPrototypeValueOf = function () {\n  console.assert(String.prototype.valueOf() === '',\n      'String.prototype.valueOf()');\n  console.assert(String.prototype.valueOf.call('a string') === 'a string',\n      \"String.prototype.valueOf.call('a string')\");\n  try {\n    String.prototype.valueOf.call({});\n    console.assert(false, \"String.prototype.valueOf.call({}) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'String.prototype.valueOf.call({}) wrong error');\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// RegExp\n\ntests.RegExpPrototypeTestApplyNonRegExpThrows = function() {\n  try {\n    /foo/.test.apply({}, ['foo']);\n    console.assert(\n        false, \"RegExp.prototype.test.apply(non-regexp) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'RegExp.prototype.test.apply(non-regexp) wrong error');\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// JSON\n\ntests.JsonStringify = function () {\n  var obj = {string: 'foo', number: 42, true: true, false: false, null: null,\n       object: { obj: {}, arr: [] }, array: [{}, []] };\n  var str = '{\"string\":\"foo\",\"number\":42,\"true\":true,\"false\":false,' +\n      '\"null\":null,\"object\":{\"obj\":{},\"arr\":[]},\"array\":[{},[]]}';\n  console.assert(JSON.stringify(obj) === str, 'JSON.stringify basic');\n\n  console.assert(JSON.stringify(function(){}) === undefined,\n      'JSON.stringify(function(){})');\n\n  console.assert(JSON.stringify([function(){}]) === '[null]',\n      'JSON.stringify([function(){}])');\n\n  console.assert(JSON.stringify({f: function(){}}) === '{}',\n      'JSON.stringify({f: function(){}})');\n\n  str = '{\"string\":\"foo\",\"number\":42}';\n  console.assert(JSON.stringify(obj, ['string', 'number']) === str,\n      'JSON.stringify filter');\n\n  str = '{\\n  \"string\": \"foo\",\\n  \"number\": 42\\n}';\n  console.assert(JSON.stringify(obj, ['string', 'number'], 2) === str,\n      'JSON.stringify pretty number');\n\n  str = '{\\n--\"string\": \"foo\",\\n--\"number\": 42\\n}';\n  console.assert(JSON.stringify(obj, ['string', 'number'], '--') === str,\n      'JSON.stringify pretty string');\n\n  obj = {e: 'enumerable', ne: 'nonenumerable'};\n  Object.defineProperty(obj, 'ne', {enumerable: false});\n  console.assert(JSON.stringify(obj) === '{\"e\":\"enumerable\"}',\n      'JSON.stringify nonenumerable');\n\n  console.assert(JSON.stringify(Object.create({foo: 'bar'})) === '{}',\n      'JSON.stringify inherited');\n\n  obj = {};\n  obj.circular = obj;\n  try {\n    JSON.stringify(obj);\n    console.assert(false, \"JSON.stringify didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError', 'JSON.stringify wrong error');\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Other built-in functions\n\ntests.decodeUriThrows = function() {\n  try {\n    decodeURI('%xy');\n    console.assert(false, \"decodeURI(invalid-URI) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'URIError', 'decodeURI(invalid-URI) wrong error');\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Other tests\n\ntests.newHack = function() {\n  console.assert(\n      (new 'Array.prototype.push') === Array.prototype.push, 'new hack');\n};\n\ntests.newHackUnknown = function() {\n  try {\n    new 'nonexistent-builtin-name';\n    console.assert(false, \"new hack with unknown built-in didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'ReferenceError',\n        'new hack with unknown built-in wrong error');\n  }\n};\n\ntests.newHacknNonLiteral = function() {\n  try {\n    var builtin = 'Object.prototype';\n    new builtin;\n    console.assert(false, \"new hack with non-literal didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'new hack with non-literal wrong error');\n  }\n};\n\ntests.es6CausesSyntaxErrors = function() {\n  var tests = [\n    // Class statements & expressions\n    'class Foo{};',\n    'false && class Foo{};',\n     // Arrow functions.\n    'false && [].map((item) => String(item));',\n     // For-of statement.\n    'for (var x of [1, 2, 3]) {};',\n     // Let & const.\n    'let x;',\n    'const x;',\n  ];\n  for (var i = 0; i < tests.length; i++) {\n    var src = tests[i];\n    try {\n      eval(tests[i]);\n      console.assert(false, \"es5 didn't throw for: \" + src);\n    } catch (e) {\n      console.assert(e.name === 'SyntaxError',\n          'es5 threw wrong error for: ' + src);\n    }\n  }\n};\n\ntests.strictModeSyntaxErrors = function() {\n  var tests = [\n    // With statement.\n    'var o = { foo: 42 }; var f = function() { with (o) { foo; }};',\n\n    // Binding eval in global scope, or arguments in a function.\n    'var eval = \"rebinding eval?!?\";',\n    '(function() { arguments = undefined; });',\n\n    // Duplicate argument names.\n    '(function(a, a) {});',\n\n    // Octal numeric literals.\n    '0777;',\n\n    // Delete of unqualified or undeclared identifier.\n    'var foo; delete foo;',\n    'delete foo;',\n  ];\n  for (var i = 0; i < tests.length; i++) {\n    var src = tests[i];\n    try {\n      eval(tests[i]);\n      console.assert(false, \"strict mode didn't throw for: \" + src);\n    } catch (e) {\n      console.assert(e.name === 'SyntaxError',\n          'strict mode wrong error for: ' + src);\n    }\n  }\n};\n"
  },
  {
    "path": "server/tests/db/test_01_es6.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test the ES6 functions of the server.\n * @author fraser@google.com (Neil Fraser)\n */\n\n// Test automatic setting of function .name properties.\ntests.functionNameSetting = function() {\n  var myAssignedFunc;\n  myAssignedFunc = function() {};\n  console.assert(myAssignedFunc.name === 'myAssignedFunc',\n      'Assignment expression sets anonymous function name');\n\n  var o = {myPropFunc: function() {}};\n  console.assert(o.myPropFunc.name === 'myPropFunc',\n      'Object expression sets anonymous function name');\n\n  var myVarDeclFunc = function() {};\n  console.assert(myVarDeclFunc.name === 'myVarDeclFunc',\n      'Variable declaration sets anonymous function name');\n};\n\n// Run some tests of the various constructors and their associated\n// literals and prototype objects.\ntests.builtinClassesES6 = function() {\n  var classes = [\n    {\n      constructor: WeakMap,\n      classStr: '[object WeakMap]',\n      prototypeClass: '[object Object]',\n      functionNotConstructor: true  // WeakMap() can't be called without new.\n    },\n  ];\n  for (var i = 0, tc; (tc = classes[i]); i++) {\n    var c = tc.constructor;\n    var prototypeType = (tc.prototypeType || 'object');\n    // Check constructor is a function:\n    console.assert(typeof c === 'function', c + ' isFunction');\n    // Check constructor's proto is Function.prototype\n    console.assert(Object.getPrototypeOf(c) === Function.prototype,\n        c + ' protoIsFunctionPrototype');\n    // Check prototype is of correct type:\n    console.assert(typeof c.prototype === prototypeType,\n        c + ' prototypeIs');\n    // Check prototype has correct class:\n    console.assert(\n        Object.prototype.toString.apply(c.prototype) ===\n        tc.prototypeClass || tc.classStr,\n        c + ' prototypeClassIs');\n    // Check prototype has correct proto:\n    console.assert(\n        Object.getPrototypeOf(c.prototype) ===\n        (tc.prototypeProto === undefined ? Object.prototype : tc.prototypeProto),\n        c + ' prototypeProtoIs');\n    // Check prototype's .constructor is constructor:\n    console.assert(c.prototype.constructor === c,\n        c + ' prototypeConstructorIs');\n\n    if (!tc.noInstance) {\n      // Check instance's type:\n      console.assert(typeof new c === prototypeType, c + ' instanceIs');\n      // Check instance's proto:\n      console.assert(Object.getPrototypeOf(new c) === c.prototype,\n          c + ' instancePrototypeIs');\n      // Check instance's class:\n      console.assert(Object.prototype.toString.apply(new c) === tc.classStr,\n          c + ' instanceClassIs');\n      // Check instance is instanceof its contructor:\n      console.assert((new c) instanceof c, c + ' instanceIsInstanceof');\n      if (!tc.functionNotConstructor) {\n        // Recheck instances when constructor called as function:\n        // Recheck instance's type:\n        console.assert(typeof c() === prototypeType, c + ' returnIs');\n        // Recheck instance's proto:\n        console.assert(Object.getPrototypeOf(c()) === c.prototype,\n            c + ' returnPrototypeIs');\n        // Recheck instance's class:\n        console.assert(Object.prototype.toString.apply(c()) === tc.classStr,\n            c + ' returnClassIs');\n        // Recheck instance is instanceof its contructor:\n        console.assert(c() instanceof c, c + ' returnIsInstanceof');\n      }\n    }\n    // No need to check literals.\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Object and Object.prototype\n\ntests.ObjectSetPrototypeOfNullUndefined = function() {\n  try {\n    Object.setPrototypeOf(null, null);\n    console.assert(false, \"Object.setPrototypeOf(null, ...) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.setPrototypeOf(null, ...) wrong error');\n  }\n  try {\n    Object.setPrototypeOf(undefined, null);\n    console.assert(false, \"Object.setPrototypeOf(undefined, ...) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.setPrototypeOf(undefined, ...) wrong error');\n  }\n};\n\ntests.ObjectSetPrototypeOfPrimitives = function() {\n  console.assert(Object.setPrototypeOf(true, null) === true,\n      'Object.setPrototypeOf boolean');\n  console.assert(Object.setPrototypeOf(1337, null) === 1337,\n      'Object.setPrototypeOf number');\n  console.assert(Object.setPrototypeOf('hi', null) === 'hi',\n      'Object.setPrototypeOf string');\n};\n\ntests.ObjectSetPrototypeOf = function() {\n  var o = {parent: 'o'};\n  var p = {parent: 'p'};\n  var q = Object.create(o);\n  console.assert(Object.setPrototypeOf(q, p) === q,\n      'Object.setPrototypeOf(q, p) return value');\n  console.assert(Object.getPrototypeOf(q) === p,\n      'Object.setPrototypeOf(q, p) new parent');\n  console.assert(q.parent === 'p',\n      'Object.setPrototypeOf(q, p) inheritance');\n};\n\ntests.ObjectSetPrototypeOfToNull = function() {\n  var o = {parent: 'o'};\n  var q = Object.create(o);\n  console.assert(Object.setPrototypeOf(q, null) === q,\n      'Object.setPrototypeOf(q, null) return value');\n  console.assert(Object.getPrototypeOf(q) === null,\n      'Object.setPrototypeOf(q, null) new parent');\n};\n\ntests.ObjectSetPrototypeOfCircular = function() {\n  var o = {};\n  var p = Object.create(o);\n  try {\n    Object.setPrototypeOf(o, p);\n    console.assert(false, \"Object.setPrototypeOf(o, p) didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Object.setPrototypeOf(o, p) wrong error');\n  }\n};\n\ntests.ObjectIs = function() {\n  console.assert(Object.is('foo', 'foo'), 'equal strings');\n  console.assert(Object.is(Array, Array), 'equal objects');\n\n  console.assert(!Object.is('foo', 'bar'), 'unequal strings');\n  console.assert(!Object.is([], []), 'unequal objects');\n\n  var test = {a: 1};\n  console.assert(Object.is(test, test), 'custom object');\n\n  console.assert(Object.is(null, null), 'null');\n\n  console.assert(!Object.is(0, -0), 'unequal zero');\n  console.assert(Object.is(-0, -0), 'negative zero');\n  console.assert(Object.is(NaN, 0/0), 'NaN');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Function and Function.prototype\n\ntests.FunctionPrototypeBindClassConstructor = function() {\n  var f = WeakMap.bind();\n  try {\n    f();\n    console.assert(false, \"Calling bound class constructor didn't throw\");\n  } catch (e) {\n    console.assert(e.name === 'TypeError',\n        'Calling bound class constructor threw wrong error');\n  }\n}\n\ntests.FunctionPrototypeBindClassConstructorNew = function() {\n  console.assert(String(new (WeakMap.bind())) === '[object WeakMap]',\n      'FunctionPrototypeBindClassConstructorNew');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Array and Array.prototype\n\ntests.ArrayFind = function() {\n  var inventory = [\n      {name: 'apples', quantity: 2},\n      {name: 'bananas', quantity: 0},\n      {name: 'cherries', quantity: 5}\n  ];\n  function isCherries(fruit) {\n    return fruit.name === 'cherries';\n  }\n  console.assert([].find(isCherries) === undefined, 'Array.find 0');\n  console.assert(inventory.find(isCherries) === inventory[2], 'Array.find 1');\n};\n\ntests.ArrayFindIndex = function() {\n  var inventory = [\n      {name: 'apples', quantity: 2},\n      {name: 'bananas', quantity: 0},\n      {name: 'cherries', quantity: 5}\n  ];\n  function isCherries(fruit) {\n    return fruit.name === 'cherries';\n  }\n  console.assert([].findIndex(isCherries) === -1, 'Array.findIndex 0');\n  console.assert(inventory.findIndex(isCherries) === 2, 'Array.findIndex 1');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// String and String.prototype\n\ntests.StringBooleanSearchFunctions = function() {\n  var str = 'To be, or not to be, that is the question.';\n\n  console.assert(str.includes('To be'), 'Includes \"To be\"');\n  console.assert(str.includes('question'), 'Includes \"question\"');\n  console.assert(!str.includes('nonexistent'), 'Includes \"nonexistent\"');\n  console.assert(!str.includes('To be', 1), 'Includes \"To be\" (1)');\n  console.assert(!str.includes('TO BE'), 'Includes \"TO BE\"');\n\n  console.assert(str.startsWith('To be'), 'StartsWith \"To be\"');\n  console.assert(!str.startsWith('not to be'), 'StartsWith \"not to be\"');\n  console.assert(str.startsWith('not to be', 10), 'StartsWith \"not to be\" (10)');\n\n  console.assert(str.endsWith('question.'), 'EndsWith \"question.\"');\n  console.assert(!str.endsWith('to be'), 'EndsWith \"to be\"');\n  console.assert(str.endsWith('to be', 19), 'EndsWith \"to be\" (19)');\n};\n\ntests.StringRepeat = function() {\n  try {\n    'abc'.repeat(-1);\n    console.assert(false, 'Repeat Negative');\n  } catch (e) {\n    console.assert(e.name === 'RangeError',\n                   'Repeat Negative Error');\n  }\n  console.assert('abc'.repeat(0) === '', 'Repeat 0');\n  console.assert('abc'.repeat(1) === 'abc', 'Repeat 1');\n  console.assert('abc'.repeat(2) === 'abcabc', 'Repeat 2');\n  console.assert('abc'.repeat(3.5) === 'abcabcabc', 'Repeat 3.5');\n  try {\n    'abc'.repeat(1 / 0);\n    console.assert(false, 'RegExpPrototypeTestApplyNonRegExpThrows');\n  } catch (e) {\n    console.assert(e.name === 'RangeError',\n                   'RegExpPrototypeTestApplyNonRegExpThrowsError');\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Number\n\ntests.NumberEpsilon = function() {\n  console.assert(Number.EPSILON > 0, 'Epsilon > zero');\n  console.assert(Number.EPSILON < 0.001, 'Epsilon < 0.001');\n};\n\ntests.NumberIsFinite = function() {\n  console.assert(!Number.isFinite(Infinity), 'Number.isFinite Infinity');\n  console.assert(!Number.isFinite(NaN), 'Number.isFinite NaN');\n  console.assert(!Number.isFinite(-Infinity), 'Number.isFinite -Infinity');\n  console.assert(Number.isFinite(0), 'Number.isFinite 0');\n  console.assert(Number.isFinite(2e64), 'Number.isFinite 2e64');\n  console.assert(!Number.isFinite('0'), 'Number.isFinite \"0\"');\n  console.assert(!Number.isFinite(null), 'Number.isFinite null');\n};\n\ntests.NumberIsNaN = function() {\n  console.assert(Number.isNaN(NaN), 'Number.isNaN NaN');\n  console.assert(Number.isNaN(Number.NaN), 'Number.isNaN Number.NaN');\n  console.assert(Number.isNaN(0 / 0), 'Number.isNaN 0 / 0');\n  console.assert(!Number.isNaN('NaN'), 'Number.isNaN \"NaN\"');\n  console.assert(!Number.isNaN(undefined), 'Number.isNaN undefined');\n  console.assert(!Number.isNaN({}), 'Number.isNaN {}');\n  console.assert(!Number.isNaN('blabla'), 'Number.isNaN \"blabla\"');\n  console.assert(!Number.isNaN(true), 'Number.isNaN true');\n  console.assert(!Number.isNaN(null), 'Number.isNaN null');\n  console.assert(!Number.isNaN(37), 'Number.isNaN 37');\n  console.assert(!Number.isNaN('37'), 'Number.isNaN \"37\"');\n  console.assert(!Number.isNaN('37.37'), 'Number.isNaN \"37.37\"');\n  console.assert(!Number.isNaN(''), 'Number.isNaN \"\"');\n  console.assert(!Number.isNaN(' '), 'Number.isNaN \" \"');\n};\n\ntests.NumberIsInteger = function() {\n  console.assert(Number.isInteger(-17), 'Number.isInteger -17');\n  console.assert(Number.isInteger(Math.pow(2, 64)), 'Number.isInteger 2**64');\n  console.assert(Number.isInteger(-Math.pow(2, 64)), 'Number.isInteger -2**64');\n  console.assert(!Number.isInteger(NaN), 'Number.isInteger NaN');\n  console.assert(!Number.isInteger(Infinity), 'Number.isInteger Infinity');\n  console.assert(!Number.isInteger('3'), 'Number.isInteger \"3\"');\n  console.assert(!Number.isInteger(3.1), 'Number.isInteger 3.1');\n  console.assert(Number.isInteger(3.0), 'Number.isInteger 3.0');\n};\n\ntests.NumberIsSafeInteger = function() {\n  console.assert(Number.isSafeInteger(3), 'Number.isSafeInteger 3');\n  console.assert(!Number.isSafeInteger(Math.pow(2, 53)), 'Number.isSafeInteger 2**53');\n  console.assert(Number.isSafeInteger(Math.pow(2, 53) - 1), 'Number.isSafeInteger 2**53-1');\n  console.assert(!Number.isSafeInteger(NaN), 'Number.isSafeInteger NaN');\n  console.assert(!Number.isSafeInteger(Infinity), 'Number.isSafeInteger Infinity');\n  console.assert(!Number.isSafeInteger('3'), 'Number.isSafeInteger \"3\"');\n  console.assert(!Number.isSafeInteger(3.1), 'Number.isSafeInteger 3.1');\n  console.assert(Number.isSafeInteger(3.0), 'Number.isSafeInteger 3.0');\n};\n\ntests.NumberMaxSafeInteger = function() {\n  console.assert(Number.MAX_SAFE_INTEGER + 1 === Math.pow(2, 53),\n      'Number.MAX_SAFE_INTEGER');\n  console.assert(Number.isSafeInteger(Number.MAX_SAFE_INTEGER),\n      'Number.isSafeInteger(Number.MAX_SAFE_INTEGER);');\n  console.assert(!Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1),\n      'Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1);');\n};\n\ntests.NumberMinSafeInteger = function() {\n  console.assert(Number.MIN_SAFE_INTEGER === -(Math.pow(2, 53) - 1),\n      'Number.MIN_SAFE_INTEGER');\n  console.assert(Number.isSafeInteger(Number.MIN_SAFE_INTEGER),\n      'Number.isSafeInteger(Number.MIN_SAFE_INTEGER);');\n  console.assert(!Number.isSafeInteger(Number.MIN_SAFE_INTEGER - 1),\n      'Number.isSafeInteger(Number.MIN_SAFE_INTEGER - 1);');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Math\n\ntests.MathAcosh = function() {\n  console.assert(Number.isNaN(Math.acosh(-1)), 'Math.acosh -1');\n  console.assert(Number.isNaN(Math.acosh(0)), 'Math.acosh 0');\n  console.assert(Number.isNaN(Math.acosh(0.5)), 'Math.acosh 0.5');\n  console.assert(Math.acosh(1) === 0, 'Math.acosh 1');\n  console.assert(Math.acosh(2).toPrecision(10) === '1.316957897', 'Math.acosh 2');\n};\n\ntests.MathAsinh = function() {\n  console.assert(Math.asinh(1).toPrecision(10) === '0.8813735870', 'Math.asinh 1');\n  console.assert(Math.asinh(0) === 0, 'Math.asinh 0');\n};\n\ntests.MathAtanh = function() {\n  console.assert(Number.isNaN(Math.atanh(-2)), 'Math.atanh -2');\n  console.assert(Math.atanh(-1) === -Infinity, 'Math.atanh -1');\n  console.assert(Math.atanh(0) === 0, 'Math.atanh 0');\n  console.assert(Math.atanh(0.5).toPrecision(10) === '0.5493061443', 'Math.atanh 0.5');\n  console.assert(Math.atanh(1) === Infinity, 'Math.atanh 1');\n  console.assert(Number.isNaN(Math.atanh(2)), 'Math.atanh 2');\n};\n\ntests.MathCbrt = function() {\n  console.assert(Number.isNaN(Math.cbrt(NaN)), 'Math.cbrt NaN');\n  console.assert(Math.cbrt(-1) === -1, 'Math.cbrt -1');\n  console.assert(Object.is(Math.cbrt(-0), -0), 'Math.cbrt -0');\n  console.assert(Math.cbrt(-Infinity) === -Infinity, 'Math.cbrt -Infinity');\n  console.assert(Object.is(Math.cbrt(0), 0), 'Math.cbrt 0');\n  console.assert(Math.cbrt(1) === 1, 'Math.cbrt 1');\n  console.assert(Math.cbrt(Infinity) === Infinity, 'Math.cbrt Infinity');\n  console.assert(Math.cbrt(null) === 0, 'Math.cbrt null');\n  console.assert(Math.cbrt(2).toPrecision(10) === '1.259921050', 'Math.cbrt 2');\n};\n\ntests.MathClz32 = function() {\n  console.assert(Math.clz32(1) === 31, 'Math.clz32 1');\n  console.assert(Math.clz32(1000) === 22, 'Math.clz32 1000');\n  console.assert(Math.clz32() === 32, 'Math.clz32 ()');\n  console.assert(Math.clz32(NaN) === 32, 'Math.clz32 NaN');\n  console.assert(Math.clz32(Infinity) === 32, 'Math.clz32 Infinity');\n  console.assert(Math.clz32(-Infinity) === 32, 'Math.clz32 -Infinity');\n  console.assert(Math.clz32(0) === 32, 'Math.clz32 0');\n  console.assert(Math.clz32(-0) === 32, 'Math.clz32 -0');\n  console.assert(Math.clz32(null) === 32, 'Math.clz32 null');\n  console.assert(Math.clz32(undefined) === 32, 'Math.clz32 undefined');\n  console.assert(Math.clz32('foo') === 32, 'Math.clz32 \"foo\"');\n  console.assert(Math.clz32({}) === 32, 'Math.clz32 {}');\n  console.assert(Math.clz32([]) === 32, 'Math.clz32 []');\n  console.assert(Math.clz32(true) === 31, 'Math.clz32 true');\n  console.assert(Math.clz32(3.5) === 30, 'Math.clz32 3.5');\n};\n\ntests.MathCosh = function() {\n  console.assert(Math.cosh(-1).toPrecision(10) === '1.543080635', 'Math.cosh -1');\n  console.assert(Math.cosh(0) === 1, 'Math.cosh 0');\n  console.assert(Math.cosh(1).toPrecision(10) === '1.543080635', 'Math.cosh 1');\n};\n\ntests.MathExpm1 = function() {\n  console.assert(Math.expm1(-1).toPrecision(10) === '-0.6321205588', 'Math.expm1 -1');\n  console.assert(Math.expm1(0) === 0, 'Math.expm1 0');\n  console.assert(Math.expm1(1).toPrecision(10) === '1.718281828', 'Math.expm1 1');\n};\n\ntests.MathFround = function() {\n  console.assert(Math.fround(1.5) === 1.5, 'Math.fround 1.5');\n  console.assert(Math.fround(1.337).toPrecision(10) === '1.337000012', 'Math.fround 1.337');\n  console.assert(Math.fround(Math.pow(2, 150)) === Infinity, 'Math.fround 2**150');\n  console.assert(Number.isNaN(Math.fround('abc')), 'Math.fround \"abc\"');\n  console.assert(Number.isNaN(Math.fround(NaN)), 'Math.fround NaN');\n};\n\ntests.MathHypot = function() {\n  console.assert(Math.hypot(3, 4) === 5, 'Math.hypot 3, 4');\n  console.assert(Math.hypot(3, 4, 5).toPrecision(10) === '7.071067812', 'Math.hypot 3, 4, 5');\n  console.assert(Math.hypot() === 0, 'Math.hypot ()');\n  console.assert(Number.isNaN(Math.hypot(NaN)), 'Math.hypot NaN');\n  console.assert(Number.isNaN(Math.hypot(3, 4, 'foo')), 'Math.hypot 3, 4, \"foo\"');\n  console.assert(Math.hypot(3, 4, '5').toPrecision(10) === '7.071067812', 'Math.hypot 3, 4, \"5\"');\n  console.assert(Math.hypot(-3) === 3, 'Math.hypot -3');\n};\n\ntests.MathImul = function() {\n  console.assert(Math.imul(2, 4) === 8, 'Math.imul 2, 4');\n  console.assert(Math.imul(-1, 8) === -8, 'Math.imul -1, 8');\n  console.assert(Math.imul(-2, -2) === 4, 'Math.imul -2, -2');\n  console.assert(Math.imul(0xffffffff, 5) === -5, 'Math.imul 0xffffffff, 5');\n  console.assert(Math.imul(0xfffffffe, 5) === -10, 'Math.imul 0xfffffffe, 5');\n};\n\ntests.MathLog10 = function() {\n  console.assert(Math.log10(2).toPrecision(10) === '0.3010299957', 'Math.log10 2');\n  console.assert(Math.log10(1) === 0, 'Math.log10 1');\n  console.assert(Math.log10(0) === -Infinity, 'Math.log10 0');\n  console.assert(Number.isNaN(Math.log10(-2)), 'Math.log10 -2');\n  console.assert(Math.log10(100000) === 5, 'Math.log10 100000');\n};\n\ntests.MathLog1p = function() {\n  console.assert(Math.log1p(1).toPrecision(10) === '0.6931471806', 'Math.log1p 1');\n  console.assert(Math.log1p(0) === 0, 'Math.log1p 0');\n  console.assert(Math.log1p(-1) === -Infinity, 'Math.log1p -1');\n  console.assert(Number.isNaN(Math.log1p(-2)), 'Math.log1p -2');\n};\n\ntests.MathLog2 = function() {\n  console.assert(Math.log2(3).toPrecision(10) === '1.584962501', 'Math.log2 3');\n  console.assert(Math.log2(2) === 1, 'Math.log2 2');\n  console.assert(Math.log2(1) === 0, 'Math.log2 1');\n  console.assert(Math.log2(0) === -Infinity, 'Math.log2 0');\n  console.assert(Number.isNaN(Math.log2(-2)), 'Math.log2 -2');\n  console.assert(Math.log2(1024) === 10, 'Math.log2 1024');\n};\n\ntests.MathSign = function() {\n  console.assert(Math.sign(3) === 1, 'Math.sign 3');\n  console.assert(Math.sign(-3) === -1, 'Math.sign -3');\n  console.assert(Math.sign('-3') === -1, 'Math.sign \"-3\"');\n  console.assert(Object.is(Math.sign(0), 0), 'Math.sign 0');\n  console.assert(Object.is(Math.sign(-0), -0), 'Math.sign -0');\n  console.assert(Number.isNaN(Math.sign(NaN)), 'Math.sign NaN');\n  console.assert(Number.isNaN(Math.sign('foo')), 'Math.sign \"foo\"');\n  console.assert(Number.isNaN(Math.sign()), 'Math.sign undefined');\n};\n\ntests.MathSinh = function() {\n  console.assert(Math.sinh(0) === 0, 'Math.sinh 0');\n  console.assert(Math.sinh(1).toPrecision(10) === '1.175201194', 'Math.sinh 1');\n};\n\ntests.MathTanh = function() {\n  console.assert(Math.tanh(0) === 0, 'Math.tanh 0');\n  console.assert(Math.tanh(Infinity) === 1, 'Math.tanh Infinity');\n  console.assert(Math.tanh(1).toPrecision(10) === '0.7615941560', 'Math.tanh 1');\n};\n\ntests.MathTrunc = function() {\n  console.assert(Math.trunc(13.37) === 13, 'Math.trunc 13.37');\n  console.assert(Math.trunc(42.84) === 42, 'Math.trunc 42.84');\n  console.assert(Object.is(Math.trunc(0.123), 0), 'Math.trunc 0.123');\n  console.assert(Object.is(Math.trunc(-0.123), -0), 'Math.trunc -0.123');\n  console.assert(Math.trunc('-1.123') === -1, 'Math.trunc \"-1.123\"');\n  console.assert(Number.isNaN(Math.trunc(NaN)), 'Math.trunc NaN');\n  console.assert(Number.isNaN(Math.trunc('foo')), 'Math.trunc \"foo\"');\n  console.assert(Number.isNaN(Math.trunc()), 'Math.trunc undefined');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// WeakMap and WeakMap.prototype\n\ntests.WeakMap = function() {\n  var w = new WeakMap;\n  var p = {};\n  var o = Object.create(p);\n  console.assert(!w.has(p), 'WeakMapPrototypeHasNonKey');\n  console.assert(!w.delete(p), 'WeakMapPrototypeDeleteNonKey');\n  console.assert(w.set(o, 'o') === w, 'WeakMapPrototypeSet');\n  console.assert(w.get(o) === 'o', 'WeakMapPrototypeGet');\n  console.assert(w.get(p) === undefined, 'WeakMapPrototypeGetNonKey');\n  console.assert(w.has(o), 'WeakMapPrototypeHas');\n  console.assert(w.delete(o), 'WeakMapPrototypeDelete');\n  console.assert(!w.has(o), 'WeakMapPrototypeHasNonKey');\n};\n\ntests.WeakMapPrototypeMethodsRejectInvalid = function() {\n  var w = new WeakMap;\n  var name = 'WeakMapPrototypeMethodsReject';\n  function expectError(method, thisVal, args) {\n    var label = String(thisVal === w ? args : 'ThisIs' + args);\n    try {\n      w[method].apply(thisVal, args);\n      console.assert(false, name + label);\n    } catch (e) {\n      console.assert(e.name === 'TypeError', name + label + 'Error');\n    }\n  }\n  var methods = ['delete', 'get', 'has', 'set'];\n  var values = [null, undefined, true, false, 0, 42, '', 'hi'];\n  for (var i = 0; i < methods.length; i++) {\n    var method = methods[i];\n    for (var j = 0; j < values.length; j++) {\n      var value = values[j];\n      expectError(method, value, [{}]);\n      expectError(method, w, [value]);\n    }\n    expectError(method, WeakMap.prototpye, [{}]);  // Ordinary object.\n  }\n};\n"
  },
  {
    "path": "server/tests/db/test_01_es7.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test the ES7 functions of the server.\n * @author fraser@google.com (Neil Fraser)\n */\n\n///////////////////////////////////////////////////////////////////////////////\n// Array and Array.prototype\n\ntests.ArrayPrototypeIncludes = function() {\n  console.assert([1, 2, 3, 2, 1].includes(2), 'Array.prototype.includes');\n  console.assert(![1, 2, 3, 2, 1].includes(4),\n      'Array.prototype.includes not found');\n  console.assert([1, 2, 3, 2, 1].includes(2, 2),\n      'Array.prototype.includes(..., +)');\n  console.assert([1, 2, 3, 2, 1].includes(1, -3),\n      'Array.prototype.includes(..., -)');\n  console.assert(['x', NaN, 'y'].includes(NaN),\n      'Array.prototype.includes NaN');\n\n  var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5};\n  console.assert(Array.prototype.includes.call(o, 2),\n      'Array.prototype.includes.call(array-like, ...)');\n};\n"
  },
  {
    "path": "server/tests/db/test_02_errors.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test language extensions related to errors.\n * @author cpcallen@google.com (Christopher Allen)\n */\n\ntests.errorStack = function() {\n  // Use eval to make parsing .stack easier.\n  var e = eval('new Error;');\n  var lines = e.stack.split('\\n');\n  console.assert(lines[0].trim() === 'at \"new Error;\" 1:1',\n      'new Error has .stack');\n\n  try {\n    (function buggy() {1 instanceof 2;})();\n    console.assert(false, \"thrown Error wasn't thrown??\");\n  } catch (e) {\n    lines = e.stack.split('\\n');\n    console.assert(lines[0].trim() === 'at buggy 1:19',\n        'thrown Error has .stack');\n  }\n\n  // Bug #241.\n  function foo() {\n    switch (1) {\n      case 1:\n        return undefined.hasNoProperties;\n    }\n  }\n  try {\n    foo();\n    console.assert(false, \"Invalid MemberExpression didn't throw??\");\n  } catch (e) {\n    lines = e.stack.split('\\n');\n    console.assert(lines[0].trim() === 'at foo 4:16',\n        'Invalid MemberExpression escaped blame');\n  }\n\n  function bar() {\n    return undefinedVariable;\n  }\n  try {\n    bar();\n    console.assert(false, \"Invalid Identifier didn't throw??\");\n  } catch (e) {\n    lines = e.stack.split('\\n');\n    console.assert(lines[0].trim() === 'at bar 2:12',\n        'Invalid Identifier escaped blame');\n  }\n};\n"
  },
  {
    "path": "server/tests/db/test_02_perms.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test the permissions system.\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n\ntests.perms = function() {\n  console.assert(perms() === CC.root, 'perms() returns root');\n};\n\ntests.setPerms = function() {\n  var bob = {};\n  console.assert(perms() === CC.root, 'before setPerms()');\n  (function() {\n    setPerms(bob);\n    console.assert(perms() === bob, 'after setPerms()');\n    // Perms revert at end of scope.\n  })();\n  console.assert(perms() === CC.root, 'after scope end');\n};\n\ntests.getOwnerOf = function() {\n  var bob = {};\n  var roots = {};\n  setPerms(bob);\n  var bobs = {};\n  console.assert(Object.getOwnerOf(Object) === CC.root, 'getOwenerOfObject');\n  console.assert(Object.getOwnerOf(roots) === CC.root, 'getOwnerOfNew');\n  console.assert(Object.getOwnerOf(bobs) === bob, 'getOwnerOfBobs');\n};\n\ntests.setOwnerOf = function() {\n  var bob = {};\n  var obj = {};\n  console.assert(Object.setOwnerOf(obj, bob) === obj, 'setOwneerOf return');\n  console.assert(Object.getOwnerOf(obj) === bob, 'setOwenerOf effect');\n};\n"
  },
  {
    "path": "server/tests/db/test_09_end.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Run the unit tests.\n * @author fraser@google.com (Neil Fraser)\n */\n\n$.system.log('Starting tests');\n\nfor (var name in tests) {\n  var oldBad = console.badCount;\n  try {\n    tests[name]();\n  } catch (e) {\n    console.assert(false, 'CRASH: ' + name + '\\n' + e);\n  }\n  if (oldBad < console.badCount) {\n    $.system.log(String(tests[name]));\n  }\n}\n\n$.system.log('');\n$.system.log('Completed tests');\n$.system.log('Pass: %d', console.goodCount);\n$.system.log('Fail: %d', console.badCount);\n"
  },
  {
    "path": "server/tests/db/test_10_fibonacci.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Run a performance stress test.\n * @author fraser@google.com (Neil Fraser)\n */\n\n// Define function as global so that it can be run again\n// after checkpoint and restart.\nfunction test_fibonacci10k() {\n  for (var run = 1; run <= 3; run++) {\n    var start = Date.now();\n    var fibonacci = function(n, output) {\n      var a = 1, b = 1, sum;\n      for (var i = 0; i < n; i++) {\n        output.push(a);\n        sum = a + b;\n        a = b;\n        b = sum;\n      }\n    }\n    for(var i = 0; i < 10000; i++) {\n      var result = [];\n      fibonacci(78, result);\n    }\n    result;\n    var ms = Date.now() - start;\n    $.system.log('Run #%d fibonacci10k: %d ms', run, ms);\n  }\n}\n\n$.system.log('Benchmarking fibonacci10k...');\ntest_fibonacci10k();\n"
  },
  {
    "path": "server/tests/db/test_20_reboot.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Reboot the server, and verify restart.\n * @author fraser@google.com (Neil Fraser)\n */\n\n$.system.shutdown();\n\n$.system.log('Benchmarking resurrected fibonacci10k...');\ntest_fibonacci10k();\n\n$.system.shutdown();\n"
  },
  {
    "path": "server/tests/dump_test.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Tests for Saving the state of the interpreter as\n *     eval-able JS.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst {configFromSpec, Do, dump} = require('../dump');\nconst fs = require('fs');\nconst Interpreter = require('../interpreter');\nconst path = require('path');\nconst Selector = require('../selector');\nconst {T} = require('./testing');\nconst util = require('util');\n\n/**\n * Unit tests for the dump function\n * @param {!T} t The test runner object.\n */\nexports.testConfigFromSpec = function(t) {\n  const cases = [{\n    input: [],\n    expected: [],\n  }, {\n    input: [\n      {filename: 'foo',\n       header: ['// F1 BIOS', '// Copyright YEAR Foonly inc.', 'LINES'],\n       headerSubs: {YEAR: '1978', LINES: ['// 1', '// 2']},\n       contents: ['a', 'b']}],\n    expected: [\n      {filename: 'foo',\n       header: '// F1 BIOS\\n// Copyright YEAR Foonly inc.\\nLINES',\n       headerSubs: {YEAR: '1978', LINES: '// 1\\n// 2'},\n       prune: [],\n       pruneRest: [],\n       contents: [\n         {selector: new Selector('a'), do: Do.RECURSE, reorder: false},\n         {selector: new Selector('b'), do: Do.RECURSE, reorder: false}\n       ],\n       rest: false\n      }],\n  }, {\n    input: [{filename: 'foo', prune: ['a', 'b'], rest: true}],\n    expected: [\n      {filename: 'foo', header: undefined, headerSubs: {},\n       prune: [new Selector('a'), new Selector('b')],\n       pruneRest: [],\n       contents: [], rest: true\n      }],\n  }, {\n    input: [{filename: 'foo', pruneRest: ['c', 'd'], rest: true}],\n    expected: [\n      {filename: 'foo', header: undefined, headerSubs: {},\n       prune: [],\n       pruneRest: [new Selector('c'), new Selector('d')],\n       contents: [], rest: true\n      }],\n  }, {\n    input: [{options: {}}, {options: {treeOnly: false}}],\n    expected: [{options: {}}, {options: {treeOnly: false}}],\n  }];\n  for (const {input, expected} of cases) {\n    const out = configFromSpec(input);\n    t.expect(util.format('configFromSpec(%o)', input),\n             util.format('%o', out),\n             util.format('%o', expected));\n  }\n\n  const invalid = [\n    undefined,  // Not an array.\n    'a string',  // Not an array.\n    {object: 'not array'},  // Not an array.\n    ['array', 'of', 'strings'],  // Array but not  of objects.\n    [{}],  // Neither SpecFileItem  nor SpecOptionsItem.\n    [{filename: 'foo'}],  // Missing both .contents and .rest.\n    [{filename: 'foo', contents: [], rest: 'bar'}],  // .rest not bool.\n    [{filename: 'foo', contents: [42]}],  // .contents[0] not object or string.\n    [{filename: 'foo', contents: ['foo[']}],  // .contents[0] invalid selector.\n    [{filename: 'foo', contents: [{}]}],  // ... has no .path.\n    [{filename: 'foo', contents: [{path: 'bar'}]}],  // ... has no .do.\n    [{filename: 'foo', contents: [{path: 'bar', do: 2}]}],  // ... invalid .do.\n    [{filename: 'foo', contents: [{path: 'bar', do: 'baz'}]}],  // Ditto.\n    [{filename: 'foo',  // .reorder not a boolean.\n      contents: [{path: 'bar', do: 'SET', reorder: 'qux'}]}],\n    [{filename: 'foo', rest: 42}],  // .rest not a boolean.\n    [{filename: 'foo', rest: 'false'}],  // .rest not a boolean.\n    [{filename: 'foo', prune: 'x', rest: true}], // .prune not an array.\n    [{filename: 'foo', prune: ['foo['], rest: true}], // .prune[0] invalid.\n    [{filename: 'foo', pruneRest: 'x', rest: true}], // .prune not an array.\n    [{filename: 'foo', pruneRest: ['foo['], rest: true}], // .prune[0] invalid.\n    [{options: 'not an object'}],  // .options is not an object.\n  ];\n  for (const input of invalid) {\n    const name = util.format('configFromSpec(%o)', input);\n    try {\n      configFromSpec(input);\n      t.fail(util.format(\"%O didn't throw\", input));\n    } catch (e) {\n      if (!(e instanceof TypeError || e instanceof SyntaxError)) {\n        t.fail(util.format('%O threw wrong error', input), e);\n      }\n    }\n  }\n};\n\n/**\n * Unit tests for the dump function\n * @param {!T} t The test runner object.\n */\nexports.testDump = function(t) {\n  const intrp = new Interpreter({noLog: ['net']});\n\n  // Load tinycore.\n  const coreDir = 'tests/tinycore';\n  for (const file of fs.readdirSync(coreDir) || []) {\n    if (file.match(/^(core|test).*\\.js$/)) {\n      const filename = path.join(coreDir, file);\n      intrp.createThreadForSrc(String(fs.readFileSync(filename, 'utf8')));\n      intrp.run();\n    }\n  }\n  intrp.stop();  // Close any listening sockets, so node will exit.\n\n  const specText = fs.readFileSync(path.join(coreDir, 'dump_spec.json'));\n  const spec = JSON.parse(String(specText));\n  var config = configFromSpec(spec);\n  dump(new Interpreter(), intrp, config, '/tmp');\n};\n"
  },
  {
    "path": "server/tests/dumper_test.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Tests for Saving the state of the interpreter as\n *     eval-able JS.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst {Dumper, Do, testOnly, Writable} = require('../dumper');\nconst {getInterpreter} = require('./interpreter_common');\nconst Interpreter = require('../interpreter');\nconst path = require('path');\nconst Selector = require('../selector');\nconst {T} = require('./testing');\nconst util = require('util');\n\n// Unpack test-only exports.\nconst {Components, ObjectDumper, ScopeDumper} = testOnly;\n\n/**\n * A mock Writable, for testing.\n * @implements {Writable}\n */\nclass MockWritable {\n  constructor() {\n    /** @const {!Array<string>} */\n    this.output = [];\n  }\n\n  /** @override */\n  write(chunk) {\n    this.output.push(String(chunk));\n  }\n\n  /** @return {string} */\n  toString() {\n    return this.output.join('');\n  }\n}\n\n/**\n * Tests for the ObjectDumper.prototype.isWritable method.\n * @suppress {accessControls}\n */\nexports.testObjectDumperPrototypeIsWritable = function(t) {\n  const intrp = getInterpreter();\n  // Create some objects and properties:\n  // - .foo writable on child but not Object.prototype.\n  // - .bar writable on child but not parent.\n  // - .baz writable on child and parent.\n  intrp.createThreadForSrc(`\n    Object.prototype.foo = undefined;  // Cheeky!\n    Object.defineProperty(Object.prototype, 'foo', {writable: false});\n\n    var parent = {bar: undefined, baz: undefined};\n    Object.defineProperty(parent, 'bar', {writable: false});\n\n    var child = {foo: undefined, bar: undefined, baz: undefined};\n    Object.setPrototypeOf(child, parent);\n  `);\n  intrp.run();\n\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n\n  dumper.dumpBinding(new Selector('Object'), Do.SET);\n  dumper.dumpBinding(new Selector('Object.prototype'), Do.SET);\n\n  const objectPrototypeDumper = dumper.getObjectDumper_(intrp.OBJECT);\n  const parentDumper = dumper.getDumperFor('parent');\n  const childDumper = dumper.getDumperFor('child');\n\n  // Fake dumping of parent and child as if created by object\n  // literals.  (.dumpBinding would use Object.create, pre-setting\n  // their prototypes - we don't want that for this test.)\n  parentDumper.proto = intrp.OBJECT;\n  parentDumper.ref = new Components(dumper.global, 'parent');\n  childDumper.proto = intrp.OBJECT;\n  childDumper.ref = new Components(dumper.global, 'child');\n\n  // Now dump various bindings in a certain order, and check\n  // writability of child.foo, .bar and .baz in each situation.\n  objectPrototypeDumper.dumpBinding(dumper, 'foo', Do.SET);\n  parentDumper.dumpBinding(dumper, Selector.PROTOTYPE, Do.SET);\n  parentDumper.dumpBinding(dumper, 'bar', Do.SET);\n  childDumper.dumpBinding(dumper, Selector.PROTOTYPE, Do.DECL);\n  t.expect(\"childDumper.isWritable('foo')  // 0\",\n      childDumper.isWritable(dumper, 'foo'), true);\n  t.expect(\"childDumper.isWritable('bar')  // 0\",\n      childDumper.isWritable(dumper, 'bar'), true);\n  t.expect(\"childDumper.isWritable('baz')  // 0\",\n      childDumper.isWritable(dumper, 'baz'), true);\n\n  objectPrototypeDumper.dumpBinding(dumper, 'foo', Do.ATTR);\n  parentDumper.dumpBinding(dumper, 'bar', Do.ATTR);\n  t.expect(\"childDumper.isWritable('foo')  // 1\",\n      childDumper.isWritable(dumper, 'foo'), false);\n  t.expect(\"childDumper.isWritable('bar')  // 1\",\n      childDumper.isWritable(dumper, 'bar'), true);\n  t.expect(\"childDumper.isWritable('baz')  // 1\",\n      childDumper.isWritable(dumper, 'baz'), true);\n\n  childDumper.dumpBinding(dumper, Selector.PROTOTYPE, Do.SET);\n  t.expect(\"childDumper.isWritable('foo')  // 2\",\n      childDumper.isWritable(dumper, 'foo'), false);\n  t.expect(\"childDumper.isWritable('bar')  // 2\",\n      childDumper.isWritable(dumper, 'bar'), false);\n  t.expect(\"childDumper.isWritable('baz')  // 2\",\n      childDumper.isWritable(dumper, 'baz'), true);\n\n  childDumper.dumpBinding(dumper, 'foo', Do.DECL);\n  childDumper.dumpBinding(dumper, 'bar', Do.DECL);\n  childDumper.dumpBinding(dumper, 'baz', Do.DECL);\n  t.expect(\"childDumper.isWritable('foo')  // 3\",\n      childDumper.isWritable(dumper, 'foo'), true);\n  t.expect(\"childDumper.isWritable('bar')  // 3\",\n      childDumper.isWritable(dumper, 'bar'), true);\n  t.expect(\"childDumper.isWritable('baz')  // 3\",\n      childDumper.isWritable(dumper, 'baz'), true);\n};\n\n/**\n * Tests for the ObjectDumper.prototype.updateRef method.\n * @suppress {accessControls}\n */\nexports.testObjectDumperUpdateRef = function(t) {\n  const intrp = new Interpreter();\n\n  // ScopeDumper for global scope and ObjectDumpers for some arbitrary objects.\n  const globalDumper = new ScopeDumper(intrp.global);\n  const fooDumper = new ObjectDumper(new intrp.Object());\n  const barDumper = new ObjectDumper(new intrp.Object());\n  const reachableDumper = new ObjectDumper(new intrp.Object());\n  const unreachableDumper = new ObjectDumper(new intrp.Object());\n\n  // Stub Dumper.\n  const /** !Dumper */ dumper = /** @type {?} */({\n    intrp2: intrp,\n    scope: intrp.global,\n  });\n\n  // Scenario 0: Reject self references.\n  fooDumper.updateRef(dumper, new Components(fooDumper, ''));\n  t.expect('fooDumper.updateRef(<foo, \"\">); fooDumper.ref',\n           fooDumper.ref, null);\n\n  // Scenario 1: Typical cases during dumping.  We've dumped foo and\n  // are dumping foo.bar, which might also have (not preferred)\n  // references from reachable and unreachable objects or the global\n  // scope.\n  fooDumper.preferredRef = new Components(globalDumper, 'foo');\n  fooDumper.ref = fooDumper.preferredRef;  // Reachable.\n  barDumper.preferredRef = new Components(fooDumper, 'bar');  // foo.bar\n  barDumper.ref = null;  // Not yet reachable.\n\n  reachableDumper.preferredRef = new Components(globalDumper, 'reachable');\n  reachableDumper.ref = reachableDumper.preferredRef;  // Reachable.\n  unreachableDumper.preferredRef = new Components(globalDumper, 'unreachable');\n  unreachableDumper.ref = null;  // Not yet reachable.\n  \n  // Test all N*N combinations of possible (existing, proposed) refs\n  // for bar.  Cases are in order increrasing preferability: earlier\n  // ones should be replace by later but not vice-versa.\n  const cases = [\n    null,  // No known reference yet.\n\n    // Refs from an unreachable object are better than nothing.\n    new Components(unreachableDumper, Selector.PROTOTYPE),\n    new Components(unreachableDumper, '#hash'),\n    new Components(unreachableDumper, '42'),\n    new Components(unreachableDumper, 'aaaaaaaaaa'),\n    new Components(unreachableDumper, 'bar'),\n\n    // Refs from reachable objects are better - but other than\n    // foo.bar, these two objects are equally good so order just comes\n    // down to selector badness.\n    new Components(reachableDumper, Selector.PROTOTYPE),\n    new Components(fooDumper, Selector.PROTOTYPE),\n    new Components(reachableDumper, '#hash'),\n    new Components(fooDumper, '#hash'),\n    new Components(reachableDumper, '42'),\n    new Components(fooDumper, '42'),\n    new Components(reachableDumper, 'aaaaaaaaaa'),\n    new Components(fooDumper, 'aaaaaaaaaa'),\n    new Components(reachableDumper, 'bar'),\n    new Components(reachableDumper, 'b'),\n    new Components(fooDumper, 'b'),\n\n    // Refs from a scope are generally better.\n    new Components(globalDumper, 'aaaaaaaaaa'),\n    new Components(globalDumper, 'bar'),\n    new Components(globalDumper, 'b'),\n\n    // The preferred reference is best of all.\n    new Components(fooDumper, 'bar'),\n  ];\n  for (var i = 0; i < cases.length; i++) {\n    for (var j = 1; j < cases.length; j++) {  // Don't call updateRef with null.\n      if (!reachableDumper.ref) throw new Error();\n      const before = cases[i];\n      const suggested = cases[j];\n      const expected = cases[Math.max(i, j)];\n      const name = util.format('updateRef %o to %o?', before, suggested);\n      const message =\n          util.format(['barDumper.ref = %s;',\n                       'barDumper.updateRef(%s);',\n                       'barDumper.ref;'].map(s => '    ' + s).join('\\n'),\n                      before, suggested);\n      barDumper.ref = before;\n      barDumper.updateRef(dumper, suggested);\n      t.expect(name, barDumper.ref, expected, message);\n    }\n  }\n\n  // TODO(cpcallen): Scenario 2: unreachable refs (e.g. due to scoping).\n};\n\n/**\n * Unit tests for the Dumper.prototype.isShadowed_ method.\n * @param {!T} t The test runner object.\n * @suppress {accessControls}\n */\nexports.testDumperPrototypeIsShadowed_ = function(t) {\n  const intrp = new Interpreter();\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n\n  intrp.global.createMutableBinding('foo', 'foo');\n  intrp.global.createMutableBinding('bar', 'bar');\n\n  const inner = new Interpreter.Scope(Interpreter.Scope.Type.FUNCTION,\n      intrp.ROOT, intrp.global);\n  inner.createMutableBinding('foo', 'foobar!');\n  dumper.scope = inner;\n\n  t.expect(\"isShadowed_('foo')\", dumper.isShadowed_('foo'), true);\n  t.expect(\"isShadowed_('bar')\", dumper.isShadowed_('bar'), false);\n};\n\n/**\n * Unit tests for the Dumper.prototype.exprForPrimitive_ method.\n * @param {!T} t The test runner object.\n * @suppress {accessControls}\n */\nexports.testDumperPrototypeExprForPrimitive_ = function(t) {\n  const intrp = new Interpreter();\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n\n  function doCases(cases) {\n    for (const tc of cases) {\n      const r = dumper.exprForPrimitive_(tc[0]);\n      t.expect(util.format('dumper.exprForPrimitive_(%o)', tc[0]), r, tc[1]);\n      t.expect(util.format('eval(dumper.exprForPrimitive_(%o))', tc[0]),\n          eval(r), tc[0]);\n    }\n  }\n\n  doCases([\n    [undefined, 'undefined'],\n    [null, 'null'],\n    [false, 'false'],\n    [true, 'true'],\n    [0, '0'],\n    [-0, '-0'],\n    [Infinity, 'Infinity'],\n    [-Infinity, '-Infinity'],\n    [NaN, 'NaN'],\n    ['foo', \"'foo'\"],\n  ]);\n\n  // Shadow some names and check results are still correct.\n  const inner = new Interpreter.Scope(Interpreter.Scope.Type.FUNCTION,\n      intrp.ROOT, intrp.global);\n  inner.createMutableBinding('Infinity', '42');\n  inner.createMutableBinding('NaN', '42');\n  inner.createMutableBinding('undefined', '42');\n  dumper.scope = inner;\n\n  doCases([\n    [undefined, '(void 0)'],\n    [Infinity, '(1/0)'],\n    [-Infinity, '(-1/0)'],\n    [NaN, '(0/0)'],\n  ]);\n};\n\n/**\n * Tests for the Dumper.prototype.exprFor_ method.\n * @param {!T} t The test runner object.\n * @suppress {accessControls}\n */\nexports.testDumperPrototypeExprFor_ = function(t) {\n  // Create an Interperter with a UserFunction to dump.\n  const intrp = new Interpreter();\n  intrp.createThreadForSrc('function foo(bar) {}');\n  intrp.run();\n  const func = /** @type {!Interpreter.prototype.UserFunction} */ (\n      intrp.global.get('foo'));\n\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n\n  // Give references to needed builtins.\n  for (const b of [\n    'Date', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'TypeError',\n    'SyntaxError', 'URIError', 'PermissionError', 'WeakMap',\n  ]) {\n    dumper.getObjectDumper_(/** @type {!Interpreter.prototype.Object} */\n        (intrp.builtins.get(b))).ref = new Components(dumper.global, b);\n  }\n  // Give foo a reference too, even though it has not been created yet.\n  dumper.getObjectDumper_(func).ref = new Components(dumper.global, 'foo');\n\n  const cases = [\n    [intrp.OBJECT, \"new 'Object.prototype'\"],\n    [func, 'function foo(bar) {}'],\n    [new intrp.Object(intrp.ROOT), '{}'],\n    [new intrp.Array(intrp.ROOT), '[]'],\n    [new intrp.Date(new Date('1975-07-27'), intrp.ROOT),\n        \"new Date('1975-07-27T00:00:00.000Z')\"],\n    [new intrp.RegExp(/foo/ig, intrp.ROOT), '/foo/gi'],\n    [new intrp.Error(intrp.ROOT, intrp.ERROR), \"new Error()\"],\n    [new intrp.Error(intrp.ROOT, intrp.ERROR, 'message'),\n        \"new Error('message')\"],\n    [new intrp.Error(intrp.ROOT, intrp.EVAL_ERROR), \"new EvalError()\"],\n    [new intrp.Error(intrp.ROOT, intrp.RANGE_ERROR), \"new RangeError()\"],\n    [new intrp.Error(intrp.ROOT, intrp.REFERENCE_ERROR),\n         \"new ReferenceError()\"],\n    [new intrp.Error(intrp.ROOT, intrp.SYNTAX_ERROR), \"new SyntaxError()\"],\n    [new intrp.Error(intrp.ROOT, intrp.TYPE_ERROR), \"new TypeError()\"],\n    [new intrp.Error(intrp.ROOT, intrp.URI_ERROR), \"new URIError()\"],\n    [new intrp.Error(intrp.ROOT, intrp.PERM_ERROR), \"new PermissionError()\"],\n    [new intrp.Error(intrp.ROOT, intrp.OBJECT), \"new Error()\"],\n    [new intrp.Error(intrp.ROOT, null), \"new Error()\"],\n    [new intrp.WeakMap(), 'new WeakMap()'],\n  ];\n  // A fake reference: exprFor_ won't create an unreferenceable object.\n  const ref = new Components(dumper.global, 'dummyVariable');\n  for (const [value, expected] of cases) {\n    const r = dumper.exprFor_(value, ref);\n    t.expect(util.format('Dumper.p.exprFor_(%s)', value), r, expected);\n  }\n};\n\n\n/**\n * Tests for Dumper.prototype.survey_, and in particular the\n * imlementation of Dijkstra's Algorigithm it uses to set the\n * .preferredRef property on ObjectDumper instances.\n * @param {!T} t The test runner object.\n * @suppress {accessControls}\n */\nexports.testDumperPrototypeSurvey = function(t) {\n  const intrp = getInterpreter();\n\n  // Create various variables to dump.\n  intrp.createThreadForSrc(`\n      var func = (function() {\n        var unreachable = {unreachable: true};\n        return function foo() {return unreachable;};\n      })();\n      var arr = [{baz: {}}];\n      var foo = {bar: arr[0]};\n      Object.setPrototypeOf(foo.bar, {});\n  `);\n  intrp.run();\n\n  // Create Dumper with pristine Interpreter instance to compare to;\n  // get ScopeDumper for global scope.  Dumper constructor performs\n  // survey.\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n\n  // Check preferredRef of various objects.  The preferred selector is\n  // assumed to be the same as the selector used to obtain the object\n  // unless otherwise specified.\n  const tc = [\n    ['func'],\n    ['func{proto}', 'Function.prototype'],\n    ['func{owner}', 'CC.root'],\n    ['func.prototype'],\n    ['func.prototype{proto}', 'Object.prototype'],\n    ['foo'],\n    ['foo{proto}', 'Object.prototype'],\n    ['foo.bar{proto}'],\n    ['foo.bar.baz{proto}', 'Object.prototype'],\n    ['arr[0]', 'foo.bar'],\n  ];\n  for (const [ss, expected] of tc) {\n    const objDumper = dumper.getDumperFor(ss);\n    t.expect('Dumper.p.survey_: .preferredRef of ' + ss,\n             objDumper.getSelector(/*preferred=*/true).toString(),\n             expected || ss);\n  }\n\n  // Can't create preferred Selector for unreachable (it's\n  // unreachable!), so check .preferredRef manually.\n\n  const func = intrp.global.get('func');\n  if (!(func instanceof intrp.UserFunction) || !func.scope.outerScope) {\n    throw new TypeError('func.scope.outerScope not a Scope');\n  }\n  const funcScopeDumper = dumper.getScopeDumper_(func.scope.outerScope);\n  const unreachable = func.scope.outerScope.get('unreachable');\n  if (!(unreachable instanceof intrp.Object)) throw new TypeError();\n  const unreachableDumper = dumper.getObjectDumper_(unreachable);\n  t.expect('Dumper.p.survey_: unreachableDumper.preferredRef.dumper',\n           unreachableDumper.preferredRef.dumper, funcScopeDumper);\n  t.expect('Dumper.p.survey_: unreachableDumper.preferredRef.part',\n           unreachableDumper.preferredRef.part, 'unreachable');\n};\n\n/**\n * Tests for the ObjectDumper.prototype.survey and\n * ScopeDumper.prototype.survey methods and their recording of\n * information about Scopes, Arguments objects and so on.\n * @param {!T} t The test runner object.\n * @suppress {accessControls}\n */\nexports.testSubDumperPrototypeSurvey = function(t) {\n  const intrp = new Interpreter();\n\n  // Create various variables to dump, including creating a closure\n  // belonging to two functions.\n  intrp.createThreadForSrc(`\n      var foo = (function() {\n        var x = 42;\n        bar = function baz() {return x;};\n        function quux() {return -x;};\n        return quux;\n        arguments;  // Never reached, but forces Arguments instantiation.\n      })();\n      var bar;  // N.B.: hoisted.\n      var orphanArgs = (function() {return arguments;})();\n  `);\n  intrp.run();\n\n  // Create Dumper with pristine Interpreter instance to compare to;\n  // get ScopeDumper for global scope.  Dumper constructor performs\n  // survey.\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n\n  // Check relationship of functions and scopes recorded by survey.\n  const baz = /** @type {!Interpreter.prototype.UserFunction} */(\n      intrp.global.get('bar'));  // Function baz was stored in var bar.\n  const quux = /** @type {!Interpreter.prototype.UserFunction} */(\n      intrp.global.get('foo'));  // IIFE returned quux; was stored in var foo.\n  const globalDumper = dumper.getScopeDumper_(intrp.global);\n  const bazDumper = dumper.getObjectDumper_(baz);\n  const bazScopeDumper = dumper.getScopeDumper_(baz.scope);\n  const quuxDumper = dumper.getObjectDumper_(quux);\n  const quuxScopeDumper = dumper.getScopeDumper_(quux.scope);\n\n  t.expect('bazScopeDumper.scope.type', bazScopeDumper.scope.type, 'funexp');\n  t.expect('quuxScopeDumper.scope.type',\n      quuxScopeDumper.scope.type, 'function');\n\n  t.expect('globalDumper.innerFunctions.size',\n      globalDumper.innerFunctions.size, 0);\n  t.expect('globalDumper.innerScopes.size', globalDumper.innerScopes.size, 1);\n  t.assert('globalDumper.innerScopes.has(/* quux.scope */)',\n      globalDumper.innerScopes.has(quuxScopeDumper));\n\n  t.expect('quuxScopeDumper.innerFunctions.size',\n      quuxScopeDumper.innerFunctions.size, 1);\n  t.assert('quuxScopeDumper.innerFunctions.has(/* quux */)',\n      quuxScopeDumper.innerFunctions.has(quuxDumper));\n  t.expect('quuxScopeDumper.innerScopes.size',\n      quuxScopeDumper.innerScopes.size, 1);\n  t.assert('quuxScopeDumper.innerScopes.has(/* baz.scope */)',\n      quuxScopeDumper.innerScopes.has(bazScopeDumper));\n\n  t.expect('bazScopeDumper.innerFunctions.size',\n      bazScopeDumper.innerFunctions.size, 1);\n  t.assert('bazScopeDumper.innerFunctions.has(/* baz */)',\n      bazScopeDumper.innerFunctions.has(bazDumper));\n  t.expect('bazScopeDumper.innerScopes.size',\n      bazScopeDumper.innerScopes.size, 0);\n\n  // Check relationship of Arguments objects and scopes recorded by survey.\n  const quuxArgs = /** @type {!Interpreter.prototype.Arguments} */(\n      quuxScopeDumper.scope.get('arguments'));\n  const orphanArgs = /** @type {!Interpreter.prototype.Arguments} */(\n      intrp.global.get('arguments'));\n  t.expect('argumentsScopeDumpers.size',\n      dumper.argumentsScopeDumpers.size, 1);\n  t.assert('argumentsScopeDumpers.get(quuxArgs) === quuxScopeDumper',\n      dumper.argumentsScopeDumpers.get(quuxArgs) === quuxScopeDumper);\n  t.assert('argumentsScopeDumpers.get(orphanArgs) === quuxScopeDumper',\n      dumper.argumentsScopeDumpers.get(orphanArgs) === undefined);\n};\n\n/**\n * Unit tests for the Dumper.prototype.exprForSelector_ method.\n * @param {!T} t The test runner object.\n * @suppress {accessControls}\n */\nexports.testDumperPrototypeExprForSelector_ = function(t) {\n  const intrp = new Interpreter();\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n\n  // Test dumping a selector before and after dumping Object.getPrototypeOf.\n  const s1 = new Selector('foo.bar{proto}.baz');\n  t.expect(util.format('Dumper.p.exprForSelector_(%s)  // 0', s1),\n           dumper.exprForSelector_(s1),\n           \"(new 'Object.getPrototypeOf')(foo.bar).baz\");\n  // Give Object.getPrototypeOf a referrence indicating it is\n  // available via the global variable myGetPrototypeOf.\n  dumper.getObjectDumper_(/** @type {!Interpreter.prototype.Object} */\n      (intrp.builtins.get('Object.getPrototypeOf'))).ref =\n          new Components(dumper.global, 'myGetPrototypeOf');\n  t.expect(util.format('Dumper.p.exprForSelector_(%s)  // 1', s1),\n           dumper.exprForSelector_(s1),\n           'myGetPrototypeOf(foo.bar).baz');\n\n  // Test dumping a selector before and after dumping Object.getOwnerOf.\n  const s2 = new Selector('quux{owner}');\n  t.expect(util.format('Dumper.p.exprForSelector_(%s)  // 0', s2),\n           dumper.exprForSelector_(s2), \"(new 'Object.getOwnerOf')(quux)\");\n  // Give Object.getOwnerOf a referrence indicating it is\n  // available via the global variable myGetOwnerOf.\n  dumper.getObjectDumper_(/** @type {!Interpreter.prototype.Object} */\n      (intrp.builtins.get('Object.getOwnerOf'))).ref =\n          new Components(dumper.global, 'myGetOwnerOf');\n  t.expect(util.format('Dumper.p.exprForSelector_(%s)  // 1', s2),\n           dumper.exprForSelector_(s2), 'myGetOwnerOf(quux)');\n};\n\n/**\n * Unit tests for the Dumper.prototype.exprForCall_ method.\n * @param {!T} t The test runner object.\n * @suppress {accessControls}\n */\nexports.testDumperPrototypeExprForCall_ = function(t) {\n  const intrp = new Interpreter();\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n\n  // Test dumping builtin calls with no arguments.  Note that eval is\n  // inserted in the global Scope at Interpreter construction time,\n  // while escape is not.\n  t.expect(\"Dumper.p.exprForCall_('eval')\",\n           dumper.exprForCall_('eval'),\n           'eval()');  // eval is inserted in global scope at creation.\n\n  t.expect(\"Dumper.p.exprForCall_('escape')\",\n           dumper.exprForCall_('escape'),\n           \"(new 'escape')()\");\n\n  // Test dumping builtin calls with primitive arguments.\n  t.expect(\"Dumper.p.exprForCall_('eval', [true])\",\n           dumper.exprForCall_('eval', [true]),\n           \"eval(true)\");\n\n  t.expect(\"Dumper.p.exprForCall_('eval', ['foo', 42])\",\n           dumper.exprForCall_('eval', ['foo', 42]),\n           \"eval('foo', 42)\");\n\n  // Test dumping builtin calls with object arguments.\n  t.expect(\"Dumper.p.exprForCall_('eval', [eval])\",\n           dumper.exprForCall_('eval', [intrp.builtins.get('eval')]),\n           \"eval(eval)\");\n\n  // Test dumping builtin calls with Selector arguments.\n  t.expect(\"Dumper.p.exprForCall_('eval', [new Selector('foo.bar.baz')])\",\n           dumper.exprForCall_('eval', [new Selector('foo.bar.baz')]),\n           \"eval(foo.bar.baz)\");\n};\n\n/**\n * Tests for the Dumper.prototype.dumpBinding method, and by\n * implication most of ScopeDumper and ObjectDumper.\n * @param {!T} t The test runner object.\n */\nexports.testDumperPrototypeDumpBinding = function(t) {\n  /**  @type {string} Common minimal init src for all testcases. */\n  const common = \"var Object = new 'Object';\\n\" +\n      ['defineProperty', 'create', 'preventExtensions',\n       'setPrototypeOf', 'setOwnerOf', 'prototype'].map(\n           (member) => `\n               Object.${member} = new 'Object.${member}';\n               Object.defineProperty(Object, '${member}', {enumerable: false});\n           `).join('');\n\n  /**\n   * @type {!Array<{src: string,\n   *                prune: (!Array<(string|number)>|undefined),\n   *                pruneRest: (!Array<(string|number)>|undefined),\n   *                skip: (!Array<(string|number)>|undefined),\n   *                set: (!Array<(string|number)>|undefined),\n   *                dump: (!Array<(string|number)>|undefined),\n   *                after: (!Array<(string|number)>|undefined)}>}\n   */\n  const cases = [\n    { // Test basics: DECL/SET/ATTR/DONE/RECURSE for variables and properties.\n      title: 'basics',\n      src: `\n        var prune = 'not dumped';\n        var skip = 'skipped';\n        var obj = {a: {x: 1}, b: 2, c: 3,\n                   u: undefined, skip: 'skipped', prune: 'not dumped'};\n        Object.defineProperty(obj, 'a', {enumerable: false});\n      `,\n      prune: ['prune', 'obj.prune'],\n      skip: ['skip', 'obj.skip'],\n      set: ['Object', 'Object.setPrototypeOf', 'Object.defineProperty'],\n      dump: [\n        // [ selector, todo, expected output, expected done (default: todo) ]\n        // Order matters.\n        ['prune', Do.SET, '', Do.UNSTARTED],\n        ['skip', Do.SET, \"var skip = 'skipped';\\n\", Do.RECURSE],\n        ['obj', Do.DECL, 'var obj;\\n'],\n        ['obj', Do.SET, 'obj = {};\\n', Do.DONE],\n\n        ['obj.a', Do.DECL, 'obj.a = undefined;\\n'],\n        ['obj.a', Do.SET, 'obj.a = {};\\n'],\n        ['obj.a', Do.ATTR,\n         \"Object.defineProperty(obj, 'a', {enumerable: false});\\n\"],\n        ['obj.a', Do.RECURSE, 'obj.a.x = 1;\\n'],\n        ['obj.b', Do.SET, 'obj.b = 2;\\n', Do.RECURSE],\n        ['obj.u', Do.DECL, 'obj.u = undefined;\\n', Do.RECURSE],\n        ['obj', Do.RECURSE, 'obj.c = 3;\\n', Do.DONE],\n        ['obj.prune', Do.SET, '', Do.UNSTARTED],\n        ['obj.skip', Do.SET, \"obj.skip = 'skipped';\\n\", Do.RECURSE],\n        ['obj', Do.RECURSE, ''],\n      ],\n      after: [\n        // [ selector, expected done ]\n        ['obj^', Do.RECURSE],\n        ['obj.c', Do.RECURSE],\n      ],\n    },\n\n    { // Test the skipBinding option.\n      title: 'skipBinding',\n      src: `\n        var obj = {a: 'a', b: 'b'};\n        Object.setPrototypeOf(obj, {});\n      `,\n      set: ['Object', 'Object.setPrototypeOf'],\n      dump: [\n        ['obj', Do.RECURSE, \"var obj = {};\\nobj.a = 'a';\\n\", Do.DONE,\n         {skipBindings: ['b', Selector.PROTOTYPE]}],\n        ['obj', Do.RECURSE, 'Object.setPrototypeOf(obj, {});\\n' +\n            \"obj.b = 'b';\\n\", Do.RECURSE, {skipBindings: []}],\n      ],\n    },\n\n    { // Test simple recursion with pruning.\n      title: 'recursion-simple',\n      src: `\n        var obj = {a: {id: 'a'}, b: {id: 'b'}, c: {id: 'c'}};\n        Object.setPrototypeOf(obj.c, {id: 'd'});\n      `,\n      // Mark obj.b.id to be pruned, and pruneRest of obj.c.\n      prune: ['obj.b.id'],\n      pruneRest: ['obj.c'],\n      dump: [\n        ['obj', Do.RECURSE,\n         'var obj = {};\\n' +\n             \"obj.a = {};\\n\" +\n             \"obj.a.id = 'a';\\n\" +\n             'obj.b = {};\\n' +\n             'obj.c = {};\\n' +\n             \"(new 'Object.setPrototypeOf')(obj.c, {});\\n\" +\n             \"(new 'Object.getPrototypeOf')(obj.c).id = 'd';\\n\"],\n      ],\n      after: [\n        ['obj.a', Do.RECURSE],\n        ['obj.a.id', Do.RECURSE],\n        ['obj.b', Do.RECURSE],\n        ['obj.b.id', Do.UNSTARTED],\n        ['obj.c', Do.RECURSE],\n        ['obj.c.id', Do.UNSTARTED],\n      ],\n    },\n\n    { // Test recursion in face of cyclic data and incomplet(able) properties.\n      title: 'recursion-incompletable',\n      src: `\n        var obj = {a: {id: 'a'}, b: {id: 'b'}, c: {id: 'c'}};\n        obj.a.self = obj.a;\n        obj.b.self = obj.b;\n        obj.c.parent = obj;\n      `,\n      // Mark obj.b.id to be skipped and obj.c.id to be pruned;\n      // attempting to dump obj recursively should be leave obj.a as\n      // RECUSE, obj.b and obj.c as DONE, and obj.a.id still\n      // UNSTARTED.  obj.c left at DONE.\n      prune: ['obj.c.id'],\n      skip: ['obj.b.id'],\n      dump: [\n        ['obj', Do.RECURSE,\n         // TODO(cpcallen): really want \"var obj = {a: {id: 'a'}, ...\".\n         'var obj = {};\\n' +\n             \"obj.a = {};\\nobj.a.id = 'a';\\nobj.a.self = obj.a;\\n\" +\n             'obj.b = {};\\nobj.b.self = obj.b;\\n' +\n             \"obj.c = {};\\nobj.c.parent = obj;\\n\", Do.DONE],\n      ],\n      after: [\n        ['obj.a', Do.RECURSE],\n        ['obj.a.self', Do.RECURSE],\n        ['obj.a.id', Do.RECURSE],\n        ['obj.b', Do.DONE],\n        ['obj.b.self', Do.DONE],\n        ['obj.b.id', Do.UNSTARTED],\n        ['obj.c', Do.DONE],\n        ['obj.c.id', Do.UNSTARTED],\n        ['obj.c.parent', Do.DONE],\n      ],\n    },\n\n    { // Test recursion that tries to revisit starting object.\n      title: 'recursion-revist',\n      src: `\n        var obj = {v: 42};\n        obj.obj = obj;\n      `,\n      dump: [\n        ['obj', Do.DONE, 'var obj = {};\\n'],\n        // TODO(cpcallen): might prefer '...obj.v = 42\\n'.\n        ['obj.obj', Do.RECURSE, 'obj.obj = obj;\\nobj.obj.v = 42;\\n'],\n        ['obj', Do.RECURSE, ''],\n      ],\n      after: [\n        ['obj.v', Do.RECURSE],\n      ],\n    },\n\n    { // Test recursion, limited by subtree.\n      title: 'recursion-treeOnly',\n      src: `\n        var outsider = {iam: 'outsider'};\n        var obj = {\n          foo: [outsider, {iam: 'insider'}],\n          bar: {iam: 'bar'},\n        };\n        obj.foo[2] = obj.bar;\n      `,\n      set: ['obj'],\n      dump: [\n        ['obj.foo', Do.RECURSE,\n         'obj.foo = [];\\n' +\n             'obj.foo[0] = {};\\n' +\n             \"obj.foo[1] = {};\\nobj.foo[1].iam = 'insider';\\n\" +\n             'obj.foo[2] = {};\\n',\n         Do.DONE, {treeOnly: true}],\n        ['obj', Do.RECURSE,\n         \"obj.bar = obj.foo[2];\\nobj.bar.iam = 'bar';\\n\",\n         Do.DONE, {treeOnly: true}],\n        ['obj', Do.RECURSE,\n         \"obj.foo[0].iam = 'outsider';\\n\",\n         Do.RECURSE, {treeOnly: false}],\n      ],\n    },\n\n    { // Test dumping property attributes.\n      title: 'attributes',\n      src: `\n        var obj = {w: {}, e: {}, c: {}};\n        Object.defineProperty(obj, 'w', {writable: false});\n        Object.defineProperty(obj, 'e', {enumerable: false});\n        Object.defineProperty(obj, 'c', {configurable: false});\n      `,\n      set: ['Object', 'obj'],\n      dump: [\n        ['obj.w', Do.ATTR, \"obj.w = {};\\n\" +\n            \"(new 'Object.defineProperty')(obj, 'w', {writable: false});\\n\"],\n\n        ['Object.defineProperty', Do.SET,\n         \"Object.defineProperty = new 'Object.defineProperty';\\n\"],\n\n        ['obj.e', Do.ATTR, \"obj.e = {};\\n\" +\n            \"Object.defineProperty(obj, 'e', {enumerable: false});\\n\"],\n        ['obj.c', Do.ATTR, \"obj.c = {};\\n\" +\n            \"Object.defineProperty(obj, 'c', {configurable: false});\\n\"],\n      ],\n    },\n\n    { // Test correct dumping inherited-non-writable properties.\n      title: 'non-writable',\n      src: `\n        var parent = {foo: 0};\n        var child = [];\n        for (var i = 0; i <= 4; i++) {\n          child[i] = Object.create(parent);\n          child[i].foo = i;\n        }\n        child[4].foo = undefined;  // Will have DECL do SET implicitly.\n        // Make it impossible to set child[i].foo by assignment.\n        Object.defineProperty(parent, 'foo', {writable: false});\n      `,\n      // Object.create is polyfilled; dumper won't call polyfill.\n      set: ['Object', 'Object.defineProperty', 'parent', 'child',\n            'child[0]', 'child[1]', 'child[2]', 'child[3]', 'child[4]'],\n      dump: [\n        // Inherited non-writable property doesn't exist yet.\n        ['child[0].foo', Do.SET, 'child[0].foo = 0;\\n', Do.RECURSE],\n\n        ['parent', Do.RECURSE, 'parent.foo = 0;\\n' +\n            \"Object.defineProperty(parent, 'foo', {writable: false});\\n\"],\n\n        ['child[1].foo', Do.DECL, \"Object.defineProperty(child[1], 'foo', \" +\n            '{writable: true, enumerable: true, configurable: true});\\n'],\n        ['child[1].foo', Do.SET, \"child[1].foo = 1;\\n\", Do.RECURSE],\n\n        ['child[2].foo', Do.SET, \"Object.defineProperty(child[2], 'foo', \" +\n            '{writable: true, enumerable: true, configurable: true,' +\n            ' value: 2});\\n', Do.RECURSE],\n\n        ['child[3].foo', Do.ATTR, \"Object.defineProperty(child[3], 'foo', \" +\n            '{writable: true, enumerable: true, configurable: true,' +\n            ' value: 3});\\n', Do.RECURSE],\n\n        ['child[4].foo', Do.DECL, \"Object.defineProperty(child[4], 'foo', \" +\n            '{writable: true, enumerable: true, configurable: true});\\n',\n         Do.RECURSE],\n      ],\n      after: [\n        ['child[0]^', Do.DONE, 'parent'],\n        ['child[1]^', Do.DONE, 'parent'],\n        ['child[2]^', Do.DONE, 'parent'],\n        ['child[3]^', Do.DONE, 'parent'],\n        ['child[4]^', Do.DONE, 'parent'],\n      ],\n    },\n\n    { // Test dumping {proto} bindings.\n      title: '{proto}',\n      src: `\n        var parent = {};\n        var child0 = Object.create(parent);\n        var child1 = Object.create(parent);\n        var child2 = Object.create(parent);\n        var child3 = Object.create(parent);\n     `,\n      set: ['Object'],  // N.B.: Object.create is polyfilled.\n      dump: [\n        ['child0', Do.DONE, 'var child0 = {};\\n'],\n        ['child1', Do.DONE, 'var child1 = {};\\n'],\n        ['child2', Do.DONE, 'var child2 = {};\\n'],\n        ['parent', Do.DONE, 'var parent = {};\\n'],\n        ['child3', Do.DONE, \"var child3 = (new 'Object.create')(parent);\\n\"],\n\n        ['child1^', Do.SET, \"(new 'Object.setPrototypeOf')(child1, parent);\\n\",\n         Do.DONE],\n\n        ['Object.setPrototypeOf', Do.SET,\n         \"Object.setPrototypeOf = new 'Object.setPrototypeOf';\\n\"],\n\n        ['child2^', Do.SET, 'Object.setPrototypeOf(child2, parent);\\n',\n         Do.DONE],\n      ],\n      after: [\n        ['child0^', Do.DECL],\n        ['child1^', Do.DONE, 'parent'],\n        ['child2^', Do.DONE, 'parent'],\n        ['child3^', Do.DONE, 'parent'],\n      ]\n    },\n\n    { // Test dumping {proto} bindings: null-protoype objects.\n      title: 'null {proto}',\n      src: `\n        var objs = {obj: {}, fun: function() {}, arr: []};\n        for (var p in objs) {\n          Object.setPrototypeOf(objs[p], null);\n        }\n      `,\n      set: ['Object', 'Object.setPrototypeOf', 'objs'],\n      dump: [\n        ['objs.obj', Do.DONE, \"objs.obj = (new 'Object.create')(null);\\n\"],\n        ['objs.obj{proto}', Do.DONE, '', Do.RECURSE],\n        ['objs.fun', Do.DONE, 'objs.fun = function() {};\\n'],\n        ['objs.fun{proto}', Do.SET, 'Object.setPrototypeOf(objs.fun, null);\\n',\n         Do.RECURSE],\n        ['objs.arr', Do.DONE, 'objs.arr = [];\\n'],\n        ['objs.arr{proto}', Do.SET, 'Object.setPrototypeOf(objs.arr, null);\\n',\n         Do.RECURSE],\n      ],\n    },\n\n    { // Test dumping {owner} bindings.\n      title: '{owner}',\n      src: `\n        var CC = {};\n        CC.root = new 'CC.root';\n        var setPerms = new 'setPerms';\n\n        var alice = {};\n        alice.thing = (function() {setPerms(alice); return {};})();\n        var bob = {};\n        bob.thing = {};\n        Object.setOwnerOf(bob.thing, bob);\n        var unowned = {};\n        Object.setOwnerOf(unowned, null);\n      `,\n      set: ['Object', 'CC', 'CC.root'],\n      dump: [\n        ['alice', Do.DONE, 'var alice = {};\\n'],\n        ['alice.thing', Do.DONE, 'alice.thing = {};\\n'],\n        ['alice.thing{owner}', Do.SET, \"(new 'Object.setOwnerOf')\" +\n            '(alice.thing, alice);\\n', Do.DONE],\n        ['Object.setOwnerOf', Do.SET,\n         \"Object.setOwnerOf = new 'Object.setOwnerOf';\\n\"],\n        ['bob', Do.RECURSE, 'var bob = {};\\nbob.thing = {};\\n' +\n            \"Object.setOwnerOf(bob.thing, bob);\\n\"],\n        ['unowned', Do.SET, 'var unowned = {};\\n', Do.DONE],\n        ['unowned{owner}', Do.SET, 'Object.setOwnerOf(unowned, null);\\n',\n         Do.RECURSE],\n      ],\n      after: [\n        ['alice', Do.DONE],\n        ['alice{owner}', Do.DONE, 'CC.root'],\n        ['alice.thing{owner}', Do.DONE, 'alice'],\n        ['bob', Do.RECURSE],\n        ['bob{owner}', Do.RECURSE, 'CC.root'],\n        ['bob.thing{owner}', Do.RECURSE, 'bob'],\n      ],\n    },\n\n    { // Test dumping extensibility (with related recursion tests).\n      title: 'extensibility',\n      src: `\n        var other = {id: 'other'};\n        var obj1 = {id: 1};\n        var obj2 = {id: 2};\n        var obj3 = {id: 3, other: other};\n        Object.preventExtensions(obj1);\n        Object.preventExtensions(obj2);\n        Object.preventExtensions(obj3);\n      `,\n      set: ['Object', 'obj1', 'obj2', 'obj3'],\n      dump: [\n        ['obj1.id', Do.SET, 'obj1.id = 1;\\n', Do.RECURSE],\n        ['obj1', Do.RECURSE, \"(new 'Object.preventExtensions')(obj1);\\n\"],\n\n        ['Object.preventExtensions', Do.SET,\n         \"Object.preventExtensions = new 'Object.preventExtensions';\\n\",],\n        // Verify property set before extensibility prevented.\n        ['obj2', Do.RECURSE, 'obj2.id = 2;\\nObject.preventExtensions(obj2);\\n'],\n        // Verify treeOnly doesn't prevent .preventExtensions being called.\n        ['obj3', Do.RECURSE, 'obj3.id = 3;\\nobj3.other = {};\\n' +\n            'Object.preventExtensions(obj3);\\n', Do.DONE, {treeOnly: true}],\n        // Verify we don't call .preventExtensions more than once.\n        ['obj3', Do.RECURSE, \"obj3.other.id = 'other';\\n\", Do.RECURSE,\n         {treeOnly: false}],\n      ],\n    },\n\n    { // Test dumping null variables.\n      // (See https://github.com/google/CodeCity/pull/371/files#r429566592)\n      title: 'null variable',\n      src: 'var n = null;',\n      dump: [\n        ['n', Do.SET, 'var n = null;\\n', Do.RECURSE],\n      ],\n    },\n\n    { // Test (not) dumping immutable bindings in the global scope.\n      title: 'immutables',\n      dump: [\n        ['NaN', Do.RECURSE, ''],\n        ['Infinity', Do.RECURSE, ''],\n        ['undefined', Do.RECURSE, ''],\n        ['eval', Do.RECURSE, ''],\n      ],\n    },\n\n    { // Test dumping Function objects.\n      title: 'Function',\n      src: `\n        var Function = new 'Function';\n\n        function f1(arg) {}\n        var f2 = function F2(arg) {};\n        var obj = {f3: function() {}};\n        var f4 = new Function('a1', 'a2,a3', 'a4, a5', '');\n      `,\n      set: ['obj'],\n      dump: [\n        // BUG(cpcallen): Really want 'function f1(arg) {};\\n'.\n        ['f1', Do.SET, 'var f1 = function f1(arg) {};\\n', Do.DONE],\n        // BUG(cpcallen): this causes a crash.\n        // ['f1', Do.RECURSE, '', Do.RECURSE],\n        ['f2', Do.SET, 'var f2 = function F2(arg) {};\\n', Do.DONE],\n        ['obj.f3', Do.SET, 'obj.f3 = function() {};\\n', Do.DONE],\n        // BUG(cpcallen): Really want '... = Function(...', due to scoping.\n        ['f4', Do.SET,\n         'var f4 = function anonymous(a1,a2,a3,a4, a5\\n) {\\n\\n};\\n', Do.DONE],\n        // TODO(ES5): verify that f4.name gets deleted.\n      ],\n      after: [\n        ['f1^', Do.DONE],\n        ['f1.length', Do.RECURSE],\n        ['f1.name', Do.RECURSE],\n        ['f1.prototype', Do.DONE, 'f1.prototype'],\n        ['f1.prototype.constructor', Do.DONE, 'f1'],\n        ['f2^', Do.DONE],\n        ['f2.length', Do.RECURSE],\n        ['f2.name', Do.RECURSE],\n        ['f2.prototype', Do.DONE, 'f2.prototype'],\n        ['f2.prototype.constructor', Do.DONE, 'f2'],\n        ['obj.f3^', Do.DONE],\n        ['obj.f3.length', Do.RECURSE],\n        ['obj.f3.name', Do.UNSTARTED],  // N.B.: not implicitly set.\n        ['obj.f3.prototype', Do.DONE, 'obj.f3.prototype'],\n        ['obj.f3.prototype.constructor', Do.DONE, 'obj.f3'],\n        ['f4^', Do.DONE],\n        // TODO(ES6): verify that f4.name is implicitly set to 'anonymous'.\n        ['f4.length', Do.RECURSE],\n        ['f4.prototype', Do.DONE, 'f4.prototype'],\n        ['f4.prototype.constructor', Do.DONE, 'f4'],\n      ],\n    },\n\n    { // Test Function objects with usable and unusable .prototype\n      // objects.  Note that we don't need to worry about the\n      // attributes of the .prototype property, because a function\n      // object's .prototype is always non-configurable.\n      title: 'Function .prototype',\n      src: `\n        var f1 = function() {};\n        var f2 = function() {};\n        var f3 = function() {};\n        var obj1 = f1.prototype;\n        var obj2 = f2.prototype;\n        f3.prototype = [];\n      `,\n      set: ['Object', 'Object.defineProperty'],\n      dump: [\n        // No problem if f1 dumped before obj1.\n        ['f1', Do.RECURSE, 'var f1 = function() {};\\n'],\n        ['obj1', Do.DONE, 'var obj1 = f1.prototype;\\n'],\n        // Surmountable difficulty if obj2 dumped before f2.\n        ['obj2', Do.DONE, 'var obj2 = {};\\n'],\n        ['f2', Do.DONE, 'var f2 = function() {};\\n'],\n        ['f2.prototype', Do.DONE, 'f2.prototype = obj2;\\n'],\n        ['f2', Do.RECURSE, 'f2.prototype.constructor = f2;\\n' +\n            \"Object.defineProperty(f2.prototype, 'constructor', \" +\n            '{enumerable: false});\\n'],\n        // Non-plain-Object .protype values require special handling too.\n        ['f3', Do.DONE, 'var f3 = function() {};\\n'],\n        ['f3', Do.RECURSE, 'f3.prototype = [];\\n'],\n      ],\n      after: [\n        ['obj1', Do.DONE, 'obj1'],  // Var not RECURSEed (only object).\n        ['f1.prototype', Do.RECURSE, 'obj1'],\n        ['f1.prototype.constructor', Do.RECURSE, 'f1'],\n        ['f2.prototype', Do.RECURSE, 'obj2'],\n        ['f2.prototype.constructor', Do.RECURSE, 'f2'],\n      ],\n    },\n\n    { // Test dumping Function objects' .prototype.constructor property.\n      title: 'Function .prototype.constructor',\n      src: `\n        var f1 = function() {};\n        var f2 = function() {};\n        var f3 = function() {};\n        Object.defineProperty(f2.prototype, 'constructor',\n                              {enumerable: true});\n        Object.defineProperty(f3.prototype, 'constructor',\n                              {writable: false, value: 42});\n      `,\n      set: ['Object', 'Object.defineProperty', 'f1', 'f2', 'f3'],\n      dump: [\n        ['f3.prototype', Do.DONE, ''],\n        ['f3.prototype.constructor', Do.SET,\n         'f3.prototype.constructor = 42;\\n'],\n        ['f3.prototype', Do.RECURSE, 'Object.defineProperty(f3.prototype, ' +\n            \"'constructor', {writable: false});\\n\"],\n      ],\n      after: [\n        ['f1.prototype.constructor', Do.DONE],\n        ['f2.prototype.constructor', Do.SET],\n      ],\n    },\n\n    { // Test dumping Function objects' .name property.\n      title: 'Function .name',\n      src: `\n        var f1 = function() {};\n        var f2 = function() {};\n        Object.defineProperty(f1, 'name', {value: 'Hi!'});\n        delete f2.name;\n      `,\n      set: ['Object', 'Object.defineProperty', 'f1', 'f2'],\n      dump: [\n        ['f1', Do.RECURSE, \"Object.defineProperty(f1, 'name', \" +\n            \"{value: 'Hi!'});\\n\"],\n        ['f2', Do.RECURSE, 'delete f2.name;\\n'],\n      ],\n    },\n\n    { // Test dumping Array objects.\n      title: 'Array',\n      src: `\n        var Array = new 'Array';\n\n        var obj = {};\n        var arr = [42, 69, 105, obj, {}];\n        var sparse = [0, , 2];\n        Object.setPrototypeOf(sparse, null);\n        sparse.length = 4;\n      `,\n      set: ['Object', 'Object.setPrototypeOf', 'obj'],\n      dump: [\n        // TODO(cpcallen): really want 'var arr = [42, 69, 105, obj, {}];\\n'.\n        ['arr', Do.RECURSE, 'var arr = [];\\narr[0] = 42;\\narr[1] = 69;\\n' +\n            'arr[2] = 105;\\narr[3] = obj;\\narr[4] = {};\\n'],\n        // TODO(cpcallen): really want something like\n        //     'var sparse = [0, , 2];\\nsparse.length = 4;'.\n        ['sparse', Do.RECURSE, 'var sparse = [];\\n' +\n            'Object.setPrototypeOf(sparse, null);\\n' +\n            'sparse[0] = 0;\\nsparse[2] = 2;\\nsparse.length = 4;\\n'],\n      ],\n      after: [\n        ['arr^', Do.RECURSE],\n        ['arr.length', Do.RECURSE],\n        ['sparse^', Do.RECURSE],\n        ['sparse.length', Do.RECURSE],\n      ],\n    },\n\n    { // Test dumping Date objects.\n      title: 'Date',\n      src: `\n        var Date = new 'Date';\n\n        var date1 = new Date('1975-07-27');\n        var date2 = new Date('1979-01-04');\n      `,\n      dump: [\n        ['date1', Do.SET,\n         \"var date1 = new (new 'Date')('1975-07-27T00:00:00.000Z');\\n\",\n         Do.DONE],\n        ['Date', Do.SET, \"var Date = new 'Date';\\n\", Do.DONE],\n        ['date2', Do.SET, \"var date2 = new Date('1979-01-04T00:00:00.000Z');\\n\",\n         Do.DONE],\n      ],\n      after: [\n        ['date1^', Do.DONE],\n        ['date2^', Do.DONE],\n      ],\n    },\n\n    { // Test dumping RegExp objects.\n      title: 'RegExp',\n      src: `\n        var RegExp = new 'RegExp';\n\n        var re0 = new RegExp();\n        var re1 = /foo/ig;\n        var re2 = /bar/g;\n        Object.setPrototypeOf(re2, re1);\n        re2.lastIndex = 42;\n        var re3 = /baz/m;\n        Object.setPrototypeOf(re3, re1);\n      `,\n      set: ['Object', 'Object.setPrototypeOf'],\n      dump: [\n        ['re0', Do.SET, 'var re0 = /(?:)/;\\n', Do.DONE],\n        ['re1', Do.SET, 'var re1 = /foo/gi;\\n', Do.DONE],\n        ['re2', Do.RECURSE, 'var re2 = /bar/g;\\n' +\n            'Object.setPrototypeOf(re2, re1);\\n' +\n            're2.lastIndex = 42;\\n'],\n        ['re3', Do.SET, 'var re3 = /baz/m;\\n', Do.DONE],\n        ['re3^', Do.SET, 'Object.setPrototypeOf(re3, re1);\\n', Do.DONE],\n      ],\n      after: [\n        ['re1^', Do.RECURSE],\n        ['re1.source', Do.RECURSE],\n        ['re1.global', Do.RECURSE],\n        ['re1.ignoreCase', Do.RECURSE],\n        ['re1.multiline', Do.RECURSE],\n        ['re1.lastIndex', Do.RECURSE],\n        ['re2^', Do.RECURSE, 're1'],\n        ['re2.source', Do.RECURSE],\n        ['re2.global', Do.RECURSE],\n        ['re2.ignoreCase', Do.RECURSE],\n        ['re2.multiline', Do.RECURSE],\n        ['re2.lastIndex', Do.RECURSE],\n        ['re3^', Do.DONE, 're1'],\n        ['re3.source', Do.RECURSE],\n        ['re3.global', Do.RECURSE],\n        ['re3.ignoreCase', Do.RECURSE],\n        ['re3.multiline', Do.RECURSE],\n        ['re3.lastIndex', Do.RECURSE],\n      ],\n    },\n\n    { // Test dumping Error objects.\n      title: 'Error',\n      src: `\n        var Error = new 'Error';\n        var TypeError = new 'TypeError';\n        var RangeError = new 'RangeError';\n\n        var error1 = new Error('message1');\n        error1.stack = 'stack1';  // Because it's otherwise kind of random.\n        var error2 = new TypeError('message2');\n        error2.stack = 'stack2';\n        var error3 = new RangeError();\n        Object.setPrototypeOf(error3, error1);\n        error3.message = 69;\n        Object.defineProperty(error3, 'message', {writable: false});\n        delete error3.stack;\n      `,\n      set: ['Object', 'Object.defineProperty', 'Object.setPrototypeOf'],\n      dump: [\n        ['error1', Do.SET, \"var error1 = new (new 'Error')('message1');\\n\",\n         Do.DONE],\n        ['error1', Do.RECURSE, \"error1.stack = 'stack1';\\n\"],\n        ['Error', Do.SET, \"var Error = new 'Error';\\n\", Do.DONE],\n        ['TypeError', Do.SET, \"var TypeError = new 'TypeError';\\n\", Do.DONE],\n        ['RangeError', Do.SET, \"var RangeError = new 'RangeError';\\n\", Do.DONE],\n        ['error2', Do.SET, \"var error2 = new TypeError('message2');\\n\",\n         Do.DONE],\n        ['error2', Do.RECURSE, \"error2.stack = 'stack2';\\n\"],\n        ['error3', Do.SET, 'var error3 = new Error();\\n', Do.DONE],\n        ['error3.message', Do.ATTR, 'error3.message = 69;\\n' +\n            \"Object.defineProperty(error3, 'message', {writable: false});\\n\",\n         Do.RECURSE],\n        ['error3', Do.RECURSE, 'delete error3.stack;\\n' +\n            'Object.setPrototypeOf(error3, error1);\\n'],\n      ],\n      after: [\n        ['error1.message', Do.RECURSE],\n        ['error2.message', Do.RECURSE],\n      ],\n    },\n\n    { // Test dumping WeakMap objects.\n      title: 'WeakMap',\n      src: `\n        var WeakMap = new 'WeakMap';\n        var Object = new 'Object';\n        Object.setPrototypeOf = new 'Object.setPrototypeOf';\n\n        var wm1 = new WeakMap();\n        var wm2 = new WeakMap();\n        Object.setPrototypeOf(wm2, null);\n      `,\n      set: ['Object', 'Object.setPrototypeOf'],\n      dump: [\n        ['wm1', Do.SET, \"var wm1 = new (new 'WeakMap')();\\n\", Do.DONE],\n        ['WeakMap', Do.SET, \"var WeakMap = new 'WeakMap';\\n\", Do.DONE],\n        ['wm2', Do.SET, 'var wm2 = new WeakMap();\\n', Do.DONE],\n      ],\n      after: [\n        ['wm1^', Do.DONE],\n        ['wm2^', Do.DECL],\n      ],\n    },\n\n    { // Test dumping builtin objects.\n      title: 'Builtins',\n      src: '',\n      dump: [\n        ['Object', Do.DONE, \"var Object = new 'Object';\\n\"],\n        ['Object.prototype', Do.SET,\n         \"Object.prototype = new 'Object.prototype';\\n\"],\n      ],\n    },\n  ];\n\n  for (const tc of cases) {\n    const prefix = 'dumpBinding: ' + tc.title + ': ';\n\n    // Create Interprerter and objects to dump.  Run minimal common\n    // init then any testcase-specific init source.\n    const intrp = new Interpreter();\n    intrp.createThreadForSrc(common);\n    if (tc.src) intrp.createThreadForSrc(tc.src);\n    intrp.run();\n\n    // Create Dumper with pristine Interpreter instance to compare to.\n    // Supply treeOnly: false because most tests were written before\n    // this option was created (and made to default to true).\n    const pristine = new Interpreter();\n    const dumper = new Dumper(pristine, intrp, {treeOnly: false});\n\n    // Set a few object .done flags in advance, to limit recursive\n    // dumping of builtins in tests.\n    for (const builtin of [intrp.OBJECT, intrp.FUNCTION, intrp.ARRAY,\n                           intrp.REGEXP, intrp.ERROR, intrp.TYPE_ERROR,\n                           intrp.RANGE_ERROR, intrp.ROOT]) {\n      /** @suppress {accessControls} */\n      dumper.getObjectDumper_(builtin).done =\n          ObjectDumper.Done.DONE_RECURSIVELY;\n    };\n    // Set a few binding .done flags in advance to simulate things\n    // already being dumped or being marked for deferred dumping.\n    for (const ss of tc.prune || []) {\n      dumper.prune(new Selector(ss));\n    }\n    for (const ss of tc.pruneRest || []) {\n      dumper.pruneRest(new Selector(ss));\n    }\n    for (const ss of tc.skip || []) {\n      dumper.skip(new Selector(ss));\n    }\n    for (const ss of tc.set || []) {\n      dumper.dumpBinding(new Selector(ss), Do.SET);\n    }\n\n    // Check generated output for (and post-dump status of) specific bindings.\n    for (const [ss, todo, expected, done, options] of tc.dump || []) {\n      const s = new Selector(ss);\n      // Dump binding and check output code.\n      const result = new MockWritable();\n      if (options) dumper.setOptions(options);\n      dumper.setOptions({output: result});\n      dumper.unskip(s);\n      dumper.dumpBinding(s, todo);\n      t.expect(util.format('%sDumper.p.dumpBinding(<%s>, %o)', prefix,\n                           s, todo),\n               String(result), expected);\n      // Check work recorded.\n      /** @suppress {accessControls} */\n      const {dumper: d, part} = dumper.getComponentsForSelector_(s);\n      t.expect(util.format('%sBinding status of <%s> (after dump)', prefix, s),\n               d.getDone(part), done === undefined ? todo : done);\n    }\n\n    // Check status of (some of the) additional bindings that will be\n    // set implicitly as a side effect of the code generated above, and\n    // that their values have the expected references (where\n    // object-valued and already dumped).\n    //\n    // TODO(cpcallen): The value checks are NOT checking the dumped\n    // value (or even, for .proto, the internal record of the current\n    // value), but instead just the preferred selector for the actual\n    // value in interp2.  That's not really too useful, so maybe they\n    // should be removed.\n    for (const [ss, done, valueSelector] of tc.after || []) {\n      const s = new Selector(ss);\n      /** @suppress {accessControls} */\n      const {dumper: d, part} = dumper.getComponentsForSelector_(s);\n      t.expect(util.format('%sbinding status of <%s> (implicit)', prefix, s),\n               d.getDone(part), done);\n      if (valueSelector) {\n        const objDumper = dumper.getDumperFor(ss);\n        t.expect(util.format('%sref for %s', prefix, s),\n                 objDumper.getSelector(/*preferred=*/true).toString(),\n                 valueSelector);\n      }\n    }\n  }\n};\n\n/**\n * Unit tests for Dumper.prototype.warn\n * @param {!T} t The test runner object.\n */\nexports.testDumperPrototypeWarn = function(t) {\n  const intrp = new Interpreter();\n  const dumper = new Dumper(intrp, intrp);\n  const output = new MockWritable();\n  dumper.setOptions({output: output});\n  dumper.warn('1');\n  dumper.warn('2\\n');\n  dumper.indent = '  ';\n  dumper.warn('3\\n4');\n  t.expect('Dumper.prototype.warn(...) output', String(output),\n           '// 1\\n// 2\\n  // 3\\n  // 4\\n');\n};\n\n/**\n * Tests for the ScopeDumper.prototype.dump method.\n * @param {!T} t The test runner object.\n */\nexports.testScopeDumperPrototypeDump = function(t) {\n  const intrp = new Interpreter();\n\n  // Create various variables to dump.\n  intrp.createThreadForSrc(`\n      var value = 42;\n      var obj = (new 'Object.create')(null);\n      obj.prop = 69;\n  `);\n  intrp.run();\n\n  // Create Dumper with pristine Interpreter instance to compare to;\n  // get ScopeDumper for global scope.\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n  /** @suppress {accessControls} */\n  const globalDumper = dumper.getScopeDumper_(intrp.global);\n\n  // Set a few object .done flags in advance, to limit recursive\n  // dumping of builtins in tests.\n  // TODO(cpcallen): this is a temporary hack while refactoring\n  // recursion out of SubDumper.p.dumpBinding; remove once that\n  // refactor is done.\n  for (const builtin of [intrp.OBJECT, intrp.FUNCTION, intrp.ARRAY,\n                         intrp.REGEXP, intrp.ERROR, intrp.TYPE_ERROR,\n                         intrp.RANGE_ERROR, intrp.ROOT]) {\n    /** @suppress {accessControls} */\n    dumper.getObjectDumper_(builtin).done =\n        ObjectDumper.Done.DONE_RECURSIVELY;\n  };\n\n  // Dump one binding and check result.\n  let result = new MockWritable();\n  dumper.setOptions({output: result});\n  globalDumper.dumpBinding(dumper, 'obj', Do.SET);\n  t.expect(\"ScopeDumper.p.dumpBinding(..., 'obj', Do.SET, ...) outputs\",\n           String(result), \"var obj = (new 'Object.create')(null);\\n\");\n\n  // Dump the rest & check result.\n  dumper.setOptions({output: (result = new MockWritable())});\n  globalDumper.dump(dumper);\n  t.expect('ScopeDumper.p.dump(...) outputs', String(result),\n           'var value = 42;\\nobj.prop = 69;\\n');\n};\n\n/**\n * Unit tests for Dumper.prototype.dump.  These need to be async\n * because connectionListen is (under the covers).\n * @param {!T} t The test runner object.\n */\nexports.testDumperPrototypeDump = async function(t) {\n  const intrp = new Interpreter({noLog: ['net']});\n\n  // Create a NativeFuction called \"continue\" that can be used to\n  // resolve awaited Promises.  (Don't add it to the global scope, as\n  // doing so causes dump errors because it's not present in a\n  // pristine Interpreter instance.)\n  // TODO(cpcallen): consider abstracting test machinery into a\n  // runAsyncDumpTest function?\n  let resolve;\n  intrp.createNativeFunction('continue', () => {resolve();}, false);\n\n  // Create a variable and two listening sockets to dump.\n  intrp.createThreadForSrc(`\n      var listener = {onRecieve: function onRecieve(data) {}};\n      (new 'CC.connectionListen')(8888, listener, 100);\n      (new 'CC.connectionListen')(8889, listener);\n      (new 'continue')();\n  `);\n  intrp.start();\n  await new Promise((res, rej) => {resolve = res;});  // Wait for continue().\n  intrp.pause();\n\n  // Create Dumper with pristine Interpreter instance to compare to.\n  const pristine = new Interpreter();\n  const dumper = new Dumper(pristine, intrp);\n  const output = new MockWritable();\n  dumper.setOptions({output: output});\n  dumper.dump();\n  t.expect('Dumper.p.dump(...) outputs', String(output),\n           'var listener = {};\\n' +\n               'listener.onRecieve = function onRecieve(data) {};\\n' +\n               \"(new 'CC.connectionListen')(8888, listener, 100);\\n\" +\n               \"(new 'CC.connectionListen')(8889, listener);\\n\");\n\n  // Clean up.\n  intrp.createThreadForSrc(`\n      (new \"CC.connectionUnlisten\")(8888);\n      (new \"CC.connectionUnlisten\")(8889);\n      (new 'continue')();\n  `);\n  intrp.start();\n  await new Promise((res, rej) => {resolve = res;});  // Wait for continue().\n  intrp.stop();\n};\n"
  },
  {
    "path": "server/tests/interpreter_bench.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Benchmarks for JavaScript interpreter.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst util = require('util');\n\nconst Interpreter = require('../interpreter');\nconst getInterpreter = require('./interpreter_common').getInterpreter;\nconst testcases = require('./testcases');\n\n/**\n * Run a benchmark of the interpreter.\n * @param {!B} b The benchmark runner object.\n * @param {string} name The name of the test.\n * @param {string} setup Source to be evaled to set up benchmark environment.\n * @param {string} timed Source to be evaled and timed.\n */\nfunction runBench(b, name, setup, timed) {\n  for (let i = 0; i < 4; i++) {\n    const interpreter = getInterpreter();\n\n    const err = undefined;\n    try {\n      interpreter.createThreadForSrc(setup);\n      interpreter.run();\n      interpreter.createThreadForSrc(timed);\n      b.start(name, i);\n      interpreter.run();\n      b.end(name, i);\n    } catch (err) {\n      b.crash(name, util.format('%s\\n%s\\n%s', setup, timed, err.stack));\n    }\n  }\n};\n\n/**\n * Run the fibbonacci10k benchmark.\n * @param {!B} b The test runner object.\n */\nexports.benchFibbonacci10k = function(b) {\n  const name = 'fibonacci10k';\n  const setup = `\n    var fibonacci = function(n, output) {\n      var a = 1, b = 1, sum;\n      for (var i = 0; i < n; i++) {\n        output.push(a);\n        sum = a + b;\n        a = b;\n        b = sum;\n      }\n    }`;\n  const timed = `\n    for(var i = 0; i < 10000; i++) {\n      var result = [];\n      fibonacci(78, result);\n    }\n    result;\n  `;\n  runBench(b, name, setup, timed);\n};\n\n/**\n * Run some benchmarks of Array.prototype.sort.\n * @param {!B} b The test runner object.\n */\nexports.benchSort = function(b) {\n  for (const len of [10, 100, 1000, 10000]) {\n    const name = 'sort ' + len;\n    const setup = `\n      var arr = [];\n      for (var i = 0; i < ${len}; i++) {\n        arr.push(Math.floor(Math.random() * ${len}));\n      }`;\n    const timed = `\n      arr.sort(function(a, b) {return a - b;});\n    `;\n    runBench(b, name, setup, timed);\n  }\n};\n"
  },
  {
    "path": "server/tests/interpreter_common.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Load polyfills for tests.\n * @author fraser@google.com (Neil Fraser)\n */\n\n'use strict';\n\nconst fs = require('fs');\nconst Interpreter = require('../interpreter');\n\nexports.startupFiles = {\n  es5: fs.readFileSync('startup/es5.js', 'utf8'),\n  es6: fs.readFileSync('startup/es6.js', 'utf8'),\n  es7: fs.readFileSync('startup/es7.js', 'utf8'),\n  esx: fs.readFileSync('startup/esx.js', 'utf8'),\n  cc: fs.readFileSync('startup/cc.js', 'utf8'),\n};\n\n/**\n * Create an initialize an Interpreter instance.\n * @param {!Interpreter.Options=} options Interpreter constructor\n *     options.  (Default: see implementation.)\n * @param {boolean=} init Load the standard startup files?  (Default: true.)\n * @return {!Interpreter}\n */\nexports.getInterpreter = function(options, init) {\n  var intrp = new Interpreter(options);\n  if (init || init === undefined) {\n    for (const file of Object.values(exports.startupFiles)) {\n      intrp.createThreadForSrc(file);\n      intrp.run();\n    }\n  }\n  return intrp;\n}\n"
  },
  {
    "path": "server/tests/interpreter_test.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Tests for JavaScript interpreter.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst http = require('http');\nconst net = require('net');\nconst util = require('util');\n\nconst Interpreter = require('../interpreter');\nconst {getInterpreter} = require('./interpreter_common');\nconst Parser = require('../parser').Parser;\nconst {T} = require('./testing');\nconst testcases = require('./testcases');\n\n///////////////////////////////////////////////////////////////////////////////\n// Test helper functions.\n///////////////////////////////////////////////////////////////////////////////\n\n// Prepare static interpreter instance for runSimpleTest.\nconst interpreter = getInterpreter();\ninterpreter.global.createMutableBinding('src');\n\n/**\n * Run a simple test of the interpreter.  A single, shared Interpreter\n * instance is used by all tests executed by this function, but eval\n * is used to evaluate src in its own scope.  The supplied src must\n * not modify objects accessible via the global scope!\n * @param {!T} t The test runner object.\n * @param {string} name The name of the test.\n * @param {string} src The code to be evaled.\n * @param {number|string|boolean|null|undefined} expected The expected\n *     completion value.\n */\nfunction runSimpleTest(t, name, src, expected) {\n  let thread;\n  try {\n    interpreter.setValueToScope(interpreter.global, 'src', src);\n    thread = interpreter.createThreadForSrc('eval(src);').thread;\n    interpreter.run();\n  } catch (e) {\n    t.crash(name, util.format('%s\\n%s', src, e.stack));\n    return;\n  }\n  const r = interpreter.pseudoToNative(thread.value);\n  t.expect(name, r, expected, src);\n}\n\n/**\n * Run a test of the interpreter using an independent Interpreter\n * instance, which may be created with non-default options and/or\n * without the standard startup files, and during which various\n * callbacks will be executed; see TestOptions for details.\n * (Simulated) time will be automatically fast-forwarded as required\n * to wake sleeping threads.\n * @param {!T} t The test runner object.\n * @param {string} name The name of the test.\n * @param {string} src The code to be evaled.\n * @param {number|string|boolean|null|undefined} expected The expected\n *     completion value.\n * @param {!TestOptions=} options Custom test options.\n */\nfunction runTest(t, name, src, expected, options) {\n  options = options || {};\n  const intrp = getInterpreter(options.options, options.standardInit);\n  if (options.onCreate) {\n    options.onCreate(intrp);\n  }\n\n  let thread;\n  try {\n    thread = intrp.createThreadForSrc(src).thread;\n    if (options.onCreateThread) {\n      options.onCreateThread(intrp, thread);\n    }\n    let runResult;\n    while ((runResult = intrp.run())) {\n      if (runResult > 0) {  // Sleeping thread(s).\n        // Fast forward to wake-up time.  Cast to defeat @private check.\n        /** @type {?} */(intrp).previousTime_ += runResult;\n      } else {  // Blocked thread(s).\n        if (options.onBlocked) {\n          options.onBlocked(intrp);\n        }\n      }\n    }\n  } catch (e) {\n    t.crash(name, util.format('%s\\n%s', src, e.stack));\n    return;\n  }\n  const r = intrp.pseudoToNative(thread.value);\n  t.expect(name, r, expected, src);\n}\n\n/**\n * Run a (truly) asynchronous test of the interpreter.  A new\n * Interpreter instance is created for each test.  Special functions\n * resolve() and reject() are inserted in the global scope; they will\n * end the test.  If resolve() is called the test will end normally\n * and the argument supplied will be compared with the expected value;\n * if reject() is called the test will instead be treated as a\n * failure.\n * @param {!T} t The test runner object.\n * @param {string} name The name of the test.\n * @param {string} src The code to be evaled.\n * @param {number|string|boolean|null|undefined} expected The expected\n *     completion value.\n * @param {!TestOptions=} options Custom test options.  Note that\n *     'onBlocked' is ignored because the interpreter is .start()ed\n *     instead of .run() being called directly.\n */\nasync function runAsyncTest(t, name, src, expected, options) {\n  options = options || {};\n  const intrp = getInterpreter(options.options, options.standardInit);\n  if (options.onCreate) {\n    options.onCreate(intrp);\n  }\n\n  // Create promise to signal completion of test from within\n  // interpreter.  Awaiting p will block until resolve or reject is\n  // called.\n  let resolve, reject, result;\n  const p = new Promise(function(res, rej) {resolve = res; reject = rej;});\n  intrp.global.createMutableBinding(\n      'resolve', intrp.createNativeFunction('resolve', resolve, false));\n  intrp.global.createMutableBinding(\n      'reject', intrp.createNativeFunction('reject', reject, false));\n\n  try {\n    const thread = intrp.createThreadForSrc(src).thread;\n    if (options.onCreateThread) {\n      options.onCreateThread(intrp, thread);\n    }\n    intrp.start();\n    result = await p;\n  } catch (e) {\n    t.fail(name, util.format('%s\\n%s', src, e));\n    return;\n  } finally {\n    intrp.stop();\n  }\n  const r = intrp.pseudoToNative(result);\n  t.expect(name, r, expected, src);\n}\n\n/**\n * Options for runTest and runAsyncTest.\n * @record\n */\nconst TestOptions = function() {};\n\n/**\n * Interpreter constructor options.\n * @type {!Interpreter.Options|undefined}\n */\nTestOptions.prototype.options;\n\n/**\n * Load the standard startup files?  (Default: true.)\n * @type {boolean|undefined}\n */\nTestOptions.prototype.standardInit;\n\n/**\n * Callback to be called after creating new interpreter instance (and\n * running standard starup files, if not suppressed with standardInit:\n * false) but before creating a thread for src.  Can be used to insert\n * extra bindings into the global scope (e.g., to create additional\n * builtins).\n *\n * The first argument is the interpreter instance to be configured.\n *\n * @type {function(!Interpreter)|undefined}\n */\nTestOptions.prototype.onCreate;\n\n/**\n * Callback to be called after creating a new Interpreter.Thread, but\n * before running it.\n *\n * The first argument is the interpreter instance.\n * The second argument is the thread just created.\n *\n * @type {function(!Interpreter, !Interpreter.Thread)|undefined}\n */\nTestOptions.prototype.onCreateThread;\n\n/**\n * Callback to be called if .run() returns a negative value,\n * indicating there are blocked threads.  Can be used to fake\n * completion of asynchronous events.\n *\n * The first argument is the interpreter instance to be configured.\n *\n * @type {function(!Interpreter)|undefined}\n */\nTestOptions.prototype.onBlocked;\n\n///////////////////////////////////////////////////////////////////////////////\n// Tests: static analysis functions\n///////////////////////////////////////////////////////////////////////////////\n\nexports.testGetBoundNames = function(t) {\n  const name = 'getBoundNames';\n  const {getBoundNames} = Interpreter.testOnly;\n\n  const src = `\n      var a, b;\n      for (var c in {}) {}\n      function f(x) {\n        var y, z;\n      };\n      (function g() { var v; })();\n  `;\n  const ast = Parser.parse(src);\n  const boundNames = getBoundNames(ast);\n  const keys = Object.getOwnPropertyNames(boundNames);\n  t.expect(`${name}() keys`, keys.join(),\n           'a,b,c,f', src);\n  for (let i = 0; i < 3; i++) {\n    t.expect(`${name}()[${i}]`, boundNames[keys[i]], undefined, src);\n  }\n  t.expect(`${name}()[3]`, boundNames['f'], ast['body'][2], src);\n};\n\nexports.testHasArgumentsOrEval = function(t) {\n  const name = 'hasArgumentsOrEval';\n  const {hasArgumentsOrEval} = Interpreter.testOnly;\n\n  const cases = [\n    // [src, expected]; will only look at first statement src.\n    ['Arguments;', false],\n    ['arguments;', true],\n    ['arguments[0];', true],\n    ['foo[arguments];', true],\n    ['bar(arguments);', true],\n    ['{var x; function myArgs() {return arguments;}}', false],\n    ['{function f() {} arguments;}', true],\n\n    ['Eval;', false],\n    ['eval;', true],\n    ['eval();', true],\n    ['Function.prototype.call(eval);', true],\n    ['{var x; function myEval(arg) {eval(arg);}}', false],\n    ['{function f() {} eval();}', true],\n  ];\n  for (const [src, expected] of cases) {\n    try {\n      const ast = Parser.parse(src);\n      const firstStatement = ast['body'][0];\n      t.expect(`${name} ${src}`, hasArgumentsOrEval(firstStatement),\n               expected, src);\n    } catch (e) {\n      t.crash(name, util.format('%s\\n%s', src, e.stack));\n    }\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Tests: run tests from testcases.js.\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Run the simple tests in testcases.js\n * @param {!T} t The test runner object.\n */\nexports.testTestcases = function(t) {\n  for (const tc of testcases) {\n    if (!('expected' in tc)) {\n      t.skip(tc.name);\n      continue;\n    }\n    if (tc.destructive) {\n      const testOptions = tc.options ? {options: tc.options} : {};\n      runTest(t, tc.name || tc.src, tc.src, tc.expected, testOptions);\n    } else {\n      const oldOptions = interpreter.options;\n      if (tc.options) interpreter.options = tc.options;\n      runSimpleTest(t, tc.name || tc.src, tc.src, tc.expected);\n      if (tc.options) interpreter.options = oldOptions;\n    }\n  }\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Tests: interpreter internals\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Run some tests of switch statement with fallthrough.\n * @param {!T} t The test runner object.\n */\nexports.testSwitchStatementFallthrough = function(t) {\n  const code = `\n      var x = '';\n      switch (i) {\n        case 1:\n          x += '1';\n          // fall through\n        case 2:\n          x += '2';\n          // fall through\n        default:\n          x += 'D';\n          // fall through\n        case 3:\n          x += '3';\n          // fall through\n        case 4:\n          x += '4';\n          // fall through\n      }\n      x;`;\n  const expected = ['D34', '12D34', '2D34', '34', '4'];\n  for (let i = 0; i < expected.length; i++) {\n    const src = 'var i = ' + i + ';\\n' + code;\n    runSimpleTest(t, 'switch fallthrough ' + i, src, expected[i]);\n  }\n};\n\n/**\n * Run some tests of switch statement completion values.\n * @param {!T} t The test runner object.\n */\nexports.testSwitchStatementBreaks = function(t) {\n  const code = `\n      foo: {\n        switch (i) {\n          case 1:\n            10;\n            // fall through\n          case 2:\n            20;\n            break;\n          default:\n            50;\n            // fall through\n          case 3:\n            30;\n            break foo;\n          case 4:\n            40;\n        }\n      }`;\n  const expected = [30, 20, 20, 30, 40];\n  for (let i = 0; i < expected.length; i++) {\n    const src = 'var i = ' + i + ';\\n' + code;\n    runSimpleTest(t, 'switch completion ' + i, src, expected[i]);\n  }\n};\n\n/**\n * Run some tests of evaluation of binary expressions, as defined in\n * §11.5--11.11 of the ES5.1 spec.\n * @param {!T} t The test runner object.\n */\nexports.testBinaryOp = function(t) {\n  const cases = [\n    // Addition / concatenation:\n    [\"1 + 1\", 2],\n    [\"'1' + 1\", '11'],\n    [\"1 + '1'\", '11'],\n\n    // Subtraction:\n    [\"'1' - 1\", 0],\n\n    // Multiplication:\n    [\"'5' * '5'\", 25],\n\n    [\"-5 * 0\", -0],\n    [\"-5 * -0\", 0],\n\n    [\"1 * NaN\", NaN],\n    [\"Infinity * NaN\", NaN],\n    [\"-Infinity * NaN\", NaN],\n\n    [\"Infinity * Infinity\", Infinity],\n    [\"Infinity * -Infinity\", -Infinity],\n    [\"-Infinity * -Infinity\", Infinity],\n    [\"-Infinity * Infinity\", -Infinity],\n    // FIXME: add overflow/underflow cases\n\n    // Division:\n    [\"35 / '7'\", 5],\n\n    [\"1 / 1\", 1],\n    [\"1 / -1\", -1],\n    [\"-1 / -1\", 1],\n    [\"-1 / 1\", -1],\n\n    [\"1 / NaN\", NaN],\n    [\"NaN / NaN\", NaN],\n    [\"NaN / 1\", NaN],\n\n    [\"Infinity / Infinity\", NaN],\n    [\"Infinity / -Infinity\", NaN],\n    [\"-Infinity / -Infinity\", NaN],\n    [\"-Infinity / Infinity\", NaN],\n\n    [\"Infinity / 0\", Infinity],\n    [\"Infinity / -0\", -Infinity],\n    [\"-Infinity / -0\", Infinity],\n    [\"-Infinity / 0\", -Infinity],\n\n    [\"Infinity / 1\", Infinity],\n    [\"Infinity / -1\", -Infinity],\n    [\"-Infinity / -1\", Infinity],\n    [\"-Infinity / 1\", -Infinity],\n\n    [\"1 / Infinity\", 0],\n    [\"1 / -Infinity\", -0],\n    [\"-1 / -Infinity\", 0],\n    [\"-1 / Infinity\", -0],\n\n    [\"0 / 0\", NaN],\n    [\"0 / -0\", NaN],\n    [\"-0 / -0\", NaN],\n    [\"-0 / 0\", NaN],\n\n    [\"1 / 0\", Infinity],\n    [\"1 / -0\", -Infinity],\n    [\"-1 / -0\", Infinity],\n    [\"-1 / 0\", -Infinity],\n    // FIXME: add overflow/underflow cases\n\n    // Remainder:\n    [\"20 % 5.5\", 3.5],\n    [\"20 % -5.5\", 3.5],\n    [\"-20 % -5.5\", -3.5],\n    [\"-20 % 5.5\", -3.5],\n\n    [\"1 % NaN\", NaN],\n    [\"NaN % NaN\", NaN],\n    [\"NaN % 1\", NaN],\n\n    [\"Infinity % 1\", NaN],\n    [\"-Infinity % 1\", NaN],\n    [\"1 % 0\", NaN],\n    [\"1 % -0\", NaN],\n    [\"Infinity % 0\", NaN],\n    [\"Infinity % -0\", NaN],\n    [\"-Infinity % -0\", NaN],\n    [\"-Infinity % 0\", NaN],\n\n    [\"0 % 1\", 0],\n    [\"-0 % 1\", -0],\n    // FIXME: add overflow/underflow cases\n\n    // Left shift:\n    [\"10 << 2\", 40],\n    [\"10 << 28\", -1610612736],\n    [\"10 << 33\", 20],\n    [\"10 << 34\", 40],\n\n    // Signed right shift:\n    [\"10 >> 4\", 0],\n    [\"10 >> 33\", 5],\n    [\"10 >> 34\", 2],\n    [\"-11 >> 1\", -6],\n    [\"-11 >> 2\", -3],\n\n    // Signed right shift:\n    [\"10 >>> 4\", 0],\n    [\"10 >>> 33\", 5],\n    [\"10 >>> 34\", 2],\n    [\"-11 >>> 0\", 0xfffffff5],\n    [\"-11 >>> 1\", 0x7ffffffa],\n    [\"-11 >>> 2\", 0x3ffffffd],\n    [\"4294967338 >>> 0\", 42],\n\n    // Bitwise:\n    [\"0x3 | 0x5\", 0x7],\n    [\"0x3 ^ 0x5\", 0x6],\n    [\"0x3 & 0x5\", 0x1],\n\n    [\"NaN | 0\", 0],\n    [\"-0 | 0\", 0],\n    [\"Infinity | 0\", 0],\n    [\"-Infinity | 0\", 0],\n\n    // Comparisons:\n    //\n    // (This is mainly about making sure that the binary operators are\n    // hooked up to the abstract relational comparison algorithm\n    // correctly; that algorithm is tested separately to make sure\n    // details of comparisons are correct.)\n    [\"1 < 2\", true],\n    [\"2 < 2\", false],\n    [\"3 < 2\", false],\n\n    [\"1 <= 2\", true],\n    [\"2 <= 2\", true],\n    [\"3 <= 2\", false],\n\n    [\"1 > 2\", false],\n    [\"2 > 2\", false],\n    [\"3 > 2\", true],\n\n    [\"1 >= 2\", false],\n    [\"2 >= 2\", true],\n    [\"3 >= 2\", true],\n\n    // (Ditto for abastract equality comparison algorithm.)\n    [\"1 == 1\", true],\n    [\"2 == 1\", false],\n    [\"2 == 2\", true],\n    [\"1 == 2\", false],\n\n    [\"1 == '1'\", true],\n\n    [\"1 != 1\", false],\n    [\"2 != 1\", true],\n    [\"2 != 2\", false],\n    [\"1 != 2\", true],\n\n    [\"1 != '1'\", false],\n\n    // (Ditto for abastract strict equality comparison algorithm.)\n    [\"1 === 1\", true],\n    [\"2 === 1\", false],\n    [\"2 === 2\", true],\n    [\"1 === 2\", false],\n\n    [\"1 === '1'\", false],\n\n    [\"1 !== 1\", false],\n    [\"2 !== 1\", true],\n    [\"2 !== 2\", false],\n    [\"1 !== 2\", true],\n\n    [\"1 !== '1'\", true],\n  ];\n  for (const tc of cases) {\n    const src = tc[0] + ';';\n    runSimpleTest(t, 'BinaryExpression: ' + tc[0], src, tc[1]);\n  }\n};\n\n/**\n * Run some tests of the Abstract Relational Comparison Algorithm, as\n * defined in §11.8.5 of the ES5.1 spec and as embodied by the '<'\n * operator.\n * @param {!T} t The test runner object.\n */\nexports.testArca = function(t) {\n  const cases = [\n    ['0, NaN', undefined],\n    ['NaN, NaN', undefined],\n    ['NaN, 0', undefined],\n\n    ['1, 1', false],\n    ['0, -0', false],\n    ['-0, 0', false],\n\n    ['Infinity, Number.MAX_VALUE', false],\n    ['Number.MAX_VALUE, Infinity', true],\n    ['-Infinity, -Number.MAX_VALUE', true],\n    ['-Number.MAX_VALUE, -Infinity', false],\n\n    ['1, 2', true],\n    ['2, 1', false],\n\n    // String comparisons:\n    ['\"\", \"\"', false],\n    ['\"\", \" \"', true],\n    ['\" \", \"\"', false],\n    ['\" \", \" \"', false],\n    ['\"foo\", \"foobar\"', true],\n    ['\"foo\", \"bar\"', false],\n    ['\"foobar\", \"foo\"', false],\n    ['\"10\", \"9\"', true],\n    ['\"10\", 9', false],\n\n    // \\ufb00 vs. \\U0001f019: this test fails if we do simple\n    // lexicographic comparison of UTF-8 or UTF-32.  The latter\n    // character is a larger code point and sorts later in UTF8,\n    // but in UTF16 it gets replaced by two surrogates, both of\n    // which are smaller than \\uf000.\n    ['\"ﬀ\", \"🀙\"', false],\n\n    // Mixed:\n    ['11, \"2\"', false],  // Numeric\n    ['2, \"11\"', true],   // Numeric\n    ['\"11\", \"2\"', true], // String\n  ];\n  for (const tc of cases) {\n    const src = `\n        (function(a,b){\n          return ((a < b) || (a >= b)) ? (a < b) : undefined;\n        })(${tc[0]});`;\n    runSimpleTest(t, 'ARCA: ' + tc[0], src, tc[1]);\n  }\n};\n\n/**\n * Run some tests of the Abstract Equality Comparison Algorithm and\n * the Abstract Strict Equality Comparison Algorithm, as defined in\n * §11.9.3 and §11.9.6 respectiveyl of the ES5.1 spec and as embodied\n * by the '==' and '===' operators.\n * @param {!T} t The test runner object.\n */\nexports.testAeca = function(t) {\n  const cases = [\n    ['false, false', true, true],  // Numeric\n    ['false, true', false, false], // Numeric\n    ['true, true', true, true],    // Numeric\n    ['true, false', false, false], // Numeric\n\n    // Numeric comparisons:\n    ['0, NaN', false, false],\n    ['NaN, NaN', false, false],\n    ['NaN, 0', false, false],\n\n    ['1, 1', true, true],\n    ['0, -0', true, true],\n    ['-0, 0', true, true],\n\n    ['Infinity, Number.MAX_VALUE', false, false],\n    ['Number.MAX_VALUE, Infinity', false, false],\n    ['Infinity, -Number.MAX_VALUE', false, false],\n    ['-Number.MAX_VALUE, -Infinity', false, false],\n\n    ['1, 2', false, false],\n    ['2, 1', false, false],\n\n    // String comparisons:\n    ['\"\", \"\"', true, true],\n    ['\"\", \" \"', false, false],\n    ['\" \", \"\"', false, false],\n    ['\" \", \" \"', true, true],\n    ['\"foo\", \"foobar\"', false, false],\n    ['\"foo\", \"bar\"', false, false],\n    ['\"foobar\", \"foo\"', false, false],\n    ['\"10\", \"9\"', false, false],\n\n    // Null / undefined:\n    ['undefined, undefined', true, true],\n    ['undefined, null', true, false],\n    ['null, null', true, true],\n    ['null, undefined', true, false],\n\n    // Objects:\n    ['Object.prototype, Object.prototype', true, true],\n    ['{}, {}', false, false],\n\n    // Mixed:\n    ['\"10\", 10', true, false],   // Numeric\n    ['10, \"10\"', true, false],   // Numeric\n    ['\"10\", 9', false, false],   // Numeric\n    ['\"10\", \"9\"', false, false], // String\n    ['\"10\", \"10\"', true, true],  // String\n\n    ['false, 0', true, false],  // Numeric\n    ['false, 1', false, false], // Numeric\n    ['true, 1', true, false],   // Numeric\n    ['true, 0', false, false],  // Numeric\n    ['0, false', true, false],  // Numeric\n    ['1, false', false, false], // Numeric\n    ['1, true', true, false],   // Numeric\n    ['0, true', false, false],  // Numeric\n\n    ['null, false', false, false],\n    ['null, 0', false, false],\n    ['null, \"\"', false, false],\n    ['false, null', false, false],\n    ['0, null', false, false],\n    ['\"\", null', false, false],\n\n    ['{}, false', false, false],\n    ['{}, 0', false, false],\n    ['{}, \"\"', false, false],\n    ['{}, null', false, false],\n    ['{}, undefined', false, false],\n  ];\n  for (const tc of cases) {\n    let src = `(function(a,b) {return a == b})(${tc[0]});`;\n    runSimpleTest(t, 'AECA: ' + tc[0], src, tc[1]);\n    src = `(function(a,b) {return a === b})(${tc[0]});`;\n    runSimpleTest(t, 'ASECA: ' + tc[0], src, tc[2]);\n  }\n};\n\n/**\n * Run a test of asynchronous functions:\n * @param {!T} t The test runner object.\n * @suppress {visibility}\n */\nexports.testAsync = function(t) {\n  // Function to install an async NativeFunction on new Interpreter\n  // instances.  The function, when called, will save its\n  // resolve/reject callbacks and first arg in test-local variables.\n  let resolve, reject, arg;\n  function createAsync(intrp) {\n    intrp.global.createMutableBinding('async', new intrp.NativeFunction({\n      name: 'async', length: 0,\n      call: function(intrp, thread, state, thisVal, args) {\n        arg = args[0];\n        const rr = intrp.getResolveReject(thread, state);\n        resolve = rr.resolve;\n        reject = rr.reject;\n        return Interpreter.FunctionResult.Block;\n      }\n    }));\n  };\n\n  // Test ordinary return.\n  let name = 'testAsyncResolve';\n  let src = `\n      'before';\n      async();\n      'between';\n      async('af') + 'ter';\n  `;\n  runTest(t, name, src, 'after', {\n    standardInit: false,  // Save time.\n    onCreate: createAsync,\n    onBlocked: (intrp) => {resolve(arg);},\n  });\n\n  // Test throwing an exception.\n  name ='testAsyncReject';\n  src = `\n      try {\n        'before';\n        async();\n        'after';\n      } catch (e) {\n        e;\n      }\n  `;\n  runTest(t, name, src, 'except', {\n    standardInit: false,  // Save time.\n    onCreate: createAsync,\n    onBlocked: (intrp) => {reject('except');},\n  });\n\n  // Extra check to verify async function can't resolve/reject more\n  // than once without an asertion failure.\n  name = 'testAsyncSafetyCheck';\n  let ok;\n  src = `\n     async();  // Returns ok === undefined then sets ok to 'ok'.\n     async();  // Returns ok === 'ok' then uselessly sets ok a second time.\n  `;\n  runTest(t, name, src, 'ok', {\n    standardInit: false,  // Save time.\n    onCreate: createAsync,\n    onBlocked: (intrp) => {\n      resolve(ok);\n      // Call reject; this is expected to blow up.\n      try {\n        reject('foo');\n      } catch (e) {\n        ok = 'ok';\n      }\n    },\n  });\n\n  // A test of unwind_, to make sure it unwinds and kills the correct\n  // thread when an async function throws.\n  name = 'testAsyncRejectUnwind';\n  const intrp = getInterpreter({noLog: ['unhandled']});\n  createAsync(intrp);  // Install async function.\n  // Create cannon-fodder thread that will usually be ready to run.\n  const bgThread = intrp.createThreadForSrc(`\n      // Repeatedly suspend; every 10th time suspend for a long time.\n      for (var i = 1; true; i++) {\n        suspend((i % 10) ? 0 : 1000);\n      }\n  `).thread;\n  // Create thread to call async function.\n  const asyncThread = intrp.createThreadForSrc('async();').thread;\n  intrp.run();\n  // asyncThread has run once and blocked; bgThread has run ten times\n  // and is now sleeping for 1s.\n\n  // Create Error err to throw.  It should have no stack to start with.\n  const err = new intrp.Error(intrp.ROOT, intrp.ERROR, 'sample error');\n  t.assert(name + ': Error has no .stack initially',\n      !err.has('stack', intrp.ROOT));\n\n  // Throw err.\n  intrp.thread_ = bgThread;  // Try to trick reject into killing wrong thread.\n  reject(err);  // Throw unhandled Error in asyncThread.\n\n  // Verify correct thread was unwound and killed.\n  t.assert(name + ': unwound thread stack empty',\n      asyncThread.stateStack_.length === 0);\n  t.expect(name + ': unwound thread status',\n      asyncThread.status, Interpreter.Thread.Status.ZOMBIE);\n  t.assert(name + ': background thread stack non-empty',\n      bgThread.stateStack_.length > 0);\n  t.expect(name + ': background thread status',\n      bgThread.status, Interpreter.Thread.Status.SLEEPING);\n\n  // Verify err has aquired a stack.\n  t.assert(name + ': Error has .stack after being thrown',\n      err.has('stack', intrp.ROOT));\n  const stack = err.get('stack', intrp.ROOT);\n  t.assert(name + ': Error .stack mentions function that threw',\n      stack.match(/in async/));\n  t.assert(name + ': Error .stack mentions call site',\n      stack.match(/at \"async\\(\\);\" 1:1/));\n};\n\n/**\n * Run tests of the Thread constructor and the suspend(), setTimeout()\n * and clearTimeout() functions.\n * @param {!T} t The test runner object.\n */\nexports.testThreading = function(t) {\n  let src = `\n      'before';\n      suspend();\n      'after';\n  `;\n  runTest(t, 'suspend()', src, 'after');\n\n  // Check that Threads have ids.\n  src = `\n      var t1 = new Thread(function() {});\n      var t2 = new Thread(function() {});\n      typeof t1.id === 'number' && typeof t2.id === 'number' && t1.id !== t2.id;\n  `;\n  runSimpleTest(t, '(new Thread).id', src, true);\n\n  src = `\n      var s = '';\n      new Thread(function() {s += this;}, 500, 2);\n      new Thread(function(x) {s += x;}, 1500, undefined, [4]);\n      new Thread(function() {s += '1';})\n      suspend(1000);\n      s += '3';\n      suspend(1000);\n      s += '5';\n      s;\n  `;\n  runTest(t, 'new Thread', src, '12345');\n\n  src = `\n      var current;\n      var thread = new Thread(function() {current = Thread.current();});\n      suspend();\n      current === thread;\n  `;\n  runTest(t, 'Thread.current()', src, true);\n\n  src = `\n      var result;\n      new Thread(function() {\n        result = 'OK';\n        Thread.kill(Thread.current());\n        result = 'The reports of my death are greatly exaggerated.';\n      });\n      suspend();\n      result;\n  `;\n  runTest(t, 'Thread.kill', src, 'OK');\n\n  src = `\n      'before';\n      suspend(10000);\n      'after';\n  `;\n  runTest(t, 'suspend(1000)', src, 'after');\n\n  src = `\n      var s = '';\n      setTimeout(function(x) {s += '2';}, 500);\n      setTimeout(function(x) {s += '4';}, 1500);\n      s += '1';\n      suspend(1000);\n      s += '3';\n      suspend(1000);\n      s += '5';\n      s;\n  `;\n  runTest(t, 'setTimeout', src, '12345');\n\n  src = `\n      // Should have no effect:\n      clearTimeout('foo');\n      clearTimeout(Thread.current());\n\n      var s = '';\n      var tid = setTimeout(function(a, b) {\n          s += a;\n          suspend();\n          s += b;\n      }, 0, '2', '4');\n      s += 1;\n      suspend();\n      s += '3';\n      clearTimeout(tid);\n      suspend();\n      s += '5';\n      s;\n  `;\n  runTest(t, 'clearTimeout', src, '1235');\n};\n\n/**\n * Run tests of the Thread time-limit mechanism.\n * @param {!T} t The test runner object.\n */\nexports.testTimeLimit = function(t) {\n  // Some constants used by several tests in this section.  It should\n  // be the case that a for loop executing the specified number of\n  // iterations will take longer than the specified time limit, even\n  // if the body of the loop is empty.\n  //\n  // Ideally these should be very small values to ensure the tests\n  // run quickly, but in practice random delays (OS-level time\n  // slicing, GC and JIT delays, etc.) make make tests very flaky if\n  // these values are too small.\n  const iterations = 10000;\n  const timeLimit = 5;  // in ms.\n\n  // First check that a sufficiently slow loop will get timed out.\n  // (This also verifies the requirements on the iterations and\n  // timeLimit constants mentioned above.)\n  let name = 'Thread hits timeLimit';\n  let src = `\n      try {\n        for (var i = 0; i < ${iterations}; i++) {\n        }\n        \"Thread didn't time out\";  // Maybe increase iterations?\n      } catch (e) {\n        e.name + ': ' + e.message;  // Can't call String(e): we're out of time!\n      }\n  `;\n  runTest(t, name, src, 'RangeError: Thread ran too long', {\n    onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;},\n  });\n\n  // Now check that calling suspend() regularly will save the thread\n  // from timing out.\n  name = 'Thread can use suspend to avoid timeLimit';\n  src = `\n      try {\n        for (var i = 0; i < ${iterations}; i++) {\n          suspend();\n        }\n        \"Thread didn't time out\";\n      } catch (e) {\n        e.name + ': ' + e.message;  // Can't call String(e): we're out of time!\n      }\n  `;\n  runTest(t, name, src, \"Thread didn't time out\", {\n    onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;},\n  });\n\n  // Test we can't call anything after timing out.\n  name = \"Thread can't call after timeout\";\n  src = `\n      try {\n        try {\n          for (var i = 0; i < ${iterations}; i++) {\n          }\n          \"Thread didn't time out\";  // Maybe increase iterations?\n        } catch (e) {\n          String(e);\n          'Still able to call';\n        }\n      } catch (e) {\n        e.name + ': ' + e.message;  // Can't call String(e): we're out of time!\n      }\n  `;\n  runTest(t, name, src, 'RangeError: Thread ran too long', {\n    onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;},\n  });\n\n  // Test we can't call anything after timing out.\n  name = \"Thread can call suspend after timeout\";\n  src = `\n      try {\n        try {\n          for (var i = 0; i < ${iterations}; i++) {\n          }\n          \"Thread didn't time out\";  // Maybe increase iterations?\n        } catch (e) {\n          suspend();\n          'Still able to call suspend';\n        }\n      } catch (e) {\n        e.name + ': ' + e.message;  // Can't call String(e): we're out of time!\n      }\n  `;\n  runTest(t, name, src, 'Still able to call suspend', {\n    onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;},\n  });\n\n  // Test timeLimit is inherited by child Threads.\n  name = 'Threads inherit timeLimit from parent Thread';\n  src = `\n      var r;\n      setTimeout(function() {\n        try {\n          for (var i = 0; i < ${iterations}; i++) {\n          }\n          r = \"Thread didn't time out\";  // Maybe increase iterations?\n        } catch (e) {\n          r = e.name + ': ' + e.message;  // Can't call String(e).\n        }\n      });\n      suspend(1000000);  // Fortunately simulated time passes really quickly.\n      r;\n  `;\n  runTest(t, name, src, 'RangeError: Thread ran too long', {\n    onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;},\n  });\n};\n\n/**\n * Run a test of the .start() and .pause() methods on Interpreter\n * instances.  This is an async test because we use real (albeit\n * small) timeouts to make sure everything works as it ought to.\n * @param {!T} t The test runner object.\n */\nexports.testStartStop = async function(t) {\n  function snooze(ms) {\n    return new Promise(function(resolve, reject) {setTimeout(resolve, ms);});\n  }\n  const intrp = getInterpreter();\n  let name = 'testStart';\n  let src = `\n      var x = 0;\n      while (true) {\n        suspend(10);\n        x++;\n      };\n  `;\n  try {\n    // Garbage collection occuring during test can case flakiness.\n    gc();\n    intrp.start();\n    // .start() will create a zero-delay timeout to check for sleeping\n    // tasks to awaken.  Snooze briefly to allow it to run, after\n    // which there should be no outstanding timeouts.  This will\n    // ensure that we verify .createThreadForSrc() frobs .start() to get\n    // things going again.\n    await snooze(0);\n    intrp.createThreadForSrc(src);\n    await snooze(29);\n    intrp.pause();\n  } catch (e) {\n    t.crash(name, util.format('%s\\n%s', src, e.stack));\n    return;\n  } finally {\n    intrp.stop();\n  }\n  let r = intrp.getValueFromScope(intrp.global, 'x');\n  const expected = 2;\n  t.expect(name, r, 2, src + '\\n(after 29ms)');\n\n  // Check that .pause() actually paused execution.\n  name = 'testPause';\n  await snooze(10);\n  r = intrp.getValueFromScope(intrp.global, 'x');\n  t.expect(name, r, expected, src + '\\n(after 39ms)');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Tests: builtins\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Run some tests of the various constructors and their associated\n * literals and prototype objects.\n * @param {!T} t The test runner object.\n */\nexports.testClasses = function(t) {\n  const classes = {\n    Object: {\n      prototypeProto: 'null',\n      literal: '{}'\n    },\n    Function: {\n      prototypeType: 'function',\n      literal: 'function(){}'\n    },\n    Array: {\n      literal: '[]'\n    },\n    RegExp: {\n      prototypeClass: 'Object', // Was 'RegExp' in ES5.1.\n      literal: '/foo/'\n    },\n    Date: {\n      prototypeClass: 'Object', // Was 'RegExp' in ES5.1.\n      functionNotConstructor: true  // Date() doesn't construct.\n    },\n    Error: {},\n    EvalError: {\n      prototypeProto: 'Error.prototype',\n      class: 'Error'\n    },\n    RangeError: {\n      prototypeProto: 'Error.prototype',\n      class: 'Error'\n    },\n    ReferenceError: {\n      prototypeProto: 'Error.prototype',\n      class: 'Error'\n    },\n    SyntaxError: {\n      prototypeProto: 'Error.prototype',\n      class: 'Error'\n    },\n    TypeError: {\n      prototypeProto: 'Error.prototype',\n      class: 'Error'\n    },\n    URIError: {\n      prototypeProto: 'Error.prototype',\n      class: 'Error'\n    },\n    PermissionError: {\n      prototypeProto: 'Error.prototype',\n      class: 'Error'\n    },\n    Boolean: {\n      literal: 'false',\n      literalType: 'boolean',\n      noInstance: true,\n    },\n    Number: {\n      literal: '42',\n      literalType: 'number',\n      noInstance: true,\n    },\n    String: {\n      literal: '\"hello\"',\n      literalType: 'string',\n      noInstance: true,\n    },\n    WeakMap: {\n      prototypeClass: 'Object',\n      functionNotConstructor: true  // WeakMap() can't be called without new.\n    },\n  };\n  for (const c in classes) {\n    const tc = classes[c];\n    // Check constructor is a function:\n    let name = c + 'IsFunction';\n    let src = 'typeof ' + c + ';';\n    runSimpleTest(t, name, src, 'function');\n    // Check constructor's proto is Function.prototype\n    name = c + 'ProtoIsFunctionPrototype';\n    src = 'Object.getPrototypeOf(' + c + ') === Function.prototype;';\n    runSimpleTest(t, name, src, true);\n    // Check prototype is of correct type:\n    const prototypeType = (tc.prototypeType || 'object');\n    name = c + 'PrototypeIs' + prototypeType;\n    src = 'typeof ' + c + '.prototype;';\n    runSimpleTest(t, name, src, prototypeType);\n    // Check prototype has correct class:\n    const prototypeClass = (tc.prototypeClass || tc.class || c);\n    name = c + 'PrototypeClassIs' + prototypeClass;\n    src = 'Object.prototype.toString.apply(' + c + '.prototype);';\n    runSimpleTest(t, name, src, '[object ' + prototypeClass + ']');\n    // Check prototype has correct proto:\n    const prototypeProto = (tc.prototypeProto || 'Object.prototype');\n    name = c + 'PrototypeProtoIs' + prototypeProto;\n    src = 'Object.getPrototypeOf(' + c + '.prototype) === ' +\n        prototypeProto + ';';\n    runSimpleTest(t, name, src, true);\n    // Check prototype's .constructor is constructor:\n    name = c + 'PrototypeConstructorIs' + c;\n    src = c + '.prototype.constructor === ' + c + ';';\n    runSimpleTest(t, name, src, true);\n\n    const cls = tc.class || c;\n    if (!tc.noInstance) {\n      // Check instance's type:\n      name = c + 'InstanceIs' + prototypeType;\n      src = 'typeof (new ' + c + ');';\n      runSimpleTest(t, name, src, prototypeType);\n      // Check instance's proto:\n      name = c + 'InstancePrototypeIs' + c + 'Prototype';\n      src = 'Object.getPrototypeOf(new ' + c + ') === ' + c + '.prototype;';\n      runSimpleTest(t, name, src, true);\n      // Check instance's class:\n      name = c + 'InstanceClassIs' + cls;\n      src = 'Object.prototype.toString.apply(new ' + c + ');';\n      runSimpleTest(t, name, src, '[object ' + cls + ']');\n      // Check instance is instanceof its contructor:\n      name = c + 'InstanceIsInstanceof' + c;\n      src = '(new ' + c + ') instanceof ' + c + ';';\n      runSimpleTest(t, name, src, true);\n      if (!tc.functionNotConstructor) {\n        // Recheck instances when constructor called as function:\n        // Recheck instance's type:\n        name = c + 'ReturnIs' + prototypeType;\n        src = 'typeof ' + c + '();';\n        runSimpleTest(t, name, src, prototypeType);\n        // Recheck instance's proto:\n        name = c + 'ReturnPrototypeIs' + c + 'Prototype';\n        src = 'Object.getPrototypeOf(' + c + '()) === ' + c + '.prototype;';\n        runSimpleTest(t, name, src, true);\n        // Recheck instance's class:\n        name = c + 'ReturnClassIs' + cls;\n        src = 'Object.prototype.toString.apply(' + c + '());';\n        runSimpleTest(t, name, src, '[object ' + cls + ']');\n        // Recheck instance is instanceof its contructor:\n        name = c + 'ReturnIsInstanceof' + c;\n        src = c + '() instanceof ' + c + ';';\n        runSimpleTest(t, name, src, true);\n      }\n    }\n    if (tc.literal) {\n      // Check literal's type:\n      const literalType = (tc.literalType || prototypeType);\n      name = c + 'LiteralIs' + literalType;\n      src = 'typeof (' + tc.literal + ');';\n      runSimpleTest(t, name, src, literalType);\n      // Check literal's proto:\n      name = c + 'LiteralPrototypeIs' + c + 'Prototype';\n      src = 'Object.getPrototypeOf(' + tc.literal + ') === ' + c +\n          '.prototype;';\n      runSimpleTest(t, name, src, true);\n      // Check literal's class:\n      name = c + 'LiteralClassIs' + cls;\n      src = 'Object.prototype.toString.apply(' + tc.literal + ');';\n      runSimpleTest(t, name, src, '[object ' + cls + ']');\n      // Primitives can never be instances.\n      if (literalType === 'object' || literalType === 'function') {\n        // Check literal is instanceof its contructor.\n        name = c + 'LiteralIsInstanceof' + c;\n        src = '(' + tc.literal + ') instanceof ' + c + ';';\n        runSimpleTest(t, name, src, true);\n      }\n    }\n  }\n};\n\n/**\n * Run a test of multiple simultaneous calls to Array.prototype.join.\n * @param {!T} t The test runner object.\n */\nexports.testArrayPrototypeJoinParallelism = function(t) {\n  let src = `\n      // Make String() do a suspend(), to tend to cause multiple\n      // simultaneous .join() calls become badly interleved with each\n      // other.\n      String = function(value) {\n        suspend();\n        return (new 'String')(value);  // Call original.\n      };\n\n      var arr = [1, [2, [3, [4, 5]]]];\n      // Set up another Array.prototype.join traversing a subset of\n      // the same objects to screw with us.\n      new Thread(function() {arr[1].join();});\n      // Try to do the join anyway.\n      arr.join()\n  `;\n  runTest(t, 'Array.prototype.join parallel', src, '1,2,3,4,5');\n};\n\n/**\n * Run some tests of Number.toString(radix) with various different\n * radix arguments.\n * @param {!T} t The test runner object.\n */\nexports.testNumberToString = function(t) {\n  const cases = [\n    ['(42).toString()', '42'],\n    ['(42).toString(16)', '2a'],\n    //['(-42.4).toString(5)', '-132.2'], Node incorrectly reports '-132.144444'.\n    ['(42).toString(\"2\")', '101010'],\n    ['(-3.14).toString()', '-3.14'],\n    ['(999999999999999999999999999).toString()', '1e+27'],\n    ['(NaN).toString()', 'NaN'],\n    ['(Infinity).toString()', 'Infinity'],\n    ['(-Infinity).toString()', '-Infinity'],\n  ];\n  for (const tc of cases) {\n    const src = tc[0] + ';';\n    runSimpleTest(t, 'testNumberToString: ' + tc[0], src, tc[1]);\n  }\n};\n\n/**\n * Run tests of the server side of the networking subsystem\n * (connectionListen et al.)\n * @param {!T} t The test runner object.\n */\nexports.testServing = async function(t) {\n  // Run a test of connectionListen() and connectionUnlisten(), and\n  // of the server receiving data using the .receive and .end methods\n  // on a connection object.\n  let name = 'testServerInbound';\n  let src = `\n      var data = '', conn = {};\n      conn.onReceive = function(d) {\n        data += d;\n      };\n      conn.onEnd = function() {\n        CC.connectionClose(this);\n        CC.connectionUnlisten(8888);\n        resolve(data);\n      };\n      CC.connectionListen(8888, conn);\n      send();\n   `;\n  function createSend(intrp) {\n    intrp.global.createMutableBinding('send', intrp.createNativeFunction(\n        'send', function() {\n          // Send some data to server.\n          const client = net.createConnection({port: 8888}, function() {\n            client.write('foo');\n            client.write('bar');\n            client.end();\n          });\n        }));\n  };\n  await runAsyncTest(t, name, src, 'foobar', {\n    options: {noLog: ['net']},\n    onCreate: createSend\n  });\n\n  // Run a test of the connectionListen(), connectionUnlisten(),\n  // connectionWrite() and connectionClose functions.\n  name = 'testServerOutbound';\n  src = `\n      var conn = {};\n      conn.onConnect = function() {\n        CC.connectionWrite(this, 'foo');\n        CC.connectionWrite(this, 'bar');\n        CC.connectionClose(this);\n      };\n      CC.connectionListen(8888, conn);\n      resolve(receive());\n      CC.connectionUnlisten(8888);\n   `;\n  function createReceive(intrp) {\n    intrp.global.createMutableBinding('receive', new intrp.NativeFunction({\n      name: 'receive', length: 0,\n      call: function(intrp, thread, state, thisVal, args) {\n        let reply = '';\n        const rr = intrp.getResolveReject(thread, state);\n        // Receive some data from the server.\n        const client = net.createConnection({port: 8888}, function() {\n          client.on('data', function(data) {\n            reply += data;\n          });\n          client.on('end', function() {\n            rr.resolve(reply);\n          });\n          client.on('error', function() {\n            rr.reject();\n          });\n        });\n        return Interpreter.FunctionResult.Block;\n      }\n    }));\n  };\n  await runAsyncTest(t, name, src, 'foobar', {\n    options: {noLog: ['net']},\n    onCreate: createReceive,\n  });\n\n  // Check to make sure that connectionListen() throws if attempting\n  // to bind to an invalid port or rebind a port already in use.\n  name = 'testConnectionListenThrows';\n  const server = new net.Server();\n  server.listen(8887);\n  src = `\n      // Some invalid ports:\n      // * 8887 is in use by the above net.Server.\n      // * 8888 will be in-use by via previous connectionListen.\n      // * Others are not integers or are out-of-range.\n      var ports = ['foo', {}, -1, 80.8, 8887, 8888, 65536];\n      try {\n        CC.connectionListen(8888, {});\n        for (var i = 0; i < ports.length; i++) {\n          try {\n            CC.connectionListen(ports[i], {});\n            resolve('Unexpected success listening on port ' + ports[i]);\n          } catch (e) {\n            if (!(e instanceof Error)) {\n              resolve('threw non-Error value ' + String(e));\n            }\n          }\n        }\n      } finally {\n        CC.connectionUnlisten(8888);\n      }\n      resolve('OK');\n   `;\n  await runAsyncTest(t, name, src, 'OK', {options: {noLog: ['net']}});\n  server.close();\n\n  // Check to make sure that connectionUnlisten() throws if attempting\n  // to unbind an invalid or not / no longer bound port.\n  name = 'testConnectionUnlistenThrows';\n  src = `\n      var ports = ['foo', {}, -1, 22, 80.8, 4567, 8888, 65536];\n      CC.connectionListen(8888, {});\n      CC.connectionUnlisten(8888, {});\n      for (var i = 0; i < ports.length; i++) {\n        try {\n          CC.connectionUnlisten(ports[i], {});\n          resolve('Unexpected success unlistening on port ' + ports[i]);\n        } catch (e) {\n          if (!(e instanceof Error)) {\n            resolve('threw non-Error value ' + String(e));\n          }\n        }\n      }\n      resolve('OK');\n   `;\n  await runAsyncTest(t, name, src, 'OK', {options: {noLog: ['net']}});\n\n  // Check to make sure that connectionWrite() throws if attempting to\n  // write anything not a string or to anything not a connected\n  // object.\n  name = 'testConnectionWriteThrows';\n  src = `\n      var conn = {toString: function() {return 'an open connection';}};\n      conn.onConnect = function() {\n        var cases = [\n          {obj: undefined, data: 'fine'},\n          {obj: null, data: 'fine'},\n          {obj: 42, data: 'fine'},\n          {obj: true, data: 'fine'},\n          {obj: 'a string', data: 'fine'},\n          {obj: {/* not connected */}, data: 'fine'},\n          {obj: this, data: undefined},\n          {obj: this, data: null},\n          {obj: this, data: 42},\n          {obj: this, data: true},\n          {obj: this, data: {}},\n        ];\n        for (var tc, i = 0; (tc = cases[i]); i++) {\n          try {\n            CC.connectionWrite(tc.obj, tc.data);\n            resolve('Unexpected success writing ' + tc.data +\n                    ' to ' + String(tc.obj));\n          } catch (e) {\n            if (!(e instanceof TypeError)) {\n              resolve('threw non-TypeError value ' + String(e));\n            }\n          }\n        }\n        CC.connectionClose(this);\n        resolve('OK');\n      };\n      CC.connectionListen(8888, conn);\n      try {\n        receive();\n      } finally {\n        CC.connectionUnlisten(8888);\n      }\n   `;\n  await runAsyncTest(t, name, src, 'OK', {\n    options: {noLog: ['net']},\n    onCreate: createReceive,\n  });\n\n  // Run a test to make sure listening sockets survive the interpreter\n  // being paused and restarted.\n  name = 'testServerPauseStart';\n  src = `\n      var data = '', conn = {};\n      conn.onReceive = function(d) {\n        data += d;\n      };\n      conn.onEnd = function() {\n        CC.connectionClose(this);\n        CC.connectionUnlisten(8888);\n        resolve(data);\n      };\n      CC.connectionListen(8888, conn);\n      pause();\n      send();\n   `;\n  function createPauseAndSend(intrp) {\n    intrp.global.createMutableBinding('pause', intrp.createNativeFunction(\n        'pause', function() {\n          intrp.pause();\n          intrp.start();\n        }));\n    createSend(intrp);\n  };\n  await runAsyncTest(t, name, src, 'foobar', {\n    options: {noLog: ['net']},\n    onCreate: createPauseAndSend\n  });\n\n  // Run a test to make sure listening sockets are re-listened after\n  // the interpreter is stopped and restarted.\n  name = 'testServerStopStart';\n  src = `\n      var data = '', conn = {};\n      conn.onReceive = function(d) {\n        data += d;\n      };\n      conn.onEnd = function() {\n        CC.connectionClose(this);\n        CC.connectionUnlisten(8888);\n        resolve(data);\n      };\n      CC.connectionListen(8888, conn);\n      stop();\n      send();\n   `;\n  function createStopAndSend(intrp) {\n    intrp.global.createMutableBinding('stop', intrp.createNativeFunction(\n        'stop', function() {\n          intrp.stop();\n          intrp.start();\n        }));\n    createSend(intrp);\n  };\n  await runAsyncTest(t, name, src, 'foobar', {\n    options: {noLog: ['net']},\n    onCreate: createStopAndSend\n  });\n};\n\n/**\n * Run tests of the client side of the networking subsystem (xhr).\n * @param {!T} t The test runner object.\n */\nexports.testClient = async function(t) {\n  // Run test of the xhr() function using HTTP.\n  let name = 'testXhrHttp';\n  const httpTestServer = http.createServer(function (req, res) {\n    res.writeHead(200, {'Content-Type': 'text/plain'});\n    res.end('OK HTTP: ' + req.url);\n  }).listen(9980);\n  let src = `\n      try {\n        resolve(CC.xhr('http://localhost:9980/foo'));\n      } catch (e) {\n        reject(e);\n      }\n  `;\n  await runAsyncTest(t, name, src, 'OK HTTP: /foo',\n                     {options: {noLog: ['net']}});\n  httpTestServer.close();\n\n  // Run test of the xhr() function using HTTPS.\n  // TODO(cpcallen): Don't depend on external webserver.\n  name = 'testXhr';\n  src = `\n      try {\n        resolve(CC.xhr('https://neil.fraser.name/software/JS-Interpreter/' +\n            'demos/async.txt'));\n      } catch (e) {\n        reject(e);\n      }\n  `;\n  await runAsyncTest(t, name, src, 'It worked!\\n', {options: {noLog: ['net']}});\n};\n"
  },
  {
    "path": "server/tests/interpreter_unit_test.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Unit tests for internal functions of JavaScript interpreter.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst util = require('util');\n\nconst Interpreter = require('../interpreter');\nconst {T} = require('./testing');\n\n/**\n * Unit tests for Interpreter.toInteger, .toLength. and .toUint32\n * @param {!T} t The test runner object.\n */\nexports.testToIntegerEtc = function(t) {\n  const intrp = new Interpreter;\n  const cases = [\n    // [value, ToInteger(value), ToLength(value), ToUint32(value)]\n    [false, 0, 0, 0],\n    [true, 1, 1, 1],\n\n    [0, 0, 0, 0],\n    [-0, -0, 0, 0],\n    [1, 1, 1, 1],\n    [-1, -1, 0, 0xffffffff],\n    [0xfffffffe, 0xfffffffe, 0xfffffffe, 0xfffffffe],\n    [0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff],\n    [0x100000000, 0x100000000, 0x100000000, 0],\n    [4.5, 4, 4, 4],\n    [2**53-1, 2**53-1, 2**53-1, 0xffffffff],\n    [2**53, 2**53, 2**53-1, 0],\n    [Infinity, Infinity, 2**53-1, 0],\n    [-Infinity, -Infinity, 0, 0],\n    [NaN, 0, 0, 0],\n\n    ['0', 0, 0, 0],\n    ['-0', -0, 0, 0],\n    ['1', 1, 1, 1],\n    ['-1', -1, 0, 0xffffffff],\n    ['0xfffffffe', 0xfffffffe, 0xfffffffe, 0xfffffffe],\n    ['0xffffffff', 0xffffffff, 0xffffffff, 0xffffffff],\n    ['0x100000000', 0x100000000, 0x100000000, 0],\n    ['4294967294', 0xfffffffe, 0xfffffffe, 0xfffffffe],\n    ['4294967295', 0xffffffff, 0xffffffff, 0xffffffff],\n    ['4294967296',  0x100000000, 0x100000000, 0],\n    ['4.5', 4, 4, 4],\n    ['9007199254740991', 2**53-1, 2**53-1, 0xffffffff],\n    ['9007199254740992', 2**53, 2**53-1, 0],\n\n    ['hello', 0, 0, 0],\n    [null, 0, 0, 0],\n    [undefined, 0, 0, 0],\n    [new intrp.Array, 0, 0, 0],\n    [new intrp.Object, 0, 0, 0],\n  ];\n  const funcs =\n      [Interpreter.toInteger, Interpreter.toLength, Interpreter.toUint32];\n  for (const [input, ...expected] of cases) {\n    for (let i = 0; i < funcs.length; i++) {\n      const name =  util.format('%s(%o)', funcs[i].name, input);\n      t.expect(name, funcs[i](input), expected[i]);\n    }\n  }\n};\n\n/**\n * Unit tests for Interpreter.prototype.nativeToPseudo.\n * @param {!T} t The test runner object.\n */\nexports.testNativeToPseudo = function(t) {\n  const intrp = new Interpreter;\n\n  // Test handling of Arrays (including extra non-index properties).\n  const props = {0: 0, 1: 1, 2: 2, length: 3, extra: 4};\n  const arr = [];\n  for (const k in props) {\n    if (!props.hasOwnProperty(k)) continue;\n    arr[/** @type{?} */(k)] = props[k];\n  }\n  const pArr = intrp.nativeToPseudo(arr, intrp.ROOT);\n  for (const k in props) {\n    if (!props.hasOwnProperty(k)) continue;\n    const name = 'testNativeToPseudo(array)[\"' + k + '\"]';\n    const r = pArr.get(k, intrp.ROOT);\n    t.expect(name, r, props[k]);\n  }\n\n  // Test handling of Errors.\n  const cases = [\n    [Error, intrp.ERROR],\n    [EvalError, intrp.EVAL_ERROR],\n    [RangeError, intrp.RANGE_ERROR],\n    [ReferenceError, intrp.REFERENCE_ERROR],\n    [SyntaxError, intrp.SYNTAX_ERROR],\n    [TypeError, intrp.TYPE_ERROR],\n    [URIError, intrp.URI_ERROR],\n  ];\n  for (const [Err, proto] of cases) {\n    const name = 'testNativeToPseudo(' + Err.prototype.name + ')';\n    const errMessage = 'test ' + Err.prototype.name;\n    const error = Err(errMessage);\n    const pError = intrp.nativeToPseudo(error, intrp.ROOT);\n\n    t.expect(name + ' instanceof intrp.Error',\n        pError instanceof intrp.Error, true);\n    t.expect(name + '.proto', pError.proto, proto);\n    t.expect(name + '.message', pError.get('message', intrp.ROOT), errMessage);\n    t.expect(name + '.stack', pError.get('stack', intrp.ROOT), error.stack);\n  }\n};\n\n/**\n * Unit tests for Interpreter.Scope class.\n * @param {!T} t The test runner object.\n */\nexports.testScope = function(t) {\n  const intrp = new Interpreter;\n  const outer = new Interpreter.Scope(\n      Interpreter.Scope.Type.DUMMY, intrp.ROOT, null, 'this');\n  const inner = new Interpreter.Scope(\n      Interpreter.Scope.Type.DUMMY, intrp.ROOT, outer);\n\n  // 0: Initial condition.\n  t.expect(\"outer.this  // 0\", outer.this, 'this');\n  t.expect(\"inner.this  // 0\", inner.this, 'this');\n  t.expect(\"outer.hasBinding('foo')  // 0\", outer.hasBinding('foo'), false);\n  t.expect(\"outer.resolve('foo')  // 0\", outer.resolve('foo'), null);\n  t.expect(\"inner.resolve('foo')  // 0\", inner.resolve('foo'), null);\n\n  // 1: Create outer binding.\n  outer.createMutableBinding('foo', 42);\n  t.expect(\"outer.hasBinding('foo')  // 1\", outer.hasBinding('foo'), true);\n  t.expect(\"inner.hasBinding('foo')  // 1\", inner.hasBinding('foo'), false);\n  t.expect(\"outer.resolve('foo')  // 1\", outer.resolve('foo'), outer);\n  t.expect(\"inner.resolve('foo')  // 1\", inner.resolve('foo'), outer);\n  t.expect(\"outer.get('foo')  // 1\", outer.get('foo'), 42);\n  t.expect(\"getValueFromScope(outer, 'foo', ...)  // 1\",\n      intrp.getValueFromScope(outer, 'foo'), 42);\n  t.expect(\"getValueFromScope(inner, 'foo', ...)  // 1\",\n      intrp.getValueFromScope(inner, 'foo'), 42);\n\n  try {\n    outer.createMutableBinding('foo', 42);\n    t.fail(\"outer.createMutableBinding('foo', ...)  // 1\", \"Didn't throw.\");\n  } catch (e) {\n    t.pass(\"outer.createMutableBinding('foo', ...)  // 1\");\n  }\n\n  // 2: Set outer binding.\n  outer.set('foo', 69);\n  t.expect(\"outer.get('foo')  // 2\", outer.get('foo'), 69);\n  t.expect(\"getValueFromScope(inner, 'foo', ...)  // 2\",\n      intrp.getValueFromScope(inner, 'foo'), 69);\n  t.expect(\"getValueFromScope(outer, 'foo', ...)  // 2\",\n      intrp.getValueFromScope(outer, 'foo'), 69);\n\n  // 3: Create inner binding.\n  inner.createImmutableBinding('foo', 105);\n  t.expect(\"outer.hasBinding('foo')  // 3\", outer.hasBinding('foo'), true);\n  t.expect(\"inner.hasBinding('foo')  // 3\", inner.hasBinding('foo'), true);\n  t.expect(\"outer.resolve('foo')  // 3\", outer.resolve('foo'), outer);\n  t.expect(\"inner.resolve('foo')  // 3\", inner.resolve('foo'), inner);\n  t.expect(\"outer.get('foo')  // 3\", outer.get('foo'), 69);\n  t.expect(\"inner.get('foo')  // 3\", inner.get('foo'), 105);\n  t.expect(\"getValueFromScope(inner, 'foo', ...)  // 3\",\n      intrp.getValueFromScope(inner, 'foo'), 105);\n  t.expect(\"getValueFromScope(outer, 'foo', ...)  // 3\",\n      intrp.getValueFromScope(outer, 'foo'), 69);\n\n  // 4: Try to create duplicate binding.\n  try {\n    outer.createMutableBinding('foo', 17);\n    t.fail(\"outer.createMutableBinding('foo', ...)  // 4\", \"Didn't throw.\");\n  } catch (e) {\n    t.pass(\"outer.createMutableBinding('foo', ...)  // 4\");\n  }\n\n  // 5: Try to set immutable binding (two different ways)\n  t.assert(\"inner.set('foo', 37) instanceof TypeError\",\n           inner.set('foo', 37) instanceof TypeError);\n  try {\n    intrp.setValueToScope(inner, 'foo', 37);\n    t.fail(\"setValueToScope(inner, 'foo', 37, ...)  // 5\", \"Didn't throw.\");\n  } catch (e) {\n    t.pass(\"setValueToScope(inner, 'foo', 37, ...)  // 5\");\n  }\n};\n\n/**\n * Unit tests for Interpreter.Source class.\n * @param {!T} t The test runner object.\n */\nexports.testSource = function(t) {\n  let src = new Interpreter.Source('ABCDEF');\n  let name = \"Source('ABCDEF')\";\n\n  src = src.slice(0, 6);\n  t.expect(name + '.toString()', String(src), 'ABCDEF');\n\n  src = src.slice(1, 5);\n  name += '.slice(1, 5)';\n  t.expect(name + '.toString()', String(src), 'BCDE');\n\n  src = src.slice(2, 4);\n  name += '.slice(2, 4)';\n  t.expect(name + '.toString()', String(src), 'CD');\n\n  const s = '1\\n.2\\n..3\\n.4\\n5\\n';\n  const pos3 = s.indexOf('3');\n  src = new Interpreter.Source(s);\n  name = util.format('Source(%o)', s);\n  let lc = src.lineColForPos(pos3);\n  t.expect(name + '.lineColForPos(' + pos3 + ').line', lc.line, 3);\n  t.expect(name + '.lineColForPos(' + pos3 + ').col', lc.col, 3);\n\n  src = src.slice(2, 12);\n  name += '.slice(2, 12)';\n  lc = src.lineColForPos(pos3);\n  t.expect(name + '.lineColForPos(' + pos3 + ').line', lc.line, 2);\n  t.expect(name + '.lineColForPos(' + pos3 + ').col', lc.col, 3);\n\n  src = src.slice(2, 12);\n  name += '.slice(2, 12)';\n  lc = src.lineColForPos(pos3);\n  t.expect(name + '.toString()', String(src), '.2\\n..3\\n.4\\n');\n\n  t.expect(name + '.lineColForPos(' + pos3 + ').line', lc.line, 2);\n  t.expect(name + '.lineColForPos(' + pos3 + ').col', lc.col, 3);\n\n  src = new Interpreter.Source('startBound').slice(0, 5).slice(0, 0);\n  name = \"Source('startBound').slice(0, 5).slice(0, 0)\";\n  lc = src.lineColForPos(0);\n  t.expect(name + '.lineColForPos(0).line', lc.line, 1);\n  t.expect(name + '.lineColForPos(0).col', lc.line, 1);\n  t.expect(name + '.toString()', String(src), '');\n\n  src = new Interpreter.Source('endBound').slice(3, 8).slice(8, 8);\n  name = \"Source('endBound').slice(3, 8).slice(8, 8)\";\n  lc = src.lineColForPos(8);\n  t.expect(name + '.lineColForPos(8).line', lc.line, 1);\n  t.expect(name + '.lineColForPos(8).col', lc.line, 1);\n  t.expect(name + '.toString()', String(src), '');\n};\n"
  },
  {
    "path": "server/tests/iterable_weakmap_test.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test for IterableWeakMap.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst util = require('util');\n\nconst IterableWeakMap = require('../iterable_weakmap');\nconst {T} = require('./testing');\n\n/**\n * Request garbage collection and cycle the event loop to give\n * finalisers a chance to be run.  No guarantees about either,\n * unfortunately.\n * @return {!Promise<void>}\n */\nasync function gcAndFinalise() {\n  // Cycle event loop to allow finalisers to run.  Need to cycle it\n  // once before GC to ensure that WeakRefs can be cleared (their\n  // targets can never be cleared in the same turn as the WeakRef was\n  // created), then again after to allow finalisers to run.\n  await new Promise((res, rej) => setImmediate(res));\n  gc();\n  await new Promise((res, rej) => setImmediate(res));\n}\n  \n/**\n * Run some basic tests of IterableWeakMap.\n * @param {!T} t The test runner object.\n */\nexports.testIterableWeakMap = async function(t) {\n  const name = 'IterableWeakMap';\n\n  const assertSame = function(got, want, desc) {\n    t.expect(name + ': ' + desc, got, want);\n  };\n\n  assertSame(IterableWeakMap.prototype[Symbol.iterator],\n      IterableWeakMap.prototype.entries,\n      'prototype[Symbol.iterator] and prototype.entries are the same method');\n\n  const obj1 = {};\n  const obj2 = {};\n  const iwm = new IterableWeakMap([[obj1, 42], [obj2, 69]]);\n  (() => {\n    // Sequester obj3 in an IIFE, because just doing tmp = undefined\n    // to allow the object to be garbage collected seems to be\n    // insufficient.  (Presumably V8 optimises the assignment away.)\n    const obj3 = {};\n    assertSame(iwm.set(obj3, 105), iwm, 'iwm.set(tmp, 105)');\n    assertSame(iwm.get(obj3), 105, 'iwm.get(tmp)');\n    assertSame(Array.from(iwm.values()).reduce((x, y) => x + y), 42 + 69 + 105,\n        'sum of .values()');\n    let count = 0;\n    let sum = 0;\n    iwm.forEach((v, k, m) => {\n      assertSame(m, iwm, 'Map param in iwm.forEach callback');\n      count++;\n      sum += v;\n    });\n    assertSame(count, 3, 'Iterations in iwm.forEach callback');\n    assertSame(sum, 42 + 69 + 105, 'Sum of values in iwm.forEach callback');\n  })();\n  assertSame(iwm.get(obj1), 42, 'iwm.get(obj)');\n  assertSame(iwm.has(obj1), true, 'iwm.has(obj)');\n  assertSame(iwm.has({}), false, 'iwm.has({})');\n  assertSame(iwm.size, 3, 'iwm.size');\n\n  await gcAndFinalise();\n  \n  assertSame(iwm.has(obj1), true, 'iwm.has(obj) (after GC)');\n  assertSame(iwm.get(obj1), 42, 'iwm.get(obj) (after GC)');\n  assertSame(iwm.size, 2, 'iwm.size (after GC)');\n  const keys = Array.from(iwm.keys());\n  assertSame(keys.length, 2, 'Array.from(iwm.keys()).length');\n  assertSame(keys[0], obj1, 'Array.from(iwm.keys())[0]');\n  assertSame(keys[1], obj2, 'Array.from(iwm.keys())[1]');\n\n  assertSame(iwm.delete({}), false, 'iwm.delete({})');\n  assertSame(iwm.delete(obj2), true, 'iwm.delete(obj)');\n  assertSame(iwm.size, 1, 'iwm.size (after delete)');\n  const entries = Array.from(iwm);\n  assertSame(entries.length, 1, 'Array.from(iwm).length (after delete)');\n  assertSame(entries[0][0], obj1, 'Array.from(iwm)[0][0]');\n  assertSame(entries[0][1], 42, 'Array.from(iwm)[0][1]');\n\n  iwm.clear();\n  assertSame(iwm.has(obj1), false, 'iwm.has(obj) (after clear)');\n  assertSame(iwm.get(obj1), undefined, 'iwm.get(obj) (after clear)');\n  assertSame(iwm.size, 0, 'iwm.size (after clear)');\n};\n\n/**\n * Test for correct handling of cyclic garbage in IterableWeakMap.\n * @param {!T} t The test runner object.\n */\nexports.testIterableWeakMapCyclic = async function(t) {\n  const iwm = new IterableWeakMap;\n  (() => {\n    const objs = [{}, {}, {}];\n    iwm.set(objs[0], objs[0]);  // obj[0] is held circularly.\n    iwm.set(objs[1], objs[2]);  // obj[1] and [2] are held by each other.\n    iwm.set(objs[2], objs[1]);\n  })();\n  t.expect('IterableWeakMapCyclic: iwm.size (before GC)', iwm.size, 3);\n\n  await gcAndFinalise();\n\n  t.expect('IterableWeakMapCyclic: iwm.size (after GC)', iwm.size, 0);\n};\n\n/**\n * Test for layered collection of IterableWeakMap.\n *\n * When a WeakMap contains a chain of object (i.e., wm.get(o1) === o2,\n * wm.get(o2) === o3, etc.) all should simultaneously be eligible for\n * collection if the 'head' object becomes unreachable.  This test\n * will either pass (if that is true of IterableWeakMap) or issue a\n * warning if it takes several GCs to entierly empty the map.\n * @param {!T} t The test runner object.\n */\nexports.testIterableWeakMapLayeredGC = async function(t) {\n  /* N.B.: This test seems to be deterministic but very sensitive to\n   * seemingly insignificant code changes, which can (for no obvious\n   * reason, but probably due to some internal optimisations) result\n   * in the IterableWeakMap keys not being garbage collected at all.\n   *\n   * This can be difficult to debug, because e.g. adding a console.log\n   * call inside the loop that calls gc() will make the problem go\n   * away.\n   */\n  const name =  'IterableWeakMapLayeredGC';\n  const iwm = new IterableWeakMap;\n\n  // Make a chain of entries.\n  (() => {\n    const objs = [{}, {}, {}, {}, {}];\n    for (let i = 0; i < objs.length; i++) {\n      iwm.set(objs[i], objs[i + 1]);\n    }\n  })();\n\n  const limit = 10;  // objs.length * 2\n  let count = 0;\n  for (; count < limit && iwm.size > 0; count++) {\n    await gcAndFinalise();\n  }\n\n  if (count >= limit) {\n    t.fail(name, 'Test failed to terminate in a reasonable time.');\n  } else if (count > 1) {\n    t.result('WARN', name,\n             'IterableWeakMap causes layered GC! (' + count + ' iterations)');\n  } else {\n    t.pass(name);\n  }\n};\n"
  },
  {
    "path": "server/tests/iterable_weakset_test.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test for IterableWeakSet.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst util = require('util');\n\nconst IterableWeakSet = require('../iterable_weakset');\nconst {T} = require('./testing');\n\n/**\n * Request garbage collection and cycle the event loop to give\n * finalisers a chance to be run.  No guarantees about either,\n * unfortunately.\n * @return {!Promise<void>}\n */\nasync function gcAndFinalise() {\n  // Cycle event loop to allow finalisers to run.  Need to cycle it\n  // once before GC to ensure that WeakRefs can be cleared (their\n  // targets can never be cleared in the same turn as the WeakRef was\n  // created), then again after to allow finalisers to run.\n  await new Promise((res, rej) => setImmediate(res));\n  gc();\n  await new Promise((res, rej) => setImmediate(res));\n}\n\n/**\n * Run some basic tests of IterableWeakSet.\n * @param {!T} t The test runner object.\n */\nexports.testIterableWeakSet = async function(t) {\n  const name = 'IterableWeakSet';\n\n  const assertSame = function(got, want, desc) {\n    t.expect(name + ': ' + desc, got, want);\n  };\n\n  assertSame(IterableWeakSet.prototype[Symbol.iterator],\n      IterableWeakSet.prototype.values,\n      'prototype[Symbol.iterator] and prototype.values are the same method');\n  assertSame(IterableWeakSet.prototype.keys, IterableWeakSet.prototype.values,\n      'prototype.keys and prototype.values are the same method');\n\n  const obj1 = {x: 42};\n  const obj2 = {x: 69};\n  const iws = new IterableWeakSet([obj1, obj2]);\n  (() => {\n    // Sequester obj3 in an IIFE, because just doing tmp = undefined\n    // to allow the object to be garbage collected seems to be\n    // insufficient.  (Presumably V8 optimises the assignment away.)\n    const obj3 = {x: 105};\n    assertSame(iws.add(obj3), iws, 'iws.add(tmp)');\n    assertSame(iws.has(obj3), true, 'iws.has(tmp)');\n    assertSame(\n        Array.from(iws.values()).map((obj) => obj.x).toString(),\n        '42,69,105', '.x values from .values()');\n    let count = 0;\n    let sum = 0;\n    iws.forEach((v1, v2, s) => {\n      assertSame(v1, v2, 'value params in iws.forEach callback');\n      assertSame(s, iws, 'Set param in iws.forEach callback');\n      count++;\n      sum += v1.x;\n    });\n    assertSame(count, 3, 'Iterations in iws.forEach callback');\n    assertSame(sum, 42 + 69 + 105, 'Sum of .x values in iws.forEach callback');\n  })();\n  assertSame(iws.has(obj1), true, 'iws.has(obj)');\n  assertSame(iws.has({}), false, 'iws.has({})');\n  assertSame(iws.size, 3, 'iws.size');\n\n  await gcAndFinalise();\n\n  assertSame(iws.has(obj1), true, 'iws.has(obj) (after GC)');\n  assertSame(iws.size, 2, 'iws.size (after GC)');\n  const keys = Array.from(iws.keys());\n  assertSame(keys.length, 2, 'Array.from(iws.keys()).length');\n  assertSame(keys[0], obj1, 'Array.from(iws.keys())[0]');\n  assertSame(keys[1], obj2, 'Array.from(iws.keys())[1]');\n\n  assertSame(iws.delete({}), false, 'iws.delete({})');\n  assertSame(iws.delete(obj2), true, 'iws.delete(obj)');\n  assertSame(iws.size, 1, 'iws.size (after delete)');\n  const values = Array.from(iws);\n  assertSame(values.length, 1, 'Array.from(iws).length (after delete)');\n  assertSame(values[0], obj1, 'Array.from(iws)[0]');\n\n  iws.clear();\n  assertSame(iws.has(obj1), false, 'iws.has(obj) (after clear)');\n  assertSame(iws.size, 0, 'iws.size (after clear)');\n};\n"
  },
  {
    "path": "server/tests/priorityqueue_test.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Tests for PriorityQueue.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst util = require('util');\n\nconst PriorityQueue = require('../priorityqueue').PriorityQueue;\nconst {T} = require('./testing');\n\n// Unpack test-only functions.\nconst {parent, children} = require('../priorityqueue').testOnly;\n\n/**\n * Test the inernal parent() function.\n * @param {!T} t The test runner object.\n */\nexports.testParent = function(t) {\n  const cases = [\n    [0, -1],\n    [1, 0],\n    [2, 0],\n    [3, 1],\n    [4, 1],\n    [5, 2],\n    [6, 2],\n  ];\n  for (const [i, expected] of cases) {\n    t.expect(util.format('parent(%d)', i), parent(i), expected);\n  };\n};\n\n/**\n * Test the internal children() function.\n * @param {!T} t The test runner object.\n */\nexports.testChildren = function(t) {\n  const cases = [\n    [0, [1, 2]],\n    [1, [3, 4]],\n    [2, [5, 6]],\n  ];\n  for (const [i, [left, right]] of cases) {\n    const result = children(i);\n    t.expect(util.format('parent(%d)[0]', i), result[0], left);\n    t.expect(util.format('parent(%d)[0]', i), result[1], right);\n  };\n};\n\n/**\n * Check pq.heap_ and pq.indices_ obey their invariants.\n * @param {T} t The test runner object.\n * @param {!PriorityQueue} pq The PriorityQueue object to test the\n * invariants of.\n * @param {string=} note A textual description of the test situation.\n * @suppress {accessControls}\n */\nfunction checkInvariants(t, pq, note) {\n  if (note) note = ' // ' + note;\n  for (let i = 0; i < pq.heap_.length; i++) {\n    // Check heap ordering invariant.\n    const p = parent(i);\n    if (p >= 0) {\n      t.assert('PriorityQueue heap ordering invariant' + note,\n               pq.heap_[i].priority >= pq.heap_[p].priority,\n               util.format(\n                   '.heap_[%d].priority === %d, .heap_[%d].priority === %d',\n                   i, pq.heap_[i].priority, p, pq.heap_[p].priority) +\n                       util.format('\\n%o\\n', pq.heap_));\n    }\n    // Check index is correct for .heap_[i].value\n    t.expect(util.format('PriorityQueue: .indices_.get(.heap_[%d].value)%s',\n                         i, note),\n             pq.indices_.get(pq.heap_[i].value), i);\n  }\n  for (const [value, index] of pq.indices_) {\n    // Check value is correct for .indices_.get(v).\n    t.expect(util.format('PriorityQueue: .heap_[.indices_.get(%o)].value%s',\n                         value, note),\n             pq.heap_[index].value, value);\n  }\n  t.expect('PriorityQueue: .heap_.length (vs. .indices_.size)' + note,\n           pq.heap_.length, pq.indices_.size);\n};\n\n/**\n * Run some basic tests of PriorityQueue.\n * @param {!T} t The test runner object.\n */\nexports.testPriorityQueue = function(t) {\n  const name = 'PriorityQueue';\n  const pq = new PriorityQueue();\n\n  // Insert some values in a particular order, using value as priority.\n  for (const v of [2, 4, 6, 8, 10, 12, 14, 15, 13, 11, 9, 7, 5, 3, 1]) {\n    pq.set(v, v);\n    checkInvariants(t, pq, util.format('after .insert(%d, %d)', v, v));\n  }\n\n  // Remove three items.\n  for (let i = 1; i <= 3; i++) {\n    t.expect(name + ' .deleteMin() // ' + i, pq.deleteMin(), i);\n    t.expect(name + ' .length // ' + i, pq.length, 15 - i);\n    checkInvariants(t, pq, 'after .deleteMin #' + i);\n  }\n\n  // Reduce priority of 6 to 4.5.\n  pq.set(6, 4.5);\n  checkInvariants(t, pq, 'after .reducePriority(6, 4.5)');\n\n  // Remove next three items; verify order per changed priorities.\n  t.expect(name + ' .deleteMin() // 4', pq.deleteMin(), 4);\n  checkInvariants(t, pq, 'after .deleteMin #4');\n  t.expect(name + ' .deleteMin() // 5', pq.deleteMin(), 6);\n  checkInvariants(t, pq, 'after .deleteMin #5');\n  t.expect(name + ' .deleteMin() // 6', pq.deleteMin(), 5);\n  checkInvariants(t, pq, 'after .deleteMin #6');\n\n  // Remove remaining items.\n  for (let i = 7; i <= 15; i++) {\n    t.expect(name + ' .deleteMin() // ' + i, pq.deleteMin(), i);\n    t.expect(name + ' .length // ' + i, pq.length, 15 - i);\n    checkInvariants(t, pq, 'after .deleteMin #' + i);\n  }\n};\n"
  },
  {
    "path": "server/tests/registry_test.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Unit tests for the Registry class.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst Registry = require('../registry');\nconst {T} = require('./testing');\n\n/**\n * Unit tests for the Interpreter.Registry class.\n * @param {!T} t The test runner object.\n */\nexports.testRegistry = function(t) {\n  const reg = new Registry;\n  const obj = {};\n\n  // 0: Initial condition.\n  t.expect(\"reg.has('foo')  // 0\", reg.has('foo'), false);\n  try {\n    reg.get('foo');\n    t.fail(\"reg.get('foo')  // 0\", \"Didn't throw.\");\n  } catch(e) {\n    t.pass(\"reg.get('foo')  // 0\");\n  }\n  t.expect(\"reg.getKey(obj)  // 0\", reg.getKey(obj), undefined);\n  t.expect(\"reg.keys().length  // 0\", reg.keys().length, 0);\n\n  // 1: Register obj as 'foo'.\n  reg.set('foo', obj);\n  t.expect(\"reg.has('foo')  // 1\", reg.has('foo'), true);\n  t.expect(\"reg.get('foo')  // 1\", reg.get('foo'), obj);\n  t.expect(\"reg.getKey(obj)  // 1\", reg.getKey(obj), 'foo');\n  t.expect(\"reg.keys().length  // 1\", reg.keys().length, 1);\n  t.expect(\"reg.keys()[0]  // 1\", reg.keys()[0], 'foo');\n\n  // 2: Attempt to register another object as 'foo'.\n  try {\n    reg.set('foo', {});\n    t.fail(\"reg.set('foo', {})  // 2\", \"Didn't throw.\");\n  } catch(e) {\n    t.pass(\"reg.set('foo', {})  // 2\");\n  }\n  t.expect(\"reg.has('foo')  // 2\", reg.has('foo'), true);\n  t.expect(\"reg.get('foo')  // 2\", reg.get('foo'), obj);\n  t.expect(\"reg.getKey(obj)  // 2\", reg.getKey(obj), 'foo');\n  t.expect(\"reg.getKey({})  // 2\", reg.getKey({}), undefined);\n\n  // 3: Attempt to register obj as 'bar'.\n  try {\n    reg.set('bar', obj);\n    t.fail(\"reg.set('bar', obj)  // 3\", \"Didn't throw.\");\n  } catch(e) {\n    t.pass(\"reg.set('bar', obj)  // 3\");\n  }\n  t.expect(\"reg.has('bar')  // 3\", reg.has('bar'), false);\n  t.expect(\"reg.getKey(obj)  // 3\", reg.getKey(obj), 'foo');\n\n  // Test iterators.\n  // TODO(cpcallen): test with more than one item to iterate over?\n  const keys = reg.keys();\n  t.expect(\"reg.keys().length\", keys.length, 1);\n  t.expect(\"reg.keys()[0]\", keys[0], 'foo');\n\n  const values = reg.values();\n  t.expect(\"reg.values().length\", values.length, 1);\n  t.expect(\"reg.values()[0]\", values[0], obj);\n\n  const entries = reg.entries();\n  t.expect(\"reg.entries().length\", entries.length, 1);\n  t.expect(\"reg.entries()[0][0]\", entries[0][0], 'foo');\n  t.expect(\"reg.entries()[0][1]\", entries[0][1], obj);\n};\n"
  },
  {
    "path": "server/tests/run",
    "content": "#!/bin/bash\n\n# Run unit tests in Node.\nnode --expose-gc tests/run.js\n\n# Delete any existing checkpoint files.\nrm tests/db/*.city\n# Start Code City the first time.\necho \"Starting Code City (1 of 2)\"\n./codecity tests/db/test.cfg\necho \"Stopped Code City (1 of 2)\"\n# Start Code City the second time.\necho \"Starting Code City (2 of 2)\"\n./codecity tests/db/test.cfg\necho \"Stopped Code City (2 of 2)\"\n"
  },
  {
    "path": "server/tests/run.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test runner for server tests.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\n// Force closure-compiler to compile server and testst/benchmarks (for\n// syntax/type checking).  Server could be compiled separately but\n// it's faster to have do both in one run.  Tests and benchmark files\n// need to be enumerated explicitly because closure-compiler ignores\n// require statements with arguments that are not a string literal.\nconst compileTargets = [\n  require('../codecity'),\n  require('./code_test'),\n  require('./dump_test'),\n  require('./dumper_test'),\n  require('./interpreter_test'),\n  require('./interpreter_unit_test'),\n  require('./interpreter_test'),\n  require('./iterable_weakmap_test'),\n  require('./iterable_weakset_test'),\n  require('./registry_test'),\n  require('./priorityqueue_test'),\n  require('./selector_test'),\n  require('./serialize_test'),\n\n  require('./interpreter_bench'),\n  require('./serialize_bench'),\n];\n\n// Force compilation of tests/benchmarks (for synta\n\nconst fs = require('fs');\nconst {T, B} = require('./testing');\n\n/**\n * Run benchmarks.\n * @param {!Array} files Filenames containing benchmarks to run.\n */\nasync function runBenchmarks(files) {\n  for (var i = 0; i < files.length; i++) {\n    var benchmarks = require(files[i]);\n    var b = new B;\n    if (!compileTargets.includes(benchmarks)) {\n      b.result('WARN', files[i] + ' is not being checked by closure-compiler');\n    }\n    for (var k in benchmarks) {\n      if (k.startsWith('bench') && typeof benchmarks[k] === 'function') {\n        try {\n          await benchmarks[k](b);\n        } catch (e) {\n          b.crash(k, e);\n        }\n      }\n    }\n  }\n}\n\n/**\n * Run tests.\n * @param {!Array} files Filenames containing tests to run.\n */\nasync function runTests(files) {\n  var t = new T;\n\n  for (var i = 0; i < files.length; i++) {\n    var tests = require(files[i]);\n    if (!compileTargets.includes(tests)) {\n      t.result('WARN', files[i] + ' is not being checked by closure-compiler');\n    }\n    for (var k in tests) {\n      if (k.startsWith('test') && typeof tests[k] === 'function') {\n        try {\n          await tests[k](t);\n        } catch (e) {\n          t.crash(k, e);\n        }\n      }\n    }\n  }\n\n  // Print results summary.\n  console.log('\\n%s\\n', String(t));\n}\n\n/**\n * Get list of test filenames matching a particular regexp.\n * @param {!RegExp} pattern RegExp to match.\n * @return {!Array} List of filenames.\n */\nfunction getFiles(pattern) {\n  var f = fs.readdirSync(__dirname);  // __dirname is location of this module.\n  return f.filter(function (fn) { return pattern.test(fn); }).\n      map(function (fn) { return './' + fn; });\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Main program\n//\n\n(async function main() {\n  await runTests(getFiles(/_test.js$/));\n  await runBenchmarks(getFiles(/_bench.js$/));\n})();\n"
  },
  {
    "path": "server/tests/selector_test.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test for CSS-style selectors for JS objects.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst Selector = require('../selector');\nconst {T} = require('./testing');\nconst util = require('util');\n\n/**\n * Unit tests for Selector\n * @param {!T} t The test runner object.\n */\nexports.testSelector = function(t) {\n  const cases = [\n    // Test cases  of form [SS, [P1, P2, ...], tS, tE, tSE] where\n    // SS: selector string, to use as argument to Selector constructor,\n    // [Pn...]: expected parts array,\n    // tS: expected toString output,\n    // tE: expected toExpr output (can be omitted if same),\n    // tSE: expected toSetExpr output (if different not same + ' = NEW').\n\n    ['foo', ['foo'], 'foo'],\n\n    ['foo.bar', ['foo', 'bar'], 'foo.bar'],\n    ['foo[\"bar\"]', ['foo', 'bar'], 'foo.bar'],\n    [\"foo['bar']\", ['foo', 'bar'], 'foo.bar'],\n\n    ['foo[42]', ['foo', '42'], 'foo[42]'],\n    [\"foo['42']\", ['foo', '42'], 'foo[42]'],\n    ['foo[\"42\"]', ['foo', '42'], 'foo[42]'],\n\n    ['foo[\"bar baz\"]', ['foo', 'bar baz'], \"foo['bar baz']\"],\n    [\"foo['bar baz']\", ['foo', 'bar baz'], \"foo['bar baz']\"],\n\n    [\"foo['\\\"\\\\'\\\"']\", ['foo', '\"\\'\"'], \"foo['\\\"\\\\'\\\"']\"],\n    ['foo[\"\\'\\\\\"\\'\"]', ['foo', \"'\\\"'\"], 'foo[\"\\'\\\\\"\\'\"]'],\n    ['foo.bar.baz', ['foo', 'bar', 'baz'], 'foo.bar.baz'],\n    ['$._.__.$$', ['$', '_', '__', '$$'], '$._.__.$$'],\n    ['foo^', ['foo', Selector.PROTOTYPE], 'foo{proto}',\n        'Object.getPrototypeOf(foo)', 'Object.setPrototypeOf(foo, NEW)'],\n    ['foo{proto}.bar', ['foo', Selector.PROTOTYPE, 'bar'], 'foo{proto}.bar',\n        'Object.getPrototypeOf(foo).bar',\n        'Object.getPrototypeOf(foo).bar = NEW'],\n    ['foo{owner}', ['foo', Selector.OWNER], 'foo{owner}',\n        'Object.getOwnerOf(foo)', 'Object.setOwnerOf(foo, NEW)'],\n    ['foo{owner}.bar', ['foo', Selector.OWNER, 'bar'], 'foo{owner}.bar',\n        'Object.getOwnerOf(foo).bar',\n        'Object.getOwnerOf(foo).bar = NEW'],\n  ];\n  for (const [input, parts, str, expr, setExpr] of cases) {\n    // Do test with selector string.\n    let name = util.format('new Selector(%o)', input);\n    let s = new Selector(input);\n    t.expect(name + '.length', s.length, parts.length);\n    for (let i = 0; i < s.length; i++) {\n      t.expect(util.format('%s[%d]', name, i), s[i], parts[i]);\n    }\n    t.expect(name + '.toString()', s.toString(), str);\n    let expectedExpr = expr || str;\n    t.expect(name + '.toExpr()', s.toExpr(), expectedExpr);\n    let expectedSetExpr = setExpr || expectedExpr + ' = NEW';\n    t.expect(name + '.toSetExpr()', s.toSetExpr('NEW'), expectedSetExpr);\n\n    // Repeat test using parts array.\n    name = util.format('new Selector(%o)', parts);\n    s = new Selector(parts);\n    t.expect(name + '.toString()', s.toString(), str);\n    t.expect(name + '.toExpr()', s.toExpr(), expectedExpr);\n    t.expect(name + '.toSetExpr()', s.toSetExpr('NEW'), expectedSetExpr);\n  }\n\n  const invalidCases = [\n    '1foo',\n    'foo.',\n    'foo[\"bar]',\n    \"foo[bar']\",\n    'foo.[42]',\n    'foo[42',\n    'foo42]',\n    'foo[42}',\n    \"foo['\\\"'\\\"']\",\n    'foo[\"\\'\"\\'\"]',\n    'foo^bar',\n    '^.bar',\n    ['1foo'],\n    '^',\n    '{proto}',\n    [Selector.PROTOTYPE],\n    \"foo['bar'}\",\n    'foo{proto]',\n    'foo{proto',\n    'foo.proto}',\n    'foo{blah}',\n    'foo{}',\n    '{owner}',\n    [Selector.OWNER],\n  ];\n  for (const input of invalidCases) {\n    // Do test with selector string.\n    const name = util.format('new Selector(%o)', input);\n    try {\n      new Selector(input);\n      t.fail(name, \"didn't throw\");\n    } catch (e) {\n      t.pass(name);\n    }\n  }\n};\n\n/**\n * Unit tests for Selector.prototype.isVar / isProp / isProto\n * @param {!T} t The test runner object.\n */\nexports.testSelectorPrototypeIsWhatever = function(t) {\n  const cases = [\n    // Test cases  of form [selector, isVar].\n    ['foo', true, false, false, false],\n    ['foo.bar', false, true, false, false],\n    ['foo^', false, false, true, false],\n    ['foo{proto}', false, false, true, false],\n    ['foo{owner}', false, false, false, true],\n  ];\n  for (const [input, isVar, isProp, isProto, isOwner] of cases) {\n    const name = util.format('new Selector(%o)', input);\n    const s = new Selector(input);\n    t.expect(name + '.isVar()', s.isVar(), isVar);\n    t.expect(name + '.isProp()', s.isProp(), isProp);\n    t.expect(name + '.isProto()', s.isProto(), isProto);\n    t.expect(name + '.isOwner()', s.isOwner(), isOwner);\n  }\n};\n\n/**\n * Unit tests for Selector.partBadness\n * @param {!T} t The test runner object.\n */\nexports.testSelectorPartBadness = function(t) {\n  // Test verifies these are in monotonically increasing order of badness.\n  const cases = [\n    'bar',\n    'quux',\n    '10',\n    '100',\n    '&',\n    '&*',\n    'ridiculouslyLongIdentifier',\n    '2872498713723',\n    '#^@*%*!@#',\n    Selector.PROTOTYPE,\n  ];\n  let previous = '(no previous)';\n  let previousBadness = -Infinity;\n  for (const part of cases) {\n    const badness = Selector.partBadness(part);\n    const name = util.format(\n        'Selector.partBadness(%o) (===%d) < Selector.partBadness(%o) (===%d)',\n        previous, previousBadness, part, badness);\n    t.assert(name, previousBadness < badness);\n    previous = part;\n    previousBadness = badness;\n  }\n};\n\n/**\n * Unit tests for Selector.prototype.badness\n * @param {!T} t The test runner object.\n */\nexports.testSelectorPrototypeBadness = function(t) {\n  // Test verifies these are in monotonically increasing order of badness.\n  const cases = [\n    'foo',\n    'foobar',\n    'foo.bar',\n    'foo[10]',\n    'foo[\"&\"]',\n    'foo.bar.baz.quux.quuux.quuux',\n    'foo{proto}',\n    'foo.bar.baz.quux.quuux.quuux.quuuux.quuuuux.quuuuuux.quuuuuuux',\n  ];\n  let previous = '(no previous)';\n  let previousBadness = -Infinity;\n  for (const ss of cases) {\n    const s = new Selector(ss);\n    const badness = s.badness();\n    const name = util.format('Selector(%o).badness() < Selector(%o).badness()',\n                             previous, ss);\n    t.assert(name, previousBadness < badness);\n    previous = ss;\n    previousBadness = badness;\n  }\n};\n\n"
  },
  {
    "path": "server/tests/serialize_bench.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Benchmarks for JavaScript interpreter.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst util = require('util');\n\nconst Interpreter = require('../interpreter');\nconst {getInterpreter, startupFiles} = require('./interpreter_common');\nconst Serializer = require('../serialize');\n\n/**\n * Run a benchmark of the interpreter being serialized/deserialized.\n * @param {!B} b The benchmark runner object.\n * @param {string} name The name of the test.\n * @param {string} src The code to be evaled before roundtripping.\n * @param {function(!Interpreter)=} initFunc Optional function to be\n *     called after creating new interpreter instance but before\n *     running src.  Can be used to insert extra native functions into\n *     the interpreter.  initFunc is called with the interpreter\n *     instance to be configured as its parameter.\n */\nfunction runSerializationBench(b, name, src, initFunc) {\n  for (let i = 0; i < 4; i++) {\n    const intrp1 = new Interpreter();\n    const intrp2 = new Interpreter();\n    if (initFunc) {\n      initFunc(intrp1);\n      initFunc(intrp2);\n    }\n    const err = undefined;\n    try {\n      intrp1.createThreadForSrc(src);\n      intrp1.run();\n      intrp1.stop();\n      b.start(name, i);\n      let json = Serializer.serialize(intrp1);\n      b.end(name + ' serialize', i);\n      let str = JSON.stringify(json);\n      let len = str.length;\n      b.end(name + ' stringify (' + Math.ceil(len / 1024) + 'kiB)', i);\n      json = JSON.parse(str);\n      b.end(name + ' parse', i);\n      Serializer.deserialize(json, intrp2);\n      b.end(name + ' deserialize', i);\n    } catch (err) {\n      b.crash(name, util.format('%s\\n%s', src, err.stack));\n    }\n  }\n};\n\n/**\n * Run a benchmark of the interpreter being serialized/deserialized.\n * @param {!B} b The benchmark runner object.\n * @param {string} name The name of the test.\n * @param {string} src The code to be evaled before roundtripping.\n * @param {function(!Interpreter)=} initFunc Optional function to be\n *     called after creating new interpreter instance but before\n *     running src.  Can be used to insert extra native functions into\n *     the interpreter.  initFunc is called with the interpreter\n *     instance to be configured as its parameter.\n */\nfunction runDeserializationBench(b, name, src, initFunc) {\n  for (var i = 0; i < 4; i++) {\n    const intrp1 = new Interpreter();\n    const intrp2 = new Interpreter();\n    if (initFunc) {\n      initFunc(intrp1);\n      initFunc(intrp2);\n    }\n    const err = undefined;\n    try {\n      intrp1.createThreadForSrc(src);\n      intrp1.run();\n      intrp1.stop();\n      b.start(name, i);\n      const json = Serializer.serialize(intrp1);\n      var len = JSON.stringify(json).length;\n      Serializer.deserialize(json, intrp2);\n      b.end(name + ' (' + Math.ceil(len / 1024) + 'kiB)', i);\n    } catch (err) {\n      b.crash(name, util.format('%s\\n%s', src, err.stack));\n    }\n  }\n};\n\n/**\n * Run a benchmark of the interpreter after being\n * serialized/deserialized.\n * @param {!B} b The benchmark runner object.\n * @param {string} name The name of the test.\n * @param {string} src The code to be evaled.\n */\nfunction runInterpreterBench(b, name, src) {\n  for (let i = 0; i < 4; i++) {\n    const intrp1 = getInterpreter();\n    const intrp2 = new Interpreter();\n    try {\n      intrp1.createThreadForSrc(src);\n      intrp1.stop();\n      const json = Serializer.serialize(intrp1);\n      Serializer.deserialize(json, intrp2);\n      // Deserialized interpreter was stopped, but we want to be able to\n      // step/run it, so wake it up to PAUSED.\n      intrp2.pause();\n      b.start(name, i);\n      intrp2.run();\n      b.end(name, i);\n    } catch (err) {\n      b.crash(name, util.format('%s\\n%s', src, err.stack));\n    } finally {\n      intrp2.stop();\n    }\n  }\n};\n\n/**\n * Run benchmarks roundtripping the interpreter.\n * @param {!B} b The test runner object.\n */\nexports.benchRoundtrip = function(b) {\n  let name = 'Roundtrip demo';\n  const demoDir = path.join(__dirname, '../../core');\n  const filenames = fs.readdirSync(demoDir);\n  filenames.sort();\n  let src = '';\n  for (const filename of filenames) {\n    if (!(filename.match(/.js$/))) continue;\n    src += fs.readFileSync(String(path.join(demoDir, filename)));\n  }\n  const fakeBuiltins = function(intrp) {\n    // Hack to install stubs for builtins found in codecity.js.\n    const builtins = [\n      'CC.log', 'CC.checkpoint', 'CC.shutdown', 'CC.hash',\n      'CC.acorn.parse', 'CC.acorn.parseExpressionAt',\n    ];\n    for (const bi of builtins) {\n      new intrp.NativeFunction({id: bi, length: 0,});\n    }\n  };\n  runSerializationBench(b, name, src, fakeBuiltins);\n};\n\n/**\n * Run the fibbonacci10k benchmark.\n * @param {!B} b The test runner object.\n */\nexports.benchResurrectedFibbonacci10k = function(b) {\n  let name = 'ressurrectedFibonacci10k';\n  let src = `\n    var fibonacci = function(n, output) {\n      var a = 1, b = 1, sum;\n      for (var i = 0; i < n; i++) {\n        output.push(a);\n        sum = a + b;\n        a = b;\n        b = sum;\n      }\n    }\n    for(var i = 0; i < 10000; i++) {\n      var result = [];\n      fibonacci(78, result);\n    }\n    result;\n  `;\n  runInterpreterBench(b, name, src);\n};\n"
  },
  {
    "path": "server/tests/serialize_test.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Serialization/deserialization tests for JavaScript interpreter.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nconst net = require('net');\nconst util = require('util');\n\nconst Interpreter = require('../interpreter');\nconst {getInterpreter} = require('./interpreter_common');\nconst Serializer = require('../serialize');\nconst {T} = require('./testing');\n\n///////////////////////////////////////////////////////////////////////////////\n// Test helper functions.\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Serialize an interpreter to JSON, then create and return a new\n * interpreter by deserializing that JSON.\n * @param {!Interpreter} intrp The interpreter to be serialized.\n * @return {?Interpreter} the freshly deserialized interpreter, or\n *     null if an error occurred.\n */\nfunction roundTrip(intrp) {\n  intrp.pause();  // Save timer info.\n  const json = JSON.stringify(Serializer.serialize(intrp), null, '  ');\n\n  const intrp2 = new Interpreter;\n  Serializer.deserialize(JSON.parse(json), intrp2);\n  // Deserialized interpreter was stopped, but we want to be able to\n  // step/run it, so wake it up to PAUSED.\n  intrp2.pause();\n  return intrp2;\n}\n\n/**\n * Run a (possibly multiple) roundtrip test:\n * - Create an interpreter instance.\n * - Create a thread to eval src1, and run it to completion.\n * - Create a thread to eval src2\n * - Step through src2, periodically serializing and unserializing.\n * - Do a final round-trip serialization, if none done yet.\n * - Create a thread to eval src3, and run it to completion.\n * - Verify value of final expression evaluated is === expected.\n * @param {!T} t The test runner object.\n * @param {string} name The name of the test.\n * @param {string} src1 The code to be evaled before any serialization.\n * @param {string} src2 The code to be evaled while periodically serializing.\n * @param {string} src3 The code to be evaled after final serialization.\n * @param {number|string|boolean|null|undefined} expected The expected\n *     completion value.\n * @param {!TestOptions=} options Custom test options.\n */\nfunction runTest(t, name, src1, src2, src3, expected, options) {\n  options = options || {};\n  let intrp = getInterpreter(options.options, options.standardInit);\n  if (options.onCreate) {\n    options.onCreate(intrp);\n  }\n\n  let thread;\n  try {\n    if (src1) {\n      thread = intrp.createThreadForSrc(src1).thread;\n      intrp.run();\n    }\n  } catch (e) {\n    t.crash(name + 'Pre', e);\n    return;\n  }\n\n  try {\n    if (src2) {\n      thread = intrp.createThreadForSrc(src2).thread;\n    }\n    let trips = 0;\n    if (options.steps === undefined) {\n      intrp.run();\n    } else {\n      let s = 0;\n      while(intrp.step()) {\n        if ((++s % options.steps) === 0) {\n          intrp = roundTrip(intrp);\n          trips++;\n        }\n      }\n    }\n    if (trips === 0) {\n      intrp = roundTrip(intrp);\n      trips++;\n    }\n  } catch (e) {\n    t.crash(name, e);\n    return;\n  }\n\n  try {\n    intrp.run();\n    if (src3) {\n      thread = intrp.createThreadForSrc(src3).thread;\n      intrp.run();\n    }\n  } catch (e) {\n    t.crash(name + 'Post', e);\n    return;\n  }\n\n  const r = intrp.pseudoToNative(thread.value);\n  const allSrc = util.format(\n      '%s\\n/* begin roundtrips */\\n%s\\n/* end roundtrips */\\n%s',\n      src1, src2, src3);\n  t.expect(name, r, expected, allSrc);\n};\n\n/**\n * Run a (truly) asynchronous roundtrip test of the interpreter.\n * A new Interpreter instance is created for each test.  Special functions\n * resolve() and reject() are inserted in the global scope; they will\n * end each section of the test.  The caller can additionally supply a\n * callback to be run before starting the interpreter.\n *\n * Full procedure:\n * - Create and initialize an interpreter instance.\n * - Call options.onCreate, if supplied, on first interpreter instance.\n * - Start the interpreter and run src1 (if supplied).\n * - Await a call to resolve() or reject(); abort the test if the latter occurs.\n * - Stop the interpreter.\n * - Serialize interpreter to JSON.\n * - Create second interpreter instance.  Don't initialize it.\n * - Call options.onCreate, if supplied, on second interpreter instance.\n * - Deserialize JSON into second interpreter instance.\n * - Start the second interpreter and allow it to run to completion.\n * - Run src2 (if supplied).\n * - Await a call to resolve() or reject().\n * - If resolve was called, verify the result is as expected.\n * @param {!T} t The test runner object.\n * @param {string} name The name of the test.\n * @param {string} src1 The code to be evaled before serialization.\n * @param {string} src2 The code to be evaled after serialization.\n * @param {number|string|boolean|null|undefined} expected The expected\n *     completion value.\n * @param {!TestOptions=} options Custom test options.\n */\nasync function runAsyncTest(t, name, src1, src2, expected, options) {\n  options = options || {};\n  const intrp1 = getInterpreter(options.options, options.standardInit);\n  if (options.onCreate) {\n    options.onCreate(intrp1);\n  }\n\n  let thread;\n  // Create promise to signal completion of test from within\n  // interpreter.  Awaiting p will block until resolve or reject is\n  // called.\n  let resolve, reject, result;\n  let p = new Promise(function(res, rej) { resolve = res; reject = rej; });\n  intrp1.global.createMutableBinding(\n      'resolve', intrp1.createNativeFunction('resolve', resolve, false));\n  intrp1.global.createMutableBinding(\n      'reject', intrp1.createNativeFunction('reject', reject, false));\n\n  try {\n    intrp1.start();\n    if (src1) {\n      intrp1.createThreadForSrc(src1);\n    }\n    await p;\n    intrp1.pause();\n  } catch (e) {\n    t.crash(name + 'Pre', e);\n    return;\n  }\n\n  // Serialize.\n  let json;\n  try {\n    json = JSON.stringify(Serializer.serialize(intrp1), null, '  ');\n  } catch (e) {\n    t.crash(name + 'Serialize', e);\n    return;\n  }\n\n  intrp1.stop();\n\n  // Restore into new interpreter.\n  const intrp2 = getInterpreter(options.options, options.standardInit);\n  if (options.onCreate) {\n    options.onCreate(intrp2);\n  }\n\n  // New promise.\n  p = new Promise(function(res, rej) { resolve = res; reject = rej; });\n  intrp2.global.createMutableBinding(\n      'resolve', intrp2.createNativeFunction('resolve', resolve, false));\n  intrp2.global.createMutableBinding(\n      'reject', intrp2.createNativeFunction('reject', reject, false));\n\n  try {\n    Serializer.deserialize(JSON.parse(json), intrp2);\n  } catch (e) {\n    t.crash(name + 'Deserialize', e);\n    return;\n  }\n\n  try {\n    intrp2.start();\n    if (src2) {\n      intrp2.createThreadForSrc(src2);\n    }\n    result = await p;\n  } catch (e) {\n    t.crash(name + 'Post', e);\n    return;\n  } finally {\n    intrp2.stop();\n  }\n\n  const r = intrp2.pseudoToNative(result);\n  const allSrc = util.format('%s\\n/* roundtrip */\\n%s', src1, src2);\n  t.expect(name, r, expected, allSrc);\n};\n\n/**\n * Options for runTest and runAsyncTest.\n * @record\n */\nconst TestOptions = function() {};\n\n/**\n * Interpreter constructor options.\n * @type {!Interpreter.Options|undefined}\n */\nTestOptions.prototype.options;\n\n/**\n * Load the standard startup files at startup?  (Default: true.)\n * Setting to false speeds up tests with many roundtrips that do not\n * need builtins.\n * @type {boolean|undefined}\n */\nTestOptions.prototype.standardInit;\n\n/**\n * Callback to be called after creating new interpreter instance (and\n * running standard starup files, if not suppressed with standardInit:\n * false) but before creating a thread for srcN.  Can be used to\n * insert extra bindings into the global scope (e.g., to create\n * additional builtins).\n *\n * The first argument is the interpreter instance to be configured.\n *\n * @type {function(!Interpreter)|undefined}\n */\nTestOptions.prototype.onCreate;\n\n/**\n * How many steps to run between serializations (run src1 to\n * completion if unspecified).\n * @type {number|undefined}\n */\nTestOptions.prototype.steps;\n\n///////////////////////////////////////////////////////////////////////////////\n// Tests: serialisation\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Run a round trip serialization-deserialization.\n * @param {!T} t The test runner object.\n */\nexports.testRoundtripSimple = function(t) {\n  runTest(t, 'testRoundtripSimple', '', `\n      var x = 1;\n      for (var i = 0; i < 8; i++) {\n        x *= 2;\n      }\n  `, 'x;', 256, {steps: 100});\n};\n\n/**\n * Run a round trip of serializing the Interpreter.SCOPE_REFERENCE\n * sentinel and an Interpreter.PropertyIterator.\n *\n * BUG(#193): running this test causes *subsequent* benchmarks to run\n *     about 15% slower for no obvious reason.  Investigate.\n * @param {!T} t The test runner object.\n */\nexports.testRoundtripScopeRefAndPropIter = function(t) {\n  runTest(t, 'testRoundtripScopeRefAndPropIter', `\n      var r = 0, o = {a: 1, b: 2};\n  `,`\n      for (var k in o) {\n        r += o[k];\n      }\n  `, 'r;', 3, {steps: 1, standardInit: false});\n};\n\n/**\n * Run a round trip of serializing WeakMaps.\n * @param {!T} t The test runner object.\n */\nexports.testRoundtripWeakMap = function(t) {\n  runTest(t, 'testRoundtripWeakMap', `\n      var o1 = {};\n      var wm = new WeakMap;\n      var o2 = {};\n      wm.set(o1, 105);\n      wm.set(o2, 42);\n      var empty = new WeakMap;\n  `, '', `\n      (empty instanceof WeakMap) && (wm instanceof WeakMap) &&\n          wm.get(o1) - wm.get(o2);\n  `, 105 - 42);\n};\n\n/**\n * Run more detailed tests of the state of the post-rountrip interpreter.\n * @param {!T} t The test runner object.\n */\nexports.testRoundtripDetails = function(t) {\n  runTest(t, 'testRoundtripPropertyAttributes', `\n    var obj = {};\n    for (var i = 0; i < 8; i++) {\n      var desc = {value: i,\n                  writable: !!(i & 0x1),\n                  enumerable: !!(i & 0x2),\n                  configurable: !!(i & 0x4)};\n      Object.defineProperty(obj, i, desc);\n    }\n  `, '', `\n    for (var i = 0; i < 8; i++) {\n      desc = Object.getOwnPropertyDescriptor(obj, i);\n      if (desc.value !== i ||\n          desc.writable !== !!(i & 0x1) ||\n          desc.enumerable !== !!(i & 0x2) ||\n          desc.configurable !== !!(i & 0x4)) {\n        throw new Error('Roundtrip failure for property ' + i);\n      }\n    }\n    'All good';\n  `, 'All good');\n\n  runTest(t, 'testRoundtripObjectExtensibility', `\n    var ext = {};\n    var nonExt = {};\n    Object.preventExtensions(nonExt);\n  `, '', `\n    Object.isExtensible(ext) && !Object.isExtensible(nonExt);\n  `, true);\n\n  // Test preservation of prototype identity, including protypes used\n  // by various built-in functions.\n  //\n  // exprs is a large object literal which maps built-in constructors\n  // to arrays of values which should all be that constructor's\n  // .prototype object.\n  const exprs = `{\n        Object: [\n          Object.prototype,\n          new 'Object.prototype',\n          Object.getPrototypeOf(new Object),\n          Object.getPrototypeOf({}),\n          Object.getPrototypeOf(Object.getOwnPropertyDescriptor(\n            Object.prototype, 'constructor')),\n        ],\n        Function: [\n          Function.prototype,\n          new 'Function.prototype',\n          Object.getPrototypeOf(new Function),\n          Object.getPrototypeOf(function() {}),\n          Object.getPrototypeOf(Function),\n        ],\n        Array: [\n          Array.prototype,\n          new 'Array.prototype',\n          Object.getPrototypeOf(new Array),\n          Object.getPrototypeOf([]),\n          Object.getPrototypeOf([].slice(0,0)),\n        ],\n        Boolean: [\n          Boolean.prototype,\n          new 'Boolean.prototype',\n          Object.getPrototypeOf(false),\n        ],\n        Number: [\n          Number.prototype,\n          new 'Number.prototype',\n          Object.getPrototypeOf(0),\n        ],\n        String: [\n          String.prototype,\n          new 'String.prototype',\n          Object.getPrototypeOf(''),\n        ],\n        RegExp: [\n          RegExp.prototype,\n          new 'RegExp.prototype',\n          Object.getPrototypeOf(new RegExp),\n          Object.getPrototypeOf(/foo/),\n        ],${['Date', 'Error', 'EvalError', 'RangeError', 'SyntaxError',\n             'TypeError', 'URIError', 'PermissionError'].map((c) => `\n        ${c}: [\n          ${c}.prototype,\n          new '${c}.prototype',\n          Object.getPrototypeOf(new ${c}),\n        ],`).join('')}\n      }`;\n  runTest(t, 'testRoundtripBuiltinPrototypes', `\n      var pre = ${exprs};\n  `, '', `\n      var post = ${exprs};\n      try {\n        // Check expressions all had same value intially.\n        for (var key in pre) {\n          if (!pre.hasOwnProperty(key)) continue;\n          for (var i = 1; i < pre[key].length; i++) {\n            if (pre[key][0] !== pre[key][i]) {\n              throw 'pre[\"' + key + '\"][0] !== pre[\"' +\n                  key + '\"][' + i + ']';\n            }\n          }\n        }\n        // Check expressions all had same value before and after.\n        for (var key in pre) {\n          if (!pre.hasOwnProperty(key)) continue;\n          for (var i = 0; i < pre[key].length; i++) {\n            if (pre[key][i] !== post[key][i]) {\n              throw 'pre[\"' + key + '\"][' + i + '] !== post[\"' +\n                  key + '\"][' + i + ']';\n            }\n          }\n        }\n        'OK';\n      } catch (e) {\n        e;\n      }\n  `, 'OK');\n\n  runTest(t, 'testRoundtripArrayLengthRemainsMagical', `\n    var arr = [0, 1, 2];\n  `, '', `\n    arr[3] = 3;\n    arr.length;\n  `, 4);\n\n};\n\n/**\n * Run tests of post-roundtrip interpreter timers & networking state.\n * @param {!T} t The test runner object.\n */\nexports.testRoundtripAsync = async function(t) {\n  // Run a test of timer preservation during serialization/deserialization.\n  var name = 'testRestoreTimers';\n  var src1 = `\n      var x = '';\n      setTimeout(function() { x += '1'; }, 0);\n      setTimeout(function() { resolve(); }, 10);\n      setTimeout(function() { x += '3'; }, 20);\n      setTimeout(function() { x += '4'; }, 40);\n  `;\n  var src2 = `\n      x += '2';\n      setTimeout(function() { resolve(x); }, 11);\n  `;\n  await runAsyncTest(t, name, src1, src2, '123');\n\n  // Run a test of the server re-listening to sockets after being\n  // deserialized.\n  name = 'testPostRestoreNetworkInbound';\n  src1 = `\n      var data = '', conn = {};\n      conn.onReceive = function(d) {\n        data += d;\n      };\n      conn.onEnd = function() {\n        CC.connectionClose(this);\n        CC.connectionUnlisten(8888);\n        resolve(data);\n      };\n      CC.connectionListen(8888, conn);\n      resolve();\n   `;\n  src2 = `\n      send();\n   `;\n  const installSend = function(intrp) {\n    intrp.global.createMutableBinding('send', intrp.createNativeFunction(\n        'send', function() {\n          // Send some data to server.\n          var client = net.createConnection({ port: 8888 }, function() {\n            client.write('foo');\n            client.write('bar');\n            client.end();\n          });\n        }));\n  };\n  await runAsyncTest(t, name, src1, src2, 'foobar', {\n    options: {noLog: ['net']},\n    onCreate: installSend,\n  });\n\n  // Run a test to verify that the connection object's .error method\n  // is called with a suitable Error object if the previously-listened\n  // port is in use when the interpreter is restarted.\n  name = 'testFailedRelistenFiresError';\n  src1 = `\n      var connection = {onError: function(err) {resolve(err.name);}};\n      CC.connectionListen(8888, connection);\n      resolve();  // Start serialisation roundtrip.\n   `;\n  src2 = `\n      suspend();  // Allow pending onError thread to run.\n      resolve('No error thrown');\n  `;\n  let /** number */ count = 0;\n  let /** ?net.Server */ server = null;\n  const blockPort = function(intrp) {\n    if (count++) {  // Do only when creating post-roundtrip Interpreter.\n      server = new net.Server();\n      server.listen(8888);\n    }\n  };\n  await runAsyncTest(t, name, src1, src2, 'Error', {\n    options: {noLog: ['net']},\n    onCreate: blockPort,\n  });\n  server.close();\n};\n"
  },
  {
    "path": "server/tests/testcases.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Test cases for JavaScript interpreter.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\n// Testcases for testSimple in interpreter_test.js.\nmodule.exports = [\n  {src: `1 + 1;`, expected: 2},\n  {src: `2 + 2;`, expected: 4},\n  {src: `6 * 7;`, expected: 42},\n  {src: `(3 + 12 / 4) * (10 - 3);`, expected: 42},\n  {src: `var x = 43; x;`, expected: 43},\n  {src: `true ? 'then' : 'else';`, expected: 'then'},\n  {src: `false ? 'then' : 'else';`, expected: 'else'},\n  {\n    name: 'if(true)',\n    src: `\n      if (true) {\n        'then';\n      } else {\n        'else';\n      }\n    `,\n    expected: 'then',\n  },\n  {\n    name: 'if(false)',\n    src: `\n      if (false) {\n        'then';\n      } else {\n        'else';\n      }\n    `,\n    expected: 'else',\n  },\n  {\n    name: 'simpleAssignment',\n    src: `var x = 0; x = 44; x;`,\n    expected: 44,\n  },\n  {\n    name: 'propertyAssignment',\n    src: `var o = {}; o.foo = 45; o.foo;`,\n    expected: 45,\n  },\n  {\n    name: 'getPropertyOnPrimitive',\n    src: `'foo'.length;`,\n    expected: 3,\n  },\n  {\n    name: 'setPropertyOnPrimitive',\n    src: `\n      try {\n        'foo'.bar = 42;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {src: `var x = 45; x++; x++;`, expected: 46},\n  {src: `var x = 45; ++x; ++x;`, expected: 47},\n  {src: `'foo' + 'bar';`, expected: 'foobar'},\n  {\n    name: 'Effect of += on left argument',\n    src: `var x = 40, y = 8; x += y; x;`,\n    expected: 48,\n  },\n  {\n    name: 'Effect of += on right argument',\n    src: `var x = 40, y = 8; x += y; y;`,\n    expected: 8,\n  },\n  {\n    name: 'FunctionExpression',\n    src: `var v, f = function() {v = 49;}; f(); v;`,\n    expected: 49,\n  },\n  {\n    name: 'variable assignment sets anonymous function name',\n    src: `\n      var myAssignedFunc;\n      myAssignedFunc = function() {};\n      myAssignedFunc.name;\n    `,\n    expected: 'myAssignedFunc',\n  },\n  {\n    name: 'property assignment does not set anonymous FunctionExpression name',\n    src: `\n      var obj = {};\n      obj.myMethod = function() {};\n      obj.myMethod.name;\n    `,\n    expected: '',\n  },\n  {\n    // This one is a CodeCity extension.\n    name: 'property assignment optionally sets anonymous function name',\n    src: `\n      var obj = {};\n      obj.myMethod = function() {};\n      obj.myMethod.name;\n    `,\n    options: {methodNames: true},\n    expected: 'myMethod',\n  },\n  {\n    name: 'object expression sets anonymous FunctionExpression name',\n    src: `({myPropFunc: function() {}}).myPropFunc.name;`,\n    expected: 'myPropFunc',\n  },\n  {\n    name: 'variable declaration sets anonymous FunctionExpression name',\n    src: `var myVarDeclFunc = function() {}; myVarDeclFunc.name;`,\n    expected: 'myVarDeclFunc',\n  },\n  {\n    name: 'funExpWithParameter',\n    src: `var v; var f = function(x) {v = x;}; f(50); v;`,\n    expected: 50,\n  },\n  {\n    name: 'funExpParameterNotShadowedByVar',\n    src: `var f = function(x) {var x; return x;}; f(50.1);`,\n    expected: 50.1,\n  },\n  {\n    name: 'funExpParameterNotShadowedByVar',\n    src: `var f = function(x) {var x = 50.2; return x;}; f(50.2);`,\n    expected: 50.2,\n  },\n  {\n    name: 'functionWithReturn',\n    src: `(function(x) {return x;})(51);`,\n    expected: 51,\n  },\n  {\n    name: 'functionWithoutReturn',\n    src: `(function() {})();`,\n    expected: undefined,\n  },\n  {\n    name: 'multipleReturn',\n    src: `\n      var f = function() {\n        try {\n          return true;\n        } finally {\n          return false;\n        }\n      }\n      f();\n    `,\n    expected: false,\n  },\n  {\n    name: 'throwCatch',\n    src: `\n      var f = function() {\n        throw 26;\n      }\n      try {\n        f();\n      } catch (e) {\n        e * 2;\n      }\n    `,\n    expected: 52,\n  },\n  {\n    name: 'throwCatchFalsey',\n    src: `\n      try {\n        throw null;\n      } catch (e) {\n        'caught ' + String(e);\n      }\n    `,\n    expected: 'caught null',\n  },\n  // N.B.: This and next tests have no equivalent in the test DB.\n  {\n    name: 'throwUnhandledError',\n    src: `throw new Error('not caught');`,\n    options: {noLog: ['unhandled']},\n    expected: undefined,\n  },\n  {\n    name: 'throwUnhandledException',\n    src: `throw 'not caught';`,\n    options: {noLog: ['unhandled']},\n    expected: undefined,\n  },\n  {\n    src: `try {throw new Error('not caught');} finally {}`,\n    options: {noLog: ['unhandled']},\n    expected: undefined,\n  },\n  {\n    src: `try {throw 'not caught';} finally {}`,\n    options: {noLog: ['unhandled']},\n    expected: undefined,\n  },\n  {src: `51, 52, 53;`, expected: 53},\n  {\n    name: 'sequenceExpression',\n    src: `\n      var x, y, z;\n      x = (y = 60, z = 5, 0.5);\n      x + y + z;\n    `,\n    expected: 65.5,\n  },\n  {\n    name: 'labeledStatement',\n    src: `foo: 54;`,\n    expected: 54,\n  },\n  {\n    name: 'whileLoop',\n    src: `\n      var a = 0;\n      while (a < 55) a++;\n      a;\n    `,\n    expected: 55,\n  },\n  {\n    name: 'while(false)',\n    src: `\n      var a = 56;\n      while (false) a++;\n      a;\n    `,\n    expected: 56,\n  },\n  {\n    name: 'do ... while(false)',\n    src: `\n      var a = 56;\n      do a++; while (false);\n      a;\n    `,\n    expected: 57,\n  },\n  {\n    name: 'do ... break ... while',\n    src: `\n      var a = 57;\n      do {\n        a++;\n        break;\n        a++;\n      } while (false);\n      a;\n    `,\n    expected: 58,\n  },\n  {\n    src: `foo: break foo;`,\n    expected: undefined,  // (but legal!)\n  },\n  {\n    name: 'try ... break ... finally',\n    src: `\n      var a = 6;\n      foo: {\n        try {\n          a *= 10;\n          break foo;\n        } finally {\n          a--;\n        }\n      }\n      a;\n    `,\n    expected: 59,\n  },\n  {\n    name: 'do ... while with try ... continue ... finally ...',\n    src: `\n      var a = 59;\n      do {\n        try {\n          continue;\n        } finally {\n          a++;\n        }\n      } while (false);\n      a;\n    `,\n    expected: 60,\n  },\n  {\n    name: 'while with try ... break ... finally continue',\n    src: `\n      var a = 0;\n      while (a++ < 60) {\n        try {\n          break;\n        } finally {\n          continue;\n        }\n      }\n      a;\n    `,\n    expected: 61,\n  },\n  {\n    name: 'while with try ... return ... finally continue',\n    src: `\n      (function() {\n        var i = 0;\n        while (i++ < 61) {\n          try {\n            return 42;\n          } finally {\n            continue;\n          }\n        }\n        return i;\n      })();\n    `,\n    expected: 62,\n  },\n  {src: `63 || 'foo';`, expected: 63},\n  {src: `false || 64;`, expected: 64},\n  {\n    name: '|| short-circuit',\n    src: `var r = 0; true || (r++); r;`,\n    expected: 0,\n  },\n  {src: `({}) && 65;`, expected: 65},\n  {src: `0 && 65;`, expected: 0},\n  {\n    name: '&&  sort-circuit',\n    src: `var r = 0; false && (r++); r;`,\n    expected: 0,\n  },\n  {\n    name: 'for',\n    src: `\n      var t = 0;\n      for (var i = 0; i < 12; i++) {\n        t += i;\n      }\n      t;\n    `,\n    expected: 66,\n  },\n  {\n    name: 'forIn',\n    src: `\n      var x = 0, a = {a: 60, b:3, c:4};\n      for (var i in a) {x += a[i];}\n      x;\n    `,\n    expected: 67,\n  },\n  {\n    name: 'forInMemberExp',\n    src: `\n      var x = 1, o = {foo: 'bar'}, a = {a:2, b:2, c:17};\n      for (o.foo in a) {x *= a[o.foo];}\n      x;\n    `,\n    expected: 68,\n  },\n  {\n    name: 'forInMembFunc',\n    src: `\n      var x = 0, o = {};\n      var f = function() {x += 20; return o;};\n      var a = {a:2, b:3, c:4};\n      for (f().foo in a) {x += a[o.foo];}\n      x;\n    `,\n    expected: 69,\n  },\n  {\n    name: 'forInNullUndefined',\n    src: `\n      var x = 0, o = {};\n      var f = function() {x++; return o;};\n      for (f().foo in null) {x++;}\n      for (f().foo in undefined) {x++;}\n      x;\n    `,\n    expected: 0,\n  },\n  {\n    name: 'switchDefaultFirst',\n    src: `\n      switch ('not found') {\n        default:\n          'OK';\n          break;\n        case 'decoy':\n          'fail';\n      };\n    `,\n    expected: 'OK',\n  },\n  {\n    name: 'switchDefaultOnly',\n    src: `\n      switch ('not found') {\n        default:\n          'OK';\n      };\n    `,\n    expected: 'OK',\n  },\n  {\n    name: 'switchEmptyToEnd',\n    src: `\n      'ok';\n      switch ('foo') {\n        default:\n          'fail';\n        case 'foo':\n        case 'bar':\n      };\n    `,\n    expected: 'ok',\n  },\n  {\n    name: 'value of this in function call',\n    src: `\n      var f = function() {return this;};\n      f();\n    `,\n    expected: undefined,\n  },\n  {\n    name: 'value of this in method call',\n    src: `\n      var obj = {method: function() {return this;}};\n      obj.method() === obj;\n    `,\n    expected: true,\n  },\n  {\n    name: 'value of this in method called as function',\n    src: `\n      var obj = {method: function() {return this;}};\n      var f = obj.method;\n      f();\n    `,\n    expected: undefined,\n  },\n  {\n    name: 'value of this outside function body',\n    src: `this === undefined;`,\n    expected: true,\n  },\n  {\n    name: 'value of this not boxed (in strict mode)',\n    destructive: true,  // Modifies String.prototype!\n    src: `\n      String.prototype.method = function() {return typeof this;};\n      'a primitive string'.method();\n    `,\n    expected: 'string',  // Would be an [object String] in non-strict mode.\n  },\n  {src: `[].length;`, expected: 0},\n  {src: `[1,,3,,].length;`, expected: 4},\n  {\n    name: 'arrayElidedNotDefinedNotUndefined',\n    src: `\n      var a = [,undefined,null,0,false];\n      !(0 in a) && (1 in a) && (2 in a) && (3 in a) && (4 in a);\n    `,\n    expected: true,\n  },\n  {\n    name: 'arrayLengthPropertyDescriptor',\n    src: `\n      var a = [1, 2, 3];\n      var pd = Object.getOwnPropertyDescriptor(a, 'length');\n      (pd.value === 3) && pd.writable && !pd.enumerable && !pd.configurable;\n    `,\n    expected: true,\n  },\n  {\n    name: 'arrayLength',\n    src: `\n      try {\n        var a;\n        function checkLen(exp, desc) {\n          if (a.length !== exp) {\n            var msg = 'a.length === ' + a.length + ' (expected: ' + exp + ')'\n            throw new Error(desc ? msg + ' ' + desc : msg);\n          }\n        }\n        // Empty array has length == 0\n        a = [];\n        checkLen(0, 'on empty array');\n        // Adding non-numeric properties does not increase length:\n        a['zero'] = 0;\n        checkLen(0, 'after setting non-index property on []');\n        // Adding numeric properties >= length does increase length:\n        for (var i = 0; i < 5; i++) {\n          a[i] = i;\n          checkLen(i + 1, 'after setting a[' + i + ']');\n        }\n        // .length works propery even for large, sparse arrays, and even\n        // if values are undefined:\n        for (i = 3; i <= 31; i++) {\n          var idx = (1 << i) >>> 0;  // >>> 0 converts int32 to uint32\n          a[idx] = undefined;\n          checkLen(idx + 1, 'after setting a[' + idx + ']');\n        }\n        // Adding numeric properties < length does not increase length:\n        a[idx - 1] = 'not the largest';\n        checkLen(idx + 1, 'after setting non-largest element');\n        // Verify behaviour around largest possible index:\n        a[0xfffffffd] = null;\n        checkLen(0xfffffffe);\n        a[0xfffffffe] = null;\n        checkLen(0xffffffff);\n        a[0xffffffff] = null;  // Not an index.\n        checkLen(0xffffffff);  // Unchanged.\n        a[0x100000000] = null; // Not an index.\n        checkLen(0xffffffff);  // Unchanged.\n        function checkIdx(idx, exp, desc) {\n          var r = a.hasOwnProperty(idx);\n          if (r !== exp) {\n            var msg = 'a.hasOwnProperty(' + idx + ') === ' + r;\n            throw new Error(desc ? msg + ' ' + desc : msg);\n          }\n        }\n        // Setting length to existing value should have no effect:\n        a.length = 0xffffffff;\n        checkIdx(0xfffffffd, true);\n        checkIdx(0xfffffffe, true);\n        checkIdx(0xffffffff, true);\n        checkIdx(0x100000000, true);\n        // Setting length one less than maximum should remove largest\n        // index, but leave properties with keys too large to be indexes:\n        a.length = 0xfffffffe;\n        checkIdx(0xfffffffd, true);\n        checkIdx(0xfffffffe, false);\n        checkIdx(0xffffffff, true);\n        checkIdx(0x100000000, true);\n        // Setting length to zero should remove all index properties:\n        a.length = 0;\n        for (var key in a) {\n          if (!a.hasOwnProperty(key)) {\n            continue;\n          }\n          if (String(key >>> 0) === key && (key >>> 0) !== 0xffffffff) {\n            throw new Error(\n                'Setting a.length = 0 failed to remove property ' + key);\n          }\n        }\n        // Make sure we didn't wipe everything!\n        if (Object.getOwnPropertyNames(a).length !== 4) {\n          throw new Error(\n              'Setting .length == 0 removed some non-index properties');\n        }\n        'OK';\n      } catch (e) {\n        String(e);\n      }\n    `,\n    expected: 'OK',\n  },\n  {\n    name: 'arrayLengthWithNonWritableProps',\n    src: `\n      var a = [];\n      Object.defineProperty(a, 0,\n          {value: 'hi', writable: false, configurable: true});\n      a.length = 0;\n      a[0] === undefined && a.length === 0;\n    `,\n    expected: true,\n  },\n  {\n    name: 'arrayLengthWithNonConfigurableProps',\n    src: `\n      var a = [];\n      Object.defineProperty(a, 0,\n          {value: 'hi', writable: false, configurable: false});\n      try {\n        a.length = 0;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'compValEmptyBlock',\n    src: `{};`,\n    expected: undefined,\n  },\n  {src: `undefined;`, expected: undefined},\n  {\n    name: 'unaryVoid',\n    src: `var x = 70; (undefined === void x++) && x;`,\n    expected: 71,\n  },\n  {src: `+'72';`, expected: 72},\n  {src: `-73;`, expected: -73},\n  {src: `~0xffffffb5;`, expected: 74},\n  {src: `!false && (!true === false);`, expected: true},\n\n  {src: `typeof undefined;`, expected: 'undefined'},\n  {src: `typeof null;`, expected: 'object'},\n  {src: `typeof false;`, expected: 'boolean'},\n  {src: `typeof 0;`, expected: 'number'},\n  {src: `typeof '';`, expected: 'string'},\n  {src: `typeof {};`, expected: 'object'},\n  {src: `typeof [];`, expected: 'object'},\n  {src: `typeof function() {};`, expected: 'function'},\n  {\n    name: 'unaryTypeofUndeclared',\n    src: `\n      try {\n        typeof undeclaredVar;\n      } catch (e) {\n        'whoops!'\n      }\n    `,\n    expected: 'undefined',\n  },\n  {\n    name: 'binaryIn',\n    src: `var o = {foo: 'bar'}; 'foo' in o && !('bar' in o);`,\n    expected: true,\n  },\n  {\n    name: 'binaryInParent',\n    src: `\n      var p = {foo: 'bar'};\n      var o = Object.create(p);\n      'foo' in o && !('bar' in o);\n    `,\n    expected: true,\n  },\n  {src: `'length' in [];`, expected: true},\n  {\n    name: 'binaryInStringLength',\n    src: `\n      try {\n        'length' in '';\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'instanceofBasics',\n    src: `\n      function F(){}\n      var f = new F;\n      f instanceof F && f instanceof Object && !(f.prototype instanceof F);\n    `,\n    expected: true,\n  },\n  {\n    name: 'instanceofNonObjectLHS',\n    src: `\n      function F() {}\n      F.prototype = null;\n      42 instanceof F;\n    `,\n    expected: false,\n  },\n  {\n    name: 'instanceofNonFunctionRHS',\n    src: `\n      try {\n        ({}) instanceof 0;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'instanceofNonObjectPrototype',\n    src: `\n      function F() {};\n      F.prototype = 'hello';\n      try {\n        ({}) instanceof F;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'undefined.foo',\n    src: `\n      try {\n        undefined.foo;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'undefined.foo = ...',\n    src: `\n      try {\n        var c = 0;\n        undefined.foo = c++;\n      } catch (e) {\n        e.name + ',' + c;\n      }\n    `,\n    expected: 'TypeError,0',\n  },\n  {\n    name: 'null.foo',\n    src: `\n      try {\n        null.foo;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'null.foo = ...',\n    src: `\n      try {\n        var c = 0;\n        null.foo = c++;\n      } catch (e) {\n        e.name + ',' + c;\n      }\n    `,\n    expected: 'TypeError,0',\n  },\n  {\n    name: 'delete',\n    src: `\n      var o = {foo: 'bar'};\n      (delete o.quux) + ('foo' in o) + (delete o.foo) +\n          !('foo' in o) + (delete o.foo);\n    `,\n    expected: 5,\n  },\n  {\n    name: 'deleteNonexistentFromPrimitive',\n    src: `(delete false.nonexistent) && (delete (42).toString);`,\n    expected: true,\n  },\n  // This \"actually\" tries to delete the non-configurable own .length\n  // property from the auto-boxed String instance created by step 4a\n  // of algorithm in §11.4.1 of the ES 5.1 spec.  We have to use a\n  // string here, because only String instances have own properties\n  // (and yes: they are all non-configurable, so delete *always*\n  // fails).\n  {\n    name: 'deleteOwnFromPrimitive',\n    src: `\n      try {\n        delete 'hello'.length;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'funcDecl',\n    src: `\n      var v;\n      function f() {\n        v = 75;\n      }\n      f();\n      v;\n    `,\n    expected: 75,\n  },\n  {\n    name: 'namedFunctionExpression',\n    src: `\n      var f = function half(x) {\n        if (x < 100) {\n          return x;\n        }\n        return half(x / 2);\n      };\n      f(152)\n    `,\n    expected: 76,\n  },\n  {\n    name: 'namedFunExpNameBinding',\n    src: `var f = function foo() {return foo;}; f() === f;`,\n    expected: true,\n  },\n  {\n    name: 'namedFunExpNameBindingNoLeak',\n    src: `var f = function foo() {}; typeof foo;`,\n    expected: 'undefined',\n  },\n  {\n    name: 'namedFunExpNameBindingImmutable',\n    src: `\n      var f = function foo() {\n        try {\n          foo = null;\n        } catch (e) {\n          return e.name;\n        }\n      };\n      f();\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'namedFunExpNameBindingShadowedByParam',\n    src: `\n      var f = function foo(foo) {\n        foo += 0.1;  // Verify mutability.\n        return foo;\n      };\n      f(76);\n    `,\n    expected: 76.1,\n  },\n  {\n    name: 'namedFunExpNameBindingShadowedByVar',\n    src: `\n      var f = function foo() {\n        var foo;\n        foo = 76.2;  // Verify mutability.\n        return foo;\n      };\n      f();\n    `,\n    expected: 76.2,\n  },\n  {\n    name: 'closureIndependence',\n    src: `\n      function makeAdder(x) {\n        return function(y) {return x + y;};\n      }\n      var plus3 = makeAdder(3);\n      var plus4 = makeAdder(4);\n      plus3(plus4(70));\n    `,\n    expected: 77,\n  },\n  {\n    name: 'internalObjectToString',\n    src: `\n      var o = {};\n      o[{}] = null;\n      for(var key in o) {\n        key;\n      }\n    `,\n    expected: '[object Object]',\n  },\n  {\n    name: 'internalFunctionToString',\n    src: `\n      var o = {}, s, f = function(){};\n      o[f] = null;\n      for(var key in o) {\n        s = key;\n      }\n      /^function.*\\(.*\\).*{[^]*}$/.test(s);\n    `,\n    expected: true,\n  },\n  {\n    name: 'internalNativeFuncToString',\n    src: `\n      var o = {}, s, f = Object.create;\n      o[f] = null;\n      for(var key in o) {\n        s = key;\n      }\n      /^function.*\\(.*\\).*{[^]*}$/.test(s);\n    `,\n    expected: true,\n  },\n  {\n    name: 'internalArrayToString',\n    src: `\n      var o = {};\n      o[[1, 2, 3]] = null;\n      for(var key in o) {\n        key;\n      }\n    `,\n    expected: '1,2,3',\n  },\n  {\n    name: 'internalDateToString',\n    src: `\n      var o = {};\n      o[new Date(0)] = null;\n      for(var key in o) {\n        key;\n      }\n    `,\n    expected: (new Date(0)).toString(),\n  },\n  {\n    name: 'internalRegExpToString',\n    src: `\n      var o = {};\n      o[/foo/g] = null;\n      for(var key in o) {\n        key;\n      }\n    `,\n    expected: '/foo/g',\n  },\n  {\n    name: 'internalErrorToString',\n    src: `\n      var o = {};\n      o[Error('oops')] = null;\n      for(var key in o) {\n        key;\n      }\n    `,\n    expected: 'Error: oops',\n  },\n  {\n    name: 'internalArgumentsToString',\n    src: `\n      var o = {};\n      (function() {\n        o[arguments] = null;\n      })();\n      for(var key in o) {\n        key;\n      }\n    `,\n    expected: '[object Arguments]',\n  },\n  {src: `debugger;`, expected: undefined},\n  {\n    name: 'newExpression',\n    src: `\n      function T(x, y) {this.sum += x + y;};\n      T.prototype = {sum: 70}\n      var t = new T(7, 0.7);\n      t.sum;\n    `,\n    expected: 77.7,\n  },\n  {\n    name: 'newExpressionReturnObj',\n    src: `\n      function T() {return {};};\n      T.prototype = {p: 'the prototype'};\n      (new T).p;\n    `,\n    expected: undefined,\n  },\n  {\n    name: 'newExpressionReturnPrimitive',\n    src: `\n      function T() {return 0;};\n      T.prototype = {p: 'the prototype'};\n      (new T).p;\n    `,\n    expected: 'the prototype',\n  },\n  {src: `/foo/.test('foobar');`, expected: true},\n  {\n    name: 'evalSeeEnclosing',\n    src: `var n = 77.77; eval('n');`,\n    expected: 77.77,\n  },\n  {\n    name: 'evalIndirectNoSeeEnclosing',\n    src: `\n      (function() {\n        var n = 77.77, gEval = eval;\n        try {\n          gEval('n');\n        } catch (e) {\n          return e.name;\n        }\n      })();\n    `,\n    expected: 'ReferenceError',\n  },\n  {\n    name: 'evalIndirectNoSeeEnclosing2',\n    src: `\n      (function() {\n        var n = 77.77;\n        try {\n          (function() {return eval;})()('n');\n        } catch (e) {\n          return e.name;\n        }\n      })();\n    `,\n    expected: 'ReferenceError',\n  },\n  {\n    name: 'evalIndirectSeeGlobal',\n    src: `var gEval = eval; gEval('typeof Array');`,\n    expected: 'function',\n  },\n  {\n    name: 'evalModifyEnclosing',\n    src: `var n = 77.77; eval('n = 77.88'); n;`,\n    expected: 77.88,\n  },\n  {\n    name: 'evalNoLeakingDecls',\n    src: `eval('var n = 88.88'); typeof n;`,\n    expected: 'undefined',\n  },\n  // A bug in eval would cause it to return the value of the\n  // previously-evaluated ExpressionStatement if the eval program did\n  // not contain any ExpressionStatements.\n  {\n    name: 'evalEmptyBlock',\n    src: `'fail'; eval('{}');`,\n    expected: undefined,\n  },\n  {\n    name: 'callEvalOrder',\n    src: `\n      var r = '';\n      function log(x) {\n        r += x;\n        return function() {};\n      };\n      (log('f'))(log('a'), log('b'), log('c'));\n      r;\n    `,\n    expected: 'fabc',\n  },\n  {\n    name: 'callEvalArgsBeforeCallability',\n    src: `\n      try {\n        var invalid = undefined;\n        function t() {throw {name: 'args'};};\n        invalid(t());\n      } catch(e) {\n        e.name;\n      }\n    `,\n    expected: 'args',\n  },\n  {\n    name: 'callNonCallable',\n    src: `\n      var tests = [\n        undefined,\n        null,\n        false,\n        42,\n        'hello',\n        Object.create(Function.prototype),\n      ];\n      var ok = 0;\n      for (var i = 0; i < tests.length; i++) {\n        try {\n          tests[i]();\n        } catch (e) {\n          var r = e;\n          if (e.name === 'TypeError') {\n            ok++;\n          }\n        }\n      }\n      (ok === tests.length) ? 'pass' : 'fail';\n    `,\n    expected: 'pass',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Object and Object.prototype\n  {\n    name: 'Object.defineProperty()',\n    src: `\n      try {\n        Object.defineProperty();\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.defineProperty non-object',\n    src: `\n      try {\n        Object.defineProperty('not an object', 'foo', {});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.defineProperty bad descriptor',\n    src: `\n      var o = {};\n      try {\n        Object.defineProperty(o, 'foo', 'not an object');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  // This also tests iteration over (non-)enumerable properties.\n  {\n    name: 'Object.defineProperty',\n    src: `\n      var o = {foo: 50}, r = 0;\n      Object.defineProperty(o, 'bar', {\n        writable: true,\n        enumerable: true,\n        configurable: true,\n        value: 0\n      });\n      o.bar = 20;\n      Object.defineProperty(o, 'baz', {\n        writable: true,\n        enumerable: true,\n        configurable: false\n      });\n      Object.defineProperty(o, 'baz', {\n        value: 4,\n      });\n      Object.defineProperty(o, 'quux', {\n        enumerable: false,\n        value: 13\n      });\n      for (var k in o) {\n        r += o[k];\n      }\n      r += Object.getOwnPropertyNames(o).length;\n      r;\n    `,\n    expected: 78,\n  },\n  {\n    name: 'Object.getPrototypeOf(null) and undefined',\n    src: `\n      var r = '', prims = [null, undefined];\n      for (var i = 0; i < prims.length; i++) {\n        try {\n          Object.getPrototypeOf(prims[i]);\n        } catch (e) {\n          r += e.name;\n        }\n      }\n      r;\n    `,\n    expected: 'TypeErrorTypeError',\n  },\n  // This tests for ES6 behaviour:\n  {\n    name: 'Object.getPrototypeOf primitives',\n    src: `\n      Object.getPrototypeOf(true) === Boolean.prototype &&\n      Object.getPrototypeOf(1337) === Number.prototype &&\n      Object.getPrototypeOf('hi') === String.prototype;\n    `,\n    expected: true,\n  },\n  {\n    name: 'Object.setPrototypeOf(null, ...) and undefined',\n    src: `\n      var r = '', prims = [null, undefined];\n      for (var i = 0; i < prims.length; i++) {\n        try {\n          Object.setPrototypeOf(prims[i], null);\n        } catch (e) {\n          r += e.name;\n        }\n      }\n      r;\n    `,\n    expected: 'TypeErrorTypeError',\n  },\n  {\n    name: 'Object.setPrototypeOf primitives',\n    src: `\n      Object.setPrototypeOf(true, null) === true &&\n      Object.setPrototypeOf(1337, null) === 1337 &&\n      Object.setPrototypeOf('hi', null) === 'hi';\n    `,\n    expected: true,\n  },\n  {\n    name: 'Object.setPrototypeOf',\n    src: `\n      var o = {parent: 'o'};\n      var p = {parent: 'p'};\n      var q = Object.create(o);\n      Object.setPrototypeOf(q, p) === q &&\n          Object.getPrototypeOf(q) === p && q.parent;\n    `,\n    expected: 'p',\n  },\n  {\n    name: 'Object.setPrototypeOf(..., null)',\n    src: `\n      var o = {parent: 'o'};\n      var q = Object.create(o);\n      Object.setPrototypeOf(q, null) === q && Object.getPrototypeOf(q);\n    `,\n    expected: null,\n  },\n  {\n    name: 'Object.setPrototypeOf circular',\n    src: `\n      var o = {};\n      var p = Object.create(o);\n      try {\n        Object.setPrototypeOf(o, p);\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.create()',\n    src: `\n      try {\n        Object.create();\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.create non-object prototype',\n    src: `\n      try {\n        Object.create(42);\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.create(null) prototype',\n    src: `Object.getPrototypeOf(Object.create(null));`,\n    expected: null,\n  },\n  {\n    name: 'Object.create',\n    src: `\n      var o = Object.create({foo: 79});\n      delete o.foo\n      o.foo;\n    `,\n    expected: 79,\n  },\n  {\n    name: 'Object.getOwnPropertyDescriptor()',\n    src: `\n      try {\n        Object.getOwnPropertyDescriptor();\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.getOwnPropertyDescriptor non-object',\n    src: `\n      try {\n        Object.getOwnPropertyDescriptor('not an object', 'foo');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.getOwnPropertyDescriptor bad key',\n    src: `Object.getOwnPropertyDescriptor({}, 'foo');`,\n    expected: undefined,\n  },\n  {\n    name: 'Object.getOwnPropertyDescriptor',\n    src: `\n      var o = {}, r = 0;\n      Object.defineProperty(o, 'foo', {value: 'bar'});\n      var desc = Object.getOwnPropertyDescriptor(o, 'foo');\n      desc.value === o.foo &&\n          !desc.writable && !desc.enumerable && !desc.configurable;\n    `,\n    expected: true,\n  },\n  {\n    name: 'Object.getOwnPropertyNames()',\n    src: `\n      try {\n        Object.getOwnPropertyNames();\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.getOwnPropertyNames string',\n    src: `\n      var i, r = 0, names = Object.getOwnPropertyNames('foo');\n      for (i = 0; i < names.length; i++) {\n        if (names[i] === 'length') {\n          r += 10;\n        } else {\n          r += Number(names[i]) + 1;\n        }\n      }\n    `,\n    expected: 16,\n  },\n  {src: `Object.getOwnPropertyNames(42).length`, expected: 0},\n  {src: `Object.getOwnPropertyNames(true).length`, expected: 0},\n  {\n    name: 'Object.getOwnPropertyNames(null)',\n    src: `\n      try {\n        Object.getOwnPropertyNames(null).length;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.getOwnPropertyNames(undefined)',\n    src: `\n      try {\n        Object.getOwnPropertyNames(undefined).length;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.getOwnPropertyNames',\n    src: `\n      var o = Object.create({baz: 999});\n      o.foo = 42;\n      Object.defineProperty(o, 'bar', {value: 38});\n      var keys = Object.getOwnPropertyNames(o);\n      var r = 0;\n      for (var i = 0; i < keys.length; i++) {\n        r += o[keys[i]];\n      }\n      r;\n    `,\n    expected: 80,\n  },\n  {\n    name: 'Object.defineProperties()',\n    src: `\n      try {\n        Object.defineProperties();\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.defineProperties non-object',\n    src: `\n      try {\n        Object.defineProperties('not an object', {});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.defineProperties non-object props',\n    src: `\n      try {\n        Object.defineProperties({}, undefined);\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.defineProperties bad descriptor',\n    src: `\n      var o = {};\n      try {\n        Object.defineProperties(o, {foo: 'not an object'});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.defineProperties',\n    src: `\n      var o = {foo: 70}, r = 0;\n      Object.defineProperties(o, {\n          bar: {\n              writable: true,\n              enumerable: true,\n              configurable: true,\n              value: 8 },\n          baz: {value: 999}});\n      for (var k in o) {\n        r += o[k];\n      }\n      r + Object.getOwnPropertyNames(o).length;\n    `,\n    expected: 81,\n  },\n  {\n    name: 'Object.create(..., properties)',\n    src: `\n      var o = Object.create({foo: 70}, {\n          bar: {\n              writable: true,\n              enumerable: true,\n              configurable: true,\n              value: 10 },\n          baz: {value: 999}});\n      var r = 0;\n      for (var k in o) {\n        r += o[k];\n      }\n      r + Object.getOwnPropertyNames(o).length;\n    `,\n    expected: 82,\n  },\n  {\n    name: 'Object.assign',\n    src: `\n      var p = {x: 'inherited enumerable', y: 'inherited nonenumerable'};\n      var o = Object.create(p);\n      o.a = 'own enumerable';\n      o.b = 'own nonenumerable';\n      o.c = 'own enumerable';\n      Object.defineProperty(p, 'y', {enumerable: false});\n      Object.defineProperty(o, 'b', {enumerable: false});\n\n      var t = {a: 'to be overwritten', b: 'not overwritten', d: 'preserved'};\n\n      Object.assign(t, o, {e: 'extra'});\n      [Object.getOwnPropertyNames(t).length,\n       t.a, t.b, t.c, t.d, t.e].toString();\n    `,\n    expected:\n      '5,own enumerable,not overwritten,own enumerable,preserved,extra',\n  },\n  {\n    name: 'Object.getOwnPropertyNames',\n    src: `\n      var p = {x: 'inherited enumerable', y: 'inherited nonenumerable'};\n      var o = Object.create(p);\n      o.a = 'own enumerable';\n      o.b = 'own nonenumerable';\n      o.c = 'own enumerable';\n      Object.defineProperty(p, 'y', {enumerable: false});\n      Object.defineProperty(o, 'b', {enumerable: false});\n      Object.getOwnPropertyNames(o).toString();\n    `,\n    expected: 'a,b,c',\n  },\n  {\n    name: 'Object.keys',\n    src: `\n      var p = {x: 'inherited enumerable', y: 'inherited nonenumerable'};\n      var o = Object.create(p);\n      o.a = 'own enumerable';\n      o.b = 'own nonenumerable';\n      o.c = 'own enumerable';\n      Object.defineProperty(p, 'y', {enumerable: false});\n      Object.defineProperty(o, 'b', {enumerable: false});\n      Object.keys(o).toString();\n    `,\n    expected: 'a,c',\n  },\n  {\n    name: 'Object.prototype.toString',\n    src: `({}).toString();`,\n    expected: '[object Object]',\n  },\n  {\n    name: 'Object.protoype.hasOwnProperty',\n    src: `\n      var o = Object.create({baz: 999});\n      o.foo = 42;\n      Object.defineProperty(o, 'bar', {value: 41, enumerable: true});\n      var r = 0;\n      for (var key in o) {\n        if (!o.hasOwnProperty(key)) continue;\n        r += o[key];\n      }\n      r;\n    `,\n    expected: 83,\n  },\n  {\n    name: 'Object.protoype.isPrototypeOf primitives',\n    src: `\n      Boolean.prototype.isPrototypeOf(false) ||\n      Number.prototype.isPrototypeOf(0) ||\n      String.prototype.isPrototypeOf('') ||\n      Object.prototype.isPrototypeOf.call(false, false) ||\n      Object.prototype.isPrototypeOf.call(0, 0) ||\n      Object.prototype.isPrototypeOf.call('', '') ||\n      Object.prototype.isPrototypeOf.call(null, null) ||\n      Object.prototype.isPrototypeOf.call(undefined, undefined);\n    `,\n    expected: false,\n  },\n  {\n    name: 'Object.protoype.isPrototypeOf.call(null, ...)',\n    src: `\n      try {\n        Object.prototype.isPrototypeOf.call(null, Object.create(null));\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.protoype.isPrototypeOf.call(undefined, ...)',\n    src: `\n      try {\n        Object.prototype.isPrototypeOf\n          .call(undefined, Object.create(undefined));\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.protoype.isPrototypeOf self',\n    src: `var o = {}; o.isPrototypeOf(o);`,\n    expected: false,\n  },\n  {src: `Object.prototype.isPrototypeOf(Object.create(null))`, expected: false},\n  {\n    name: 'Object.protoype.isPrototypeOf related',\n    src: `\n      var g = {};\n      var p = Object.create(g);\n      var o = Object.create(p);\n      !o.isPrototypeOf({}) &&\n      g.isPrototypeOf(o) && p.isPrototypeOf(o) &&\n      !o.isPrototypeOf(p) && !o.isPrototypeOf(g);\n    `,\n    expected: true,\n  },\n  {\n    name: 'Object.protoype.propertyIsEnumerable(null)',\n    src: `\n      try {\n        Object.prototype.propertyIsEnumerable.call(null, '');\n      } catch(e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'ObjectProtoypePropertyIsEnumerableUndefined',\n    src: `\n      try {\n        Object.prototype.propertyIsEnumerable.call(undefined, '');\n      } catch(e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Object.protoype.propertyIsEnumerable primitives',\n    src: `\n      var OppIE = Object.prototype.propertyIsEnumerable;\n      OppIE.call('foo', '0') && !OppIE.call('foo', 'length');\n    `,\n    expected: true,\n  },\n  {\n    name: 'Object.protoype.propertyIsEnumerable',\n    src: `\n      var o = {foo: 'foo'};\n      Object.defineProperty(o, 'bar', {value: 'bar', enumerable: false});\n      o.propertyIsEnumerable('foo') && !o.propertyIsEnumerable('bar') &&\n          !o.propertyIsEnumerable('baz');\n    `,\n    expected: true,\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Function and Function.prototype\n  {\n    name: 'new Function() returns callable',\n    src: `new Function()();`,\n    expected: undefined,\n  },\n  {src: `(new Function()).length;`, expected: 0},\n  {src: `new Function().toString()`, expected: 'function anonymous(\\n) {\\n\\n}'},\n  {\n    name: 'new Function(/* body */) returns callable',\n    src: `new Function('return 42;')();`,\n    expected: 42,\n  },\n  {\n    name: 'Function constructor accepts trailing line comments in body',\n    src: `typeof new Function('//');`,\n    expected: 'function',\n  },\n  {src: `new Function(/* body */).length;`, expected: 0},\n  {\n    src: `new Function('return 42;').toString()`,\n    expected: 'function anonymous(\\n) {\\nreturn 42;\\n}'\n  },\n  {\n    name: 'new Function(/* args... */, /* body */) returns callable',\n    src: `new Function('a, b', 'c', 'return a + b * c;')(2, 3, 10);`,\n    expected: 32,\n  },\n  {\n    name: \"(new Function('a, b', 'c', /* body */)).length\",\n    src: `new Function('a, b', 'c', 'return a + b * c;').length;`,\n    expected: 3,\n  },\n  {\n    name: 'new Function(/* args... */, /* body */).toString()',\n    src: `new Function('a, b', 'c', 'return a + b * c;').toString()`,\n    expected: 'function anonymous(a, b,c\\n) {\\nreturn a + b * c;\\n}',\n  },\n  {\n    name: 'Function constructor accepts non-ASCII parameter names',\n    src: `new Function('fußball', '').toString()`,\n    expected: 'function anonymous(fußball\\n) {\\n\\n}',\n  },\n  {\n    name: 'Function constructor rejects non-unicode-letter parameter names',\n    src: `\n      try {\n        new Function('a…z', '');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'SyntaxError',\n  },\n  {\n    name: 'Function constructor accepts block comments in parameter list',\n    src: `new Function('a, /*test*/b', 'c', 'return a + b * c;')(2, 4, 10)`,\n    expected: 42,\n  },\n  {\n    name: 'Function constructor accepts line comments in parameter list',\n    src: `new Function('a, b', 'c //test', 'return a + b * c;')(2, 4, 10)`,\n    expected: 42,\n  },\n  {\n    name: 'Function constructor parameter line comments hide later parameters',\n    src: `new Function('dummy //', 'escape', 'return typeof escape')(0, 0);`,\n    expected: 'function',\n  },\n\n  {\n    name: 'Function.prototype has no .prototype',\n    src: `Function.prototype.hasOwnProperty('prototype');`,\n    expected: false,\n  },\n  {\n    src: `Function.prototype.toString()`,\n    expected: 'function () { [native code] }'\n  },\n  {\n    name: 'Function.prototype.toString.call(/* non-function */) throws',\n    src: `\n      try {\n        Function.prototype.toString.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Function.prototype.toSting on NativeFunction',\n    src: `escape.toString();`,\n    expected: 'function escape() { [native code] }',\n  },\n  {\n    name: 'Function.prototype.toSting on modified NativeFunction',\n    destructive: true,  // Modifies escape.\n    src: `\n      // Delete escape's original .name make it inherit a new one.\n      delete escape.name;\n      Object.setPrototypeOf(escape, function parent() {});\n      escape.toString();\n    `,\n    expected: 'function escape() { [native code] }',\n  },\n  {\n    name: 'Function.prototype.apply.call(/* non-function */) throws',\n    src: `\n      try {\n        Function.prototype.apply.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Function.prototype.apply this',\n    src: `\n      var o = {};\n      function f() {return this;}\n      f.apply(o, []) === o;\n    `,\n    expected: true,\n  },\n  {\n    name: 'Function.prototype.apply(..., undefined) or null',\n    src: `\n      var n = 0;\n      function f() {n += arguments.length;}\n      f.apply(undefined, undefined);\n      f.apply(undefined, null);\n      n;\n    `,\n    expected: 0,\n  },\n  {\n    name: 'Function.prototype.apply(..., /* non-object */) throws',\n    src: `\n      try {\n        (function() {}).apply(undefined, 'not an object');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Function.prototype.apply(..., /* sparse array */)',\n    src: `\n      (function(a, b, c) {\n        if (!(1 in arguments)) {\n          throw new Error('arguments[1] missing');\n        }\n        return a + c;\n      }).apply(undefined, [1, , 3]);\n    `,\n    expected: 4,\n  },\n  {\n    name: 'Function.prototype.apply(..., /* array-like */)',\n    src: `\n      (function(a, b, c) {\n        return a + b + c;\n      }).apply(undefined, {0: 1, 1: 2, 2: 3, length: 3});\n    `,\n    expected: 6,\n  },\n  {\n    name: 'Function.prototype.apply(..., /* non-array-like */)',\n    src: `\n      (function(a, b, c) {\n        return a + b + c;\n      }).apply(undefined, {0: 1, 1: 2, 2: 4});\n    `,\n    expected: NaN  // Because undefined + undefined === NaN.,\n  },\n  {\n    name: 'Function.prototype.call.call(/* non-function */) throws',\n    src: `\n      try {\n        Function.prototype.call.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Function.prototype.call this',\n    src: `\n      var o = {};\n      function f() {return this;}\n      f.call(o) === o;\n    `,\n    expected: true,\n  },\n  {\n    name: 'Function.prototype.call() gives arguments.length === 0',\n    src: `(function() {return arguments.length;}).call();`,\n    expected: 0,\n  },\n  {\n    name: 'Function.prototype.call(..., /* sparse array */)',\n    src: `\n      (function(a, b, c) {\n        if (!(1 in arguments)) {\n          throw new Error('Argument 1 missing');\n        }\n        return a + c;\n      }).call(undefined, 1, 2, 3);\n    `,\n    expected: 4,\n  },\n  {\n    name: 'Function.prototype.bind.call(/* non-function */) throws',\n    src: `\n      try {\n        Function.prototype.bind.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'Function.prototype.bind this',\n    src: `\n      var o = {};\n      function f() {return this;}\n      f.bind(o)() === o;\n    `,\n    expected: true,\n  },\n  {\n    name: 'Function.prototype.bind no args',\n    src: `(function() {return arguments.length;}).bind()();`,\n    expected: 0,\n  },\n  {\n    name: 'Function.prototype.bind',\n    src: `\n      var d = 4;\n      (function(a, b, c) {\n        return a + b + c + d;\n      }).bind(undefined, 1).bind(undefined, 2)(3);\n    `,\n    expected: 10,\n  },\n  {\n    name: 'Function.prototype.bind call BF',\n    src: `\n      var constructed;\n      function Foo() {constructed = (this instanceof Foo)}\n      var f = Foo.bind();\n      f();\n      constructed;\n    `,\n    expected: false,\n  },\n  {\n    name: 'Function.prototype.bind construct BF',\n    src: `\n      var constructed;\n      function Foo() {constructed = (this instanceof Foo)}\n      var f = Foo.bind();\n      new f;\n      constructed;\n    `,\n    expected: true,\n  },\n  {\n    name: 'Function.prototype.call.bind construct BF',\n    src: `\n      var invoked;\n      function Foo() {invoked = true};\n      var f = Foo.call.bind(Foo);\n      try {\n        new f;\n      } catch (e) {\n        !invoked && e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  // N.B.: tests of semantics of class constructors are unavoidably ES6.\n  {\n    name: 'Function.prototype.bind class constructor w/o new',\n    src: `\n      var f = WeakMap.bind();  // Should be O.K.\n      try {\n        f();\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  // N.B.: tests of semantics of class constructors are unavoidably ES6.\n  {\n    name: 'Function.prototype.bind class constructor',\n    src: `String(new (WeakMap.bind()));`,\n    expected: '[object WeakMap]',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Array and Array.prototype\n  {\n    name: 'new Array()',\n    src: `var a = new Array(); Array.isArray(a) && a.length;`,\n    expected: 0,\n  },\n  {\n    name: 'newArray(/* number */)',\n    src: `\n      var a = new Array(42);\n      Array.isArray(a) && !(0 in a) && !(41 in a) && a.length;\n    `,\n    expected: 42,\n  },\n  {\n    name: 'new Array(/* non-number */)',\n    src: `\n      var a = new Array('foo');\n      Array.isArray(a) && a.length === 1 && a[0];\n    `,\n    expected: 'foo',\n  },\n  {\n    name: 'new Array(/* multiple args */)',\n    src: `\n      var a = new Array(1, 2, 3);\n      Array.isArray(a) && a.length === 3 && String(a);\n    `,\n    expected: '1,2,3',\n  },\n  {src: `Array.isArray(Array.prototype);`, expected: true},\n  {src: `Array.isArray(new Array);`, expected: true},\n  {src: `Array.isArray([]);`, expected: true},\n  {src: `Array.isArray({0: 'foo', 1: 'bar', length: 2});`, expected: false},\n  {\n    name: 'Array.prototype.concat()',\n    src: `\n      var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n      var c = a.concat();\n      a.length === 6 && c.length === 6 && c !== a && String(c);\n    `,\n    expected: 'foo,bar,baz,,quux,quuux',\n  },\n  {\n    name: 'Array.prototype.concat(...)',\n    src: `\n      var o = {0: 'quux', 1: 'quuux', length: 2};\n      var c = [].concat(['foo', 'bar'], 'baz', undefined, o);\n      c.length === 5 && '3' in c && c[3] === undefined && String(c);\n    `,\n    expected: 'foo,bar,baz,,[object Object]',\n  },\n  {\n    name: 'Array.prototype.concat.call(object, ...)',\n    src: `\n      var o = {0: 'foo', 1: 'bar', length: 2};\n      var c = Array.prototype.concat.call(o, 'baz', [, 'quux', 'quuux']);\n      c.length === 5 && String(c);\n    `,\n    expected: '[object Object],baz,,quux,quuux',\n  },\n  {src: `[1, 2, 3, 2, 1].includes(2);`, expected: true},\n  {src: `[1, 2, 3, 2, 1].includes(4);`, expected: false},\n  {\n    name: 'Array.prototype.includes fromIndex',\n    src: `[1, 2, 3, 2, 1].includes(2, 2);`,\n    expected: true,\n  },\n  {\n    name: 'Array.prototype.includes negative fromIndex',\n    src: `[1, 2, 3, 2, 1].includes(1, -3);`,\n    expected: true,\n  },\n  {src: `['x', NaN, 'y'].includes(NaN);`, expected: true},\n  {\n    name: 'Array.prototype.includes.call(array-like, ...)',\n    src: `\n      var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5};\n      Array.prototype.includes.call(o, 2);\n    `,\n    expected: true,\n  },\n  {\n    name: 'Array.prototype.indexOf',\n    src: `[1, 2, 3, 2, 1].indexOf(2);`,\n    expected: 1,\n  },\n  {\n    name: 'Array.prototype.indexOf not found',\n    src: `[1, 2, 3, 2, 1].indexOf(4);`,\n    expected: -1,\n  },\n  {\n    name: 'Array.prototype.indexOf fromIndex',\n    src: `[1, 2, 3, 2, 1].indexOf(2, 2);`,\n    expected: 3,\n  },\n  {\n    name: 'Array.prototype.indexOf negative fromIndex',\n    src: `[1, 2, 3, 2, 1].indexOf(1, -3);`,\n    expected: 4,\n  },\n  {\n    name: 'Array.prototype.indexOf NaN',\n    src: `['x', NaN, 'y'].indexOf(NaN);`,\n    expected: -1,\n  },\n  {\n    name: 'Array.prototype.indexOf.call(array-like, ...)',\n    src: `\n      var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5};\n      Array.prototype.indexOf.call(o, 2);\n    `,\n    expected: 1,\n  },\n  {\n    name: 'Array.prototype.join',\n    src: `[1, 2, 3].join('-');`,\n    expected: '1-2-3',\n  },\n  {\n    name: 'Array.prototype.join cycle detection',\n    src: `\n      var a = [1, , 3];\n      a[1] = a;\n      a.join('-');\n      \"Didn't crash!\";\n    `,\n    expected: 'Didn\\'t crash!',\n  },\n  {\n    name: 'Array.prototype.lastIndexOf',\n    src: `[1, 2, 3, 2, 1].lastIndexOf(2);`,\n    expected: 3,\n  },\n  {\n    name: 'Array.prototype.lastIndexOf not found',\n    src: `[1, 2, 3, 2, 1].lastIndexOf(4);`,\n    expected: -1,\n  },\n  {\n    name: 'Array.prototype.lastIndexOf(..., +)',\n    src: `[1, 2, 3, 2, 1].lastIndexOf(2, 2);`,\n    expected: 1,\n  },\n  {\n    name: 'Array.prototype.lastIndexOf(..., -)',\n    src: `[1, 2, 3, 2, 1].lastIndexOf(1, -3);`,\n    expected: 0,\n  },\n  {\n    name: 'Array.prototype.lastIndexOf.call(array-like, ...)',\n    src: `\n      var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5};\n      Array.prototype.lastIndexOf.call(o, 2);\n    `,\n    expected: 3,\n  },\n  {\n    name: 'Array.prototype.pop',\n    src: `\n      var a = ['foo', 'bar', 'baz'];\n      var r = a.pop();\n      a.length === 2 && r;\n    `,\n    expected: 'baz',\n  },\n  {\n    name: 'Array.prototype.pop empty array',\n    src: `\n      var a = [];\n      var r = a.pop();\n      a.length === 0 && r;\n    `,\n    expected: undefined,\n  },\n  {\n    name: 'Array.prototype.pop.apply(array-like)',\n    src: `\n      var o = {0: 'foo', 1: 'bar', 2: 'baz', length: 3};\n      var r = Array.prototype.pop.apply(o);\n      o.length === 2 && r;\n    `,\n    expected: 'baz',\n  },\n  {\n    name: 'Array.prototype.pop.apply(empty array-like)',\n    src: `\n      var o = {length: 0};\n      var r = Array.prototype.pop.apply(o);\n      o.length === 0 && r;\n    `,\n    expected: undefined,\n  },\n  {\n    name: 'Array.prototype.pop.apply(huge array-like)',\n    src: `\n      var o = {5000000000000000: 'foo',\n               5000000000000001: 'quux',\n               length: 5000000000000002};\n      var r = Array.prototype.pop.apply(o);\n      o.length === 5000000000000001 && o[5000000000000000] === 'foo' && r;\n    `,\n    expected: 'quux',\n  },\n  {\n    name: 'Array.prototype.push',\n    src: `\n      var a = [];\n      a.push('foo') === 1 && a.push('bar') === 2 &&\n          a.length === 2 && a[0] === 'foo' && a[1] === 'bar';\n    `,\n    expected: true,\n  },\n  {\n    name: 'Array.prototype.push.call(array-like, ...)',\n    src: `\n      var o = {length: 0};\n      Array.prototype.push.call(o, 'foo') === 1 &&\n          Array.prototype.push.call(o, 'bar') === 2 &&\n          o.length === 2 && o[0] === 'foo' && o[1] === 'bar';\n    `,\n    expected: true,\n  },\n  {\n    name: 'Array.prototype.push.call(huge array-like, ...)',\n    src: `\n      var o = {length: 5000000000000000};\n      var o = {length: 5000000000000000};\n      Array.prototype.push.call(o, 'foo') === 5000000000000001 &&\n          Array.prototype.push.call(o, 'bar') === 5000000000000002 &&\n          o[5000000000000000] === 'foo' && o[5000000000000001] === 'bar' &&\n          o.length === 5000000000000002\n    `,\n    expected: true,\n  },\n  {\n    name: 'Array.prototype.reverse odd-length',\n    src: `\n      var a = [1, 2, 3];\n      a.reverse() === a && a.length === 3 && String(a);\n    `,\n    expected: '3,2,1',\n  },\n  {\n    name: 'Array.prototype.reverse even-length',\n    src: `\n      var a = [1, 2, , 4];\n      a.reverse() === a && a.length === 4 && String(a);\n    `,\n    expected: '4,,2,1',\n  },\n  {\n    name: 'Array.prototype.reverse empty',\n    src: `\n      var a = [];\n      a.reverse() === a && a.length;\n    `,\n    expected: 0,\n  },\n  {\n    name: 'Array.prototype.reverse.call(odd-length array-like)',\n    src: `\n      var o = {0: 1, 1: 2, 2: 3, length: 3};\n      Array.prototype.reverse.call(o) === o && o.length === 3 &&\n          Array.prototype.slice.apply(o).toString();\n    `,\n    expected: '3,2,1',\n  },\n  {\n    name: 'Array.prototype.reverse.call(even-length array-like)',\n    src: `\n      var o = {0: 1, 1: 2, 3: 4, length: 4};\n      Array.prototype.reverse.call(o) === o && o.length === 4 &&\n          Array.prototype.slice.apply(o).toString();\n    `,\n    expected: '4,,2,1',\n  },\n  {\n    name: 'Array.prototype.reverse.call(empty array-like)',\n    src: `\n      var o = {length: 0};\n      Array.prototype.reverse.call(o) === o && o.length;\n    `,\n    expected: 0,\n  },\n  {\n    name: 'Array.prototype.shift',\n    src: `\n      var a = ['foo', 'bar', 'baz'];\n      var r = a.shift();\n      a.length === 2 && a[0] === 'bar' && a[1] === 'baz' && r;\n    `,\n    expected: 'foo',\n  },\n  {\n    name: 'Array.prototype.shift empty array',\n    src: `\n      var a = [];\n      var r = a.shift();\n      a.length === 0 && r;\n    `,\n    expected: undefined,\n  },\n  {\n    name: 'Array.prototype.shift.apply(array-like)',\n    src: `\n      var o = {0: 'foo', 1: 'bar', 2: 'baz', length: 3};\n      var r = Array.prototype.shift.apply(o);\n      o.length === 2 && o[0] === 'bar' && o[1] === 'baz' && r;\n    `,\n    expected: 'foo',\n  },\n  {\n    name: 'Array.prototype.shift.apply(empty array-like)',\n    src: `\n      var o = {length: 0};\n      var r = Array.prototype.shift.apply(o);\n      o.length === 0 && r;\n    `,\n    expected: undefined,\n  },\n  {\n    name: 'Array.prototype.shift.apply(huge array-like)',\n    src: `\n      var o = {5000000000000000: 'foo',\n               5000000000000001: 'quux',\n               length: 5000000000000002};\n      var r = Array.prototype.shift.apply(o);\n      o.length === 5000000000000001 && o[5000000000000000] === 'quux' && r;\n    `,\n    // SKIP until more efficient shift implementation available.\n    /* expected: 'foo' */\n  },\n  {\n    name: 'Array.prototype.slice()',\n    src: `\n      var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n      var s = a.slice();\n      a.length === 6 && s.length === 6 && String(s);\n    `,\n    expected: 'foo,bar,baz,,quux,quuux',\n  },\n  {\n    name: 'Array.prototype.slice(-)',\n    src: `\n      var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n      var s = a.slice(-2);\n      a.length === 6 && s.length === 2 && String(s);\n    `,\n    expected: 'quux,quuux',\n  },\n  {\n    name: 'Array.prototype.slice(+, +)',\n    src: `\n      var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n      var s = a.slice(1, 4);\n      a.length === 6 && s.length === 3 && !('2' in s) && String(s);\n    `,\n    expected: 'bar,baz,',\n  },\n  {\n    name: 'Array.prototype.slice(+, -)',\n    src: `\n      var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n      var s = a.slice(1, -2);\n      a.length === 6 && s.length === 3 && !('2' in s) && String(s);\n    `,\n    expected: 'bar,baz,',\n  },\n  {\n    name: 'Array.prototype.slice.call(array-like, -, +)',\n    src: `\n      var o = {\n        0: 'foo', 1: 'bar', 2: 'baz', 4: 'quux', 5: 'quuux', length: 6\n      };\n      var s = Array.prototype.slice.call(o, -5, 4);\n      !Array.isArray(o) && o.length === 6 &&\n          Array.isArray(s) && s.length === 3 && !('2' in s) && String(s);\n    `,\n    expected: 'bar,baz,',\n  },\n  {\n    name: 'Array.prototype.slice.call(huge array-like, -, -)',\n    src: `\n      var o = {\n        5000000000000000: 'foo', 5000000000000001: 'bar',\n        5000000000000002: 'baz', 5000000000000004: 'quux',\n        5000000000000005: 'quuux', length: 5000000000000006\n      };\n      var s = Array.prototype.slice.call(o, -5, -2);\n      !Array.isArray(o) && o.length === 5000000000000006 &&\n          Array.isArray(s) && s.length === 3 && !('2' in s) && String(s);\n    `,\n    expected: 'bar,baz,',\n  },\n  {\n    name: 'Array.prototype.sort()',\n    src: `[5, 2, 3, 1, 4].sort().join();  // Sorts ASCIIbetically.`,\n    expected: '1,2,3,4,5',\n  },\n  {\n    name: 'Array.prototype.sort() compaction',\n    src: `\n      ['z', undefined, 10, , 'aa', null, 'a', 5, NaN, , 1].sort()\n          .map(String).join();\n    `,\n    expected: '1,10,5,NaN,a,aa,null,z,undefined,,',\n  },\n  {\n    name: 'Array.prototype.sort(/* comparefn */)',\n    src: `\n      [99, 9, 10, 11, 1, 0, 5]\n          .sort(function(a, b) {return a - b;}).join();\n    `,\n    expected: '0,1,5,9,10,11,99',\n  },\n  {\n    name: 'Array.prototype.sort(/* comparefn */) compaction',\n    src: `\n      ['z', undefined, 10, , 'aa', null, 'a', 5, NaN, , 1]\n          .sort(function(a, b) {\n            // Try to put undefineds first - should not succeed.\n            if (a === undefined) return b === undefined ? 0 : -1;\n            if (b === undefined) return 1;\n            // Reverse order of ususal sort.\n            a = String(a);\n            b = String(b);\n            if (a > b) return -1;\n            if (b > a) return 1;\n            return 0;\n          }).map(String).join();\n    `,\n    expected: 'z,null,aa,a,NaN,5,10,1,undefined,,',\n  },\n  {\n    name: 'Array.prototype.splice()',\n    src: `\n      var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n      var s = a.splice();\n      a.length === 6 && s.length === 0 && String(a) + ':' + String(s);\n    `,\n    expected: 'foo,bar,baz,,quux,quuux:',\n  },\n  {\n    name: 'Array.prototype.splice(-)',\n    src: `\n      var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n      var s = a.splice(-2);\n      a.length === 4 && s.length === 2 && String(a) + ':' + String(s);\n    `,\n    expected: 'foo,bar,baz,:quux,quuux',\n  },\n  {\n    name: 'Array.prototype.splice(+, +, ...)',\n    src: `\n      var a = ['foo', 'bar', 'baz', , 'quux', 'quuux'];\n      var s = a.splice(1, 3, 'bletch');\n      a.length === 4 && s.length === 3 && String(a) + ':' + String(s);\n    `,\n    expected: 'foo,bletch,quux,quuux:bar,baz,',\n  },\n  {\n    name: 'Array.prototype.splice.call(array-like, 0, large, ...)',\n    src: `\n      var o = {\n        0: 'foo', 1: 'bar', 2: 'baz', 4: 'quux', 5: 'quuux', length: 6\n      };\n      var s = Array.prototype.splice.call(o, 0, 100, 'bletch');\n      !Array.isArray(o) && o.length === 1 && Object.keys(o).length === 2 &&\n      o[0] === 'bletch' &&\n      Array.isArray(s) && s.length === 6 && !('3' in s) && String(s);\n    `,\n    expected: 'foo,bar,baz,,quux,quuux',\n  },\n  {\n    name: 'Array.prototype.splice.call(huge array-like, -, -, many...)',\n    src: `\n      var o = {\n        5000000000000000: 'foo', 5000000000000001: 'bar',\n        5000000000000002: 'baz', 5000000000000004: 'quux',\n        5000000000000005: 'quuux', length: 5000000000000006\n      };\n      var s = Array.prototype.splice.call(o, -2, -999, 'bletch', 'qux');\n      !Array.isArray(o) && o.length === 5000000000000008 &&\n          o[5000000000000004] === 'bletch' && o[5000000000000005] === 'qux' &&\n          o[5000000000000006] === 'quux' && o[5000000000000007] === 'quuux' &&\n          Array.isArray(s) && s.length === 0;\n    `,\n    expected: true,\n  },\n  {\n    name: 'Array.prototype.toString cycle detection',\n    src: `\n      var a = [1, , 3];\n      a[1] = a;\n      a.toString();\n      \"Didn't crash!\";\n    `,\n    expected: 'Didn\\'t crash!',\n  },\n  {\n    name: 'Array.prototype.toString.call(obj-w/join)',\n    src: `Array.prototype.toString.apply({join: function() {return 'OK';}});`,\n    expected: 'OK',\n  },\n  {\n    name: 'Array.prototype.toString.call(array-like)',\n    src: `Array.prototype.toString.apply({0: 'foo', 1: 'bar', length: 2});`,\n    expected: '[object Object]',\n  },\n  {\n    name: 'Array.prototype.unshift',\n    src: `\n      var a = [];\n      a.unshift('foo') === 1 && a.unshift('bar') === 2 &&\n          a.length === 2 && a[0] === 'bar' && a[1] === 'foo';\n    `,\n    expected: true,\n  },\n  {\n    name: 'Array.prototype.unshift.call(array-like, ...)',\n    src: `\n      var o = {length: 0};\n      Array.prototype.unshift.call(o, 'foo') === 1 &&\n          Array.prototype.unshift.call(o, 'bar') === 2 &&\n          o.length === 2 && o[0] === 'bar' && o[1] === 'foo';\n    `,\n    expected: true,\n  },\n  {\n    name: 'Array.prototype.unshift.call(huge array-like, ...)',\n    src: `\n      var o = {length: 5000000000000000};\n      var o = {length: 5000000000000000};\n      Array.prototype.unshift.call(o, 'foo') === 5000000000000001 &&\n          Array.prototype.push.call(o, 'bar') === 5000000000000002 &&\n          o[5000000000000000] === 'bar' && o[5000000000000001] === 'foo' &&\n          o.length === 5000000000000002\n    `,\n    // SKIP until more efficient unshift implementation available.\n    /* expected: true */\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Boolean and Boolean.prototype\n  {src: `Boolean(undefined);`, expected: false},\n  {src: `Boolean(null);`, expected: false},\n  {src: `Boolean(false);`, expected: false},\n  {src: `Boolean(true);`, expected: true},\n  {src: `Boolean(NaN);`, expected: false},\n  {src: `Boolean(0);`, expected: false},\n  {src: `Boolean(1);`, expected: true},\n  {src: `Boolean('');`, expected: false},\n  {src: `Boolean('foo');`, expected: true},\n  {src: `Boolean({});`, expected: true},\n  {src: `Boolean([]);`, expected: true},\n  {src: `Boolean(function() {});`, expected: true},\n\n  {src: `Boolean.prototype.toString();`, expected: 'false'},\n  {src: `Boolean.prototype.toString.call(true);`, expected: 'true'},\n  {src: `Boolean.prototype.toString.call(false);`, expected: 'false'},\n  {\n    name: 'Boolean.prototype.toString.call non-Boolean object',\n    src: `\n      try {\n        Boolean.prototype.toString.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {src: `Boolean.prototype.valueOf();`, expected: false},\n  {src: `Boolean.prototype.valueOf.call(true);`, expected: true},\n  {src: `Boolean.prototype.valueOf.call(false);`, expected: false},\n  {\n    name: 'Boolean.prototype.valueOf.call non-Boolean object',\n    src: `\n      try {\n        Boolean.prototype.valueOf.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Number and Number.prototype\n  {src: `Number();`, expected: 0},\n  {src: `Number(undefined);`, expected: NaN},\n  {src: `Number(null);`, expected: 0},\n  {src: `Number(true);`, expected: 1},\n  {src: `Number(false);`, expected: 0},\n  {src: `Number('42');`, expected: 42},\n  {src: `Number('');`, expected: 0},\n  {src: `Number({});`, expected: NaN},\n  {src: `Number([]);`, expected: 0},\n  {src: `Number([42]);`, expected: 42},\n  {src: `Number([1,2,3]);`, expected: NaN},\n  {src: `Number(function() {});`, expected: NaN},\n\n  {\n    name: 'Number.MAX_SAFE_INTEGER',\n    src: `\n      Number.MAX_SAFE_INTEGER + 1 === Math.pow(2, 53) &&\n          Number.isSafeInteger(Number.MAX_SAFE_INTEGER) &&\n          !Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1);\n    `,\n    expected: true,\n  },\n  {src: `Number.prototype.toString();`, expected: '0'},\n  {src: `Number.prototype.toString.call(84);`, expected: '84'},\n  {\n    name: 'Number.prototype.toString.call non-Number object',\n    src: `\n      try {\n        Number.prototype.toString.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {src: `Number.prototype.valueOf();`, expected: 0},\n  {src: `Number.prototype.valueOf.call(85);`, expected: 85},\n  {\n    name: 'Number.prototype.valueOf.call non-Number object',\n    src: `\n      try {\n        Number.prototype.valueOf.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // String and String.prototype\n  {src: `String();`, expected: ''},\n  {src: `String(undefined);`, expected: 'undefined'},\n  {src: `String(null);`, expected: 'null'},\n  {src: `String(true);`, expected: 'true'},\n  {src: `String(false);`, expected: 'false'},\n  {src: `String(0);`, expected: '0'},\n  {src: `String(-0);`, expected: '0'},\n  {src: `String(Infinity);`, expected: 'Infinity'},\n  {src: `String(-Infinity);`, expected: '-Infinity'},\n  {src: `String(NaN);`, expected: 'NaN'},\n  {src: `String({});`, expected: '[object Object]'},\n  {src: `String([1, 2, 3,,5]);`, expected: '1,2,3,,5'},\n\n  {\n    name: 'String calls valueOf',\n    src: `\n      var o = Object.create(null);\n      o.valueOf = function() {return 'OK';};\n      String(o);\n    `,\n    expected: 'OK',\n  },\n  {\n    name: 'String calling valueOf returns string',\n    src: `\n      var o = Object.create(null);\n      o.valueOf = function() {return 42;};\n      String(o);\n    `,\n    expected: '42',\n  },\n  {\n    name: 'String calling valueOf throws',\n    src: `\n      var o = Object.create(null);\n      o.valueOf = function() {return {};};\n      try {\n        String(o);\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'String calls toString',\n    src: `\n      var o = Object.create(null);\n      o.valueOf = function() {return 'Whoops: called valueOf';};\n      o.toString = function() {return 'OK';};\n      String(o);\n    `,\n    expected: 'OK',\n  },\n  {\n    name: 'String calling toString returns string',\n    src: `\n      var o = Object.create(null);\n      o.valueOf = function() {return 42;};\n      String(o);\n    `,\n    expected: '42',\n  },\n  {\n    name: 'String calling toString throws',\n    src: `\n      var o = Object.create(null);\n      o.valueOf = function() {return {};};\n      o.toString = function() {return {};};\n      try {\n        String(o);\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {src: `String.prototype.length;`, expected: 0},\n  {\n    name: 'String.prototype.replace(string, string)',\n    src: `'xxxx'.replace('xx', 'y');`,\n    expected: 'yxx',\n  },\n  {\n    name: 'String.prototype.replace(regexp, string)',\n    src: `'xxxx'.replace(/(X)\\\\1/ig, 'y');`,\n    expected: 'yy',\n  },\n  {\n    name: 'String.prototype.replace(string, function)',\n    src: `\n      'xxxx'.replace('xx', function() {\n           return '[' + Array.prototype.join.apply(arguments) + ']';\n      });\n    `,\n    expected: '[xx,0,xxxx]xx',\n  },\n  {\n    name: 'String.prototype.replace(regexp, function)',\n    src: `\n      'xxxx'.replace(/(X)\\\\1/ig, function() {\n           return '[' + Array.prototype.join.apply(arguments) + ']';\n      });\n    `,\n    expected: '[xx,x,0,xxxx][xx,x,2,xxxx]',\n  },\n  {\n    name: 'String.prototype.search(string) not found',\n    src: `'hello'.search('H')`,\n    expected: -1,\n  },\n  {\n    name: 'String.prototype.search(string) found',\n    src: `'hello'.search('ll')`,\n    expected: 2,\n  },\n  {\n    name: 'String.prototype.search(regexp) not found',\n    src: `'hello'.search(/H/)`,\n    expected: -1,\n  },\n  {\n    name: 'String.prototype.search(regexp) found',\n    src: `'hello'.search(/(.)\\\\1/)`,\n    expected: 2,\n  },\n  {src: `String.prototype.toString();`, expected: ''},\n  {\n    name: 'String.prototype.toString.call primitive',\n    src: `String.prototype.toString.call('a string');`,\n    expected: 'a string',\n  },\n  {\n    name: 'String.prototype.toString.call non-String object',\n    src: `\n      try {\n        String.prototype.toString.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {src: `String.prototype.valueOf();`, expected: ''},\n  {\n    name: 'String.prototype.valueOf.call primitive',\n    src: `String.prototype.valueOf.call('a string');`,\n    expected: 'a string',\n  },\n  {\n    name: 'String.prototype.valueOf.call non-String object',\n    src: `\n      try {\n        String.prototype.valueOf.call({});\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // RegExp\n  {src: `new RegExp(undefined).source`, expected: '(?:)'},\n  {src: `new RegExp(null).source`, expected: 'null'},\n  {src: `new RegExp(true).source`, expected: 'true'},\n  {src: `new RegExp(false).source`, expected: 'false'},\n  {src: `new RegExp('').source`, expected: '(?:)'},\n  {src: `new RegExp('foo').source`, expected: 'foo'},\n  {src: `new RegExp('0').source`, expected: '0'},\n  {src: `new RegExp({}).source`, expected: '[object Object]'},\n  {src: `new RegExp([]).source`, expected: '(?:)'},\n\n  {src: `RegExp(undefined).source`, expected: '(?:)'},\n  {src: `RegExp(null).source`, expected: 'null'},\n  {src: `RegExp(true).source`, expected: 'true'},\n  {src: `RegExp(false).source`, expected: 'false'},\n  {src: `RegExp('').source`, expected: '(?:)'},\n  {src: `RegExp('foo').source`, expected: 'foo'},\n  {src: `RegExp('0').source`, expected: '0'},\n  {src: `RegExp({}).source`, expected: '[object Object]'},\n  {src: `RegExp([]).source`, expected: '(?:)'},\n\n  // TODO(ES6):\n  // {src: `new RegExp('foo', '').flags`, expected: ''},\n  // {src: `new RegExp('foo', 'g').flags`, expected: 'g'},\n  // {src: `new RegExp('foo', 'i').flags`, expected: 'i'},\n  // {src: `new RegExp('foo', 'gi').flags`, expected: 'gi'},\n  // {src: `new RegExp('foo', 'm').flags`, expected: 'm'},\n  // {src: `new RegExp('foo', 'gm').flags`, expected: 'gm'},\n  // {src: `new RegExp('foo', 'im').flags`, expected: 'im'},\n  // {src: `new RegExp('foo', 'gim').flags`, expected: 'gim'},\n\n  {src: `new RegExp('foo', '').global`, expected: false},\n  {src: `new RegExp('foo', 'g').global`, expected: true},\n  {src: `new RegExp('foo', '').ignoreCase`, expected: false},\n  {src: `new RegExp('foo', 'i').ignoreCase`, expected: true},\n  {src: `new RegExp('foo', '').multiline`, expected: false},\n  {src: `new RegExp('foo', 'm').multiline`, expected: true},\n\n  {\n    name: \"new RegExp('', 'x') throws\",\n    src: `\n      try {\n        new RegExp('', 'x');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'SyntaxError',\n  },\n  {\n    name: \"new RegExp('', 'gg') throws\",\n    src: `\n      try {\n        new RegExp('', 'gg');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'SyntaxError',\n  },\n\n  // Check behaviour of RegExp when called with and without new, when\n  // pattern is itself a RegExp, and flags are or are not supplied.\n  {src: `var re = /foo/; new RegExp(re) === re;`, expected: false},\n  {src: `var re = /foo/; RegExp(re) === re;`, expected: true},\n  {src: `var re = /foo/; RegExp(re, 'm') === re;`, expected: false},\n  {src: `var re = /foo/m; RegExp(re, 'm') === re;`, expected: false},\n  {src: `var re = /foo/m; RegExp(re) === re;`, expected: true},\n  {\n    name: 'RegExp called as function checks .constructor',\n    src: `\n      function SubClass() {};\n      Object.setPrototypeOf(SubClass, RegExp);\n      Object.setPrototypeOf(SubClass.prototype, RegExp.prototype);\n      var re = /foo/;\n      re.constructor = SubClass;\n      RegExp(re) === re;\n    `,\n    expected: false,\n  },\n  // TODO(ES6):\n  // {src: `var re = /foo/m; RegExp(re, 'i').flags;`, expected: 'i'},\n  {src: `var re = /foo/m; RegExp(re, 'i').multiline;`, expected: false},\n  {src: `var re = /foo/m; RegExp(re, 'i').ignoreCase;`, expected: true},\n\n\n  // Check behaviour of RegExp.prototype methods.\n  {\n    name: 'RegExp.prototype.exec.call(undefined) throws',\n    src: `\n      try {\n        RegExp.prototype.exec.call(undefined, 'foo');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'RegExp.prototype.exec.call(non-regexp) throws',\n    src: `\n      try {\n        RegExp.prototype.exec.call({}, 'foo');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {src: `/undefined/.exec(undefined).length;`, expected: 1},\n  {src: `/null/.exec(null).length;`, expected: 1},\n  {\n    name: 'RegExp.prototype.test.call(undefined) throws',\n    src: `\n      try {\n        RegExp.prototype.test.call(undefined);\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError'\n  },\n  {\n    name: 'RegExp.prototype.test.call(/* non-regexp */) throws',\n    src: `\n      try {\n        RegExp.Prototype.test.call({}, 'foo');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Error and Error.prototype (and all the other native error types too)\n  {\n    name: 'new Error has .stack',\n    src: `\n      // Use eval to make parsing .stack easier.\n      var e = eval('new Error;');\n      var lines = e.stack.split('\\\\n');\n      lines[0].trim();\n    `,\n    expected: 'at \"new Error;\" 1:1',\n  },\n  {\n    name: 'thrown Error has .stack',\n    src: `\n      try {\n        (function buggy() {1 instanceof 2;})();\n      } catch (e) {\n        var lines = e.stack.split('\\\\n');\n      }\n      lines[0].trim();\n    `,\n    expected: 'at buggy 1:19',\n  },\n  {\n    name: 'Error .stack correctly reports anonymous function',\n    src: `\n      // Use eval to make parsing .stack easier.\n      var e = eval('(function() {return new Error;})()');\n      var lines = e.stack.split('\\\\n');\n      lines[0].trim();\n    `,\n    expected: 'at anonymous function 1:20',\n  },\n  // Bug #241.\n  {\n    name: 'Error .stack correctly blames MemberExpression',\n    src: `\n      function foo() {\n        switch (1) {\n          case 1:\n            return undefined.hasNoProperties;\n        }\n      }\n      try {\n        foo();\n      } catch (e) {\n        var lines = e.stack.split('\\\\n');\n      }\n      lines[0].trim();\n    `,\n    expected: 'at foo 4:20',\n  },\n  {\n    name: 'Error .stack correctly blames Identifier',\n    src: `\n      function foo() {\n        return undefinedVariable;\n      }\n      try {\n        foo();\n      } catch (e) {\n        var lines = e.stack.split('\\\\n');\n      }\n      lines[0].trim();\n    `,\n    expected: 'at foo 2:16',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // JSON\n  {\n    name: 'JSON.parse(undefined) throws',\n    src: `\n      try {\n        JSON.parse(undefined);\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'SyntaxError',\n  },\n  {src: `JSON.parse(null);`, expected: null},\n  {src: `JSON.parse(true);`, expected: true},\n  {src: `JSON.parse(false);`, expected: false},\n  {src: `JSON.parse(42);`, expected: 42},\n  {\n    name: \"JSON.parse('') throws\",\n    src: `\n      try {\n        JSON.parse('');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'SyntaxError',\n  },\n  {\n    name: 'JSON.parse([]) throws',\n    src: `\n      try {\n        JSON.parse([]);  // Equivalent to JSON.parse('');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'SyntaxError',\n  },\n  {\n    name: 'JSON.parse({}) throws',\n    src: `\n      try {\n        JSON.parse({});  // Equivalent to JSON.parse('[object Object]');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'SyntaxError',\n  },\n\n  {src: `JSON.stringify(undefined);`, expected: undefined},\n  {src: `JSON.stringify(null);`, expected: 'null'},\n  {src: `JSON.stringify(true);`, expected: 'true'},\n  {src: `JSON.stringify(false);`, expected: 'false'},\n  {src: `JSON.stringify(42);`, expected: '42'},\n  {src: `JSON.stringify('string');`, expected: '\"string\"'},\n  {src: `JSON.stringify([1,2,,4]);`, expected: '[1,2,null,4]'},\n  {\n    name: 'JSON.stringify({...})',\n    src: `\n      JSON.stringify({\n          string: 'foo', number: 42, true: true, false: false, null: null,\n          object: {obj: {}, arr: []}, array: [{}, []] });\n    `,\n    expected: '{\"string\":\"foo\",\"number\":42,\"true\":true,\"false\":false,' +\n        '\"null\":null,\"object\":{\"obj\":{},\"arr\":[]},\"array\":[{},[]]}',\n  },\n  {src: `JSON.stringify(function(){});`, expected: undefined},\n  {src: `JSON.stringify([function(){}]);`, expected: '[null]'},\n  {src: `JSON.stringify({f: function(){}});`, expected: '{}'},\n  {\n    name: 'JSON.stringify({...}, [/* filter array */])',\n    src: `\n      JSON.stringify({\n          string: 'foo', number: 42, true: true, false: false, null: null,\n          object: {obj: {}, arr: []}, array: [{}, []] },\n          ['string', 'number']);\n    `,\n    expected: '{\"string\":\"foo\",\"number\":42}',\n  },\n  {\n    name: 'JSON.stringify({...}, [...], /* space number */)',\n    src: `\n      JSON.stringify({\n          string: 'foo', number: 42, true: true, false: false, null: null,\n          object: {obj: {}, arr: []}, array: [{}, []] },\n          ['string', 'number'], 2);\n    `,\n    expected: '{\\n  \"string\": \"foo\",\\n  \"number\": 42\\n}',\n  },\n  {\n    name: 'JSON.stringify({...}, [...], /* space  string */)',\n    src: `\n      JSON.stringify({\n          string: 'foo', number: 42, true: true, false: false, null: null,\n          object: {obj: {}, arr: []}, array: [{}, []] },\n          ['string', 'number'], '--');\n    `,\n    expected: '{\\n--\"string\": \"foo\",\\n--\"number\": 42\\n}',\n  },\n  {\n    name: 'JSON.stringify ignores nonenumerable properties',\n    src: `\n      var obj = {e: 'enumerable', ne: 'nonenumerable'};\n      Object.defineProperty(obj, 'ne', {enumerable: false});\n      JSON.stringify(obj);\n    `,\n    expected: '{\"e\":\"enumerable\"}',\n  },\n  {\n    name: 'JSON.stringify ignores inherited properties',\n    src: `JSON.stringify(Object.create({foo: 'bar'}));`,\n    expected: '{}',\n  },\n  {\n    name: 'JSON.stringify throws when value is cyclic',\n    src: `\n      var obj = {};\n      obj.circular = obj;\n      try {\n        JSON.stringify(obj);\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Other built-in functions\n  {\n    name: 'decodeURI throws',\n    src: `\n      try {\n        decodeURI('%xy');\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'URIError',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // WeakMap\n  {\n    name: 'WeakMap',\n    src: `\n      var w = new WeakMap;\n      var p = {};\n      var o = Object.create(p);\n      var fails = 0;\n      !w.has(p) || fails++;\n      !w.delete(p) || fails++;\n      w.set(o, 'o') === w || fails++;\n      w.get(o) === 'o' || fails++;\n      w.get(p) === undefined || fails++;\n      w.has(o) || fails++;\n      w.delete(o) || fails++;\n      !w.has(o) || fails++;\n      fails;\n    `,\n    expected: 0,\n  },\n  {\n    name: 'WeakMap.prototype methods reject non-WeakMap this',\n    src: `\n      var w = new WeakMap;\n      var fails = 0;\n      function expectError(method, thisVal, args) {\n        try {\n          w[method].apply(thisVal, args);\n          fails++;\n        } catch (e) {\n          if (e.name !== 'TypeError') fails++;\n        }\n      }\n      var methods = ['delete', 'get', 'has', 'set'];\n      var values = [null, undefined, true, false, 0, 42, '', 'hi'];\n      for (var i = 0; i < methods.length; i++) {\n        var method = methods[i];\n        for (var j = 0; j < values.length; j++) {\n          var value = values[j];\n          expectError(method, value, [{}]); // Can't call method on non-WeakMap.\n          expectError(method, w, [value]); // Can't store non-object in WeakMap.\n        }\n        // WeakMap.prototype is an ordinary object, not a WeakMap.\n        expectError(method, WeakMap.prototpye, [{}]);\n      }\n      fails;\n    `,\n    expected: 0,\n  },\n  {\n    name: 'WeakMap',\n    src: `\n      var w = new WeakMap;\n      var p = {};\n      var o = Object.create(p);\n      var fails = 0;\n      !w.has(p) || fails++;\n      !w.delete(p) || fails++;\n      w.set(o, 'o') === w || fails++;\n      w.get(o) === 'o' || fails++;\n      w.get(p) === undefined || fails++;\n      w.has(o) || fails++;\n      w.delete(o) || fails++;\n      !w.has(o) || fails++;\n      fails;\n    `,\n    expected: 0,\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Thread and Thread.prototype:\n  // TODO(cpallen): change .eval to .program when test harness no\n  //     longer relies on eval.\n  {\n    name: 'Thread.callers() ownership',\n    src: `\n      var owner = {};\n      setPerms(owner);\n      var callers = Thread.callers();\n      Object.getOwnerOf(callers) === owner &&\n          Object.getOwnerOf(callers[0]) === owner;\n    `,\n    expected: true,\n  },\n  {\n    name: 'Thread.callers()[0].eval',\n    src: `Thread.callers()[0].eval`,\n    expected: 'Thread.callers()[0].eval',\n  },\n  {\n    name: 'Thread.callers()[0].line & .col',\n    src: `var frame = Thread.callers()[0]; frame.line + \",\" + frame.col;`,\n    expected: '1,13',\n  },\n  {\n    name: 'Thread.callers()[/* last */].program',\n    src: `\n      var callers = Thread.callers();\n      typeof callers[callers.length - 1].program;\n    `,\n    expected: 'string',\n  },\n  {\n    name: 'Thread.callers()[0].callerPerms',\n    src: `\n      CC.root.name = 'root';\n      var user = {name: 'user'};\n      function f() {\n        return Thread.callers()[0].callerPerms.name;\n      }\n      setPerms(user);\n      f();\n    `,\n    expected: 'user',\n  },\n  // Time limit tests.  Actual enforcement is tested in\n  // interpreter_tests.js; this is just checking behaviour of get/set\n  // builtins.\n  {\n    name: 'Thread.prototype.getTimeLimit() initially 0',\n    src: `Thread.current().getTimeLimit();`,\n    expected: 0,\n  },\n  {\n    name: 'Thread.prototype.setTimeLimit()',\n    src: `\n      Thread.current().setTimeLimit(1000);\n      Thread.current().getTimeLimit();\n    `,\n    expected: 1000,\n  },\n  {\n    name: 'Thread.prototype.setTimeLimit(...)',\n    src: `\n      Thread.current().setTimeLimit(1000);\n      Thread.current().getTimeLimit();\n    `,\n    expected: 1000,\n  },\n  // Check invalid time limits are rejected.\n  {\n    name: 'Thread.prototype.setTimeLimit(/* invalid value */) throws',\n    src: `\n      Thread.current().setTimeLimit(1000);\n      var invalid = [0, 1001, NaN, 'foo', true, {}];\n      var failures = [];\n      for (var i = 0; i < invalid.length; i++) {\n        try {\n          Thread.current().setTimeLimit(invalid[i]);\n          failures.push(invalid[i]);\n        } catch (e) {\n        }\n      }\n      (failures.length === 0) ? 'OK' : String(failures);\n    `,\n    expected: 'OK',\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Permissions system:\n  {\n    name: 'perms returns root',\n    src: `perms() === CC.root;`,\n    expected: true,\n  },\n  {\n    name: 'setPerms',\n    src: `\n      CC.root.name = 'Root';\n      var bob = {};\n      bob.name = 'Bob';\n      var r = '';\n      r += perms().name;\n      (function() {\n        setPerms(bob);\n        r += perms().name;\n        // Perms revert at end of scope.\n      })();\n      r += perms().name;\n      r;\n    `,\n    expected: 'RootBobRoot',\n  },\n  {\n    name: 'getOwnerOf',\n    src: `\n      var bob = {};\n      var roots = {};\n      setPerms(bob);\n      var bobs = new Object;\n      Object.getOwnerOf(Object) === CC.root &&\n      Object.getOwnerOf(roots) === CC.root &&\n      Object.getOwnerOf(bobs) === bob\n    `,\n    expected: true,\n  },\n  {\n    name: 'setOwnerOf',\n    src: `\n      var bob = {};\n      var obj = {};\n      Object.setOwnerOf(obj, bob) === obj && Object.getOwnerOf(obj) === bob;\n    `,\n    expected: true,\n  },\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Other tests:\n  {\n    name: 'new hack',\n    src: `(new 'Array.prototype.push') === Array.prototype.push`,\n    expected: true,\n  },\n  {\n    name: 'new hack with unkown builtin',\n    src: `\n      try {\n        new 'nonexistent-builtin-name';\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'ReferenceError',\n  },\n  {\n    name: 'new hack with other than string literal',\n    src: `\n      try {\n        var builtin = 'Object.prototype';\n        new builtin;\n      } catch (e) {\n        e.name;\n      }\n    `,\n    expected: 'TypeError',\n  },\n  {\n    name: 'ES6 causes syntax errors',\n    src: `\n      var tests = [\n        // Class statements & expressions\n        'class Foo{};',\n        'false && class Foo{};',\n        // Arrow functions.\n        'false && [].map((item) => String(item));',\n        // For-of statement.\n        'for (var x of [1, 2, 3]) {};',\n        // Let & const.\n        'let x;',\n        'const x;',\n      ];\n      var failed = [];\n      for (var i = 0; i < tests.length; i++) {\n        try {\n          eval(tests[i]);\n          failed.push(\"Didn't throw: \" + tests[i]);\n        } catch (e) {\n          if (e.name !== 'SyntaxError') {\n            failed.push('Wrong error: ' + tests[i] + ' threw ' + String(e));\n          }\n        }\n      }\n      failed.length ? failed.join('\\\\n') : 'OK';\n    `,\n    expected: 'OK',\n  },\n  {\n    name: 'Strict mode syntax errors',\n    src: `\n      var tests = [\n        // With statement.\n        'var o = {foo: 42}; var f = function() {with (o) {foo;}};',\n        // Binding eval in global scope, or arguments in a function.\n        'var eval = \"rebinding eval?!?\";',\n        '(function() {arguments = undefined;});',\n        // Duplicate argument names.\n        '(function(a, a) {});',\n        \"new Function('a', 'a', '');\",\n        // Octal numeric literals.\n        '0777;',\n        // Delete of unqualified or undeclared identifier.\n        'var foo; delete foo;',\n        'delete foo;',\n      ];\n      var failed = [];\n      for (var i = 0; i < tests.length; i++) {\n        try {\n          eval(tests[i]);\n          failed.push(\"Didn't throw: \" + tests[i]);\n        } catch (e) {\n          if (e.name !== 'SyntaxError') {\n            failed.push('Wrong error: ' + tests[i] + ' threw ' + String(e));\n          }\n        }\n      }\n      failed.length ? failed.join('\\\\n') : 'OK';\n    `,\n    expected: 'OK',\n  },\n  {\n    name: 'Stack overflow errors',\n    src: `\n      try {\n        (function f() {f();})();\n      } catch (e) {\n        e.name;\n      }\n    `,\n    options: {stackLimit: 100},\n    expected: 'RangeError',\n  },\n  {\n    name: 'Minimum stack depth limit',\n    src: `\n      function f() {\n        try {\n          return f() + 1;\n        } catch (e) {\n          return 1;\n        }\n      }\n      var limit = f();\n      limit > 100 ? 'OK' : limit;\n    `,\n    options: {stackLimit: 1000},\n    expected: 'OK',\n  },\n];\n"
  },
  {
    "path": "server/tests/testing.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview General-purpose test infrastructure.\n * @author cpcallen@google.com (Christopher Allen)\n */\n'use strict';\n\nconst util = require('util');\n\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Class that records benchmark results; much like Go's testing.B type.\n * @constructor\n */\nfunction B() {\n  this.results = {};\n}\n\n/**\n * Report a benchmark or test result.\n * @param {string} status The test result status (e.g., 'OK', 'FAIL', 'SKIP').\n * @param {string} name Name of test.\n * @param {string=} message Additional information to lot about result.\n */\nB.prototype.result = function(status, name, message) {\n  console.log('%s\\t%s', status, name);\n  if (message) {\n    console.log(message);\n  }\n  this.results[status] = this.results[status] + 1 || 1;\n};\n\n/**\n * Report a benchmark start.\n * @param {string} name Name of test.  (Not used.)\n * @param {number} run Which run is this?  (Run 0 is warm-up run.)\n */\nB.prototype.start = function(name, run) {\n  const r = (run === 0) ? 'WARMUP' : ('RUN ' + run);\n  this.startTime = Date.now();\n};\n\n/**\n * Report a benchmark end.\n * @param {string} name Name of test.\n * @param {number} run Which run is this?  (Run 0 is warm-up run.)\n */\nB.prototype.end = function(name, run) {\n  const endTime = Date.now();\n  const r = (run === 0) ? 'WARMUP' : ('RUN ' + run);\n  console.log('%s\\t%s: %d ms', r, name, endTime - this.startTime);\n  this.startTime = Date.now();\n};\n\n/**\n * Report a benchmark or test failure due to crash.\n * @param {string} name Name of test.\n * @param {string=} message Additional info (e.g., stack trace) to log.\n */\nB.prototype.crash = function(name, message) {\n  this.result('CRASH', name, message);\n};\n\n/**\n * Report a bench or test skip.\n * @param {string} name Name of test.\n * @param {string=} message Additional info to log.\n */\nB.prototype.skip = function(name, message) {\n  this.result('SKIP', name, message);\n};\n\n/**\n * Return results as string.\n * @return {string}\n */\nB.prototype.toString = function() {\n  const lines = ['Totals:'];\n  for (const status in this.results) {\n    lines.push(util.format('%s\\t%d tests', status, this.results[status]));\n  }\n  return lines.join('\\n');\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Class that records test results; much like Go's testing.T type.\n * @constructor\n * @extends {B}\n */\nfunction T() {\n  B.call(this);\n  this.results['OK'] = 0;\n  this.results['FAIL'] = 0;\n}\n\nT.prototype = Object.create(B.prototype);\nT.prototype.constructor = T;\n\n/**\n * Report a test result.\n * @param {string} status The test result status (e.g., 'OK', 'FAIL', 'SKIP').\n * @param {string} name Name of test.\n * @param {string=} message Additional info to log.\n */\nT.prototype.result = function(status, name, message) {\n  status === 'OK' || console.log('%s:\\t%s', status, name);\n  if (message) {\n    console.log(message);\n  }\n  this.results[status] = this.results[status] + 1 || 1;\n};\n\n/**\n * Report a test pass.\n * @param {string} name Name of test.\n * @param {string=} message Additional info to log.\n */\nT.prototype.pass = function(name, message) {\n  this.result('OK', name, message);\n};\n\n/**\n * Report a test failure.\n * @param {string} name Name of test.\n * @param {string=} message Additional info to log.\n */\nT.prototype.fail = function(name, message) {\n  this.result('FAIL', name, message);\n};\n\n\n/**\n * Check if assertion is true and nd record test pass if so or test\n * failure otherwise.\n * @param {string} name The name of the test.\n * @param {*} assertion Condition to verify.\n * @param {string=} message Additional info to log on failure only.\n */\nT.prototype.assert = function(name, assertion, message) {\n  if (assertion) {\n    this.pass(name);\n  } else {\n    this.fail(name, message);\n  }\n};\n\n/**\n * Check if Object.is(got, want) and record test pass if so or test\n * failure otherwise.\n * @param {string} name The name of the test.\n * @param {*} got The actual result of the test.\n * @param {*} want The expected result of the test.\n * @param {string=} message Additional info to log on failure only.\n */\nT.prototype.expect = function(name, got, want, message) {\n  if (Object.is(got, want)) {\n    this.pass(name);\n  } else {\n    message = message ? message + '\\n' : '';\n    // Are they both strings, and at least one has multiple lines?\n    if (typeof(got) === 'string' && typeof(want) === 'string' &&\n        (got.trimRight().split('\\n').length > 1 ||\n        want.trimRight().split('\\n').length > 1)) {\n      message = util.format('%sgot:\\n%s\\nwant:\\n%s', message, got, want);\n    } else {\n      message = util.format('%sgot %o  want %o', message, got, want);\n    }\n    this.fail(name, message);\n  }\n};\n\nexports.B = B;\nexports.T = T;\n"
  },
  {
    "path": "server/tests/tinycore/README",
    "content": "A very tiny database, just big enough to run an eval server."
  },
  {
    "path": "server/tests/tinycore/core_00_es_minimal.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Polyfills to bring the server's partial JavaScript\n * implementation up to JavaScript 5.1 (or close to it).\n * @author fraser@google.com (Neil Fraser)\n */\n\n// Global functions.\nvar parseInt = new 'parseInt';\nvar parseFloat = new 'parseFloat';\nvar isNaN = new 'isNaN';\nvar isFinite = new 'isFinite';\n\n\n// Global objects.\nvar Object = new 'Object';\nvar Function = new 'Function';\nvar Array = new 'Array';\nvar String = new 'String';\nvar Boolean = new 'Boolean';\nvar Number = new 'Number';\nvar Date = new 'Date';\nvar RegExp = new 'RegExp';\nvar Error = new 'Error';\nvar EvalError = new 'EvalError';\nvar RangeError = new 'RangeError';\nvar ReferenceError = new 'ReferenceError';\nvar SyntaxError = new 'SyntaxError';\nvar TypeError = new 'TypeError';\nvar URIError = new 'URIError';\nvar Math = {};\nvar JSON = {};\n\n// Bootstrap the defineProperty function in two steps.\nObject.defineProperty = new 'Object.defineProperty';\nObject.defineProperty(Object, 'defineProperty', {enumerable: false});\n\n(function() {\n  // Hack to work around restriction that the 'new hack' only works on\n  // literal strings.  Note name must not contain any double quotes or\n  // backslashes, because we have no easy way to escape them yet!\n  var builtin = function(name) {\n    return eval('new \"' + name + '\"');\n  };\n\n  var classes = ['Object', 'Function', 'Array', 'String', 'Boolean', 'Number',\n                 'Date', 'RegExp', 'Error', 'EvalError', 'RangeError',\n                 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError'];\n  // Prototypes of global constructors.\n  for (var i = 0; i < classes.length; i++) {\n    var constructor = builtin(classes[i]);\n    Object.defineProperty(constructor, 'prototype', {\n                          configurable: false,\n                          enumerable: false,\n                          writable: false,\n                          value: builtin(classes[i] + '.prototype')\n                          });\n    Object.defineProperty(constructor.prototype, 'constructor', {\n                          configurable: true,\n                          enumerable: false,\n                          writable: true,\n                          value: constructor\n                          });\n  }\n  // Configure Error and its subclasses.\n  var errors = ['Error', 'EvalError', 'RangeError', 'ReferenceError',\n                'SyntaxError', 'TypeError', 'URIError'];\n  for (var i = 0; i < errors.length; i++) {\n    var constructor = builtin(errors[i]);\n    Object.defineProperty(constructor.prototype, 'name', {\n                          configurable: true,\n                          enumerable: false,\n                          writable: true,\n                          value: errors[i]\n                          });\n  }\n  Object.defineProperty(Error.prototype, 'message', {\n                        configurable: true,\n                        enumerable: false,\n                        writable: true,\n                        value: ''\n                        });\n\n  // Struct is a list of tuples:\n  //     [Object, 'Object', [static methods], [instance methods]]\n\n  var struct = [\n    [Object, 'Object',\n     ['create', 'getOwnPropertyNames', 'keys', 'getOwnPropertyDescriptor',\n      'getPrototypeOf', 'isExtensible', 'preventExtensions'],\n     ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',\n      'propertyIsEnumerable', 'isPrototypeOf']],\n    [Function, 'Function',\n     [],\n     ['apply', 'bind', 'call', 'toString']],\n    [Array, 'Array',\n     ['isArray'],\n     ['toString', 'pop', 'push', 'shift', 'unshift', 'reverse', 'splice',\n      'slice', 'concat', 'indexOf', 'lastIndexOf']],\n    [String, 'String',\n     ['fromCharCode'],\n     ['trim', 'toLowerCase', 'toUpperCase', 'toLocaleLowerCase',\n      'toLocaleUpperCase', 'charAt', 'charCodeAt', 'substring', 'slice',\n      'substr', 'indexOf', 'lastIndexOf', 'concat', 'localeCompare', 'replace',\n      'split', 'match', 'search', 'replace', 'toString', 'valueOf']],\n    [Boolean, 'Boolean',\n     [],\n     ['toString', 'valueOf']],\n    [Number, 'Number',\n     [],\n     ['toExponential', 'toFixed', 'toLocaleString', 'toPrecision', 'toString',\n      'valueOf']],\n    [Date, 'Date',\n     ['now', 'parse', 'UTC'],\n     ['toString', 'getDate', 'getDay', 'getFullYear', 'getHours',\n      'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime',\n      'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear',\n      'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth',\n      'getUTCSeconds', 'getYear', 'setDate', 'setFullYear', 'setHours',\n      'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime',\n      'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds',\n      'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear',\n      'toDateString', 'toISOString', 'toJSON', 'toGMTString', 'toTimeString',\n      'toUTCString', 'toLocaleDateString', 'toLocaleString',\n      'toLocaleTimeString']],\n    [RegExp, 'RegExp',\n     [],\n     ['toString', 'test', 'exec']],\n    [Error, 'Error',\n     [],\n     ['toString']],\n    [Math, 'Math',\n     ['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor',\n      'log', 'max', 'min', 'pow', 'random', 'round', 'sin', 'sqrt', 'tan'],\n     []],\n    [JSON, 'JSON',\n     ['parse', 'stringify'],\n     []]\n  ];\n  for (var i = 0; i < struct.length; i++) {\n    var obj = struct[i][0];\n    var objName = struct[i][1];\n    var staticMethods = struct[i][2];\n    var instanceMethods = struct[i][3];\n    for (var j = 0; j < staticMethods.length; j++) {\n      var member = staticMethods[j];\n      Object.defineProperty(obj, member,\n          {configurable: true,\n           enumerable: false,\n           writable: true,\n           value: builtin(objName + '.' + member)});\n    }\n    for (var j = 0; j < instanceMethods.length; j++) {\n      var member = instanceMethods[j];\n      Object.defineProperty(obj.prototype, member,\n          {configurable: true,\n           enumerable: false,\n           writable: true,\n           value: builtin(objName + '.prototype.' + member)});\n    }\n  }\n})();\n\nObject.defineProperty(Number, 'MAX_VALUE', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 1.7976931348623157e+308\n                      });\nObject.defineProperty(Number, 'MIN_VALUE', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 5e-324\n                      });\nObject.defineProperty(Number, 'NaN', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: NaN\n                      });\nObject.defineProperty(Number, 'NEGATIVE_INFINITY', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: -Infinity\n                      });\nObject.defineProperty(Number, 'POSITIVE_INFINITY', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: Infinity\n                      });\n\nObject.defineProperty(Math, 'E', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 2.718281828459045\n                      });\nObject.defineProperty(Math, 'LN2', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 0.6931471805599453\n                      });\nObject.defineProperty(Math, 'LN10', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 2.302585092994046\n                      });\nObject.defineProperty(Math, 'LOG2E', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 1.4426950408889634\n                      });\nObject.defineProperty(Math, 'LOG10E', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 0.4342944819032518\n                      });\nObject.defineProperty(Math, 'PI', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 3.141592653589793\n                      });\nObject.defineProperty(Math, 'SQRT1_2', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 0.7071067811865476\n                      });\nObject.defineProperty(Math, 'SQRT2', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: 1.4142135623730951\n                      });\n\nObject.defineProperty(RegExp.prototype, 'global', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: undefined\n                      });\nObject.defineProperty(RegExp.prototype, 'ignoreCase', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: undefined\n                      });\nObject.defineProperty(RegExp.prototype, 'multiline', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: undefined\n                      });\nObject.defineProperty(RegExp.prototype, 'source', {\n                      configurable: false,\n                      enumerable: false,\n                      writable: false,\n                      value: '(?:)'\n                      });\n\n///////////////////////////////////////////////////////////////////////////////\n// Array.prototype polyfills\n///////////////////////////////////////////////////////////////////////////////\n\n(function() {\n  // For cycle detection in array to string and error conversion; see\n  // spec bug github.com/tc39/ecma262/issues/289.\n  var visited = [];\n\n  Object.defineProperty(Array.prototype, 'join', {value: function(separator) {\n    // This implements Array.prototype.join from ES5 §15.4.4.5, with\n    // the addition of cycle detection as discussed in\n    // https://github.com/tc39/ecma262/issues/289.\n    //\n    // Variable names reflect those in the spec.\n    //\n    // N.B. This function is defined in a closure!\n    var isObj = (typeof this === 'object' || typeof this === 'function') &&\n        this !== null;\n    if (isObj) {\n      if (visited.indexOf(this) !== -1) {\n        return '';\n      }\n      visited.push(this);\n    }\n    try {\n      // TODO(cpcallen): setPerms(callerPerms());\n      var len = this.length >>> 0;\n      var sep = (separator === undefined) ? ',' : String(separator);\n      if (!len) {\n        return '';\n      }\n      var r = '';\n      for (var k = 0; k < len; k++) {\n        if (k > 0) r += sep;\n        var element = this[k];\n        if (element !== undefined && element !== null) {\n          r += String(element);\n        }\n      }\n      return r;\n    } finally {\n      if (isObj) visited.pop();\n    }\n  }, configurable: true, writable: true});\n})();\n\n///////////////////////////////////////////////////////////////////////////////\n// String.prototype polyfills\n///////////////////////////////////////////////////////////////////////////////\n\n// String.prototype.length is always 0.\nObject.defineProperty(String.prototype, 'length', {value: 0});\n"
  },
  {
    "path": "server/tests/tinycore/core_10_base.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Demonstration database for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n\nvar $ = function() {\n  throw new Error('not implemented');\n};\n\n// System object: $.system\n$.system = {};\n$.system.connectionListen = new 'CC.connectionListen';\n$.system.connectionUnlisten = new 'CC.connectionUnlisten';\n$.system.connectionWrite = new 'CC.connectionWrite';\n$.system.connectionClose = new 'CC.connectionClose';\n$.system.xhr = new 'CC.xhr';\n\n// Utility object: $.utils\n$.utils = {};\n\n\n$.connection = {};\n\n$.connection.onConnect = function() {\n  this.user = null;\n  this.buffer = '';\n};\n\n$.connection.onReceive = function(text) {\n  this.buffer += text.replace(/\\r/g, '');\n  var lf;\n  while ((lf = this.buffer.indexOf('\\n')) !== -1) {\n    var line = this.buffer.substring(0, lf);\n    this.buffer = this.buffer.substring(lf + 1);\n    this.onReceiveLine(line);\n  }\n};\n\n$.connection.onReceiveLine = function(text) {\n  // Override this on child classes.\n};\n\n$.connection.onEnd = function() {\n  // Override this on child classes.\n};\n\n$.connection.write = function(text) {\n  $.system.connectionWrite(this, text);\n};\n\n$.connection.close = function() {\n  $.system.connectionClose(this);\n};\n\n$.servers = {};\n"
  },
  {
    "path": "server/tests/tinycore/core_13_$.utils.code.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Code utilities for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n\n$.utils.code = {};\n\n\n$.utils.code.toSource = function(value, opt_seen) {\n  // Given an arbitrary value, produce a source code representation.\n  // Primitive values are straightforward: \"42\", \"'abc'\", \"false\", etc.\n  // Functions, RegExps, Dates, Arrays, and errors are returned as their\n  // definitions.\n  // Other objects and symbols are returned as selector expression.\n  // Throws if a code representation can't be made.\n  var type = typeof value;\n  if (value === undefined || value === null ||\n      type === 'number' || type === 'boolean') {\n    if (Object.is(value, -0)) {\n      return '-0';\n    }\n    return String(value);\n  } else if (type === 'string') {\n    return JSON.stringify(value);\n  } else if (type === 'function') {\n    return Function.prototype.toString.call(value);\n  } else if (type === 'object') {\n    // TODO: Replace opt_seen with Set, once available.\n    if (opt_seen) {\n      if (opt_seen.includes(value)) {\n        throw new RangeError('[Recursive data structure]');\n      }\n      opt_seen.push(value);\n    } else {\n      opt_seen = [value];\n    }\n    var proto = Object.getPrototypeOf(value);\n    if (proto === RegExp.prototype) {\n      return String(value);\n    } else if (proto === Date.prototype) {\n      return 'Date(\\'' + value.toJSON() + '\\')';\n    } else if (proto === Array.prototype && Array.isArray(value) &&\n               value.length <= 100) {\n      var props = Object.getOwnPropertyNames(value);\n      var data = [];\n      for (var i = 0; i < value.length; i++) {\n        if (props.includes(String(i))) {\n          try {\n            data[i] = $.utils.code.toSource(value[i], opt_seen);\n          } catch (e) {\n            // Recursive data structure.  Bail.\n            data = null;\n            break;\n          }\n        } else {\n          data[i] = '';\n        }\n      }\n      if (data) {\n        return '[' + data.join(', ') + ']';\n      }\n    } else if (value instanceof Error) {\n      var constructor;\n      if (proto === Error.prototype) {\n        constructor = 'Error';\n      } else if (proto === EvalError.prototype) {\n        constructor = 'EvalError';\n      } else if (proto === RangeError.prototype) {\n        constructor = 'RangeError';\n      } else if (proto === ReferenceError.prototype) {\n        constructor = 'ReferenceError';\n      } else if (proto === SyntaxError.prototype) {\n        constructor = 'SyntaxError';\n      } else if (proto === TypeError.prototype) {\n        constructor = 'TypeError';\n      } else if (proto === URIError.prototype) {\n        constructor = 'URIError';\n      } else if (proto === PermissionError.prototype) {\n        constructor = 'PermissionError';\n      }\n      var msg;\n      if (value.message === undefined) {\n        msg = '';\n      } else {\n        try {\n          msg = $.utils.code.toSource(value.message, opt_seen);\n        } catch (e) {\n          // Leave msg undefined.\n        }\n      }\n      if (constructor && msg !== undefined) {\n        return constructor + '(' + msg + ')';\n      }\n    }\n  }\n  if (type === 'object' || type === 'symbol') {\n    // No Selectors in this tiny db, so just toString it.\n    return Object.prototype.toString.call(value);\n  }\n  // Can't happen.\n  throw new TypeError('[' + type + ']');\n};\n\n$.utils.code.eval = function(src, evalFunc) {\n  // Eval src and attempt to print the resulting value readably.\n  //\n  // Evaluation is done by calling evalFunc (passing src) if supplied,\n  // or by calling the eval built-in function (under a different name,\n  // so it operates in the global scope).  Unhandled exceptions are\n  // caught and converted to a string.\n  //\n  // Caller may wish to transform input with\n  // $.utils.code.rewriteForEval before passing it to this function.\n  evalFunc = evalFunc || eval;\n  var out;\n  try {\n    out = evalFunc(src);\n    try {\n      // Attempt to print a source-legal representation.\n      out = $.utils.code.toSource(out);\n    } catch (e) {\n      try {\n        // Maybe it's something JSON can deal with (like an array).\n        out = JSON.stringify(out);\n      } catch (e) {\n        try {\n          // Maybe it's a recursive data structure.\n          out = String(out);\n        } catch (e) {\n          // Maybe it's Object.create(null).\n          out = '[Unprintable value]';\n        }\n      }\n    }\n  } catch (e) {\n    // Exception thrown.  Use built-in ToString via + to avoid calling\n    // String, least it call a .toString method that itself throws.\n    // TODO(cpcallen): find an alternative way of doing this safely\n    // once the interpreter calls String for all string conversions.\n    if (e instanceof Error) {\n      out = 'Unhandled error: ' + e.name;\n      if (e.message) {\n        out += ': ' + e.message;\n      }\n      if (e.stack) {\n        out += '\\n' + e.stack;\n      }\n    } else {\n      out = 'Unhandled exception: ' + e;\n    }\n  }\n  return out;\n};\n"
  },
  {
    "path": "server/tests/tinycore/core_35_$.servers.eval.js",
    "content": "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Eval server for Code City.\n * @author cpcallen@google.com (Christopher Allen)\n */\n\n$.servers.eval = {};\n\n$.servers.eval.connected = null;\n\n$.servers.eval.connection = Object.create($.connection);\n\n$.servers.eval.connection.onConnect = function() {\n  $.connection.onConnect.apply(this, arguments);\n  if ($.servers.eval.connected) {\n    $.servers.eval.connected.close();\n  }\n  $.servers.eval.connected = this;\n  this.write('eval> ');\n};\n\n$.servers.eval.connection.onReceiveLine = function(text) {\n  if (this !== $.servers.eval.connected) {\n    this.close();\n    return;\n  }\n  this.write('⇒ ' + $.utils.code.eval(text) + '\\n');\n  this.write('eval> ');\n};\n\n$.servers.eval.connection.onEnd = function() {\n  $.servers.eval.connected = null;\n  return $.connection.onEnd.apply(this, arguments);\n};\n\n$.servers.eval.connection.close = function() {\n  this.write('This session has been terminated.\\n');\n  return $.connection.close.apply(this, arguments);\n};\n\n\n$.system.connectionListen(9999, $.servers.eval.connection, 100);\n"
  },
  {
    "path": "server/tests/tinycore/dump_spec.json",
    "content": "[\n  {\n    \"filename\": \"core_00_es_minimal.js\",\n    \"contents\": [\n      {\"path\": \"Object\", \"do\": \"SET\"},\n      {\"path\": \"Function\", \"do\": \"SET\"},\n      {\"path\": \"Object.defineProperty\", \"do\": \"ATTR\"},\n      \"Object\",\n      \"Function\",\n      \"Array\",\n      \"String\",\n      \"Boolean\",\n      \"Number\",\n      \"Date\",\n      \"RegExp\",\n      \"Error\",\n      \"EvalError\",\n      \"RangeError\",\n      \"ReferenceError\",\n      \"SyntaxError\",\n      \"TypeError\",\n      \"URIError\",\n      \"Math\",\n      \"JSON\",\n      \"isFinite\",\n      \"isNaN\",\n      \"parseFloat\",\n      \"parseInt\"\n    ]\n  }, {\n    \"filename\": \"core_10_base.js\",\n    \"contents\": [\n      {\"path\": \"$\", \"do\": \"SET\"},\n      \"$.system\",\n      \"$.utils\",\n      \"$.connection\",\n      \"$.servers\"\n    ]\n  }, {\n    \"filename\": \"core_13_$.utils.code.js\",\n    \"contents\": [\n      \"$.utils.code\"\n    ]\n  }, {\n    \"filename\": \"core_35_$.servers.eval.js\",\n    \"contents\": [\n      \"$.servers.eval\"\n    ]\n  }, {\n    \"options\": {\"treeOnly\": false}\n  }, {\n    \"filename\": \"core_99_rest.js\",\n    \"rest\": true\n  }\n]\n"
  },
  {
    "path": "server/tests/tinycore/tiny.cfg",
    "content": "{\n  \"databaseDirectory\": \"./\",\n  \"checkpointInterval\": 0,\n  \"checkpointAtShutdown\": false,\n  \"checkpointMinFiles\": 0,\n  \"checkpointMaxDirectorySize\": 0\n}\n"
  },
  {
    "path": "static/503.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n<head>\n  <title>503 - Code City</title>\n  <style>\n    body {\n      font-family: \"Roboto Mono\", monospace;\n      text-align: center;\n    }\n    h1 {\n      font-size: 40pt;\n      font-weight: 100;\n    }\n    h1>img {\n      vertical-align: text-bottom;\n    }\n    #tagline {\n      font-style: italic;\n      margin: 2em;\n    }\n  </style>\n  <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto+Mono\">\n  <link rel=\"shortcut icon\" href=\"/static/favicon.ico\">\n</head>\n<body>\n  <h1>\n    <img src=\"/static/logo-error.svg\" width=\"95px\" height=\"100px\" alt=\"\">\n    503 Unavailable\n  </h1>\n  <p>Uh oh&hellip;</p>\n  <p>For some reason the Code City server is not\n  responding to HTTP connections.  Could be that it has crashed,\n  overloaded, or down for maintenance&mdash;or it could be that we've\n  accidentally broken the internal web server (<tt>$.servers.http</tt>).  In\n  the latter case you <em>might</em> still be able\n  to <a href=\"/login\">login&nbsp;via the telnet&nbsp;interface</a> as usual.</p>\n  <p>In any case the problem is likely to be temporary so do please\n  come back later and try again!</p>\n</body>\n</html>\n"
  },
  {
    "path": "static/code/code.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Integrated Development Environment for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\n/**\n * If not otherwise specified, what should /code point at?\n */\nCode.DEFAULT = '$';\n\n/**\n * Raw string of selector.\n * E.g. '$.foo[\"bar\"]'\n */\nCode.selector = location.search ?\n    decodeURIComponent(location.search.substring(1)) : Code.DEFAULT;\n\n/**\n * Got a ping from someone.  Check sessionStorage to see if selector has\n * changed and, if so, propagate ping to subframes.\n * @param {?Event} event Message event, or null if called from popState.\n */\nCode.receiveMessage = function(event) {\n  // Check to see if the stored values have changed.\n  var selector = sessionStorage.getItem(Code.Common.SELECTOR);\n  if (selector === Code.selector) {\n    return;\n  }\n  Code.selector = selector;\n  if (event) {\n    // Change the URL if this is NOT the result of a forwards/back navigation.\n    var query = encodeURIComponent(selector);\n    query = query.replace(/%24/g, '$');  // No need to encode $.\n    history.pushState(selector, selector, '?' + query);\n  }\n  // Propagate the ping down the tree of frames.\n  try {\n    document.getElementById('explorer').contentWindow.postMessage('ping', '*');\n  } catch (e) {\n    // Maybe explorer frame hasn't loaded yet.\n  }\n  try {\n    document.getElementById('editor').contentWindow.postMessage('ping', '*');\n  } catch (e) {\n    // Maybe editor frame hasn't loaded yet.\n  }\n  Code.setTitle();\n};\n\n/**\n * User has navigated forwards or backwards.\n * @param {!Event} event History change event.\n */\nCode.popState = function(event) {\n  var selector = event.state || Code.DEFAULT;\n  sessionStorage.setItem(Code.Common.SELECTOR, selector);\n  // Attempt to pull the focus away from the explorer's input field.\n  // This will allow it to update the displayed selector.\n  try {\n    document.getElementById('explorer').contentDocument\n        .getElementById('input').blur();\n  } catch (e) {\n    console.log('Unable to blur input: ' + e);\n  }\n  Code.receiveMessage(null);\n};\n\n/**\n * Set the code editor's title.\n */\nCode.setTitle = function() {\n  var title = Code.selector;\n  if (title.length > 36) {\n    // Max title length in Chrome is 36 before truncation.\n    title = '…' + title.substr(-35);\n  }\n  document.title = title;\n};\n\nif (!window.TEST) {\n  Code.setTitle();\n  sessionStorage.setItem(Code.Common.SELECTOR, Code.selector);\n  window.addEventListener('message', Code.receiveMessage, false);\n  window.addEventListener('popstate', Code.popState, false);\n}\n\n////////////////////////////////////////////\n// Add bridge for SVG editor's clipboard.  This copy allows the clipboard to\n// sync across all /code tabs even if the SVG editor isn't currently loaded.\n// Copied from /code/SVG-Edit/svgcanvas.js\n\nconst CLIPBOARD_ID = 'svgedit_clipboard';\n\n/**\n* Flash the clipboard data momentarily on localStorage so all tabs can see.\n* @returns {void}\n*/\nfunction flashStorage () {\n  const data = sessionStorage.getItem(CLIPBOARD_ID);\n  localStorage.setItem(CLIPBOARD_ID, data);\n  setTimeout(function () {\n    localStorage.removeItem(CLIPBOARD_ID);\n  }, 1);\n}\n\n/**\n* Transfers sessionStorage from one tab to another.\n* @param {!Event} ev Storage event.\n* @returns {void}\n*/\nfunction storageChange(ev) {\n  if (!ev.newValue) return; // This is a call from removeItem.\n  if (ev.key === CLIPBOARD_ID + '_startup') {\n    // Another tab asked for our sessionStorage.\n    localStorage.removeItem(CLIPBOARD_ID + '_startup');\n    flashStorage();\n  } else if (ev.key === CLIPBOARD_ID) {\n    // Another tab sent data.\n    sessionStorage.setItem(CLIPBOARD_ID, ev.newValue);\n  }\n}\n\n// Listen for changes to localStorage.\nwindow.addEventListener('storage', storageChange, false);\n// Ask other tabs for sessionStorage (this is ONLY to trigger event).\nlocalStorage.setItem(CLIPBOARD_ID + '_startup', Math.random());\n\n// End of bridge for SVG editor's clipboard.\n////////////////////////////////////////////\n"
  },
  {
    "path": "static/code/common.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Integrated Development Environment for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nvar Code = {};\nCode.Common = {};\n\n// Keys for the sessionStorage.\nCode.Common.SELECTOR = 'code selector';\n\n// Set containing all supported {xyz} names.\nCode.Common.KEYWORD_TYPES =\n    new Set(['{proto}', '{owner}', '{children}', '{owned}', '{keys}', '{values}']);\n\n/**\n * Tokenize a string such as '$.foo[\"bar\"]' into tokens:\n *   {type: \"id\",  raw: \"$\",     valid: true, index: 0, value: \"$\"}\n *   {type: \".\",   raw: \".\",     valid: true, index: 1}\n *   {type: \"id\",  raw: \"foo\",   valid: true, index: 2, value: \"foo\"}\n *   {type: \"[\",   raw: \"[\",     valid: true, index: 5}\n *   {type: \"str\", raw: \"\"bar\"\", valid: true, index: 6, value: \"bar\"}\n *   {type: \"]\",   raw: \"]\",     valid: true, index: 11}\n * Other tokens include:\n *   {type: \"num\",     raw: \"42\",         valid: true, index: 2, value: 42}\n *   {type: \"keyword\", raw: \"{proto}\",    valid: true, index: 5, value: '{proto}'}\n *   {type: \"keyword\", raw: \"{owner}\",    valid: true, index: 5, value: '{owner}'}\n *   {type: \"keyword\", raw: \"{children}\", valid: true, index: 5, value: '{children}'}\n *   {type: \"keyword\", raw: \"{owned}\",    valid: true, index: 5, value: '{owned}'}\n *   {type: \"keyword\", raw: \"{keys}\",     valid: true, index: 5, value: '{keys}'}\n *   {type: \"keyword\", raw: \"{values}\",   valid: true, index: 5, value: '{values}'}\n * If the string is permanently invalid, the last token is:\n *   {type: \"?\",   raw: \"\",      valid: false}\n * A temporary token is used internally during parsing:\n *   {type: \"unparsed\", raw: \"[42].foo\", index: 8}\n * @param {string} text Selector string.\n * @return {!Array<!Object>} Array of tokens.\n */\nCode.Common.tokenizeSelector = function(text) {\n  // Trim left whitespace.\n  var trimText = text.replace(/^[\\s\\xa0]+/, '');\n  if (!trimText) {\n    return [];\n  }\n  var whitespaceLength = text.length - trimText.length;\n  text = trimText;\n\n  // Split the text into an array of tokens.\n  // First step is to create two types of tokens: 'str' and 'unparsed'.\n  var state = null;\n  // null - non-string state\n  // 'sqStr' - single quote string\n  // 'dqStr' - double quote string\n  // 'sqSlash' - backslash in single quote string\n  // 'dqSlash' - backslash in double quote string\n  var tokens = [];\n  var buffer = [];\n  for (var i = 0; i < text.length; i++) {\n    var char = text[i];\n    var index = whitespaceLength + i;\n    if (state === null) {\n      if (char === \"'\") {\n        Code.Common.pushUnparsed_(buffer, index, tokens);\n        state = 'sqStr';\n      } else if (char === '\"') {\n        Code.Common.pushUnparsed_(buffer, index, tokens);\n        state = 'dqStr';\n      } else {\n        buffer.push(char);\n      }\n    } else if (state === 'sqStr') {\n      if (char === \"'\") {\n        Code.Common.pushString_(\"'\", buffer, index, tokens);\n        state = null;\n      } else {\n        buffer.push(char);\n        if (char === '\\\\') {\n          state = 'sqSlash';\n        }\n      }\n    } else if (state === 'dqStr') {\n      if (char === '\"') {\n        Code.Common.pushString_('\"', buffer, index, tokens);\n        state = null;\n      } else {\n        buffer.push(char);\n        if (char === '\\\\') {\n          state = 'dqSlash';\n        }\n      }\n    } else if (state === 'sqSlash') {\n      buffer.push(char);\n      state = 'sqStr';\n    } else if (state === 'dqSlash') {\n      buffer.push(char);\n      state = 'dqStr';\n    }\n  }\n  if (state !== null) {\n    // Convert state into quote type.\n    var quotes = (state === 'sqStr' || state === 'sqSlash') ? \"'\" : '\"';\n    Code.Common.pushString_(quotes, buffer, index + 1, tokens);\n  } else if (buffer.length) {\n    Code.Common.pushUnparsed_(buffer, index + 1, tokens);\n  }\n\n  // Second step is to parse each 'unparsed' token and split out '[', and ']'\n  // tokens.\n  for (var i = tokens.length - 1; i >= 0; i--) {\n    var token = tokens[i];\n    if (token.type === 'unparsed') {\n      var index = token.index + token.raw.length;\n      // Split string on brackets.\n      var split = token.raw.split(/(\\s*[\\[\\]]\\s*)/);\n      for (var j = split.length - 1; j >= 0; j--) {\n        var raw = split[j];\n        index -= raw.length;\n        var rawTrim = raw.trim();\n        if (raw === '') {\n          split.splice(j, 1);  // Delete the empty string.\n          continue;\n        } else if (rawTrim === '[' || rawTrim === ']') {\n          split[j] = {type: rawTrim, valid: true};\n        } else {\n          split[j] = {type: 'unparsed'};\n        }\n        split[j].raw = raw;\n        split[j].index = index;\n      }\n      // Replace token with split array.\n      split.unshift(i, 1);\n      Array.prototype.splice.apply(tokens, split);\n    }\n  }\n\n  // Third step is to parse each 'unparsed' token and split out '{xxx}' tokens.\n  for (var i = tokens.length - 1; i >= 0; i--) {\n    var token = tokens[i];\n    if (token.type === 'unparsed') {\n      var index = token.index + token.raw.length;\n      var split = token.raw.split(/(\\s*{\\s*\\w*\\s*(?:}\\s*|$))/);\n      for (var j = split.length - 1; j >= 0; j--) {\n        var raw = split[j];\n        index -= raw.length;\n        var rawTrim = raw.trim();\n        if (raw === '') {\n          split.splice(j, 1);  // Delete the empty string.\n          continue;\n        }\n        var m = rawTrim.match(/{\\s*(\\w*)\\s*(}|$)/);\n        if (m) {\n          var keywordToken = {type: 'keyword', value: '{' + m[1] + m[2]};\n          keywordToken.complete =\n              Code.Common.KEYWORD_TYPES.has(keywordToken.value);\n          if (keywordToken.complete) {\n            keywordToken.valid = true;\n          } else {\n            keywordToken.valid = false;\n            for (var validKeyword of Code.Common.KEYWORD_TYPES) {\n              if (validKeyword.startsWith(keywordToken.value)) {\n                keywordToken.valid = true;\n                break;\n              }\n            }\n          }\n          split[j] = keywordToken;\n        } else {\n          split[j] = {type: 'unparsed'};\n        }\n        split[j].raw = raw;\n        split[j].index = index;\n      }\n      // Replace token with split array.\n      split.unshift(i, 1);\n      Array.prototype.splice.apply(tokens, split);\n    }\n  }\n\n  // Fourth step is to parse each 'unparsed' token as a number, if it is\n  // preceded by a '[' token.  If the result is NaN (e.g. in the case it is an\n  // unquoted identifier) mark the token as invalid.\n  for (var i = 1; i < tokens.length; i++) {\n    var token = tokens[i];\n    if (tokens[i - 1].type === '[' && token.type === 'unparsed') {\n      token.type = 'num';\n      token.value = NaN;\n      token.valid = false;\n      // Does not support E-notation or NaN.\n      if (/^\\s*[-+]?(\\d*\\.?\\d*|Infinity)\\s*$/.test(token.raw)) {\n        token.value = Number(token.raw);\n        token.valid = !isNaN(token.value);\n        token.value = String(token.value);\n      }\n    }\n  }\n\n  // Fifth step is to split remaining 'unparsed' tokens into 'id' and '.'\n  // tokens.  The '.' tokens could not be split out before numbers were parsed,\n  // since numbers have decimal points.\n  var unicodeRegex = /\\\\u([0-9A-F]{4})/ig;\n  function decodeUnicode(m, p1) {\n    return String.fromCodePoint(parseInt(p1, 16));\n  }\n  for (var i = tokens.length - 1; i >= 0; i--) {\n    var token = tokens[i];\n    if (token.type !== 'unparsed') {\n      continue;\n    }\n    var index = token.index + token.raw.length;\n    // Split string on periods.\n    var split = token.raw.split(/(\\s*\\.\\s*)/);\n    for (var j = split.length - 1; j >= 0; j--) {\n      var raw = split[j];\n      index -= raw.length;\n      if (raw === '') {\n        split.splice(j, 1);  // Delete the empty string.\n        continue;\n      } else if (raw.trim() === '.') {\n        split[j] = {\n          type: '.',\n          valid: true\n        };\n      } else {\n        // Parse Unicode escapes in identifiers.\n        var valid = true;\n        var value = split[j];\n        while (true) {\n          var test = value.replace(unicodeRegex, '');\n          if (!test.includes('\\\\')) {\n            break;\n          }\n          // Invalid escape found.  Trim off last char and try again.\n          value = value.substring(0, value.length - 1);\n          valid = false;\n        }\n        // Decode Unicode.\n        value = value.replace(unicodeRegex, decodeUnicode);\n        split[j] = {type: 'id', value: value, valid: valid};\n      }\n      split[j].raw = raw;\n      split[j].index = index;\n    }\n    // Replace token with split array.\n    split.unshift(i, 1);\n    Array.prototype.splice.apply(tokens, split);\n  }\n\n  // Finally, validate order of tokens.  Only check for permanent errors.\n  // E.g. '$..foo' can never be legal.\n  // E.g. '$[\"foo' isn't legal now, but could become legal after more typing.\n  var state = 0;\n  // 0 - Start or after '.'.  Expecting 'id'.\n  // 1 - After 'id' or ']' or 'keyword'.\n  //     Expecting '.' or '[' or 'keyword'.\n  // 2 - After '['.  Expecting 'str' or 'num'.\n  // 3 - After 'str' or 'num'.  Expecting ']'.\n  for (var i = 0; i < tokens.length; i++) {\n    var token = tokens[i];\n    if (state === 0) {\n      if (token.type === 'id') {\n        state = 1;\n      } else {\n        break;\n      }\n    } else if (state === 1) {\n      if (token.type === '.') {\n        state = 0;\n      } else if (token.type === 'keyword') {\n        state = 1;\n      } else if (token.type === '[') {\n        state = 2;\n      } else {\n        break;\n      }\n    } else if (state === 2) {\n      if (token.type === 'str' || token.type === 'num') {\n        state = 3;\n      } else {\n        break;\n      }\n    } else if (state === 3) {\n      if (token.type === ']') {\n        state = 1;\n      } else {\n        break;\n      }\n    } else {\n      break;\n    }\n  }\n  // Remove any illegal tokens.\n  if (i < tokens.length) {\n    tokens = tokens.slice(0, i);\n    // Add fail token to prevent autocompletion.\n    tokens.push({type: '?', raw: '', valid: false});\n  }\n  return tokens;\n};\n\n/**\n * Push a 'str' token type onto the list of tokens.\n * Handles invalid strings, e.g. 'abc \\u---- xyz'\n * @param {string} quotes Quote type (' vs \").\n * @param {!Array<string>} buffer Array of chars that make the string.\n * @param {number} index Char index of start of this token in original input.\n * @param {!Array<!Object>} tokens List of tokens.\n * @private\n */\nCode.Common.pushString_ = function(quotes, buffer, index, tokens) {\n  var token = {\n    type: 'str',\n    raw: quotes + buffer.join('') + quotes,\n    valid: true\n  };\n  token.index = index - (token.raw.length - 1);\n  do {\n    var raw = quotes + buffer.join('') + quotes;\n    // Attempt to parse a string.\n    try {\n      var str = eval(raw);\n      break;\n    } catch (e) {\n      // Invalid escape found.  Trim off last char and try again.\n      buffer.pop();\n      token.valid = false;\n    }\n  } while (true);\n  buffer.length = 0;\n  token.value = str;\n  tokens.push(token);\n};\n\n/**\n * Push an 'unparsed' token type onto the list of tokens.\n * @param {!Array<string>} buffer Array of chars that make the value.\n * @param {number} index Character index of this token in original input.\n * @param {!Array<!Object>} tokens List of tokens.\n * @private\n */\nCode.Common.pushUnparsed_ = function(buffer, index, tokens) {\n  var raw = buffer.join('');\n  buffer.length = 0;\n  if (raw) {\n    var token = {\n      type: 'unparsed',\n      raw: raw,\n      index: index - raw.length\n    };\n    tokens.push(token);\n  }\n};\n\n/**\n * Split a path selector into a list of parts.\n * E.g. '${proto}.foo' ->\n *   [{type: 'id', value: '$'}, {type: 'keyword', value: '{proto}'}, {type: 'id', value: 'foo'}]\n * @param {string} text Selector string.\n * @return {?Array<!Object>} Array of parts or null if invalid.\n */\nCode.Common.selectorToParts = function(text) {\n  // TODO: Try caching the results for performance.\n  var tokens = Code.Common.tokenizeSelector(text);\n  var parts = [];\n  for (var token of tokens) {\n    if (!token.valid) {\n      return null;\n    }\n    if (['id', 'str', 'num'].includes(token.type)) {\n      parts.push({type: 'id', value: token.value});\n    } else if (token.type === 'keyword') {\n      parts.push({type: token.type, value: token.value});\n    }\n  }\n  return parts;\n};\n\n/**\n * Join a list of parts into a path selector.\n * E.g. [{type: 'id', value: '$'}, {type: 'keyword', value: '{proto}'}, {type: 'id', value: 'foo'}] ->\n *   '${proto}.foo'\n * @param {!Array<!Object>} parts Array of parts.\n * @return {string} Selector string.\n */\nCode.Common.partsToSelector = function(parts) {\n  var text = '';\n  for (var i = 0; i < parts.length; i++) {\n    var part = parts[i];\n    if (part.type === 'id') {\n      var value = part.value;\n      if (/^[A-Z_$][0-9A-Z_$]*$/i.test(value)) {\n        if (i !== 0) {\n          text += '.';\n        }\n        text += value;\n      } else {\n        text += '[';\n        if (/^-?\\d{1,15}$/.test(value)) {\n          text += value;\n        } else {\n          text += JSON.stringify(value);\n        }\n        text += ']';\n      }\n    } else if (part.type === 'keyword') {\n      text += part.value;\n    }\n  }\n  return text;\n};\n\n/**\n * Turn a selector string into a valid code reference.\n * E.g. \"$.foo\" -> \"$.foo\"\n * E.g. \"${proto}.foo\" -> \"$('${proto}.foo')\"\n * Join a list of parts into a valid code reference.\n * @param {string} selector Selector string.\n * @return {string} Code reference.\n */\nCode.Common.selectorToReference = function(selector) {\n  var noStrings = selector.replace(/([\"'])(?:[^\\1\\\\]|\\\\.)*?\\1/g, '');\n  if (noStrings.includes('{')) {\n    return \"$('\" + selector + \"')\";\n  }\n  return selector;\n};\n\n/**\n * Comparison function to sort strings A-Z without regard to case.\n * @param {string} a One string.\n * @param {string} b Another string.\n * @return {number} -1/0/1 comparator value.\n */\nCode.Common.caseInsensitiveComp = function(a, b) {\n  a = a.toLowerCase();\n  b = b.toLowerCase();\n  var aNum = parseFloat(a);\n  var bNum = parseFloat(b);\n  if (!isNaN(aNum) && !isNaN(bNum) && aNum !== bNum) {\n    // Numeric.\n    return (aNum < bNum) ? -1 : 1;\n  }\n  // ASCIIbetical.\n  return (a < b) ? -1 : ((a > b) ? 1 : 0);\n};\n\n// Set background colour to differentiate server vs local copy.\nif (location.hostname === 'localhost') {\n  window.addEventListener('load', function() {\n    document.body.style.backgroundColor = '#ffe';\n  });\n}\n"
  },
  {
    "path": "static/code/diff.css",
    "content": "body {\n  white-space: pre-wrap;\n}\n\nins {\n  background: #e6ffe6;\n}\n\ndel {\n  background: #ffe6e6;\n}\n"
  },
  {
    "path": "static/code/diff.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Diff Editor.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nvar diffEditor = {};\n\n/**\n * Diff Match Patch object.\n */\ndiffEditor.dmp = new diff_match_patch();\n\n/**\n * Current source.\n */\ndiffEditor.source = '';\n\n/**\n * Check to see if the parent window left us an initial source to render.\n */\ndiffEditor.init = function() {\n  var newSource = window.initialSource;\n  var oldSource = window.originalSource;\n  if (newSource && oldSource) {\n    diffEditor.setString(newSource, oldSource);\n    delete window.initialSource;\n    delete window.originalSource;\n  }\n};\n\n/**\n * Set the strings for a new diff.\n * @param {string} newString Current source.\n * @param {string} oldString Source as of last save.\n */\ndiffEditor.setString = function(newString, oldString) {\n  this.source = newString;\n  var diff = this.dmp.diff_main(oldString, newString);\n  this.dmp.diff_cleanupSemantic(diff);\n  diffEditor.render(diff, document.body);\n};\n\n/**\n * Return the current source.\n * @return {string} Source.\n */\ndiffEditor.getString = function() {\n  return this.source;\n};\n\n/**\n * Convert a diff array into a pretty HTML report and inject it on the page.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @param {!Element} container HTML element into which to render the diff.\n */\ndiffEditor.render = function(diffs, container) {\n  container.innerHTML = '';\n  for (var i = 0; i < diffs.length; i++) {\n    var op = diffs[i][0];    // Operation (insert, delete, equal)\n    var text = diffs[i][1];  // Text of change.\n    var el = document.createElement(diffEditor.tagMap[op]);\n    el.appendChild(document.createTextNode(text));\n    container.appendChild(el);\n  }\n};\n\n/**\n * Mapping from diff operation to relevant tag.\n */\ndiffEditor.tagMap = {};\ndiffEditor.tagMap[DIFF_INSERT] = 'ins';\ndiffEditor.tagMap[DIFF_DELETE] = 'del';\ndiffEditor.tagMap[DIFF_EQUAL] = 'span';\n\nwindow.addEventListener('load', diffEditor.init);\n"
  },
  {
    "path": "static/code/editor.css",
    "content": "#editorButter {\n  display: none;\n  left: 0;\n  position: absolute;\n  right: 0;\n  top: 0;\n  pointer-events: none;\n  z-index: 10;\n}\n\n#editorButter>div {\n  text-align: center;\n}\n\n#editorButterText {\n  background: #f9edbe;\n  border: 1px solid #f0c36d;\n  border-radius: 0 0 2px 2px;\n  border-top: 0;\n  box-shadow: 0 2px 4px rgba(0,0,0,0.2);\n  display: inline-block;\n  padding: 0 10px;\n  pointer-events: auto;\n}\n\n#valueEditor {\n  position: absolute;\n  top: 60px;\n  bottom: 20px;\n  left: 10px;\n  right: 20px\n}\n\n#functionEditor {\n  position: absolute;\n  top: 60px;\n  bottom: 45px;\n  left: 10px;\n  right: 20px\n}\n\n#jsspEditor {\n  position: absolute;\n  top: 60px;\n  bottom: 45px;\n  left: 10px;\n  right: 20px\n}\n\n.editorBigQuotes {\n  font-family: serif;\n  font-size: 48pt;\n  position: absolute;\n}\n"
  },
  {
    "path": "static/code/editor.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Integrated Development Environment for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nCode.Editor = {};\n\n/**\n * List of complete object selector parts.\n * @type {Array<!Object>}\n */\nCode.Editor.parts = null;\n\n/**\n * Currently selected editor.\n * @type {?Code.GenericEditor}\n */\nCode.Editor.currentEditor = null;\n\n/**\n * Current source code for editors that haven't yet been created.\n * @type {string}\n */\nCode.Editor.uncreatedEditorSource = '';\n\n/**\n * URL of this script.\n * Might be with or without subdomains:\n * https://static.google.codecity.world/code/editor.js\n * http://localhost:8080/static/code/editor.js\n * @type {string}\n */\nCode.Editor.mySource = document.getElementById('editor_js').src;\n\n\n/**\n * Got a ping from someone.  Something might have changed and need updating.\n */\nCode.Editor.receiveMessage = function() {\n  if (Code.Editor.isSaveDialogVisible) {\n    return;  // Ignore messages if the modal save dialog is up.\n  }\n  var selector = sessionStorage.getItem(Code.Common.SELECTOR);\n  var parts = Code.Common.selectorToParts(selector);\n  if (!parts || !parts.length) {\n    return;  // Invalid parts, ignore.\n  }\n  if (parts === Code.Editor.parts) {\n    return;  // No change.\n  }\n  if (Code.Editor.parts === null) {\n    Code.Editor.load();  // Initial load of content.\n  } else {\n    Code.Editor.updateCurrentSource();\n    if (Code.Editor.currentSource === Code.Editor.originalSource) {\n      Code.Editor.reload();  // Reload to load different content.\n    } else {\n      Code.Editor.showSave();  // User needs to save/discard/cancel.\n    }\n  }\n};\n\n/**\n * Page has loaded, initialize the editor.\n */\nCode.Editor.init = function() {\n  // Initialize button handlers.\n  document.getElementById('editorConfirmDiscard').addEventListener('click',\n      Code.Editor.reload);\n  document.getElementById('editorConfirmCancel').addEventListener('click',\n      Code.Editor.hideDialog);\n  document.getElementById('editorConfirmSave').addEventListener('click',\n      Code.Editor.save);\n  document.getElementById('editorSave').addEventListener('click',\n      Code.Editor.save);\n  document.getElementById('editorShare').addEventListener('click',\n      Code.Editor.showShare);\n  document.getElementById('editorShareOk').addEventListener('click',\n      Code.Editor.hideDialog);\n  document.getElementById('editorShareCheck').addEventListener('change',\n      Code.Editor.checkShare);\n\n\n  // Create the tabs.\n  var tabRow = document.getElementById('editorTabs');\n  var containerRow = document.getElementById('editorContainers');\n  for (var i = 0, editor; (editor = Code.Editor.editors[i]); i++) {\n    var span = document.createElement('span');\n    span.className = 'jfk-button';\n    span.appendChild(document.createTextNode(editor.name));\n    span.setAttribute('role', 'button');\n    span.setAttribute('tabindex', i);\n    span.addEventListener('click', Code.Editor.tabClick);\n    tabRow.appendChild(span);\n    var spacer = document.createElement('span');\n    spacer.className = 'spacer';\n    tabRow.appendChild(spacer);\n    var div = document.createElement('div');\n    containerRow.appendChild(div);\n    // Cross-link span/div to editor.\n    span.editor = editor;\n    div.editor = editor;\n    editor.tabElement = span;\n    editor.containerElement = div;\n  }\n\n  document.addEventListener('keydown', Code.Editor.keyDown);\n\n  Code.Editor.receiveMessage();\n\n  // Defer loading of JSHint to get editors running faster.\n  setTimeout(Code.Editor.importJSHint, 1);\n};\n\n/**\n * Load content into the editors.\n */\nCode.Editor.load = function() {\n  var selector = sessionStorage.getItem(Code.Common.SELECTOR);\n  var parts = Code.Common.selectorToParts(selector);\n  if (!parts) {\n    return;  // Invalid parts, ignore.\n  }\n  Code.Editor.parts = parts.slice();  // Shallow copy, since it's popped below.\n  // Request data from Code City server.\n  Code.Editor.key = undefined;\n  Code.Editor.sendXhr();\n\n  // Set the header.\n  var header = document.getElementById('editorHeader');\n  header.innerHTML = '';\n  if (parts.length < 2) {\n    // Global object.\n    var reference = Code.Common.partsToSelector(parts) + ' = ';\n  } else {\n    // Remove the last part.\n    var lastPart = parts.pop();\n    var selector = Code.Common.partsToSelector(parts);\n    var reference = Code.Common.selectorToReference(selector);\n    // Put the last part back on.\n    // Render as '.foo' or '[42]' or '[\"???\"]' or '{xxx}'.\n    if (lastPart.type === 'id') {\n      var mockParts = [{type: 'id', value: 'X'}, lastPart];\n      reference += Code.Common.partsToSelector(mockParts).substring(1) + ' = ';\n    } else if (lastPart.type === 'keyword') {\n      if (lastPart.value === '{proto}') {\n        reference = 'Object.setPrototypeOf(' + reference + ', ...) ';\n      } else if (lastPart.value === '{owner}') {\n        reference = 'Object.setOwnerOf(' + reference + ', ...) ';\n      } else {\n        throw new TypeError('Unknown keyword value: ' + lastPart.value);\n      }\n    } else {\n      throw new TypeError('Unknown part type: ' + lastPart.type);\n    }\n  }\n  header.appendChild(document.createTextNode(reference));\n};\n\n/**\n * Check the currently active editor and update Code.Editor.currentSource\n * if there has been a change.\n */\nCode.Editor.updateCurrentSource = function() {\n  if (Code.Editor.currentEditor && !Code.Editor.currentEditor.isSaved()) {\n    Code.Editor.currentSource = Code.Editor.currentEditor.getSource();\n  }\n  if (!Code.Editor.isSaveDialogVisible) {\n    Code.Editor.saturateSave(\n        Code.Editor.currentSource !== Code.Editor.originalSource);\n  }\n};\n\n/**\n * Keydown handler for the editor frame.\n * @param {!KeyboardEvent} e Keydown event.\n */\nCode.Editor.keyDown = function(e) {\n  // Save the editor if ⌘-s or Ctrl-s is pressed.\n  if (e.key === 's' && (e.metaKey || e.ctrlKey)) {\n    Code.Editor.save();\n    e.preventDefault();\n    e.stopPropagation();\n  }\n\n  // Before starting a search, render the editors' entire document.\n  if ((e.key === 'f' || e.key === 'g') && (e.metaKey || e.ctrlKey)) {\n    if (Code.Editor.currentEditor) {\n      var cm = Code.Editor.currentEditor.getCodeMirror();\n      if (cm) {\n        cm.setOption('viewportMargin', Infinity);\n      }\n    }\n  }\n};\n\n/**\n * Save the current editor content.\n */\nCode.Editor.save = function() {\n  Code.Editor.updateCurrentSource();\n  Code.Editor.sendXhr();\n  // Prevent the user from interacting with the editor during an async save.\n  // TODO: Implement merging.\n  var mask = document.getElementById('editorSavingMask');\n  mask.style.display = 'block';\n  Code.Editor.saveMaskPid = setTimeout(function() {\n    mask.style.opacity = 0.2;\n  }, 1000);  // Wait a second before starting visible transition.\n};\n\n/**\n * Force a reload of this editor.  Used to switch to edit something else.\n */\nCode.Editor.reload = function() {\n  Code.Editor.hideDialog();\n  Code.Editor.beforeUnload.disabled = true;\n  location.reload();\n};\n\n/**\n * Issue a warning if the user has unsaved changes and is attempting to leave\n * the code editor (e.g. typing a new URL).  This is not triggered due to\n * in-editor navigation.\n * @param {!Event} e A beforeunload event.\n */\nCode.Editor.beforeUnload = function(e) {\n  if (Code.Editor.isSaveDialogVisible) {\n    // The user has already got a warning but is ignoring it.  Just leave.\n    Code.Editor.hideDialog();\n    return;\n  }\n  Code.Editor.updateCurrentSource();\n  if (!Code.Editor.beforeUnload.disabled &&\n      Code.Editor.currentSource !== Code.Editor.originalSource) {\n    e.returnValue = 'You have unsaved changes.';\n    e.preventDefault();\n  }\n};\n\n/**\n * Flag to allow navigation away from current page, despite unsaved changes.\n */\nCode.Editor.beforeUnload.disabled = false;\n\n/**\n * Asynchronously load MobWrite's JavaScript files.\n * @param {!Function} callback Function to call when MobWrite is loaded.\n */\nCode.Editor.loadMobWrite = function(callback) {\n  if (!Code.Editor.waitMobWrite_.isLoaded) {\n    var files = ['dmp.js', 'mobwrite_core.js', 'mobwrite_cc.js'];\n    for (var file of files) {\n      var script = document.createElement('script');\n      script.src = Code.Editor.mySource.replace('editor.js', 'mobwrite/' + file);\n      document.head.appendChild(script);\n    }\n  }\n  Code.Editor.waitMobWrite_(callback);\n};\n\n/**\n * Wait for MobWrite to load.  Initialize it, then run the callback.\n * @param {!Function} callback Function to call when MobWrite is loaded.\n * @private\n */\nCode.Editor.waitMobWrite_ = function(callback) {\n  if (typeof diff_match_patch === 'undefined' ||\n      typeof mobwrite === 'undefined' ||\n      typeof Code.MobwriteShare === 'undefined') {\n    // Not loaded, try again later.\n    setTimeout(Code.Editor.waitMobWrite_, 50, callback);\n  } else {\n    if (!Code.Editor.waitMobWrite_.isLoaded) {\n      Code.MobwriteShare.init();\n      // Point MobWrite at the daemon on Code City.\n      var url = Code.Editor.mySource.replace('/code/editor.js', '');\n      if (url.endsWith('/static')) {\n        // http://localhost:8080/static\n        mobwrite.syncGateway = url.replace(/\\/static$/, '/mobwrite');\n      } else if (/:\\/\\/static\\./.test(url)) {\n        // https://static.google.codecity.world\n        mobwrite.syncGateway = url.replace('://static.', '://mobwrite.');\n      } else {\n        throw Error('Source does not match known pattern: ' + url);\n      }\n      Code.Editor.waitMobWrite_.isLoaded = true;\n    }\n    callback();\n  }\n};\n\nCode.Editor.waitMobWrite_.isLoaded = false;\n\n/**\n * When a tab is clicked, highlight it and show its container.\n * @param {!Event|!Object} e Click event or object pretending to be an event.\n */\nCode.Editor.tabClick = function(e) {\n  if (Code.Editor.tabClick.disabled) {\n    return;\n  }\n\n  // Unhighlight all tabs, hide all containers.\n  var tab = document.querySelector('#editorTabs>.highlighted');\n  tab && tab.classList.remove('highlighted');\n  var containers = document.querySelectorAll('#editorContainers>div');\n  for (var container of containers) {\n    container.style.display = 'none';\n  }\n\n  Code.Editor.updateCurrentSource();\n\n  // Highlight one tab, show one container.\n  var tab = e.target;\n  tab.classList.add('highlighted');\n  var editor = tab.editor;\n  Code.Editor.currentEditor = editor;\n  var container = editor.containerElement;\n  if (!editor.created) {\n    editor.createDom(container);\n    editor.created = true;\n  }\n  container.style.display = 'block';\n  Code.Editor.setSourceToAllEditors(Code.Editor.currentSource);\n  // If e is an event, then this click is the result of a user's direct action.\n  // If not, then it's a fake event as a result of page load.\n  var userAction = e instanceof Event;\n  editor.focus(userAction);\n};\n\n/**\n * Don't allow clicking of tabs before data is received from Code City.\n */\nCode.Editor.tabClick.disabled = true;\n\n/**\n * Send a request to Code City's code editor service.\n */\nCode.Editor.sendXhr = function() {\n  var selector = Code.Common.partsToSelector(Code.Editor.parts);\n  var xhr = Code.Editor.codeRequest_;\n  xhr.abort();\n  xhr.open('POST', 'editorXhr');\n  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n  xhr.onload = Code.Editor.receiveXhr;\n  var src = Code.Editor.currentSource || '';\n  var data =\n      'key=' + encodeURIComponent(Code.Editor.key) +\n      '&selector=' + encodeURIComponent(selector);\n  if (src) {\n    data += '&src=' + encodeURIComponent(src);\n  }\n  xhr.send(data);\n};\n\n/**\n * Reusable XHR object for server pings.\n */\nCode.Editor.codeRequest_ = new XMLHttpRequest();\n\n/**\n * Got a response from Code City's code editor service.\n */\nCode.Editor.receiveXhr = function() {\n  var xhr = Code.Editor.codeRequest_;\n  if (xhr.status !== 200) {\n    Code.Editor.clearSaveMask();\n    Code.Editor.showButter('Save failed: Status ' + xhr.status, 5000);\n    return;\n  }\n  var data = JSON.parse(xhr.responseText);\n  if (data.hasOwnProperty('key')) {\n    Code.Editor.key = data.key;\n  }\n  if (data.hasOwnProperty('src')) {\n    Code.Editor.originalSource = data.src;\n    // Only update the displayed source if a) this is the initial load,\n    // or b) the previous save was successful.\n    if (Code.Editor.currentSource === null || data.saved) {\n      Code.Editor.currentSource = data.src;\n      Code.Editor.setSourceToAllEditors(data.src);\n    }\n  }\n  Code.Editor.clearSaveMask();\n\n  if (data.saved === false && !data.login) {\n    // Save was requested, but failed due to lack of a login.\n    // Open login window.\n    var loginWindow = open('login', 'login', 'height=600,width=500');\n    if (loginWindow) {\n      window.addEventListener('message', function(event) {\n        if (event.data === 'closeMe') {\n          loginWindow.close();\n          Code.Editor.save();\n        }\n      }, false);\n    } else {\n      alert('Your browser has blocked the opening of the page you requested.\\n' +\n            'Please allow pop-ups on this domain. ✓️');\n    }\n  }\n\n  // While a save is in-flight, the user might have navigated away and be\n  // currently blocked by a warning dialog regarding unsaved work.\n  if (Code.Editor.isSaveDialogVisible) {\n    if (data.saved) {\n      // If the save was successful, then proceed with the requested navigation.\n      Code.Editor.reload();\n    } else {\n      // If the save was not successful, close the dialog and hope there's some\n      // butter to show.\n      Code.Editor.hideDialog();\n    }\n  }\n\n  // If there's a message, show it in the butter.\n  if (data.butter) {\n    Code.Editor.showButter(data.butter, 5000);\n  }\n\n  Code.Editor.ready && Code.Editor.ready();\n};\n\n/**\n * Remove saving mask that prevents UI interaction.\n */\nCode.Editor.clearSaveMask = function() {\n  clearTimeout(Code.Editor.saveMaskPid);\n  var mask = document.getElementById('editorSavingMask');\n  mask.style.display = 'none';\n  mask.style.opacity = 0;\n};\n\n/**\n * The original source text from the server.\n * @type {?string}\n */\nCode.Editor.originalSource = null;\n\n/**\n * Current source text from the most recent active editor.\n * @type {?string}\n */\nCode.Editor.currentSource = null;\n\n/**\n * Data has been received, ready to allow the user to edit.\n */\nCode.Editor.ready = function() {\n  // Configure tabs.\n  document.getElementById('editorTabs').classList.remove('disabled');\n  Code.Editor.tabClick.disabled = false;\n\n  // Switch tabs to show the highest confidence editor.\n  var bestEditor = Code.Editor.mostConfidentEditor();\n  if (bestEditor) {\n    var fakeEvent = {target: bestEditor.tabElement};\n    Code.Editor.tabClick(fakeEvent);\n  }\n\n  // Remove the loading animation.\n  var header = document.getElementById('editorHeader');\n  header.className = '';\n\n  // Update the save button's saturation state once a second.\n  setInterval(Code.Editor.updateCurrentSource, 1000);\n\n  var hash = parent && parent.location && parent.location.hash;\n  if (hash.length > 1) {\n    Code.Editor.loadMobWrite(function() {\n      mobwrite.share('Code');\n    });\n  }\n\n  // Only run this code once.\n  Code.Editor.ready = undefined;\n};\n\n\n/**\n * Find the editor with the highest confidence for the current text.\n * Confidence levels are recorded when text is set in each editor.\n * @return {Code.GenericEditor} Best editor, or null if none.\n */\nCode.Editor.mostConfidentEditor = function() {\n  var bestEditor = null;\n  var bestConfidence = -Infinity;\n  for (var editor of Code.Editor.editors) {\n    if (bestConfidence < editor.confidence) {\n      bestConfidence = editor.confidence;\n      bestEditor = editor;\n    }\n  }\n  return bestEditor;\n};\n\n/**\n * Set the values of all the editors.\n * @param {string} src Plain text contents.\n */\nCode.Editor.setSourceToAllEditors = function(src) {\n  if (typeof src !== 'string') {\n    throw TypeError(src);\n  }\n  Code.Editor.uncreatedEditorSource = src;\n  for (var editor of Code.Editor.editors) {\n    editor.setSource(src);\n    // Round-trip version of the source.\n    editor.unmodifiedSource = editor.getSource();\n  }\n};\n\n/**\n * Show the save dialog.\n */\nCode.Editor.showSave = function() {\n  Code.Editor.showDialog('editorConfirmBox');\n  // Desaturate save button.  Don't visually conflict with the 'save' button\n  // in save dialog.\n  Code.Editor.saturateSave(false);\n  Code.Editor.isSaveDialogVisible = true;\n};\n\n/**\n * Show the share dialog.\n */\nCode.Editor.showShare = function() {\n  Code.Editor.showDialog('editorShareBox');\n  document.body.style.cursor = 'wait';\n  Code.Editor.loadMobWrite(Code.Editor.populateShare);\n};\n\n/**\n * Show the share dialog.\n */\nCode.Editor.populateShare = function() {\n  document.body.style.cursor = '';\n  document.getElementById('editorShareBox').className = '';\n  var check = document.getElementById('editorShareCheck');\n  check.disabled = '';\n  check.checked = !!Object.keys(mobwrite.shared).length;\n  Code.Editor.checkShare();\n};\n\n/**\n * Called when the sharing checkbox is ticked or unticked.\n */\nCode.Editor.checkShare = function() {\n  var check = document.getElementById('editorShareCheck');\n  var input = document.getElementById('editorShareAddress');\n  input.disabled = !check.checked;\n\n  var shared = !!Object.keys(mobwrite.shared).length;\n  var hash = '#';\n  if (check.checked) {\n    if (!shared) {\n      mobwrite.share('Code');\n    }\n    hash += Code.MobwriteShare.id;\n  } else if (!check.checked) {\n    if (shared) {\n      mobwrite.unshare('Code');\n    }\n  }\n  if (parent && parent.history) {\n    // Update the URL on the parent frame.\n    parent.history.replaceState(undefined, undefined, hash);\n    // Update the address field the user can copy from.\n    input.value = check.checked ? parent.location : '';\n    input.select();\n  }\n};\n\n/**\n * Show a dialog.\n * @param {string} contentId ID of dialog's content div.\n */\nCode.Editor.showDialog = function(contentId) {\n  // Clean up and hide existing things that might be visible.\n  clearTimeout(Code.Editor.dialogAnimationPid);\n  Code.Editor.hideButter();\n  document.getElementById('editorConfirmBox').style.display = 'none';\n  document.getElementById('editorShareBox').style.display = 'none';\n  // Show the requested dialog.\n  document.getElementById(contentId).style.display = 'block';\n  document.getElementById('editorDialog').style.display = 'block';\n  var mask = document.getElementById('editorDialogMask');\n  var box = document.getElementById('editorDialogBox');\n  box.style.display = 'block';\n  mask.style.transitionDuration = '.4s';\n  box.style.transitionDuration = '.4s';\n  // Add a little bounce at the end of the animation.\n  box.style.transitionTimingFunction = 'cubic-bezier(.6,1.36,.75,1)';\n  Code.Editor.dialogAnimationPid = setTimeout(function() {\n    mask.style.opacity = 0.2;\n    box.style.top = '-10px';\n  }, 100);  // Firefox requires at least 10ms to process this timing function.\n};\n\n/**\n * Hide the dialog.\n */\nCode.Editor.hideDialog = function() {\n  clearTimeout(Code.Editor.dialogAnimationPid);\n  var mask = document.getElementById('editorDialogMask');\n  var box = document.getElementById('editorDialogBox');\n  mask.style.transitionDuration = '.2s';\n  box.style.transitionDuration = '.2s';\n  box.style.transitionTimingFunction = 'ease-in';\n  mask.style.opacity = 0;\n  box.style.top = '-120px';\n  Code.Editor.dialogAnimationPid = setTimeout(function() {\n    document.getElementById('editorDialog').style.display = 'none';\n    box.style.display = 'none';\n    document.getElementById('editorConfirmBox').style.display = 'none';\n    document.getElementById('editorShareBox').style.display = 'none';\n  }, 250);\n  // Resaturate the save button.\n  Code.Editor.saturateSave(true);\n  Code.Editor.isSaveDialogVisible = false;\n};\n\n/**\n * Is the save dialog currently visible?\n */\nCode.Editor.isSaveDialogVisible = false;\n\n/**\n * PID of any animation task.  Allows animations to be canceled so that two\n * near-simultaneous actions don't collide.\n */\nCode.Editor.dialogAnimationPid = 0;\n\n/**\n * Saturate or desaturate the editor's save button.\n * @param {boolean} saturated True if button should be saturated.\n */\nCode.Editor.saturateSave = function(saturated) {\n  var button = document.getElementById('editorSave');\n  button.className = saturated ? 'jfk-button jfk-button-submit' : 'jfk-button';\n};\n\n/**\n * Show the text in the butter bar for a period of time.\n * Clobber any existing display.\n * @param {string} text Text to display.\n * @param {number} time Number of milliseconds to display butter.\n */\nCode.Editor.showButter = function(text, time) {\n  clearTimeout(Code.Editor.showButter.pid_);\n  var textDiv = document.getElementById('editorButterText');\n  textDiv.innerHTML = '';\n  textDiv.appendChild(document.createTextNode(text));\n  document.getElementById('editorButter').style.display = 'block';\n  Code.Editor.showButter.pid_ = setTimeout(Code.Editor.hideButter, time);\n};\n\nCode.Editor.showButter.pid_ = 0;\n\n/**\n * Hide the butter bar.\n */\nCode.Editor.hideButter = function() {\n  document.getElementById('editorButter').style.display = 'none';\n};\n\n/**\n * Create a CodeMirror editor.\n * @param {!Element} container HTML element to hold the editor.\n * @param {!Object} extraOptions Editor configuration.\n * @return {!Object} CodeMirron editor.\n */\nCode.Editor.newCodeMirror = function(container, extraOptions) {\n  var options = {\n    extraKeys: {\n      Tab: function(cm) {\n        if (cm.somethingSelected()) {\n          cm.indentSelection('add');\n        } else {\n          cm.replaceSelection('  ');\n        }\n      },\n      'Shift-Tab': function(cm) {\n        cm.indentSelection('subtract');\n      }\n    },\n    gutters: ['CodeMirror-lint-markers'],\n    lineNumbers: true,\n    matchBrackets: true,\n    tabSize: 2,\n    undoDepth: 1024\n  };\n  // Merge extraOptions into default options.\n  Object.assign(options, extraOptions);\n  var editor = CodeMirror(container, options);\n  editor.setSize('100%', '100%');\n  return editor;\n};\n\n/**\n * Has the JSHint library loaded yet?\n */\nCode.Editor.JSHintReady = false;\n\n/**\n * Load the JSHint library.\n * Defer loading until page is loaded and responsive.\n */\nCode.Editor.importJSHint = function() {\n  // <script type=\"text/javascript\" src=\"/static/JSHint/jshint.js\"></script>\n  var script = document.createElement('script');\n  script.type = 'text/javascript';\n  script.src = Code.Editor.mySource.replace('code/editor.js', 'JSHint/jshint.js');\n  script.onload = function() {\n    Code.Editor.JSHintReady = true;\n    // Activate linting for any editor that's loaded and waiting.\n    for (var i = 0, editor; (editor = Code.Editor.editors[i]); i++) {\n      var cm = editor.getCodeMirror();\n      if (cm && editor.useJSHint) {\n        cm.setOption('lint', true);\n      }\n    }\n  };\n  document.head.appendChild(script);\n};\n\nif (!window.TEST) {\n  window.addEventListener('load', Code.Editor.init);\n  window.addEventListener('message', Code.Editor.receiveMessage, false);\n  window.addEventListener('beforeunload', Code.Editor.beforeUnload);\n}\n\nCode.Editor.editors = [];\n\n/**\n * Base class for editors.\n * @param {string} name User-facing name of editor (used in tab).\n * @constructor\n */\nCode.GenericEditor = function(name) {\n  /**\n   * Human-readable name of editor.\n   * @type {string}\n   */\n  this.name = name;\n\n  /**\n   * A float from 0 (bad) to 1 (perfect) indicating the editor's fitness to\n   * edit the given content.\n   */\n  this.confidence = 0;\n\n  /**\n   * Has the DOM for this editor been created yet?\n   */\n  this.created = false;\n\n  /**\n   * Span that forms the tab button.\n   * @type {?Element}\n   */\n  this.tabElement = null;\n\n  /**\n   * Div that forms the editor's container.\n   * @type {?Element}\n   */\n  this.containerElement = null;\n\n  /**\n   * Plain text representation of this editor's contents as of load or last save.\n   * @type {?string}\n   */\n  this.unmodifiedSource = null;\n\n  /**\n   * Should this editor use JSHint for syntax checking?\n   */\n  this.useJSHint = false;\n\n  // Register this editor.\n  Code.Editor.editors.push(this);\n};\n\n/**\n * Create the DOM for this editor.\n * @param {!Element} container DOM should be appended to this containing div.\n */\nCode.GenericEditor.prototype.createDom = function(container) {\n  var text = 'TODO: Implement createDom for ' + this.name + ' editor.';\n  container.appendChild(document.createTextNode(text));\n};\n\n/**\n * Get the contents of the editor.\n * @return {string} Plain text contents.\n */\nCode.GenericEditor.prototype.getSource = function() {\n  throw new ReferenceError('getSource not implemented on editor');\n};\n\n/**\n * Set the contents of the editor.\n * @param {string} source Plain text contents.\n */\nCode.GenericEditor.prototype.setSource = function(source) {\n  throw new ReferenceError('setSource not implemented on editor');\n};\n\n/**\n * Is the user's work in this editor saved?\n * @return {boolean} True if work is saved.\n */\nCode.GenericEditor.prototype.isSaved = function() {\n  return this.getSource() === this.unmodifiedSource;\n};\n\n/**\n * Return this editor's CodeMirror instance.\n * @return {Object} Defaults to null.\n */\nCode.GenericEditor.prototype.getCodeMirror = function() {\n  return null;\n};\n\n/**\n * Notification that this editor has just been displayed.\n * @param {boolean} userAction True if user clicked on a tab.\n */\nCode.GenericEditor.prototype.focus = function(userAction) {\n};\n\n\n////////////////////////////////////////////////////////////////////////////////\nCode.valueEditor = new Code.GenericEditor('Value');\n\n// The value editor can handle any content, but express a low confidence in\n// order to defer to more specialized editors.\nCode.valueEditor.confidence = 0.1;\n\nCode.valueEditor.useJSHint = true;\n\n/**\n * CodeMirror editor.  Does not exist until tab is selected.\n * @type {Object}\n * @private\n */\nCode.valueEditor.editor_ = null;\n\n/**\n * Return this editor's CodeMirror instance.\n * @return {Object} Defaults to null.\n */\nCode.valueEditor.getCodeMirror = function() {\n  return this.editor_;\n};\n\n/**\n * Create the DOM for this editor.\n * @param {!Element} container DOM should be appended to this containing div.\n */\nCode.valueEditor.createDom = function(container) {\n  container.id = 'valueEditor';\n  // Use different theme in value editor to distinguish it from other editors.\n  var options = {\n    continueComments: {continueLineComment: false},\n    lint: Code.Editor.JSHintReady,\n    mode: 'text/javascript',\n    theme: 'default'\n  };\n  this.editor_ = Code.Editor.newCodeMirror(container, options);\n};\n\n/**\n * Get the contents of the editor.\n * @return {string} Plain text contents.\n */\nCode.valueEditor.getSource = function() {\n  return this.created ?\n      this.editor_.getValue() : Code.Editor.uncreatedEditorSource;\n};\n\n/**\n * Set the contents of the editor.\n * @param {string} source Plain text contents.\n */\nCode.valueEditor.setSource = function(source) {\n  if (this.created) {\n    this.editor_.setValue(source);\n  }\n};\n\n/**\n * Notification that this editor has just been displayed.\n * @param {boolean} userAction True if user clicked on a tab.\n */\nCode.valueEditor.focus = function(userAction) {\n  this.editor_.refresh();\n  if (userAction) {\n    this.editor_.focus();\n  }\n};\n\n\n////////////////////////////////////////////////////////////////////////////////\nCode.functionEditor = new Code.GenericEditor('Function');\n\nCode.functionEditor.useJSHint = true;\n\n/**\n * CodeMirror editor.  Does not exist until tab is selected.\n * @type {Object}\n * @private\n */\nCode.functionEditor.editor_ = null;\n\n/**\n * Return this editor's CodeMirror instance.\n * @return {Object} Defaults to null.\n */\nCode.functionEditor.getCodeMirror = function() {\n  return this.editor_;\n};\n\n/**\n * Create the DOM for this editor.\n * @param {!Element} container DOM should be appended to this containing div.\n */\nCode.functionEditor.createDom = function(container) {\n  container.innerHTML = `\n<div>\n  <input type=\"checkbox\" name=\"isVerb\" id=\"isVerb\"\n      onclick=\"Code.functionEditor.updateDisabled()\">\n  <label for=\"isVerb\">Verb:</label>\n  <input id=\"verb\" value=\"\" placeholder=\"name\">\n  <select id=\"dobj\">\n    <option>none</option>\n    <option>this</option>\n    <option>something</option>\n    <option>any</option>\n  </select>\n  <select id=\"prep\">\n    <option>none</option>\n    <option>any</option>\n    <option>with/using</option>\n    <option>at/to</option>\n    <option>in front of</option>\n    <option>in/inside/into</option>\n    <option>on top of/on/onto/upon</option>\n    <option>out of/from inside/from</option>\n    <option>over</option>\n    <option>through</option>\n    <option>under/underneath/beneath</option>\n    <option>behind</option>\n    <option>beside</option>\n    <option>for/about</option>\n    <option>is</option>\n    <option>as</option>\n    <option>off/off of</option>\n  </select>\n  <select id=\"iobj\">\n    <option>none</option>\n    <option>this</option>\n    <option>something</option>\n    <option>any</option>\n  </select>\n</div>\n  `;\n  container.id = 'functionEditor';\n  var options = {\n    continueComments: {continueLineComment: false},\n    lint: Code.Editor.JSHintReady,\n    mode: 'text/javascript',\n    rulers: [{color: '#ddd', column: 80, lineStyle: 'dashed'}],\n    theme: 'eclipse'\n  };\n  this.editor_ = Code.Editor.newCodeMirror(container, options);\n\n  this.isVerbElement_ = document.getElementById('isVerb');\n  this.verbElement_ = document.getElementById('verb');\n  this.dobjElement_ = document.getElementById('dobj');\n  this.prepElement_ = document.getElementById('prep');\n  this.iobjElement_ = document.getElementById('iobj');\n};\n\n// Matches the signature of a function declaration.\n// Split the source into leading meta-data comments and function body.\nCode.functionEditor.functionRegex_ =\n    /^((?:[ \\t]*(?:\\/\\/[^\\n]*)?\\n)*)\\s*(function[\\S\\s]*)$/;\n\n/**\n * Enable or disable the verb UI elements based on the isVerb checkbox.\n */\nCode.functionEditor.updateDisabled = function() {\n  var disabled = this.isVerbElement_.checked ? '' : 'disabled';\n  this.verbElement_.disabled = disabled;\n  this.dobjElement_.disabled = disabled;\n  this.prepElement_.disabled = disabled;\n  this.iobjElement_.disabled = disabled;\n};\n\n/**\n * Get the contents of the editor.\n * @return {string} Plain text contents.\n */\nCode.functionEditor.getSource = function() {\n  if (!this.created) {\n    return Code.Editor.uncreatedEditorSource;\n  }\n  var source = this.editor_.getValue();\n  // Trim trailing whitespace.\n  source = source.replace(/[ \\t]+(?=\\n)/g, '').replace(/[ \\t]+$/, '');\n  var verb = '@delete_prop verb';\n  var dobj = '@delete_prop dobj';\n  var prep = '@delete_prop prep';\n  var iobj = '@delete_prop iobj';\n  if (this.isVerbElement_.checked) {\n    verb = '@set_prop verb = ' + JSON.stringify(this.verbElement_.value);\n    dobj = '@set_prop dobj = ' + JSON.stringify(this.dobjElement_.value);\n    prep = '@set_prop prep = ' + JSON.stringify(this.prepElement_.value);\n    iobj = '@set_prop iobj = ' + JSON.stringify(this.iobjElement_.value);\n  }\n  return `\n${this.metaExtra_.join('\\n').trim()}\n// ${verb}\n// ${dobj}\n// ${prep}\n// ${iobj}\n${source}\n  `.trim();\n};\n\n/**\n * Set the contents of the editor.\n * @param {string} source Plain text contents.\n */\nCode.functionEditor.setSource = function(source) {\n  var m = source.match(Code.functionEditor.functionRegex_);\n  this.confidence = m ? 0.5 : 0;\n  if (this.created) {\n    this.metaExtra_ = [];\n    var meta;\n    if (m) {\n      meta = m[1].split(/\\n/);\n      source = m[2];\n    } else {\n      meta = '';\n      source = 'function() {\\n}';\n    }\n    var props = {\n      'verb': '',\n      'dobj': 'none',\n      'prep': 'none',\n      'iobj': 'none'\n    };\n    var isVerb = false;\n    for (var line of meta) {\n      var m = line.match(Code.functionEditor.setSource.metaSetRegex_);\n      if (m) {\n        try {\n          props[m[1]] = JSON.parse(m[2]);\n          isVerb = true;\n        } catch (e) {\n          console.log('Ignoring invalid ' + m[1] + ': ' + m[2]);\n        }\n      } else if (!Code.functionEditor.setSource.metaDeleteRegex_.test(line)) {\n        // Not a meta value we recognize.  Preserve it.\n        this.metaExtra_.push(line);\n      }\n    }\n    this.verbElement_.value = props['verb'];\n    this.dobjElement_.value = props['dobj'];\n    this.prepElement_.value = props['prep'];\n    this.iobjElement_.value = props['iobj'];\n    this.isVerbElement_.checked = isVerb;\n    this.updateDisabled();\n    this.editor_.setValue(source);\n  }\n};\n\n// Matches one meta-data comment:  // @set_prop verb = \"foobar\"\nCode.functionEditor.setSource.metaSetRegex_ =\n    /^\\s*\\/\\/\\s*@set_prop\\s+(verb|dobj|prep|iobj)\\s*=\\s*(.+)$/;\n// Matches one meta-data comment:  // @delete_prop verb\nCode.functionEditor.setSource.metaDeleteRegex_ =\n    /^\\s*\\/\\/\\s*@delete_prop\\s+(verb|dobj|prep|iobj)$/;\n\nCode.functionEditor.metaExtra_ = [];\n\n/**\n * Notification that this editor has just been displayed.\n * @param {boolean} userAction True if user clicked on a tab.\n */\nCode.functionEditor.focus = function(userAction) {\n  this.editor_.refresh();\n  if (userAction) {\n    this.editor_.focus();\n  }\n};\n\n////////////////////////////////////////////////////////////////////////////////\nCode.jsspEditor = new Code.GenericEditor('JSSP');\n\n/**\n * JavaScript Server Page editor.  Does not exist until tab is selected.\n * @type {Object}\n * @private\n */\nCode.jsspEditor.editor_ = null;\n\n/**\n * Return this editor's CodeMirror instance.\n * @return {Object} Defaults to null.\n */\nCode.jsspEditor.getCodeMirror = function() {\n  return this.editor_;\n};\n\n/**\n * Create the DOM for this editor.\n * @param {!Element} container DOM should be appended to this containing div.\n */\nCode.jsspEditor.createDom = function(container) {\n  container.id = 'jsspEditor';\n  var options = {\n    continueComments: 'Enter',\n    lint: false,  // CodeMirror doesn't understand <% %>.\n    mode: 'application/x-ejs',\n    theme: 'eclipse'\n  };\n  this.editor_ = Code.Editor.newCodeMirror(container, options);\n};\n\n/**\n * Get the contents of the editor.\n * @return {string} Plain text contents.\n */\nCode.jsspEditor.getSource = function() {\n  if (!this.created) {\n    return Code.Editor.uncreatedEditorSource;\n  }\n  var source = this.editor_.getValue();\n  return JSON.stringify(source);\n};\n\n/**\n * Set the contents of the editor.\n * @param {string} source Plain text contents.\n */\nCode.jsspEditor.setSource = function(source) {\n  var str;\n  try {\n    str = JSON.parse(source);\n  } catch (e) {}\n  if (typeof str !== 'string') {\n    str = '';\n    this.confidence = 0;\n  } else {\n    if (str.includes('<%') && str.includes('%>')) {\n      this.confidence = 0.95;\n    } else {\n      this.confidence = 0.8;\n    }\n  }\n  if (this.created) {\n    this.editor_.setValue(str);\n  }\n};\n\n/**\n * Notification that this editor has just been displayed.\n * @param {boolean} userAction True if user clicked on a tab.\n */\nCode.jsspEditor.focus = function(userAction) {\n  this.editor_.refresh();\n  if (userAction) {\n    this.editor_.focus();\n  }\n};\n\n////////////////////////////////////////////////////////////////////////////////\nCode.svgEditor = new Code.GenericEditor('SVG');\n\n/**\n * DOMParser used to determine if the source is SVG.\n */\nCode.svgEditor.parser = new DOMParser();\n\n/**\n * Create the DOM for this editor.\n * @param {!Element} container DOM should be appended to this containing div.\n */\nCode.svgEditor.createDom = function(container) {\n  container.innerHTML = `\n<div style=\"position: absolute; top: 60px; bottom: 0; left: 0; right: 0; overflow: hidden;\">\n  <iframe src=\"svg\" style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0\"></iframe>\n</div>\n  `;\n  this.frameWindow_ = container.querySelector('iframe').contentWindow;\n};\n\n/**\n * Get the contents of the editor.\n * @return {string} Plain text contents.\n */\nCode.svgEditor.getSource = function() {\n  if (!this.created) {\n    return Code.Editor.uncreatedEditorSource;\n  }\n  var xmlString = this.frameWindow_.hasOwnProperty('initialSource') ?\n      this.frameWindow_.initialSource :\n      this.frameWindow_.svgEditor.getString();\n  return JSON.stringify(xmlString);\n};\n\n/**\n * Set the contents of the editor.\n * @param {string} text Plain text contents.\n */\nCode.svgEditor.setSource = function(source) {\n  var str = undefined;\n  this.confidence = 0;\n  try {\n    str = JSON.parse(source);\n  } catch (e) {}\n  if (typeof str === 'string') {\n    // DOMParser needs contents wrapped in a parent SVG node.\n    var dom = Code.svgEditor.parser.parseFromString('<svg>' + str + '</svg>',\n        'text/xml');\n    // Let's see if this DOM contains only SVG tags.\n    var nodes = dom.documentElement.querySelectorAll('*');\n    var isSvg = nodes.length > 0;\n    for (var node of nodes) {\n      if (!Code.svgEditor.ELEMENT_NAMES.has(node.tagName)) {\n        isSvg = false;\n        break;\n      }\n    }\n    if (isSvg) {\n      this.confidence = 0.95;\n    } else {\n      str = '';\n    }\n  } else {\n    str = '';\n  }\n\n  if (this.created) {\n    if (this.frameWindow_.svgEditor) {\n      this.frameWindow_.svgEditor.setString(str);\n    } else {\n      // The iframe exists, but the editor hasn't loaded yet.\n      // Save the source in a property on the iframe, so it can load when ready.\n      this.frameWindow_.initialSource = str;\n    }\n  }\n};\n\n/**\n * Notification that this editor has just been displayed.\n * @param {boolean} userAction True if user clicked on a tab.\n */\nCode.svgEditor.focus = function(userAction) {\n  if (userAction && this.frameWindow_.svgEditor) {\n    // Window may have resized since this tab was last visible.\n    this.frameWindow_.svgEditor.resize();\n  }\n};\n\n/**\n * Whitelist of all allowed SVG element names.\n * Try to keep this list in sync with CCC.World.xmlToSvg.ELEMENT_NAMES.\n */\nCode.svgEditor.ELEMENT_NAMES = new Set([\n  'circle',\n  'desc',\n  'ellipse',\n  'g',\n  'line',\n  'path',\n  'polygon',\n  'polyline',\n  'rect',\n  'svg',\n  'text',\n  'title',\n  'tspan',\n]);\n\n////////////////////////////////////////////////////////////////////////////////\nCode.stringEditor = new Code.GenericEditor('String');\n\n/**\n * Create the DOM for this editor.\n * @param {!Element} container DOM should be appended to this containing div.\n */\nCode.stringEditor.createDom = function(container) {\n  container.innerHTML = `\n<div style=\"position: absolute; top: 60px; bottom: 20px; left: 45px; right: 50px\">\n  <textarea style=\"height: 100%; width: 100%; resize: none;\"></textarea>\n</div>\n<div class=\"editorBigQuotes\" style=\"left: 10px; top: 57px\">“</div>\n<div class=\"editorBigQuotes\" style=\"right: 10px; bottom: 0\">”</div>\n  `;\n  this.textarea_ = container.querySelector('textarea');\n};\n\n/**\n * Get the contents of the editor.\n * @return {string} Plain text contents.\n */\nCode.stringEditor.getSource = function() {\n  return this.created ?\n      JSON.stringify(this.textarea_.value) :\n      Code.Editor.uncreatedEditorSource;\n};\n\n/**\n * Set the contents of the editor.\n * @param {string} text Plain text contents.\n */\nCode.stringEditor.setSource = function(source) {\n  var str;\n  try {\n    str = Code.stringEditor.parseString(source.trim());\n    this.confidence = 0.9;\n  } catch (e) {\n    str = '';\n    this.confidence = 0;\n  }\n  if (this.created) {\n    this.textarea_.value = str;\n  }\n};\n\n/**\n * Convert a string representation of a string literal to a string.\n * Basically does eval(s), but safely and only if s is a string\n * literal.\n * Copied from $.utils.code.parseString\n * @param {string} s Candidate string literal.\n * @retun {string} String value.\n */\nCode.stringEditor.parseString = function(s) {\n  if (!Code.stringEditor.stringExact_.test(s)) {\n    throw new TypeError('Not a string literal');\n  }\n  return s.slice(1, -1).replace(Code.stringEditor.stringEscapes_, function(esc) {\n    switch (esc[1]) {\n      case \"'\":\n      case '\"':\n      case '/':\n      case '\\\\':\n        return esc[1];\n      case '0':\n        return '\\0';\n      case 'b':\n        return '\\b';\n      case 'f':\n        return '\\f';\n      case 'n':\n        return '\\n';\n      case 'r':\n        return '\\r';\n      case 't':\n        return '\\t';\n      case 'v':\n        return '\\v';\n      case 'u':\n      case 'x':\n        return String.fromCharCode(parseInt(esc.slice(2), 16));\n      default:\n        // RegExp in call to replace has accepted something we\n        // don't know how to decode.\n        throw new Error('unknown escape sequence \"' + esc + '\"??');\n    }\n  });\n};\n\n/**\n * Tests if a valid string literal.\n * Copied from $.utils.code.regexps.stringExact\n */\nCode.stringEditor.stringExact_ = /^(?:'(?:[^'\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*'|\"(?:[^\"\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*\")$/;\n\n/**\n * Finds escape sequences in string literals.\n * Copied from $.utils.code.regexps.escapes\n */\nCode.stringEditor.stringEscapes_ = /\\\\(?:[\"'\\\\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g;\n\n/**\n * Notification that this editor has just been displayed.\n * @param {boolean} userAction True if user clicked on a tab.\n */\nCode.stringEditor.focus = function(userAction) {\n  if (userAction) {\n    this.textarea_.focus();\n  }\n};\n\n////////////////////////////////////////////////////////////////////////////////\n//Code.regExpEditor = new Code.GenericEditor('RegExp');\n\n////////////////////////////////////////////////////////////////////////////////\n//Code.dateEditor = new Code.GenericEditor('Date');\n\n////////////////////////////////////////////////////////////////////////////////\nCode.diffEditor = new Code.GenericEditor('Diff');\n\n/**\n * Create the DOM for this editor.\n * @param {!Element} container DOM should be appended to this containing div.\n */\nCode.diffEditor.createDom = function(container) {\n  container.innerHTML = `\n<div style=\"position: absolute; top: 60px; bottom: 0; left: 0; right: 0; overflow: hidden;\">\n  <iframe src=\"diff\" style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0\"></iframe>\n</div>\n  `;\n  this.frameWindow_ = container.querySelector('iframe').contentWindow;\n};\n\n/**\n * Get the contents of the editor.\n * @return {string} Plain text contents.\n */\nCode.diffEditor.getSource = function() {\n  if (!this.created) {\n    return Code.Editor.uncreatedEditorSource;\n  }\n  if (this.frameWindow_.hasOwnProperty('initialSource')) {\n    return this.frameWindow_.initialSource;\n  }\n  return this.frameWindow_.diffEditor.getString();\n};\n\n/**\n * Set the contents of the editor.\n * @param {string} source Plain text contents.\n */\nCode.diffEditor.setSource = function(source) {\n  if (this.created) {\n    if (this.frameWindow_.diffEditor) {\n      this.frameWindow_.diffEditor.setString(source, Code.Editor.originalSource);\n    } else {\n      // The iframe exists, but the editor hasn't loaded yet.\n      // Save the source in a property on the iframe, so it can load when ready.\n      this.frameWindow_.initialSource = source;\n      this.frameWindow_.originalSource = Code.Editor.originalSource;\n    }\n  }\n};\n"
  },
  {
    "path": "static/code/explorer.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Integrated Development Environment for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nCode.Explorer = {};\n\n/**\n * Width in pixels of each monospaced character in the input.\n * Used to line up the autocomplete menu.\n * TODO: If the menu starts getting out of alignment, measure the text instead.\n */\nCode.Explorer.SIZE_OF_INPUT_CHARS = 8.8;\n\n/**\n * Offset in pixels of start of first character in the input.\n * Used to line up the autocomplete menu.\n * TODO: If the menu starts getting out of alignment, measure the text instead.\n */\nCode.Explorer.LEFT_OF_INPUT_CHARS = 6;\n\n/**\n * Value of the input field last time it was processed.\n * @type {?string}\n */\nCode.Explorer.oldInputValue = null;\n\n/**\n * JSON-encoded list of complete object selector parts.\n * @type {string}\n */\nCode.Explorer.partsJSON = '[]';\n\n/**\n * Final token which may not be complete and isn't included in the parts list.\n * E.g. '$.foo.bar' the 'bar' might become 'bart' or 'barf'.\n * @type {?Object}\n */\nCode.Explorer.lastNameToken = null;\n\n/**\n * PID of task polling for changes to the input field.\n */\nCode.Explorer.inputPollPid = 0;\n\n/**\n * Is it ok to normalize the input?  False if the user is typing.\n */\nCode.Explorer.inputUpdatable = true;\n\n/**\n * The last set of autocompletion options from Code City.\n * The 'properties' property is an array of arrays of strings.  The first array\n * contains the properties on the object, the second array contains the\n * properties on the object's prototype, and so on.\n * The 'keywords' property is an array of strings.  E.g. ['{proto}', '{owner}']\n * @type {Object}\n */\nCode.Explorer.autocompleteData = null;\n\n/**\n * The type of the autocomplete menu, 'id' or 'keyword'.\n * @type {string}\n */\nCode.Explorer.autocompleteType = '';\n\n/**\n * Got a ping from someone.  Something might have changed and need updating.\n */\nCode.Explorer.receiveMessage = function() {\n  var selector = sessionStorage.getItem(Code.Common.SELECTOR);\n  // Propagate the ping down the tree of frames.\n  var parts = Code.Common.selectorToParts(selector);\n  if (parts) {\n    if (Code.Explorer.inputUpdatable) {\n      // Valid parts, set the input to be canonical version.\n      Code.Explorer.setInput(parts);\n    }\n    Code.Explorer.loadPanels(parts);\n  } else {\n    // Invalid parts, set the input to the raw string.\n    // Can be caused by going to: /code?$.foo...bar\n    var input = document.getElementById('input');\n    input.value = selector;\n    Code.Explorer.inputChange();\n    input.focus();\n  }\n};\n\n/**\n * Handle any changes to the input field.\n */\nCode.Explorer.inputChange = function() {\n  var input = document.getElementById('input');\n  if (Code.Explorer.oldInputValue === input.value) {\n    return;  // No change.\n  }\n  Code.Explorer.oldInputValue = input.value;\n  var parsed = Code.Explorer.parseInput(input.value);\n  if (Code.Explorer.lastNameToken === null && parsed.lastNameToken) {\n    // Look for cases where a deletion has resulted in a valid parts list.\n    // E.g. $.foo.bar. -> $.foo.bar\n    // Without this check, 'bar' would be considered a lastNameToken fragment\n    // and the object panels would back-slide one step to $.foo\n    var partsCopy = parsed.parts.slice();\n    partsCopy.push(\n        {type: parsed.lastNameToken.type, value: parsed.lastNameToken.value});\n    var oldParts = JSON.parse(Code.Explorer.partsJSON);\n    if (oldParts) {\n      oldParts.length = partsCopy.length;\n    }\n    if (JSON.stringify(partsCopy) === JSON.stringify(oldParts)) {\n      // Rewrite the parsed input to be complete.\n      parsed = {\n        lastNameToken: null,\n        lastToken: null,\n        parts: partsCopy,\n        valid: true\n      };\n    }\n  }\n  Code.Explorer.lastNameToken = parsed.lastNameToken;\n  var partsJSON = JSON.stringify(parsed.parts);\n  if (Code.Explorer.partsJSON === partsJSON) {\n    Code.Explorer.updateAutocompleteMenu();\n  } else {\n    Code.Explorer.hideAutocompleteMenu();\n    Code.Explorer.setParts(parsed.parts, false);\n  }\n  input.classList.toggle('invalid', !parsed.valid);\n};\n\n/**\n * Parse the input value.\n * @param {string} inputValue Selector string from input field.\n * @return {!Object} Object with four fields:\n *     parts: Array of selector parts.\n *     lastNameToken: Last token that was an id, str, num, or keyword.\n *     lastToken: Last token.  Null if no tokens.\n *     valid: True if all tokens are valid (or could become valid).\n */\nCode.Explorer.parseInput = function(inputValue) {\n  var tokens = Code.Common.tokenizeSelector(inputValue);\n  var parts = [];\n  var token = null;\n  var lastNameToken = null;\n  var valid = true;\n  for (token of tokens) {\n    if (lastNameToken) {\n      parts.push({type: 'id', value: lastNameToken.value});\n      lastNameToken = null;\n    }\n    if (!token.valid) {\n      valid = false;\n      break;\n    }\n    if (token.type === 'keyword' && token.complete) {\n      parts.push({type: 'keyword', value: token.value});\n    } else if (['id', 'str', 'num', 'keyword'].includes(token.type)) {\n      lastNameToken = token;\n    }\n  }\n  return {\n    parts: parts,\n    lastNameToken: lastNameToken,\n    lastToken: token,\n    valid: valid\n  };\n};\n\n/**\n * Check to see if there's any autocomplete data, and if so update the menu.\n */\nCode.Explorer.loadAutocomplete = function() {\n  var parts = JSON.parse(Code.Explorer.partsJSON);\n  var selector = Code.Common.partsToSelector(parts);\n  var data = Code.Explorer.getPanelData(selector);\n  if (data) {\n    Code.Explorer.autocompleteData = {};\n    // Flatten the data into a sorted list of options.\n    var set = new Set();\n    if (data.properties) {\n      for (var obj of data.properties) {\n        for (var prop of obj) {\n          set.add(prop.name);\n        }\n      }\n    }\n    if (data.roots) {\n      for (var root of data.roots) {\n        set.add(root.name);\n      }\n    }\n    Code.Explorer.autocompleteData.properties =\n        Array.from(set.keys()).sort(Code.Common.caseInsensitiveComp);\n    set.clear();\n    if (data.keywords) {\n      for (var word of data.keywords) {\n        set.add(word);\n      }\n    }\n    Code.Explorer.autocompleteData.keywords =\n        Array.from(set.keys()).sort();\n  } else {\n    Code.Explorer.autocompleteData = null;\n  }\n\n  // If the input value is unchanged, display the autocompletion menu.\n  var input = document.getElementById('input');\n  if (Code.Explorer.oldInputValue === input.value) {\n    Code.Explorer.updateAutocompleteMenu();\n  }\n};\n\n/**\n * Given a partial prefix, filter the autocompletion menu and display\n * all matching options.\n */\nCode.Explorer.updateAutocompleteMenu = function() {\n  if (!Code.Explorer.autocompleteData) return;\n  var parsed = Code.Explorer.parseInput(input.value);\n  var token = parsed.lastToken;\n  // If the lastToken is part of the submitted parts, no menu.\n  if (token) {\n    parsed.parts.push({'type': token.type, 'value': token.value});\n  }\n  if (JSON.stringify(parsed.parts) === Code.Explorer.partsJSON) {\n    Code.Explorer.hideAutocompleteMenu();\n    return;\n  }\n  // Otherwise, show a menu filtered on the partial token.\n  var options = [];\n  var index = token ? token.index : 0;\n  if (token.type === 'keyword') {\n    var prefix = token.value;\n    // Filter the keywords.\n    for (var option of Code.Explorer.autocompleteData.keywords) {\n      if (option.substring(0, prefix.length).toLowerCase() === prefix) {\n        options.push(option);\n      }\n    }\n    Code.Explorer.autocompleteType = 'keyword';\n  } else {\n    // Property.\n    var prefix = '';\n    if (token) {\n      if (token.type === 'id' || token.type === 'str') {\n        prefix = token.value.toLowerCase();\n      }\n      if ((token.type === 'num') && !isNaN(token.value)) {\n        prefix = String(token.value);\n      }\n      if (token.type === '.' || token.type === '[') {\n        index += token.raw.length;\n      }\n    }\n    if (!token || token.type === '.' || token.type === 'id' ||\n        token.type === '[' || token.type === 'str' || token.type === 'num') {\n      // Filter the properties.\n      for (var option of Code.Explorer.autocompleteData.properties) {\n        if (option.substring(0, prefix.length).toLowerCase() === prefix) {\n            options.push(option);\n        }\n      }\n    }\n    Code.Explorer.autocompleteType = 'id';\n  }\n  if (!options.length ||\n      (options.length === 1 && options[0].length === prefix.length)) {\n    // Length equality above is needed since prefix is lowercased.\n    Code.Explorer.hideAutocompleteMenu();\n  } else {\n    Code.Explorer.showAutocompleteMenu(options, index);\n  }\n};\n\n/**\n * Hide any autocompletions if the cursor isn't at the end.\n * @return {boolean} True if cursor is not at the end.\n */\nCode.Explorer.autocompleteCursorMonitor = function() {\n  var input = document.getElementById('input');\n  if (typeof input.selectionStart === 'number' &&\n      input.selectionStart !== input.value.length) {\n    Code.Explorer.hideAutocompleteMenu();\n    return true;\n  }\n  return false;\n};\n\n/**\n * Display the autocomplete menu, populated with the provided options.\n * @param {!Array<string>} options Array of options.\n * @param {number} index Left offset (in characters) to position menu.\n */\nCode.Explorer.showAutocompleteMenu = function(options, index) {\n  if (Code.Explorer.autocompleteCursorMonitor()) {\n    return;\n  }\n  var scrollDiv = document.getElementById('autocompleteMenuScroll');\n  scrollDiv.innerHTML = '';\n  for (var option of options) {\n    var div = document.createElement('div');\n    div.appendChild(document.createTextNode(option));\n    div.addEventListener('mouseover', Code.Explorer.autocompleteMouseOver);\n    div.addEventListener('mouseout', Code.Explorer.autocompleteMouseOut);\n    div.setAttribute('data-option', option);\n    scrollDiv.appendChild(div);\n  }\n  var menuDiv = document.getElementById('autocompleteMenu');\n  menuDiv.style.display = 'block';\n  menuDiv.scrollTop = 0;\n  var left = Math.round(index * Code.Explorer.SIZE_OF_INPUT_CHARS -\n                        Code.Explorer.LEFT_OF_INPUT_CHARS);\n  var maxLeft = window.innerWidth - menuDiv.offsetWidth;\n  menuDiv.style.left = Math.min(left, maxLeft) + 'px';\n  var maxHeight = window.innerHeight - menuDiv.offsetTop - 12;\n  menuDiv.style.maxHeight = maxHeight + 'px';\n};\n\n/**\n * Stop displaying the autocomplete menu.\n */\nCode.Explorer.hideAutocompleteMenu = function() {\n  document.getElementById('autocompleteMenu').style.display = 'none';\n  Code.Explorer.autocompleteSelect(null);\n  Code.Explorer.autocompleteType = '';\n};\n\n/**\n * Date/time of last keyboard navigation.\n * Don't allow mouse movements to change the autocompletion selection\n * Right after a keyboard navigation.  Otherwise an arrow keypress could cause\n * a scroll which could cause an apparent mouse move, which could cause an\n * unwanted selection change.\n */\nCode.Explorer.keyNavigationTime = 0;\n\n/**\n * Highlight one autocomplete option.\n * @param {!Event} e Mouse over event.\n */\nCode.Explorer.autocompleteMouseOver = function(e) {\n  if (Date.now() - Code.Explorer.keyNavigationTime > 250) {\n    Code.Explorer.autocompleteSelect(e.target);\n  }\n};\n\n/**\n * Remove highlighting from autocomplete option.\n * @param {!Event} e Mouse out event.\n */\nCode.Explorer.autocompleteMouseOut = function() {\n  if (Date.now() - Code.Explorer.keyNavigationTime > 250) {\n    Code.Explorer.autocompleteSelect(null);\n  }\n};\n\n/**\n * Highlight one option.  Unhighlight all other options.\n * @param {?Element} div Option to highlight or null for none.\n */\nCode.Explorer.autocompleteSelect = function(div) {\n  // There should only be zero or one option selected, but deselect them\n  // all in case there was a UI bug.\n  var selections =\n      document.querySelectorAll('#autocompleteMenuScroll>.selected');\n  for (var selected of selections) {\n    selected.className = '';\n  }\n  if (div) {\n    div.className = 'selected';\n  }\n};\n\n/**\n * An autocompletion option has been clicked by the user.\n * @param {!Event} e Click event.\n */\nCode.Explorer.autocompleteClick = function(e) {\n  var option = e.target.getAttribute('data-option');\n  var parts = JSON.parse(Code.Explorer.partsJSON);\n  parts.push({type: Code.Explorer.autocompleteType, value: option});\n  Code.Explorer.setParts(parts, true);\n};\n\n/**\n * Set the currently specified path.\n * Notify the parent frame.\n * @param {!Array<!Object>} parts List of parts.\n * @param {boolean} updateInput Normalize the input if true.\n */\nCode.Explorer.setParts = function(parts, updateInput) {\n  Code.Explorer.partsJSON = JSON.stringify(parts);\n  Code.Explorer.inputUpdatable = updateInput;\n  Code.Explorer.hideAutocompleteMenu();\n  Code.Explorer.loadAutocomplete();\n  var selector = Code.Common.partsToSelector(parts);\n  sessionStorage.setItem(Code.Common.SELECTOR, selector);\n  window.parent.postMessage('ping', '*');\n};\n\n/**\n * Set the input to be the specified path.\n * @param {!Array<!Object>} parts List of parts.\n */\nCode.Explorer.setInput = function(parts) {\n  Code.Explorer.hideAutocompleteMenu();\n  var value = Code.Common.partsToSelector(parts);\n  var input = document.getElementById('input');\n  input.value = value;\n  input.classList.remove('invalid');\n  input.focus();\n  Code.Explorer.oldInputValue = value;  // Don't autocomplete this value.\n};\n\n/**\n * Start polling for changes.\n */\nCode.Explorer.inputFocus = function() {\n  clearInterval(Code.Explorer.inputPollPid);\n  Code.Explorer.inputPollPid = setInterval(Code.Explorer.inputChange, 10);\n  Code.Explorer.inputUpdatable = false;\n};\n\n/**\n * Stop polling for changes and hide the autocomplete menu.\n */\nCode.Explorer.inputBlur = function() {\n  if (Code.Explorer.inputBlur.disable_) {\n    Code.Explorer.inputBlur.disable_ = false;\n    return;\n  }\n  clearInterval(Code.Explorer.inputPollPid);\n  Code.Explorer.hideAutocompleteMenu();\n  Code.Explorer.inputUpdatable = true;\n};\nCode.Explorer.inputBlur.disable_ = false;\n\n/**\n * When clicking on the autocomplete menu, disable the blur\n * (which would otherwise close the menu).\n */\nCode.Explorer.autocompleteMouseDown = function() {\n  Code.Explorer.inputBlur.disable_ = true;\n};\n\n/**\n * Intercept some control keys to control the autocomplete menu.\n * @param {!Event} e Keypress event.\n */\nCode.Explorer.inputKey = function(e) {\n  var key = {\n    TAB: 9,\n    ENTER: 13,\n    ESC: 27,\n    UP: 38,\n    DOWN: 40\n  };\n  if (e.keyCode === key.ESC) {\n    Code.Explorer.hideAutocompleteMenu();\n  }\n  Code.Explorer.autocompleteCursorMonitor();\n  var scrollDiv = document.getElementById('autocompleteMenuScroll');\n  var selected = scrollDiv.querySelector('.selected');\n  var menuDiv = document.getElementById('autocompleteMenu');\n  var hasMenu = menuDiv.style.display !== 'none';\n  if (e.keyCode === key.ENTER) {\n    var parts = JSON.parse(Code.Explorer.partsJSON);\n    if (selected) {\n      // Add the selected autocomplete option to the input.\n      var option = selected.getAttribute('data-option');\n      parts.push({type: Code.Explorer.autocompleteType, value: option});\n    } else if (Code.Explorer.lastNameToken &&\n        Code.Explorer.lastNameToken.valid) {\n      // The currently typed input should be considered complete.\n      // E.g. $.foo<enter> is not waiting to become $.foot\n      parts.push({type: 'id', value: Code.Explorer.lastNameToken.value});\n      Code.Explorer.lastNameToken = null;\n    }\n    Code.Explorer.setParts(parts, true);\n    e.preventDefault();\n  }\n  if (e.keyCode === key.TAB) {\n    if (hasMenu) {\n      // Extract all options from the menu.\n      var options = [];\n      for (var i = 0, option; (option = scrollDiv.childNodes[i]); i++) {\n        options[i] = option.getAttribute('data-option');\n      }\n      var prefix = '';\n      if (Code.Explorer.lastNameToken &&\n          Code.Explorer.lastNameToken.type === 'id') {\n        prefix = Code.Explorer.lastNameToken.value;\n      }\n      var tuple = Code.Explorer.autocompletePrefix(options, prefix);\n      if (tuple.terminal) {\n        // There was only one option.  Choose it.\n        var parts = JSON.parse(Code.Explorer.partsJSON);\n        parts.push({type: Code.Explorer.autocompleteType, value: tuple.prefix});\n        Code.Explorer.setParts(parts, true);\n      } else {\n        // Append the common prefix to the existing input.\n        var input = document.getElementById('input');\n        if (Code.Explorer.lastNameToken) {\n          input.value = input.value.substring(0,\n              Code.Explorer.lastNameToken.index) + tuple.prefix;\n        } else {\n          input.value += tuple.prefix;\n        }\n        // TODO: Tab-completion of partial strings and numbers.\n      }\n    }\n    e.preventDefault();\n  }\n  if (hasMenu && (e.keyCode === key.UP || e.keyCode === key.DOWN)) {\n    Code.Explorer.keyNavigationTime = Date.now();\n    var newSelected;\n    if (e.keyCode === key.UP) {\n      if (!selected) {\n        newSelected = scrollDiv.lastChild;\n      } else if (selected.previousSibling) {\n        newSelected = selected.previousSibling;\n      }\n    } else if (e.keyCode === key.DOWN) {\n      if (!selected) {\n        newSelected = scrollDiv.firstChild;\n      } else if (selected.nextSibling) {\n        newSelected = selected.nextSibling;\n      }\n    }\n    if (newSelected) {\n      Code.Explorer.autocompleteSelect(newSelected);\n      if (newSelected.scrollIntoView) {\n        newSelected.scrollIntoView({block: 'nearest', inline: 'nearest'});\n      }\n    }\n    e.preventDefault();\n  }\n};\n\n/**\n * Given a list of options, and an existing prefix, return the common prefix.\n * E.g. (['food', 'foot'], 'f') -> {prefix: 'foo', terminal: false}\n * @param {!Array<string>} options Array of autocompleted strings.\n * @param {string} prefix Any existing prefix.\n * @return {{prefix: string, terminal: boolean}} Tuple with the maximum common\n *   prefix, and whether this completion is terminal (true), or if there's the\n *   option of continuing (false).\n */\nCode.Explorer.autocompletePrefix = function(options, prefix) {\n  // Filter out only those completions that case-sensitively match the prefix.\n  var optionsCase = options.filter(\n      function(option) {return option.startsWith(prefix);});\n  if (optionsCase.length) {\n    return {prefix: Code.Explorer.getPrefix(optionsCase),\n        terminal: optionsCase.length === 1};\n  }\n  // Find completions that don't match the prefix's case.\n  var common = Code.Explorer.getPrefix(options);\n  if (common.length > prefix.length) {\n    var optionsCommon = options.filter(\n        function(option) {return option.startsWith(common);});\n    return {prefix: common, terminal: optionsCommon.length === 1};\n  }\n  return {prefix: prefix, terminal: false};\n};\n\n/**\n * Compute and return the common prefix of n (relatively short) strings.\n * @param {!Array<string>} strs Array of string.\n * @return {string} Common prefix.\n */\nCode.Explorer.getPrefix = function(strs) {\n  if (strs.length === 0) {\n    return '';\n  }\n  var i = 0;\n  while (true) {\n    var letter = strs[0][i];\n    for (var j = 0; j < strs.length; j++) {\n      if (strs[j].length <= i) {\n        return strs[j];\n      }\n      if (strs[j][i] !== letter) {\n        return strs[j].substring(0, i);\n      }\n    }\n    i++;\n  }\n};\n\n/**\n * If a mouse-click caused the cursor to move away from the end,\n * close the autocomplete menu.\n */\nCode.Explorer.inputMouseDown = function() {\n  setTimeout(Code.Explorer.autocompleteCursorMonitor, 1);\n};\n\n/**\n * Number of object panels.\n */\nCode.Explorer.panelCount = 0;\n\n/**\n * Size of temporary spacer margin for smooth scrolling after deletion.\n */\nCode.Explorer.panelSpacerMargin = 0;\n\n/**\n * Update the panels with the specified list of parts.\n * @param {!Array<!Object>} parts List of parts.\n */\nCode.Explorer.loadPanels = function(parts) {\n  for (var i = 0; i <= parts.length; i++) {\n    var selector = Code.Common.partsToSelector(parts.slice(0, i));\n    var iframe = document.getElementById('objectPanel' + i);\n    if (iframe) {\n      if (iframe.getAttribute('data-selector') === selector) {\n        // Highlight current item.\n        iframe.contentWindow.postMessage('ping', '*');\n        continue;\n      } else {\n        while (Code.Explorer.panelCount > i) {\n          Code.Explorer.removePanel();\n        }\n      }\n    }\n    iframe = Code.Explorer.addPanel(selector);\n  }\n  while (Code.Explorer.panelCount > i) {\n    Code.Explorer.removePanel();\n  }\n};\n\n/**\n * Add an object panel to the right.\n * @param {string} selector Selector string.\n */\nCode.Explorer.addPanel = function(selector) {\n  var panelsScroll = document.getElementById('panelsScroll');\n  var iframe = document.createElement('iframe');\n  iframe.addEventListener('load', Code.Explorer.loadAutocomplete);\n  iframe.id = 'objectPanel' + Code.Explorer.panelCount;\n  iframe.src = 'objectPanel?' + encodeURIComponent(selector);\n  iframe.setAttribute('data-selector', selector);\n  var spacer = document.getElementById('panelSpacer');\n  panelsScroll.insertBefore(iframe, spacer);\n  Code.Explorer.panelCount++;\n  Code.Explorer.panelSpacerMargin =\n      Math.max(0, Code.Explorer.panelSpacerMargin - iframe.offsetWidth);\n  Code.Explorer.scrollPanel();\n};\n\n/**\n * Remove the right-most panel.\n */\nCode.Explorer.removePanel = function() {\n  Code.Explorer.panelCount--;\n  var iframe = document.getElementById('objectPanel' +\n      Code.Explorer.panelCount);\n  Code.Explorer.panelSpacerMargin += iframe.offsetWidth;\n  iframe.parentNode.removeChild(iframe);\n  Code.Explorer.scrollPanel();\n};\n\n/**\n * After addition, quickly scroll the panels all the way to see the right edge.\n * After deletion, reduce the spacer so that the panels scroll to the edge.\n */\nCode.Explorer.scrollPanel = function() {\n  var spacer = document.getElementById('panelSpacer');\n  var speed = 20;\n  clearTimeout(Code.Explorer.scrollPid_);\n  if (Code.Explorer.panelSpacerMargin > 0) {\n    // Reduce spacer.\n    Code.Explorer.panelSpacerMargin =\n        Math.max(0, Code.Explorer.panelSpacerMargin - speed);\n    spacer.style.marginRight = Code.Explorer.panelSpacerMargin + 'px';\n    if (Code.Explorer.panelSpacerMargin > 0) {\n      Code.Explorer.scrollPid_ = setTimeout(Code.Explorer.scrollPanel, 10);\n    }\n  } else {\n    spacer.style.marginRight = 0;\n    // Scroll right.\n    var panels = document.getElementById('panels');\n    var oldScroll = panels.scrollLeft;\n    panels.scrollLeft += speed;\n    if (panels.scrollLeft > oldScroll) {\n      Code.Explorer.scrollPid_ = setTimeout(Code.Explorer.scrollPanel, 10);\n    }\n  }\n};\n\n/**\n * PID of currently executing scroll animation.\n * @private\n */\nCode.Explorer.scrollPid_ = 0;\n\n/**\n * Get the data blob from the specified object panel.\n * @param {string} selector Selector string.\n * @return {!Object|undefined} Data blob, or undefined if data is not\n *   currently available.\n */\nCode.Explorer.getPanelData = function(selector) {\n  // Find the object panel that contains the needed data.\n  for (var iframe of document.getElementsByTagName('iframe')) {\n    if (iframe.getAttribute('data-selector') === selector) {\n      try {\n        // Risky: Content may not have loaded yet.\n        var data = iframe.contentWindow.Code.ObjectPanel.data;\n      } catch (e) {}\n      break;\n    }\n  }\n  return data;\n};\n\n/**\n * Keydown handler for the explorer frame.\n * @param {!KeyboardEvent} e Keydown event.\n */\nCode.Explorer.keyDown = function(e) {\n  // The editor frame may have strong opinions about key presses.\n  try {\n    parent.frames[1].Code.Editor.keyDown(e);\n  } catch (ex) {\n    // Frame might not be loaded yet.\n  }\n};\n\n/**\n * Page has loaded, initialize the explorer.\n */\nCode.Explorer.init = function() {\n  var input = document.getElementById('input');\n  input.addEventListener('focus', Code.Explorer.inputFocus);\n  input.addEventListener('blur', Code.Explorer.inputBlur);\n  input.addEventListener('keydown', Code.Explorer.inputKey);\n  input.addEventListener('mousedown', Code.Explorer.inputMouseDown);\n  document.addEventListener('keydown', Code.Explorer.keyDown);\n  var scrollDiv = document.getElementById('autocompleteMenuScroll');\n  scrollDiv.addEventListener('mousedown', Code.Explorer.autocompleteMouseDown);\n  scrollDiv.addEventListener('click', Code.Explorer.autocompleteClick);\n  Code.Explorer.receiveMessage();\n};\n\nif (!window.TEST) {\n  window.addEventListener('load', Code.Explorer.init);\n  window.addEventListener('message', Code.Explorer.receiveMessage, false);\n}\n"
  },
  {
    "path": "static/code/mobwrite/demo/editor.html",
    "content": "<HTML>\n<HEAD>\n<TITLE>MobWrite as a Collaborative Editor</TITLE>\n<STYLE type=\"text/css\">\nBODY {\n  background-color: white;\n  font-family: sans-serif;\n}\nH1, H2, H3 {\n  font-weight: normal;\n}\nTEXTAREA {\n  font-family: sans-serif;\n}\n</STYLE>\n<script SRC=\"../dmp.js\"></script>\n<script SRC=\"../mobwrite_core.js\"></script>\n<script SRC=\"mobwrite_form.js\"></script>\n<script>\n  mobwrite.syncGateway = '/mobwrite';\n</script>\n\n</HEAD>\n<BODY ONLOAD=\"mobwrite.share('demo_editor_title', 'demo_editor_text');\">\n\n<TABLE STYLE=\"height: 100%; width: 100%\">\n\n<TR><TD HEIGHT=1><H1>MobWrite as a Collaborative Editor</H1></TD></TR>\n\n<TR><TD HEIGHT=1><INPUT TYPE=\"text\" ID=\"demo_editor_title\" STYLE=\"width: 50%\"></TD></TR>\n\n<TR><TD><TEXTAREA ID=\"demo_editor_text\" STYLE=\"width: 100%; height: 100%\"></TEXTAREA></TD></TR>\n\n</TABLE>\n\n</BODY>\n</HTML>\n"
  },
  {
    "path": "static/code/mobwrite/demo/form.html",
    "content": "<HTML>\n<HEAD>\n<TITLE>MobWrite as a Collaborative Form</TITLE>\n<STYLE type=\"text/css\">\nBODY {\n  background-color: white;\n  font-family: sans-serif;\n}\nH1, H2, H3 {\n  font-weight: normal;\n}\nTEXTAREA {\n  font-family: sans-serif;\n}\nTH {\n  text-align: left;\n  vertical-align: top;\n}\n</STYLE>\n<script SRC=\"../dmp.js\"></script>\n<script SRC=\"../mobwrite_core.js\"></script>\n<script SRC=\"mobwrite_form.js\"></script>\n<script>\n  mobwrite.syncGateway = '/mobwrite';\n</script>\n</HEAD>\n<BODY ONLOAD=\"mobwrite.share('demo_form');\">\n\n<H1>MobWrite as a Collaborative Form</H1>\n\n<FORM ID=\"demo_form\">\n\n<TABLE>\n<TR>\n  <TH>What</TH>\n  <TD><INPUT TYPE=\"text\" NAME=\"what\" ID=\"demo_form_what\" SIZE=30 VALUE=\"New event\"></TD>\n</TR>\n<TR>\n  <TH>When</TH>\n  <TD>\n    <INPUT TYPE=\"text\" NAME=\"date\" ID=\"demo_form_date1\" SIZE=6 VALUE=\"9:00\">\n    <SPAN ID=\"all_day_span\">to <INPUT TYPE=\"text\" NAME=\"date\" ID=\"demo_form_date2\" SIZE=6 VALUE=\"10:00\"></SPAN>\n    <INPUT TYPE=\"checkbox\" NAME=\"all_day\" ID=\"demo_form_all_day\" ONCHANGE=\"document.getElementById('all_day_span').style.display = this.checked ? 'none' : 'inline'\">\n    <LABEL FOR=\"demo_form_all_day\">All day</LABEL>\n  </TD>\n</TR>\n<TR>\n  <TH>Where</TH>\n  <TD>\n    <INPUT NAME=\"where\" ID=\"demo_form_where1\" VALUE=\"SFO\" type=\"radio\" CHECKED>\n    <LABEL FOR=\"demo_form_where1\">San Francisco</LABEL><br>\n    <INPUT NAME=\"where\" ID=\"demo_form_where2\" VALUE=\"NYC\" type=\"radio\">\n    <LABEL FOR=\"demo_form_where2\">New York</LABEL><br>\n    <INPUT NAME=\"where\" ID=\"demo_form_where3\" VALUE=\"YYZ\" type=\"radio\">\n    <LABEL FOR=\"demo_form_where3\">Toronto</LABEL><br>\n  </TD>\n</TR>\n<TR>\n  <TH>Who</TH>\n  <TD>\n    <SELECT NAME=\"who\" ID=\"demo_form_who\" MULTIPLE>\n      <OPTION VALUE=\"Alice\">Alice</OPTION>\n      <OPTION VALUE=\"Bob\">Bob</OPTION>\n      <OPTION VALUE=\"Eve\">Eve</OPTION>\n    </SELECT>\n  </TD>\n</TR>\n<TR>\n  <TH>Hidden</TH>\n  <TD>\n    <INPUT TYPE=\"hidden\" NAME=\"hidden\" ID=\"demo_form_hidden\">\n    [<a href=\"javascript:var el = document.getElementById('demo_form_hidden');\n    var v = prompt('Hidden value', el.value);\n    if (v !== null) {el.value = v};\n    undefined;\">get/set</a>]\n  </TD>\n</TR>\n<TR>\n  <TH>Password</TH>\n  <TD><INPUT TYPE=\"password\" NAME=\"password\" ID=\"demo_form_password\"></TD>\n</TR>\n<TR>\n  <TH>Description</TH>\n  <TD><TEXTAREA NAME=\"description\" ID=\"demo_form_description\" COLS=50 ROWS=5></TEXTAREA></TD>\n</TR>\n<TR>\n  <TH></TH>\n  <TD>\n    <INPUT TYPE=\"submit\" VALUE=\"Save event\">\n  </TD>\n</TR>\n</TABLE>\n\n</FORM>\n\n</BODY>\n</HTML>\n"
  },
  {
    "path": "static/code/mobwrite/demo/mobwrite_form.js",
    "content": "/**\n * @license\n * Copyright 2008 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview This client-side code interfaces with form elements.\n * @author fraser@google.com (Neil Fraser)\n */\n\n/**\n * Checks to see if the provided node is still part of the DOM.\n * @param {Node} node DOM node to verify.\n * @return {boolean} Is this node part of a DOM?\n * @private\n */\nmobwrite.validNode_ = function(node) {\n  while (node.parentNode) {\n    node = node.parentNode;\n  }\n  // The topmost node should be type 9, a document.\n  return node.nodeType == 9;\n};\n\n\n// FORM\n\n\n/**\n * Handler to accept forms as elements that can be shared.\n * Share each of the form's elements.\n * @param {Object|string} form Form or ID of form to share\n * @return {Object?} A sharing object or null.\n */\nmobwrite.shareHandlerForm = function(form) {\n  if (typeof form == 'string') {\n    form = document.getElementById(form) || document.forms[form];\n  }\n  if (form && 'tagName' in form && form.tagName == 'FORM') {\n    for (var x = 0, el; el = form.elements[x]; x++) {\n      mobwrite.share(el);\n    }\n  }\n  return null;\n};\n\n\n// Register this shareHandler with MobWrite.\nmobwrite.shareHandlers.push(mobwrite.shareHandlerForm);\n\n\n// HIDDEN\n\n\n/**\n * Constructor of shared object representing a hidden input.\n * @param {Node} node A hidden element.\n * @constructor\n */\nmobwrite.shareHiddenObj = function(node) {\n  // Call our prototype's constructor.\n  mobwrite.shareObj.apply(this, [node.id]);\n  this.element = node;\n};\n\n\n// The hidden input's shared object's parent is a shareObj.\nmobwrite.shareHiddenObj.prototype = new mobwrite.shareObj('');\n\n\n/**\n * Retrieve the user's content.\n * @return {string} Plaintext content.\n */\nmobwrite.shareHiddenObj.prototype.getClientText = function() {\n  if (!mobwrite.validNode_(this.element)) {\n    mobwrite.unshare(this.file);\n  }\n  // Numeric data should use overwrite mode.\n  this.mergeChanges = !this.element.value.match(/^\\s*-?[\\d.]+\\s*$/);\n  return this.element.value;\n};\n\n\n/**\n * Set the user's content.\n * @param {string} text New content.\n */\nmobwrite.shareHiddenObj.prototype.setClientText = function(text) {\n  this.element.value = text;\n};\n\n\n/**\n * Handler to accept hidden fields as elements that can be shared.\n * If the element is a hidden field, create a new sharing object.\n * @param {*} node Object or ID of object to share.\n * @return {Object?} A sharing object or null.\n */\nmobwrite.shareHiddenObj.shareHandler = function(node) {\n  if (typeof node == 'string') {\n    node = document.getElementById(node);\n  }\n  if (node && 'type' in node && node.type == 'hidden') {\n    return new mobwrite.shareHiddenObj(node);\n  }\n  return null;\n};\n\n\n// Register this shareHandler with MobWrite.\nmobwrite.shareHandlers.push(mobwrite.shareHiddenObj.shareHandler);\n\n\n// CHECKBOX\n\n\n/**\n * Constructor of shared object representing a checkbox.\n * @param {Node} node A checkbox element.\n * @constructor\n */\nmobwrite.shareCheckboxObj = function(node) {\n  // Call our prototype's constructor.\n  mobwrite.shareObj.apply(this, [node.id]);\n  this.element = node;\n  this.mergeChanges = false;\n};\n\n\n// The checkbox shared object's parent is a shareObj.\nmobwrite.shareCheckboxObj.prototype = new mobwrite.shareObj('');\n\n\n/**\n * Retrieve the user's check.\n * @return {string} Plaintext content.\n */\nmobwrite.shareCheckboxObj.prototype.getClientText = function() {\n  if (!mobwrite.validNode_(this.element)) {\n    mobwrite.unshare(this.file);\n  }\n  return this.element.checked ? this.element.value : '';\n};\n\n\n/**\n * Set the user's check.\n * @param {string} text New content.\n */\nmobwrite.shareCheckboxObj.prototype.setClientText = function(text) {\n  // Safari has a blank value if not set, all other browsers have 'on'.\n  var value = this.element.value || 'on';\n  this.element.checked = (text == value);\n  this.fireChange(this.element);\n};\n\n\n/**\n * Handler to accept checkboxen as elements that can be shared.\n * If the element is a checkbox, create a new sharing object.\n * @param {*} node Object or ID of object to share.\n * @return {Object?} A sharing object or null.\n */\nmobwrite.shareCheckboxObj.shareHandler = function(node) {\n  if (typeof node == 'string') {\n    node = document.getElementById(node);\n  }\n  if (node && 'type' in node && node.type == 'checkbox') {\n    return new mobwrite.shareCheckboxObj(node);\n  }\n  return null;\n};\n\n\n// Register this shareHandler with MobWrite.\nmobwrite.shareHandlers.push(mobwrite.shareCheckboxObj.shareHandler);\n\n\n// SELECT OPTION\n\n\n/**\n * Constructor of shared object representing a select box.\n * @param {Node} node A select box element.\n * @constructor\n */\nmobwrite.shareSelectObj = function(node) {\n  // Call our prototype's constructor.\n  mobwrite.shareObj.apply(this, [node.id]);\n  this.element = node;\n  // If the select box is select-one, use overwrite mode.\n  // If it is select-multiple, use text merge mode.\n  this.mergeChanges = (node.type == 'select-multiple');\n};\n\n\n// The select box shared object's parent is a shareObj.\nmobwrite.shareSelectObj.prototype = new mobwrite.shareObj('');\n\n\n/**\n * Retrieve the user's selection(s).\n * @return {string} Plaintext content.\n */\nmobwrite.shareSelectObj.prototype.getClientText = function() {\n  if (!mobwrite.validNode_(this.element)) {\n    mobwrite.unshare(this.file);\n  }\n  var selected = [];\n  for (var x = 0, option; option = this.element.options[x]; x++) {\n    if (option.selected) {\n      selected.push(option.value);\n    }\n  }\n  return selected.join('\\0');\n};\n\n\n/**\n * Set the user's selection(s).\n * @param {string} text New content.\n */\nmobwrite.shareSelectObj.prototype.setClientText = function(text) {\n  text = '\\0' + text + '\\0';\n  for (var x = 0, option; option = this.element.options[x]; x++) {\n    option.selected = (text.indexOf('\\0' + option.value + '\\0') != -1);\n  }\n  this.fireChange(this.element);\n};\n\n\n/**\n * Handler to accept select boxen as elements that can be shared.\n * If the element is a select box, create a new sharing object.\n * @param {*} node Object or ID of object to share\n * @return {Object?} A sharing object or null.\n */\nmobwrite.shareSelectObj.shareHandler = function(node) {\n  if (typeof node == 'string') {\n    node = document.getElementById(node);\n  }\n  if (node && 'type' in node && (node.type == 'select-one' || node.type == 'select-multiple')) {\n    return new mobwrite.shareSelectObj(node);\n  }\n  return null;\n};\n\n\n// Register this shareHandler with MobWrite.\nmobwrite.shareHandlers.push(mobwrite.shareSelectObj.shareHandler);\n\n\n// RADIO BUTTON\n\n\n/**\n * Constructor of shared object representing a radio button.\n * @param {Node} node A radio button element.\n * @constructor\n */\nmobwrite.shareRadioObj = function(node) {\n  // Call our prototype's constructor.\n  mobwrite.shareObj.apply(this, [node.id]);\n  this.elements = [node];\n  this.form = node.form;\n  this.name = node.name;\n  this.mergeChanges = false;\n};\n\n\n// The radio button shared object's parent is a shareObj.\nmobwrite.shareRadioObj.prototype = new mobwrite.shareObj('');\n\n\n/**\n * Retrieve the user's check.\n * @return {string} Plaintext content.\n */\nmobwrite.shareRadioObj.prototype.getClientText = function() {\n  // TODO: Handle cases where the radio buttons are added or removed.\n  if (!mobwrite.validNode_(this.elements[0])) {\n    mobwrite.unshare(this.file);\n  }\n  // Group of radio buttons\n  for (var x = 0; x < this.elements.length; x++) {\n    if (this.elements[x].checked) {\n      return this.elements[x].value;\n    }\n  }\n  // Nothing checked.\n  return '';\n};\n\n\n/**\n * Set the user's check.\n * @param {string} text New content.\n */\nmobwrite.shareRadioObj.prototype.setClientText = function(text) {\n  for (var x = 0; x < this.elements.length; x++) {\n    this.elements[x].checked = (text == this.elements[x].value);\n    this.fireChange(this.elements[x]);\n  }\n};\n\n\n/**\n * Handler to accept radio buttons as elements that can be shared.\n * If the element is a radio button, create a new sharing object.\n * @param {*} node Object or ID of object to share.\n * @return {Object?} A sharing object or null.\n */\nmobwrite.shareRadioObj.shareHandler = function(node) {\n  if (typeof node == 'string') {\n    node = document.getElementById(node);\n  }\n  if (node && 'type' in node && node.type == 'radio') {\n    // Check to see if this is another element of an existing radio button group.\n    for (var id in mobwrite.shared) {\n      if (mobwrite.shared[id].form == node.form && mobwrite.shared[id].name == node.name) {\n        mobwrite.shared[id].elements.push(node);\n        return null;\n      }\n    }\n    // Create new radio button object.\n    return new mobwrite.shareRadioObj(node);\n  }\n  return null;\n};\n\n\n// Register this shareHandler with MobWrite.\nmobwrite.shareHandlers.push(mobwrite.shareRadioObj.shareHandler);\n\n\n// TEXTAREA, TEXT & PASSWORD INPUTS\n\n\n/**\n * Constructor of shared object representing a text field.\n * @param {Node} node A textarea, text or password input.\n * @constructor\n */\nmobwrite.shareTextareaObj = function(node) {\n  // Call our prototype's constructor.\n  mobwrite.shareObj.apply(this, [node.id]);\n  this.element = node;\n  if (node.type == 'password') {\n    // Use overwrite mode for password field, users can't see.\n    this.mergeChanges = false;\n  }\n};\n\n\n// The textarea shared object's parent is a shareObj.\nmobwrite.shareTextareaObj.prototype = new mobwrite.shareObj('');\n\n\n/**\n * Retrieve the user's text.\n * @return {string} Plaintext content.\n */\nmobwrite.shareTextareaObj.prototype.getClientText = function() {\n  if (!mobwrite.validNode_(this.element)) {\n    mobwrite.unshare(this.file);\n  }\n  var text = mobwrite.shareTextareaObj.normalizeLinebreaks_(this.element.value);\n  if (this.element.type == 'text') {\n    // Numeric data should use overwrite mode.\n    this.mergeChanges = !text.match(/^\\s*-?[\\d.,]+\\s*$/);\n  }\n  return text;\n};\n\n\n/**\n * Set the user's text.\n * @param {string} text New text\n */\nmobwrite.shareTextareaObj.prototype.setClientText = function(text) {\n  this.element.value = text;\n  this.fireChange(this.element);\n};\n\n\n/**\n * Modify the user's plaintext by applying a series of patches against it.\n * @param {Array.<patch_obj>} patches Array of Patch objects.\n */\nmobwrite.shareTextareaObj.prototype.patchClientText = function(patches) {\n  // Set some constants which tweak the matching behaviour.\n  // Maximum distance to search from expected location.\n  this.dmp.Match_Distance = 1000;\n  // At what point is no match declared (0.0 = perfection, 1.0 = very loose)\n  this.dmp.Match_Threshold = 0.6;\n\n  var oldClientText = this.getClientText();\n  var cursor = this.captureCursor_();\n  // Pack the cursor offsets into an array to be adjusted.\n  // See http://neil.fraser.name/writing/cursor/\n  var offsets = [];\n  if (cursor) {\n    offsets[0] = cursor.startOffset;\n    if ('endOffset' in cursor) {\n      offsets[1] = cursor.endOffset;\n    }\n  }\n  var newClientText = this.patch_apply_(patches, oldClientText, offsets);\n  // Set the new text only if there is a change to be made.\n  if (oldClientText != newClientText) {\n    this.setClientText(newClientText);\n    if (cursor) {\n      // Unpack the offset array.\n      cursor.startOffset = offsets[0];\n      if (offsets.length > 1) {\n        cursor.endOffset = offsets[1];\n        if (cursor.startOffset >= cursor.endOffset) {\n          cursor.collapsed = true;\n        }\n      }\n      this.restoreCursor_(cursor);\n    }\n  }\n};\n\n\n/**\n * Merge a set of patches onto the text.  Return a patched text.\n * @param {Array.<patch_obj>} patches Array of patch objects.\n * @param {string} text Old text.\n * @param {Array.<number>} offsets Offset indices to adjust.\n * @return {string} New text.\n */\nmobwrite.shareTextareaObj.prototype.patch_apply_ =\n    function(patches, text, offsets) {\n  if (patches.length == 0) {\n    return text;\n  }\n\n  // Deep copy the patches so that no changes are made to originals.\n  patches = this.dmp.patch_deepCopy(patches);\n  var nullPadding = this.dmp.patch_addPadding(patches);\n  text = nullPadding + text + nullPadding;\n\n  this.dmp.patch_splitMax(patches);\n  // delta keeps track of the offset between the expected and actual location\n  // of the previous patch.  If there are patches expected at positions 10 and\n  // 20, but the first patch was found at 12, delta is 2 and the second patch\n  // has an effective expected position of 22.\n  var delta = 0;\n  for (var x = 0; x < patches.length; x++) {\n    var expected_loc = patches[x].start2 + delta;\n    var text1 = this.dmp.diff_text1(patches[x].diffs);\n    var start_loc;\n    var end_loc = -1;\n    if (text1.length > this.dmp.Match_MaxBits) {\n      // patch_splitMax will only provide an oversized pattern in the case of\n      // a monster delete.\n      start_loc = this.dmp.match_main(text,\n          text1.substring(0, this.dmp.Match_MaxBits), expected_loc);\n      if (start_loc != -1) {\n        end_loc = this.dmp.match_main(text,\n            text1.substring(text1.length - this.dmp.Match_MaxBits),\n            expected_loc + text1.length - this.dmp.Match_MaxBits);\n        if (end_loc == -1 || start_loc >= end_loc) {\n          // Can't find valid trailing context.  Drop this patch.\n          start_loc = -1;\n        }\n      }\n    } else {\n      start_loc = this.dmp.match_main(text, text1, expected_loc);\n    }\n    if (start_loc == -1) {\n      // No match found.  :(\n      if (mobwrite.debug) {\n        window.console.warn('Patch failed: ' + patches[x]);\n      }\n      // Subtract the delta for this failed patch from subsequent patches.\n      delta -= patches[x].length2 - patches[x].length1;\n    } else {\n      // Found a match.  :)\n      if (mobwrite.debug) {\n        window.console.info('Patch OK.');\n      }\n      delta = start_loc - expected_loc;\n      var text2;\n      if (end_loc == -1) {\n        text2 = text.substring(start_loc, start_loc + text1.length);\n      } else {\n        text2 = text.substring(start_loc, end_loc + this.dmp.Match_MaxBits);\n      }\n      // Run a diff to get a framework of equivalent indices.\n      var diffs = this.dmp.diff_main(text1, text2, false);\n      if (text1.length > this.dmp.Match_MaxBits &&\n          this.dmp.diff_levenshtein(diffs) / text1.length >\n          this.dmp.Patch_DeleteThreshold) {\n        // The end points match, but the content is unacceptably bad.\n        if (mobwrite.debug) {\n          window.console.warn('Patch contents mismatch: ' + patches[x]);\n        }\n      } else {\n        var index1 = 0;\n        var index2;\n        for (var y = 0; y < patches[x].diffs.length; y++) {\n          var mod = patches[x].diffs[y];\n          if (mod[0] !== DIFF_EQUAL) {\n            index2 = this.dmp.diff_xIndex(diffs, index1);\n          }\n          if (mod[0] === DIFF_INSERT) {  // Insertion\n            text = text.substring(0, start_loc + index2) + mod[1] +\n                   text.substring(start_loc + index2);\n            for (var i = 0; i < offsets.length; i++) {\n              if (offsets[i] + nullPadding.length > start_loc + index2) {\n                offsets[i] += mod[1].length;\n              }\n            }\n          } else if (mod[0] === DIFF_DELETE) {  // Deletion\n            var del_start = start_loc + index2;\n            var del_end = start_loc + this.dmp.diff_xIndex(diffs,\n                index1 + mod[1].length);\n            text = text.substring(0, del_start) + text.substring(del_end);\n            for (var i = 0; i < offsets.length; i++) {\n              if (offsets[i] + nullPadding.length > del_start) {\n                if (offsets[i] + nullPadding.length < del_end) {\n                  offsets[i] = del_start - nullPadding.length;\n                } else {\n                  offsets[i] -= del_end - del_start;\n                }\n              }\n            }\n          }\n          if (mod[0] !== DIFF_DELETE) {\n            index1 += mod[1].length;\n          }\n        }\n      }\n    }\n  }\n  // Strip the padding off.\n  text = text.substring(nullPadding.length, text.length - nullPadding.length);\n  return text;\n};\n\n\n/**\n * Record information regarding the current cursor.\n * @return {Object?} Context information of the cursor.\n * @private\n */\nmobwrite.shareTextareaObj.prototype.captureCursor_ = function() {\n  if ('activeElement' in this.element && !this.element.activeElement) {\n    // Safari specific code.\n    // Restoring a cursor in an unfocused element causes the focus to jump.\n    return null;\n  }\n  var padLength = this.dmp.Match_MaxBits / 2;  // Normally 16.\n  var text = this.element.value;\n  var cursor = {};\n  if ('selectionStart' in this.element) {  // W3\n    try {\n      var selectionStart = this.element.selectionStart;\n      var selectionEnd = this.element.selectionEnd;\n    } catch (e) {\n      // No cursor; the element may be \"display:none\".\n      return null;\n    }\n    cursor.startPrefix = text.substring(selectionStart - padLength, selectionStart);\n    cursor.startSuffix = text.substring(selectionStart, selectionStart + padLength);\n    cursor.startOffset = selectionStart;\n    cursor.collapsed = (selectionStart == selectionEnd);\n    if (!cursor.collapsed) {\n      cursor.endPrefix = text.substring(selectionEnd - padLength, selectionEnd);\n      cursor.endSuffix = text.substring(selectionEnd, selectionEnd + padLength);\n      cursor.endOffset = selectionEnd;\n    }\n  } else {  // IE\n    // Walk up the tree looking for this textarea's document node.\n    var doc = this.element;\n    while (doc.parentNode) {\n      doc = doc.parentNode;\n    }\n    if (!doc.selection || !doc.selection.createRange) {\n      // Not IE?\n      return null;\n    }\n    var range = doc.selection.createRange();\n    if (range.parentElement() != this.element) {\n      // Cursor not in this textarea.\n      return null;\n    }\n    var newRange = doc.body.createTextRange();\n\n    cursor.collapsed = (range.text == '');\n    newRange.moveToElementText(this.element);\n    if (!cursor.collapsed) {\n      newRange.setEndPoint('EndToEnd', range);\n      cursor.endPrefix = newRange.text;\n      cursor.endOffset = cursor.endPrefix.length;\n      cursor.endPrefix = cursor.endPrefix.substring(cursor.endPrefix.length - padLength);\n    }\n    newRange.setEndPoint('EndToStart', range);\n    cursor.startPrefix = newRange.text;\n    cursor.startOffset = cursor.startPrefix.length;\n    cursor.startPrefix = cursor.startPrefix.substring(cursor.startPrefix.length - padLength);\n\n    newRange.moveToElementText(this.element);\n    newRange.setEndPoint('StartToStart', range);\n    cursor.startSuffix = newRange.text.substring(0, padLength);\n    if (!cursor.collapsed) {\n      newRange.setEndPoint('StartToEnd', range);\n      cursor.endSuffix = newRange.text.substring(0, padLength);\n    }\n  }\n\n  // Record scrollbar locations\n  if ('scrollTop' in this.element) {\n    cursor.scrollTop = this.element.scrollTop / this.element.scrollHeight;\n    cursor.scrollLeft = this.element.scrollLeft / this.element.scrollWidth;\n  }\n\n  // alert(cursor.startPrefix + '|' + cursor.startSuffix + ' ' +\n  //     cursor.startOffset + '\\n' + cursor.endPrefix + '|' +\n  //     cursor.endSuffix + ' ' + cursor.endOffset + '\\n' +\n  //     cursor.scrollTop + ' x ' + cursor.scrollLeft);\n  return cursor;\n};\n\n\n/**\n * Attempt to restore the cursor's location.\n * @param {Object} cursor Context information of the cursor.\n * @private\n */\nmobwrite.shareTextareaObj.prototype.restoreCursor_ = function(cursor) {\n  // Set some constants which tweak the matching behaviour.\n  // Maximum distance to search from expected location.\n  this.dmp.Match_Distance = 1000;\n  // At what point is no match declared (0.0 = perfection, 1.0 = very loose)\n  this.dmp.Match_Threshold = 0.9;\n\n  var padLength = this.dmp.Match_MaxBits / 2;  // Normally 16.\n  var newText = this.element.value;\n\n  // Find the start of the selection in the new text.\n  var pattern1 = cursor.startPrefix + cursor.startSuffix;\n  var pattern2, diff;\n  var cursorStartPoint = this.dmp.match_main(newText, pattern1,\n      cursor.startOffset - padLength);\n  if (cursorStartPoint !== null) {\n    pattern2 = newText.substring(cursorStartPoint,\n                                 cursorStartPoint + pattern1.length);\n    //alert(pattern1 + '\\nvs\\n' + pattern2);\n    // Run a diff to get a framework of equivalent indicies.\n    diff = this.dmp.diff_main(pattern1, pattern2, false);\n    cursorStartPoint += this.dmp.diff_xIndex(diff, cursor.startPrefix.length);\n  }\n\n  var cursorEndPoint = null;\n  if (!cursor.collapsed) {\n    // Find the end of the selection in the new text.\n    pattern1 = cursor.endPrefix + cursor.endSuffix;\n    cursorEndPoint = this.dmp.match_main(newText, pattern1,\n        cursor.endOffset - padLength);\n    if (cursorEndPoint !== null) {\n      pattern2 = newText.substring(cursorEndPoint,\n                                   cursorEndPoint + pattern1.length);\n      //alert(pattern1 + '\\nvs\\n' + pattern2);\n      // Run a diff to get a framework of equivalent indicies.\n      diff = this.dmp.diff_main(pattern1, pattern2, false);\n      cursorEndPoint += this.dmp.diff_xIndex(diff, cursor.endPrefix.length);\n    }\n  }\n\n  // Deal with loose ends\n  if (cursorStartPoint === null && cursorEndPoint !== null) {\n    // Lost the start point of the selection, but we have the end point.\n    // Collapse to end point.\n    cursorStartPoint = cursorEndPoint;\n  } else if (cursorStartPoint === null && cursorEndPoint === null) {\n    // Lost both start and end points.\n    // Jump to the offset of start.\n    cursorStartPoint = cursor.startOffset;\n  }\n  if (cursorEndPoint === null) {\n    // End not known, collapse to start.\n    cursorEndPoint = cursorStartPoint;\n  }\n\n  // Restore selection.\n  if ('selectionStart' in this.element) {  // W3\n    this.element.selectionStart = cursorStartPoint;\n    this.element.selectionEnd = cursorEndPoint;\n  } else {  // IE\n    // Walk up the tree looking for this textarea's document node.\n    var doc = this.element;\n    while (doc.parentNode) {\n      doc = doc.parentNode;\n    }\n    if (!doc.selection || !doc.selection.createRange) {\n      // Not IE?\n      return;\n    }\n    // IE's TextRange.move functions treat '\\r\\n' as one character.\n    var snippet = this.element.value.substring(0, cursorStartPoint);\n    var ieStartPoint = snippet.replace(/\\r\\n/g, '\\n').length;\n\n    var newRange = doc.body.createTextRange();\n    newRange.moveToElementText(this.element);\n    newRange.collapse(true);\n    newRange.moveStart('character', ieStartPoint);\n    if (!cursor.collapsed) {\n      snippet = this.element.value.substring(cursorStartPoint, cursorEndPoint);\n      var ieMidLength = snippet.replace(/\\r\\n/g, '\\n').length;\n      newRange.moveEnd('character', ieMidLength);\n    }\n    newRange.select();\n  }\n\n  // Restore scrollbar locations\n  if ('scrollTop' in cursor) {\n    this.element.scrollTop = cursor.scrollTop * this.element.scrollHeight;\n    this.element.scrollLeft = cursor.scrollLeft * this.element.scrollWidth;\n  }\n};\n\n\n/**\n * Ensure that all linebreaks are LF\n * @param {string} text Text with unknown line breaks\n * @return {string} Text with normalized linebreaks\n * @private\n */\nmobwrite.shareTextareaObj.normalizeLinebreaks_ = function(text) {\n  return text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n};\n\n\n/**\n * Handler to accept text fields as elements that can be shared.\n * If the element is a textarea, text or password input, create a new\n * sharing object.\n * @param {*} node Object or ID of object to share.\n * @return {Object?} A sharing object or null.\n */\nmobwrite.shareTextareaObj.shareHandler = function(node) {\n  if (typeof node == 'string') {\n    node = document.getElementById(node);\n  }\n  if (node && 'value' in node && 'type' in node && (node.type == 'textarea' ||\n      node.type == 'text' || node.type == 'password')) {\n    if (mobwrite.UA_webkit) {\n      // Safari needs to track which text element has the focus.\n      node.addEventListener('focus', function() {this.activeElement = true;},\n          false);\n      node.addEventListener('blur', function() {this.activeElement = false;},\n          false);\n      node.activeElement = false;\n    }\n    return new mobwrite.shareTextareaObj(node);\n  }\n  return null;\n};\n\n\n// Register this shareHandler with MobWrite.\nmobwrite.shareHandlers.push(mobwrite.shareTextareaObj.shareHandler);\n"
  },
  {
    "path": "static/code/mobwrite/demo/test.html",
    "content": "<HTML>\n<HEAD>\n<TITLE>Manual test of MobWrite's client-server Protocol</TITLE>\n</HEAD>\n<BODY>\n<H1>Manual test of MobWrite's client-server Protocol</H1>\n<FORM METHOD=\"post\" ACTION=\"/mobwrite\">\n<TEXTAREA NAME=\"q\" COLS=70 ROWS=6>u:hacker\nF:0:manualtest\nR:0:I am%0ACanadian.\nd:0:=2\t-2\t+was\t=10\n\n</TEXTAREA>\n<P>\n<INPUT TYPE=\"submit\" VALUE=\"Submit to Server\">\n</FORM>\n</BODY>\n</HTML>\n"
  },
  {
    "path": "static/code/mobwrite/mobwrite_cc.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Realtime collaboration for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\n/**\n * Constructor of sharing object representing the code editor.\n * @constructor\n */\nCode.MobwriteShare = function() {\n  // Call our prototype's constructor.\n  mobwrite.shareObj.call(this, Code.MobwriteShare.id);\n};\n\n/**\n * Handler to accept the code editor as an element that can be shared.\n * @param {string} type Type of object to share\n *     ('Code' is currently the only option).\n * @return {Object?} A sharing object or null.\n */\nCode.MobwriteShare.shareHandler = function(type) {\n  if (type === 'Code') {\n    return new Code.MobwriteShare();\n  }\n  return null;\n};\n\n/**\n * Initialization that happens once DMP, MobWrite, and this file are all loaded.\n * Called by Code.Editor.waitMobWrite_\n */\nCode.MobwriteShare.init = function() {\n  // Fetch the sharing ID from the parent frame's URL, or invent a new one.\n  var hash = parent && parent.location && parent.location.hash;\n  if (hash) {\n    hash = hash.substring(1);\n  }\n  Code.MobwriteShare.id = hash || mobwrite.uniqueId();\n\n  // The sharing object's parent is a shareObj.\n  Code.MobwriteShare.prototype = new mobwrite.shareObj();\n\n  /**\n   * Retrieve the user's content.\n   * @return {string} Plaintext content.\n   */\n  Code.MobwriteShare.prototype.getClientText = function() {\n    var value = '';\n    if (Code.Editor.currentEditor) {\n      value = Code.Editor.currentEditor.getSource() || '';\n    }\n    // Numeric data should use overwrite mode.\n    this.mergeChanges = !value.match(/^\\s*-?[\\d.]+\\s*$/);\n    return value;\n  };\n\n  /**\n   * Set the user's content.\n   * @param {string} text New content.\n   */\n  Code.MobwriteShare.prototype.setClientText = function(text) {\n    Code.Editor.setSourceToAllEditors(text, false);\n  };\n\n  // Register this shareHandler with MobWrite.\n  mobwrite.shareHandlers.push(Code.MobwriteShare.shareHandler);\n  // Default max is 10 seconds.  Decrease to 5.\n  mobwrite.maxSyncInterval = 5000;\n};\n"
  },
  {
    "path": "static/code/mobwrite/mobwrite_core.js",
    "content": "/**\n * @license\n * Copyright 2006 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview This client-side code drives the synchronisation.\n * @author fraser@google.com (Neil Fraser)\n */\n\n\n/**\n * Namespace containing all MobWrite code.\n */\nvar mobwrite = {};\n\n\n/**\n * URL of Ajax gateway.\n * @type {string}\n */\nmobwrite.syncGateway = '/scripts/q.py';\n\n\n/**\n * Print diagnostic messages to the browser's console.\n * @type {boolean}\n */\nmobwrite.debug = true;\n\n\n/**\n * PID of task which will trigger next Ajax request.\n * @type {number?}\n * @private\n */\nmobwrite.syncRunPid_ = null;\n\n\n/**\n * PID of task which will kill stalled Ajax request.\n * @type {number?}\n * @private\n */\nmobwrite.syncKillPid_ = null;\n\n\n/**\n * Time to wait for a connection before giving up and retrying.\n * @type {number}\n */\nmobwrite.timeoutInterval = 30000;\n\n\n/**\n * Shortest interval (in milliseconds) between connections.\n * @type {number}\n */\nmobwrite.minSyncInterval = 1000;\n\n\n/**\n * Longest interval (in milliseconds) between connections.\n * @type {number}\n */\nmobwrite.maxSyncInterval = 4000;\n\n\n/**\n * Initial interval (in milliseconds) for connections.\n * This value is modified later as traffic rates are established.\n * @type {number}\n */\nmobwrite.syncInterval = 2000;\n\n\n/**\n * Optional prefix to automatically add to all IDs.\n * @type {string}\n */\nmobwrite.idPrefix = '';\n\n\n/**\n * Flag to nullify all shared elements and terminate.\n * @type {boolean}\n */\nmobwrite.nullifyAll = false;\n\n\n/**\n * Track whether something changed client-side in each sync.\n * @type {boolean}\n * @private\n */\nmobwrite.clientChange_ = false;\n\n\n/**\n * Track whether something changed server-side in each sync.\n * @type {boolean}\n * @private\n */\nmobwrite.serverChange_ = false;\n\n\n/**\n * Temporary object used while each sync is airborne.\n * @type {Object?}\n * @private\n */\nmobwrite.syncAjaxObj_ = null;\n\n\n/**\n * Return a random ID that's 6 characters long.\n * 79^6 = 243,087,455,521\n * @return {string} Random ID.\n */\nmobwrite.uniqueId = function() {\n  // All the legal characters for a URL 'fragment' (hash) as per RFC 3986.\n  var soup = 'ABCDEFGHIJKLMNOPQUSTPVWXYZabcdefghijklmnopqrstuvwxyz' +\n      '0123456789-._~!$&\\'()*+,;=?/';\n  var id = '';\n  for (var i = 0; i < 6; i++) {\n    id += soup.charAt(Math.random() * soup.length);\n  }\n  return id;\n};\n\n\n/**\n * Unique ID for this session.\n * @type {string}\n */\nmobwrite.syncUsername = mobwrite.uniqueId();\n\n\n/**\n * Hash of all shared objects.\n * @type {Object}\n */\nmobwrite.shared = Object.create(null);\n\n\n/**\n * Array of registered handlers for sharing types.\n * Modules add their share functions to this list.\n * @type {Array.<Function>}\n */\nmobwrite.shareHandlers = [];\n\n\n/**\n * Prototype of shared object.\n * @param {string=} id Unique file ID.\n * @constructor\n */\nmobwrite.shareObj = function(id) {\n  if (!id) return;  // Creating subclass prototype object.\n  this.file = id;\n  this.dmp = new diff_match_patch();\n  this.dmp.Diff_Timeout = 0.5;\n  // List of unacknowledged edits sent to the server.\n  this.editStack = [];\n  if (mobwrite.debug) {\n    console.info('Creating shareObj: \"' + id + '\"');\n  }\n};\n\n\n/**\n * Client's understanding of what the server's text looks like.\n * @type {string}\n */\nmobwrite.shareObj.prototype.shadowText = '';\n\n\n/**\n * The client's version for the shadow (n).\n * @type {number}\n */\nmobwrite.shareObj.prototype.clientVersion = 0;\n\n\n/**\n * The server's version for the shadow (m).\n * @type {number}\n */\nmobwrite.shareObj.prototype.serverVersion = 0;\n\n\n/**\n * Did the client understand the server's delta in the previous heartbeat?\n * Initialize false because the server and client are out of sync initially.\n * @type {boolean}\n */\nmobwrite.shareObj.prototype.deltaOk = false;\n\n\n/**\n * Synchronization mode.\n * True: Used for text, attempts to gently merge differences together.\n * False: Used for numbers, overwrites conflicts, last save wins.\n * @type {boolean}\n */\nmobwrite.shareObj.prototype.mergeChanges = true;\n\n\n/**\n * Fetch or compute a plaintext representation of the user's text.\n * @return {string} Plaintext content.\n */\nmobwrite.shareObj.prototype.getClientText = function() {\n  throw new Error('Defined by subclass');\n};\n\n\n/**\n * Set the user's text based on the provided plaintext.\n * @param {string} text New text.\n */\nmobwrite.shareObj.prototype.setClientText = function(text) {\n  throw new Error('Defined by subclass');\n};\n\n\n/**\n * Modify the user's plaintext by applying a series of patches against it.\n * @param {Array.<patch_obj>} patches Array of Patch objects.\n */\nmobwrite.shareObj.prototype.patchClientText = function(patches) {\n  var oldClientText = this.getClientText();\n  var result = this.dmp.patch_apply(patches, oldClientText);\n  // Set the new text only if there is a change to be made.\n  if (oldClientText != result[0]) {\n    // The following will probably destroy any cursor or selection.\n    // Widgets with cursors should override and patch more delicately.\n    this.setClientText(result[0]);\n  }\n};\n\n\n/**\n * Notification of when a diff was sent to the server.\n * @param {Array.<Array.<*>>} diffs Array of diff tuples.\n */\nmobwrite.shareObj.prototype.onSentDiff = function(diffs) {\n  // Potential hook for subclass.\n};\n\n\n/**\n * Fire a synthetic 'change' event to a target element.\n * Notifies an element that its contents have been changed.\n * @param {Object} target Element to notify.\n */\nmobwrite.shareObj.prototype.fireChange = function(target) {\n  if ('createEvent' in document) {  // W3\n    var e = document.createEvent('HTMLEvents');\n    e.initEvent('change', false, false);\n    target.dispatchEvent(e);\n  } else if ('fireEvent' in target) { // IE\n    target.fireEvent('onchange');\n  }\n};\n\n\n/**\n * Return the command to nullify this field.  Also unshares this field.\n * @return {string} Command to be sent to the server.\n */\nmobwrite.shareObj.prototype.nullify = function() {\n  mobwrite.unshare(this.file);\n  return 'N:' + mobwrite.idPrefix + this.file + '\\n';\n};\n\n\n/**\n * Asks the shareObj to synchronize.  Computes client-made changes since\n * previous postback.  Return '' to skip this synchronization.\n * @return {string} Commands to be sent to the server.\n */\nmobwrite.shareObj.prototype.syncText = function() {\n  var clientText = this.getClientText();\n  if (this.deltaOk) {\n    // The last delta postback from the server to this shareObj was successful.\n    // Send a compressed delta.\n    var diffs = this.dmp.diff_main(this.shadowText, clientText, true);\n    if (diffs.length > 2) {\n      this.dmp.diff_cleanupSemantic(diffs);\n      this.dmp.diff_cleanupEfficiency(diffs);\n    }\n    var changed = diffs.length != 1 || diffs[0][0] != DIFF_EQUAL;\n    if (changed) {\n      mobwrite.clientChange_ = true;\n      this.shadowText = clientText;\n    }\n    // Don't bother appending a no-change diff onto the stack if the stack\n    // already contains something.\n    if (changed || !this.editStack.length) {\n      var action = (this.mergeChanges ? 'd:' : 'D:') + this.clientVersion +\n          ':' + this.dmp.diff_toDelta(diffs);\n      this.editStack.push([this.clientVersion, action]);\n      this.clientVersion++;\n      this.onSentDiff(diffs);\n    }\n  } else {\n    // The last delta postback from the server to this shareObj didn't match.\n    // Send a full text dump to get back in sync.  This will result in any\n    // changes since the last postback being wiped out. :(\n    this.shadowText = clientText;\n    this.clientVersion++;\n    var action = 'r:' + this.clientVersion + ':' +\n                 encodeURI(clientText).replace(/%20/g, ' ');\n    // Append the action to the edit stack.\n    this.editStack.push([this.clientVersion, action]);\n    // Sending a raw dump will put us back in sync.\n    // Set deltaOk to true in case this sync fails to connect, in which case\n    // the following sync(s) should be a delta, not more raw dumps.\n    this.deltaOk = true;\n  }\n\n  // Create the output starting with the file statement, followed by the edits.\n  var data = 'F:' + this.serverVersion + ':' +\n      mobwrite.idPrefix + this.file + '\\n';\n  for (var i = 0; i < this.editStack.length; i++) {\n    data += this.editStack[i][1] + '\\n';\n  }\n  return data;\n};\n\n\n/**\n * Collect all client-side changes and send them to the server.\n * @private\n */\nmobwrite.syncRun1_ = function() {\n  // Initialize clientChange_, to be checked at the end of syncRun2_.\n  mobwrite.clientChange_ = false;\n  var data = [];\n  data[0] = 'u:' + mobwrite.syncUsername + '\\n';\n  var empty = true;\n  // Ask every shared object for their deltas.\n  for (var x in mobwrite.shared) {\n    if (mobwrite.shared[x]) {\n      if (mobwrite.nullifyAll) {\n        data.push(mobwrite.shared[x].nullify());\n      } else {\n        data.push(mobwrite.shared[x].syncText());\n      }\n      empty = false;\n    }\n  }\n  if (empty) {\n    // No sync objects.\n    if (mobwrite.debug) {\n      console.info('MobWrite task stopped.');\n    }\n    return;\n  }\n  if (data.length == 1) {\n    // No sync data.\n    if (mobwrite.debug) {\n      console.info('All objects silent; null sync.');\n    }\n    mobwrite.syncRun2_('\\n\\n');\n    return;\n  }\n\n  if (mobwrite.debug) {\n    console.info('TO server:\\n' + data.join(''));\n  }\n  // Add terminating blank line.\n  data.push('\\n');\n  data = data.join('');\n\n  // Schedule a watchdog task to catch us if something horrible happens.\n  mobwrite.syncKillPid_ =\n      setTimeout(mobwrite.syncKill_, mobwrite.timeoutInterval);\n\n  // Issue Ajax post of client-side changes and request server-side changes.\n  data = 'q=' + encodeURIComponent(data);\n  mobwrite.syncAjaxObj_ = mobwrite.syncLoadAjax_(mobwrite.syncGateway, data,\n      mobwrite.syncCheckAjax_);\n  // Execution will resume in either syncCheckAjax_(), or syncKill_()\n};\n\n\n/**\n * Parse all server-side changes and distribute them to the shared objects.\n * @param {string} text Raw content from server.\n * @private\n */\nmobwrite.syncRun2_ = function(text) {\n  // Initialize serverChange_, to be checked at the end of syncRun2_.\n  mobwrite.serverChange_ = false;\n  if (mobwrite.debug) {\n    console.info('FROM server:\\n' + text);\n  }\n  // There must be a newline followed by a blank line.\n  if (text.length < 2 || text.substring(text.length - 2) != '\\n\\n') {\n    text = '';\n    if (mobwrite.debug) {\n      console.info('Truncated data.  Abort.');\n    }\n  }\n  var lines = text.split('\\n');\n  var file = null;\n  var clientVersion = null;\n  for (var i = 0; i < lines.length; i++) {\n    var line = lines[i];\n    if (!line) {\n      // Terminate on blank line.\n      break;\n    }\n    // Divide each line into 'N:value' pairs.\n    if (line.charAt(1) != ':') {\n      if (mobwrite.debug) {\n        console.error('Unparsable line: ' + line);\n      }\n      continue;\n    }\n    var name = line.charAt(0);\n    var value = line.substring(2);\n\n    // Parse out a version number for file, delta or raw.\n    var version;\n    if ('FfDdRr'.indexOf(name) != -1) {\n      var div = value.indexOf(':');\n      if (div < 1) {\n        if (mobwrite.debug) {\n          console.error('No version number: ' + line);\n        }\n        continue;\n      }\n      version = parseInt(value.substring(0, div), 10);\n      if (isNaN(version)) {\n        if (mobwrite.debug) {\n          console.error('NaN version number: ' + line);\n        }\n        continue;\n      }\n      value = value.substring(div + 1);\n    }\n    if (name == 'F' || name == 'f') {\n      // File indicates which shared object following delta/raw applies to.\n      if (value.substring(0, mobwrite.idPrefix.length) == mobwrite.idPrefix) {\n        // Trim off the ID prefix.\n        value = value.substring(mobwrite.idPrefix.length);\n      } else {\n        // This file does not have our ID prefix.\n        file = null;\n        if (mobwrite.debug) {\n          console.error('File does not have \"' + mobwrite.idPrefix +\n              '\" prefix: ' + value);\n        }\n        continue;\n      }\n      if (mobwrite.shared[value]) {\n        file = mobwrite.shared[value];\n        file.deltaOk = true;\n        clientVersion = version;\n        // Remove any elements from the edit stack with low version numbers\n        // which have been acked by the server.\n        for (var j = 0; j < file.editStack.length; j++) {\n          if (file.editStack[j][0] <= clientVersion) {\n            file.editStack.splice(j, 1);\n            j--;\n          }\n        }\n\n      } else {\n        // This file does not map to a currently shared object.\n        file = null;\n        if (mobwrite.debug) {\n          console.error('Unknown file: ' + value);\n        }\n      }\n    } else if (name == 'R' || name == 'r') {\n      // The server reports it was unable to integrate the previous delta.\n      if (file) {\n        file.shadowText = decodeURI(value);\n        file.clientVersion = clientVersion;\n        file.serverVersion = version;\n        file.editStack = [];\n        if (name == 'R') {\n          // Accept the server's raw text dump and wipe out any user's changes.\n          file.setClientText(file.shadowText);\n        }\n        // Server-side activity.\n        mobwrite.serverChange_ = true;\n      }\n    } else if (name == 'D' || name == 'd') {\n      // The server offers a compressed delta of changes to be applied.\n      if (file) {\n        if (clientVersion != file.clientVersion) {\n          // Can't apply a delta on a mismatched shadow version.\n          file.deltaOk = false;\n          if (mobwrite.debug) {\n            console.error('Client version number mismatch.\\n' +\n                'Expected: ' + file.clientVersion + ' Got: ' + clientVersion);\n          }\n        } else if (version > file.serverVersion) {\n          // Server has a version in the future?\n          file.deltaOk = false;\n          if (mobwrite.debug) {\n            console.error('Server version in future.\\n' +\n                'Expected: ' + file.serverVersion + ' Got: ' + version);\n          }\n        } else if (version < file.serverVersion) {\n          // We've already seen this diff.\n          if (mobwrite.debug) {\n            console.warn('Server version in past.\\n' +\n                'Expected: ' + file.serverVersion + ' Got: ' + version);\n          }\n        } else {\n          // Expand the delta into a diff using the client shadow.\n          var diffs;\n          try {\n            diffs = file.dmp.diff_fromDelta(file.shadowText, value);\n            file.serverVersion++;\n          } catch (ex) {\n            // The delta the server supplied does not fit on our copy of\n            // shadowText.\n            diffs = null;\n            // Set deltaOk to false so that on the next sync we send\n            // a complete dump to get back in sync.\n            file.deltaOk = false;\n            // Do the next sync soon because the user will lose any changes.\n            mobwrite.syncInterval = 0;\n            if (mobwrite.debug) {\n              console.error('Delta mismatch.\\n' + encodeURI(file.shadowText));\n            }\n          }\n          if (diffs && (diffs.length != 1 || diffs[0][0] != DIFF_EQUAL)) {\n            // Compute and apply the patches.\n            if (name == 'D') {\n              // Overwrite text.\n              file.shadowText = file.dmp.diff_text2(diffs);\n              file.setClientText(file.shadowText);\n            } else {\n              // Merge text.\n              var patches = file.dmp.patch_make(file.shadowText, diffs);\n              // First shadowText.  Should be guaranteed to work.\n              var serverResult = file.dmp.patch_apply(patches, file.shadowText);\n              file.shadowText = serverResult[0];\n              // Second the user's text.\n              file.patchClientText(patches);\n            }\n            // Server-side activity.\n            mobwrite.serverChange_ = true;\n          }\n        }\n      }\n    }\n  }\n\n  mobwrite.computeSyncInterval_();\n\n  // Ensure that there is only one sync task.\n  clearTimeout(mobwrite.syncRunPid_);\n  // Schedule the next sync.\n  mobwrite.syncRunPid_ =\n      setTimeout(mobwrite.syncRun1_, mobwrite.syncInterval);\n  // Terminate the watchdog task, everything's ok.\n  clearTimeout(mobwrite.syncKillPid_);\n  mobwrite.syncKillPid_ = null;\n};\n\n\n/**\n * Compute how long to wait until next synchronization.\n * @private\n */\nmobwrite.computeSyncInterval_ = function() {\n  var range = mobwrite.maxSyncInterval - mobwrite.minSyncInterval;\n  if (mobwrite.clientChange_) {\n    // Client-side activity.\n    // Cut the sync interval by 40% of the min-max range.\n    mobwrite.syncInterval -= range * 0.4;\n  }\n  if (mobwrite.serverChange_) {\n    // Server-side activity.\n    // Cut the sync interval by 20% of the min-max range.\n    mobwrite.syncInterval -= range * 0.2;\n  }\n  if (!mobwrite.clientChange_ && !mobwrite.serverChange_) {\n    // No activity.\n    // Let the sync interval creep up by 10% of the min-max range.\n    mobwrite.syncInterval += range * 0.1;\n  }\n  // Keep the sync interval constrained between min and max.\n  mobwrite.syncInterval =\n      Math.max(mobwrite.minSyncInterval, mobwrite.syncInterval);\n  mobwrite.syncInterval =\n      Math.min(mobwrite.maxSyncInterval, mobwrite.syncInterval);\n};\n\n\n/**\n * If the Ajax call doesn't complete after a timeout period, start over.\n * @private\n */\nmobwrite.syncKill_ = function() {\n  mobwrite.syncKillPid_ = null;\n  if (mobwrite.syncAjaxObj_) {\n    // Cleanup old Ajax connection.\n    mobwrite.syncAjaxObj_.abort();\n    mobwrite.syncAjaxObj_ = null;\n  }\n  if (mobwrite.debug) {\n    console.warn('Connection timeout.');\n  }\n  clearTimeout(mobwrite.syncRunPid_);\n  // Initiate a new sync right now.\n  mobwrite.syncRunPid_ = setTimeout(mobwrite.syncRun1_, 1);\n};\n\n\n/**\n * Initiate an Ajax network connection.\n * @param {string} url Location to send request.\n * @param {string} post Data to be sent.\n * @param {Function} callback Function to be called when response arrives.\n * @return {!Object} New Ajax object.\n * @private\n */\nmobwrite.syncLoadAjax_ = function(url, post, callback) {\n  var req = new XMLHttpRequest();\n  req.onload = callback;\n  req.open('POST', url, true);\n  req.withCredentials = true;\n  req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');\n  req.send(post);\n  return req;\n};\n\n\n/**\n * Callback function for Ajax request.  Checks network response was ok,\n * then calls mobwrite.syncRun2_.\n * @private\n */\nmobwrite.syncCheckAjax_ = function() {\n  if (typeof mobwrite == 'undefined' || !mobwrite.syncAjaxObj_) {\n    // This might be a callback after the page has unloaded,\n    // or this might be a callback which we deemed to have timed out.\n    return;\n  }\n  // Only if \"OK\"\n  if (mobwrite.syncAjaxObj_.status === 200) {\n    var text = mobwrite.syncAjaxObj_.responseText;\n    mobwrite.syncAjaxObj_ = null;\n    mobwrite.syncRun2_(text);\n  } else if (mobwrite.syncAjaxObj_.status === 410) {\n    // Required cookie not found.  Stop sharing.\n    console.warn('410: Required cookie not found');\n    for (var file in mobwrite.shared) {\n      delete mobwrite.shared[file];\n    }\n  } else {\n    if (mobwrite.debug) {\n      console.warn('Connection error code: ' + mobwrite.syncAjaxObj_.status);\n    }\n    mobwrite.syncAjaxObj_ = null;\n  }\n};\n\n\n/**\n * When unloading, run a sync one last time.\n * @private\n */\nmobwrite.unload_ = function() {\n  if (!mobwrite.syncKillPid_) {\n    // Turn off debug mode since the console disappears on page unload before\n    // this code does.\n    mobwrite.debug = false;\n    mobwrite.syncRun1_();\n  }\n  // By the time the callback runs mobwrite.syncRun2_, this page will probably\n  // be gone.  But that's ok, we are just sending our last changes out, we\n  // don't care what the server says.\n};\n\n\n// Attach unload event to\naddEventListener('unload', mobwrite.unload_, false);\n\n\n/**\n * Start sharing the specified object(s).\n * @param {*} var_args Object(s) or ID(s) of object(s) to share.\n */\nmobwrite.share = function(var_args) {\n  for (var i = 0; i < arguments.length; i++) {\n    var el = arguments[i];\n    var result = null;\n    // Ask every registered handler if it knows what to do with this object.\n    for (var j = 0; j < mobwrite.shareHandlers.length && !result; j++) {\n      result = mobwrite.shareHandlers[j].call(mobwrite, el);\n    }\n    if (result && result.file) {\n      if (!result.file.match(/^[-.~!$&\\'()*+,;=?\\/\\w]*$/)) {\n        if (mobwrite.debug) {\n          console.error('Illegal id \"' + result.file + '\".');\n        }\n        continue;\n      }\n      if (result.file in mobwrite.shared) {\n        // Already exists.\n        // Don't replace, since we don't want to lose state.\n        if (mobwrite.debug) {\n          console.warn('Ignoring duplicate share on \"' + el + '\".');\n        }\n        continue;\n      }\n      mobwrite.shared[result.file] = result;\n\n      if (mobwrite.syncRunPid_ === null) {\n        // Startup the main task if it doesn't already exist.\n        if (mobwrite.debug) {\n          console.info('MobWrite task started.');\n        }\n      } else {\n        // Bring sync forward in time.\n        clearTimeout(mobwrite.syncRunPid_);\n      }\n      mobwrite.syncRunPid_ = setTimeout(mobwrite.syncRun1_, 10);\n    } else {\n      if (mobwrite.debug) {\n        console.warn('Share: Unknown widget type: ' + el + '.');\n      }\n    }\n  }\n};\n\n\n/**\n * Stop sharing the specified object(s).\n * Does not handle forms recursively.\n * @param {*} var_args Object(s) or ID(s) of object(s) to unshare.\n */\nmobwrite.unshare = function(var_args) {\n  for (var i = 0; i < arguments.length; i++) {\n    var el = arguments[i];\n    if (typeof el == 'string' && mobwrite.shared[el]) {\n      delete mobwrite.shared[el];\n      if (mobwrite.debug) {\n        console.info('Unshared: ' + el);\n      }\n    } else {\n      // Pretend to want to share this object, acquire a new shareObj, then use\n      // its ID to locate and kill the existing shareObj that's already shared.\n      var result = null;\n      // Ask every registered handler if it knows what to do with this object.\n      for (var j = 0; j < mobwrite.shareHandlers.length && !result; j++) {\n        result = mobwrite.shareHandlers[j].call(mobwrite, el);\n      }\n      if (result && result.file) {\n        if (mobwrite.shared[result.file]) {\n          delete mobwrite.shared[result.file];\n          if (mobwrite.debug) {\n            console.info('Unshared: ' + el);\n          }\n        } else {\n          if (mobwrite.debug) {\n            console.warn('Ignoring ' + el + '. Not currently shared.');\n          }\n        }\n      } else {\n        if (mobwrite.debug) {\n          console.warn('Unshare: Unknown widget type: ' + el + '.');\n        }\n      }\n    }\n  }\n};\n"
  },
  {
    "path": "static/code/objectPanel.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Integrated Development Environment for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nCode.ObjectPanel = {};\n\n/**\n * List of parts (passed in by the URL hash).\n * @type {?Array<!Object>}\n */\nCode.ObjectPanel.parts = null;\n\n/**\n * DOM node containing the list of properties.\n * @type {?Element}\n */\nCode.ObjectPanel.tableBody = null;\n\n/**\n * Structured data from Code City.\n * @type {?Object}\n */\nCode.ObjectPanel.data = null;\n\n/**\n * Page has loaded, initialize the panel.  Called by Code City with data.\n */\nCode.ObjectPanel.init = function() {\n  Code.ObjectPanel.tableBody = document.getElementById('objectTableBody');\n  // Clear the '...'\n  Code.ObjectPanel.tableBody.innerHTML = '';\n  var data = Code.ObjectPanel.data;\n  if (!data) {\n    // Server error.  Should not happen.\n    var title = document.getElementById('objectTitle');\n    title.className = 'objectFailTitle';\n    var fail = document.getElementById('objectFail');\n    fail.style.display = 'table-row';\n    return;\n  }\n  if (data.roots) {\n    // Print all root objects.\n    for (var root of data.roots) {\n      var part = {type: 'id', value: root.name};\n      Code.ObjectPanel.addLink(part, root.type, false);\n    }\n  }\n  if (data.properties) {\n    Code.ObjectPanel.filterShadowed(data.properties);\n    // Print all properties of this object.\n    for (var i = 0; i < data.properties.length; i++) {\n      var propList = data.properties[i];\n      propList.sort(Code.ObjectPanel.caseInsensitiveComp_);\n      for (var j = 0; j < propList.length; j++) {\n        var part = {type: 'id', value: propList[j].name};\n        Code.ObjectPanel.addLink(part, propList[j].type, i && !j);\n      }\n    }\n  }\n  if (data.keywords) {\n    var first = true;\n    for (var keyword of data.keywords) {\n      var part = {type: 'keyword', value: keyword};\n      Code.ObjectPanel.addLink(part, 'object', first);\n      first = false;\n    }\n  }\n\n  // Position the type symbols, and monitor for layout changes.\n  Code.ObjectPanel.positionTypes();\n  window.addEventListener('scroll', Code.ObjectPanel.positionTypes, false);\n  window.addEventListener('resize', Code.ObjectPanel.positionTypes, false);\n\n  // Highlight current item, and monitor for path changes.\n  Code.ObjectPanel.highlight();\n  window.addEventListener('message', Code.ObjectPanel.highlight, false);\n};\n\n/**\n * Create the DOM elements to add one property link to the list.\n * @param {!Object} part Single selector part.\n * @param {string} type Type of the property value.\n * @param {boolean} section Flag indicating a new section.\n */\nCode.ObjectPanel.addLink = function(part, type, section) {\n  var newParts = Code.ObjectPanel.parts.concat(part);\n  var selector = Code.Common.partsToSelector(newParts);\n  var a = document.createElement('a');\n  var query = encodeURIComponent(selector).replace(/%24/g, '$');\n  a.href = './?' + query;\n  a.target = '_blank';\n  a.setAttribute('data-link', JSON.stringify(part));\n  a.addEventListener('click', Code.ObjectPanel.click);\n  var text = document.createTextNode(Code.Common.partsToSelector([part]));\n  a.appendChild(text);\n  var td = document.createElement('td');\n  if (section) {\n    td.className = 'section';\n  }\n  var typeSymbol = Code.ObjectPanel.TYPES[type];\n  if (typeSymbol) {\n    var div = document.createElement('div');\n    div.className = 'objectType';\n    div.appendChild(document.createTextNode(typeSymbol));\n    div.title = type;\n    td.appendChild(div);\n  }\n  td.appendChild(a);\n  var tr = document.createElement('tr');\n  tr.appendChild(td);\n  Code.ObjectPanel.tableBody.appendChild(tr);\n};\n\n/**\n * Symbols to print next to properties.\n */\nCode.ObjectPanel.TYPES = {\n  'array': '[]',\n  'boolean': '⏼',\n  'function': '𝑓',\n  'null': '␀',\n  'number': '#',\n  'object': '{}',\n  'string': '”',\n  'symbol': '☆',\n  'verb': '𝑣𝑓'\n};\n\n/**\n * When scrollbar is moved or size changes reposition the floating types.\n */\nCode.ObjectPanel.positionTypes = function() {\n  var left = (document.body.clientWidth + window.scrollX - 18) + 'px';\n  var types = document.getElementsByClassName('objectType');\n  for (var t of types) {\n    t.style.left = left;\n  }\n};\n\n/**\n * When a property is clicked, trigger an update.\n * @param {!Event} e Click event.\n */\nCode.ObjectPanel.click = function(e) {\n  if (e.metaKey || e.ctrlKey) {\n    return;\n  }\n  var part = JSON.parse(e.currentTarget.getAttribute('data-link'));\n  var newParts = Code.ObjectPanel.parts.concat(part);\n  var selector = Code.Common.partsToSelector(newParts);\n  // Store the new selector in sessionStorage for all frames to see.\n  sessionStorage.setItem(Code.Common.SELECTOR, selector);\n  // Alert the top \"/code\" frameset that there's been a selector change.\n  window.parent.parent.postMessage('ping', '*');\n  // Don't navigate to this link.\n  e.preventDefault();\n};\n\n/**\n * Currently selected property, or null if none.\n * @type {?Element}\n */\nCode.ObjectPanel.highlighted = null;\n\n/**\n * Highlight the currently selected property (if any).\n * The current selection is based on a value in sessionStorage.\n */\nCode.ObjectPanel.highlight = function() {\n  var selector = sessionStorage.getItem(Code.Common.SELECTOR);\n  var parts = Code.Common.selectorToParts(selector);\n  var part = parts ? parts[Code.ObjectPanel.parts.length] : null;\n  var jsonPart = JSON.stringify(part);\n  var newHighlighted = null;\n  for (var tr of Code.ObjectPanel.tableBody.childNodes) {\n    var td = tr.firstChild;\n    var link = td.lastChild;  // There might be an objectType div first.\n    if (link.getAttribute('data-link') === jsonPart) {\n      newHighlighted = td;\n    }\n  }\n  if (newHighlighted !== Code.ObjectPanel.highlighted) {\n    if (Code.ObjectPanel.highlighted) {\n      Code.ObjectPanel.highlighted.classList.remove('highlighted');\n    }\n    if (newHighlighted) {\n      newHighlighted.classList.add('highlighted');\n      if (newHighlighted.scrollIntoView) {\n        newHighlighted.scrollIntoView({block: 'nearest', inline: 'nearest'});\n      }\n    }\n    Code.ObjectPanel.highlighted = newHighlighted;\n  }\n};\n\n/**\n * Remove any properties that are shadowed by objects higher on the inheritance\n * chain.\n * @param {Array<!Array<!Object>>} data Property names from Code City.\n */\nCode.ObjectPanel.filterShadowed = function(data) {\n  if (!data || data.length < 2) return;\n  var seen = Object.create(null);\n  for (var datum of data) {\n    var cursorInsert = 0;\n    var cursorRead = 0;\n    while (cursorRead < datum.length) {\n      var prop = datum[cursorRead++];\n      if (!seen[prop.name]) {\n        seen[prop.name] = true;\n        datum[cursorInsert++] = prop;\n      }\n    }\n    datum.length = cursorInsert;\n  }\n};\n\n/**\n * Comparison function to sort named objects A-Z without regard to case.\n * @param {!Object} a One named object.\n * @param {!Object} b Another named object.\n * @return {number} -1/0/1 comparator value.\n * @private\n */\nCode.ObjectPanel.caseInsensitiveComp_ = function(a, b) {\n  return Code.Common.caseInsensitiveComp(a.name, b.name);\n};\n\nif (!window.TEST) {\n  (function() {\n    // Fill in the object name.\n    var query = decodeURIComponent(location.search.substring(1));\n    Code.ObjectPanel.parts = Code.Common.selectorToParts(query);\n    var div = document.getElementById('objectTitle');\n    var lastPart = Code.ObjectPanel.parts[Code.ObjectPanel.parts.length - 1];\n    var name;\n    if (!lastPart) {\n      name = 'Globals';\n    } else if (Code.ObjectPanel.parts.length === 1) {\n      // Render as 'foo' or '[42]' or '[\"???\"]' or '{xyz}'.\n      name = Code.Common.partsToSelector([lastPart]);\n    } else {\n      // Render as '.foo' or '[42]' or '[\"???\"]' or '{xyz}'.\n      var mockParts = [{type: 'id', value: 'X'}, lastPart];\n      name = Code.Common.partsToSelector(mockParts).substring(1);\n    }\n    div.innerHTML = '';\n    div.appendChild(document.createTextNode(name));\n  })();\n\n  window.addEventListener('load', Code.ObjectPanel.init);\n}\n"
  },
  {
    "path": "static/code/style.css",
    "content": "body {\n  background: #fff;\n  color: #444;\n  font-family: \"Roboto Mono\", monospace;\n  font-size: 11pt;\n}\n\ninput,\ntextarea {\n  font-family: \"Roboto Mono\", monospace;\n  font-size: 11pt;\n}\n\n#input {\n  box-sizing: border-box;\n  margin-left: -2px;\n  width: 100%;\n}\n\n#input.invalid {\n  color: red;\n}\n\n#autocompleteMenu {\n  background: #fff;\n  border-color: #ccc #666 #666 #ccc;\n  border-style: solid;\n  border-width: 1px;\n  display: none;\n  max-width: 20em;\n  overflow-y: auto;\n  padding: 4px 0;\n  position: absolute;\n  z-index: 1;\n}\n\n#autocompleteMenuScroll {\n}\n\n#autocompleteMenuScroll>div {\n  cursor: default;\n  overflow-x: hidden;\n  padding: 0 1em;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n#autocompleteMenuScroll>div.selected {\n  background-color: #def;\n}\n\n#panels {\n  bottom: 5px;\n  left: 0;\n  overflow-x: auto;\n  overflow-y: hidden;\n  position: absolute;\n  right: 0;\n  top: 42px;\n  width: 100%;\n}\n\n#panelsScroll {\n  height: 100%;\n  padding-left: 5px;\n  white-space: nowrap;\n}\n\n#panelsScroll>iframe {\n  border: 2px solid #444;\n  border-radius: 2px;\n  box-sizing: border-box;\n  height: 100%;\n  margin: 0 5px 0 0;\n  padding: 0;\n  width: 300px;\n}\n\n#panelsScroll>iframe:last-of-type {\n  width: 500px;\n}\n\n#objectPanel {\n  margin: 0;\n}\n\n#objectFail {\n  display: none;\n}\n\n#objectFail>tr>td {\n  padding: 8px;\n}\n\n.objectFailTitle {\n  background-color: #d00;\n  color: #fff;\n}\n\n#objectPanel {\n  margin: 0;\n}\n\n#objectTitle {\n  border-bottom: 2px solid #444;\n  padding: 8px;\n}\n\n#objectTable {\n  border-collapse: collapse;\n  width: 100%;\n}\n\n#objectTableBody>tr>td {\n  padding: 0 2ex 0 8px;\n}\n\n#objectTableBody>tr>td>a {\n  color: #444;\n  display: block;\n  text-decoration: none;\n}\n\n#objectTableBody>tr>td:hover {\n  background-color: #d6e9f8;\n}\n\n#objectTableBody>tr>td.highlighted {\n  background-color: #ccc;\n}\n\n#objectTableBody>tr>td.section {\n  border-top: 1px solid #444;\n}\n\n.objectType {\n  color: #888;\n  font-family: monospace;\n  font-size: medium;\n  padding-top: 2px;\n  position: absolute;\n  text-align: center;\n  width: 3ex;\n}\n\n.loading:after {\n  animation: ellipsis steps(5, end) 1000ms infinite;\n  content: \"...\";\n  display: inline-block;\n  overflow: hidden;\n  vertical-align: bottom;\n  width: 0;\n}\n\n@keyframes ellipsis {\n  to {\n    width: 3.2em;\n  }\n}\n\n#editorButtons {\n  float: right;\n  margin-right: 3px;\n}\n\n#editorHeader {\n  margin-top: 5px;\n  overflow: hidden;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n}\n\n#editorTabs {\n  font-family: \"Arial\", \"Helvetica\", sans-serif;\n  font-size: 11px;\n  margin-top: -2px;\n}\n\n#editorTabs>.spacer {\n  border-bottom: 1px solid rgba(0,0,0,.1);\n  padding: 4px 5px;\n}\n\n#editorTabs>.jfk-button {\n  border-bottom-color: #f1f1f1;\n  border-bottom-left-radius: 0;\n  border-bottom-right-radius: 0;\n  height: auto;\n  line-height: normal;\n  margin-right: 0;\n  padding-bottom: 4px;\n  padding-top: 4px;\n}\n\n#editorTabs.disabled>.jfk-button {\n  color: #ccc;\n}\n\n#editorTabs>.highlighted {\n  background-color: #ccc;\n  background-image: none;\n}\n\n#editorContainers>div {\n  display: none;\n}\n\n#editorDialog,\n#editorDialogBox,\n#editorConfirmBox,\n#editorShareBox {\n  display: none;\n}\n\n#editorDialogMask,\n#editorSavingMask {\n  background-color: #000;\n  bottom: 0;\n  left: 0;\n  opacity: 0;\n  position: absolute;\n  right: 0;\n  top: 0;\n  transition-property: opacity;\n  z-index: 998;\n}\n\n#editorSavingMask {\n  cursor: wait;\n  display: none;\n  transition-duration: 1s;\n}\n\n#editorDialogBox {\n  background-color: #fff;\n  border: 2px solid #444;\n  border-radius: 2px;\n  border-top: none;\n  left: 0;\n  margin: 0 auto;\n  padding: 1em;\n  position: absolute;\n  right: 0;\n  text-align: center;\n  top: -120px;\n  transition-property: top;\n  width: 20em;\n  z-index: 999;\n}\n\n#editorConfirmDiscard {\n  float: left;\n  margin-left: 25px;\n}\n\n#editorConfirmCancel {\n  float: right;\n}\n\n#editorConfirmSave,\n#editorShareOk {\n  float: right;\n  margin-right: 25px;\n}\n\n#editorShareBox.disabled {\n  color: #ccc;\n}\n\n#editorShareAddress {\n  width: 18em;\n}\n\n.CodeMirror {\n  border: 1px solid #ddd;\n}\n"
  },
  {
    "path": "static/code/svg.css",
    "content": "body {\n  margin: 0;\n  padding: 0;\n  overflow: hidden;\n}\n\n#editorContainer {\n  position: absolute;\n}\n\n#toolbox {\n  padding-left: 2px;\n}\n\n#svgroot {\n  border: 1px solid #ccc;\n  box-sizing: border-box;\n  overflow: hidden;\n}\n\n#canvasBackground {\n  display: none;\n}\n\n#toolboxColumn1 {\n  left: 3px;\n  position: absolute;\n  top: 0;\n}\n\n#toolboxColumn2 {\n  left: 40px;\n  position: absolute;\n  top: 0;\n}\n\n#toolbox button {\n  background: #eee;\n  border-radius: 3px;\n  box-shadow: inset 1px 1px 2px white, 1px 1px 1px rgba(0,0,0,0.3);\n  margin: 4px;\n  padding: 1px;\n  display: block;\n}\n\n#toolbox button:hover {\n  background: #d6e9f8;\n}\n\n#toolbox button.selected {\n  background: #ccc;\n  box-shadow: inset 1px 1px 2px rgba(0,0,0,0.4), 1px 1px 0 #fff;\n}\n\n#toolbox button:focus {\n  outline: 0;\n}\n\n#menu {\n  background: #fff;\n  border-color: #ccc #666 #666 #ccc;\n  border-radius: 4px;\n  border-style: solid;\n  border-width: 1px;\n  cursor: default;\n  display: none;\n  font: normal 13px Arial, sans-serif;\n  margin: 0;\n  max-height: 100%;\n  outline: none;\n  padding: 4px 0;\n  position: absolute;\n  user-select: none;\n  z-index: 100;\n}\n\n.menuitem {\n  color: #444;\n  margin: 0;\n  padding: 4px 1em;\n  white-space: nowrap;\n}\n\n.menuitem:hover:not(.menuItemDisabled) {\n  background-color: #d6e9f8;\n  border-color: #d6e9f8;\n  border-style: dotted;\n  border-width: 1px 0;\n  padding-bottom: 3px;\n  padding-top: 3px;\n}\n\n.menuItemDisabled {\n  color: #ccc;\n}\n\n.menudiv {\n  border-top: 1px solid #ccc;\n  margin-top: 4px;\n  padding-top: 4px;\n}\n"
  },
  {
    "path": "static/code/svg.js",
    "content": "/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview SVG Editor using SvgCanvas from SVG-Edit.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nimport Canvas from './SVG-Edit/svgcanvas.js';\n\nvar svgEditor = {};\n// Export namespace variable to window (would normally happen automatically,\n// but this file is being loaded as a module).\n// Used to for the parent frame to communicate with us.\nwindow.svgEditor = svgEditor;\n\nsvgEditor.init = function() {\n  var container = document.getElementById('editorContainer');\n  var config = {\n    initFill: {color: 'FFFFFF', opacity: 1},\n    initStroke: {color: '000000', opacity: 1, width: 1},\n    text: {stroke_width: 0, font_size: 24, font_family: 'serif'},\n    initOpacity: 1,\n    imgPath: 'SVG-Edit/images/',\n    baseUnit: 'px',\n  };\n\n  svgEditor.canvas = new Canvas(container, config);\n\n  // Check to see if the parent window left us an initial source to render.\n  var source = window.initialSource;\n  if (source !== undefined) {\n    svgEditor.setString(source);\n    delete window.initialSource;\n  }\n  svgEditor.resize();\n\n  // Update the toolbox whenever a button is clicked.\n  // Don't wait for up to a quarter second until the next scheduled call.\n  // Also force a heavier update to catch changes such as open-close path.\n  var update = svgEditor.updateToolbox.bind(svgEditor, true);\n  for (var button of document.querySelectorAll('#toolbox button')) {\n    button.addEventListener('click', update, false);\n  }\n\n  document.addEventListener('keydown', svgEditor.keypress);\n  document.addEventListener('contextmenu', svgEditor.openMenu, false);\n  document.addEventListener('mousedown', svgEditor.mousedown, false);\n  document.getElementById('menu').addEventListener('click', svgEditor.menuClick);\n  // Don't undo beyond initialization.\n  svgEditor.canvas.undoMgr.resetUndoStack();\n};\n\n/**\n * Resize and reposition the SVG canvas when the window has changed shape.\n * Zoom so that a 100 unit tall image fills the screen.\n */\nsvgEditor.resize = function() {\n  var top = 0;\n  var left = 80;\n  var height = window.innerHeight;\n  var width = window.innerWidth - left;\n  var container = document.getElementById('editorContainer');\n  container.style.top = top + 'px';\n  container.style.left = left + 'px';\n\n  // Code City sprites are 100 units tall.\n  var FIXED_HEIGHT = 100;\n  var zoom = height / FIXED_HEIGHT;\n  svgEditor.canvas.setZoom(zoom);\n  svgEditor.canvas.setResolution(width / height * FIXED_HEIGHT, FIXED_HEIGHT);\n  svgEditor.canvas.updateCanvas(width, height);\n  // Recenter the origin to be the middle of the screen.\n  svgEditor.canvas.getRootElem().setAttribute('viewBox',\n      (-width / 2) + ' 0 ' + width + ' ' + height);\n};\n\n/**\n * Handle mouse down actions.\n */\nsvgEditor.mousedown = function(e) {\n  // Control-clicking on Mac OS X is treated as a right-click.\n  // WebKit on Mac OS X fails to change button to 2 (but Gecko does).\n  if (e.ctrlKey || e.button === 2) {\n    svgEditor.openMenu(e);\n  } else if (!document.getElementById('menu').contains(e.target)) {\n    svgEditor.closeMenu();\n  }\n};\n\n/**\n * Handle keyboard commands.\n */\nsvgEditor.keypress = function(e) {\n  if (e.key === 'Delete' || e.key === 'Backspace') {\n    svgEditor.delete();\n    e.preventDefault();\n  } else if (e.ctrlKey || e.metaKey) {\n    if (e.key === 'z') {\n      if (e.shiftKey) {\n        svgEditor.redo();\n      } else {\n        svgEditor.undo();\n      }\n      e.preventDefault();\n    } else if (e.key === 'x') {\n      svgEditor.cut();\n      e.preventDefault();\n    } else if (e.key === 'c') {\n      svgEditor.copy();\n      e.preventDefault();\n    } else if (e.key === 'v') {\n      svgEditor.paste();\n      e.preventDefault();\n    }\n  }\n};\n\n/**\n * Redo one action.\n */\nsvgEditor.redo = function() {\n  var undoMgr = svgEditor.canvas.undoMgr;\n  if (undoMgr.getRedoStackSize() > 0) {\n    undoMgr.redo();\n  }\n};\n\n/**\n * Undo one action.\n */\nsvgEditor.undo = function() {\n  var undoMgr = svgEditor.canvas.undoMgr;\n  if (undoMgr.getUndoStackSize() > 0) {\n    undoMgr.undo();\n  }\n};\n\n/**\n * Cut selected element(s).\n */\nsvgEditor.cut = function() {\n  svgEditor.copy();\n  svgEditor.canvas.deleteSelectedElements();\n};\n\n/**\n * Copy selected element(s).\n */\nsvgEditor.copy = function() {\n  svgEditor.canvas.copySelectedElements();\n};\n\n/**\n * Delete selected element(s).\n */\nsvgEditor.delete = function() {\n  svgEditor.canvas.deleteSelectedElements();\n};\n\n/**\n * Paste clipboard to middle of editor.\n */\nsvgEditor.paste = function() {\n  var svgCanvas = svgEditor.canvas;\n  var workarea = document.getElementById('editorContainer');\n  var zoom = svgCanvas.getZoom();\n  var y = (workarea.scrollTop + workarea.offsetHeight / 2) / zoom - svgCanvas.contentH;\n  svgCanvas.pasteElements('point', 0, -y);\n};\n\n/**\n * Inject SVG to the editor.\n * @param {string} xmlString SVG rendered as text.\n */\nsvgEditor.setString = function(xmlString) {\n  // SvgCanvas needs contents wrapped in a throw-away SVG node.\n  if (xmlString) {\n    var svgString = '<svg xmlns=\"http://www.w3.org/2000/svg\">' +\n        xmlString + '</svg>';\n    svgEditor.canvas.setSvgString(svgString);\n  } else {\n    svgEditor.canvas.clear();\n  }\n  svgEditor.resize();\n\n  // Preserve the original input, alongside its round-tripped output.\n  svgEditor.inputString = xmlString;\n  svgEditor.outputString = svgEditor.getString();\n};\n\nsvgEditor.inputString = undefined;\nsvgEditor.outputString = undefined;\n\n/**\n * Extract the SVG from the editor.\n * @return {string} SVG rendered as text.\n */\nsvgEditor.getString = function() {\n  var rootSvg = svgEditor.canvas.getContentElem();\n  // The user's image is the wrapped in the first group.\n  var contentSvg = rootSvg.querySelector('svg g').cloneNode(true);\n  // Remove the layer title.\n  var title = contentSvg.querySelector('g>title');\n  title.parentNode.removeChild(title);\n  // Walk the tree removing unused properties.\n  var tw = document.createTreeWalker(contentSvg, NodeFilter.SHOW_ELEMENT);\n  do {\n    var node = tw.currentNode;\n    node.removeAttribute('id');\n    node.removeAttribute('fill');\n    node.removeAttribute('stroke');\n  } while (tw.nextNode());\n\n  var source = svgEditor.canvas.svgToString(contentSvg, -1);\n  // Remove the wrapping <g>.\n  source = source.replace(/^\\s*<g[^>]*>\\s*/i, '');\n  source = source.replace(/\\s*<\\/g>\\s*$/i, '');\n\n  // If the output is the same as the original input's round-tripped value,\n  // then return the original input.\n  // Otherwise changes may be claimed when none were made by the user.\n  if (source === svgEditor.outputString) {\n    return svgEditor.inputString;\n  }\n  return source;\n};\n\n/**\n * Update the toolbox visualization in response to the editor state.\n * This function is called four times a second, and when a button is clicked.\n * @param {boolean=} force If true, force a redraw.\n */\nsvgEditor.updateToolbox = function(force) {\n  // Highlight the current mode button.\n  var mode = svgEditor.canvas.getMode();\n  if (force ||\n      (mode !== 'resize' && mode !== 'rotate' &&\n      mode !== svgEditor.updateToolbox.oldMode_)) {\n    var stylePathEdit = document.getElementById('mode-pathedit').style;\n    var styleSelect = document.getElementById('mode-select').style;\n    var styleNodeActions = document.getElementById('node-actions').style;\n    if (mode === 'pathedit') {\n      styleSelect.display = 'none';\n      stylePathEdit.display = 'block';\n      styleNodeActions.display = 'block';\n      // Show or hide the appropriate open/close path button.\n      var styleCloseAction = document.getElementById('close-action').style;\n      var styleOpenAction = document.getElementById('open-action').style;\n      if (svgEditor.canvas.pathActions.closed_subpath) {\n        styleCloseAction.display = 'none';\n        styleOpenAction.display = 'block';\n      } else {\n        styleOpenAction.display = 'none';\n        styleCloseAction.display = 'block';\n      }\n    } else {\n      stylePathEdit.display = 'none';\n      styleSelect.display = 'block';\n      styleNodeActions.display = 'none';\n    }\n    var button = document.getElementById('mode-' +\n                                         svgEditor.updateToolbox.oldMode_);\n    if (button) {\n      button.classList.remove('selected');\n    }\n    svgEditor.updateToolbox.oldMode_ = mode;\n    button = document.getElementById('mode-' + mode);\n    if (button) {\n      button.classList.add('selected');\n    }\n  }\n\n  // Show or hide action buttons that apply to one or more selected elements.\n  var selected = svgEditor.canvas.getSelectedElems();\n  if (selected.length !== svgEditor.updateToolbox.oldSelectedCount_) {\n    var actions = document.getElementById('selected-actions');\n    var singleActions = document.getElementById('selected-single-actions');\n    actions.style.display = selected.length > 0 ? 'block' : 'none';\n    singleActions.style.display = selected.length === 1 ? 'block' : 'none';\n    svgEditor.updateToolbox.oldSelectedCount_ = selected.length;\n    document.getElementById('menuCut').classList\n        .toggle('menuItemDisabled', selected.length === 0);\n    document.getElementById('menuCopy').classList\n        .toggle('menuItemDisabled', selected.length === 0);\n    document.getElementById('menuDelete').classList\n        .toggle('menuItemDisabled', selected.length === 0);\n  }\n  if (selected.length === 1) {\n    var element = selected[0];\n    document.getElementById('convertpath-action').style.display =\n        element.tagName === 'path' ? 'none' : 'block';\n\n    var fillStroke = svgEditor.getFillStroke(element);\n    var fill = fillStroke[0];\n    var stroke = fillStroke[1];\n\n    var fillRect = document.getElementById('fillRect');\n    var fillNoneStyle = document.getElementById('fillNone').style;\n    if (fill === 'fillNone') {\n      fillNoneStyle.display = 'inline';\n      fillRect.setAttribute('class', 'fillWhite');\n    } else {\n      fillNoneStyle.display = 'none';\n      fillRect.setAttribute('class', fill);\n    }\n\n    var strokeRect = document.getElementById('strokeRect');\n    if (stroke === 'strokeNone') {\n      strokeRect.setAttribute('stroke-width', '1');\n      strokeRect.setAttribute('stroke', '#d40000');\n      strokeRect.setAttribute('class', '');\n    } else {\n      strokeRect.setAttribute('stroke-width', '4');\n      strokeRect.setAttribute('stroke', '');\n      strokeRect.setAttribute('class', stroke);\n    }\n  }\n};\n\nsvgEditor.updateToolbox.oldMode_ = '';\nsvgEditor.updateToolbox.oldSelectedCount_ = NaN;\n\n/**\n * Find the fill and stroke for an element.\n * @param {!Element} element Element with style.\n * @return {!Array<string>} Array with normalized fill and stroke strings.\n */\nsvgEditor.getFillStroke = function(element) {\n  if (!element) throw new TypeError('Element not provided');\n  var classes = element.getAttribute('class') || '';\n  classes = classes.replace(/Gray/g, 'Grey');\n  var fill = classes.match(/\\b(fill(None|White|Black|Grey))\\b/);\n  fill = fill ? fill[1] : 'fillNone';\n  var stroke = classes.match(/\\b(stroke(None|White|Black|Grey))\\b/);\n  stroke = stroke ? stroke[1] : 'strokeBlack';\n  return [fill, stroke];\n};\n\n/**\n * Rotate the fill in the currently selected object between allowed options.\n */\nsvgEditor.changeFill = function() {\n  var element = svgEditor.canvas.getSelectedElems()[0];\n  var fill = svgEditor.getFillStroke(element)[0];\n  var fillOptions = ['fillNone', 'fillBlack', 'fillGrey', 'fillWhite'];\n  var fillIndex = Math.max(fillOptions.indexOf(fill), 0);\n  fillIndex++;\n  fillIndex %= fillOptions.length;\n  var classes = element.getAttribute('class') || '';\n  classes = classes.replace(/\\bfill\\w+\\b/g, '');\n  classes += ' ' + fillOptions[fillIndex];\n  classes = classes.replace(/\\s+/g, ' ').trim();\n  element.setAttribute('class', classes);\n};\n\n/**\n * Rotate the stroke in the currently selected object between allowed options.\n */\nsvgEditor.changeStroke = function() {\n  var element = svgEditor.canvas.getSelectedElems()[0];\n  var stroke = svgEditor.getFillStroke(element)[1];\n  var strokeOptions = ['strokeBlack', 'strokeGrey', 'strokeWhite', 'strokeNone'];\n  var strokeIndex = Math.max(strokeOptions.indexOf(stroke), 0);\n  strokeIndex++;\n  strokeIndex %= strokeOptions.length;\n  var classes = element.getAttribute('class') || '';\n  classes = classes.replace(/\\bstroke\\w+\\b/g, '');\n  classes += ' ' + strokeOptions[strokeIndex];\n  classes = classes.replace(/\\s+/g, ' ').trim();\n  element.setAttribute('class', classes);\n};\n\n/**\n * Open the context menu command menu at the mouse location.\n * @param {!Event} e Mouse event.\n */\nsvgEditor.openMenu = function(e) {\n  svgEditor.closeMenu();\n  var menu = document.getElementById('menu');\n  var pageHeight = window.innerHeight;\n  var pageWidth = window.innerWidth;\n  var top = e.y;\n  var left = e.x;\n  menu.style.display = 'block';\n  // Don't go off the bottom of the page (hug the bottom).\n  if (top + menu.offsetHeight > pageHeight) {\n    top = Math.max(pageHeight - menu.offsetHeight, 0);\n  }\n  // Don't go off the right of the page (flip menu).\n  if (left + menu.offsetWidth > pageWidth) {\n    left = Math.max(left - menu.offsetWidth, 0);\n  }\n  menu.style.top = top + 'px';\n  menu.style.left = left + 'px';\n  // Don't open the system context menu.\n  e.preventDefault();\n};\n\n/**\n * If there is a menu open, close it.\n */\nsvgEditor.closeMenu = function() {\n  document.getElementById('menu').style.display = 'none';\n};\n\n/**\n * Handle mouse clicking on a context menu option.\n * @param {!Event} e Mouse event.\n */\nsvgEditor.menuClick = function(e) {\n  if (!e.target.classList.contains('menuItemDisabled')) {\n    switch (e.target.id) {\n      case 'menuCut':\n        svgEditor.cut();\n        break;\n      case 'menuCopy':\n        svgEditor.copy();\n        break;\n      case 'menuPaste':\n        svgEditor.paste();\n        break;\n      case 'menuDelete':\n        svgEditor.delete();\n        break;\n    }\n  }\n  svgEditor.closeMenu();\n};\n\nwindow.addEventListener('load', svgEditor.init);\nwindow.addEventListener('resize', svgEditor.resize);\nwindow.addEventListener('mousedown', window.focus);\nsetInterval(svgEditor.updateToolbox, 250);\n"
  },
  {
    "path": "static/code/tests/test.html",
    "content": "<html>\n  <head>\n    <title>Test harness for Code City: Code</title>\n\n    <script>\n      window.TEST = true;\n    </script>\n    <script src=\"../common.js\"></script>\n    <script src=\"../code.js\"></script>\n    <script src=\"../explorer.js\"></script>\n    <script src=\"../objectPanel.js\"></script>\n    <script src=\"../editor.js\"></script>\n    <script src=\"test.js\"></script>\n\n    <script>\n      // Counters for unit test results.\n      var test_good = 0;\n      var test_bad = 0;\n\n      // If expected and actual are the identical, print 'Ok', otherwise 'Fail!'\n      function assertEquals(expected, actual, msg) {\n        if (msg === undefined) {\n          // msg is optional.\n          msg = 'Expected: \\'' + expected + '\\' Actual: \\'' + actual + '\\'';\n        }\n        if (expected === actual) {\n          document.write('<div class=\"ok\">Ok</div>');\n          test_good++;\n          return true;\n        } else {\n          document.write('<div class=\"fail\">Fail!</div>');\n          msg = msg.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n          document.write('<code>' + msg + '</code><BR>');\n          test_bad++;\n          return false;\n        }\n      }\n\n      function assertTrue(msg, actual) {\n        return assertEquals(msg, true, actual);\n      }\n\n      function assertFalse(msg, actual) {\n        return assertEquals(msg, false, actual);\n      }\n\n      function runTests() {\n        // Find all 'test' functions.\n        var tests = Object.getOwnPropertyNames(window).filter(\n            function(name) {return /^test[A-Z]/.test(name)});\n        for (var x = 0; x < tests.length; x++) {\n          document.write('<h3>' + tests[x] + ':</h3>');\n          window[tests[x]]();\n        }\n      }\n    </script>\n\n    <style>\n      div.ok {\n        color: #090;\n      }\n      div.fail {\n        color: #900;\n        font-size: bigger;\n      }\n    </style>\n  </head>\n\n  <body>\n    <h1>Test harness for Code City: Code</h1>\n\n    <script>\n      var startTime = Date.now();\n      runTests();\n      var endTime = Date.now();\n      document.write('<h3>Done.</h3>');\n      document.write('<p>Tests passed: ' + test_good + '<br>Tests failed: ' + test_bad + '</p>');\n      document.write('<p>Total time: ' + (endTime - startTime) + ' ms</p>');\n    </script>\n  </body>\n</html>\n"
  },
  {
    "path": "static/code/tests/test.js",
    "content": "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Tests for Integrated Development Environment for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nfunction testCommonSelectorToParts() {\n  // Join a list of parts into a path selector.\n  assertEquals('[{\"type\":\"id\",\"value\":\"$\"},{\"type\":\"keyword\",\"value\":\"{proto}\"},{\"type\":\"id\",\"value\":\"foo\"}]', JSON.stringify(Code.Common.selectorToParts('${proto}.foo')));\n}\n\nfunction testCommonPartsToSelector() {\n  // Join a list of parts into a path selector.\n  assertEquals('${proto}.foo', Code.Common.partsToSelector([{type: 'id', value: '$'}, {type: 'keyword', value: '{proto}'}, {type: 'id', value: 'foo'}]));\n}\n\nfunction testCommonSelectorToReference() {\n  // No substitution.\n  assertEquals('$.foo', Code.Common.selectorToReference('$.foo'));\n  // Parent substitution.\n  assertEquals(\"$('${proto}.foo')\", Code.Common.selectorToReference('${proto}.foo'));\n}\n\nfunction testGetPrefix() {\n  // No string.\n  assertEquals('', Code.Explorer.getPrefix([]));\n  // One string.\n  assertEquals('foo', Code.Explorer.getPrefix(['foo']));\n  // No prefix.\n  assertEquals('', Code.Explorer.getPrefix(['foo', 'bar', 'baz']));\n  // Some prefix.\n  assertEquals('ba', Code.Explorer.getPrefix(['bar', 'baz']));\n  // Whole prefix.\n  assertEquals('foo', Code.Explorer.getPrefix(['foo', 'foot', 'food']));\n  // Case-sensitive.\n  assertEquals('foo', Code.Explorer.getPrefix(['foot', 'fooT']));\n}\n\nfunction testAutocompletePrefix() {\n  // No options.\n  assertEquals('{\"prefix\":\"foo\",\"terminal\":false}', JSON.stringify(Code.Explorer.autocompletePrefix([], 'foo')));\n  // One option.\n  assertEquals('{\"prefix\":\"FOOT\",\"terminal\":true}', JSON.stringify(Code.Explorer.autocompletePrefix(['FOOT'], 'foo')));\n  // No prefix, one option.\n  assertEquals('{\"prefix\":\"foot\",\"terminal\":true}', JSON.stringify(Code.Explorer.autocompletePrefix(['foot'], '')));\n  // No prefix, two options.\n  assertEquals('{\"prefix\":\"foo\",\"terminal\":false}', JSON.stringify(Code.Explorer.autocompletePrefix(['food', 'foot'], '')));\n  // Case-sensitive prefix.\n  assertEquals('{\"prefix\":\"foo\",\"terminal\":false}', JSON.stringify(Code.Explorer.autocompletePrefix(['foot', 'fool', 'FORK'], 'f')));\n  // Case-sensitive prefix.\n  assertEquals('{\"prefix\":\"FORK\",\"terminal\":true}', JSON.stringify(Code.Explorer.autocompletePrefix(['foot', 'fool', 'FORK'], 'F')));\n  // Case-insensitive prefix.\n  assertEquals('{\"prefix\":\"foo\",\"terminal\":false}', JSON.stringify(Code.Explorer.autocompletePrefix(['foot', 'fool'], 'F')));\n  // Case-insensitive no match.\n  assertEquals('{\"prefix\":\"Fo\",\"terminal\":false}', JSON.stringify(Code.Explorer.autocompletePrefix(['FOOT', 'fool'], 'Fo')));\n}\n"
  },
  {
    "path": "static/connect/common.css",
    "content": "body {\n  color: #444;\n}\n\na {\n  color: #00e;\n}\n\na:hover {\n  color: #d00;\n}\n\na.command {\n  cursor: pointer;\n  text-decoration: underline dotted;\n}\n\nbody.disconnected a.command,\nbody.disconnected a.command:hover {\n  cursor: not-allowed;\n  color: #444;\n  text-decoration-color: #444;\n}\n\n#scrollDiv {\n  bottom: 0;\n  left: 0;\n  max-height: 100%;\n  overflow-y: auto;\n  position: absolute;\n  right: 0;\n}\n\nsvg.menuIcon {\n  cursor: pointer;\n  display: inline;\n  fill: #444;\n  height: 10px;\n  stroke: #fff;\n  vertical-align: top;\n  width: 11px;\n}\n\nbody.disconnected svg.menuIcon {\n  cursor: not-allowed;\n  fill: #ccc;\n}\n\nsvg.menuIcon:hover {\n  fill: #d00;\n}\n\nbody.disconnected svg.menuIcon:hover {\n  fill: #aaa;\n}\n\n#menu {\n  background: #fff;\n  border-color: #ccc #666 #666 #ccc;\n  border-radius: 4px;\n  border-style: solid;\n  border-width: 1px;\n  cursor: default;\n  font: normal 13px Arial, sans-serif;\n  margin: 0;\n  max-height: 100%;\n  outline: none;\n  padding: 4px 0;\n  position: absolute;\n  z-index: 100;\n}\n\n.menuitem {\n  color: #444;\n  margin: 0;\n  padding: 4px 1em;\n  white-space: nowrap;\n}\n\nbody.disconnected .menuitem {\n  color: #ccc;\n  cursor: not-allowed;\n}\n\n.menuitem:hover {\n  background-color: #d6e9f8;\n  border-color: #d6e9f8;\n  border-style: dotted;\n  border-width: 1px 0;\n  padding-bottom: 3px;\n  padding-top: 3px;\n}\n"
  },
  {
    "path": "static/connect/common.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Functions common across log/world frames of Code City's client.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nvar CCC = {};\nCCC.Common = {};\n\n\n/**\n * Namespace for SVG elements.\n * @constant\n */\nCCC.Common.NS = 'http://www.w3.org/2000/svg';\n\n/**\n * Is the client currently connected to the server?\n */\nCCC.Common.isConnected = false;\n\n/**\n * Enum for message types to the log/world frames.\n * Should be identical to CCC.MessageTypes\n * @enum {string}\n */\nCCC.Common.MessageTypes = {\n  // Messages that may be paused:\n  COMMAND: 'command',  // User-generated command echoed.\n  MEMO: 'memo',  // Block of text from Code City.\n  CONNECT_MSG: 'connect msg',  // User-visible connection message.\n  DISCONNECT_MSG: 'disconnect msg',  // User-visible disconnection message.\n  // Messages that may be sent while paused:\n  CONNECTION: 'connection',  // Signal change of connection state.\n  CLEAR: 'clear',  // Signal tho clear history.\n  BLUR: 'blur'  // Signal to close pop-up menus.\n};\n\n/**\n * Initialization code called on startup.\n */\nCCC.Common.init = function() {\n  CCC.Common.parser = new DOMParser();\n  CCC.Common.serializer = new XMLSerializer();\n  document.body.addEventListener('click', CCC.Common.closeMenu, true);\n  document.body.addEventListener('keydown', CCC.Common.keyDown, true);\n  document.body.addEventListener('keypress', CCC.Common.keyPress, true);\n\n  // Report back to the parent frame that we're fully loaded and ready to go.\n  parent.postMessage('init', location.origin);\n};\n\n/**\n * Verify that a received message is from our parent frame.\n * @param {!Event} e Incoming message event.\n * @return {*} Value from message.\n */\nCCC.Common.verifyMessage = function(e) {\n  var origin = e.origin || e.originalEvent.origin;\n  if (origin !== location.origin) {\n    throw new Error('Message received by frame from unknown origin: ' + origin);\n  }\n  return e.data;\n};\n\n/**\n * Change the connection status between being connected or disconnected.\n * @param {boolean} newConnected New status.\n */\nCCC.Common.setConnected = function(newConnected) {\n  if (newConnected === CCC.Common.isConnected) {\n    return;  // No change.\n  }\n  CCC.Common.isConnected = newConnected;\n  // Add/remove a classname on body, so that links and menus can change style.\n  if (CCC.Common.isConnected) {\n    document.body.classList.remove('disconnected');\n  } else {\n    document.body.classList.add('disconnected');\n  }\n};\n\n\n/**\n * Create a command menu icon.  Attach the menu commands to the icon.\n * @param {!Array<string>|!Element} cmds Array of menu commands,\n *     or root DOM element describing the menu commands.\n * @return {SVGSVGElement} Root element of icon.\n */\nCCC.Common.newMenuIcon = function(cmds) {\n  if (cmds.querySelectorAll) {\n    // HTML frames provide commands as XML.\n    // Convert the command DOM into an array.\n    // <cmds><cmd>look Bob</cmd></cmds> -> ['look Bob']\n    var nodes = cmds.querySelectorAll('cmd');\n    cmds = [];\n    for (var i = 0; i < nodes.length; i++) {\n      cmds[i] = CCC.Common.innerText(nodes[i]);\n    }\n  }\n  if (!cmds.length) {\n    return null;\n  }\n  var svg = CCC.Common.createSvgElement('svg',\n      {'class': 'menuIcon', 'data-cmds': JSON.stringify(cmds)});\n  CCC.Common.createSvgElement('path', {'d': 'm 0.5,2.5 5,5 5,-5 z'}, svg);\n  return svg;\n};\n\n/**\n * Concatenate all the text element in a DOM tree.\n * <foo>123<bar>456</bar>789</foo> -> '123456789'\n * @param {!Element} node Root DOM element.\n * @return {string} Plain text.\n */\nCCC.Common.innerText = function(node) {\n  var text = '';\n  if (node.nodeType === Node.TEXT_NODE) {\n    text = node.data;\n  } else if (node.nodeType === Node.ELEMENT_NODE) {\n    for (var child of node.childNodes) {\n      text += CCC.Common.innerText(child);\n    }\n  }\n  return text;\n};\n\n/**\n * Open the command menu for the clicked menu icon.\n * @param {!Event} e Click event.\n * @this {!SVGSVGElement} Root element of icon.\n */\nCCC.Common.openMenu = function(e) {\n  CCC.Common.closeMenu();  // Should be already closed, but let's make sure.\n  var cmds = JSON.parse(this.getAttribute('data-cmds'));\n  var menu = document.createElement('div');\n  menu.id = 'menu';\n  for (var cmd of cmds) {\n    var menuItem = document.createElement('div');\n    menuItem.className = 'menuitem';\n    menuItem.appendChild(document.createTextNode(cmd));\n    menuItem.addEventListener('click', CCC.Common.commandFunction, false);\n    menu.appendChild(menuItem);\n  }\n  var scrollDiv = document.getElementById('scrollDiv');\n  var pageHeight = scrollDiv.scrollHeight;\n  var pageWidth = scrollDiv.scrollWidth;\n  scrollDiv.appendChild(menu);\n  var iconRect = this.getBoundingClientRect();\n  // Calculate preferred location of below and right of icon.\n  var top = iconRect.top + scrollDiv.scrollTop + iconRect.height -\n      scrollDiv.offsetTop;\n  var left = iconRect.left + scrollDiv.scrollLeft;\n  // Flip up if below page.\n  if (top + menu.offsetHeight > pageHeight) {\n    top -= menu.offsetHeight + iconRect.height;\n    // Don't go off the top of the page.\n    top = Math.max(top, 0);\n  }\n  // Don't go off the right of the page.\n  if (left + menu.offsetWidth > pageWidth) {\n    left = pageWidth - menu.offsetWidth;\n    // Don't go off the right of the page.\n    left = Math.max(left, 0);\n  }\n  menu.style.top = top + 'px';\n  menu.style.left = left + 'px';\n};\n\n/**\n * If there is a menu open, close it.\n */\nCCC.Common.closeMenu = function() {\n  var menu = document.getElementById('menu');\n  if (menu) {\n    menu.parentNode.removeChild(menu);\n    CCC.Common.parentFocus();\n  }\n};\n\n/**\n * When clicked, execute the printed command.\n * @this {!Element} Clicked element.\n */\nCCC.Common.commandFunction = function() {\n  var command = this.innerText;\n  // Menu commands should never be multi-line.\n  // This should never happen and be caught earlier.\n  // But if it does, fail here rather than be a security hole.\n  if (command.split(/[\\r\\n]/).length !== 1) {\n    throw new Error('Multi-line command: ' + command);\n  }\n  if (CCC.Common.isConnected) {\n    parent.postMessage({'commands': [command]}, location.origin);\n  }\n  CCC.Common.parentFocus();\n};\n\n/**\n * The user pressed a key with the focus in the world/log frame.\n * Move focus back to the parent frame and inject the keystroke into the\n * command area.\n * @param {!KeyboardEvent} e Keyboard down event.\n */\nCCC.Common.keyDown = function(e) {\n  if (e.key === 'Alt' || e.key === 'Control' || e.key === 'Meta') {\n    // Don't steal focus if the user is pressing a modifier key in preparation\n    // for a cut/copy operation.\n    return;\n  }\n  if (e.ctrlKey || e.altKey || e.metaKey) {\n    // Allow Chrome time to complete a copy before moving focus.\n    setTimeout(CCC.Common.parentFocus, 0);\n  } else {\n    CCC.Common.parentFocus(e);\n  }\n};\n\n/**\n * The user pressed a key with the focus in the world/log frame.\n * Move focus back to the parent frame and inject the keystroke into the\n * command area.\n * @param {!KeyboardEvent} e Keyboard press event.\n */\nCCC.Common.keyPress = function(e) {\n  // Allow Firefox time to complete a copy before moving focus.\n  setTimeout(CCC.Common.parentFocus, 0);\n};\n\n/**\n * Move focus back to the parent frame.  If specified, inject the keystroke\n * into the command area.\n * @param {KeyboardEvent} e Optional keyboard event.\n */\nCCC.Common.parentFocus = function(e) {\n  try {\n    var ct = parent.document.getElementById('commandTextarea');\n    ct.focus();\n    // Chrome won't type the character in the textarea after a focus change.\n    // For the easy case where the field is empty, just add the character.\n    // TODO: Handle cases where the field is not empty.\n    if (e && e.key.length === 1 && !ct.value.length) {\n      ct.value = e.key;\n      // Firefox will type the character a second time, prevent this.\n      e.preventDefault();\n    }\n  } catch (e) {\n    // Cross-frame is risky in some browsers.  Fallback method.\n    parent.focus();\n  }\n};\n\n/**\n * Helper method for creating SVG elements.\n * @param {string} name Element's tag name.\n * @param {!Object} attrs Dictionary of attribute names and values.\n * @param {!Element=} opt_parent Optional parent on which to append the element.\n * @return {!SVGElement} Newly created SVG element.\n */\nCCC.Common.createSvgElement = function(name, attrs, opt_parent) {\n  var el = document.createElementNS(CCC.Common.NS, name);\n  for (var key in attrs) {\n    el.setAttribute(key, attrs[key]);\n  }\n  if (opt_parent) {\n    opt_parent.appendChild(el);\n  }\n  return el;\n};\n\n/**\n * Given plain text, encode spaces and tabs such that HTML won't crush it.\n * Does not handle line breaks in any way.\n * @param {string} text Plain text.\n * @return {string} HTML with any runs of spaces encoded.\n */\nCCC.Common.escapeSpaces = function(text) {\n  return text.replace(/\\t/g, '\\u00A0 \\u00A0 \\u00A0 \\u00A0 ')\n      .replace(/  /g, '\\u00A0 ').replace(/  /g, '\\u00A0 ')\n      .replace(/^ /gm, '\\u00A0');\n};\n\n/**\n * Detect URLs in the provided document fragment and replace with links.\n * @param {!Element} el A DOM element to scan and modify.\n */\nCCC.Common.autoHyperlink = function(el) {\n  var isSvg = el.namespaceURI === CCC.Common.NS;\n  var children = el.childNodes;  // This is a live NodeList.\n  for (var i = children.length - 1, child; (child = children[i]); i--) {\n    if (child.nodeType !== Node.TEXT_NODE) {\n      CCC.Common.autoHyperlink(child);\n      continue;\n    }\n    var text = child.nodeValue;\n    var parts = text.split(CCC.Common.autoHyperlink.urlRegex);\n    if (parts.length <= 1) {  // No hyperlinks found.\n      continue;\n    }\n    for (var j = 0; j < parts.length; j++) {\n      var part = parts[j];\n      var m = part.match(CCC.Common.autoHyperlink.urlRegex);\n      // Look up the previous character (if it exists), to weed out: $.www.bar\n      var prevChar = j ? parts[j - 1].substr(-1) : '';\n      if (prevChar !== '.' && m && m[0] === part) {\n        // This part is a URL.\n        var n = part.match(/[.,!)\\]?']+$/);\n        if (n) {\n          // Move any trailing punctuation out of URL.\n          part = part.substring(0, part.length - n[0].length);\n          parts[j + 1] = n[0] + (parts[j + 1] || '');\n        }\n        var href = part;\n        if (!/^https?:\\/\\//.test(href)) {\n          href = 'http://' + href;\n        }\n        var link = isSvg ? document.createElementNS(CCC.Common.NS, 'a') :\n            document.createElement('a');\n        link.setAttribute('href', href);\n        link.setAttribute('target', '_blank');\n        link.setAttribute('rel', 'noopener noreferrer');\n        link.appendChild(document.createTextNode(part));\n        newNode = link;\n      } else {\n        // This part is plain text.\n        var newNode = document.createTextNode(part);\n      }\n      el.insertBefore(newNode, child);\n    }\n    el.removeChild(child);\n  }\n};\n\nCCC.Common.autoHyperlink.urlRegex =\n    /(\\b(?:https?:\\/\\/|www\\.)[-\\w.~:\\/?#\\[\\]@!$&'()*+,;=%]+)/i;\n\n// Set background colour to differentiate server vs local copy.\nif (location.hostname === 'localhost') {\n  window.addEventListener('load', function() {\n    document.body.style.backgroundColor = '#ffe';\n  });\n}\n"
  },
  {
    "path": "static/connect/connect.css",
    "content": "html {\n  height: 100%;\n}\n\nbody {\n  color: #444;\n  background-color: #fff;\n  border-left: 2px dashed #fff;\n  border-right: 2px dashed #fff;\n  font-family: 'Roboto Mono', monospace;\n  height: 100%;\n  margin: 0;\n  overflow: hidden;\n  padding: 0;\n  transition: border 0.5s;\n}\n\nbody.paused {\n  border-left: 2px dashed #d00;\n  border-right: 2px dashed #d00;\n}\n\n#worldFrame, #logFrame {\n  position: absolute;\n  width: 100%;\n  z-index: -1;\n  border: none;\n}\n\n#mainTable {\n  height: 100%;\n  width: 100%;\n  background: #fff;\n}\n\ntfoot {\n  height: 1%;\n}\n\n#displayCell {\n  text-align: center;\n}\n\n#commandTextarea {\n  color: #000;\n  box-sizing: border-box;\n  background-color: #f8f8f8;\n  font-size: 12pt;\n  height: 42pt;\n  margin-top: 2px;\n  resize: none;\n  width: 100%;\n}\n\n#optionsDiv {\n  background: rgba(255,255,255, 0.8);\n  margin-right: 25px; /* Leave room for the scrollbar. */\n  position: fixed;\n  right: 0;\n  top: 0;\n  z-index: 9;  /* On top of the iframes. */\n  padding: 0 2px 2px 2px;\n}\n\n.icon {\n  height: 8px;\n  width: 8px;\n  fill: #444;\n}\n\n.jfk-button {\n  border-top-left-radius: 0;\n  border-top-right-radius: 0;\n  border-top: none !important;\n}\n\n#playIcon {\n  fill: #fff;\n}\n\n#worldButton {\n  border-bottom-right-radius: 0;\n  margin-right: 0;\n}\n\n#logButton {\n  border-bottom-left-radius: 0;\n  margin-left: -1px;\n}\n\n#clearButton {\n  margin-right: 0;  /* This is the right-most button. */\n}\n"
  },
  {
    "path": "static/connect/connect.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Code City's client.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nvar CCC = {};\n\n/**\n * Smallest interval in milliseconds between pings.\n * @constant\n */\nCCC.MIN_PING_INTERVAL = 1000;\n\n/**\n * Largest interval in milliseconds between pings.\n * @constant\n */\nCCC.MAX_PING_INTERVAL = 4000;\n\n/**\n * Maximum number of commands saved in history.\n * @constant\n */\nCCC.MAX_HISTORY_SIZE = 1000;\n\n/**\n * Location to send pings to.\n * @constant\n */\nCCC.PING_URL = 'ping';\n\n// Properties below this point are not configurable.\n\n/**\n * All the commands the user has sent.\n */\nCCC.commandHistory = [];\n\n/**\n * When browsing the command history, save the current command here.\n */\nCCC.commandTemp = '';\n\n/**\n * Where in the command history are we browsing?\n */\nCCC.commandHistoryPointer = -1;\n\n/**\n * When was the last time we saw the user?\n * @type {number}\n */\nCCC.lastActiveTime = Date.now();\n\n/**\n * Number of lines we think the user has not seen.\n */\nCCC.unreadLines = 0;\n\n/**\n * The index number of the most recent command added to the command buffer.\n */\nCCC.commandNum = 0;\n\n/**\n * Buffer of commands being sent, awaiting acks from server.\n */\nCCC.commandBuffer = [];\n\n/**\n * Bit to switch off local echo when typing passwords.\n */\nCCC.localEcho = true;\n\n/**\n * The index number of the most recent memo received from the server.\n */\nCCC.memoNum = 0;\n\n/**\n * Number of calls to countdown required before launching.\n */\nCCC.countdownValue = 3;\n\n/**\n * XMLHttpRequest currently in flight, or null.\n * @type {XMLHttpRequest}\n */\nCCC.xhrObject = null;\n\n/**\n * Current length of time between pings.\n */\nCCC.pingInterval = CCC.MIN_PING_INTERVAL;\n\n/**\n * Process ID of next ping to the server.\n */\nCCC.nextPingPid = -1;\n\n/**\n * Flag for only acknowledging new memos after a new memo has arrived.\n * Saves bandwidth.\n */\nCCC.ackMemoNextPing = true;\n\n/**\n * Buffer to accumulate incoming messages when paused.\n */\nCCC.pauseBuffer = null;\n\n/**\n * Number of consecutive ping errors that have occurred.\n */\nCCC.xhrErrorCounter = 0;\n\n/**\n * Sequence of possible connection states.\n * @enum {number}\n */\nCCC.ConnectionStates = {\n  NEVER_CONNECTED: 0,\n  CONNECTED: 1,\n  DISCONNECTED: 2\n};\n\n/**\n * Is the client currently connected to the server?\n * @type {CCC.ConnectionStates}\n */\nCCC.connectionState = CCC.ConnectionStates.NEVER_CONNECTED;\n\n/**\n * Enum for message types to the log/world frames.\n * Should be identical to CCC.Common.MessageTypes\n * @enum {string}\n */\nCCC.MessageTypes = {\n  // Messages that may be paused:\n  COMMAND: 'command',  // User-generated command echoed.\n  MEMO: 'memo',  // Block of text from Code City.\n  CONNECT_MSG: 'connect msg',  // User-visible connection message.\n  DISCONNECT_MSG: 'disconnect msg',  // User-visible disconnection message.\n  // Messages that may be sent while paused:\n  CONNECTION: 'connection',  // Signal change of connection state.\n  CLEAR: 'clear',  // Signal to clear history.\n  BLUR: 'blur'  // Signal to close pop-up menus.\n};\n\n/**\n * Unique queue ID.  Identifies this client to the connectServer across\n * polling connections.  Set by the server at startup.\n * @private\n */\nCCC.queueId_ = SESSION_ID;\n\n/**\n * After every iframe has reported ready, call the initialization.\n */\nCCC.countdown = function() {\n  CCC.countdownValue--;\n  if (!CCC.countdownValue) {\n    CCC.init();\n  }\n};\n\n/**\n * Initialization code called on startup.\n */\nCCC.init = function() {\n  CCC.worldFrame = document.getElementById('worldFrame');\n  CCC.logFrame = document.getElementById('logFrame');\n  CCC.displayCell = document.getElementById('displayCell');\n  CCC.commandTextarea = document.getElementById('commandTextarea');\n\n  // When the user closes the tab/window, tell connect server to logout.\n  window.addEventListener('unload', function() {\n    CCC.abortPing();\n    clearTimeout(CCC.nextPingPid);\n    var sendingJson = {\n      'q': CCC.queueId_,\n      'logout': true\n    };\n    navigator.sendBeacon(CCC.PING_URL, JSON.stringify(sendingJson));\n  }, false);\n\n  // When focus returns to this frame from an iframe, go to the command area.\n  // This happens whenever a command link is clicked in an iframe.\n  window.addEventListener('focus', function() {\n    CCC.commandTextarea.focus();\n  }, false);\n  window.addEventListener('resize', CCC.resize, false);\n  // Firefox needs a 0ms delay before first resize, Chrome does not care.\n  setTimeout(CCC.resize, 0);\n\n  CCC.commandTextarea.addEventListener('keydown', CCC.keydown, false);\n  CCC.commandTextarea.addEventListener('click', CCC.userActive, false);\n  CCC.commandTextarea.value = '';\n\n  // Restore command history from sessionStorage.\n  var sessionHistory = sessionStorage.getItem('commandHistory');\n  if (sessionHistory) {\n    CCC.commandHistory = JSON.parse(sessionHistory);\n  }\n\n  var clearButton = document.getElementById('clearButton');\n  clearButton.addEventListener('click', CCC.clear, false);\n  var pauseButton = document.getElementById('pauseButton');\n  pauseButton.addEventListener('click', CCC.pause, false);\n  var worldButton = document.getElementById('worldButton');\n  worldButton.addEventListener('click', CCC.tab.bind(null, 'world'), false);\n  var logButton = document.getElementById('logButton');\n  logButton.addEventListener('click', CCC.tab.bind(null, 'log'), false);\n  document.body.addEventListener('click', function() {\n    CCC.postToAllFrames({'mode': 'blur'});\n  }, true);\n  CCC.tab();\n  CCC.schedulePing(0);\n  // Firefox sometimes caches the disabled value on reload.\n  CCC.commandTextarea.disabled = false;\n};\n\n/**\n * Switch between world and log views.\n * @param {string=} mode Either 'world' or 'log', or undefined.\n */\nCCC.tab = function(mode) {\n  if (!mode) {\n    // Check for a cookie preference.\n    var m = document.cookie.match(/(?:^|;\\s*)TAB=(\\w+)(?:;|$)/);\n    mode = m ? m[1] : 'world';\n  }\n  CCC.userActive();\n  var worldButton = document.getElementById('worldButton');\n  var logButton = document.getElementById('logButton');\n  if (mode === 'world') {\n    CCC.worldFrame.style.zIndex = 1;\n    CCC.logFrame.style.zIndex = -1;\n    CCC.commandTextarea.style.fontFamily = '\"Patrick Hand\", \"Comic Sans MS\"';\n    worldButton.classList.add('jfk-checked');\n    logButton.classList.remove('jfk-checked');\n  } else {\n    CCC.logFrame.style.zIndex = 1;\n    CCC.worldFrame.style.zIndex = -1;\n    CCC.commandTextarea.style.fontFamily = '\"Roboto Mono\", monospace';\n    worldButton.classList.remove('jfk-checked');\n    logButton.classList.add('jfk-checked');\n  }\n  // Set a session cookie to preserve this setting.\n  document.cookie = 'TAB=' + mode;\n  CCC.commandTextarea.focus();\n};\n\n/**\n * Clear all history.\n */\nCCC.clear = function() {\n  CCC.userActive();\n  CCC.commandHistory.length = 0;\n  CCC.commandTemp = '';\n  CCC.commandHistoryPointer = -1;\n  sessionStorage.removeItem('commandHistory');\n  if (CCC.pauseBuffer) {\n    var datum;\n    while ((datum = CCC.pauseBuffer[0]) &&\n           datum[0] !== CCC.MessageTypes.DISCONNECT_MSG) {\n      CCC.pauseBuffer.shift();\n    }\n    // Clear the date/time on the 'Reconnect?' line (if it exists).\n    if (datum) {\n      datum[1] = '...';\n    }\n  }\n  CCC.postToAllFrames({'mode': 'clear'});\n  CCC.commandTextarea.focus();\n};\n\n/**\n * Toggle pausing of incoming messages.\n */\nCCC.pause = function() {\n  CCC.userActive();\n  var paused = CCC.pauseBuffer === null;\n  var pauseButton = document.getElementById('pauseButton');\n  var pauseIcon = document.getElementById('pauseIcon');\n  var playIcon = document.getElementById('playIcon');\n  if (paused) {\n    document.body.classList.add('paused');\n    pauseButton.classList.add('jfk-button-action');\n    pauseIcon.style.display = 'none';\n    playIcon.style.display = '';\n    // Initialize the pause buffer.\n    CCC.pauseBuffer = [];\n  } else {\n    document.body.classList.remove('paused');\n    pauseButton.classList.remove('jfk-button-action');\n    pauseIcon.style.display = '';\n    playIcon.style.display = 'none';\n    // Fire off all accumulated messages.\n    var buffer = CCC.pauseBuffer;\n    CCC.pauseBuffer = null;\n    for (var args of buffer) {\n      CCC.distributeMessage.apply(null, args);\n    }\n  }\n  CCC.commandTextarea.focus();\n};\n\n/**\n * Reposition the iframes over the placeholder displayCell.\n * Called when the window changes size.\n */\nCCC.resize = function() {\n  // Compute the absolute coordinates and dimensions of displayCell.\n  var element = CCC.displayCell;\n  var x = 0;\n  var y = 0;\n  do {\n    x += element.offsetLeft;\n    y += element.offsetTop;\n    element = element.offsetParent;\n  } while (element);\n  // Position both iframes over displayCell.\n  CCC.worldFrame.style.left = x + 'px';\n  CCC.worldFrame.style.top = y + 'px';\n  CCC.worldFrame.style.width = CCC.displayCell.offsetWidth + 'px';\n  CCC.worldFrame.style.height = CCC.displayCell.offsetHeight + 'px';\n  CCC.logFrame.style.left = x + 'px';\n  CCC.logFrame.style.top = y + 'px';\n  CCC.logFrame.style.width = CCC.displayCell.offsetWidth + 'px';\n  CCC.logFrame.style.height = CCC.displayCell.offsetHeight + 'px';\n};\n\n/**\n * Receive messages from our child frames.\n * @param {!Event} e Incoming message event.\n */\nCCC.receiveMessage = function(e) {\n  var origin = e.origin || e.originalEvent.origin;\n  if (origin !== location.origin) {\n    console.error('Message received by client frame from unknown origin: ' +\n                  origin);\n    return;\n  }\n  if (!e.data) {\n    // Shouldn't happen, but harmless.\n  } else if (e.data === 'init') {\n    // A frame is notifying us that it has fully loaded.\n    CCC.countdown();\n  } else if (e.data['commands'] && e.data['commands'].length) {\n    // User has clicked a command link or command menu.\n    for (var command of e.data['commands']) {\n      CCC.sendCommand(command, true);\n    }\n  } else {\n    console.log('Unknown message received by client frame: ' + e.data);\n  }\n};\n\n/**\n * Distribute a line of text to all frames.  If paused, hold this message back.\n * @param {!CCC.MessageTypes} mode Message type.\n * @param {string} text Text to or from Code City.\n */\nCCC.distributeMessage = function(mode, text) {\n  if (CCC.pauseBuffer) {\n    CCC.pauseBuffer.push(arguments);\n    return;\n  }\n  CCC.postToAllFrames({'mode': mode, 'text': text});\n};\n\n/**\n * Distribute an encoded message to all sub-frames.\n * @param {!Object} json Encoded message.\n */\nCCC.postToAllFrames = function(json) {\n  CCC.worldFrame.contentWindow.postMessage(json, location.origin);\n  CCC.logFrame.contentWindow.postMessage(json, location.origin);\n};\n\n/**\n * Add one command to the outbound queue.\n * @param {string} commands Text of user's command.  May be more than one line.\n * @param {boolean} echo True if command to be saved in history.\n */\nCCC.sendCommand = function(commands, echo) {\n  CCC.userActive();\n  commands = commands.split('\\n');\n  // A blank line at the end of a multi-line command is usually accidental.\n  if (commands.length > 1 && !commands[commands.length - 1]) {\n    commands.pop();\n  }\n  for (var command of commands) {\n    // Add command to list of commands to send to server.\n    CCC.commandBuffer.push(command + '\\n');\n    CCC.commandNum++;\n    // Add command to history.\n    if (echo) {\n      if (!CCC.commandHistory.length ||\n          CCC.commandHistory[CCC.commandHistory.length - 1] !== command) {\n        CCC.commandHistory.push(command);\n      }\n    }\n    while (CCC.commandHistory.length > CCC.MAX_HISTORY_SIZE) {\n      CCC.commandHistory.shift();\n    }\n    // Echo command onscreen.\n    if (echo) {\n      CCC.distributeMessage(CCC.MessageTypes.COMMAND, command);\n    }\n  }\n  CCC.commandTemp = '';\n  CCC.commandHistoryPointer = -1;\n  sessionStorage.setItem('commandHistory', JSON.stringify(CCC.commandHistory));\n  // User is sending command, reset the ping to be frequent.\n  CCC.pingInterval = CCC.MIN_PING_INTERVAL;\n  CCC.abortPing();\n  CCC.doPing();\n};\n\n/**\n * Interrupt any in-flight ping.\n */\nCCC.abortPing = function() {\n  if (CCC.xhrObject) {\n    CCC.xhrObject.abort();\n    CCC.xhrObject = null;\n  }\n};\n\n/**\n * Initiate an XHR network connection.\n */\nCCC.doPing = function() {\n  if (CCC.xhrObject) {\n    // Another ping is currently in progress.\n    return;\n  }\n  // Next ping will be scheduled when this ping completes,\n  // but schedule a contingency ping in case of some thrown error.\n  CCC.schedulePing(CCC.MAX_PING_INTERVAL + 1);\n\n  var sendingJson = {\n    'q': CCC.queueId_\n  };\n  if (CCC.ackMemoNextPing) {\n    sendingJson['ackMemoNum'] = CCC.memoNum;\n  }\n  if (CCC.commandBuffer.length) {\n    sendingJson['cmdNum'] = CCC.commandNum;\n    sendingJson['cmds'] = CCC.commandBuffer;\n  }\n\n  // XMLHttpRequest with timeout works in IE8 or better.\n  var req = new XMLHttpRequest();\n  req.onload = CCC.xhrLoaded;\n  req.ontimeout = CCC.xhrError;\n  req.onerror = CCC.xhrError;\n  req.open('POST', CCC.PING_URL, true);\n  req.timeout = CCC.MAX_PING_INTERVAL;  // Time in milliseconds.\n  req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n  req.send(JSON.stringify(sendingJson));\n  CCC.xhrObject = req;\n  // Let the ping interval creep up.\n  CCC.pingInterval = Math.min(CCC.MAX_PING_INTERVAL, CCC.pingInterval * 1.1);\n};\n\n/**\n * Error handler for XHR request.\n * @this {!XMLHttpRequest}\n */\nCCC.xhrError = function() {\n  CCC.xhrErrorCounter++;\n  console.warn('Connection error: ' + CCC.xhrErrorCounter);\n  CCC.xhrObject = null;\n  if (CCC.xhrErrorCounter >= 8) {\n    // Too many errors.  Drop the connection.\n    CCC.terminate();\n    return;\n  } else {\n    CCC.schedulePing(CCC.pingInterval);\n  }\n};\n\n/**\n * Callback function for XHR request.\n * Check network response was ok, then call CCC.parse.\n * @this {!XMLHttpRequest}\n */\nCCC.xhrLoaded = function() {\n  CCC.xhrObject = null;\n  // Only if \"OK\".\n  if (this.status === 200) {\n    try {\n      var json = JSON.parse(this.responseText);\n    } catch (e) {\n      console.warn('Invalid JSON: ' + this.responseText);\n      CCC.xhrError();\n      return;\n    }\n    CCC.xhrErrorCounter = 0;\n    CCC.parse(json);\n  } else if (this.status === 410) {\n    console.warn('Session closed.');\n    CCC.terminate();\n    return;\n  } else if (this.status) {\n    console.warn('Connection error code: ' + this.status);\n    CCC.xhrError();\n    return;\n  }\n  CCC.schedulePing(CCC.pingInterval);\n};\n\n/**\n * Received an error from the server, indicating that our connection is closed.\n */\nCCC.terminate = function() {\n  CCC.connectionState = CCC.ConnectionStates.DISCONNECTED;\n  clearTimeout(CCC.nextPingPid);\n  // Send immediate signal to enter readonly-mode for all frames.\n  CCC.postToAllFrames({'mode': CCC.MessageTypes.CONNECTION, 'state': false});\n  // Send user-visible message (which might be delayed due to pause).\n  CCC.distributeMessage(CCC.MessageTypes.DISCONNECT_MSG,\n                        CCC.currentDateString());\n};\n\n/**\n * Parse the response from the server.\n * @param {!Object} receivedJson Server data.\n */\nCCC.parse = function(receivedJson) {\n  if (CCC.connectionState === CCC.ConnectionStates.DISCONNECTED) {\n    throw new Error('JSON received after disconnection: ' + receivedJson);\n  } else if (CCC.connectionState === CCC.ConnectionStates.NEVER_CONNECTED) {\n    CCC.postToAllFrames({'mode': CCC.MessageTypes.CONNECTION, 'state': true});\n    CCC.distributeMessage(CCC.MessageTypes.CONNECT_MSG,\n                          CCC.currentDateString());\n    CCC.connectionState = CCC.ConnectionStates.CONNECTED;\n  }\n  var ackCmdNum = receivedJson['ackCmdNum'];\n  var memoNum = receivedJson['memoNum'];\n  var memos = receivedJson['memos'];\n\n  if (typeof ackCmdNum === 'number') {\n    if (ackCmdNum > CCC.commandNum) {\n      console.error('Server acks ' + ackCmdNum +\n                    ', but CCC.commandNum is only ' + CCC.commandNum);\n      CCC.terminate();\n    }\n    // Server acknowledges receipt of commands.\n    // Remove them from the output list.\n    CCC.commandBuffer.splice(0,\n        CCC.commandBuffer.length + ackCmdNum - CCC.commandNum);\n  }\n\n  if (typeof memoNum === 'number') {\n    // Server sent messages.  Increase client's index for acknowledgment.\n    var currentIndex = memoNum - memos.length + 1;\n    for (var memo of memos) {\n      if (currentIndex > CCC.memoNum) {\n        CCC.memoNum = currentIndex;\n        CCC.distributeMessage(CCC.MessageTypes.MEMO, memo);\n        // Reduce ping interval.\n        CCC.pingInterval =\n            Math.max(CCC.MIN_PING_INTERVAL, CCC.pingInterval * 0.8);\n      }\n      currentIndex++;\n    }\n    CCC.setUnreadLines(CCC.unreadLines + memos.length);\n    CCC.ackMemoNextPing = true;\n  } else {\n    CCC.ackMemoNextPing = false;\n  }\n};\n\n/**\n * Schedule the next ping.\n * @param {number} ms Milliseconds.\n */\nCCC.schedulePing = function(ms) {\n  clearTimeout(CCC.nextPingPid);\n  CCC.nextPingPid = setTimeout(CCC.doPing, ms);\n};\n\n/**\n * Monitor the user's keystrokes in the command text area.\n * @param {!Event} e Keydown event.\n */\nCCC.keydown = function(e) {\n  CCC.userActive();\n  if (!e.shiftKey && e.key === 'Enter') {\n    // Enter\n    if (CCC.connectionState === CCC.ConnectionStates.CONNECTED) {\n      CCC.sendCommand(CCC.commandTextarea.value, CCC.localEcho);\n      // Clear the textarea.\n      CCC.commandTextarea.value = '';\n      CCC.commandHistoryPointer = -1;\n      CCC.commandTemp = '';\n    } else {\n      // Pulse the command text area to indicate disconnection.\n      CCC.commandTextarea.style.transition = '';\n      CCC.commandTextarea.style.backgroundColor = '#f88';\n      // Wait 0.1 seconds for the browser to process the above style changes.\n      setTimeout(function() {\n        CCC.commandTextarea.style.transition = 'background-color 1s';\n        CCC.commandTextarea.style.backgroundColor = '';\n      }, 100);\n    }\n    e.preventDefault();  // Don't add an enter after the clear.\n  } else if ((!e.shiftKey && e.key === 'ArrowUp') ||\n             (e.ctrlKey && e.key === 'p')) {\n    // Up or Ctrl-P\n    if (!CCC.commandHistory.length) {\n      return;\n    }\n    if (CCC.commandHistoryPointer === -1) {\n      CCC.commandTemp = CCC.commandTextarea.value;\n      CCC.commandHistoryPointer = CCC.commandHistory.length - 1;\n      CCC.commandTextarea.value = CCC.commandHistory[CCC.commandHistoryPointer];\n    } else if (CCC.commandHistoryPointer > 0) {\n      CCC.commandHistoryPointer--;\n      CCC.commandTextarea.value = CCC.commandHistory[CCC.commandHistoryPointer];\n    }\n    e.preventDefault();  // Don't move the cursor to start after change.\n  } else if ((!e.shiftKey && e.key === 'ArrowDown') ||\n             (e.ctrlKey && e.key === 'n')) {\n    // Down or Ctrl-N\n    if (!CCC.commandHistory.length) {\n      return;\n    }\n    if (CCC.commandHistoryPointer === CCC.commandHistory.length - 1) {\n      CCC.commandHistoryPointer = -1;\n      CCC.commandTextarea.value = CCC.commandTemp;\n      CCC.commandTemp = '';\n    } else if (CCC.commandHistoryPointer >= 0) {\n      CCC.commandHistoryPointer++;\n      CCC.commandTextarea.value = CCC.commandHistory[CCC.commandHistoryPointer];\n    }\n  } else if (e.key === 'Tab') {\n    // Tab\n    e.preventDefault();  // Don't change the focus.\n    if (!CCC.commandHistory.length) {\n      return;\n    }\n    var chp = CCC.commandHistoryPointer;\n    if (chp === -1) {  // Save the current value.\n      CCC.commandTemp = CCC.commandTextarea.value;\n    }\n    var reverse = e.shiftKey;\n    for (var i = 0; i <= CCC.commandHistory.length; i++) {\n      // Loop through the entire history, and the current value.\n      chp += reverse ? 1 : -1;\n      if (chp < -1) {  // Wrap up.\n        chp = CCC.commandHistory.length - 1;\n      } else if (chp >= CCC.commandHistory.length) {  // Wrap down.\n        chp = -1;\n      }\n      if (chp === -1) {\n        // The current value is always a match.\n        CCC.commandHistoryPointer = -1;\n        CCC.commandTextarea.value = CCC.commandTemp;\n        CCC.commandTemp = '';\n        break;\n      } else if (CCC.commandHistory[chp].toLowerCase()\n                 .startsWith(CCC.commandTemp.toLowerCase())) {\n        CCC.commandHistoryPointer = chp;\n        CCC.commandTextarea.value = CCC.commandHistory[chp];\n        break;\n      }\n    }\n  } else if (e.key.length === 1) {\n    CCC.commandHistoryPointer = -1;\n    CCC.commandTemp = '';\n  }\n  // Delete the placeholder text as soon as the user types anything.\n  CCC.commandTextarea.placeholder = '';\n};\n\n/**\n * The user is active.\n * Reset the last active time, and clear the notification of unread lines.\n */\nCCC.userActive = function() {\n  CCC.lastActiveTime = Date.now();\n  CCC.setUnreadLines(0);\n};\n\n/**\n * Change the number of unread lines, as notified in the title.\n * @param {number} n Number of unread lines.\n */\nCCC.setUnreadLines = function(n) {\n  CCC.unreadLines = n;\n  var title = document.title;\n  // Strip off old number.\n  title = title.replace(/ \\(\\d+\\)$/, '');\n  // Add new number if user hasn't been seen in 10 seconds.\n  if (n && CCC.lastActiveTime + 10000 < Date.now()) {\n    title += ' (' + n + ')';\n  }\n  document.title = title;\n};\n\n/**\n * Return a local date/time in 'yyyy-mm-dd hh:mm:ss' format.\n * @return {string} Current date/time.\n */\nCCC.currentDateString = function() {\n  var now = new Date();\n  var dy = now.getFullYear();\n  var dm = ('0' + (now.getMonth() + 1)).slice(-2);\n  var dd = ('0' + now.getDate()).slice(-2);\n  var th = ('0' + now.getHours()).slice(-2);\n  var tm = ('0' + now.getMinutes()).slice(-2);\n  var ts = ('0' + now.getSeconds()).slice(-2);\n  return dy + '-' + dm + '-' + dd + ' ' + th + ':' + tm + ':' + ts;\n};\n\nwindow.addEventListener('message', CCC.receiveMessage, false);\nwindow.addEventListener('load', CCC.countdown, false);\n"
  },
  {
    "path": "static/connect/log.css",
    "content": "body {\n  font-family: 'Roboto Mono', monospace;\n}\n\n#scrollDiv {\n  padding-left: 15px;\n}\n\n#scrollDiv>div:first-child {\n  /* Add whitespace above the first line so that the client buttons don't\n  obscure any content. */\n  margin-top: 2em;\n}\n\n.zippySpan {\n  cursor: pointer;\n  margin-left: -15px;\n  position: absolute;\n}\n\n.zippySpan::before {\n  content: '▸ ';\n }\n\n.zippySpan.open::before {\n  content: '▾ ';\n}\n\n.zippySpan:hover {\n  color: #d00;\n}\n\npre {\n  font-family: 'Roboto Mono', monospace;\n  margin-bottom: 0;\n  margin-top: 0;\n}\n\n.commandDiv {\n  background: #ffc;\n}\n\n.sceneTitle {\n  font-weight: bold;\n}\n\n.openIcon {\n  fill: #444;\n  width: 1.5ex;\n}\n\n.openIcon:hover {\n  fill: #d00;\n}\n\n.connectDiv {\n  background-color: #0a0;\n}\n\n.disconnectDiv {\n  background-color: #d00;\n}\n\n.connectDiv, .disconnectDiv {\n  color: #fff;\n  padding: 0 15px;\n  margin-left: -15px;\n}\n\n.connectDiv>.date, .disconnectDiv>.date {\n  float: right;\n}\n\na.reconnect {\n  color: #fff;\n  cursor: pointer;\n  margin-left: 1em;\n  text-decoration: underline dotted;\n  user-select: none;\n}\n\na.reconnect:hover {\n  opacity: .9;\n}\n"
  },
  {
    "path": "static/connect/log.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Log frame of Code City's client.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nCCC.Log = {};\n\n\n/**\n * Maximum number of lines saved in history.\n */\nCCC.Log.maxHistorySize = 10000;\n\n/**\n * Allowed protocols for iframe links.\n * Probably best not to allow 'javascript:' URIs due to security reasons.\n */\nCCC.Log.protocolRegex =\n    /^((https?|ftp|gopher|data|irc|telnet|news|wais|file|nntp|mailto):|\\/)/;\n\n/**\n * Record of the user's name.  Used for displaying 2nd person vs 3rd person\n * messages.  E.g.:  You say, \"Hello.\"  -vs-  Max says, \"Hello.\"\n * @type {string=}\n */\nCCC.Log.userName = undefined;\n\n/**\n * Initialization code called on startup.\n */\nCCC.Log.init = function() {\n  CCC.Common.init();\n  CCC.Log.scrollDiv = document.getElementById('scrollDiv');\n  window.addEventListener('resize', CCC.Log.scrollToBottom, false);\n  // Lazy-load prettify library.\n  setTimeout(CCC.Log.importPrettify, 1);\n};\n\n/**\n * Load the Prettify CSS and JavaScript.\n */\nCCC.Log.importPrettify = function() {\n  // <link rel=\"stylesheet\" type=\"text/css\" href=\"connect/prettify.css\">\n  // <script type=\"text/javascript\" src=\"connect/prettify.js\"></script>\n  var link = document.createElement('link');\n  link.rel = 'stylesheet';\n  link.type = 'text/css';\n  link.href = STATIC_URL + 'connect/prettify.css';\n  document.head.appendChild(link);\n  var script = document.createElement('script');\n  script.src = STATIC_URL + 'connect/prettify.js';\n  document.head.appendChild(script);\n};\n\n/**\n * Receive messages from our parent frame.\n * @param {!Event} e Incoming message event.\n */\nCCC.Log.receiveMessage = function(e) {\n  var data = CCC.Common.verifyMessage(e);\n  if (!data) {\n    return;\n  }\n  var mode = data['mode'];\n  if (mode === CCC.Common.MessageTypes.CLEAR) {\n    // Clear all lines, except for the 'Reconnect?' line (if it exists).\n    var div;\n    while ((div = CCC.Log.scrollDiv.firstChild) &&\n           div.className !== 'disconnectDiv') {\n      CCC.Log.scrollDiv.removeChild(div);\n    }\n    // Clear the date/time on the 'Reconnect?' line (if it exists).\n    if (div) {\n      var dates = div.getElementsByClassName('date');\n      if (dates[0]) {\n        dates[0].textContent = '...';\n      }\n    }\n  } else if (mode === CCC.Common.MessageTypes.BLUR) {\n    CCC.Common.closeMenu();\n  } else if (mode === CCC.Common.MessageTypes.COMMAND) {\n    var text = data['text'];\n    var div = CCC.Log.textToHtml(text);\n    div.className = 'commandDiv';\n    CCC.Log.appendRow(div);\n  } else if (mode === CCC.Common.MessageTypes.CONNECTION) {\n    CCC.Common.setConnected(data['state']);\n  } else if (mode === CCC.Common.MessageTypes.CONNECT_MSG) {\n    // Notify the user of the connection.\n    var div = CCC.Log.connectDiv(true, data['text']);\n    CCC.Log.appendRow(div);\n  } else if (mode === CCC.Common.MessageTypes.DISCONNECT_MSG) {\n    // Notify the user of the disconnection.\n    var div = CCC.Log.connectDiv(false, data['text']);\n    CCC.Log.appendRow(div);\n  } else if (mode === CCC.Common.MessageTypes.MEMO) {\n    var text = data['text'];\n    try {\n      var json = JSON.parse(text);\n    } catch (e) {\n      // Not valid JSON, treat as string literal.\n      var div = CCC.Log.textToHtml(text);\n      CCC.Log.appendRow(div);\n      return;\n    }\n    CCC.Log.addJson(json);\n  }\n};\n\n/**\n * Create a div notifying the user of connection or disconnection.\n * @param {boolean} isConnected New connection state.\n * @param {string} date Date/time of connection/disconnection.\n * @return {!Element} HTML div element.\n */\nCCC.Log.connectDiv = function(isConnected, date) {\n  var div = document.createElement('div');\n  div.className = (isConnected ? 'connectDiv' : 'disconnectDiv');\n  var span = document.createElement('span');\n  span.className = 'date';\n  span.appendChild(document.createTextNode(date));\n  div.appendChild(span);\n\n  div.appendChild(CCC.Log.getTemplate(isConnected ?\n      'connectedTemplate' : 'disconnectedTemplate'));\n  if (!isConnected) {\n    var link = document.createElement('a');\n    link.className = 'reconnect';\n    link.appendChild(CCC.Log.getTemplate('reconnectTemplate'));\n    div.appendChild(link);\n    link.addEventListener('click', parent.location.reload.bind(parent.location));\n  }\n  return div;\n};\n\n/**\n * Convert plain text to HTML.  Preserve spaces and line breaks.\n * @param {string} text Line of text.\n * @return {!Element} HTML div element.\n */\nCCC.Log.textToHtml = function(text) {\n  text = CCC.Common.escapeSpaces(text);\n  var lines = text.split('\\n');\n  var div = document.createElement('div');\n  for (var i = 0; i < lines.length; i++) {\n    if (i !== 0) {\n      div.appendChild(document.createElement('br'));\n    }\n    div.appendChild(document.createTextNode(lines[i]));\n  }\n  return div;\n};\n\n/**\n * Add one row of JSON to the log.\n * @param {!Object} json JSON structure.\n */\nCCC.Log.addJson = function(json) {\n  var rendered = CCC.Log.renderJson(json);\n  if (rendered === null) {\n    return;  // Unrequested scene.\n  }\n  var pre = document.createElement('pre');\n  pre.textContent = JSON.stringify(json, null, 2);\n  if (typeof prettyPrint === 'function') {\n    pre.className = 'prettyprint lang-js';\n    var div = document.createElement('div');\n    div.appendChild(pre);\n    prettyPrint(null, div);\n  }\n\n  if (rendered) {\n    if (typeof rendered === 'string') {\n      var div = CCC.Log.textToHtml(rendered);\n    } else {\n      var div = rendered;\n    }\n    div.className = 'zippyDiv';\n    var span = document.createElement('span');\n    span.className = 'zippySpan';\n    span.addEventListener('click', CCC.Log.toggleZippy);\n    div.insertBefore(span, div.firstChild);\n    pre.style.display = 'none';\n    div.appendChild(pre);\n    CCC.Log.appendRow(div);\n  } else {\n    CCC.Log.appendRow(pre);\n  }\n};\n\nCCC.Log.toggleZippy = function(e) {\n  var zippy = e.target;\n  var pre = zippy.parentNode.lastChild;\n  if (!zippy.className.includes(' open')) {\n    zippy.className += ' open';\n    pre.style.display = 'block';\n    if (!zippy.parentNode.nextSibling) {\n      // Opening a zippy at the bottom of the page.  Scroll down.\n      CCC.Log.scrollToBottom();\n    }\n  } else {\n    zippy.className = zippy.className.replace(' open', '');\n    pre.style.display = 'none';\n  }\n};\n\n/**\n * Attempt to render the JSON as a plain text version.\n * @param {!Object} json JSON object.\n * @return {Element} Div of text, or null if not to be visualized,\n *   or undefined if unknown/corrupt format.\n */\nCCC.Log.renderJson = function(json) {\n  switch (json.type) {\n    case 'iframe':\n      // {type: \"iframe\", url: \"https://example.com/foo\", alt: \"Alt text\"}\n      var src = json.url;\n      var m = src.match(CCC.Log.protocolRegex);\n      if (!m) {\n        return undefined;  // Invalid src attribute.\n      }\n      var div = document.createElement('div');\n      var text = json.alt || src;\n      div.appendChild(document.createTextNode(text));\n      div.appendChild(CCC.Log.openIcon(src));\n      return div;\n    case 'html':\n      // {type: \"html\", htmlText: \"<div>Arbitrary HTML</div>\"}\n      var dom = CCC.Common.parser.parseFromString(json.htmlText, 'text/html');\n      if (dom.body) {\n        var div = document.createElement('div');\n        CCC.Log.renderHtmltext(div, dom.body);\n        CCC.Common.autoHyperlink(div);\n        return div;\n      }\n      return undefined;  // Illegal HTML.\n    case 'scene':\n      //{\n      //  type: \"scene\",\n      //  requested: true,\n      //  user: \"Max\",\n      //  where: \"Hangout\",\n      //  description: \"The lights are dim and blah blah blah...\",\n      //  svgText: \"...\",\n      //  contents: [\n      //    {\n      //      type: \"user\",\n      //      what: \"Max\",\n      //      svgText: \"...\",\n      //      cmds: [\"look Max\", \"kick Max\"]\n      //    },\n      //    {\n      //      type: \"thing\",\n      //      what: \"clock\",\n      //      svgText: \"...\",\n      //      cmds: [\"look clock\"]\n      //    }\n      //  ]\n      //}\n      if (!json.requested) {\n        return null;  // Do not display this scene update in the log.\n      }\n      if (json.user) {\n        // Record the user name if present.\n        CCC.Log.userName = json.user;\n      }\n      var objects = [];\n      var users = [];\n      if (json.contents) {\n        for (var content of json.contents) {\n          if (content.type === 'user' && CCC.Log.userName === content.what) {\n            continue;  // Don't show the current user.\n          }\n          var df = document.createDocumentFragment();\n          df.appendChild(document.createTextNode(content.what));\n          if (content.cmds) {\n            var icon = CCC.Common.newMenuIcon(content.cmds);\n            if (icon) {\n              icon.addEventListener('click', CCC.Common.openMenu);\n              df.appendChild(icon);\n            }\n          }\n          (content.type === 'user' ? users : objects).push(df);\n        }\n      }\n      var div = document.createElement('div');\n      if (json.where) {\n        var titleDiv = document.createElement('div');\n        titleDiv.className = 'sceneTitle';\n        titleDiv.appendChild(document.createTextNode(json.where));\n        div.appendChild(titleDiv);\n      }\n      if (json.description) {\n        var descriptionDiv = CCC.Log.textToHtml(json.description);\n        CCC.Common.autoHyperlink(descriptionDiv);\n        div.appendChild(descriptionDiv);\n      }\n      if (objects.length) {\n        var objectsDiv = document.createElement('div');\n        if (objects.length === 1) {\n          objectsDiv.appendChild(CCC.Log.getTemplate(\n              'roomObjectTemplate', objects[0]));\n        } else if (objects.length > 1) {\n          objectsDiv.appendChild(CCC.Log.getTemplate(\n              'roomObjectsTemplate', CCC.Log.naturalList(objects)));\n        }\n        div.appendChild(objectsDiv);\n      }\n      if (users.length) {\n        var usersDiv = document.createElement('div');\n        if (users.length === 1) {\n          usersDiv.appendChild(CCC.Log.getTemplate(\n              'roomUserTemplate', users[0]));\n        } else if (users.length > 1) {\n          usersDiv.appendChild(CCC.Log.getTemplate(\n              'roomUsersTemplate', CCC.Log.naturalList(users)));\n        }\n        div.appendChild(usersDiv);\n      }\n      return div;\n    case 'say':\n      // {type: \"say\", text: \"Welcome\"}\n      // {type: \"say\", source: \"Max\", where: \"Hangout\", text: \"Hello world.\"}\n      // {type: \"say\", source: \"Cat\", where: \"Hangout\", text: \"Meow.\"}\n      // Fall through.\n    case 'think':\n      // {type: \"think\", text: \"Don't be evil.\"}\n      // {type: \"think\", source: \"Max\", where: \"Hangout\", text: \"I'm hungry.\"}\n      // {type: \"think\", source: \"Cat\", where: \"Hangout\", text: \"I'm evil.\"}\n      var text = CCC.Common.escapeSpaces(json.text);\n      if (json.type === 'think') {\n        var type = 'think';\n      } else {\n        var lastLetter = text.trim().slice(-1);\n        var type = (lastLetter === '?') ? 'ask' :\n            ((lastLetter === '!') ? 'exclaim' : 'say');\n      }\n      if (json.source && CCC.Log.userName === json.source) {\n        var fragment = CCC.Log.getTemplate(type + 'SelfTemplate', text);\n      } else {\n        var who = json.source || CCC.Log.getTemplate('unknownTemplate');\n        var fragment = CCC.Log.getTemplate(type + 'Template', who, text);\n      }\n      CCC.Common.autoHyperlink(fragment);\n      var div = document.createElement('div');\n      div.appendChild(fragment);\n      return div;\n    case 'narrate':\n      // {type: \"narrate\", text: \"Command not recognized.\"}\n      // {type: \"narrate\", where: \"Hangout\", text: \"Hangout is dark.\"}\n      // {type: \"narrate\", source: \"Max\", where: \"Hangout\", text: \"Max smiles.\"}\n      // {type: \"narrate\", source: \"Cat\", where: \"Hangout\", text: \"Cat meows.\"}\n      var div = document.createElement('div');\n      var text = json.text;\n      if (json.source) {\n        text = json.source + ': ' + text;\n      }\n      div.appendChild(document.createTextNode(text));\n      CCC.Common.autoHyperlink(div);\n      return div;\n    case 'link':\n      // {type: \"link\", href: \"https://example.com/\"}\n      var div = document.createElement('div');\n      var a = document.createElement('a');\n      a.href = json.href;\n      a.target = '_blank';\n      a.appendChild(document.createTextNode(json.href));\n      div.appendChild(a);\n      // Note: this opens the link in a new tab regardless of whether the user\n      // is in world or log view.\n      var success = window.open(json.href);\n      if (!success) {\n        alert('Your browser has blocked the opening of the page you requested.\\n' +\n              'Please allow pop-ups on this domain. ✓️');\n      }\n      return div;\n  }\n  // Unknown XML.\n  return undefined;\n};\n\n/**\n * Create an icon that links to a page in a new window.\n * @param {string} src URL of link to open.\n * @return {!Element} DOM element of newly-created link and icon.\n */\nCCC.Log.openIcon = function(src) {\n  // <a href=\"https://example.com\" target=\"_blank\">\n  //   <svg class=\"openIcon\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 3 24 24\">\n  //     <path d=\"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1...\"/>\n  //   </svg>\n  // </a>\n  // Icon artwork sourced from https://icons.googleplex.com/\n  var link = document.createElement('a');\n  link.href = src;\n  link.target = '_blank';\n  link.rel = 'noopener noreferrer';\n  var svg = CCC.Common.createSvgElement('svg',\n      {'class': 'openIcon', 'viewBox': '0 3 24 24'}, link);\n  CCC.Common.createSvgElement('path',\n      {'d': 'M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z'}, svg);\n  return link;\n};\n\n/**\n * Create a mostly text-based representation of the provided DOM.\n * @param {!Element} div Div element to append content to.\n * @param {!Node} node DOM to walk.\n */\nCCC.Log.renderHtmltext = function(div, node) {\n  if (node.nodeType === Node.ELEMENT_NODE) {\n    // Element.\n    if (node.tagName === 'svg') {  // XML tagNames are lowercase.\n      return;  // No text content of this tag should be rendered.\n    }\n    if (node.tagName === 'CMDS') {  // HTML tagNames are uppercase.\n      var icon = CCC.Common.newMenuIcon(node);\n      if (icon) {\n        icon.addEventListener('click', CCC.Common.openMenu);\n        div.appendChild(icon);\n      }\n      return;\n    }\n    if (node.tagName === 'CMD') {  // HTML tagNames are uppercase.\n      var cmdText = node.innerText;\n      var a = document.createElement('a');\n      a.className = 'command';\n      a.appendChild(document.createTextNode(cmdText));\n      a.addEventListener('click', CCC.Common.commandFunction, false);\n      div.appendChild(a);\n      return;\n    }\n    for (var child of node.childNodes) {\n      CCC.Log.renderHtmltext(div, child);\n    }\n    if (CCC.Log.renderHtmltext.BLOCK_NAMES.has(node.tagName)) {\n      // Add a <br> tag, but not if there's already one.\n      var lastTag = div.lastChild;\n      while (lastTag && lastTag.nodeType !== Node.ELEMENT_NODE) {\n        if (lastTag.nodeType === Node.TEXT_NODE && lastTag.nodeValue.trim()) {\n          // Found text that's not whitespace.  Bail.\n          lastTag = null;\n        } else {\n          // Nothing printable found so far, keep walking up looking for a <br>.\n          lastTag = lastTag.previousSibling;\n        }\n      }\n      if (div.hasChildNodes() && (!lastTag || lastTag.tagName !== 'BR')) {\n        div.appendChild(document.createElement('br'));\n      }\n    }\n  } else if (node.nodeType === Node.TEXT_NODE) {\n    // Text node.\n    div.appendChild(document.createTextNode(node.data));\n  }\n};\n\n/**\n * List of elements that are blocks, rather than inline.\n */\nCCC.Log.renderHtmltext.BLOCK_NAMES = new Set([\n  'ADDRESS',\n  'BLOCKQUOTE',\n  'BR',\n  'DIV',\n  'DL',\n  'DT',\n  'FIELDSET',\n  'H1', 'H2', 'H3', 'H4', 'H5', 'H6',\n  'HR',\n  'LI',\n  'OL',\n  'P',\n  'PRE',\n  'TABLE',\n  'TR',\n  'UL',\n]);\n\n/**\n * Gets the template with the given key from the document.\n * @param {string} key The key of the document element.\n * @param {...string|DocumentFragment} var_args Optional substitutions for %1...\n * @return {!DocumentFragment} A document fragment containing the text.\n */\nCCC.Log.getTemplate = function(key, var_args) {\n  var element = document.getElementById(key);\n  if (!element) {\n    throw new Error('Unknown template ' + key);\n  }\n  var text = element.textContent;\n  var parts = text.split(/(%\\d)/);\n  var df = document.createDocumentFragment();\n  // Inject any substitutions.\n  for (var part of parts) {\n    var m = part.match(/^%(\\d)$/);\n    if (m) {\n      var inject = arguments[m[1]];\n      if (typeof inject === 'string') {\n        inject = document.createTextNode(inject);\n      }\n      df.appendChild(inject);\n    } else if (part) {\n      df.appendChild(document.createTextNode(part));\n    }\n  }\n  return df;\n};\n\n/**\n * Make a natural language list.  Don't use Oxford comma due to lack of plurals.\n * ['apple', 'banana', 'cherry'] -> 'apple, banana and cherry'\n * @param {!Array.<!DocumentFragment>} list List of items to concatenate.\n * @return {!DocumentFragment} A document fragment containing the text.\n */\nCCC.Log.naturalList = function(list) {\n  if (list.length === 1) {\n    return list[0];\n  }\n  var df = document.createDocumentFragment();\n  for (var i = 0; i < list.length - 1; i++) {\n    if (i) {\n      df.appendChild(document.createTextNode(', '));\n    }\n    df.appendChild(list[i]);\n  }\n  df.appendChild(document.createTextNode(' '));\n  df.appendChild(CCC.Log.getTemplate('andTemplate'));\n  df.appendChild(document.createTextNode(' '));\n  df.appendChild(list[list.length - 1]);\n  return df;\n};\n\n/**\n * Add one row to the log.  Scroll page to the bottom.\n * @param {!Element} element HTML element to add.\n */\nCCC.Log.appendRow = function(element) {\n  var div = CCC.Log.scrollDiv;\n  div.appendChild(element);\n  if (div.childNodes.length > CCC.Log.maxHistorySize) {\n    div.removeChild(document.body.firstChild);\n  }\n  CCC.Log.scrollToBottom();\n};\n\n/**\n * Scroll the log to the bottom.\n */\nCCC.Log.scrollToBottom = function() {\n  CCC.Log.scrollDiv.scrollTop = CCC.Log.scrollDiv.scrollHeight;\n  CCC.Log.scrollDiv.scrollLeft = 0;\n};\n\nif (!window.TEST) {\n  window.addEventListener('message', CCC.Log.receiveMessage, false);\n  window.addEventListener('load', CCC.Log.init, false);\n}\n"
  },
  {
    "path": "static/connect/prettify.css",
    "content": ".pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee}"
  },
  {
    "path": "static/connect/prettify.js",
    "content": "!function(){/*\n\n Copyright 2006 Google LLC\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n      http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\nwindow.PR_SHOULD_USE_CONTINUATION=!0;\n(function(){function T(a){function d(e){var b=e.charCodeAt(0);if(92!==b)return b;var a=e.charAt(1);return(b=w[a])?b:\"0\"<=a&&\"7\">=a?parseInt(e.substring(1),8):\"u\"===a||\"x\"===a?parseInt(e.substring(2),16):e.charCodeAt(1)}function f(e){if(32>e)return(16>e?\"\\\\x0\":\"\\\\x\")+e.toString(16);e=String.fromCharCode(e);return\"\\\\\"===e||\"-\"===e||\"]\"===e||\"^\"===e?\"\\\\\"+e:e}function b(e){var b=e.substring(1,e.length-1).match(/\\\\u[0-9A-Fa-f]{4}|\\\\x[0-9A-Fa-f]{2}|\\\\[0-3][0-7]{0,2}|\\\\[0-7]{1,2}|\\\\[\\s\\S]|-|[^-\\\\]/g);e=\n[];var a=\"^\"===b[0],c=[\"[\"];a&&c.push(\"^\");for(var a=a?1:0,g=b.length;a<g;++a){var h=b[a];if(/\\\\[bdsw]/i.test(h))c.push(h);else{var h=d(h),k;a+2<g&&\"-\"===b[a+1]?(k=d(b[a+2]),a+=2):k=h;e.push([h,k]);65>k||122<h||(65>k||90<h||e.push([Math.max(65,h)|32,Math.min(k,90)|32]),97>k||122<h||e.push([Math.max(97,h)&-33,Math.min(k,122)&-33]))}}e.sort(function(e,a){return e[0]-a[0]||a[1]-e[1]});b=[];g=[];for(a=0;a<e.length;++a)h=e[a],h[0]<=g[1]+1?g[1]=Math.max(g[1],h[1]):b.push(g=h);for(a=0;a<b.length;++a)h=b[a],\nc.push(f(h[0])),h[1]>h[0]&&(h[1]+1>h[0]&&c.push(\"-\"),c.push(f(h[1])));c.push(\"]\");return c.join(\"\")}function v(e){for(var a=e.source.match(/(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)/g),c=a.length,d=[],g=0,h=0;g<c;++g){var k=a[g];\"(\"===k?++h:\"\\\\\"===k.charAt(0)&&(k=+k.substring(1))&&(k<=h?d[k]=-1:a[g]=f(k))}for(g=1;g<d.length;++g)-1===d[g]&&(d[g]=++A);for(h=g=0;g<c;++g)k=a[g],\"(\"===k?(++h,d[h]||(a[g]=\"(?:\")):\"\\\\\"===\nk.charAt(0)&&(k=+k.substring(1))&&k<=h&&(a[g]=\"\\\\\"+d[k]);for(g=0;g<c;++g)\"^\"===a[g]&&\"^\"!==a[g+1]&&(a[g]=\"\");if(e.ignoreCase&&n)for(g=0;g<c;++g)k=a[g],e=k.charAt(0),2<=k.length&&\"[\"===e?a[g]=b(k):\"\\\\\"!==e&&(a[g]=k.replace(/[a-zA-Z]/g,function(a){a=a.charCodeAt(0);return\"[\"+String.fromCharCode(a&-33,a|32)+\"]\"}));return a.join(\"\")}for(var A=0,n=!1,l=!1,m=0,c=a.length;m<c;++m){var p=a[m];if(p.ignoreCase)l=!0;else if(/[a-z]/i.test(p.source.replace(/\\\\u[0-9a-f]{4}|\\\\x[0-9a-f]{2}|\\\\[^ux]/gi,\"\"))){n=!0;\nl=!1;break}}for(var w={b:8,t:9,n:10,v:11,f:12,r:13},r=[],m=0,c=a.length;m<c;++m){p=a[m];if(p.global||p.multiline)throw Error(\"\"+p);r.push(\"(?:\"+v(p)+\")\")}return new RegExp(r.join(\"|\"),l?\"gi\":\"g\")}function U(a,d){function f(a){var c=a.nodeType;if(1==c){if(!b.test(a.className)){for(c=a.firstChild;c;c=c.nextSibling)f(c);c=a.nodeName.toLowerCase();if(\"br\"===c||\"li\"===c)v[l]=\"\\n\",n[l<<1]=A++,n[l++<<1|1]=a}}else if(3==c||4==c)c=a.nodeValue,c.length&&(c=d?c.replace(/\\r\\n?/g,\"\\n\"):c.replace(/[ \\t\\r\\n]+/g,\n\" \"),v[l]=c,n[l<<1]=A,A+=c.length,n[l++<<1|1]=a)}var b=/(?:^|\\s)nocode(?:\\s|$)/,v=[],A=0,n=[],l=0;f(a);return{a:v.join(\"\").replace(/\\n$/,\"\"),c:n}}function J(a,d,f,b,v){f&&(a={h:a,l:1,j:null,m:null,a:f,c:null,i:d,g:null},b(a),v.push.apply(v,a.g))}function V(a){for(var d=void 0,f=a.firstChild;f;f=f.nextSibling)var b=f.nodeType,d=1===b?d?a:f:3===b?W.test(f.nodeValue)?a:d:d;return d===a?void 0:d}function G(a,d){function f(a){for(var l=a.i,m=a.h,c=[l,\"pln\"],p=0,w=a.a.match(v)||[],r={},e=0,t=w.length;e<\nt;++e){var z=w[e],q=r[z],g=void 0,h;if(\"string\"===typeof q)h=!1;else{var k=b[z.charAt(0)];if(k)g=z.match(k[1]),q=k[0];else{for(h=0;h<A;++h)if(k=d[h],g=z.match(k[1])){q=k[0];break}g||(q=\"pln\")}!(h=5<=q.length&&\"lang-\"===q.substring(0,5))||g&&\"string\"===typeof g[1]||(h=!1,q=\"src\");h||(r[z]=q)}k=p;p+=z.length;if(h){h=g[1];var B=z.indexOf(h),D=B+h.length;g[2]&&(D=z.length-g[2].length,B=D-h.length);q=q.substring(5);J(m,l+k,z.substring(0,B),f,c);J(m,l+k+B,h,K(q,h),c);J(m,l+k+D,z.substring(D),f,c)}else c.push(l+\nk,q)}a.g=c}var b={},v;(function(){for(var f=a.concat(d),l=[],m={},c=0,p=f.length;c<p;++c){var w=f[c],r=w[3];if(r)for(var e=r.length;0<=--e;)b[r.charAt(e)]=w;w=w[1];r=\"\"+w;m.hasOwnProperty(r)||(l.push(w),m[r]=null)}l.push(/[\\0-\\uffff]/);v=T(l)})();var A=d.length;return f}function y(a){var d=[],f=[];a.tripleQuotedStrings?d.push([\"str\",/^(?:\\'\\'\\'(?:[^\\'\\\\]|\\\\[\\s\\S]|\\'{1,2}(?=[^\\']))*(?:\\'\\'\\'|$)|\\\"\\\"\\\"(?:[^\\\"\\\\]|\\\\[\\s\\S]|\\\"{1,2}(?=[^\\\"]))*(?:\\\"\\\"\\\"|$)|\\'(?:[^\\\\\\']|\\\\[\\s\\S])*(?:\\'|$)|\\\"(?:[^\\\\\\\"]|\\\\[\\s\\S])*(?:\\\"|$))/,\nnull,\"'\\\"\"]):a.multiLineStrings?d.push([\"str\",/^(?:\\'(?:[^\\\\\\']|\\\\[\\s\\S])*(?:\\'|$)|\\\"(?:[^\\\\\\\"]|\\\\[\\s\\S])*(?:\\\"|$)|\\`(?:[^\\\\\\`]|\\\\[\\s\\S])*(?:\\`|$))/,null,\"'\\\"`\"]):d.push([\"str\",/^(?:\\'(?:[^\\\\\\'\\r\\n]|\\\\.)*(?:\\'|$)|\\\"(?:[^\\\\\\\"\\r\\n]|\\\\.)*(?:\\\"|$))/,null,\"\\\"'\"]);a.verbatimStrings&&f.push([\"str\",/^@\\\"(?:[^\\\"]|\\\"\\\")*(?:\\\"|$)/,null]);var b=a.hashComments;b&&(a.cStyleComments?(1<b?d.push([\"com\",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,\"#\"]):d.push([\"com\",/^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\\b|[^\\r\\n]*)/,\nnull,\"#\"]),f.push([\"str\",/^<(?:(?:(?:\\.\\.\\/)*|\\/?)(?:[\\w-]+(?:\\/[\\w-]+)+)?[\\w-]+\\.h(?:h|pp|\\+\\+)?|[a-z]\\w*)>/,null])):d.push([\"com\",/^#[^\\r\\n]*/,null,\"#\"]));a.cStyleComments&&(f.push([\"com\",/^\\/\\/[^\\r\\n]*/,null]),f.push([\"com\",/^\\/\\*[\\s\\S]*?(?:\\*\\/|$)/,null]));if(b=a.regexLiterals){var v=(b=1<b?\"\":\"\\n\\r\")?\".\":\"[\\\\S\\\\s]\";f.push([\"lang-regex\",RegExp(\"^(?:^^\\\\.?|[+-]|[!=]=?=?|\\\\#|%=?|&&?=?|\\\\(|\\\\*=?|[+\\\\-]=|->|\\\\/=?|::?|<<?=?|>>?>?=?|,|;|\\\\?|@|\\\\[|~|{|\\\\^\\\\^?=?|\\\\|\\\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\\\s*(\"+\n(\"/(?=[^/*\"+b+\"])(?:[^/\\\\x5B\\\\x5C\"+b+\"]|\\\\x5C\"+v+\"|\\\\x5B(?:[^\\\\x5C\\\\x5D\"+b+\"]|\\\\x5C\"+v+\")*(?:\\\\x5D|$))+/\")+\")\")])}(b=a.types)&&f.push([\"typ\",b]);b=(\"\"+a.keywords).replace(/^ | $/g,\"\");b.length&&f.push([\"kwd\",new RegExp(\"^(?:\"+b.replace(/[\\s,]+/g,\"|\")+\")\\\\b\"),null]);d.push([\"pln\",/^\\s+/,null,\" \\r\\n\\t\\u00a0\"]);b=\"^.[^\\\\s\\\\w.$@'\\\"`/\\\\\\\\]*\";a.regexLiterals&&(b+=\"(?!s*/)\");f.push([\"lit\",/^@[a-z_$][a-z_$@0-9]*/i,null],[\"typ\",/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\\w+_t\\b)/,null],[\"pln\",/^[a-z_$][a-z_$@0-9]*/i,\nnull],[\"lit\",/^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*/i,null,\"0123456789\"],[\"pln\",/^\\\\[\\s\\S]?/,null],[\"pun\",new RegExp(b),null]);return G(d,f)}function L(a,d,f){function b(a){var c=a.nodeType;if(1==c&&!A.test(a.className))if(\"br\"===a.nodeName)v(a),a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)b(a);else if((3==c||4==c)&&f){var d=a.nodeValue,q=d.match(n);q&&(c=d.substring(0,q.index),a.nodeValue=c,(d=d.substring(q.index+q[0].length))&&\na.parentNode.insertBefore(l.createTextNode(d),a.nextSibling),v(a),c||a.parentNode.removeChild(a))}}function v(a){function b(a,c){var d=c?a.cloneNode(!1):a,k=a.parentNode;if(k){var k=b(k,1),e=a.nextSibling;k.appendChild(d);for(var f=e;f;f=e)e=f.nextSibling,k.appendChild(f)}return d}for(;!a.nextSibling;)if(a=a.parentNode,!a)return;a=b(a.nextSibling,0);for(var d;(d=a.parentNode)&&1===d.nodeType;)a=d;c.push(a)}for(var A=/(?:^|\\s)nocode(?:\\s|$)/,n=/\\r\\n?|\\n/,l=a.ownerDocument,m=l.createElement(\"li\");a.firstChild;)m.appendChild(a.firstChild);\nfor(var c=[m],p=0;p<c.length;++p)b(c[p]);d===(d|0)&&c[0].setAttribute(\"value\",d);var w=l.createElement(\"ol\");w.className=\"linenums\";d=Math.max(0,d-1|0)||0;for(var p=0,r=c.length;p<r;++p)m=c[p],m.className=\"L\"+(p+d)%10,m.firstChild||m.appendChild(l.createTextNode(\"\\u00a0\")),w.appendChild(m);a.appendChild(w)}function t(a,d){for(var f=d.length;0<=--f;){var b=d[f];I.hasOwnProperty(b)?E.console&&console.warn(\"cannot override language handler %s\",b):I[b]=a}}function K(a,d){a&&I.hasOwnProperty(a)||(a=/^\\s*</.test(d)?\n\"default-markup\":\"default-code\");return I[a]}function M(a){var d=a.j;try{var f=U(a.h,a.l),b=f.a;a.a=b;a.c=f.c;a.i=0;K(d,b)(a);var v=/\\bMSIE\\s(\\d+)/.exec(navigator.userAgent),v=v&&8>=+v[1],d=/\\n/g,A=a.a,n=A.length,f=0,l=a.c,m=l.length,b=0,c=a.g,p=c.length,w=0;c[p]=n;var r,e;for(e=r=0;e<p;)c[e]!==c[e+2]?(c[r++]=c[e++],c[r++]=c[e++]):e+=2;p=r;for(e=r=0;e<p;){for(var t=c[e],z=c[e+1],q=e+2;q+2<=p&&c[q+1]===z;)q+=2;c[r++]=t;c[r++]=z;e=q}c.length=r;var g=a.h;a=\"\";g&&(a=g.style.display,g.style.display=\"none\");\ntry{for(;b<m;){var h=l[b+2]||n,k=c[w+2]||n,q=Math.min(h,k),B=l[b+1],D;if(1!==B.nodeType&&(D=A.substring(f,q))){v&&(D=D.replace(d,\"\\r\"));B.nodeValue=D;var N=B.ownerDocument,u=N.createElement(\"span\");u.className=c[w+1];var y=B.parentNode;y.replaceChild(u,B);u.appendChild(B);f<h&&(l[b+1]=B=N.createTextNode(A.substring(q,h)),y.insertBefore(B,u.nextSibling))}f=q;f>=h&&(b+=2);f>=k&&(w+=2)}}finally{g&&(g.style.display=a)}}catch(x){E.console&&console.log(x&&x.stack||x)}}var E=window,C=[\"break,continue,do,else,for,if,return,while\"],\nF=[[C,\"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\"],\"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof\"],H=[F,\"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,noexcept,noreturn,nullptr,property,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where\"],\nO=[F,\"abstract,assert,boolean,byte,extends,finally,final,implements,import,instanceof,interface,null,native,package,strictfp,super,synchronized,throws,transient\"],P=[F,\"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\"],\nF=[F,\"abstract,async,await,constructor,debugger,enum,eval,export,function,get,implements,instanceof,interface,let,null,set,undefined,var,with,yield,Infinity,NaN\"],Q=[C,\"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None\"],R=[C,\"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END\"],C=[C,\"case,done,elif,esac,eval,fi,function,in,local,set,then,until\"],\nS=/^(DIR|FILE|array|vector|(de|priority_)?queue|(forward_)?list|stack|(const_)?(reverse_)?iterator|(unordered_)?(multi)?(set|map)|bitset|u?(int|float)\\d*)\\b/,W=/\\S/,X=y({keywords:[H,P,O,F,\"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\",Q,R,C],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),I={};t(X,[\"default-code\"]);t(G([],[[\"pln\",/^[^<?]+/],[\"dec\",\n/^<!\\w[^>]*(?:>|$)/],[\"com\",/^<\\!--[\\s\\S]*?(?:-\\->|$)/],[\"lang-\",/^<\\?([\\s\\S]+?)(?:\\?>|$)/],[\"lang-\",/^<%([\\s\\S]+?)(?:%>|$)/],[\"pun\",/^(?:<[%?]|[%?]>)/],[\"lang-\",/^<xmp\\b[^>]*>([\\s\\S]+?)<\\/xmp\\b[^>]*>/i],[\"lang-js\",/^<script\\b[^>]*>([\\s\\S]*?)(<\\/script\\b[^>]*>)/i],[\"lang-css\",/^<style\\b[^>]*>([\\s\\S]*?)(<\\/style\\b[^>]*>)/i],[\"lang-in.tag\",/^(<\\/?[a-z][^<>]*>)/i]]),\"default-markup htm html mxml xhtml xml xsl\".split(\" \"));t(G([[\"pln\",/^[\\s]+/,null,\" \\t\\r\\n\"],[\"atv\",/^(?:\\\"[^\\\"]*\\\"?|\\'[^\\']*\\'?)/,null,\n\"\\\"'\"]],[[\"tag\",/^^<\\/?[a-z](?:[\\w.:-]*\\w)?|\\/?>$/i],[\"atn\",/^(?!style[\\s=]|on)[a-z](?:[\\w:-]*\\w)?/i],[\"lang-uq.val\",/^=\\s*([^>\\'\\\"\\s]*(?:[^>\\'\\\"\\s\\/]|\\/(?=\\s)))/],[\"pun\",/^[=<>\\/]+/],[\"lang-js\",/^on\\w+\\s*=\\s*\\\"([^\\\"]+)\\\"/i],[\"lang-js\",/^on\\w+\\s*=\\s*\\'([^\\']+)\\'/i],[\"lang-js\",/^on\\w+\\s*=\\s*([^\\\"\\'>\\s]+)/i],[\"lang-css\",/^style\\s*=\\s*\\\"([^\\\"]+)\\\"/i],[\"lang-css\",/^style\\s*=\\s*\\'([^\\']+)\\'/i],[\"lang-css\",/^style\\s*=\\s*([^\\\"\\'>\\s]+)/i]]),[\"in.tag\"]);t(G([],[[\"atv\",/^[\\s\\S]+/]]),[\"uq.val\"]);t(y({keywords:H,\nhashComments:!0,cStyleComments:!0,types:S}),\"c cc cpp cxx cyc m\".split(\" \"));t(y({keywords:\"null,true,false\"}),[\"json\"]);t(y({keywords:P,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:S}),[\"cs\"]);t(y({keywords:O,cStyleComments:!0}),[\"java\"]);t(y({keywords:C,hashComments:!0,multiLineStrings:!0}),[\"bash\",\"bsh\",\"csh\",\"sh\"]);t(y({keywords:Q,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),[\"cv\",\"py\",\"python\"]);t(y({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\",\nhashComments:!0,multiLineStrings:!0,regexLiterals:2}),[\"perl\",\"pl\",\"pm\"]);t(y({keywords:R,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[\"rb\",\"ruby\"]);t(y({keywords:F,cStyleComments:!0,regexLiterals:!0}),[\"javascript\",\"js\",\"ts\",\"typescript\"]);t(y({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\",hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,\nregexLiterals:!0}),[\"coffee\"]);t(G([],[[\"str\",/^[\\s\\S]+/]]),[\"regex\"]);var Y=E.PR={createSimpleLexer:G,registerLangHandler:t,sourceDecorator:y,PR_ATTRIB_NAME:\"atn\",PR_ATTRIB_VALUE:\"atv\",PR_COMMENT:\"com\",PR_DECLARATION:\"dec\",PR_KEYWORD:\"kwd\",PR_LITERAL:\"lit\",PR_NOCODE:\"nocode\",PR_PLAIN:\"pln\",PR_PUNCTUATION:\"pun\",PR_SOURCE:\"src\",PR_STRING:\"str\",PR_TAG:\"tag\",PR_TYPE:\"typ\",prettyPrintOne:E.prettyPrintOne=function(a,d,f){f=f||!1;d=d||null;var b=document.createElement(\"div\");b.innerHTML=\"<pre>\"+a+\"</pre>\";\nb=b.firstChild;f&&L(b,f,!0);M({j:d,m:f,h:b,l:1,a:null,i:null,c:null,g:null});return b.innerHTML},prettyPrint:E.prettyPrint=function(a,d){function f(){for(var b=E.PR_SHOULD_USE_CONTINUATION?c.now()+250:Infinity;p<t.length&&c.now()<b;p++){for(var d=t[p],l=g,m=d;m=m.previousSibling;){var n=m.nodeType,u=(7===n||8===n)&&m.nodeValue;if(u?!/^\\??prettify\\b/.test(u):3!==n||/\\S/.test(m.nodeValue))break;if(u){l={};u.replace(/\\b(\\w+)=([\\w:.%+-]+)/g,function(a,b,c){l[b]=c});break}}m=d.className;if((l!==g||r.test(m))&&\n!e.test(m)){n=!1;for(u=d.parentNode;u;u=u.parentNode)if(q.test(u.tagName)&&u.className&&r.test(u.className)){n=!0;break}if(!n){d.className+=\" prettyprinted\";n=l.lang;if(!n){var n=m.match(w),C;!n&&(C=V(d))&&z.test(C.tagName)&&(n=C.className.match(w));n&&(n=n[1])}if(y.test(d.tagName))u=1;else var u=d.currentStyle,x=v.defaultView,u=(u=u?u.whiteSpace:x&&x.getComputedStyle?x.getComputedStyle(d,null).getPropertyValue(\"white-space\"):0)&&\"pre\"===u.substring(0,3);x=l.linenums;(x=\"true\"===x||+x)||(x=(x=m.match(/\\blinenums\\b(?::(\\d+))?/))?\nx[1]&&x[1].length?+x[1]:!0:!1);x&&L(d,x,u);M({j:n,h:d,m:x,l:u,a:null,i:null,c:null,g:null})}}}p<t.length?E.setTimeout(f,250):\"function\"===typeof a&&a()}for(var b=d||document.body,v=b.ownerDocument||document,b=[b.getElementsByTagName(\"pre\"),b.getElementsByTagName(\"code\"),b.getElementsByTagName(\"xmp\")],t=[],n=0;n<b.length;++n)for(var l=0,m=b[n].length;l<m;++l)t.push(b[n][l]);var b=null,c=Date;c.now||(c={now:function(){return+new Date}});var p=0,w=/\\blang(?:uage)?-([\\w.]+)(?!\\S)/,r=/\\bprettyprint\\b/,\ne=/\\bprettyprinted\\b/,y=/pre|xmp/i,z=/^code$/i,q=/^(?:pre|code|xmp)$/i,g={};f()}},H=E.define;\"function\"===typeof H&&H.amd&&H(\"google-code-prettify\",[],function(){return Y})})();}()\n"
  },
  {
    "path": "static/connect/tests/test.html",
    "content": "<html>\n  <head>\n    <title>Test harness for Code City: Client</title>\n\n    <script>\n      window.TEST = true;\n    </script>\n    <script src=\"../common.js\"></script>\n    <script src=\"../log.js\"></script>\n    <script src=\"../world.js\"></script>\n    <script src=\"test.js\"></script>\n\n    <script>\n      // Counters for unit test results.\n      var test_good = 0;\n      var test_bad = 0;\n\n      // If expected and actual are the identical, print 'Ok', otherwise 'Fail!'\n      function assertEquals(expected, actual, msg) {\n        if (msg === undefined) {\n          // msg is optional.\n          msg = 'Expected: \\'' + expected + '\\' Actual: \\'' + actual + '\\'';\n        }\n        if (expected === actual) {\n          document.write('<div class=\"ok\">Ok</div>');\n          test_good++;\n          return true;\n        } else {\n          document.write('<div class=\"fail\">Fail!</div>');\n          msg = msg.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n          document.write('<code>' + msg + '</code><BR>');\n          test_bad++;\n          return false;\n        }\n      }\n\n      function assertTrue(msg, actual) {\n        return assertEquals(msg, true, actual);\n      }\n\n      function assertFalse(msg, actual) {\n        return assertEquals(msg, false, actual);\n      }\n\n      function runTests() {\n        // Find all 'test' functions.\n        var tests = Object.getOwnPropertyNames(window).filter(\n            function(name) {return /^test[A-Z]/.test(name)});\n        for (var x = 0; x < tests.length; x++) {\n          document.write('<h3>' + tests[x] + ':</h3>');\n          window[tests[x]]();\n        }\n      }\n    </script>\n\n    <style>\n      div.ok {\n        color: #090;\n      }\n      div.fail {\n        color: #900;\n        font-size: bigger;\n      }\n    </style>\n  </head>\n\n  <body>\n    <h1>Test harness for Code City: Connect</h1>\n\n    <script>\n      var startTime = Date.now();\n      runTests();\n      var endTime = Date.now();\n      document.write('<h3>Done.</h3>');\n      document.write('<p>Tests passed: ' + test_good + '<br>Tests failed: ' + test_bad + '</p>');\n      document.write('<p>Total time: ' + (endTime - startTime) + ' ms</p>');\n    </script>\n  </body>\n</html>\n"
  },
  {
    "path": "static/connect/tests/test.js",
    "content": "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Tests for Integrated Development Environment for Code City.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\n// common.js\n\nfunction testCommonEscapeSpaces() {\n  // Escape strings with whitespace into non-collapsable HTML strings.\n  assertEquals('a\\u00A0 \\u00A0 b', CCC.Common.escapeSpaces('a    b'));\n  assertEquals('\\u00A0a\\u00A0 \\u00A0 \\u00A0 \\u00A0 b', CCC.Common.escapeSpaces(' a\\tb'));\n}\n\n// log.js\n\nfunction testLogGetTemplate() {\n  // Fetch a template string from HTML\n  // <span id=\"testTemplate\">%1 kicks %2.</span>\n  var span = document.createElement('span');\n  span.id = 'testTemplate';\n  span.innerHTML = '%1 kicks %2.';\n  document.body.appendChild(span);\n  try {\n    var df = CCC.Log.getTemplate(span.id, 'Max', 'Fido');\n  } finally {\n    document.body.removeChild(span);\n  }\n  // Render the DocumentFragment.\n  var div = document.createElement('div');\n  div.appendChild(df);\n  assertEquals('Max kicks Fido.', div.innerHTML);\n}\n\n// world.js\n\nfunction testWorldGetTemplate() {\n  // Fetch a template string from HTML\n  // <span id=\"testTemplate\">Today is a good day to die.</span>\n  var span = document.createElement('span');\n  span.id = 'testTemplate';\n  span.innerHTML = 'Today is a good day to die.';\n  document.body.appendChild(span);\n  try {\n    var text = CCC.World.getTemplate(span.id);\n  } finally {\n    document.body.removeChild(span);\n  }\n  assertEquals('Today is a good day to die.', text);\n}\n\nfunction testWorldWrap() {\n  var svg = CCC.Common.createSvgElement('svg', {'xmlns:xlink': 'http://www.w3.org/1999/xlink'}, document.body);\n  svg.scaledHeight_ = 100;\n  svg.scaledWidth_ = 200;\n  try {\n    var wrapped = CCC.World.wrap(svg, 'Alpha Bravo Charlie Delta Echo', 10, 100000);\n  } finally {\n    document.body.removeChild(svg);\n  }\n  assertEquals('Alpha \\nBravo \\nCharlie \\nDelta \\nEcho', wrapped);\n}\n"
  },
  {
    "path": "static/connect/world.css",
    "content": "body {\n  font-family: 'Patrick Hand', 'Comic Sans MS';\n  margin: 0;\n  overflow: hidden;\n}\n\n.historyPanel {\n  border: 2px solid #444;\n  border-radius: 2px;\n  display: inline-block;\n  margin: 5px 5px 0 5px;\n  overflow: hidden;\n}\n\n#panoramaDiv {\n  border: 2px solid #444;\n  border-radius: 2px;\n  height: 295px;\n  margin: 5px 6px 0 5px;\n  overflow: hidden;\n}\n\n#iframeStorage>iframe {\n  border: none;\n  left: 0;\n  position: absolute;\n  top: 0;\n}\n\n.iframeClose:hover {\n  opacity: 1;\n}\n\n.iframeClose {\n  cursor: pointer;\n  position: absolute;\n  margin-left: -16px;\n  margin-top: -5px;\n  opacity: .7;\n  z-index: 1;\n}\n\n.iframeRelaunch {\n  cursor: pointer;\n}\n\n.iframeRelaunch:hover>text {\n  fill: #f00;\n}\n\n.iframeRelaunch>rect {\n  fill: #222;\n}\n\n.iframeRelaunch>text {\n  fill: #ccc;\n  text-anchor: middle;\n  alignment-baseline: middle;\n}\n\n.iframeRelaunch:hover>text {\n  fill: #fff;\n}\n\n.iframeRelaunch:hover>rect {\n  fill: #000;\n}\n\n.htmlPanel {\n  height: 100%;\n  overflow: auto;\n}\n\n.connectDiv {\n  background-color: #0a0;\n}\n\n.disconnectDiv {\n  background-color: #d00;\n}\n\n.connectDiv, .disconnectDiv {\n  color: #fff;\n  text-align: center;\n}\n\n.connectionIcon {\n  display: block;\n  height: 48px;\n  margin-left: auto;\n  margin-top: 80px;\n  margin-right: auto;\n  opacity: .7;\n  width: 48px;\n}\n\n.connectionIcon[src$=\"#reload\"]:hover {\n  cursor: pointer;\n  opacity: 1;\n}\n\n.systemTime {\n  margin-top: 60px;\n  text-align: center;\n}\n\n.sceneBackground {\n  stroke: #888;\n}\n\n.bubbleBG {\n  fill: #000;\n  stroke: none;\n}\n\n.bubbleFG {\n  fill: #fff;\n  stroke: none;\n}\n\n.bubbleArrow {\n  fill: #fff;\n}\n\ng.say {\n  text-anchor: middle;\n}\n\na.disabled {\n  color: #444;\n  cursor: no-drop;\n  text-decoration: underline dotted #444;\n}\n"
  },
  {
    "path": "static/connect/world.js",
    "content": "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview World frame of Code City's client.\n * @author fraser@google.com (Neil Fraser)\n */\n'use strict';\n\nCCC.World = {};\n\n\n/**\n * Maximum number of messages saved in history.\n */\nCCC.World.maxHistorySize = 10000;\n\n/**\n * Messages in the history panels.\n */\nCCC.World.historyMessages = [];\n\n/**\n * Messages in the panorama panel.\n */\nCCC.World.panoramaMessages = [];\n\n/**\n * Height of history panels.\n * @constant\n */\nCCC.World.panelHeight = 256;\n\n/**\n * Width of planned history panels.\n */\nCCC.World.panelWidths = [];\n\n/**\n * Width of panel borders (must match CSS).\n * @constant\n */\nCCC.World.panelBorder = 2;\n\n/**\n * Div containing a partial row of history panels (null if new row needed).\n * @type {Element}\n */\nCCC.World.historyRow = null;\n\n/**\n * PID of rate-limiter for resize events.\n */\nCCC.World.resizePid = 0;\n\n/**\n * The last recorded screen width.  Used to determine if a resize event resulted\n * in a change of width.\n */\nCCC.World.lastWidth = NaN;\n\n/**\n * SVG scratchpad for rendering potential history panels.\n * @type {Element}\n */\nCCC.World.scratchHistory = null;\n\n/**\n * SVG scratchpad for rendering potential panorama panels.\n * @type {Element}\n */\nCCC.World.scratchPanorama = null;\n\n/**\n * Width of a scrollbar.  Computed once at startup.\n */\nCCC.World.scrollBarWidth = NaN;\n\n/**\n * Record of the current scene.\n * @type {Object}\n */\nCCC.World.scene = null;\n\n/**\n * Initialization code called on startup.\n */\nCCC.World.init = function() {\n  CCC.Common.init();\n  CCC.World.scrollDiv = document.getElementById('scrollDiv');\n  CCC.World.panoramaDiv = document.getElementById('panoramaDiv');\n  CCC.World.scrollBarWidth = CCC.World.getScrollBarWidth();\n  CCC.World.scene = {};  // Blank scene.\n  delete CCC.World.getScrollBarWidth;  // Free memory.\n\n  window.addEventListener('resize', CCC.World.resizeSoon, false);\n};\n\n/**\n * Receive messages from our parent frame.\n * @param {!Event} e Incoming message event.\n */\nCCC.World.receiveMessage = function(e) {\n  var data = CCC.Common.verifyMessage(e);\n  if (!data) {\n    return;\n  }\n  var mode = data['mode'];\n  var text = data['text'];\n  if (mode === CCC.Common.MessageTypes.CLEAR) {\n    // Clear all content, except for the 'Reconnect?' panel (if it exists).\n    document.getElementById('iframeStorage').innerHTML = '';\n    CCC.World.historyMessages.length = 0;\n    var firstPanoramaMessage = CCC.World.panoramaMessages[0];\n    if (firstPanoramaMessage && firstPanoramaMessage.type === 'connected' &&\n        !firstPanoramaMessage.isConnected) {\n      // Clear the date/time on the 'Reconnect?' panel (if it exists).\n      firstPanoramaMessage.time = '...';\n    } else {\n      CCC.World.panoramaMessages.length = 0;\n    }\n    CCC.World.removeNode(CCC.World.scratchHistory);\n    CCC.World.removeNode(CCC.World.scratchPanorama);\n    var scene = CCC.World.scene;  // Save the scene.\n    CCC.World.renderHistory();\n    CCC.World.scene = scene;  // Restore the scene.\n  } else if (mode === CCC.Common.MessageTypes.BLUR) {\n      CCC.Common.closeMenu();\n  } else if (mode === CCC.Common.MessageTypes.CONNECTION) {\n    CCC.Common.setConnected(data['state']);\n  } else if (mode === CCC.Common.MessageTypes.CONNECT_MSG) {\n    // Notify the user of the connection.\n    CCC.World.renderMessage({type: 'connected',\n                             isConnected: true,\n                             time: data['text']});\n  } else if (mode === CCC.Common.MessageTypes.DISCONNECT_MSG) {\n    // Notify the user of the disconnection.\n    CCC.World.renderMessage({type: 'connected',\n                             isConnected: false,\n                             time: data['text']});\n  } else if (mode === CCC.Common.MessageTypes.MEMO) {\n    try {\n      var msg = JSON.parse(text);\n    } catch (e) {\n      // Not valid JSON, treat as string literal.\n      msg = {type: 'narrate', text: text};\n    }\n    CCC.World.preprocessMessage(msg);\n    CCC.World.renderMessage(msg);\n  }\n};\n\n/**\n * Parse the message and deal with any chunks that need one-time processing.\n * @param {*} msg JSON structure, or component thereof.\n */\nCCC.World.preprocessMessage = function(msg) {\n  if (Array.isArray(msg)) {\n    for (var singleMsg of msg) {\n      CCC.World.preprocessMessage(singleMsg);\n    }\n    return;\n  }\n  if (typeof msg === 'object' && msg !== null) {\n    for (var prop in msg) {\n      CCC.World.preprocessMessage(msg[prop]);\n    }\n\n    // Text too large for a bubble should be in an HTML frame.\n    if ((msg.type === 'say' || msg.type === 'think' || msg.type === 'narrate') &&\n        msg.text.length > 800) {\n      // TODO: Render say/think text in log form:  Bob says, \"Blah blah...\"\n      var text = msg.text;\n      // Transform this memo into an HTML frame.\n      for (prop in msg) {\n        delete msg[prop];\n      }\n      msg.type = 'html';\n      text = CCC.Common.escapeSpaces(text.replace(/&/g, '&amp;')\n          .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\\n/g, '<br>'));\n      msg.htmlText = text;\n    }\n\n    // Find all stringified SVG props and replace them with actual SVG props.\n    if ('svgText' in msg) {\n      var svgDom = CCC.World.stringToSvg(msg.svgText);\n      if (svgDom) {\n        msg.svgDom = svgDom;\n      }\n      delete msg.svgText;\n    }\n\n    // Find all stringified HTML props and replace them with actual HTML props.\n    if ('htmlText' in msg) {\n      var htmlDom = CCC.World.stringToHtml(msg.htmlText);\n      if (htmlDom) {\n        msg.htmlDom = htmlDom;\n      }\n      delete msg.htmlText;\n    }\n\n    // Find all iframes and create DOM elements for them.\n    if (msg.type === 'iframe') {\n      // {type: \"iframe\", url: \"https://example.com/foo\", alt: \"Alt text\"}\n      msg.iframeId = CCC.World.createIframe(msg.url);\n    }\n\n    // Move the current user to the start of the room contents list.\n    if (msg.type === 'scene' && msg.user && msg.contents) {\n      for (var i = 1, content; (content = msg.contents[i]); i++) {\n        if (content.type === 'user' && content.what === msg.user) {\n          msg.contents.unshift(msg.contents.splice(i, 1)[0]);\n        }\n      }\n    }\n  }\n};\n\n/**\n * Render a message to the panorama panel, optionally triggering a history push.\n * @param {!Object} memo JSON structure.\n */\nCCC.World.renderMessage = function(memo) {\n  if (memo.type === 'link') {\n    // {type: \"link\", href: \"https://example.com/\"}\n    // Link is opened by log.  No visualization in world.\n    return;\n  }\n  if (isNaN(CCC.World.lastWidth)) {\n    // Race condition, message has arrived before world is ready to render.\n    // Just add to the panorama queue, it will be rendered later.\n    CCC.World.panoramaMessages.push(memo);\n    return;\n  }\n\n  if (memo.type === 'scene' && memo.user) {\n    // This is the user's current location.  Save this environment data.\n    CCC.World.scene = memo;\n  }\n  // Unrequested scenes should only show if either there is no immediately\n  // following message (within half a second), or the following message is\n  // something other than say/think/narrate.\n  if (memo.type === 'scene' && !memo.requested) {\n    memo.requested = true;\n    CCC.World.renderMessage.pendingSceneMsg_ = memo;\n    clearTimeout(CCC.World.renderMessage.pendingScenePid_);\n    CCC.World.renderMessage.pendingScenePid_ = setTimeout(function() {\n        // No following message arrived.  Render scene change.\n        CCC.World.renderMessage(memo);\n      }, 500);\n    return;\n  }\n  if (memo.type === 'say' || memo.type === 'think' || memo.type === 'narrate' ||\n      memo.type === 'scene') {\n    // Throw away any pending scene change since say/think/narrate will show\n    // the updated scene.\n    CCC.World.renderMessage.pendingSceneMsg_ = null;\n    clearTimeout(CCC.World.renderMessage.pendingScenePid_);\n  }\n  if (CCC.World.renderMessage.pendingSceneMsg_) {\n    // Show any pending scene before the current message.\n    CCC.World.renderMessage(CCC.World.renderMessage.pendingSceneMsg_);\n    CCC.World.renderMessage.pendingSceneMsg_ = null;\n    clearTimeout(CCC.World.renderMessage.pendingScenePid_);\n  }\n\n  if (!CCC.World.panelWidths.length) {\n    CCC.World.panelWidths = CCC.World.rowWidths();\n  }\n\n  var backupScratchHistory =\n      CCC.World.scratchHistory && CCC.World.scratchHistory.cloneNode(true);\n  if (CCC.World.prerenderHistory(memo) && CCC.World.prerenderPanorama(memo)) {\n    // Rendering successful in both panorama and pending history panel.\n    CCC.World.panoramaMessages.push(memo);\n    CCC.World.publishPanorama();\n  } else {\n    // Failure to render.  Publish the previous history, and start fresh.\n    CCC.World.removeNode(CCC.World.scratchHistory);\n    CCC.World.removeNode(CCC.World.scratchPanorama);\n    CCC.World.scratchHistory = null;\n    CCC.World.scratchPanorama = null;\n    // Publish one panel to the history.\n    CCC.World.publishHistory(backupScratchHistory);\n    // Move all panorama messages into history.\n    Array.prototype.push.apply(CCC.World.historyMessages,\n                               CCC.World.panoramaMessages);\n    CCC.World.panoramaMessages.length = 0;\n    // Try again.\n    CCC.World.renderMessage(memo);\n  }\n};\n\nCCC.World.renderMessage.pendingSceneMsg_ = null;\nCCC.World.renderMessage.pendingScenePid_ = 0;\n\n/**\n * Experimentally render a new message onto the most recent history frame.\n * @param {!Object} memo JSON structure.\n * @return {boolean} True if the message fit.  False if overflow.\n */\nCCC.World.prerenderHistory = function(memo) {\n  if (memo.type === 'iframe') {\n    if (CCC.World.scratchHistory) {\n      return false;  // Every iframe needs to be in its own panel.\n    }\n    // Create relaunch button if iframe is closed.\n    var svg = CCC.World.createHiddenSvg(CCC.World.panelWidths[0],\n                                        CCC.World.panelHeight);\n    svg.style.backgroundColor = '#696969';\n    svg.setAttribute('data-iframe-id', memo.iframeId);\n    var g = CCC.Common.createSvgElement('g',\n        {'class': 'iframeRelaunch',\n         'transform': 'translate(0, 50)',\n         'data-iframe-src': memo.url}, svg);\n    // Add relaunch button.\n    var rect = document.createElementNS(CCC.Common.NS, 'rect');\n    var text = document.createElementNS(CCC.Common.NS, 'text');\n    text.appendChild(document.createTextNode(\n        CCC.World.getTemplate('relaunchIframeTemplate')));\n    g.appendChild(rect);\n    g.appendChild(text);\n    // Size the rectangle to match the text size.\n    var bBox = text.getBBox();\n    var r = Math.min(bBox.height, bBox.width) / 2;\n    rect.setAttribute('height', bBox.height);\n    rect.setAttribute('width', bBox.width + 2 * r);\n    rect.setAttribute('x', bBox.x - r);\n    rect.setAttribute('y', bBox.y);\n    rect.setAttribute('rx', r);\n    rect.setAttribute('ry', r);\n    CCC.World.scratchHistory = svg;\n    return true;\n  }\n\n  if (memo.type === 'html') {\n    if (CCC.World.scratchHistory) {\n      return false;  // Every htmlframe needs to be in its own panel.\n    }\n    var div = CCC.World.createHiddenDiv();\n    CCC.World.cloneAndAppend(div, memo.htmlDom);\n    CCC.World.scratchHistory = div;\n    return true;\n  }\n\n  if (memo.type === 'connected') {\n    if (CCC.World.scratchHistory) {\n      return false;  // Every connect/disconnect needs to be in its own panel.\n    }\n    var div = CCC.World.createHiddenDiv();\n    div.appendChild(CCC.World.connectPanel(memo));\n    CCC.World.scratchHistory = div;\n    return true;\n  }\n\n  if (memo.type === 'scene') {\n    //{\n    //  type: \"scene\",\n    //  requested: true,\n    //  user: \"Max\",\n    //  where: \"Hangout\",\n    //  description: \"The lights are dim and blah blah blah...\",\n    //  svgText: \"...\",\n    //  contents: [\n    //    {\n    //      type: \"user\",\n    //      what: \"Max\",\n    //      svgText: \"...\",\n    //      cmds: [\"look Max\", \"kick Max\"]\n    //    },\n    //    {\n    //      type: \"thing\",\n    //      what: \"clock\",\n    //      svgText: \"...\",\n    //      cmds: [\"look clock\"]\n    //    }\n    //  ]\n    //}\n    // Each scene message needs its own frame.\n    if (CCC.World.scratchHistory) {\n      return false;\n    }\n    memo = CCC.World.sceneDescription(memo);\n  }\n\n  // If bubbles can be merged, attempt to do so.\n  var merge = CCC.World.mergeBubbles(CCC.World.scratchHistory, memo);\n  if (merge !== undefined) {\n    return merge;\n  }\n\n  // For now every message needs its own frame.\n  if (CCC.World.scratchHistory) {\n    return false;\n  }\n  var svg = CCC.World.scratchHistory;\n  if (!svg) {\n    svg = CCC.World.createHiddenSvg(CCC.World.panelWidths[0],\n                                    CCC.World.panelHeight);\n    CCC.World.drawScene(svg);\n  }\n  if (memo.type === 'say' || memo.type === 'think' || memo.type === 'narrate') {\n    CCC.World.createBubble(memo, svg);\n  }\n\n  CCC.World.scratchHistory = svg;\n  return true;\n};\n\n/**\n * Experimentally render a new message onto the panorama frame.\n * @param {!Object} memo JSON structure.\n * @return {boolean} True if the message fit.  False if overflow.\n */\nCCC.World.prerenderPanorama = function(memo) {\n  if (memo.type === 'iframe') {\n    if (CCC.World.scratchPanorama) {\n      return false;  // Every iframe needs to be in its own panel.\n    }\n    var svg = CCC.World.createHiddenSvg(CCC.World.panoramaDiv.offsetWidth,\n                                        CCC.World.panoramaDiv.offsetHeight);\n    svg.setAttribute('data-iframe-id', memo.iframeId);\n    CCC.World.scratchPanorama = svg;\n    return true;\n  }\n\n  if (memo.type === 'html') {\n    if (CCC.World.scratchPanorama) {\n      return false;  // Every htmlframe needs to be in its own panel.\n    }\n    var div = CCC.World.createHiddenDiv();\n    CCC.World.cloneAndAppend(div, memo.htmlDom);\n    CCC.World.scratchPanorama = div;\n    return true;\n  }\n\n  if (memo.type === 'connected') {\n    if (CCC.World.scratchPanorama) {\n      return false;  // Every connect/disconnect needs to be in its own panel.\n    }\n    var div = CCC.World.createHiddenDiv();\n    div.appendChild(CCC.World.connectPanel(memo));\n    CCC.World.scratchPanorama = div;\n    return true;\n  }\n\n  if (memo.type === 'scene') {\n    memo = CCC.World.sceneDescription(memo);\n  }\n\n  // If bubbles can be merged, attempt to do so.\n  var merge = CCC.World.mergeBubbles(CCC.World.scratchPanorama, memo);\n  if (merge !== undefined) {\n    return merge;\n  }\n\n  // For now every message needs its own frame.\n  if (CCC.World.scratchPanorama) {\n    return false;\n  }\n  var svg = CCC.World.scratchPanorama;\n  if (!svg) {\n    var svg = CCC.World.createHiddenSvg(CCC.World.panoramaDiv.offsetWidth,\n                                        CCC.World.panoramaDiv.offsetHeight);\n    CCC.World.drawScene(svg);\n  }\n  if (memo.type === 'say' || memo.type === 'think' || memo.type === 'narrate') {\n    CCC.World.createBubble(memo, svg);\n  }\n\n  CCC.World.scratchPanorama = svg;\n  return true;\n};\n\n/**\n * Create a panel for a connection/disconnection event.\n * @param {!Object} memo Object containing connection/disconnection mode and\n *   date/time of event.\n * @return {!DocumentFragment} Document fragment containing rendered panel.\n */\nCCC.World.connectPanel = function(memo) {\n  var isConnected = memo.isConnected;\n  var df = document.createDocumentFragment();\n  var div = document.createElement('div');\n  div.className = isConnected ? 'connectDiv' : 'disconnectDiv';\n  var text = CCC.World.getTemplate(\n      isConnected ? 'connectedTemplate' : 'disconnectedTemplate');\n  div.appendChild(document.createTextNode(text));\n  df.appendChild(div);\n\n  var img = document.createElement('img');\n  img.className = 'connectionIcon';\n  img.src = STATIC_URL + 'connect/connectionIcons.svg' +\n      (isConnected ? '#connect' : '#reload');\n  df.appendChild(img);\n\n  div = document.createElement('div');\n  div.className = 'systemTime';\n  div.appendChild(document.createTextNode(memo.time));\n  df.appendChild(div);\n\n  return df;\n};\n\n/**\n *\n * @param {!SVGElement} svg SVG element in which to draw the background.\n * @param {!Object} memo JSON structure.\n * @return {?boolean} True if merged, false if overflow, undefined if no match.\n */\nCCC.World.mergeBubbles = function(svg, memo) {\n  var previousMessage =\n      CCC.World.panoramaMessages[CCC.World.panoramaMessages.length - 1];\n  if (!svg || !previousMessage || previousMessage.type !== memo.type ||\n      previousMessage.source !== memo.source ||\n      previousMessage.where !== memo.where) {\n    return undefined;  // Current message not a match with previous message.\n  }\n  // Remove previous bubble.\n  svg.removeChild(svg.lastBubbleText_);\n  svg.removeChild(svg.lastBubbleGroup_);\n  // Try to add a merged bubble.\n  var mergedNode = {};\n  for (var prop in memo) {\n    mergedNode[prop] = memo[prop];\n  }\n  mergedNode.text = svg.lastPlainText_ + '\\n' + memo.text;\n  CCC.World.createBubble(mergedNode, svg);\n\n  // If the merged bubble is too big, reject the merge.\n  var bBox = CCC.World.getBBoxWithTransform(svg.lastBubbleText_);\n  var bottom = bBox.y + bBox.height - 2;  // -2 for the border.\n  var anchor = CCC.World.getAnchor(memo, svg);\n  var limitY = anchor ? 100 - anchor.headY - anchor.headR : 100;\n  return bottom < limitY;\n};\n\n/**\n * Forge a text message with the room name and description.\n * @param {!Object} memo JSON structure.\n * @return {Object} Text message to render, or empty object if no message.\n */\nCCC.World.sceneDescription = function(memo) {\n  var title = memo.where;\n  if (typeof title !== 'string') {\n    return {};\n  }\n  // Render title with HTML collapsing space rules.\n  title = title.replace(/\\s+/g, ' ');\n  var text = [title];\n  var description = memo.description;\n  if (description) {\n    text.push(description);\n  }\n  text = text.join('\\n');\n  return {type: 'narrate', text: text, where: title};\n};\n\n/**\n * Draw the currently recorded scene background into the provided SVG.\n * @param {!SVGElement} svg SVG element in which to draw the background.\n */\nCCC.World.drawSceneBackground = function(svg) {\n  var svgDom = CCC.World.scene.svgDom;\n  if (svgDom) {\n    var g = CCC.Common.createSvgElement('g',\n        {'class': 'sceneBackground'}, svg);\n    CCC.World.cloneAndAppend(g, svgDom);\n  }\n};\n\n\n/**\n * Draw the users and objects in the currently recorded scene.\n * @param {!SVGElement} svg SVG element in which to draw the users and objects.\n */\nCCC.World.drawScene = function(svg) {\n  CCC.World.drawSceneBackground(svg);\n  // Obtain an ordered list of contents.\n  var contentsArray = CCC.World.scene.contents;\n  if (contentsArray) {\n    var userTotal = 0;\n      for (var i = 0; i < contentsArray.length; i++) {\n        userTotal += contentsArray[i].type === 'user';\n      }\n    svg.sceneUserLocations = Object.create(null);\n    svg.sceneObjectLocations = Object.create(null);\n    // Draw each item.\n    var icons = [];\n    var userCount = 0;\n    for (var i = 0, thing; (thing = contentsArray[i]); i++) {\n      var cursorX = (i + 1) / (contentsArray.length + 1) * svg.scaledWidth_ -\n          svg.scaledWidth_ / 2;\n      var bBox = null;\n      var isUser = thing.type === 'user';\n      var svgDom = thing.svgDom;\n      if (svgDom && svgDom.firstChild) {\n        var name = thing.what;\n        var g = CCC.Common.createSvgElement('g', {'class': thing.type}, svg);\n        var title = CCC.Common.createSvgElement('title', {}, g);\n        title.appendChild(document.createTextNode(name));\n        // TODO: Reenable whiteShadow.\n        // whiteShadow disabled due to clipping bugs.\n        //g.setAttribute('filter', 'url(#' + svg.whiteShadowId_ + ')');\n        CCC.World.cloneAndAppend(g, svgDom);\n        // Users should face the majority of other users.\n        // If user is alone, should face majority of objects.\n        if (isUser && (userTotal === 1 ?\n            (i > 0 && i >= Math.floor(contentsArray.length / 2)) :\n            (userCount > 0 && userCount >= Math.floor(userTotal / 2)))) {\n          // Wrap mirrored users in an extra group.\n          var g2 = CCC.Common.createSvgElement('g', {}, svg);\n          g.setAttribute('transform', 'scale(-1,1)');\n          g2.appendChild(g);\n          g = g2;\n        }\n        // Move the sprite into position.\n        bBox = g.getBBox();\n        var dx = cursorX - bBox.x - (bBox.width / 2);\n        g.setAttribute('transform', 'translate(' + dx + ', 0)');\n        // Record location of each user for positioning of speech bubbles.\n        var radius = Math.min(bBox.height, bBox.width) / 2;\n        var location = {\n          headX: cursorX,\n          headY: bBox.y + radius,\n          headR: radius\n        };\n        if (isUser) {\n          svg.sceneUserLocations[name] = location;\n        } else {\n          svg.sceneObjectLocations[name] = location;\n        }\n      }\n      var cmds = thing.cmds;\n      if (cmds) {\n        var iconSize = 6;\n        var x = cursorX - iconSize / 2;\n        var y = isUser ? 40 : 60;\n        if (bBox) {\n          // Align menu icon with top-right corner of user's sprite.\n          x = Math.min(cursorX + bBox.width / 2,\n                       svg.scaledWidth_ / 2 - iconSize);\n          y = Math.max(0, bBox.y);\n        }\n        var icon = CCC.Common.newMenuIcon(cmds);\n        icon.setAttribute('width', iconSize);\n        icon.setAttribute('height', iconSize);\n        icon.setAttribute('viewBox', '0 0 10 10');\n        icon.setAttribute('x', x);\n        icon.setAttribute('y', y);\n        icons.push(icon);\n      }\n      if (isUser) {\n        userCount++;\n      }\n    }\n    // Menu icons should be added after all the sprites so that they aren't\n    // occluded by user content.\n    for (var icon of icons) {\n      svg.appendChild(icon);\n    }\n  }\n};\n\n/**\n * Write text in a bubble.\n * @param {!Object} memo JSON structure.\n * @param {!SVGElement} svg SVG Element to place the text and bubble.\n */\nCCC.World.createBubble = function(memo, svg) {\n  // {type: \"say\", text: \"Welcome\"}\n  // {type: \"say\", source: \"Max\", where: \"Hangout\", text: \"Hello world.\"}\n  // {type: \"say\", source: \"Cat\", where: \"Hangout\", text: \"Meow.\"}\n  // {type: \"think\", text: \"Don't be evil.\"}\n  // {type: \"think\", source: \"Max\", where: \"Hangout\", text: \"I'm hungry.\"}\n  // {type: \"think\", source: \"Cat\", where: \"Hangout\", text: \"I'm evil.\"}\n  // {type: \"narrate\", text: \"Command not recognized.\"}\n  // {type: \"narrate\", where: \"Hangout\", text: \"Hangout is dark.\"}\n  // {type: \"narrate\", source: \"Max\", where: \"Hangout\", text: \"Max smiles.\"}\n  // {type: \"narrate\", source: \"Cat\", where: \"Hangout\", text: \"Cat meows.\"}\n  var source = memo.source;\n  var where = memo.where;\n  var text = memo.text || '';\n  var width = memo.type === 'narrate' ? 150 : 100;\n  width = Math.min(svg.scaledWidth_, width);\n  var textGroup = CCC.World.createTextArea(svg, text, width, 30);\n  textGroup.setAttribute('class', memo.type);\n  var bubbleGroup = CCC.Common.createSvgElement('g', {'class': 'bubble'}, svg);\n  if (source) {\n    var title = CCC.Common.createSvgElement('title', {}, bubbleGroup);\n    title.appendChild(document.createTextNode(source));\n    var title = CCC.Common.createSvgElement('title', {}, textGroup);\n    title.appendChild(document.createTextNode(source));\n  }\n  svg.appendChild(textGroup);\n  var textBBox = textGroup.getBBox();\n\n  var anchor = CCC.World.getAnchor(memo, svg);\n  if (!anchor && where && where === CCC.World.scene.where) {\n    // This text box is coming from the room, not a user or object.\n    // A bit of a hack: place anchor under box.\n    anchor = {headX: 1 - svg.scaledWidth_ / 2, headY: 2, headR: 0};\n  }\n\n  // Align the text above the user.\n  var cursorX = anchor ? anchor.headX : 0;\n  // Don't overflow the right edge.\n  cursorX = Math.min(cursorX, svg.scaledWidth_ / 2 - textBBox.width / 2 - 1);\n  // Don't overflow the left edge.\n  cursorX = Math.max(cursorX, textBBox.width / 2 - svg.scaledWidth_ / 2 + 1);\n  cursorX -= textBBox.x + textBBox.width / 2;\n  textGroup.setAttribute('transform', 'translate(' + cursorX + ', 2)');\n  CCC.World.drawBubble(memo.type, bubbleGroup, textGroup, anchor);\n  // Record the appended DOM elements so that they may be removed if more\n  // text needs to be appended.\n  svg.lastBubbleGroup_ = bubbleGroup;\n  svg.lastBubbleText_ = textGroup;\n  svg.lastPlainText_ = text;\n};\n\n/**\n * Find the location of the actor who is initiating a bubble.\n * @param {!Object} memo JSON structure.\n * @param {!SVGElement} svg SVG Element to place the text and bubble.\n * @return {Object} Provides headX, headY, and headR properties.\n */\nCCC.World.getAnchor = function(memo, svg) {\n  var anchor = null;\n  try {\n    if ((memo.where && memo.where === CCC.World.scene.where) || memo.source) {\n      anchor = svg.sceneUserLocations[memo.source] ||\n               svg.sceneObjectLocations[memo.source];\n    }\n  } catch (e) {\n    // No anchor.  Simpler to try/catch than to check every step.\n  }\n  return anchor;\n};\n\n/**\n * Return the object's bounding box, compensating for any transform-translate.\n * @param {!Element} element Element to measure.\n * @return {!Object} Height, width, x and y.\n */\nCCC.World.getBBoxWithTransform = function(element) {\n  var bBox = element.getBBox();\n  // getBBox doesn't look at element's transform=\"translate(...)\".\n  var transform = element.getAttribute('transform');\n  var r = transform && transform.match(\n      /translate\\(\\s*([-+\\d.e]+)([ ,]\\s*([-+\\d.e]+)\\s*\\))?/);\n  if (r) {\n    bBox.x += parseFloat(r[1]);\n    if (r[3]) {\n      bBox.y += parseFloat(r[3]);\n    }\n  }\n  return bBox;\n};\n\n/**\n * Draw a bubble around some content.\n * @param {!string} type Type of bubble: 'say' or 'text'.\n * @param {!SVGElement} bubbleGroup Empty group to render the bubble in.\n * @param {!SVGElement} contentGroup Group to surround.\n * @param {Object} opt_anchor Optional anchor location for arrow tip.\n */\nCCC.World.drawBubble = function(type, bubbleGroup, contentGroup, opt_anchor) {\n  // Find coordinates of the contents.\n  var contentBBox = CCC.World.getBBoxWithTransform(contentGroup);\n  // Draw a solid black bubble, then the arrow (with border), then a slightly\n  // smaller solid white bubble, resulting in a clean border.\n  if (type === 'think') {\n    var strokeWidth = 0.7;  // Matches with CSS.\n    var radiusXAverage = 4;  // Target size of cloud puffs.\n    var radiusYAverage = 3;  // Target size of cloud puffs.\n    var radiusVariation = 0.5;  // Cloud puffs can be + or - this amount.\n    var inflateRadius = 1;  // Expand the radii a bit to make less jagged.\n    // Pick a radius that's within the standard variation.\n    var randomRadius = function(r) {\n      return r + (Math.random() - 0.5) * radiusVariation * 2;\n    };\n    // Create a horizontal or vertical line of puff descriptors.\n    var puffLine = function(x, y, dx, dy) {\n      var d = Math.max(dx, dy);\n      var radiusAverage = (d === dx) ? radiusXAverage : radiusYAverage;\n      var line = new Array(Math.round(d / radiusAverage / 2));\n      radiusAverage = d / line.length / 2;\n      for (var i = 0; i < line.length - 1; i += 2) {\n        line[i] = randomRadius(radiusAverage);\n        line[i + 1] = radiusAverage * 2 - line[i];\n      }\n      if (line[line.length - 1] === undefined) {\n        // There was an odd number of puffs.  Add the remaining orphan.\n        line[line.length - 1] = radiusAverage;\n      }\n      CCC.World.shuffle(line);\n      var cursor = (d === dx) ? x : y;\n      for (var i = 0; i < line.length; i++) {\n        var r = line[i];\n        var puff;\n        if (d === dx) {\n          puff = {\n            rx: r,\n            ry: randomRadius(radiusYAverage),\n            cx: cursor + r,\n            cy: y\n          };\n          cursor += puff.rx * 2;\n        } else {\n          puff = {\n            rx: randomRadius(radiusXAverage),\n            ry: r,\n            cx: x,\n            cy: cursor + r\n          };\n          cursor += puff.ry * 2;\n        }\n        line[i] = puff;\n      }\n      return line;\n    };\n\n    var puffs = [];\n    // Top edge.\n    puffs = puffs.concat(puffLine(inflateRadius, inflateRadius,\n        contentBBox.width - 2 * inflateRadius, 0));\n    // Right edge.\n    puffs = puffs.concat(puffLine(contentBBox.width - inflateRadius,\n        inflateRadius, 0, contentBBox.height - 2 * inflateRadius));\n    // Bottom edge.\n    puffs = puffs.concat(puffLine(inflateRadius, contentBBox.height -\n        inflateRadius, contentBBox.width - 2 * inflateRadius, 0));\n    // Left edge.\n    puffs = puffs.concat(puffLine(inflateRadius, inflateRadius, 0,\n        contentBBox.height - 2 * inflateRadius));\n    if (!puffs.length) {\n      // Empty thought bubble.  Add one puff.\n      puffs[0] = {rx: radiusXAverage, ry: radiusYAverage, cx: 0, cy: 0};\n    }\n    if (contentBBox.height > 2 * inflateRadius &&\n        contentBBox.width > 2 * inflateRadius) {\n      CCC.Common.createSvgElement('rect',\n          {'class': 'bubbleBG',\n           'x': inflateRadius - strokeWidth, 'y': inflateRadius - strokeWidth,\n           'height': contentBBox.height + 2 * strokeWidth - 2 * inflateRadius,\n           'width': contentBBox.width + 2 * strokeWidth - 2 * inflateRadius},\n           bubbleGroup);\n    }\n    for (var puff of puffs) {\n      CCC.Common.createSvgElement('ellipse',\n          {'class': 'bubbleBG',\n           'cx': puff.cx, 'cy': puff.cy,\n           'rx': puff.rx + inflateRadius + strokeWidth,\n           'ry': puff.ry + inflateRadius + strokeWidth},\n           bubbleGroup);\n    }\n    if (contentBBox.height > 2 * inflateRadius &&\n        contentBBox.width > 2 * inflateRadius) {\n      CCC.Common.createSvgElement('rect',\n          {'class': 'bubbleFG',\n           'x': inflateRadius, 'y': inflateRadius,\n           'height': contentBBox.height - 2 * inflateRadius,\n           'width': contentBBox.width - 2 * inflateRadius},\n           bubbleGroup);\n    }\n    for (var puff of puffs) {\n      CCC.Common.createSvgElement('ellipse',\n          {'class': 'bubbleFG',\n           'cx': puff.cx, 'cy': puff.cy,\n           'rx': puff.rx + inflateRadius, 'ry': puff.ry + inflateRadius},\n           bubbleGroup);\n    }\n    if (opt_anchor) {\n      bubbleGroup.appendChild(\n          CCC.World.drawArrow_(contentBBox, opt_anchor, true));\n    }\n  } else {\n    if (type === 'say') {\n      var strokeWidth = 0.7;  // Matches with CSS.\n      var marginV = 2;\n      var marginH = 6;\n      var radius = 15;\n    } else {\n      var strokeWidth = 0.4;\n      var marginV = 1;\n      var marginH = 2;\n      var radius = 0.5;\n    }\n    CCC.Common.createSvgElement('rect',\n        {'class': 'bubbleBG',\n         'x': -marginH - strokeWidth, 'y': -marginV - strokeWidth,\n         'rx': radius + strokeWidth, 'ry': radius + strokeWidth,\n         'height': contentBBox.height + 2 * (marginV + strokeWidth),\n         'width': contentBBox.width + 2 * (marginH + strokeWidth)},\n         bubbleGroup);\n    if (opt_anchor) {\n      bubbleGroup.appendChild(\n          CCC.World.drawArrow_(contentBBox, opt_anchor, false));\n    }\n    CCC.Common.createSvgElement('rect',\n        {'class': 'bubbleFG',\n         'x': -marginH, 'y': -marginV,\n         'rx': radius, 'ry': radius,\n         'height': contentBBox.height + 2 * marginV,\n         'width': contentBBox.width + 2 * marginH},\n         bubbleGroup);\n  }\n  bubbleGroup.setAttribute('transform', 'translate(' + contentBBox.x +\n      ', ' + contentBBox.y + ')');\n};\n\n/**\n * Draw the arrow between the bubble and the origin.\n * @param {!Object} contentBBox Dimensions of the bubble's contents.\n * @param {!Object} anchor Anchor location for arrow tip.\n * @param {boolean} thought True if a thought bubble, false for solid arrow.\n * @return {!Element} Path for arrow.\n * @private\n */\nCCC.World.drawArrow_ = function(contentBBox, anchor, thought) {\n  // Find the relative coordinates of the center of the bubble.\n  var relBubbleX = contentBBox.width / 2;\n  var relBubbleY = contentBBox.height / 2;\n  // Find the relative coordinates of the center of the anchor.\n  var relAnchorX = anchor.headX - contentBBox.x;\n  var relAnchorY = anchor.headY - contentBBox.y;\n  if (relBubbleX === relAnchorX && relBubbleY === relAnchorY) {\n    // Null case.  Bubble is directly on top of the anchor.\n    // Short circuit this rather than wade through divide by zeros.\n    return CCC.Common.createSvgElement('g', {}, null);\n  }\n  // Compute the angle of the arrow's line.\n  var rise = relAnchorY - relBubbleY;\n  var run = relAnchorX - relBubbleX;\n  var hypotenuse = Math.sqrt(rise * rise + run * run);\n  var angle = Math.acos(run / hypotenuse);\n  if (rise < 0) {\n    angle = 2 * Math.PI - angle;\n  }\n  // Compute a line perpendicular to the arrow.\n  var rightAngle = angle + Math.PI / 2;\n  if (rightAngle > Math.PI * 2) {\n    rightAngle -= Math.PI * 2;\n  }\n  var rightRise = Math.sin(rightAngle);\n  var rightRun = Math.cos(rightAngle);\n\n  // Calculate the thickness of the base of the arrow.\n  var thickness = (contentBBox.width + contentBBox.height) /\n                  CCC.World.ARROW_THICKNESS;\n  thickness = Math.min(thickness, contentBBox.width, contentBBox.height) / 4;\n\n  // Back the tip of the arrow off of the anchor.\n  var backoffRatio = 1 - (anchor.headR + 5) / hypotenuse;\n  relAnchorX = relBubbleX + backoffRatio * run;\n  relAnchorY = relBubbleY + backoffRatio * rise;\n\n  // Distortion to curve the arrow.\n  var swirlAngle = angle + Math.random() - 0.5;\n  if (swirlAngle > Math.PI * 2) {\n    swirlAngle -= Math.PI * 2;\n  }\n  var swirlRise = Math.sin(swirlAngle) * hypotenuse / CCC.World.ARROW_BEND;\n  var swirlRun = Math.cos(swirlAngle) * hypotenuse / CCC.World.ARROW_BEND;\n\n  if (thought) {\n    var group = CCC.Common.createSvgElement('g', {class: 'fillWhite'}, null);\n    // The commented out code below is a guide path to verify the placement of\n    // the thought bubbles which make up the arrow.\n    //var d = 'M' + relBubbleX + ',' + relBubbleY +\n    //    ' Q' + (relBubbleX + swirlRun) + ',' + (relBubbleY + swirlRise) +\n    //    ' ' + relAnchorX + ',' + relAnchorY;\n    //CCC.Common.createSvgElement('path', {'d': d}, group);\n    /**\n     * Given two x/y points, find the point at the specified distance between.\n     * @param {number} x1 Horizontal position of first point.\n     * @param {number} y1 Vertical position of first point.\n     * @param {number} x2 Horizontal position of second point.\n     * @param {number} y2 Vertical position of second point.\n     * @param {number} t Interpolation distance (0.0 - 1.0).\n     * @return {!Object} Contains x and y properties.\n     */\n    var interpolate = function(x1, y1, x2, y2, t) {\n      var x = t * (x2 - x1) + x1;\n      var y = t * (y2 - y1) + y1;\n      return {x: x, y: y};\n    };\n    // Pythagorean theorem for approximate length of arrow\n    // (doesn't count the added length caused by the bend).\n    var length = Math.sqrt(Math.pow(relBubbleX - relAnchorX, 2) +\n                           Math.pow(relBubbleY - relAnchorY, 2));\n    var t = 0;\n    while (t < 1) {\n      // Add a little bubble on the arrow's path.\n      // Compute point on a quadratic curve.\n      var q1 = interpolate(relBubbleX, relBubbleY,\n                           relBubbleX + swirlRun, relBubbleY + swirlRise, t);\n      var q2 = interpolate(relBubbleX + swirlRun, relBubbleY + swirlRise,\n                           relAnchorX, relAnchorY, t);\n      var p = interpolate(q1.x, q1.y, q2.x, q2.y, t);\n      // The bubble's radius gets smaller as one gets closer to the anchor.\n      var ry = (1 - t) * 2 + 1;\n      if (p.y > contentBBox.height + ry) {\n        CCC.Common.createSvgElement('ellipse',\n            {'rx': ry * 1.5, 'ry': ry, 'cx': p.x, 'cy': p.y}, group);\n        // Place next bubble three radii away from this bubble.\n        t += 3 * ry / length;\n      } else {\n        // Skip this bubble, since it is over the main thought bubble.\n        t += 0.1;\n      }\n    }\n    return group;\n  } else {\n    // Coordinates for the base of the arrow.\n    var baseX1 = relBubbleX + thickness * rightRun;\n    var baseY1 = relBubbleY + thickness * rightRise;\n    var baseX2 = relBubbleX - thickness * rightRun;\n    var baseY2 = relBubbleY - thickness * rightRise;\n\n    var steps = ['M' + baseX1 + ',' + baseY1];\n    steps.push('C' + (baseX1 + swirlRun) + ',' + (baseY1 + swirlRise) +\n               ' ' + relAnchorX + ',' + relAnchorY +\n               ' ' + relAnchorX + ',' + relAnchorY);\n    steps.push('C' + relAnchorX + ',' + relAnchorY +\n               ' ' + (baseX2 + swirlRun) + ',' + (baseY2 + swirlRise) +\n               ' ' + baseX2 + ',' + baseY2);\n    steps.push('z');\n    return CCC.Common.createSvgElement('path',\n            {'class': 'bubbleArrow', 'd': steps.join(' ')}, null);\n  }\n};\n\n/**\n * Determines the thickness of the base of the arrow in relation to the size\n * of the bubble.  Higher numbers result in thinner arrows.\n */\nCCC.World.ARROW_THICKNESS = 5;\n\n/**\n * The sharpness of the arrow's bend.  Higher numbers result in smoother arrows.\n */\nCCC.World.ARROW_BEND = 4;\n\n/**\n * Publish the previously experimentally rendered history frame to the user.\n * @param {!Element} historyElement Rendered history panel.\n */\nCCC.World.publishHistory = function(historyElement) {\n  if (!CCC.World.historyRow) {\n    var rowDiv = document.createElement('div');\n    rowDiv.className = 'historyRow';\n    CCC.World.scrollDiv.insertBefore(rowDiv, CCC.World.panoramaDiv);\n    CCC.World.historyRow = rowDiv;\n  }\n  var width = CCC.World.panelWidths.shift();\n  var panelDiv = document.createElement('div');\n  panelDiv.className = 'historyPanel';\n  panelDiv.style.height = CCC.World.panelHeight + 'px';\n  panelDiv.style.width = width + 'px';\n  CCC.World.historyRow.appendChild(panelDiv);\n  panelDiv.appendChild(historyElement);\n  CCC.World.stripActions(panelDiv);\n  var iframeId = historyElement.getAttribute('data-iframe-id');\n  if (iframeId) {\n    var iframe = document.getElementById(iframeId);\n    CCC.World.positionIframe(iframe, panelDiv);\n    // Add <img height=21 width=21 src=\"close.png\" title=\"Close iframe\">\n    var closeImg = new Image(21, 21);\n    closeImg.className = 'iframeClose';\n    closeImg.src = STATIC_URL + 'connect/close.png';\n    closeImg.title = CCC.World.getTemplate('closeIframeTemplate');\n    closeImg.addEventListener('click', function() {\n      closeImg.style.display = 'none';\n      panelDiv.firstChild.style.visibility = 'visible';  // SVG.\n      CCC.World.removeNode(iframe);\n    }, false);\n    // Add event handler on <g class=\"iframeRelaunch\"> element.\n    var group = panelDiv.querySelector('g.iframeRelaunch');\n    group.addEventListener('click', function() {\n      var iframeSrc = group.getAttribute('data-iframe-src');\n      iframeId = CCC.World.createIframe(iframeSrc);\n      iframe = document.getElementById(iframeId);\n      var div = historyElement.parentNode;\n      CCC.World.positionIframe(iframe, div);\n      div.firstChild.style.visibility = 'hidden';  // SVG.\n      div.lastChild.style.display = 'inline';  // Close button.\n    }, false);\n    panelDiv.appendChild(closeImg);\n  } else {\n    CCC.World.svgZoom(historyElement);\n    // The occasional (non-iframe) panel should lack a border.\n    var connectDiv = historyElement.firstChild &&\n        historyElement.firstChild.className === 'connectDiv';\n    if (!connectDiv && (Math.random() < 1 / 16)) {\n      panelDiv.style.borderColor = '#fff';\n    }\n    // While being built, the SVG was hidden.\n    // Make it visible, unless there is an iframe displayed on top of it.\n    historyElement.style.visibility = 'visible';\n  }\n  CCC.World.scrollDiv.scrollTop = CCC.World.scrollDiv.scrollHeight;\n\n  if (!CCC.World.panelWidths.length) {\n    CCC.World.historyRow = null;  // Next row.\n  }\n};\n\n/**\n * Publish the previously experimentally rendered panorama frame to the user.\n */\nCCC.World.publishPanorama = function() {\n  // Destroy any existing content.\n  while (CCC.World.panoramaDiv.firstChild) {\n    CCC.World.panoramaDiv.removeChild(CCC.World.panoramaDiv.firstChild);\n  }\n  // Insert new content.\n  var content = CCC.World.scratchPanorama.cloneNode(true);\n  CCC.World.panoramaDiv.appendChild(content);\n  var iframeId = content.getAttribute('data-iframe-id');\n  if (iframeId) {\n    var iframe = document.getElementById(iframeId);\n    CCC.World.positionIframe(iframe, CCC.World.panoramaDiv);\n  } else {\n    content.style.visibility = 'visible';\n    CCC.World.svgZoom(content);\n    // Add event handlers on all <a class=\"command\"> links.\n    var commands = content.querySelectorAll('a.command');\n    for (var command of commands) {\n      command.addEventListener('click', CCC.Common.commandFunction, false);\n    }\n    // Add event handlers on all <svg class=\"menuIcon\"> menus.\n    var menus = content.querySelectorAll('svg.menuIcon');\n    for (var menu of menus) {\n      menu.addEventListener('click', CCC.Common.openMenu, false);\n    }\n    // Add an event handler to a reload icon.\n    var icon = content.querySelector('.connectionIcon[src$=\"#reload\"]');\n    if (icon) {\n      icon.addEventListener('click',\n          parent.location.reload.bind(parent.location));\n      icon.title = CCC.World.getTemplate('reconnectTemplate');\n    }\n  }\n};\n\n/**\n * Find all SVG images with viewBox=\"0 0 0 0\" attribute and resize them to fit.\n * @param {!Element} container DOM node for panel.\n */\nCCC.World.svgZoom = function(container) {\n  var svgNodes = container.getElementsByTagName('svg');\n  for (var svg of svgNodes) {\n    var viewBox = svg.getAttribute('viewBox');\n    if (viewBox && viewBox.match(/^\\s*0\\s+0\\s+0\\s+0\\s*$/)) {\n      //var outerSize = svg.getBoundingClientRect();\n      var bBox = svg.getBBox();\n      var height = bBox.height + 1; // Add half the stroke width to each side.\n      var width = bBox.width + 1;\n      var x = bBox.x - 0.5;\n      var y = bBox.y - 0.5;\n      svg.setAttribute('viewBox', x + ' ' + y + ' ' + width + ' ' + height);\n    }\n  }\n};\n\n/**\n * Absolutely position an iframe so that it fits exactly inside a comic panel.\n * @param {!Element} iframe DOM node for iframe.\n * @param {!Element} container DOM node for panel.\n */\nCCC.World.positionIframe = function(iframe, container) {\n  var borderWidth = 2;\n  iframe.style.width = (container.offsetWidth - borderWidth * 2) + 'px';\n  iframe.style.height = (container.offsetHeight - borderWidth * 2) + 'px';\n  var x = 0;\n  var y = 0;\n  do {\n    x += container.offsetLeft;\n    y += container.offsetTop;\n  } while ((container = container.offsetParent) &&\n           (container !== CCC.World.scrollDiv));\n  iframe.style.top = (y + borderWidth) + 'px';\n  iframe.style.left = (x + borderWidth) + 'px';\n};\n\n/**\n * Strip all command links and menus.  History panels should not be interactive.\n * @param {!Element} div History panel div.\n */\nCCC.World.stripActions = function(div) {\n  var menus = div.querySelectorAll('svg.menuIcon');\n  for (var menu of menus) {\n    menu.parentNode.removeChild(menu);\n  }\n  var commands = div.querySelectorAll('a.command');\n  for (var command of commands) {\n    command.className = 'disabled';\n  }\n};\n\n/**\n * Create a blank, hidden SVG.\n * @param {number} width Width of panel in pixels.\n * @param {number} height Height of panel in pixels.\n * @return {!SVGElement} SVG element.\n */\nCCC.World.createHiddenSvg = function(width, height) {\n  var svg = CCC.Common.createSvgElement('svg',\n      {'xmlns:xlink': 'http://www.w3.org/1999/xlink'}, document.body);\n  svg.style.visibility = 'hidden';\n  // Compute the scaled height and width and save on private properties.\n  width -= CCC.World.panelBorder * 2;\n  height -= CCC.World.panelBorder * 2;\n  svg.scaledHeight_ = 100;\n  svg.scaledWidth_ = width / height * svg.scaledHeight_;\n  svg.setAttribute('viewBox', [-svg.scaledWidth_ / 2, 0,\n                               svg.scaledWidth_, svg.scaledHeight_].join(' '));\n  /*\n  <filter id=\"whiteShadow25501663536281627\" filterUnits=\"userSpaceOnUse\">\n    <feFlood result=\"flood\" flood-color=\"#fff\" flood-opacity=\"1\" />\n    <feComposite in=\"flood\" result=\"mask\" in2=\"SourceGraphic\" operator=\"in\" />\n    <feMorphology in=\"mask\" result=\"dilated\" operator=\"dilate\" radius=\"4\" />\n    <feGaussianBlur in=\"dilated\" result=\"blurred\" stdDeviation=\"2\" />\n    <feMerge>\n      <feMergeNode in=\"blurred\" />\n      <feMergeNode in=\"SourceGraphic\" />\n    </feMerge>\n  </filter>\n  */\n  // Filters cannot be shared between SVGs, doing so can even crash browsers.\n  // https://bugs.webkit.org/show_bug.cgi?id=149613\n  var id = 'whiteShadow' + String(Math.random()).substring(2);\n  svg.whiteShadowId_ = id;\n  var filter = CCC.Common.createSvgElement('filter',\n      {'id': id, 'filterUnits': 'userSpaceOnUse'}, svg);\n  CCC.Common.createSvgElement('feFlood',\n      {'result': 'flood', 'flood-color': '#fff', 'flood-opacity': 1}, filter);\n  CCC.Common.createSvgElement('feComposite',\n      {'in': 'flood', 'result': 'mask', 'in2': 'SourceGraphic',\n      'operator': 'in'}, filter);\n  CCC.Common.createSvgElement('feMorphology',\n      {'in': 'mask', 'result': 'dilated', 'operator': 'dilate', 'radius': 1},\n      filter);\n  CCC.Common.createSvgElement('feGaussianBlur',\n      {'in': 'dilated', 'result': 'blurred', 'stdDeviation': 5}, filter);\n  var feMerge = CCC.Common.createSvgElement('feMerge', {}, filter);\n  CCC.Common.createSvgElement('feMergeNode', {'in': 'blurred'}, feMerge);\n  CCC.Common.createSvgElement('feMergeNode', {'in': 'SourceGraphic'}, feMerge);\n  return svg;\n};\n\n/**\n * Create a blank, hidden div.\n * @return {!Element} Div element.\n */\nCCC.World.createHiddenDiv = function() {\n  var div = document.createElement('div');\n  div.className = 'htmlPanel';\n  div.style.visibility = 'hidden';\n  document.body.appendChild(div);\n  return div;\n};\n\n/**\n * Instantiate an iframe based on a message.\n * @param {string} src URL of target.\n * @return {string} The iframe's UUID.\n */\nCCC.World.createIframe = function(src) {\n  var iframe = document.createElement('iframe');\n  iframe.id = 'iframe' +  (Math.random() + '').substring(2);\n  iframe.sandbox = 'allow-forms allow-scripts allow-same-origin';\n  iframe.src = src;\n  document.getElementById('iframeStorage').appendChild(iframe);\n  return iframe.id;\n};\n\n\n/**\n * Buffer temporally close resize events.\n * Called when the window changes size.\n */\nCCC.World.resizeSoon = function() {\n  // First resize should call function immediately,\n  // subsequent ones should throttle resizing reflows.\n  if (CCC.World.resizePid) {\n    clearTimeout(CCC.World.resizePid);\n    CCC.World.resizePid = setTimeout(CCC.World.resizeNow, 1000);\n  } else {\n    CCC.World.resizeNow();\n    CCC.World.resizePid = -1;\n  }\n};\n\n/**\n * Rerender the history and the panorama panels.\n * Called when the window changes size.\n */\nCCC.World.resizeNow = function() {\n  var width = CCC.World.scrollDiv.offsetWidth;\n  if (width === CCC.World.lastWidth) {\n    // Width hasn't changed.  Maybe just the height changed.  Snap to bottom.\n    CCC.World.scrollDiv.scrollTop = CCC.World.scrollDiv.scrollHeight;\n    return;\n  }\n  CCC.World.lastWidth = width;\n  CCC.World.renderHistory();\n};\n\n/**\n * Rerender entire history.\n * Called when the window changes size.\n */\nCCC.World.renderHistory = function() {\n  // Destroy all existing history.\n  var historyRows = document.getElementsByClassName('historyRow');\n  while (historyRows[0]) {\n    CCC.World.removeNode(historyRows[0]);\n  }\n  while (CCC.World.panoramaDiv.firstChild) {\n    CCC.World.panoramaDiv.removeChild(CCC.World.panoramaDiv.firstChild);\n  }\n  CCC.World.panelWidths.length = 0;\n  CCC.World.historyRow = null;\n  CCC.World.scratchHistory = null;\n  CCC.World.scratchPanorama = null;\n  CCC.World.scene = {};\n  // Create new history.\n  var msgs = CCC.World.historyMessages.concat(CCC.World.panoramaMessages);\n  CCC.World.historyMessages.length = 0;\n  CCC.World.panoramaMessages.length = 0;\n  for (var msg of msgs) {\n    CCC.World.renderMessage(msg);\n  }\n  CCC.World.scrollDiv.scrollTop = CCC.World.scrollDiv.scrollHeight;\n};\n\n/**\n * Given the current window width, assign the number and widths of panels on\n * one history row.\n * @return {!Array.<number>} Array of lengths.\n */\nCCC.World.rowWidths = function() {\n  // Margin and border widths must match the CSS.\n  var panelBloat = 2 * (5 + CCC.World.panelBorder);\n  var windowWidth = CCC.World.lastWidth - CCC.World.scrollBarWidth - 1;\n  var idealWidth = CCC.World.panelHeight * 5 / 4;  // Standard TV ratio.\n  var panelCount = Math.round(windowWidth / idealWidth);\n  var averageWidth = Math.floor(windowWidth / panelCount);\n  var smallWidth = Math.round(averageWidth * 0.9);\n  var largeWidth = averageWidth * 2 - smallWidth;\n  averageWidth -= panelBloat;\n  smallWidth -= panelBloat;\n  largeWidth -= panelBloat;\n  // Build an array of lengths.  Add in matching pairs.\n  var panels = [];\n  for (var i = 0; i < Math.floor(panelCount / 2); i++) {\n    if (Math.random() > 0.5) {\n      panels.push(averageWidth, averageWidth);\n    } else {\n      panels.push(smallWidth, largeWidth);\n    }\n  }\n  // Odd number of panels has one in the middle.\n  if (panels.length < panelCount) {\n    panels.push(averageWidth);\n  }\n  CCC.World.shuffle(panels);\n  return panels;\n};\n\n/**\n * Shuffles the values in the specified array using the Fisher-Yates in-place\n * shuffle (also known as the Knuth Shuffle).\n * Copied from Google Closure's goog.array.shuffle\n * @param {!Array} arr The array to be shuffled.\n */\nCCC.World.shuffle = function(arr) {\n for (var i = arr.length - 1; i > 0; i--) {\n    // Choose a random array index in [0, i] (inclusive with i).\n    var j = Math.floor(Math.random() * (i + 1));\n    var tmp = arr[i];\n    arr[i] = arr[j];\n    arr[j] = tmp;\n  }\n};\n\n/**\n * Unserialize stringified HTML.  Wrap the HTML elements in a body.\n * @param {string} svgText '<p>Hello</p>'\n * @return {Element} <body><p>Hello</p></body>\n */\nCCC.World.stringToHtml = function(htmlText) {\n  var dom = CCC.Common.parser.parseFromString(htmlText, 'text/html');\n  if (!dom.body) {\n    // Not valid XML.\n    console.log('Syntax error in HTML: ' + htmlText);\n    return null;\n  }\n  var body = CCC.World.xmlToHtml(dom.body);\n  CCC.Common.autoHyperlink(body);\n  return body;\n};\n\n/**\n * Convert an XML tree into an HTML tree.\n * Whitelist used for all elements and properties.\n * @param {!Element} dom XML tree.\n * @return {Element} HTML tree.\n */\nCCC.World.xmlToHtml = function(dom) {\n  if (!dom) {\n    return null;\n  }\n  switch (dom.nodeType) {\n    case Node.ELEMENT_NODE:\n      if (dom.tagName === 'svg') {  // XML tagNames are lowercase.\n        // Switch to SVG rendering mode.\n        return CCC.World.xmlToSvg(dom);\n      }\n      if (dom.tagName === 'CMDS') {  // HTML tagNames are uppercase.\n        return CCC.Common.newMenuIcon(dom);\n      }\n      if (dom.tagName === 'CMD') {  // HTML tagNames are uppercase.\n        var cmdText = dom.innerText;\n        var a = document.createElement('a');\n        a.className = 'command';\n        a.appendChild(document.createTextNode(cmdText));\n        return a;\n      }\n      if (CCC.World.xmlToHtml.ELEMENT_NAMES &&\n          !CCC.World.xmlToHtml.ELEMENT_NAMES.has(dom.tagName)) {\n        console.log('HTML element not in whitelist: <' + dom.tagName + '>');\n        return null;\n      }\n      var element = document.createElement(dom.tagName);\n      for (var attr of dom.attributes) {\n        if (CCC.World.xmlToHtml.ATTRIBUTE_NAMES &&\n            !CCC.World.xmlToHtml.ATTRIBUTE_NAMES.has(attr.name)) {\n          console.log('HTML attribute not in whitelist: ' +\n              '<' + dom.tagName + ' ' + attr.name + '=\"' + attr.value + '\">');\n        } else {\n          element.setAttribute(attr.name, attr.value);\n          // Remove all styles not in the whitelist.\n          if (attr.name === 'style') {\n            for (var name in element.style) {\n              if (element.style.hasOwnProperty(name) &&\n                  isNaN(parseFloat(name)) && // Don't delete indexed props.\n                  element.style[name] && element.style[name] !== 'initial' &&\n                  CCC.World.xmlToHtml.STYLE_NAMES &&\n                  !CCC.World.xmlToHtml.STYLE_NAMES.has(name)) {\n                console.log('Style attribute not in whitelist: ' +\n                    name + ': ' + element.style[name]);\n                element.style[name] = '';\n              }\n            }\n          }\n        }\n      }\n      for (var childDom of dom.childNodes) {\n        var childNode = CCC.World.xmlToHtml(childDom);\n        if (childNode) {\n          element.appendChild(childNode);\n        }\n      }\n      return element;\n    case Node.TEXT_NODE:\n      return document.createTextNode(dom.data);\n    case Node.COMMENT_NODE:\n      return null;\n  }\n  console.log('Unknown HTML node type: ' + dom);\n  return null;\n};\n\n/**\n * Whitelist of all allowed HTML element names.\n * 'svg' element is handled separately.\n * Set to null to disable filtering.\n */\nCCC.World.xmlToHtml.ELEMENT_NAMES = new Set([\n  'ABBR',\n  'ADDRESS',\n  'ARTICLE',\n  'ASIDE',\n  'B',\n  'BDI',\n  'BDO',\n  'BLOCKQUOTE',\n  'BODY',\n  'BR',\n  'CAPTION',\n  'CITE',\n  'CODE',\n  'COL',\n  'COLGROUP',\n  'DATA',\n  'DD',\n  'DEL',\n  'DFN',\n  'DIV',\n  'DL',\n  'DT',\n  'EM',\n  'FIELDSET',\n  'FIGCAPTION',\n  'FIGURE',\n  'FOOTER',\n  'H1', 'H2', 'H3', 'H4', 'H5', 'H6',\n  'HEADER',\n  'HGROUP',\n  'HR',\n  'I',\n  'INS',\n  'KBD',\n  'LEGEND',\n  'LI',\n  'MAIN',\n  'MARK',\n  'NAV',\n  'OL',\n  'P',\n  'PRE',\n  'Q',\n  'RP',\n  'RT',\n  'RTC',\n  'RUBY',\n  'S',\n  'SAMP',\n  'SECTION',\n  'SMALL',\n  'SPAN',\n  'STRONG',\n  'SUB',\n  'SUP',\n  'TABLE',\n  'TBODY',\n  'TD',\n  'TFOOT',\n  'TH',\n  'THEAD',\n  'TIME',\n  'TR',\n  'U',\n  'UL',\n  'VAR',\n  'WBR',\n]);\n\n/**\n * Whitelist of all allowed HTML property names.\n * This architecture assumes that there are no banned properties\n * on one element type which are allowed on another.\n * Set to null to disable filtering.\n */\nCCC.World.xmlToHtml.ATTRIBUTE_NAMES = new Set([\n  'cite',\n  'colspan',\n  'datetime',\n  'dir',\n  'headers',\n  'nowrap',\n  'reversed',\n  'rowspan',\n  'scope',\n  'span',\n  'start',\n  'style',\n  'title',\n  'type',\n  'value',\n]);\n\n/**\n * Whitelist of all allowed style property names.\n * Set to null to disable filtering.\n */\nCCC.World.xmlToHtml.STYLE_NAMES = new Set([\n  'border',\n  'borderBottom',\n  'borderBottomColor',\n  'borderBottomLeftRadius',\n  'borderBottomRightRadius',\n  'borderBottomStyle',\n  'borderBottomWidth',\n  'borderCollapse',\n  'borderColor',\n  'borderLeft',\n  'borderLeftColor',\n  'borderLeftStyle',\n  'borderLeftWidth',\n  'borderRadius',\n  'borderRight',\n  'borderRightColor',\n  'borderRightStyle',\n  'borderRightWidth',\n  'borderSpacing',\n  'borderStyle',\n  'borderTop',\n  'borderTopColor',\n  'borderTopLeftRadius',\n  'borderTopRightRadius',\n  'borderTopStyle',\n  'borderTopWidth',\n  'borderWidth',\n  'clear',\n  'direction',\n  'display',\n  'float',\n  'fontWeight',\n  'height',\n  'hyphens',\n  'padding',\n  'paddingBottom',\n  'paddingLeft',\n  'paddingRight',\n  'paddingTop',\n  'textAlign',\n  'verticalAlign',\n  'width',\n]);\n\n/**\n * Unserialize stringified SVG.  Wrap the SVG elements in an SVG.\n * @param {string} svgText '<rect /><circle r=\"5\" />'\n * @return {SVGSVGElement} <svg><rect /><circle r=\"5\" /></svg>\n */\nCCC.World.stringToSvg = function(svgText) {\n  var dom = CCC.Common.parser.parseFromString(\n      '<svg>' + svgText + '</svg>', 'image/svg+xml');\n  if (dom.getElementsByTagName('parsererror').length) {\n    // Not valid XML.\n    console.log('Syntax error in SVG: ' + svgText);\n    return null;\n  }\n  return CCC.World.xmlToSvg(dom.firstChild);\n};\n\n/**\n * Convert an XML tree into an SVG tree.\n * Whitelist used for all elements and properties.\n * @param {!Element} dom XML tree.\n * @return {SVGElement} SVG tree.\n */\nCCC.World.xmlToSvg = function(dom) {\n  if (!dom) {\n    return null;\n  }\n  switch (dom.nodeType) {\n    case Node.ELEMENT_NODE:\n      if (CCC.World.xmlToSvg.ELEMENT_NAMES &&\n          !CCC.World.xmlToSvg.ELEMENT_NAMES.has(dom.tagName)) {\n        console.log('SVG element not in whitelist: <' + dom.tagName + '>');\n        return null;\n      }\n      var svg = document.createElementNS(CCC.Common.NS, dom.tagName);\n      for (var attr of dom.attributes) {\n        if (CCC.World.xmlToSvg.ATTRIBUTE_NAMES &&\n            !CCC.World.xmlToSvg.ATTRIBUTE_NAMES.has(attr.name)) {\n          console.log('SVG attribute not in whitelist: ' +\n              '<' + dom.tagName + ' ' + attr.name + '=\"' + attr.value + '\">');\n        } else {\n          // Remove all styles not in the whitelist.\n          if (attr.name === 'class') {\n            var classes = attr.value.split(/\\s+/g);\n            for (var i = classes.length - 1; i >= 0; i--) {\n              if (CCC.World.xmlToSvg.CLASS_NAMES &&\n                  !CCC.World.xmlToSvg.CLASS_NAMES.has(classes[i])) {\n                console.log('Class name not in whitelist: ' + classes[i]);\n                classes.splice(i, 1);\n              }\n            }\n            attr.value = classes.join(' ');\n          }\n          svg.setAttribute(attr.name, attr.value);\n        }\n      }\n      for (var childDom of dom.childNodes) {\n        var childSvg = CCC.World.xmlToSvg(childDom);\n        if (childSvg) {\n          svg.appendChild(childSvg);\n        }\n      }\n      return svg;\n    case Node.TEXT_NODE:\n      return document.createTextNode(dom.data);\n    case Node.COMMENT_NODE:\n      return null;\n  }\n  console.log('Unknown XML node type: ' + dom);\n  return null;\n};\n\n/**\n * Whitelist of all allowed SVG element names.\n * Try to keep this list in sync with Code.svgEditor.ELEMENT_NAMES.\n * Set to null to disable filtering.\n */\nCCC.World.xmlToSvg.ELEMENT_NAMES = new Set([\n  'circle',\n  'desc',\n  'ellipse',\n  'g',\n  'line',\n  'path',\n  'polygon',\n  'polyline',\n  'rect',\n  'svg',\n  'text',\n  'title',\n  'tspan',\n]);\n\n/**\n * Whitelist of all allowed SVG property names.\n * This architecture assumes that there are no banned properties\n * on one element type which are allowed on another.\n * Set to null to disable filtering.\n */\nCCC.World.xmlToSvg.ATTRIBUTE_NAMES = new Set([\n  'class',\n  'cx',\n  'cy',\n  'd',\n  'dx',\n  'dy',\n  'height',\n  'lengthAdjust',\n  'points',\n  'r',\n  'rx',\n  'ry',\n  'text-anchor',\n  'textLength',\n  'transform',\n  'viewBox',\n  'x',\n  'x1',\n  'x2',\n  'y',\n  'y1',\n  'y2',\n  'width',\n]);\n\n/**\n * Whitelist of all allowed class names.\n * Set to null to disable filtering.\n */\nCCC.World.xmlToSvg.CLASS_NAMES = new Set([\n  'fillNone',\n  'fillWhite',\n  'fillBlack',\n  'fillGrey', 'fillGray',\n  'strokeNone',\n  'strokeWhite',\n  'strokeBlack',\n  'strokeGrey', 'strokeGray',\n]);\n\n/**\n * Clone a tree of elements, and append it as a new child onto a DOM.\n * @param {!Element} parent Parent DOM element.\n * @param {Element} container A disposable <body> or <svg> wrapper.\n */\nCCC.World.cloneAndAppend = function(parent, container) {\n  if (container) {\n    var clonedContianer = container.cloneNode(true);\n    while (clonedContianer.firstChild) {\n      parent.appendChild(clonedContianer.firstChild);\n    }\n  }\n};\n\n/**\n * Remove a node from the DOM.\n * @param {Node} node Node to remove, ok if null.\n */\nCCC.World.removeNode = function(node) {\n  if (node) {\n    node.parentNode.removeChild(node);\n  }\n};\n\n/**\n * Gets the template with the given key from the document.\n * @param {string} key The key of the document element.\n * @return {string} The textContent of the specified element.\n */\nCCC.World.getTemplate = function(key) {\n  var element = document.getElementById(key);\n  if (!element) {\n    throw new Error('Unknown template ' + key);\n  }\n  return element.textContent;\n};\n\n/**\n * Determine the width of scrollbars on this platform.\n * Code copied from https://stackoverflow.com/questions/8079187/\n * @return {number} Width in pixels.\n */\nCCC.World.getScrollBarWidth = function() {\n  var inner = document.createElement('p');\n  inner.style.width = '100%';\n  inner.style.height = '200px';\n\n  var outer = document.createElement('div');\n  outer.style.position = 'absolute';\n  outer.style.top = 0;\n  outer.style.left = 0;\n  outer.style.visibility = 'hidden';\n  outer.style.width = '200px';\n  outer.style.height = '150px';\n  outer.style.overflow = 'hidden';\n  outer.appendChild(inner);\n\n  document.body.appendChild(outer);\n  var w1 = inner.offsetWidth;\n  outer.style.overflow = 'scroll';\n  var w2 = inner.offsetWidth;\n  if (w1 === w2) {\n    w2 = outer.clientWidth;\n  }\n  document.body.removeChild(outer);\n\n  return w1 - w2;\n};\n\n/**\n * Create a block of text on SVG constrained to a given size.\n * @param {!SVGSVGElement} svg SVG element to use.\n * @param {string} text Text to create.\n * @param {number} width Maximum width.\n * @param {number} height Maximum height.\n * @return {!SVGElement} SVG group containing text.\n */\nCCC.World.createTextArea = function(svg, text, width, height) {\n  text = CCC.World.wrap(svg, text, width, height);\n  text = CCC.Common.escapeSpaces(text);\n  var lines = text.split('\\n');\n  var textNode = document.createElementNS(CCC.Common.NS, 'text');\n  textNode.setAttribute('alignment-baseline', 'hanging');\n  if (lines.length) {\n    var dy = CCC.World.measureText(svg, 'Wg').height;\n    for (var line of lines) {\n      if (line === '\\r' || line === '\\n') {\n        line = '\\u200B';  // Zero-width space.\n      }\n      var tspan = document.createElementNS(CCC.Common.NS, 'tspan');\n      tspan.appendChild(document.createTextNode(line));\n      tspan.setAttribute('x', 0);\n      tspan.setAttribute('dy', dy);\n      textNode.appendChild(tspan);\n    }\n  }\n  var g = document.createElementNS(CCC.Common.NS, 'g');\n  CCC.Common.autoHyperlink(textNode);\n  g.appendChild(textNode);\n  return g;\n};\n\n/**\n * Wrap text to the specified width.\n * @param {!SVGSVGElement} svg SVG element to use.\n * @param {string} text Text to wrap.\n * @param {number} width Maximum width.\n * @param {number} height Maximum height.\n * @return {string} Wrapped text.\n */\nCCC.World.wrap = function(svg, text, width, height) {\n  if (text.length > 1024) {\n    // This algorithm doesn't scale to large texts.\n    // Large texts shouldn't be in speech bubbles anyway.\n    return text;\n  }\n  var minWidth = width;\n  var maxWidth = svg.scaledWidth_ - 10;\n  var measuredWidth, measuredHeight;\n  var dy = CCC.World.measureText(svg, 'Wg').height;\n  function wrapForWidth(width) {\n    measuredWidth = 0;\n    measuredHeight = 0;\n    var paragraphs = text.split('\\n');\n    for (var i = 0; i < paragraphs.length; i++) {\n      paragraphs[i] = CCC.World.wrapLine_(svg, paragraphs[i], width);\n      var lines = paragraphs[i].split('\\n');\n      for (var line of lines) {\n        var size = CCC.World.measureText(svg, line);\n        measuredWidth = Math.max(measuredWidth, size.width);\n        measuredHeight += dy;\n      }\n    }\n    return paragraphs.join('\\n');\n  }\n  var wrappedText = wrapForWidth(width);\n  if (measuredHeight > height) {\n    // If overflowing on height, increase the width using a binary search.\n    // Do not exceed the full width of the SVG.\n    do {\n      if (measuredHeight > height) {\n        minWidth = width;\n        width = Math.round((maxWidth - width) / 2 + width);\n      } else {\n        maxWidth = width;\n        width = Math.round((width - minWidth) / 2 + minWidth);\n      }\n      wrappedText = wrapForWidth(width);\n    } while (maxWidth - minWidth > 10);\n    if (measuredHeight > height) {\n      wrappedText = wrapForWidth(maxWidth);\n    }\n  }\n  return wrappedText;\n};\n\n/**\n * Wrap single line of text to the specified width.\n * @param {!SVGSVGElement} svg SVG element to use.\n * @param {string} text Text to wrap.\n * @param {number} limit Width to wrap each line.\n * @return {string} Wrapped text.\n * @private\n */\nCCC.World.wrapLine_ = function(svg, text, limit) {\n  if (CCC.World.measureText(svg, text).width <= limit) {\n    // Short text, no need to wrap.\n    return text;\n  }\n  // Split the text into words.\n  var words = text.split(/\\b(?=\\w)/);\n  // Set limit to be the length of the largest word.\n  for (var word of words) {\n    limit = Math.max(CCC.World.measureText(svg, word).width, limit);\n  }\n  limit = Math.min(svg.scaledWidth_ - 5, limit);  // But not wider than panel.\n\n  var lastScore;\n  var score = -Infinity;\n  var lastText;\n  var lineCount = 1;\n  do {\n    lastScore = score;\n    lastText = text;\n    // Create a list of booleans representing if a space (false) or\n    // a break (true) appears after each word.\n    var wordBreaks = [];\n    // Seed the list with evenly spaced linebreaks.\n    var steps = words.length / lineCount;\n    var insertedBreaks = 1;\n    for (var i = 0; i < words.length - 1; i++) {\n      if (insertedBreaks < (i + 1.5) / steps) {\n        insertedBreaks++;\n        wordBreaks[i] = true;\n      } else {\n        wordBreaks[i] = false;\n      }\n    }\n    wordBreaks = CCC.World.wrapMutate_(svg, words, wordBreaks, limit);\n    score = CCC.World.wrapScore_(svg, words, wordBreaks, limit);\n    text = CCC.World.wrapToText_(words, wordBreaks);\n    lineCount++;\n  } while (score > lastScore);\n  return lastText;\n};\n\n/**\n * Compute a score for how good the wrapping is.\n * @param {!SVGSVGElement} svg SVG element to use.\n * @param {!Array.<string>} words Array of each word.\n * @param {!Array.<boolean>} wordBreaks Array of line breaks.\n * @param {number} limit Width to wrap each line.\n * @return {number} Larger the better.\n * @private\n */\nCCC.World.wrapScore_ = function(svg, words, wordBreaks, limit) {\n  // If this function becomes a performance liability, add caching.\n  // Compute the length of each line.\n  var lines = [[]];\n  for (var i = 0; i < words.length; i++) {\n    lines[lines.length - 1].push(words[i]);\n    if (wordBreaks[i] === true) {\n      lines.push([]);\n    }\n  }\n  var lineLengths = [];\n  for (var i = 0; i < lines.length; i++) {\n    lines[i] = lines[i].join('');\n    lineLengths.push(CCC.World.measureText(svg, lines[i]).width);\n  }\n\n  var score = 0;\n  for (var i = 0; i < lineLengths.length; i++) {\n    // Optimize for width.\n    if (lineLengths[i] > limit) {\n      // -1000 points per unit over limit.\n      score -= (lineLengths[i] - limit) * 1000;\n    } else {\n      // -1 point per unit under limit (scaled to the power of 1.5).\n      score -= Math.pow(Math.abs(limit - lineLengths[i]) * 1, 1.5);\n    }\n    // Optimize for structure.\n    // Add score to line endings after punctuation.\n    var lastLetter = lines[i].trim().slice(-1);\n    if ('.?!'.includes(lastLetter)) {\n      score += 6;\n    } else if (',;)]}'.includes(lastLetter)) {\n      score += 3;\n    }\n  }\n  // All else being equal, the last line should not be longer than the\n  // previous line.  For example, this looks wrong:\n  // aaa bbb\n  // ccc ddd eee\n  if (lineLengths.length > 1 && lineLengths[lineLengths.length - 1] <=\n      lineLengths[lineLengths.length - 2]) {\n    score += 5;\n  }\n  // Likewise, the first line should not be longer than the next line.\n  // An ideal bubble with centered text has the first and last lines shorter.\n  if (lineLengths.length > 2 && lineLengths[0] <= lineLengths[1]) {\n    score += 5;\n  }\n  return score;\n};\n\n/**\n * Mutate the array of line break locations until an optimal solution is found.\n * No line breaks are added or deleted, they are simply moved around.\n * @param {!SVGSVGElement} svg SVG element to use.\n * @param {!Array.<string>} words Array of each word.\n * @param {!Array.<boolean>} wordBreaks Array of line breaks.\n * @param {number} limit Width to wrap each line.\n * @return {!Array.<boolean>} New array of optimal line breaks.\n * @private\n */\nCCC.World.wrapMutate_ = function(svg, words, wordBreaks, limit) {\n  var bestScore = CCC.World.wrapScore_(svg, words, wordBreaks, limit);\n  var bestBreaks;\n  // Try shifting every line break forward or backward.\n  for (var i = 0; i < wordBreaks.length - 1; i++) {\n    if (wordBreaks[i] === wordBreaks[i + 1]) {\n      continue;\n    }\n    var mutatedWordBreaks = [].concat(wordBreaks);\n    mutatedWordBreaks[i] = !mutatedWordBreaks[i];\n    mutatedWordBreaks[i + 1] = !mutatedWordBreaks[i + 1];\n    var mutatedScore =\n        CCC.World.wrapScore_(svg, words, mutatedWordBreaks, limit);\n    if (mutatedScore > bestScore) {\n      bestScore = mutatedScore;\n      bestBreaks = mutatedWordBreaks;\n    }\n  }\n  if (bestBreaks) {\n    // Found an improvement.  See if it may be improved further.\n    return CCC.World.wrapMutate_(svg, words, bestBreaks, limit);\n  }\n  // No improvements found.  Done.\n  return wordBreaks;\n};\n\n/**\n * Reassemble the array of words into text, with the specified line breaks.\n * @param {!Array.<string>} words Array of each word.\n * @param {!Array.<boolean>} wordBreaks Array of line breaks.\n * @return {string} Plain text.\n * @private\n */\nCCC.World.wrapToText_ = function(words, wordBreaks) {\n  var text = [];\n  for (var i = 0; i < words.length; i++) {\n    text.push(words[i]);\n    if (wordBreaks[i]) {\n      text.push('\\n');\n    }\n  }\n  return text.join('');\n};\n\n/**\n * Measure one line of text to obtain its height and width.\n * @param {!SVGSVGElement} svg SVG element to use.\n * @param {string} text Text to measure.\n * @return {!SVGRect} Height and width of text.\n */\nCCC.World.measureText = function(svg, text) {\n  if (!svg.measureTextCache_) {\n    svg.measureTextCache_ = Object.create(null);\n  } else if (svg.measureTextCache_[text]) {\n    return svg.measureTextCache_[text];\n  }\n  var textarea = document.createElementNS(CCC.Common.NS, 'text');\n  textarea.appendChild(document.createTextNode(text));\n  svg.appendChild(textarea);\n  var bBox = textarea.getBBox();\n  svg.removeChild(textarea);\n  svg.measureTextCache_[text] = bBox;\n  return bBox;\n};\n\nif (!window.TEST) {\n  window.addEventListener('message', CCC.World.receiveMessage, false);\n  window.addEventListener('load', CCC.World.init, false);\n\n  // Temporary disabling of SVG filters.  June 2020\n  CCC.World.xmlToSvg.ELEMENT_NAMES = null;\n  CCC.World.xmlToSvg.ATTRIBUTE_NAMES = null;\n  CCC.World.xmlToSvg.CLASS_NAMES = null;\n}\n"
  },
  {
    "path": "static/flamethrower.html",
    "content": "<html>\n  <head>\n    <style>\n      body {\n        background: #000;\n        background-size: contain;\n        background-repeat: no-repeat;\n        background-position: 0% center;\n        background-image: url(flamethrower.gif)\n      }\n    </style>\n  </head>\n  <body>\n  </body>\n</html>\n"
  },
  {
    "path": "static/login-close.html",
    "content": "<!doctype html>\n\n<html lang=\"en\">\n<head>\n  <title>Code City Login</title>\n  <style>\n    body {\n      font-family: \"Roboto Mono\", monospace;\n      text-align: center;\n    }\n    .container {\n      display: table;\n      position: absolute;\n      top: 0;\n      left: 0;\n      height: 100%;\n      width: 100%;\n    }\n    .centered {\n      display: table-cell;\n      vertical-align: middle;\n    }\n  </style>\n</head>\n<body>\n  <div class=\"container\">\n    <div class=\"centered\">\n      <p>Login successful.</p>\n      <p>Close this window.</p>\n    </div>\n  </div>\n  <script>\n    // Send message that allows any opener window to know that this window may be closed.\n    opener.postMessage('closeMe', '*');\n  </script>\n</body>\n</html>\n"
  },
  {
    "path": "static/securitystore/style.css",
    "content": "body {\n  background-color: white;\n  font-family: sans-serif;\n  max-width: 50em;\n  margin: 1em;\n}\n\nh1, h2, h3 {\n  font-weight: normal;\n}\n\n.productImage {\n  float: left;\n  height: 60px;\n  margin 1em;\n  width: 60px;\n}\n\n.basketImage {\n  height: 30px;\n  width: 30px;\n}\n\n.footer {\n  font-size: small;\n  margin-top: 2em;\n}\n\n.balls {\n  float: right;\n}\n"
  },
  {
    "path": "static/securitystore/utils.js",
    "content": "// Client-side utility functions for formatting prices according to the user's localle.\n\n// Format a number as a price.  E.g. '1234.5' -> '$1,234.50'\nfunction formattedPrice(number) {\n  return Number(number).toLocaleString('en', {\n    style: 'currency',\n    currency: 'USD'\n  });\n}\n\n// Find all '<span class=\"price\">123</span>' and format them as prices.\nfunction renderPrices() {\n  var priceSpans = document.getElementsByClassName('price');\n  for (var i = 0, priceSpan; (priceSpan = priceSpans[i]); i++) {\n    priceSpan.textContent = formattedPrice(priceSpan.textContent);\n  }\n}\nwindow.addEventListener('DOMContentLoaded', renderPrices);\n"
  },
  {
    "path": "static/style/jfk.css",
    "content": "body {\n  background-color: #fff;\n}\n\n/* Kennedy buttons. */\n.jfk-button {\n  user-select: none;\n  box-shadow: none;\n  background-color: #f5f5f5;\n  background-image: -webkit-linear-gradient(top,#f5f5f5,#f1f1f1);\n  background-image: -moz-linear-gradient(top,#f5f5f5,#f1f1f1);\n  background-image: -ms-linear-gradient(top,#f5f5f5,#f1f1f1);\n  background-image: -o-linear-gradient(top,#f5f5f5,#f1f1f1);\n  background-image: linear-gradient(top,#f5f5f5,#f1f1f1);\n  colour: #444;\n  border: 1px solid rgba(0,0,0,.1);\n  border-radius: 2px;\n  cursor: default;\n  font-size: 11px;\n  font-weight: bold;\n  text-align: center;\n  white-space: nowrap;\n  margin-right: 8px;\n  height: 27px;\n  line-height: 27px;\n  min-width: 54px;\n  outline: 0;\n  padding: 0 8px;\n  position: relative;\n  display: inline-block;\n  font-family: \"Arial\", \"Helvetica\", sans-serif;\n}\n\n.jfk-button:hover {\n  box-shadow: none;\n  background-color: #f8f8f8;\n  background-image: -webkit-linear-gradient(top,#f8f8f8,#f1f1f1);\n  background-image: -moz-linear-gradient(top,#f8f8f8,#f1f1f1);\n  background-image: -ms-linear-gradient(top,#f8f8f8,#f1f1f1);\n  background-image: -o-linear-gradient(top,#f8f8f8,#f1f1f1);\n  background-image: linear-gradient(top,#f8f8f8,#f1f1f1);\n  border: 1px solid #c6c6c6;\n  color: #333\n}\n\n.jfk-button:active {\n\tbox-shadow: inset 0 1px 2px rgba(0,0,0,.2);\n}\n\n/* Unresponsive 'checked' buttons. */\n.jfk-checked, .jfk-checked:hover, .jfk-checked:active {\n  box-shadow: inset 0 1px 2px rgba(0,0,0,.1);\n  background-color: #eee;\n  background-image: -webkit-linear-gradient(top,#eee,#e0e0e0);\n  background-image: -moz-linear-gradient(top,#eee,#e0e0e0);\n  background-image: -ms-linear-gradient(top,#eee,#e0e0e0);\n  background-image: -o-linear-gradient(top,#eee,#e0e0e0);\n  background-image: linear-gradient(top,#eee,#e0e0e0);\n  color: #333\n}\n\n/* Red 'action' buttons. */\n.jfk-button-action {\n  color: #fff;\n  background-color: #d14836;\n  background-image: -webkit-linear-gradient(top,#dd4b39,#d14836);\n  background-image: -moz-linear-gradient(top,#dd4b39,#d14836);\n  background-image: -ms-linear-gradient(top,#dd4b39,#d14836);\n  background-image: -o-linear-gradient(top,#dd4b39,#d14836);\n  background-image: linear-gradient(top,#dd4b39,#d14836);\n}\n\n.jfk-button-action:hover {\n  color: #fff;\n  box-shadow: 0 1px 1px rgba(0,0,0,.2);\n  background-color: #c53727;\n  background-image: -webkit-linear-gradient(top,#dd4b39,#c53727);\n  background-image: -moz-linear-gradient(top,#dd4b39,#c53727);\n  background-image: -ms-linear-gradient(top,#dd4b39,#c53727);\n  background-image: -o-linear-gradient(top,#dd4b39,#c53727);\n  background-image: linear-gradient(top,#dd4b39,#c53727);\n  border: 1px solid #b0281a;\n  border-bottom-color: #af301f\n}\n\n/* Blue 'submit' buttons. */\n.jfk-button-submit {\n  color: #fff;\n  background-color: #4d90fe;\n  background-image: -webkit-linear-gradient(top,#4d90fe,#4787ed);\n  background-image: -moz-linear-gradient(top,#4d90fe,#4787ed);\n  background-image: -ms-linear-gradient(top,#4d90fe,#4787ed);\n  background-image: -o-linear-gradient(top,#4d90fe,#4787ed);\n  background-image: linear-gradient(top,#4d90fe,#4787ed);\n  border-color: #3079ed;\n}\n\n.jfk-button-submit:hover {\n  color: #fff;\n  background-color: #357ae8;\n  background-image: -webkit-linear-gradient(top,#4d90fe,#357ae8);\n  background-image: -moz-linear-gradient(top,#4d90fe,#357ae8);\n  background-image: -ms-linear-gradient(top,#4d90fe,#357ae8);\n  background-image: -o-linear-gradient(top,#4d90fe,#357ae8);\n  background-image: linear-gradient(top,#4d90fe,#357ae8);\n  border-color: #2f5bb7;\n}\n"
  },
  {
    "path": "static/style/svg.css",
    "content": "/* Enforce a consistent drawing style on all content. */\nsvg {\n  fill: none;\n  stroke: #000;\n  stroke-linecap: round;\n  stroke-linejoin: round;\n  stroke-width: .7px;\n}\n\ntext {\n  fill: #000;\n  font-size: 4pt;\n  stroke-width: 0;\n}\n\na {\n  cursor: pointer;\n  text-decoration: underline;\n  fill: #00e;\n}\n\na:hover {\n  fill: #d00;\n}\n\n.strokeNone {\n  stroke: none;\n}\n\n.strokeWhite {\n  stroke: #fff;\n}\n\n.strokeBlack {\n  stroke: #000;\n}\n\n.strokeGrey, .strokeGray {\n  stroke: #888;\n}\n\n.fillNone {\n  fill: none;\n}\n\n.fillWhite {\n  fill: #fff;\n}\n\n.fillBlack {\n  fill: #000;\n}\n\n.fillGrey, .fillGray {\n  fill: #888;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/AUTHORS",
    "content": "List of CodeMirror contributors. Updated before every release.\n\n4oo4\n4r2r\nAaron Brooks\nAbdelouahab\nAbdussalam Abdurrahman\nAbe Fettig\nAbhishek Gahlot\nAdam Ahmed\nAdam King\nAdam Particka\nadanlobato\nAdán Lobato\nAdrian Aichner\nAdrian Heine\nAdrien Bertrand\naeroson\nAhmad Amireh\nAhmad M. Zawawi\nahoward\nAkeksandr Motsjonov\nAlasdair Smith\nAlbertHilb\nAlberto González Palomo\nAlberto Pose\nAlbert Xing\nAlexander Pavlov\nAlexander Schepanovski\nAlexander Shvets\nAlexander Solovyov\nAlexandre Bique\nalexey-k\nAlex Piggott\nAliaksei Chapyzhenka\nAllen Sarkisyan\nAmi Fischman\nAmin Shali\nAmin Ullah Khan\namshali@google.com\nAmsul\namuntean\nAmy\nAnanya Sen\nanaran\nAndersMad\nAnders Nawroth\nAnderson Mesquita\nAnders Wåglund\nAndrea G\nAndreas Reischuck\nAndres Taylor\nAndre von Houck\nAndrew Cheng\nAndrew Dassonville\nAndrey Fedorov\nAndrey Klyuchnikov\nAndrey Lushnikov\nAndrey Shchekin\nAndy Joslin\nAndy Kimball\nAndy Li\nAngelo\nangelozerr\nangelo.zerr@gmail.com\nAnkit\nAnkit Ahuja\nAnsel Santosa\nAnthony Dugois\nanthonygego\nAnthony Gégo\nAnthony Grimes\nAnton Kovalyov\nApollo Zhu\nAQNOUCH Mohammed\nAram Shatakhtsyan\nareos\nArnab Bose\nArsène von Wyss\nArthur Müller\nArun Narasani\nas3boyan\nasolove\natelierbram\nAtomicPages LLC\nAtul Bhouraskar\nAurelian Oancea\nAxel Lewenhaupt\nBaptiste Augrain\nBarret Rennie\nBartosz Dziewoński\nBasarat Ali Syed\nBastian Müller\nbelhaj\nBem Jones-Bey\nbenbro\nBeni Cherniavsky-Paskin\nBenjamin DeCoste\nBenjamin Young\nBen Keen\nBen Miller\nBen Mosher\nBernhard Sirlinger\nBert Chang\nBharad\nBigBlueHat\nBilly Moon\nbinny\nBjorn Hansen\nB Krishna Chaitanya\nBlaine G\nblukat29\nBo\nboomyjee\nBo Peng\nborawjm\nBrad Metcalf\nBrandon Frohs\nBrandon Wamboldt\nBret Little\nBrett Zamir\nBrian Grinstead\nBrian Sletten\nbrrd\nBruce Mitchener\nBryan Massoth\nCaitlin Potter\nCalin Barbat\ncallodacity\nCamilo Roca\nCasey Klebba\nCésar González Íñiguez\nChad Jolly\nChandra Sekhar Pydi\nCharles Skelton\nCheah Chu Yeow\nChris Colborne\nChris Coyier\nChris Ford\nChris Granger\nChris Houseknecht\nChris Lohfink\nChris Morgan\nChris Reeves\nChris Smith\nChristian Gruen\nChristian Oyarzun\nChristian Petrov\nchristopherblaser\nChristopher Brown\nChristopher Kramer\nChristopher Mitchell\nChristopher Pfohl\nChristopher Wallis\nChunliang Lyu\nciaranj\nCodeAnimal\nCodeBitt\ncoderaiser\nCole R Lawrence\nComFreek\nCristian Prieto\nCurran Kelleher\nCurtis Gagliardi\ndagsta\ndaines\nDale Jung\nDan Bentley\nDan Heberden\nDaniel, Dao Quang Minh\nDaniele Di Sarli\nDaniel Faust\nDaniel Hanggi\nDaniel Huigens\nDaniel Kesler\nDaniel KJ\nDaniel Neel\nDaniel Parnell\nDaniel Thwaites\nDanila Malyutin\nDanny Yoo\ndarealshinji\nDarius Roberts\ndatabricks-david-lewis\nDave Brondsema\nDave MacLachlan\nDave Myers\nDavid Barnett\nDavid H. Bronke\nDavid Mignot\nDavid Pathakjee\nDavid Santana\nDavid Vázquez\nDavid Whittington\ndeebugger\nDeep Thought\nDevin Abbott\nDevon Carew\nDick Choi\ndignifiedquire\nDimage Sapelkin\ndmaclach\nDmitry Kiselyov\ndomagoj412\nDominator008\nDomizio Demichelis\nDoug Blank\nDoug Wikle\nDrew Bratcher\nDrew Hintz\nDrew Khoury\nDrini Cami\nDror BG\nduralog\ndwelle\neborden\nedsharp\nekhaled\nElisée\nEmmanuel Schanzer\nEnam Mijbah Noor\nEric Allam\nEric Bogard\nErik Welander\neustas\nFabien Dubosson\nFabien O'Carroll\nFabio Zendhi Nagao\nFaiza Alsaied\nFauntleroy\nfbuchinger\nfeizhang365\nFelipe Lalanne\nFelix Raab\nficristo\nFilip Noetzel\nFilip Stollár\nFilype Pereira\nfinalfantasia\nflack\nFlorian Felten\nForbesLindesay\nForbes Lindesay\nFord_Lawnmower\nForrest Oliphant\nFranco Catena\nFrank Wiegand\nfraxx001\nFredrik Borg\nFUJI Goro (gfx)\nGabriel Gheorghian\nGabriel Horner\nGabriel Nahmias\ngalambalazs\nGary Sheng\nGautam Mehta\nGavin Douglas\ngekkoe\nGeordie Hall\nGeorge Stephanis\ngeowarin\nGerard Braad\nGergely Hegykozi\nGermain Chazot\nGiovanni Calò\nGlebov Boris\nGlenn Jorde\nGlenn Ruehle\ngoldsmcb\nGolevka\nGoogle LLC\nGordon Smith\nGrant Skinner\ngreengiant\nGregory Koberger\nGrzegorz Mazur\nGuan Gui\nGuillaume Massé\nGuillaume Massé\nguraga\nGustavo Rodrigues\nHakan Tunc\nHans Engel\nHarald Schilly\nHardest\nHarshvardhan Gupta\nHasan Karahan\nHeanes\nHector Oswaldo Caballero\nHélio\nHendrik Wallbaum\nHenrik Haugbølle\nHerculano Campos\nhidaiy\nHiroyuki Makino\nhitsthings\nHocdoc\nHugues Malphettes\nIan Beck\nIan Davies\nIan Dickinson\nIan Rose\nIan Wehrman\nIan Wetherbee\nIce White\nICHIKAWA, Yuji\nidleberg\nilvalle\nIngo Richter\nIrakli Gozalishvili\nIvan Kurnosov\nIvoah\nJacob Lee\nJaimin\nJake Peyser\nJakob Miland\nJakub Vrana\nJakub Vrána\nJames Campos\nJames Howard\nJames Thorne\nJamie Hill\nJamie Morris\nJanice Leung\nJan Jongboom\njankeromnes\nJan Keromnes\nJan Odvarko\nJan Schär\nJan T. Sott\nJared Dean\nJared Forsyth\nJared Jacobs\nJason\nJason Barnabe\nJason Grout\nJason Heeris\nJason Johnston\nJason San Jose\nJason Siefken\nJayaprabhakar\nJaydeep Solanki\nJean Boussier\nJeff Blaisdell\nJeff Hanke\nJeff Jenkins\njeffkenton\nJeff Pickhardt\njem (graphite)\nJeremy Parmenter\nJim\nJim Avery\njkaplon\nJobJob\njochenberger\nJochen Berger\nJoel Einbinder\njoelpinheiro\njoewalsh\nJohan Ask\nJohn Connor\nJohn-David Dalton\nJohn Engler\nJohn Lees-Miller\nJohn Snelson\nJohn Van Der Loo\nJon Ander Peñalba\nJonas Döbertin\nJonas Helfer\nJonathan Dierksen\nJonathan Hart\nJonathan Malmaud\nJon Gacnik\njongalloway\nJon Malmaud\nJon Sangster\nJoost-Wim Boekesteijn\nJoseph Pecoraro\nJosh Barnes\nJosh Cohen\nJosh Soref\nJoshua Newman\nJosh Watzman\njots\njsoojeon\nju1ius\nJuan Benavides Romero\nJucovschi Constantin\nJuho Vuori\nJulien CROUZET\nJulien Rebetez\nJustin Andresen\nJustin Hileman\njwallers@gmail.com\nkaniga\nkarevn\nKarol\nKayur Patel\nKazuhito Hokamura\nKen Newman\nken restivo\nKen Rockot\nKevin Earls\nKevin Kwok\nKevin Muret\nKevin Sawicki\nKevin Ushey\nKier Darby\nKlaus Silveira\nKoh Zi Han, Cliff\nkomakino\nKonstantin Lopuhin\nkoops\nKris Ciccarello\nks-ifware\nkubelsmieci\nKwanEsq\nKyle Kelley\nKyleMcNutt\nLaKing\nLanfei\nLanny\nlaobubu\nLaszlo Vidacs\nleaf corcoran\nLemmon\nLeonid Khachaturov\nLeon Sorokin\nLeonya Khachaturov\nLiam Newman\nLibo Cannici\nLior Goldberg\nLior Shub\nLloydMilligan\nLM\nlochel\nLorenzo Simionato\nLorenzo Stoakes\nLouis Mauchet\nLuca Fabbri\nLuciano Longo\nLu Fangjian\nLuke Browning\nLuke Granger-Brown\nLuke Stagner\nlynschinzer\nM1cha\nMadhura Jayaratne\nMaksim Lin\nMaksym Taran\nMalay Majithia\nManideep\nManuel Rego Casasnovas\nMarat Dreizin\nMarcel Gerber\nMarcelo Camargo\nMarco Aurélio\nMarco Munizaga\nMarcus Bointon\nMarek Rudnicki\nMarijn Haverbeke\nMário Gonçalves\nMario Pietsch\nMark Anderson\nMark Dalgleish\nMark Lentczner\nMarko Bonaci\nMark Peace\nMarkus Bordihn\nMarkus Olsson\nMartin Balek\nMartín Gaitán\nMartin Hasoň\nMartin Hunt\nMartin Laine\nMartin Zagora\nMason Malone\nMateusz Paprocki\nMathias Bynens\nmats cronqvist\nMatt Gaide\nMatthew Bauer\nMatthew Beale\nmatthewhayes\nMatthew Rathbone\nMatthew Suozzo\nMatthias Bussonnier\nMatthias BUSSONNIER\nMatt MacPherson\nMatt McDonald\nMatt Pass\nMatt Sacks\nmauricio\nMaximilian Hils\nMaxim Kraev\nMax Kirsch\nMax Schaefer\nMax Xiantu\nmbarkhau\nMcBrainy\nmce2\nmelpon\nmeshuamam\nMetatheos\nMicah Dubinko\nMichael\nMichael Goderbauer\nMichael Grey\nMichael Kaminsky\nMichael Lehenbauer\nMichael Wadman\nMichael Walker\nMichael Zhou\nMichal Čihař\nMichal Dorner\nMichal Kapiczynski\nMighty Guava\nMiguel Castillo\nmihailik\nMika Andrianarijaona\nMike\nMike Bostock\nMike Brevoort\nMike Diaz\nMike Ivanov\nMike Kadin\nMike Kobit\nMilan Szekely\nMinRK\nMiraculix87\nmisfo\nmkaminsky11\nmloginov\nMoritz Schubotz (physikerwelt)\nMoritz Schwörer\nMoshe Wajnberg\nmps\nms\nmtaran-google\nMu-An Chiou\nMu-An ✌️ Chiou\nmzabuawala\nNarciso Jaramillo\nNathan Williams\nndr\nNeil Anderson\nneon-dev\nnerbert\nNetworkNode\nnextrevision\nngn\nnguillaumin\nNg Zhi An\nNicholas Bollweg\nNicholas Bollweg (Nick)\nNickKolok\nNick Kreeger\nNick Small\nNicolas Kick\nNicolò Ribaudo\nNiels van Groningen\nnightwing\nNikita Beloglazov\nNikita Vasilyev\nNikolaj Kappler\nNikolay Kostov\nnilp0inter\nNisarg Jhaveri\nnlwillia\nnoragrossman\nNorman Rzepka\nOleksandr Yakovenko\nopl-\nOreoluwa Onatemowo\nOskar Segersvärd\noverdodactyl\npablo\npabloferz\nPablo Zubieta\npaddya\nPage\npaladox\nPanupong Pasupat\nparis\nParis\nParis Kasidiaris\nPatil Arpith\nPatrick Stoica\nPatrick Strawderman\nPaul Garvin\nPaul Ivanov\nPaul Masson\nPavel\nPavel Feldman\nPavel Petržela\nPavel Strashkin\nPaweł Bartkiewicz\npeteguhl\npeter\nPeter Flynn\npeterkroon\nPeter Kroon\nPhilipp A\nPhilipp Markovics\nPhilip Stadermann\nPi Delport\nPierre Gerold\nPieter Ouwerkerk\nPontus Melke\nprasanthj\nPrasanth J\nPrayag Verma\nPrendota\nQiang Li\nRadek Piórkowski\nRahul\nRahul Anand\nramwin1\nRandall Mason\nRandy Burden\nRandy Edmunds\nRandy Luecke\nRaphael Amorim\nRasmus Erik Voel Jensen\nRasmus Schultz\nRaymond Hill\nray ratchup\nRay Ratchup\nRemi Nyborg\nRenaud Durlin\nReynold Xin\nRichard Denton\nRichard van der Meer\nRichard Z.H. Wang\nRishi Goomar\nRobert Brignull\nRobert Crossfield\nRoberto Abdelkader Martínez Pérez\nrobertop23\nRobert Plummer\nRrandom\nRrrandom\nRuslan Osmanov\nRyan Petrello\nRyan Prior\nryu-sato\nsabaca\nSam Lee\nSam Rawlins\nSamuel Ainsworth\nSam Wilson\nsandeepshetty\nSander AKA Redsandro\nSander Verweij\nsantec\nSarah McAlear and Wenlin Zhang\nSascha Peilicke\nsatamas\nsatchmorun\nsathyamoorthi\nSaul Costa\nS. Chris Colbert\nSCLINIC\\jdecker\nScott Aikin\nScott Goodhew\nSebastian Wilzbach\nSebastian Zaha\nSeren D\nSergey Goder\nSergey Tselovalnikov\nSe-Won Kim\nShane Liesegang\nshaund\nshaun gilchrist\nShawn A\nShea Bunge\nsheopory\nShil S\nShiv Deepak\nShmuel Englard\nShubham Jain\nSiamak Mokhtari\nsilverwind\nSimon Edwards\nsinkuu\nsnasa\nsoliton4\nsonson\nSorab Bisht\nspastorelli\nsrajanpaliwal\nStanislav Oaserele\nstan-z\nStas Kobzar\nStefan Borsje\nSteffen Beyer\nSteffen Bruchmann\nSteffen Kowalski\nStephane Moore\nStephen Lavelle\nSteve Champagne\nSteve Hoover\nSteve O'Hara\nstoskov\nStu Kennedy\nSungho Kim\nsverweij\nTaha Jahangir\ntakamori\nTako Schotanus\nTakuji Shimokawa\nTakuya Matsuyama\nTarmil\nTDaglis\ntel\nTentone\ntfjgeorge\nThaddee Tyl\nthanasis\nTheHowl\nthemrmax\nthink\nThomas Brouard\nThomas Dvornik\nThomas Kluyver\nThomas Schmid\nTim Alby\nTim Baumann\nTimothy Farrell\nTimothy Gu\nTimothy Hatcher\nTobias Bertelsen\nTobiasBg\nTodd Berman\nTodd Kennedy\nTomas-A\nTomas Varaneckas\nTom Erik Støwer\nTom Klancer\nTom MacWright\nTom McLaughlin\nTony Jian\ntophf\ntotalamd\nTravis Heppe\nTriangle717\nTristan Tarrant\nTSUYUSATO Kitsune\nTugrul Elmas\ntwifkak\nTyler Long\nVadzim Ramanenka\nVaibhav Sagar\nVapidWorx\nVestimir Markov\nvf\nVictor Bocharsky\nVincent Woo\nVolker Mische\nvtripolitakis\nwdouglashall\nWeiyan Shao\nwenli\nWes Cossick\nWesley Wiser\nWeston Ruter\nWill Binns-Smith\nWill Dean\nWilliam Jamieson\nWilliam Stein\nWilly\nWojtek Ptak\nwonderboyjon\nWu Cheng-Han\nXavier Mendez\nYassin N. Hassan\nYNH Webdev\nyoongu\nYunchi Luo\nYuvi Panda\nYvonnick Esnault\nZac Anger\nZachary Dremann\nZeno Rocha\nZhang Hao\nZiv\nzziuni\n魏鹏刚\n"
  },
  {
    "path": "third_party/CodeMirror/CHANGELOG.md",
    "content": "## 5.43.0 (2019-01-21)\n\n### Bug fixes\n\nFix mistakes in passing through the arguments to `indent` in several wrapping modes.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Fix parsing for a number of new and obscure TypeScript features.\n\n[ruby mode](https://codemirror.net/mode/ruby): Support indented end tokens for heredoc strings.\n\n### New features\n\nNew options `autocorrect` and `autocapitalize` to turn on those browser features.\n\n## 5.42.2 (2018-12-21)\n\n### Bug fixes\n\nFix problem where canceling a change via the `\"beforeChange\"` event could corrupt the textarea input.\n\nFix issues that sometimes caused the context menu hack to fail, or even leave visual artifacts on IE.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Make it possible to select text between angle brackets.\n\n[css mode](https://codemirror.net/mode/css/): Fix tokenizing of CSS variables.\n\n[python mode](https://codemirror.net/mode/python/): Fix another bug in tokenizing of format strings.\n\n[soy mode](https://codemirror.net/mode/soy/): More accurate highlighting.\n\n## 5.42.0 (2018-11-20)\n\n### Bug fixes\n\nFix an issue where wide characters could cause lines to be come wider than the editor's horizontal scroll width.\n\nOptimize handling of window resize events.\n\n[show-hint addon](https://codemirror.net/doc/manual.html#addon_show-hint): Don't assume the hints are shown in the same document the library was loaded in.\n\n[python mode](https://codemirror.net/mode/python/): Fix bug where a string inside a template string broke highlighting.\n\n[swift mode](https://codemirror.net/mode/swift): Support multi-line strings.\n\n### New features\n\nThe [`markText` method](https://codemirror.net/doc/manual.html#markText) now takes an [`attributes`](https://codemirror.net/doc/manual.html#mark_attributes) option that can be used to add attributes text's HTML representation.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Add support for the `=` binding.\n\n## 5.41.0 (2018-10-25)\n\n### Bug fixes\n\nFix firing of [`\"gutterContextMenu\"`](https://codemirror.net/doc/manual.html#event_gutterContextMenu) event on Firefox.\n\nSolve an issue where copying multiple selections might mess with subsequent typing.\n\nDon't crash when [`endOperation`](https://codemirror.net/doc/manual.html#endOperation) is called with no operation active.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Fix insert mode repeat after visualBlock edits.\n\n[scheme mode](https://codemirror.net/mode/scheme/index.html): Improve highlighting of quoted expressions.\n\n[soy mode](https://codemirror.net/mode/soy/): Support injected data and `@param` in comments.\n\n[objective c mode](https://codemirror.net/mode/clike/): Improve conformance to the actual language.\n\n### New features\n\nA new [`selectionsMayTouch`](https://codemirror.net/doc/manual.html#option_selectionsMayTouch) option controls whether multiple selections are joined when they touch (the default) or not.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Add `noremap` binding command.\n\n## 5.40.2 (2018-09-20)\n\n### Bug fixes\n\nFix firing of `gutterContextMenu` event on Firefox.\n\nAdd `hintWords` (basic completion) helper to [clojure](https://codemirror.net/mode/clojure/index.html), [mllike](https://codemirror.net/mode/mllike/index.html), [julia](https://codemirror.net/mode/julia/), [shell](https://codemirror.net/mode/shell/), and [r](https://codemirror.net/mode/r/) modes.\n\n[clojure mode](https://codemirror.net/mode/clojure/index.html): Clean up and improve.\n\n## 5.40.0 (2018-08-25)\n\n### Bug fixes\n\n[closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Fix issue where bracket-closing wouldn't work before punctuation.\n\n[panel addon](https://codemirror.net/doc/manual.html#addon_panel): Fix problem where replacing the last remaining panel dropped the newly added panel.\n\n[hardwrap addon](https://codemirror.net/doc/manual.html#addon_hardwrap): Fix an infinite loop when the indention is greater than the target column.\n\n[jinja2](https://codemirror.net/mode/jinja2/) and [markdown](https://codemirror.net/mode/markdown/) modes: Add comment metadata.\n\n### New features\n\nNew method [`phrase`](https://codemirror.net/doc/manual.html#phrase) and option [`phrases`](https://codemirror.net/doc/manual.html#option_phrases) to make translating UI text in addons easier.\n\n## 5.39.2 (2018-07-20)\n\n### Bug fixes\n\nFix issue where when you pass the document as a `Doc` instance to the `CodeMirror` constructor, the `mode` option was ignored.\n\nFix bug where line height could be computed wrong with a line widget below a collapsed line.\n\nFix overeager `.npmignore` dropping the `bin/source-highlight` utility from the distribution.\n\n[show-hint addon](https://codemirror.net/doc/manual.html#addon_show-hint): Fix behavior when backspacing to the start of the line with completions open.\n\n## 5.39.0 (2018-06-20)\n\n### Bug fixes\n\nFix issue that in some circumstances caused content to be clipped off at the bottom after a resize.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Improve handling of blank lines in HTML tags.\n\n### New features\n\n[stex mode](https://codemirror.net/mode/stex/): Add an `inMathMode` option to start the mode in math mode.\n\n## 5.38.0 (2018-05-21)\n\n### Bug fixes\n\nImprove reliability of noticing a missing mouseup event during dragging.\n\nMake sure `getSelection` is always called on the correct document.\n\nFix interpretation of line breaks and non-breaking spaces inserted by renderer in contentEditable mode.\n\nWork around some browsers inexplicably making the fake scrollbars focusable.\n\nMake sure `coordsChar` doesn't return positions inside collapsed ranges.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Support block scopes, bindingless catch, bignum suffix, `s` regexp flag.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Adjust a wasteful regexp.\n\n[show-hint addon](https://codemirror.net/doc/manual.html#addon_show-hint): Allow opening the control without any item selected.\n\n### New features\n\nNew theme: [darcula](https://codemirror.net/demo/theme.html#darcula).\n\n[dialog addon](https://codemirror.net/doc/manual.html#addon_dialog): Add a CSS class (`dialog-opened`) to the editor when a dialog is open.\n\n## 5.37.0 (2018-04-20)\n\n### Bug fixes\n\nSuppress keypress events during composition, for platforms that don't properly do this themselves.\n\n[xml-fold addon](https://codemirror.net/demo/folding.html): Improve handling of line-wrapped opening tags.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Improve TypeScript support.\n\n[python mode](https://codemirror.net/mode/python/): Highlight expressions inside format strings.\n\n### New features\n\n[vim bindings](https://codemirror.net/demo/vim.html): Add support for '(' and ')' movement.\n\nNew themes: [idea](https://codemirror.net/demo/theme.html#idea), [ssms](https://codemirror.net/demo/theme.html#ssms), [gruvbox-dark](https://codemirror.net/demo/theme.html#gruvbox-dark).\n\n## 5.36.0 (2018-03-20)\n\n### Bug fixes\n\nMake sure all document-level event handlers are registered on the document that the editor is part of.\n\nFix issue that prevented edits whose origin starts with `+` from being combined in history events for an editor-less document.\n\n[multiplex addon](https://codemirror.net/demo/multiplex.html): Improve handling of indentation.\n\n[merge addon](https://codemirror.net/doc/manual.html#addon_merge): Use CSS `:after` element to style the scroll-lock icon.\n\n[javascript-hint addon](https://codemirror.net/doc/manual.html#addon_javascript-hint): Don't provide completions in JSON mode.\n\n[continuelist addon](https://codemirror.net/doc/manual.html#addon_continuelist): Fix numbering error.\n\n[show-hint addon](https://codemirror.net/doc/manual.html#addon_show-hint): Make `fromList` completion strategy act on the current token up to the cursor, rather than the entire token.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Fix a regexp with potentially exponental complexity.\n\n### New features\n\nNew theme: [lucario](https://codemirror.net/demo/theme.html#lucario).\n\n## 5.35.0 (2018-02-20)\n\n### Bug fixes\n\nFix problem where selection undo might change read-only documents.\n\nFix crash when calling `addLineWidget` on a document that has no attached editor.\n\n[searchcursor addon](https://codemirror.net/doc/manual.html#addon_searchcursor): Fix behavior of `^` in multiline regexp mode.\n\n[match-highlighter addon](https://codemirror.net/doc/manual.html#addon_match-highlighter): Fix problem with matching words that have regexp special syntax in them.\n\n[sublime bindings](https://codemirror.net/demo/sublime.html): Fix `addCursorToSelection` for short lines.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Support TypeScript intersection types, dynamic `import`.\n\n[stex mode](https://codemirror.net/mode/stex/): Fix parsing of `\\(` `\\)` delimiters, recognize more atom arguments.\n\n[haskell mode](https://codemirror.net/mode/haskell/): Highlight more builtins, support `<*` and `*>`.\n\n[sql mode](https://codemirror.net/mode/sql/): Make it possible to disable backslash escapes in strings for dialects that don't have them, do this for MS SQL.\n\n[dockerfile mode](https://codemirror.net/mode/dockerfile/): Highlight strings and ports, recognize more instructions.\n\n### New features\n\n[vim bindings](https://codemirror.net/demo/vim.html): Support alternative delimiters in replace command.\n\n## 5.34.0 (2018-01-29)\n\n### Bug fixes\n\n[markdown mode](https://codemirror.net/mode/markdown/): Fix a problem where inline styles would persist across list items.\n\n[sublime bindings](https://codemirror.net/demo/sublime.html): Fix the `toggleBookmark` command.\n\n[closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Improve behavior when closing triple quotes.\n\n[xml-fold addon](https://codemirror.net/demo/folding.html): Fix folding of line-broken XML tags.\n\n[shell mode](https://codemirror.net/mode/shell/): Better handling of nested quoting.\n\n[javascript-lint addon](https://codemirror.net/demo/lint.html): Clean up and simplify.\n\n[matchbrackets addon](https://codemirror.net/doc/manual.html#addon_matchbrackets): Fix support for multiple editors at the same time.\n\n### New features\n\nNew themes: [oceanic-next](https://codemirror.net/demo/theme.html#oceanic-next) and [shadowfox](https://codemirror.net/demo/theme.html#shadowfox).\n\n## 5.33.0 (2017-12-21)\n\n### Bug fixes\n\n[lint addon](https://codemirror.net/doc/manual.html#addon_lint): Make updates more efficient.\n\n[css mode](https://codemirror.net/mode/css/): The mode is now properly case-insensitive.\n\n[continuelist addon](https://codemirror.net/doc/manual.html#addon_continuelist): Fix broken handling of unordered lists introduced in previous release.\n\n[swift](https://codemirror.net/mode/swift) and [scala](https://codemirror.net/mode/clike/) modes: Support nested block comments.\n\n[mllike mode](https://codemirror.net/mode/mllike/index.html): Improve OCaml support.\n\n[sublime bindings](https://codemirror.net/demo/sublime.html): Use the proper key bindings for `addCursorToNextLine` and `addCursorToPrevLine`.\n\n### New features\n\n[jsx mode](https://codemirror.net/mode/jsx/index.html): Support JSX fragments.\n\n[closetag addon](https://codemirror.net/demo/closetag.html): Add an option to disable auto-indenting.\n\n## 5.32.0 (2017-11-22)\n\n### Bug fixes\n\nIncrease contrast on default bracket-matching colors.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Recognize TypeScript type parameters for calls, type guards, and type parameter defaults. Improve handling of `enum` and `module` keywords.\n\n[comment addon](https://codemirror.net/doc/manual.html#addon_comment): Fix bug when uncommenting a comment that spans all but the last selected line.\n\n[searchcursor addon](https://codemirror.net/doc/manual.html#addon_searchcursor): Fix bug in case folding.\n\n[emacs bindings](https://codemirror.net/demo/emacs.html): Prevent single-character deletions from resetting the kill ring.\n\n[closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Tweak quote matching behavior.\n\n### New features\n\n[continuelist addon](https://codemirror.net/doc/manual.html#addon_continuelist): Increment ordered list numbers when adding one.\n\n## 5.31.0 (2017-10-20)\n\n### Bug fixes\n\nFurther improve selection drawing and cursor motion in right-to-left documents.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Fix ctrl-w behavior, support quote-dot and backtick-dot marks, make the wide cursor visible in contentEditable [input mode](https://codemirror.net/doc/manual.html#option_contentEditable).\n\n[continuecomment addon](https://codemirror.net/doc/manual.html#addon_continuecomment): Fix bug when pressing enter after a single-line block comment.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Fix issue with leaving indented fenced code blocks.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Fix bad parsing of operators without spaces between them. Fix some corner cases around semicolon insertion and regexps.\n\n### New features\n\nModes added with [`addOverlay`](https://codemirror.net/doc/manual.html#addOverlay) now have access to a [`baseToken`](https://codemirror.net/doc/manual.html#baseToken) method on their input stream, giving access to the tokens of the underlying mode.\n\n## 5.30.0 (2017-09-20)\n\n### Bug fixes\n\nFixed a number of issues with drawing right-to-left selections and mouse selection in bidirectional text.\n\n[search addon](https://codemirror.net/demo/search/): Fix crash when restarting search after doing empty search.\n\n[mark-selection addon](http://cm/doc/manual.html#addon_mark-selection): Fix off-by-one bug.\n\n[tern addon](https://codemirror.net/demo/tern.html): Fix bad request made when editing at the bottom of a large document.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Improve parsing in a number of corner cases.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Fix crash when a sub-mode doesn't support indentation, allow uppercase X in task lists.\n\n[gfm mode](https://codemirror.net/mode/gfm/): Don't highlight SHA1 'hashes' without numbers to avoid false positives.\n\n[soy mode](https://codemirror.net/mode/soy/): Support injected data and `@param` in comments.\n\n### New features\n\n[simple mode addon](https://codemirror.net/demo/simplemode.html): Allow groups in regexps when `token` isn't an array.\n\n## 5.29.0 (2017-08-24)\n\n### Bug fixes\n\nFix crash in contentEditable input style when editing near a bookmark.\n\nMake sure change origins are preserved when splitting changes on [read-only marks](https://codemirror.net/doc/manual.html#mark_readOnly).\n\n[javascript mode](https://codemirror.net/mode/javascript/): More support for TypeScript syntax.\n\n[d mode](https://codemirror.net/mode/d/): Support nested comments.\n\n[python mode](https://codemirror.net/mode/python/): Improve tokenizing of operators.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Further improve CommonMark conformance.\n\n[css mode](https://codemirror.net/mode/css/): Don't run comment tokens through the mode's state machine.\n\n[shell mode](https://codemirror.net/mode/shell/): Allow strings to span lines.\n\n[search addon](https://codemirror.net/demo/search/): Fix crash in persistent search when `extraKeys` is null.\n\n## 5.28.0 (2017-07-21)\n\n### Bug fixes\n\nFix copying of, or replacing editor content with, a single dash character when copying a big selection in some corner cases.\n\nMake [`\"goLineLeft\"`](https://codemirror.net/doc/manual.html#command_goLineLeft)/`\"goLineRight\"` behave better on wrapped lines.\n\n[sql mode](https://codemirror.net/mode/sql/): Fix tokenizing of multi-dot operator and allow digits in subfield names.\n\n[searchcursor addon](https://codemirror.net/doc/manual.html#addon_searchcursor): Fix infinite loop on some composed character inputs.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Make list parsing more CommonMark-compliant.\n\n[gfm mode](https://codemirror.net/mode/gfm/): Highlight colon syntax for emoji.\n\n### New features\n\nExpose [`startOperation`](https://codemirror.net/doc/manual.html#startOperation) and `endOperation` for explicit operation management.\n\n[sublime bindings](https://codemirror.net/demo/sublime.html): Add extend-selection (Ctrl-Alt- or Cmd-Shift-Up/Down).\n\n## 5.27.4 (2017-06-29)\n\n### Bug fixes\n\nFix crash when using mode lookahead.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Don't block inner mode's indentation support.\n\n## 5.27.2 (2017-06-22)\n\n### Bug fixes\n\nFix crash in the [simple mode](https://codemirror.net/demo/simplemode.html)< addon.\n\n## 5.27.0 (2017-06-22)\n\n### Bug fixes\n\nFix infinite loop in forced display update.\n\nProperly disable the hidden textarea when `readOnly` is `\"nocursor\"`.\n\nCalling the `Doc` constructor without `new` works again.\n\n[sql mode](https://codemirror.net/mode/sql/): Handle nested comments.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Improve support for TypeScript syntax.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Fix bug where markup was ignored on indented paragraph lines.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Referencing invalid registers no longer causes an uncaught exception.\n\n[rust mode](https://codemirror.net/mode/rust/): Add the correct MIME type.\n\n[matchbrackets addon](https://codemirror.net/doc/manual.html#addon_matchbrackets): Document options.\n\n### New features\n\nMouse button clicks can now be bound in keymaps by using names like `\"LeftClick\"` or `\"Ctrl-Alt-MiddleTripleClick\"`. When bound to a function, that function will be passed the position of the click as second argument.\n\nThe behavior of mouse selection and dragging can now be customized with the [`configureMouse`](https://codemirror.net/doc/manual.html#option_configureMouse) option.\n\nModes can now look ahead across line boundaries with the [`StringStream`](https://codemirror.net/doc/manual.html#StringStream)`.lookahead` method.\n\nIntroduces a `\"type\"` token type, makes modes that recognize types output it, and add styling for it to the themes.\n\nNew [`pasteLinesPerSelection`](https://codemirror.net/doc/manual.html#option_pasteLinesPerSelection) option to control the behavior of pasting multiple lines into multiple selections.\n\n[searchcursor addon](https://codemirror.net/doc/manual.html#addon_searchcursor): Support multi-line regular expression matches, and normalize strings when matching.\n\n## 5.26.0 (2017-05-22)\n\n### Bug fixes\n\nIn textarea-mode, don't reset the input field during composition.\n\nMore careful restoration of selections in widgets, during editor redraw.\n\n[javascript mode](https://codemirror.net/mode/javascript/): More TypeScript parsing fixes.\n\n[julia mode](https://codemirror.net/mode/julia/): Fix issue where the mode gets stuck.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Understand cross-line links, parse all bracketed things as links.\n\n[soy mode](https://codemirror.net/mode/soy/): Support single-quoted strings.\n\n[go mode](https://codemirror.net/mode/go/): Don't try to indent inside strings or comments.\n\n### New features\n\n[vim bindings](https://codemirror.net/demo/vim.html): Parse line offsets in line or range specs.\n\n## 5.25.2 (2017-04-20)\n\n### Bug fixes\n\nBetter handling of selections that cover the whole viewport in contentEditable-mode.\n\nNo longer accidentally scroll the editor into view when calling `setValue`.\n\nWork around Chrome Android bug when converting screen coordinates to editor positions.\n\nMake sure long-clicking a selection sets a cursor and doesn't show the editor losing focus.\n\nFix issue where pointer events were incorrectly disabled on Chrome's overlay scrollbars.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Recognize annotations and TypeScript-style type parameters.\n\n[shell mode](https://codemirror.net/mode/shell/): Handle nested braces.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Make parsing of strong/em delimiters CommonMark-compliant.\n\n## 5.25.0 (2017-03-20)\n\n### Bug fixes\n\nIn contentEditable-mode, properly locate changes that repeat a character when inserted with IME.\n\nFix handling of selections bigger than the viewport in contentEditable mode.\n\nImprove handling of changes that insert or delete lines in contentEditable mode.\n\nCount Unicode control characters 0x80 to 0x9F as special (non-printing) chars.\n\nFix handling of shadow DOM roots when finding the active element.\n\nAdd `role=presentation` to more DOM elements to improve screen reader support.\n\n[merge addon](https://codemirror.net/doc/manual.html#addon_merge): Make aligning of unchanged chunks more robust.\n\n[comment addon](https://codemirror.net/doc/manual.html#addon_comment): Fix comment-toggling on a block of text that starts and ends in a (differnet) block comment.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Improve support for TypeScript syntax.\n\n[r mode](https://codemirror.net/mode/r/): Fix indentation after semicolon-less statements.\n\n[shell mode](https://codemirror.net/mode/shell/): Properly handle escaped parentheses in parenthesized expressions.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Fix a few bugs around leaving fenced code blocks.\n\n[soy mode](https://codemirror.net/mode/soy/): Improve indentation.\n\n### New features\n\n[lint addon](https://codemirror.net/doc/manual.html#addon_lint): Support asynchronous linters that return promises.\n\n[continuelist addon](https://codemirror.net/doc/manual.html#addon_continuelist): Support continuing task lists.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Make Y behave like yy.\n\n[sql mode](https://codemirror.net/mode/sql/): Support sqlite dialect.\n\n## 5.24.2 (2017-02-22)\n\n### Bug fixes\n\n[javascript mode](https://codemirror.net/mode/javascript/): Support computed class method names.\n\n[merge addon](https://codemirror.net/doc/manual.html#addon_merge): Improve aligning of unchanged code in the presence of marks and line widgets.\n\n## 5.24.0 (2017-02-20)\n\n### Bug fixes\n\nA cursor directly before a line-wrapping break is now drawn before or after the line break depending on which direction you arrived from.\n\nVisual cursor motion in line-wrapped right-to-left text should be much more correct.\n\nFix bug in handling of read-only marked text.\n\n[shell mode](https://codemirror.net/mode/shell/): Properly tokenize nested parentheses.\n\n[python mode](https://codemirror.net/mode/python/): Support underscores in number literals.\n\n[sass mode](https://codemirror.net/mode/sass/): Uses the full list of CSS properties and keywords from the CSS mode, rather than defining its own incomplete subset.\n\n[css mode](https://codemirror.net/mode/css/): Expose `lineComment` property for LESS and SCSS dialects. Recognize vendor prefixes on pseudo-elements.\n\n[julia mode](https://codemirror.net/mode/julia/): Properly indent `elseif` lines.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Properly recognize the end of fenced code blocks when inside other markup.\n\n[scala mode](https://codemirror.net/mode/clike/): Improve handling of operators containing <code>#</code>, <code>@</code>, and <code>:</code> chars.\n\n[xml mode](https://codemirror.net/mode/xml/): Allow dashes in HTML tag names.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Improve parsing of async methods, TypeScript-style comma-separated superclass lists.\n\n[indent-fold addon](https://codemirror.net/demo/folding.html): Ignore comment lines.\n\n### New features\n\nPositions now support a `sticky` property which determines whether they should be associated with the character before (value `\"before\"`) or after (value `\"after\"`) them.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Make it possible to remove built-in bindings through the API.\n\n[comment addon](https://codemirror.net/doc/manual.html#addon_comment): Support a per-mode <code>useInnerComments</code> option to optionally suppress descending to the inner modes to get comment strings.\n\n### Breaking changes\n\nThe [sass mode](https://codemirror.net/mode/sass/) now depends on the [css mode](https://codemirror.net/mode/css/).\n\n## 5.23.0 (2017-01-19)\n\n### Bug fixes\n\nPresentation-related elements DOM elements are now marked as such to help screen readers.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Be more picky about what HTML tags look like to avoid false positives.\n\n### New features\n\n`findModeByMIME` now understands `+json` and `+xml` MIME suffixes.\n\n[closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Add support for an `override` option to ignore language-specific defaults.\n\n[panel addon](https://codemirror.net/doc/manual.html#addon_panel): Add a `stable` option that auto-scrolls the content to keep it in the same place when inserting/removing a panel.\n\n## 5.22.2 (2017-01-12)\n\n### Bug fixes\n\nInclude rollup.config.js in NPM package, so that it can be used to build from source.\n\n## 5.22.0 (2016-12-20)\n\n### Bug fixes\n\n[sublime bindings](https://codemirror.net/demo/sublime.html): Make `selectBetweenBrackets` work with multiple cursors.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Fix issues with parsing complex TypeScript types, imports, and exports.\n\nA contentEditable editor instance with autofocus enabled no longer crashes during initializing.\n\n### New features\n\n[emacs bindings](https://codemirror.net/demo/emacs.html): Export `CodeMirror.emacs` to allow other addons to hook into Emacs-style functionality.\n\n[active-line addon](https://codemirror.net/doc/manual.html#addon_active-line): Add `nonEmpty` option.\n\nNew event: [`optionChange`](https://codemirror.net/doc/manual.html#event_optionChange).\n\n## 5.21.0 (2016-11-21)\n\n### Bug fixes\n\nTapping/clicking the editor in [contentEditable mode](https://codemirror.net/doc/manual.html#option_inputStyle) on Chrome now puts the cursor at the tapped position.\n\nFix various crashes and misbehaviors when reading composition events in [contentEditable mode](https://codemirror.net/doc/manual.html#option_inputStyle).\n\nCatches and ignores an IE 'Unspecified Error' when creating an editor in an iframe before there is a `<body>`.\n\n[merge addon](https://codemirror.net/doc/manual.html#addon_merge): Fix several issues in the chunk-aligning feature.\n\n[verilog mode](https://codemirror.net/mode/verilog): Rewritten to address various issues.\n\n[julia mode](https://codemirror.net/mode/julia): Recognize Julia 0.5 syntax.\n\n[swift mode](https://codemirror.net/mode/swift): Various fixes and adjustments to current syntax.\n\n[markdown mode](https://codemirror.net/mode/markdown): Allow lists without a blank line above them.\n\n### New features\n\nThe [`setGutterMarker`](https://codemirror.net/doc/manual.html#setGutterMarker), [`clearGutter`](https://codemirror.net/doc/manual.html#clearGutter), and [`lineInfo`](https://codemirror.net/doc/manual.html#lineInfo) methods are now available on `Doc` objects.\n\nThe [`heightAtLine`](https://codemirror.net/doc/manual.html#heightAtLine) method now takes an extra argument to allow finding the height at the top of the line's line widgets.\n\n[ruby mode](https://codemirror.net/mode/ruby): `else` and `elsif` are now immediately indented.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Bind Ctrl-T and Ctrl-D to in- and dedent in insert mode.\n\n## 5.20.2 (2016-10-21)\n\n### Bug fixes\n\nFix `CodeMirror.version` returning the wrong version number.\n\n## 5.20.0 (2016-10-20)\n\n### Bug fixes\n\nMake `newlineAndIndent` command work with multiple cursors on the same line.\n\nMake sure keypress events for backspace are ignored.\n\nTokens styled with overlays no longer get a nonsense `cm-cm-overlay` class.\n\nLine endings for pasted content are now normalized to the editor's [preferred ending](https://codemirror.net/doc/manual.html#option_lineSeparator).\n\n[javascript mode](https://codemirror.net/mode/javascript): Improve support for class expressions. Support TypeScript optional class properties, the `abstract` keyword, and return type declarations for arrow functions.\n\n[css mode](https://codemirror.net/mode/css): Fix highlighting of mixed-case keywords.\n\n[closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Improve behavior when typing a quote before a string.\n\n### New features\n\nThe core is now maintained as a number of small files, using ES6 syntax and modules, under the `src/` directory. A git checkout no longer contains a working `codemirror.js` until you `npm build` (but when installing from NPM, it is included).\n\nThe [`refresh`](https://codemirror.net/doc/manual.html#event_refresh) event is now documented and stable.\n\n## 5.19.0 (2016-09-20)\n\n### Bugfixes\n\n[erlang mode](https://codemirror.net/mode/erlang): Fix mode crash when trying to read an empty context.\n\n[comment addon](https://codemirror.net/doc/manual.html#addon_comment): Fix broken behavior when toggling comments inside a comment.\n\nxml-fold addon: Fix a null-dereference bug.\n\nPage up and page down now do something even in single-line documents.\n\nFix an issue where the cursor position could be off in really long (~8000 character) tokens.\n\n### New features\n\n[javascript mode](https://codemirror.net/mode/javascript): Better indentation when semicolons are missing. Better support for TypeScript classes, optional parameters, and the `type` keyword.\n\nThe [`blur`](https://codemirror.net/doc/manual.html#event_blur) and [`focus`](https://codemirror.net/doc/manual.html#event_focus) events now pass the DOM event to their handlers.\n\n## 5.18.2 (2016-08-23)\n\n### Bugfixes\n\n[vue mode](https://codemirror.net/mode/vue): Fix outdated references to renamed Pug mode dependency.\n\n## 5.18.0 (2016-08-22)\n\n### Bugfixes\n\nMake sure [gutter backgrounds](https://codemirror.net/doc/manual.html#addLineClass) stick to the rest of the gutter during horizontal scrolling.\n\nThe contenteditable [`inputStyle`](https://codemirror.net/doc/manual.html#option_inputStyle) now properly supports pasting on pre-Edge IE versions.\n\n[javascript mode](https://codemirror.net/mode/javascript): Fix some small parsing bugs and improve TypeScript support.\n\n[matchbrackets addon](https://codemirror.net/doc/manual.html#addon_matchbrackets): Fix bug where active highlighting was left in editor when the addon was disabled.\n\n[match-highlighter addon](https://codemirror.net/doc/manual.html#addon_match-highlighter): Only start highlighting things when the editor gains focus.\n\n[javascript-hint addon](https://codemirror.net/doc/manual.html#addon_javascript-hint): Also complete non-enumerable properties.\n\n### New features\n\nThe [`addOverlay`](https://codemirror.net/doc/manual.html#addOverlay) method now supports a `priority` option to control the order in which overlays are applied.\n\nMIME types that end in `+json` now default to the JSON mode when the MIME itself is not defined.\n\n### Breaking changes\n\nThe mode formerly known as Jade was renamed to [Pug](https://codemirror.net/mode/pug).\n\nThe [Python mode](https://codemirror.net/mode/python) now defaults to Python 3 (rather than 2) syntax.\n\n## 5.17.0 (2016-07-19)\n\n### Bugfixes\n\nFix problem with wrapped trailing whitespace displaying incorrectly.\n\nPrevent IME dialog from overlapping typed content in Chrome.\n\nImprove measuring of characters near a line wrap.\n\n[javascript mode](https://codemirror.net/mode/javascript): Improve support for `async`, allow trailing commas in `import` lists.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Fix backspace in replace mode.\n\n[sublime bindings](https://codemirror.net/demo/sublime.html): Fix some key bindings on OS X to match Sublime Text.\n\n### New features\n\n[markdown mode](https://codemirror.net/mode/markdown): Add more classes to image links in highlight-formatting mode.\n\n## 5.16.0 (2016-06-20)\n\n### Bugfixes\n\nFix glitches when dragging content caused by the drop indicator receiving mouse events.\n\nMake Control-drag work on Firefox.\n\nMake clicking or selection-dragging at the end of a wrapped line select the right position.\n\n[show-hint addon](https://codemirror.net/doc/manual.html#addon_show-hint): Prevent widget scrollbar from hiding part of the hint text.\n\n[rulers addon](https://codemirror.net/doc/manual.html#addon_rulers): Prevent rulers from forcing a horizontal editor scrollbar.\n\n### New features\n\n[search addon](https://codemirror.net/doc/manual.html#addon_search): Automatically bind search-related keys in persistent dialog.\n\n[sublime keymap](https://codemirror.net/demo/sublime.html): Add a multi-cursor aware smart backspace binding.\n\n## 5.15.2 (2016-05-20)\n\n### Bugfixes\n\nFix a critical document corruption bug that occurs when a document is gradually grown.\n\n## 5.15.0 (2016-05-20)\n\n### Bugfixes\n\nFix bug that caused the selection to reset when focusing the editor in contentEditable input mode.\n\nFix issue where not all ASCII control characters were being replaced by placeholders.\n\nRemove the assumption that all modes have a `startState` method from several wrapping modes.\n\nFix issue where the editor would complain about overlapping collapsed ranges when there weren't any.\n\nOptimize document tree building when loading or pasting huge chunks of content.\n\n[markdown mode](https://codemirror.net/mode/markdown/): Fix several issues in matching link targets.\n\n[clike mode](https://codemirror.net/mode/clike/): Improve indentation of C++ template declarations.\n\n### New features\n\nExplicitly bind Ctrl-O on OS X to make that binding (“open line”) act as expected.\n\nPasting [linewise-copied](https://codemirror.net/doc/manual.html#option_lineWiseCopyCut) content when there is no selection now inserts the lines above the current line.\n\n[javascript mode](https://codemirror.net/mode/javascript/): Support `async`/`await` and improve support for TypeScript type syntax.\n\n## 5.14.2 (2016-04-20)\n\n### Bugfixes\n\nPush a new package to NPM due to an [NPM bug](https://github.com/npm/npm/issues/5082) omitting the LICENSE file in 5.14.0.\n\nSet `dataTransfer.effectAllowed` in `dragstart` handler to help browsers use the right drag icon.\n\nAdd the [mbox mode](https://codemirror.net/mode/mbox/index.html) to `mode/meta.js`.\n\n## 5.14.0 (2016-04-20)\n\n### Bugfixes\n\n[`posFromIndex`](https://codemirror.net/doc/manual.html#posFromIndex) and [`indexFromPos`](https://codemirror.net/doc/manual.html#indexFromPos) now take [`lineSeparator`](https://codemirror.net/doc/manual.html#option_lineSeparator) into account.\n\n[vim bindings](https://codemirror.net/demo/vim.html): Only call `.save()` when it is actually available.\n\n[comment addon](https://codemirror.net/doc/manual.html#addon_comment): Be careful not to mangle multi-line strings.\n\n[Python mode](https://codemirror.net/mode/python/index.html): Improve distinguishing of decorators from `@` operators.\n\n[`findMarks`](https://codemirror.net/doc/manual.html#findMarks): No longer return marks that touch but don't overlap given range.\n\n### New features\n\n[vim bindings](https://codemirror.net/demo/vim.html): Add yank command.\n\n[match-highlighter addon](https://codemirror.net/doc/manual.html#addon_match-highlighter): Add `trim` option to disable ignoring of whitespace.\n\n[PowerShell mode](https://codemirror.net/mode/powershell/index.html): Added.\n\n[Yacas mode](https://codemirror.net/mode/yacas/index.html): Added.\n\n[Web IDL mode](https://codemirror.net/mode/webidl/index.html): Added.\n\n[SAS mode](https://codemirror.net/mode/sas/index.html): Added.\n\n[mbox mode](https://codemirror.net/mode/mbox/index.html): Added.\n\n## 5.13.2 (2016-03-23)\n\n### Bugfixes\n\nSolves a problem where the gutter would sometimes not extend all the way to the end of the document.\n\n## 5.13.0 (2016-03-21)\n\n### New features\n\nNew DOM event forwarded: [`\"dragleave\"`](https://codemirror.net/doc/manual.html#event_dom).\n\n[protobuf mode](https://codemirror.net/mode/protobuf/index.html): Newly added.\n\n### Bugfixes\n\nFix problem where [`findMarks`](https://codemirror.net/doc/manual.html#findMarks) sometimes failed to find multi-line marks.\n\nFix crash that showed up when atomic ranges and bidi text were combined.\n\n[show-hint addon](https://codemirror.net/demo/complete.html): Completion widgets no longer close when the line indented or dedented.\n\n[merge addon](https://codemirror.net/demo/merge.html): Fix bug when merging chunks at the end of the file.\n\n[placeholder addon](https://codemirror.net/doc/manual.html#addon_placeholder): No longer gets confused by [`swapDoc`](https://codemirror.net/doc/manual.html#swapDoc).\n\n[simplescrollbars addon](https://codemirror.net/doc/manual.html#addon_simplescrollbars): Fix invalid state when deleting at end of document.\n\n[clike mode](https://codemirror.net/mode/clike/index.html): No longer gets confused when a comment starts after an operator.\n\n[markdown mode](https://codemirror.net/mode/markdown/index.html): Now supports CommonMark-style flexible list indentation.\n\n[dylan mode](https://codemirror.net/mode/dylan/index.html): Several improvements and fixes.\n\n## 5.12.0 (2016-02-19)\n\n### New features\n\n[Vim bindings](https://codemirror.net/demo/vim.html): Ctrl-Q is now an alias for Ctrl-V.\n\n[Vim bindings](https://codemirror.net/demo/vim.html): The Vim API now exposes an `unmap` method to unmap bindings.\n\n[active-line addon](https://codemirror.net/demo/activeline.html): This addon can now style the active line's gutter.\n\n[FCL mode](https://codemirror.net/mode/fcl/): Newly added.\n\n[SQL mode](https://codemirror.net/mode/sql/): Now has a Postgresql dialect.\n\n### Bugfixes\n\nFix [issue](https://github.com/codemirror/CodeMirror/issues/3781) where trying to scroll to a horizontal position outside of the document's width could cause the gutter to be positioned incorrectly.\n\nUse absolute, rather than fixed positioning in the context-menu intercept hack, to work around a [problem](https://github.com/codemirror/CodeMirror/issues/3238) when the editor is inside a transformed parent container.\n\nSolve a [problem](https://github.com/codemirror/CodeMirror/issues/3821) where the horizontal scrollbar could hide text in Firefox.\n\nFix a [bug](https://github.com/codemirror/CodeMirror/issues/3834) that caused phantom scroll space under the text in some situations.\n\n[Sublime Text bindings](https://codemirror.net/demo/sublime.html): Bind delete-line to Shift-Ctrl-K on OS X.\n\n[Markdown mode](https://codemirror.net/mode/markdown/): Fix [issue](https://github.com/codemirror/CodeMirror/issues/3787) where the mode would keep state related to fenced code blocks in an unsafe way, leading to occasional corrupted parses.\n\n[Markdown mode](https://codemirror.net/mode/markdown/): Ignore backslashes in code fragments.\n\n[Markdown mode](https://codemirror.net/mode/markdown/): Use whichever mode is registered as `text/html` to parse HTML.\n\n[Clike mode](https://codemirror.net/mode/clike/): Improve indentation of Scala `=>` functions.\n\n[Python mode](https://codemirror.net/mode/python/): Improve indentation of bracketed code.\n\n[HTMLMixed mode](https://codemirror.net/mode/htmlmixed/): Support multi-line opening tags for sub-languages (`<script>`, `<style>`, etc).\n\n[Spreadsheet mode](https://codemirror.net/mode/spreadsheet/): Fix bug where the mode did not advance the stream when finding a backslash.\n\n[XML mode](https://codemirror.net/mode/xml/): The mode now takes a `matchClosing` option to configure whether mismatched closing tags should be highlighted as errors.\n\n## 5.11.0 (2016-01-20)\n\n* New modes: [JSX](https://codemirror.net/mode/jsx/index.html), [literate Haskell](https://codemirror.net/mode/haskell-literate/index.html)\n* The editor now forwards more [DOM events](https://codemirror.net/doc/manual.html#event_dom): `cut`, `copy`, `paste`, and `touchstart`. It will also forward `mousedown` for drag events\n* Fixes a bug where bookmarks next to collapsed spans were not rendered\n* The [Swift](https://codemirror.net/mode/swift/index.html) mode now supports auto-indentation\n* Frontmatters in the [YAML frontmatter](https://codemirror.net/mode/yaml-frontmatter/index.html) mode are now optional as intended\n\n## 5.10.0 (2015-12-21)\n\n* Modify the way [atomic ranges](https://codemirror.net/doc/manual.html#mark_atomic) are skipped by selection to try and make it less surprising.\n* The [Swift mode](https://codemirror.net/mode/swift/index.html) was rewritten.\n* New addon: [jump-to-line](https://codemirror.net/doc/manual.html#addon_jump-to-line).\n* New method: [`isReadOnly`](https://codemirror.net/doc/manual.html#isReadOnly).\n* The [show-hint addon](https://codemirror.net/doc/manual.html#addon_show-hint) now defaults to picking completions on single click.\n* The object passed to [`\"beforeSelectionChange\"`](https://codemirror.net/doc/manual.html#event_beforeSelectionChange) events now has an `origin` property.\n* New mode: [Crystal](https://codemirror.net/mode/crystal/index.html).\n\n## 5.9.0 (2015-11-23)\n\n* Improve the way overlay (OS X-style) scrollbars are handled\n* Make [annotatescrollbar](https://codemirror.net/doc/manual.html#addon_annotatescrollbar) and scrollpastend addons work properly together\n* Make [show-hint](https://codemirror.net/doc/manual.html#addon_show-hint) addon select options on single click by default, move selection to hovered item\n* Properly fold comments that include block-comment-start markers\n* Many small language mode fixes\n\n## 5.8.0 (2015-10-20)\n\n* Fixes an infinite loop in the [hardwrap addon](https://codemirror.net/doc/manual.html#addon_hardwrap)\n* New modes: [NSIS](https://codemirror.net/mode/nsis/index.html), [Ceylon](https://codemirror.net/mode/clike/index.html)\n* The Kotlin mode is now a [clike](https://codemirror.net/mode/clike/index.html) dialect, rather than a stand-alone mode\n* New option: [`allowDropFileTypes`](https://codemirror.net/doc/manual.html#option_allowDropFileTypes). Binary files can no longer be dropped into CodeMirror\n* New themes: [bespin](https://codemirror.net/demo/theme.html#bespin), [hopscotch](https://codemirror.net/demo/theme.html#hopscotch), [isotope](https://codemirror.net/demo/theme.html#isotope), [railscasts](https://codemirror.net/demo/theme.html#railscasts)\n\n## 5.7.0 (2015-09-21)\n\n* New modes: [Vue](https://codemirror.net/mode/vue/index.html), [Oz](https://codemirror.net/mode/oz/index.html), [MscGen](https://codemirror.net/mode/mscgen/index.html) (and dialects), [Closure Stylesheets](https://codemirror.net/mode/css/gss.html)\n* Implement [CommonMark](http://commonmark.org)-style flexible list indent and cross-line code spans in [Markdown](https://codemirror.net/mode/markdown/index.html) mode\n* Add a replace-all button to the [search addon](https://codemirror.net/doc/manual.html#addon_search), and make the persistent search dialog transparent when it obscures the match\n* Handle `acync`/`await` and ocal and binary numbers in [JavaScript mode](https://codemirror.net/mode/javascript/index.html)\n* Fix various issues with the [Haxe mode](https://codemirror.net/mode/haxe/index.html)\n* Make the [closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets) select only the wrapped text when wrapping selection in brackets\n* Tokenize properties as properties in the [CoffeeScript mode](https://codemirror.net/mode/coffeescript/index.html)\n* The [placeholder addon](https://codemirror.net/doc/manual.html#addon_placeholder) now accepts a DOM node as well as a string placeholder\n\n## 5.6.0 (2015-08-20)\n\n* Fix bug where you could paste into a `readOnly` editor\n* Show a cursor at the drop location when dragging over the editor\n* The [Rust mode](https://codemirror.net/mode/rust/index.html) was rewritten to handle modern Rust\n* The editor and theme CSS was cleaned up. Some selectors are now less specific than before\n* New theme: [abcdef](https://codemirror.net/demo/theme.html#abcdef)\n* Lines longer than [`maxHighlightLength`](https://codemirror.net/doc/manual.html#option_maxHighlightLength) are now less likely to mess up indentation\n* New addons: [`autorefresh`](https://codemirror.net/doc/manual.html#addon_autorefresh) for refreshing an editor the first time it becomes visible, and `html-lint` for using [HTMLHint](http://htmlhint.com/)\n* The [`search`](https://codemirror.net/doc/manual.html#addon_search) addon now recognizes `\\r` and `\\n` in pattern and replacement input\n\n## 5.5.0 (2015-07-20)\n\n*   New option: [`lineSeparator`](https://codemirror.net/doc/manual.html#option_lineSeparator) (with corresponding [method](https://codemirror.net/doc/manual.html#lineSeparator))\n*   New themes: [dracula](https://codemirror.net/demo/theme.html#dracula), [seti](https://codemirror.net/demo/theme.html#seti), [yeti](https://codemirror.net/demo/theme.html#yeti), [material](https://codemirror.net/demo/theme.html#material), and [icecoder](https://codemirror.net/demo/theme.html#icecoder)\n*   New modes: [Brainfuck](https://codemirror.net/mode/brainfuck/index.html), [VHDL](https://codemirror.net/mode/vhdl/index.html), Squirrel ([clike](https://codemirror.net/mode/clike/index.html) dialect)\n*   Define a `findPersistent` command in the [search](https://codemirror.net/demo/search.html) addon, for a dialog that stays open as you cycle through matches\n*   From this release on, the NPM module doesn't include documentation and demos\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/5.4.0...5.5.0)\n\n## 5.4.0 (2015-06-25)\n\n*   New modes: [Twig](https://codemirror.net/mode/twig/index.html), [Elm](https://codemirror.net/mode/elm/index.html), [Factor](https://codemirror.net/mode/factor/index.html), [Swift](https://codemirror.net/mode/swift/index.html)\n*   Prefer clipboard API (if available) when pasting\n*   Refined definition highlighting in [clike](https://codemirror.net/mode/clike/index.html) mode\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/5.3.0...5.4.0)\n\n## 5.3.0 (2015-05-20)\n\n*   Fix several regressions in the [`show-hint`](https://codemirror.net/doc/manual.html#addon_show-hint) addon (`completeSingle` option, `\"shown\"` and `\"close\"` events)\n*   The [vim mode](https://codemirror.net/demo/vim.html) API was [documented](https://codemirror.net/doc/manual.html#vimapi)\n*   New modes: [ASN.1](https://codemirror.net/mode/asn.1/index.html), [TTCN](https://codemirror.net/mode/ttcn/index.html), and [TTCN-CFG](https://codemirror.net/mode/ttcn-cfg/index.html)\n*   The [clike](https://codemirror.net/mode/clike/index.html) mode can now deep-indent `switch` statements, and roughly recognizes types and defined identifiers\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/5.2.0...5.3.0)\n\n## 5.2.0 (2015-04-20)\n\n*   Fix several race conditions in [`show-hint`](https://codemirror.net/doc/manual.html#addon_show-hint)'s asynchronous mode\n*   Fix backspace binding in [Sublime bindings](https://codemirror.net/demo/sublime.html)\n*   Change the way IME is handled in the `\"textarea\"` [input style](https://codemirror.net/doc/manual.html#option_inputStyle)\n*   New modes: [MUMPS](https://codemirror.net/mode/mumps/index.html), [Handlebars](https://codemirror.net/mode/handlebars/index.html)\n*   Rewritten modes: [Django](https://codemirror.net/mode/django/index.html), [Z80](https://codemirror.net/mode/z80/index.html)\n*   New theme: [Liquibyte](https://codemirror.net/demo/theme.html#liquibyte)\n*   New option: [`lineWiseCopyCut`](https://codemirror.net/doc/manual.html#option_lineWiseCopyCut)\n*   The [Vim mode](https://codemirror.net/demo/vim.html) now supports buffer-local options and the `filetype` setting\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/5.1.0...5.2.0)\n\n## 5.1.0 (2015-03-23)\n\n*   New modes: [ASCII armor](https://codemirror.net/mode/asciiarmor/index.html) (PGP data), [Troff](https://codemirror.net/mode/troff/index.html), and [CMake](https://codemirror.net/mode/cmake/index.html).\n*   Remove SmartyMixed mode, rewrite [Smarty](https://codemirror.net/mode/smarty/index.html) mode to supersede it.\n*   New commands in the [merge addon](https://codemirror.net/doc/manual.html#addon_merge): `goNextDiff` and `goPrevDiff`.\n*   The [closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets) can now be configured per mode.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/5.0.0...5.1.0).\n\n## 5.0.0 (2015-02-20)\n\n*   Experimental mobile support (tested on iOS, Android Chrome, stock Android browser)\n*   New option [`inputStyle`](https://codemirror.net/doc/manual.html#option_inputStyle) to switch between hidden textarea and contenteditable input.\n*   The [`getInputField`](https://codemirror.net/doc/manual.html#getInputField) method is no longer guaranteed to return a textarea.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.13.0...5.0.0).\n\n## 4.13.0 (2015-02-20)\n\n*   Fix the way the [`closetag`](https://codemirror.net/demo/closetag.html) demo handles the slash character.\n*   New modes: [Forth](https://codemirror.net/mode/forth/index.html), [Stylus](https://codemirror.net/mode/stylus/index.html).\n*   Make the [CSS mode](https://codemirror.net/mode/css/index.html) understand some modern CSS extensions.\n*   Have the [Scala mode](https://codemirror.net/mode/clike/index.html) handle symbols and triple-quoted strings.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.12.0...4.13.0).\n\n## 4.12.0 (2015-01-22)\n\n*   The [`closetag`](https://codemirror.net/doc/manual.html#addon_closetag) addon now defines a `\"closeTag\"` command.\n*   Adds a `findModeByFileName` to the [mode metadata](https://codemirror.net/doc/manual.html#addon_meta) addon.\n*   [Simple mode](https://codemirror.net/demo/simplemode.html) rules can now contain a `sol` property to only match at the start of a line.\n*   New addon: [`selection-pointer`](https://codemirror.net/doc/manual.html#addon_selection-pointer) to style the mouse cursor over the selection.\n*   Improvements to the [Sass mode](https://codemirror.net/mode/sass/index.html)'s indentation.\n*   The [Vim keymap](https://codemirror.net/demo/vim.html)'s search functionality now supports [scrollbar annotation](https://codemirror.net/doc/manual.html#addon_matchesonscrollbar).\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.11.0...4.12.0).\n\n## 4.11.0 (2015-01-09)\n\nUnfortunately, 4.10 did not take care of the Firefox scrolling issue entirely. This release adds two more patches to address that.\n\n## 4.10.0 (2014-12-29)\n\nEmergency single-patch update to 4.9\\. Fixes Firefox-specific problem where the cursor could end up behind the horizontal scrollbar.\n\n## 4.9.0 (2014-12-23)\n\n*   Overhauled scroll bar handling. Add pluggable [scrollbar implementations](https://codemirror.net/demo/simplescrollbars.html).\n*   Tweaked behavior for the [completion addons](https://codemirror.net/doc/manual.html#addon_show-hint) to not take text after cursor into account.\n*   Two new optional features in the [merge addon](https://codemirror.net/doc/manual.html#addon_merge): aligning editors, and folding unchanged text.\n*   New modes: [Dart](https://codemirror.net/mode/dart/index.html), [EBNF](https://codemirror.net/mode/ebnf/index.html), [spreadsheet](https://codemirror.net/mode/spreadsheet/index.html), and [Soy](https://codemirror.net/mode/soy/index.html).\n*   New [addon](https://codemirror.net/demo/panel.html) to show persistent panels below/above an editor.\n*   New themes: [zenburn](https://codemirror.net/demo/theme.html#zenburn) and [tomorrow night bright](https://codemirror.net/demo/theme.html#tomorrow-night-bright).\n*   Allow ctrl-click to clear existing cursors.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.8.0...4.9.0).\n\n## 4.8.0 (2014-11-22)\n\n*   Built-in support for [multi-stroke key bindings](https://codemirror.net/doc/manual.html#normalizeKeyMap).\n*   New method: [`getLineTokens`](https://codemirror.net/doc/manual.html#getLineTokens).\n*   New modes: [dockerfile](https://codemirror.net/mode/dockerfile/index.html), [IDL](https://codemirror.net/mode/idl/index.html), [Objective C](https://codemirror.net/mode/clike/index.html) (crude).\n*   Support styling of gutter backgrounds, allow `\"gutter\"` styles in [`addLineClass`](https://codemirror.net/doc/manual.html#addLineClass).\n*   Many improvements to the [Vim mode](https://codemirror.net/demo/vim.html), rewritten visual mode.\n*   Improvements to modes: [gfm](https://codemirror.net/mode/gfm/index.html) (strikethrough), [SPARQL](https://codemirror.net/mode/sparql/index.html) (version 1.1 support), and [sTeX](https://codemirror.net/mode/stex/index.html) (no more runaway math mode).\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.7.0...4.8.0).\n\n## 4.7.0 (2014-10-20)\n\n*   **Incompatible**: The [lint addon](https://codemirror.net/demo/lint.html) now passes the editor's value as first argument to asynchronous lint functions, for consistency. The editor is still passed, as fourth argument.\n*   Improved handling of unicode identifiers in modes for languages that support them.\n*   More mode improvements: [CoffeeScript](https://codemirror.net/mode/coffeescript/index.html) (indentation), [Verilog](https://codemirror.net/mode/verilog/index.html) (indentation), [Scala](https://codemirror.net/mode/clike/index.html) (indentation, triple-quoted strings), and [PHP](https://codemirror.net/mode/php/index.html) (interpolated variables in heredoc strings).\n*   New modes: [Textile](https://codemirror.net/mode/textile/index.html) and [Tornado templates](https://codemirror.net/mode/tornado/index.html).\n*   Experimental new [way to define modes](https://codemirror.net/demo/simplemode.html).\n*   Improvements to the [Vim bindings](https://codemirror.net/demo/vim.html): Arbitrary insert mode key mappings are now possible, and text objects are supported in visual mode.\n*   The mode [meta-information file](https://codemirror.net/mode/meta.js) now includes information about file extensions, and [helper functions](https://codemirror.net/doc/manual.html#addon_meta) `findModeByMIME` and `findModeByExtension`.\n*   New logo!\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.6.0...4.7.0).\n\n## 4.6.0 (2014-09-19)\n\n*   New mode: [Modelica](https://codemirror.net/mode/modelica/index.html)\n*   New method: [`findWordAt`](https://codemirror.net/doc/manual.html#findWordAt)\n*   Make it easier to [use text background styling](https://codemirror.net/demo/markselection.html)\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.5.0...4.6.0).\n\n## 4.5.0 (2014-08-21)\n\n*   Fix several serious bugs with horizontal scrolling\n*   New mode: [Slim](https://codemirror.net/mode/slim/index.html)\n*   New command: [`goLineLeftSmart`](https://codemirror.net/doc/manual.html#command_goLineLeftSmart)\n*   More fixes and extensions for the [Vim](https://codemirror.net/demo/vim.html) visual block mode\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.4.0...4.5.0).\n\n## 4.4.0 (2014-07-21)\n\n*   **Note:** Some events might now fire in slightly different order (`\"change\"` is still guaranteed to fire before `\"cursorActivity\"`)\n*   Nested operations in multiple editors are now synced (complete at same time, reducing DOM reflows)\n*   Visual block mode for [vim](https://codemirror.net/demo/vim.html) (<C-v>) is nearly complete\n*   New mode: [Kotlin](https://codemirror.net/mode/kotlin/index.html)\n*   Better multi-selection paste for text copied from multiple CodeMirror selections\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.3.0...4.4.0).\n\n## 4.3.0 (2014-06-23)\n\n*   Several [vim bindings](https://codemirror.net/demo/vim.html) improvements: search and exCommand history, global flag for `:substitute`, `:global` command.\n*   Allow hiding the cursor by setting [`cursorBlinkRate`](https://codemirror.net/doc/manual.html#option_cursorBlinkRate) to a negative value.\n*   Make gutter markers themeable, use this in foldgutter.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.2.0...4.3.0).\n\n## 4.2.0 (2014-05-19)\n\n*   Fix problem where some modes were broken by the fact that empty tokens were forbidden.\n*   Several fixes to context menu handling.\n*   On undo, scroll _change_, not cursor, into view.\n*   Rewritten [Jade](https://codemirror.net/mode/jade/index.html) mode.\n*   Various improvements to [Shell](https://codemirror.net/mode/shell/index.html) (support for more syntax) and [Python](https://codemirror.net/mode/python/index.html) (better indentation) modes.\n*   New mode: [Cypher](https://codemirror.net/mode/cypher/index.html).\n*   New theme: [Neo](https://codemirror.net/demo/theme.html#neo).\n*   Support direct styling options (color, line style, width) in the [rulers](https://codemirror.net/doc/manual.html#addon_rulers) addon.\n*   Recognize per-editor configuration for the [show-hint](https://codemirror.net/doc/manual.html#addon_show-hint) and [foldcode](https://codemirror.net/doc/manual.html#addon_foldcode) addons.\n*   More intelligent scanning for existing close tags in [closetag](https://codemirror.net/doc/manual.html#addon_closetag) addon.\n*   In the [Vim bindings](https://codemirror.net/demo/vim.html): Fix bracket matching, support case conversion in visual mode, visual paste, append action.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.1.0...4.2.0).\n\n## 4.1.0 (2014-04-22)\n\n*   _Slightly incompatible_: The [`\"cursorActivity\"`](https://codemirror.net/doc/manual.html#event_cursorActivity) event now fires after all other events for the operation (and only for handlers that were actually registered at the time the activity happened).\n*   New command: [`insertSoftTab`](https://codemirror.net/doc/manual.html#command_insertSoftTab).\n*   New mode: [Django](https://codemirror.net/mode/django/index.html).\n*   Improved modes: [Verilog](https://codemirror.net/mode/verilog/index.html) (rewritten), [Jinja2](https://codemirror.net/mode/jinja2/index.html), [Haxe](https://codemirror.net/mode/haxe/index.html), [PHP](https://codemirror.net/mode/php/index.html) (string interpolation highlighted), [JavaScript](https://codemirror.net/mode/javascript/index.html) (indentation of trailing else, template strings), [LiveScript](https://codemirror.net/mode/livescript/index.html) (multi-line strings).\n*   Many small issues from the 3.x→4.x transition were found and fixed.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/4.0.3...4.1.0).\n\n## 3.24.0 (2014-04-22)\n\nMerges the improvements from 4.1 that could easily be applied to the 3.x code. Also improves the way the editor size is updated when line widgets change.\n\n## 3.23.0 (2014-03-20)\n\n*   In the [XML mode](https://codemirror.net/mode/xml/index.html), add `brackets` style to angle brackets, fix case-sensitivity of tags for HTML.\n*   New mode: [Dylan](https://codemirror.net/mode/dylan/index.html).\n*   Many improvements to the [Vim bindings](https://codemirror.net/demo/vim.html).\n\n## 3.22.0 (2014-02-21)\n\n*   Adds the [`findMarks`](https://codemirror.net/doc/manual.html#findMarks) method.\n*   New addons: [rulers](https://codemirror.net/doc/manual.html#addon_rulers), markdown-fold, yaml-lint.\n*   New theme: [mdn-like](https://codemirror.net/demo/theme.html#mdn-like).\n*   New mode: [Solr](https://codemirror.net/mode/solr/index.html).\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/3.21.0...3.22.0).\n\n## 3.21.0 (2014-01-16)\n\n*   Auto-indenting a block will no longer add trailing whitespace to blank lines.\n*   Marking text has a new option [`clearWhenEmpty`](https://codemirror.net/doc/manual.html#markText) to control auto-removal.\n*   Several bugfixes in the handling of bidirectional text.\n*   The [XML](https://codemirror.net/mode/xml/index.html) and [CSS](https://codemirror.net/mode/css/index.html) modes were largely rewritten. [LESS](https://codemirror.net/mode/css/less.html) support was added to the CSS mode.\n*   The OCaml mode was moved to an [mllike](https://codemirror.net/mode/mllike/index.html) mode, F# support added.\n*   Make it possible to fetch multiple applicable helper values with [`getHelpers`](https://codemirror.net/doc/manual.html#getHelpers), and to register helpers matched on predicates with [`registerGlobalHelper`](https://codemirror.net/doc/manual.html#registerGlobalHelper).\n*   New theme [pastel-on-dark](https://codemirror.net/demo/theme.html#pastel-on-dark).\n*   Better ECMAScript 6 support in [JavaScript](https://codemirror.net/mode/javascript/index.html) mode.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/3.20.0...3.21.0).\n\n## 3.20.0 (2013-11-21)\n\n*   New modes: [Julia](https://codemirror.net/mode/julia/index.html) and [PEG.js](https://codemirror.net/mode/pegjs/index.html).\n*   Support ECMAScript 6 in the [JavaScript mode](https://codemirror.net/mode/javascript/index.html).\n*   Improved indentation for the [CoffeeScript mode](https://codemirror.net/mode/coffeescript/index.html).\n*   Make non-printable-character representation [configurable](https://codemirror.net/doc/manual.html#option_specialChars).\n*   Add ‘notification’ functionality to [dialog](https://codemirror.net/doc/manual.html#addon_dialog) addon.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/3.19.0...3.20.0).\n\n## 3.19.0 (2013-10-21)\n\n*   New modes: [Eiffel](https://codemirror.net/mode/eiffel/index.html), [Gherkin](https://codemirror.net/mode/gherkin/index.html), [MSSQL dialect](https://codemirror.net/mode/sql/?mime=text/x-mssql).\n*   New addons: [hardwrap](https://codemirror.net/doc/manual.html#addon_hardwrap), [sql-hint](https://codemirror.net/doc/manual.html#addon_sql-hint).\n*   New theme: [MBO](https://codemirror.net/demo/theme.html#mbo).\n*   Add [support](https://codemirror.net/doc/manual.html#token_style_line) for line-level styling from mode tokenizers.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/3.18.0...3.19.0).\n\n## 3.18.0 (2013-09-23)\n\nEmergency release to fix a problem in 3.17 where `.setOption(\"lineNumbers\", false)` would raise an error.\n\n## 3.17.0 (2013-09-23)\n\n*   New modes: [Fortran](https://codemirror.net/mode/fortran/index.html), [Octave](https://codemirror.net/mode/octave/index.html) (Matlab), [TOML](https://codemirror.net/mode/toml/index.html), and [DTD](https://codemirror.net/mode/dtd/index.html).\n*   New addons: [`css-lint`](https://codemirror.net/addon/lint/css-lint.js), [`css-hint`](https://codemirror.net/doc/manual.html#addon_css-hint).\n*   Improve resilience to CSS 'frameworks' that globally mess up `box-sizing`.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/3.16.0...3.17.0).\n\n## 3.16.0 (2013-08-21)\n\n*   The whole codebase is now under a single [license](https://codemirror.net/LICENSE) file.\n*   The project page was overhauled and redesigned.\n*   New themes: [Paraiso](https://codemirror.net/demo/theme.html#paraiso-dark) ([light](https://codemirror.net/demo/theme.html#paraiso-light)), [The Matrix](https://codemirror.net/demo/theme.html#the-matrix).\n*   Improved interaction between themes and [active-line](https://codemirror.net/doc/manual.html#addon_active-line)/[matchbrackets](https://codemirror.net/doc/manual.html#addon_matchbrackets) addons.\n*   New [folding](https://codemirror.net/doc/manual.html#addon_foldcode) function `CodeMirror.fold.comment`.\n*   Added [fullscreen](https://codemirror.net/doc/manual.html#addon_fullscreen) addon.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/3.15.0...3.16.0).\n\n## 3.15.0 (2013-07-29)\n\n*   New modes: [Jade](https://codemirror.net/mode/jade/index.html), [Nginx](https://codemirror.net/mode/nginx/index.html).\n*   New addons: [Tern](https://codemirror.net/demo/tern.html), [matchtags](https://codemirror.net/doc/manual.html#addon_matchtags), and [foldgutter](https://codemirror.net/doc/manual.html#addon_foldgutter).\n*   Introduced [_helper_](https://codemirror.net/doc/manual.html#getHelper) concept ([context](https://groups.google.com/forum/#!msg/codemirror/cOc0xvUUEUU/nLrX1-qnidgJ)).\n*   New method: [`getModeAt`](https://codemirror.net/doc/manual.html#getModeAt).\n*   New themes: base16 [dark](https://codemirror.net/demo/theme.html#base16-dark)/[light](https://codemirror.net/demo/theme.html#base16-light), 3024 [dark](https://codemirror.net/demo/theme.html#3024-night)/[light](https://codemirror.net/demo/theme.html#3024-day), [tomorrow-night](https://codemirror.net/demo/theme.html#tomorrow-night-eighties).\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/3.14.0...3.15.0).\n\n## 3.14.0 (2013-06-20)\n\n*   New addons: [trailing space highlight](https://codemirror.net/doc/manual.html#addon_trailingspace), [XML completion](https://codemirror.net/doc/manual.html#addon_xml-hint) (rewritten), and [diff merging](https://codemirror.net/doc/manual.html#addon_merge).\n*   [`markText`](https://codemirror.net/doc/manual.html#markText) and [`addLineWidget`](https://codemirror.net/doc/manual.html#addLineWidget) now take a `handleMouseEvents` option.\n*   New methods: [`lineAtHeight`](https://codemirror.net/doc/manual.html#lineAtHeight), [`getTokenTypeAt`](https://codemirror.net/doc/manual.html#getTokenTypeAt).\n*   More precise cleanness-tracking using [`changeGeneration`](https://codemirror.net/doc/manual.html#changeGeneration) and [`isClean`](https://codemirror.net/doc/manual.html#isClean).\n*   Many extensions to [Emacs](https://codemirror.net/demo/emacs.html) mode (prefixes, more navigation units, and more).\n*   New events [`\"keyHandled\"`](https://codemirror.net/doc/manual.html#event_keyHandled) and [`\"inputRead\"`](https://codemirror.net/doc/manual.html#event_inputRead).\n*   Various improvements to [Ruby](https://codemirror.net/mode/ruby/index.html), [Smarty](https://codemirror.net/mode/smarty/index.html), [SQL](https://codemirror.net/mode/sql/index.html), and [Vim](https://codemirror.net/demo/vim.html) modes.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/3.13.0...3.14.0).\n\n## 3.13.0 (2013-05-20)\n\n*   New modes: [COBOL](https://codemirror.net/mode/cobol/index.html) and [HAML](https://codemirror.net/mode/haml/index.html).\n*   New options: [`cursorScrollMargin`](https://codemirror.net/doc/manual.html#option_cursorScrollMargin) and [`coverGutterNextToScrollbar`](https://codemirror.net/doc/manual.html#option_coverGutterNextToScrollbar).\n*   New addon: [commenting](https://codemirror.net/doc/manual.html#addon_comment).\n*   More features added to the [Vim keymap](https://codemirror.net/demo/vim.html).\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/v3.12...3.13.0).\n\n## 3.12.0 (2013-04-19)\n\n*   New mode: [GNU assembler](https://codemirror.net/mode/gas/index.html).\n*   New options: [`maxHighlightLength`](https://codemirror.net/doc/manual.html#option_maxHighlightLength) and [`historyEventDelay`](https://codemirror.net/doc/manual.html#option_historyEventDelay).\n*   Added [`addToHistory`](https://codemirror.net/doc/manual.html#mark_addToHistory) option for `markText`.\n*   Various fixes to JavaScript tokenization and indentation corner cases.\n*   Further improvements to the vim mode.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/v3.11...v3.12).\n\n## 3.11.0 (2013-03-20)\n\n*   **Removed code:** `collapserange`, `formatting`, and `simple-hint` addons. `plsql` and `mysql` modes (use [`sql`](https://codemirror.net/mode/sql/index.html) mode).\n*   **Moved code:** the range-finding functions for folding now have [their own files](https://codemirror.net/addon/fold/).\n*   **Changed interface:** the [`continuecomment`](https://codemirror.net/doc/manual.html#addon_continuecomment) addon now exposes an option, rather than a command.\n*   New modes: [SCSS](https://codemirror.net/mode/css/scss.html), [Tcl](https://codemirror.net/mode/tcl/index.html), [LiveScript](https://codemirror.net/mode/livescript/index.html), and [mIRC](https://codemirror.net/mode/mirc/index.html).\n*   New addons: [`placeholder`](https://codemirror.net/demo/placeholder.html), [HTML completion](https://codemirror.net/demo/html5complete.html).\n*   New methods: [`hasFocus`](https://codemirror.net/doc/manual.html#hasFocus), [`defaultCharWidth`](https://codemirror.net/doc/manual.html#defaultCharWidth).\n*   New events: [`beforeCursorEnter`](https://codemirror.net/doc/manual.html#event_beforeCursorEnter), [`renderLine`](https://codemirror.net/doc/manual.html#event_renderLine).\n*   Many improvements to the [`show-hint`](https://codemirror.net/doc/manual.html#addon_show-hint) completion dialog addon.\n*   Tweak behavior of by-word cursor motion.\n*   Further improvements to the [vim mode](https://codemirror.net/demo/vim.html).\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/v3.1...v3.11).\n\n## 3.02.0 (2013-01-25)\n\nSingle-bugfix release. Fixes a problem that prevents CodeMirror instances from being garbage-collected after they become unused.\n\n## 3.01.0 (2013-01-21)\n\n*   Move all add-ons into an organized directory structure under [`/addon`](https://codemirror.net/addon/). **You might have to adjust your paths.**\n*   New modes: [D](https://codemirror.net/mode/d/index.html), [Sass](https://codemirror.net/mode/sass/index.html), [APL](https://codemirror.net/mode/apl/index.html), [SQL](https://codemirror.net/mode/sql/index.html) (configurable), and [Asterisk](https://codemirror.net/mode/asterisk/index.html).\n*   Several bugfixes in right-to-left text support.\n*   Add [`rtlMoveVisually`](https://codemirror.net/doc/manual.html#option_rtlMoveVisually) option.\n*   Improvements to vim keymap.\n*   Add built-in (lightweight) [overlay mode](https://codemirror.net/doc/manual.html#addOverlay) support.\n*   Support `showIfHidden` option for [line widgets](https://codemirror.net/doc/manual.html#addLineWidget).\n*   Add simple [Python hinter](https://codemirror.net/doc/manual.html#addon_python-hint).\n*   Bring back the [`fixedGutter`](https://codemirror.net/doc/manual.html#option_fixedGutter) option.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/v3.0...v3.01).\n\n## 3.1.0 (2013-02-21)\n\n*   **Incompatible:** key handlers may now _return_, rather than _throw_ `CodeMirror.Pass` to signal they didn't handle the key.\n*   Make documents a [first-class construct](https://codemirror.net/doc/manual.html#api_doc), support split views and subviews.\n*   Add a [new module](https://codemirror.net/doc/manual.html#addon_show-hint) for showing completion hints. Deprecate `simple-hint.js`.\n*   Extend [htmlmixed mode](https://codemirror.net/mode/htmlmixed/index.html) to allow custom handling of script types.\n*   Support an `insertLeft` option to [`setBookmark`](https://codemirror.net/doc/manual.html#setBookmark).\n*   Add an [`eachLine`](https://codemirror.net/doc/manual.html#eachLine) method to iterate over a document.\n*   New addon modules: [selection marking](https://codemirror.net/demo/markselection.html), [linting](https://codemirror.net/demo/lint.html), and [automatic bracket closing](https://codemirror.net/demo/closebrackets.html).\n*   Add [`\"beforeChange\"`](https://codemirror.net/doc/manual.html#event_beforeChange) and [`\"beforeSelectionChange\"`](https://codemirror.net/doc/manual.html#event_beforeSelectionChange) events.\n*   Add [`\"hide\"`](https://codemirror.net/doc/manual.html#event_hide) and [`\"unhide\"`](https://codemirror.net/doc/manual.html#event_unhide) events to marked ranges.\n*   Fix [`coordsChar`](https://codemirror.net/doc/manual.html#coordsChar)'s interpretation of its argument to match the documentation.\n*   New modes: [Turtle](https://codemirror.net/mode/turtle/index.html) and [Q](https://codemirror.net/mode/q/index.html).\n*   Further improvements to the [vim mode](https://codemirror.net/demo/vim.html).\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/v3.01...v3.1).\n\n## 3.0.0 (2012-12-10)\n\n**New major version**. Only partially backwards-compatible. See the [upgrading guide](https://codemirror.net/doc/upgrade_v3.html) for more information. Changes since release candidate 2:\n\n*   Rewritten VIM mode.\n*   Fix a few minor scrolling and sizing issues.\n*   Work around Safari segfault when dragging.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/v3.0rc2...v3.0).\n\n## 2.38.0 (2013-01-21)\n\nIntegrate some bugfixes, enhancements to the vim keymap, and new modes ([D](https://codemirror.net/mode/d/index.html), [Sass](https://codemirror.net/mode/sass/index.html), [APL](https://codemirror.net/mode/apl/index.html)) from the v3 branch.\n\n## 2.37.0 (2012-12-20)\n\n*   New mode: [SQL](https://codemirror.net/mode/sql/index.html) (will replace [plsql](https://codemirror.net/mode/plsql/index.html) and [mysql](https://codemirror.net/mode/mysql/index.html) modes).\n*   Further work on the new VIM mode.\n*   Fix Cmd/Ctrl keys on recent Operas on OS X.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/v2.36...v2.37).\n\n## 2.36.0 (2012-11-20)\n\n*   New mode: [Z80 assembly](https://codemirror.net/mode/z80/index.html).\n*   New theme: [Twilight](https://codemirror.net/demo/theme.html#twilight).\n*   Add command-line compression helper.\n*   Make [`scrollIntoView`](https://codemirror.net/doc/manual.html#scrollIntoView) public.\n*   Add [`defaultTextHeight`](https://codemirror.net/doc/manual.html#defaultTextHeight) method.\n*   Various extensions to the vim keymap.\n*   Make [PHP mode](https://codemirror.net/mode/php/index.html) build on [mixed HTML mode](https://codemirror.net/mode/htmlmixed/index.html).\n*   Add [comment-continuing](https://codemirror.net/doc/manual.html#addon_continuecomment) add-on.\n*   Full [list of patches](https://codemirror.net/https://github.com/codemirror/CodeMirror/compare/v2.35...v2.36).\n\n## 2.35.0 (2012-10-22)\n\n*   New (sub) mode: [TypeScript](https://codemirror.net/mode/javascript/typescript.html).\n*   Don't overwrite (insert key) when pasting.\n*   Fix several bugs in [`markText`](https://codemirror.net/doc/manual.html#markText)/undo interaction.\n*   Better indentation of JavaScript code without semicolons.\n*   Add [`defineInitHook`](https://codemirror.net/doc/manual.html#defineInitHook) function.\n*   Full [list of patches](https://github.com/codemirror/CodeMirror/compare/v2.34...v2.35).\n\n## 2.34.0 (2012-09-19)\n\n*   New mode: [Common Lisp](https://codemirror.net/mode/commonlisp/index.html).\n*   Fix right-click select-all on most browsers.\n*   Change the way highlighting happens:\n      Saves memory and CPU cycles.\n      `compareStates` is no longer needed.\n      `onHighlightComplete` no longer works.\n*   Integrate mode (Markdown, XQuery, CSS, sTex) tests in central testsuite.\n*   Add a [`CodeMirror.version`](https://codemirror.net/doc/manual.html#version) property.\n*   More robust handling of nested modes in [formatting](https://codemirror.net/demo/formatting.html) and [closetag](https://codemirror.net/demo/closetag.html) plug-ins.\n*   Un/redo now preserves [marked text](https://codemirror.net/doc/manual.html#markText) and bookmarks.\n*   [Full list](https://github.com/codemirror/CodeMirror/compare/v2.33...v2.34) of patches.\n\n## 2.33.0 (2012-08-23)\n\n*   New mode: [Sieve](https://codemirror.net/mode/sieve/index.html).\n*   New [`getViewPort`](https://codemirror.net/doc/manual.html#getViewport) and [`onViewportChange`](https://codemirror.net/doc/manual.html#option_onViewportChange) API.\n*   [Configurable](https://codemirror.net/doc/manual.html#option_cursorBlinkRate) cursor blink rate.\n*   Make binding a key to `false` disabling handling (again).\n*   Show non-printing characters as red dots.\n*   More tweaks to the scrolling model.\n*   Expanded testsuite. Basic linter added.\n*   Remove most uses of `innerHTML`. Remove `CodeMirror.htmlEscape`.\n*   [Full list](https://github.com/codemirror/CodeMirror/compare/v2.32...v2.33) of patches.\n\n## 2.32.0 (2012-07-23)\n\nEmergency fix for a bug where an editor with line wrapping on IE will break when there is _no_ scrollbar.\n\n## 2.31.0 (2012-07-20)\n\n*   New modes: [OCaml](https://codemirror.net/mode/ocaml/index.html), [Haxe](https://codemirror.net/mode/haxe/index.html), and [VB.NET](https://codemirror.net/mode/vb/index.html).\n*   Several fixes to the new scrolling model.\n*   Add a [`setSize`](https://codemirror.net/doc/manual.html#setSize) method for programmatic resizing.\n*   Add [`getHistory`](https://codemirror.net/doc/manual.html#getHistory) and [`setHistory`](https://codemirror.net/doc/manual.html#setHistory) methods.\n*   Allow custom line separator string in [`getValue`](https://codemirror.net/doc/manual.html#getValue) and [`getRange`](https://codemirror.net/doc/manual.html#getRange).\n*   Support double- and triple-click drag, double-clicking whitespace.\n*   And more... [(all patches)](https://github.com/codemirror/CodeMirror/compare/v2.3...v2.31)\n\n## 2.30.0 (2012-06-22)\n\n*   **New scrollbar implementation**. Should flicker less. Changes DOM structure of the editor.\n*   New theme: [vibrant-ink](https://codemirror.net/demo/theme.html#vibrant-ink).\n*   Many extensions to the VIM keymap (including text objects).\n*   Add [mode-multiplexing](https://codemirror.net/demo/multiplex.html) utility script.\n*   Fix bug where right-click paste works in read-only mode.\n*   Add a [`getScrollInfo`](https://codemirror.net/doc/manual.html#getScrollInfo) method.\n*   Lots of other [fixes](https://github.com/codemirror/CodeMirror/compare/v2.25...v2.3).\n\n## 2.25.0 (2012-05-23)\n\n*   New mode: [Erlang](https://codemirror.net/mode/erlang/index.html).\n*   **Remove xmlpure mode** (use [xml.js](https://codemirror.net/mode/xml/index.html)).\n*   Fix line-wrapping in Opera.\n*   Fix X Windows middle-click paste in Chrome.\n*   Fix bug that broke pasting of huge documents.\n*   Fix backspace and tab key repeat in Opera.\n\n## 2.24.0 (2012-04-23)\n\n*   **Drop support for Internet Explorer 6**.\n*   New modes: [Shell](https://codemirror.net/mode/shell/index.html), [Tiki wiki](https://codemirror.net/mode/tiki/index.html), [Pig Latin](https://codemirror.net/mode/pig/index.html).\n*   New themes: [Ambiance](https://codemirror.net/demo/theme.html#ambiance), [Blackboard](https://codemirror.net/demo/theme.html#blackboard).\n*   More control over drag/drop with [`dragDrop`](https://codemirror.net/doc/manual.html#option_dragDrop) and [`onDragEvent`](https://codemirror.net/doc/manual.html#option_onDragEvent) options.\n*   Make HTML mode a bit less pedantic.\n*   Add [`compoundChange`](https://codemirror.net/doc/manual.html#compoundChange) API method.\n*   Several fixes in undo history and line hiding.\n*   Remove (broken) support for `catchall` in key maps, add `nofallthrough` boolean field instead.\n\n## 2.23.0 (2012-03-26)\n\n*   Change **default binding for tab**. Starting in 2.23, these bindings are default:\n    *   Tab: Insert tab character\n    *   Shift-tab: Reset line indentation to default\n    *   Ctrl/Cmd-[: Reduce line indentation (old tab behaviour)\n    *   Ctrl/Cmd-]: Increase line indentation (old shift-tab behaviour)\n*   New modes: [XQuery](https://codemirror.net/mode/xquery/index.html) and [VBScript](https://codemirror.net/mode/vbscript/index.html).\n*   Two new themes: [lesser-dark](https://codemirror.net/mode/less/index.html) and [xq-dark](https://codemirror.net/mode/xquery/index.html).\n*   Differentiate between background and text styles in [`setLineClass`](https://codemirror.net/doc/manual.html#setLineClass).\n*   Fix drag-and-drop in IE9+.\n*   Extend [`charCoords`](https://codemirror.net/doc/manual.html#charCoords) and [`cursorCoords`](https://codemirror.net/doc/manual.html#cursorCoords) with a `mode` argument.\n*   Add [`autofocus`](https://codemirror.net/doc/manual.html#option_autofocus) option.\n*   Add [`findMarksAt`](https://codemirror.net/doc/manual.html#findMarksAt) method.\n\n## 2.22.0 (2012-02-27)\n\n*   Allow [key handlers](https://codemirror.net/doc/manual.html#keymaps) to pass up events, allow binding characters.\n*   Add [`autoClearEmptyLines`](https://codemirror.net/doc/manual.html#option_autoClearEmptyLines) option.\n*   Properly use tab stops when rendering tabs.\n*   Make PHP mode more robust.\n*   Support indentation blocks in [code folder](https://codemirror.net/doc/manual.html#addon_foldcode).\n*   Add a script for [highlighting instances of the selection](https://codemirror.net/doc/manual.html#addon_match-highlighter).\n*   New [.properties](https://codemirror.net/mode/properties/index.html) mode.\n*   Fix many bugs.\n\n## 2.21.0 (2012-01-27)\n\n*   Added [LESS](https://codemirror.net/mode/less/index.html), [MySQL](https://codemirror.net/mode/mysql/index.html), [Go](https://codemirror.net/mode/go/index.html), and [Verilog](https://codemirror.net/mode/verilog/index.html) modes.\n*   Add [`smartIndent`](https://codemirror.net/doc/manual.html#option_smartIndent) option.\n*   Support a cursor in [`readOnly`](https://codemirror.net/doc/manual.html#option_readOnly)-mode.\n*   Support assigning multiple styles to a token.\n*   Use a new approach to drawing the selection.\n*   Add [`scrollTo`](https://codemirror.net/doc/manual.html#scrollTo) method.\n*   Allow undo/redo events to span non-adjacent lines.\n*   Lots and lots of bugfixes.\n\n## 2.20.0 (2011-12-20)\n\n*   Slightly incompatible API changes. Read [this](https://codemirror.net/doc/upgrade_v2.2.html).\n*   New approach to [binding](https://codemirror.net/doc/manual.html#option_extraKeys) keys, support for [custom bindings](https://codemirror.net/doc/manual.html#option_keyMap).\n*   Support for overwrite (insert).\n*   [Custom-width](https://codemirror.net/doc/manual.html#option_tabSize) and [stylable](https://codemirror.net/demo/visibletabs.html) tabs.\n*   Moved more code into [add-on scripts](https://codemirror.net/doc/manual.html#addons).\n*   Support for sane vertical cursor movement in wrapped lines.\n*   More reliable handling of editing [marked text](https://codemirror.net/doc/manual.html#markText).\n*   Add minimal [emacs](https://codemirror.net/demo/emacs.html) and [vim](https://codemirror.net/demo/vim.html) bindings.\n*   Rename `coordsFromIndex` to [`posFromIndex`](https://codemirror.net/doc/manual.html#posFromIndex), add [`indexFromPos`](https://codemirror.net/doc/manual.html#indexFromPos) method.\n\n## 2.18.0 (2011-11-21)\n\nFixes `TextMarker.clear`, which is broken in 2.17.\n\n## 2.17.0 (2011-11-21)\n\n*   Add support for [line wrapping](https://codemirror.net/doc/manual.html#option_lineWrapping) and [code folding](https://codemirror.net/doc/manual.html#hideLine).\n*   Add [Github-style Markdown](https://codemirror.net/mode/gfm/index.html) mode.\n*   Add [Monokai](https://codemirror.net/theme/monokai.css) and [Rubyblue](https://codemirror.net/theme/rubyblue.css) themes.\n*   Add [`setBookmark`](https://codemirror.net/doc/manual.html#setBookmark) method.\n*   Move some of the demo code into reusable components under [`lib/util`](https://codemirror.net/addon/).\n*   Make screen-coord-finding code faster and more reliable.\n*   Fix drag-and-drop in Firefox.\n*   Improve support for IME.\n*   Speed up content rendering.\n*   Fix browser's built-in search in Webkit.\n*   Make double- and triple-click work in IE.\n*   Various fixes to modes.\n\n## 2.16.0 (2011-10-27)\n\n*   Add [Perl](https://codemirror.net/mode/perl/index.html), [Rust](https://codemirror.net/mode/rust/index.html), [TiddlyWiki](https://codemirror.net/mode/tiddlywiki/index.html), and [Groovy](https://codemirror.net/mode/groovy/index.html) modes.\n*   Dragging text inside the editor now moves, rather than copies.\n*   Add a [`coordsFromIndex`](https://codemirror.net/doc/manual.html#coordsFromIndex) method.\n*   **API change**: `setValue` now no longer clears history. Use [`clearHistory`](https://codemirror.net/doc/manual.html#clearHistory) for that.\n*   **API change**: [`markText`](https://codemirror.net/doc/manual.html#markText) now returns an object with `clear` and `find` methods. Marked text is now more robust when edited.\n*   Fix editing code with tabs in Internet Explorer.\n\n## 2.15.0 (2011-09-26)\n\nFix bug that snuck into 2.14: Clicking the character that currently has the cursor didn't re-focus the editor.\n\n## 2.14.0 (2011-09-26)\n\n*   Add [Clojure](https://codemirror.net/mode/clojure/index.html), [Pascal](https://codemirror.net/mode/pascal/index.html), [NTriples](https://codemirror.net/mode/ntriples/index.html), [Jinja2](https://codemirror.net/mode/jinja2/index.html), and [Markdown](https://codemirror.net/mode/markdown/index.html) modes.\n*   Add [Cobalt](https://codemirror.net/theme/cobalt.css) and [Eclipse](https://codemirror.net/theme/eclipse.css) themes.\n*   Add a [`fixedGutter`](https://codemirror.net/doc/manual.html#option_fixedGutter) option.\n*   Fix bug with `setValue` breaking cursor movement.\n*   Make gutter updates much more efficient.\n*   Allow dragging of text out of the editor (on modern browsers).\n\n## 2.13.0 (2011-08-23)\n\n*   Add [Ruby](https://codemirror.net/mode/ruby/index.html), [R](https://codemirror.net/mode/r/index.html), [CoffeeScript](https://codemirror.net/mode/coffeescript/index.html), and [Velocity](https://codemirror.net/mode/velocity/index.html) modes.\n*   Add [`getGutterElement`](https://codemirror.net/doc/manual.html#getGutterElement) to API.\n*   Several fixes to scrolling and positioning.\n*   Add [`smartHome`](https://codemirror.net/doc/manual.html#option_smartHome) option.\n*   Add an experimental [pure XML](https://codemirror.net/mode/xmlpure/index.html) mode.\n\n## 2.12.0 (2011-07-25)\n\n*   Add a [SPARQL](https://codemirror.net/mode/sparql/index.html) mode.\n*   Fix bug with cursor jumping around in an unfocused editor in IE.\n*   Allow key and mouse events to bubble out of the editor. Ignore widget clicks.\n*   Solve cursor flakiness after undo/redo.\n*   Fix block-reindent ignoring the last few lines.\n*   Fix parsing of multi-line attrs in XML mode.\n*   Use `innerHTML` for HTML-escaping.\n*   Some fixes to indentation in C-like mode.\n*   Shrink horiz scrollbars when long lines removed.\n*   Fix width feedback loop bug that caused the width of an inner DIV to shrink.\n\n## 2.11.0 (2011-07-04)\n\n*   Add a [Scheme mode](https://codemirror.net/mode/scheme/index.html).\n*   Add a `replace` method to search cursors, for cursor-preserving replacements.\n*   Make the [C-like mode](https://codemirror.net/mode/clike/index.html) mode more customizable.\n*   Update XML mode to spot mismatched tags.\n*   Add `getStateAfter` API and `compareState` mode API methods for finer-grained mode magic.\n*   Add a `getScrollerElement` API method to manipulate the scrolling DIV.\n*   Fix drag-and-drop for Firefox.\n*   Add a C# configuration for the [C-like mode](https://codemirror.net/mode/clike/index.html).\n*   Add [full-screen editing](https://codemirror.net/demo/fullscreen.html) and [mode-changing](https://codemirror.net/demo/changemode.html) demos.\n\n## 2.10.0 (2011-06-07)\n\nAdd a [theme](https://codemirror.net/doc/manual.html#option_theme) system ([demo](https://codemirror.net/demo/theme.html)). Note that this is not backwards-compatible—you'll have to update your styles and modes!\n\n## 2.2.0 (2011-06-07)\n\n*   Add a [Lua mode](https://codemirror.net/mode/lua/index.html).\n*   Fix reverse-searching for a regexp.\n*   Empty lines can no longer break highlighting.\n*   Rework scrolling model (the outer wrapper no longer does the scrolling).\n*   Solve horizontal jittering on long lines.\n*   Add [runmode.js](https://codemirror.net/demo/runmode.html).\n*   Immediately re-highlight text when typing.\n*   Fix problem with 'sticking' horizontal scrollbar.\n\n## 2.1.0 (2011-05-26)\n\n*   Add a [Smalltalk mode](https://codemirror.net/mode/smalltalk/index.html).\n*   Add a [reStructuredText mode](https://codemirror.net/mode/rst/index.html).\n*   Add a [Python mode](https://codemirror.net/mode/python/index.html).\n*   Add a [PL/SQL mode](https://codemirror.net/mode/plsql/index.html).\n*   `coordsChar` now works\n*   Fix a problem where `onCursorActivity` interfered with `onChange`.\n*   Fix a number of scrolling and mouse-click-position glitches.\n*   Pass information about the changed lines to `onChange`.\n*   Support cmd-up/down on OS X.\n*   Add triple-click line selection.\n*   Don't handle shift when changing the selection through the API.\n*   Support `\"nocursor\"` mode for `readOnly` option.\n*   Add an `onHighlightComplete` option.\n*   Fix the context menu for Firefox.\n\n## 2.0.0 (2011-03-28)\n\nCodeMirror 2 is a complete rewrite that's faster, smaller, simpler to use, and less dependent on browser quirks. See [this](https://codemirror.net/doc/internals.html) and [this](http://groups.google.com/group/codemirror/browse_thread/thread/5a8e894024a9f580) for more information.\n"
  },
  {
    "path": "third_party/CodeMirror/CONTRIBUTING.md",
    "content": "# How to contribute\n\n- [Getting help](#getting-help)\n- [Submitting bug reports](#submitting-bug-reports)\n- [Contributing code](#contributing-code)\n\n## Getting help\n\nCommunity discussion, questions, and informal bug reporting is done on the\n[discuss.CodeMirror forum](http://discuss.codemirror.net).\n\n## Submitting bug reports\n\nThe preferred way to report bugs is to use the\n[GitHub issue tracker](http://github.com/codemirror/CodeMirror/issues). Before\nreporting a bug, read these pointers.\n\n**Note:** The issue tracker is for *bugs*, not requests for help. Questions\nshould be asked on the\n[discuss.CodeMirror forum](http://discuss.codemirror.net) instead.\n\n### Reporting bugs effectively\n\n- CodeMirror is maintained by volunteers. They don't owe you anything, so be\n  polite. Reports with an indignant or belligerent tone tend to be moved to the\n  bottom of the pile.\n\n- Include information about **the browser in which the problem occurred**. Even\n  if you tested several browsers, and the problem occurred in all of them,\n  mention this fact in the bug report. Also include browser version numbers and\n  the operating system that you're on.\n\n- Mention which release of CodeMirror you're using. Preferably, try also with\n  the current development snapshot, to ensure the problem has not already been\n  fixed.\n\n- Mention very precisely what went wrong. \"X is broken\" is not a good bug\n  report. What did you expect to happen? What happened instead? Describe the\n  exact steps a maintainer has to take to make the problem occur. We can not\n  fix something that we can not observe.\n\n- If the problem can not be reproduced in any of the demos included in the\n  CodeMirror distribution, please provide an HTML document that demonstrates\n  the problem. The best way to do this is to go to\n  [jsbin.com](http://jsbin.com/ihunin/edit), enter it there, press save, and\n  include the resulting link in your bug report.\n\n## Contributing code\n\nNote that we are not accepting any new addons or modes into the main\ndistribution. If you've written such a module, please distribute it as\na separate NPM package.\n\n- Make sure you have a [GitHub Account](https://github.com/signup/free)\n- Fork [CodeMirror](https://github.com/codemirror/CodeMirror/)\n  ([how to fork a repo](https://help.github.com/articles/fork-a-repo))\n- Make your changes\n- If your changes are easy to test or likely to regress, add tests.\n  Tests for the core go into `test/test.js`, some modes have their own\n  test suite under `mode/XXX/test.js`. Feel free to add new test\n  suites to modes that don't have one yet (be sure to link the new\n  tests into `test/index.html`).\n- Follow the general code style of the rest of the project (see\n  below). Run `bin/lint` to verify that the linter is happy.\n- Make sure all tests pass. Visit `test/index.html` in your browser to\n  run them.\n- Submit a pull request\n([how to create a pull request](https://help.github.com/articles/fork-a-repo)).\n  Don't put more than one feature/fix in a single pull request.\n\nBy contributing code to CodeMirror you\n\n - agree to license the contributed code under CodeMirror's [MIT\n   license](https://codemirror.net/LICENSE).\n\n - confirm that you have the right to contribute and license the code\n   in question. (Either you hold all rights on the code, or the rights\n   holder has explicitly granted the right to use it like this,\n   through a compatible open source license or through a direct\n   agreement with you.)\n\n### Coding standards\n\n- 2 spaces per indentation level, no tabs.\n\n- Note that the linter (`bin/lint`) which is run after each commit\n  complains about unused variables and functions. Prefix their names\n  with an underscore to muffle it.\n\n- CodeMirror does *not* follow JSHint or JSLint prescribed style.\n  Patches that try to 'fix' code to pass one of these linters will be\n  unceremoniously discarded.\n"
  },
  {
    "path": "third_party/CodeMirror/LICENSE",
    "content": "MIT License\n\nCopyright (C) 2017 by Marijn Haverbeke <marijnh@gmail.com> and others\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "third_party/CodeMirror/METADATA",
    "content": "name: \"CodeMirror\"\ndescription:\n    \"CodeMirror is a code editor embedable in a webpage.\"\n\nthird_party {\n  url {\n    type: HOMEPAGE\n    value: \"https://codemirror.net/\"\n  }\n  url {\n    type: GIT\n    value: \"https://github.com/codemirror/codemirror\"\n  }\n  version: \"5.43.0\"\n  last_upgrade_date { year: 2019 month: 2 day: 12 }\n  license_type: NOTICE\n}\n"
  },
  {
    "path": "third_party/CodeMirror/README.md",
    "content": "# CodeMirror\n\n[![Build Status](https://travis-ci.org/codemirror/CodeMirror.svg)](https://travis-ci.org/codemirror/CodeMirror)\n[![NPM version](https://img.shields.io/npm/v/codemirror.svg)](https://www.npmjs.org/package/codemirror)\n[![Join the chat at https://gitter.im/codemirror/CodeMirror](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/codemirror/CodeMirror)  \n\nCodeMirror is a versatile text editor implemented in JavaScript for\nthe browser. It is specialized for editing code, and comes with over\n100 language modes and various addons that implement more advanced\nediting functionality. Every language comes with fully-featured code\nand syntax highlighting to help with reading and editing complex code.\n\nA rich programming API and a CSS theming system are available for\ncustomizing CodeMirror to fit your application, and extending it with\nnew functionality.\n\nYou can find more information (and the\n[manual](https://codemirror.net/doc/manual.html)) on the [project\npage](https://codemirror.net). For questions and discussion, use the\n[discussion forum](https://discuss.codemirror.net/).\n\nSee\n[CONTRIBUTING.md](https://github.com/codemirror/CodeMirror/blob/master/CONTRIBUTING.md)\nfor contributing guidelines.\n\nThe CodeMirror community aims to be welcoming to everybody. We use the\n[Contributor Covenant\n(1.1)](http://contributor-covenant.org/version/1/1/0/) as our code of\nconduct.\n\n### Installation\n\nEither get the [zip file](https://codemirror.net/codemirror.zip) with\nthe latest version, or make sure you have [Node](https://nodejs.org/)\ninstalled and run:\n\n    npm install codemirror\n\n**NOTE**: This is the source repository for the library, and not the\ndistribution channel. Cloning it is not the recommended way to install\nthe library, and will in fact not work unless you also run the build\nstep.\n\n### Quickstart\n\nTo build the project, make sure you have Node.js installed (at least version 6)\nand then `npm install`. To run, just open `index.html` in your\nbrowser (you don't need to run a webserver). Run the tests with `npm test`.\n"
  },
  {
    "path": "third_party/CodeMirror/addon/comment/comment.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var noOptions = {};\n  var nonWS = /[^\\s\\u00a0]/;\n  var Pos = CodeMirror.Pos;\n\n  function firstNonWS(str) {\n    var found = str.search(nonWS);\n    return found == -1 ? 0 : found;\n  }\n\n  CodeMirror.commands.toggleComment = function(cm) {\n    cm.toggleComment();\n  };\n\n  CodeMirror.defineExtension(\"toggleComment\", function(options) {\n    if (!options) options = noOptions;\n    var cm = this;\n    var minLine = Infinity, ranges = this.listSelections(), mode = null;\n    for (var i = ranges.length - 1; i >= 0; i--) {\n      var from = ranges[i].from(), to = ranges[i].to();\n      if (from.line >= minLine) continue;\n      if (to.line >= minLine) to = Pos(minLine, 0);\n      minLine = from.line;\n      if (mode == null) {\n        if (cm.uncomment(from, to, options)) mode = \"un\";\n        else { cm.lineComment(from, to, options); mode = \"line\"; }\n      } else if (mode == \"un\") {\n        cm.uncomment(from, to, options);\n      } else {\n        cm.lineComment(from, to, options);\n      }\n    }\n  });\n\n  // Rough heuristic to try and detect lines that are part of multi-line string\n  function probablyInsideString(cm, pos, line) {\n    return /\\bstring\\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\\'\\\"\\`]/.test(line)\n  }\n\n  function getMode(cm, pos) {\n    var mode = cm.getMode()\n    return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos)\n  }\n\n  CodeMirror.defineExtension(\"lineComment\", function(from, to, options) {\n    if (!options) options = noOptions;\n    var self = this, mode = getMode(self, from);\n    var firstLine = self.getLine(from.line);\n    if (firstLine == null || probablyInsideString(self, from, firstLine)) return;\n\n    var commentString = options.lineComment || mode.lineComment;\n    if (!commentString) {\n      if (options.blockCommentStart || mode.blockCommentStart) {\n        options.fullLines = true;\n        self.blockComment(from, to, options);\n      }\n      return;\n    }\n\n    var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);\n    var pad = options.padding == null ? \" \" : options.padding;\n    var blankLines = options.commentBlankLines || from.line == to.line;\n\n    self.operation(function() {\n      if (options.indent) {\n        var baseString = null;\n        for (var i = from.line; i < end; ++i) {\n          var line = self.getLine(i);\n          var whitespace = line.slice(0, firstNonWS(line));\n          if (baseString == null || baseString.length > whitespace.length) {\n            baseString = whitespace;\n          }\n        }\n        for (var i = from.line; i < end; ++i) {\n          var line = self.getLine(i), cut = baseString.length;\n          if (!blankLines && !nonWS.test(line)) continue;\n          if (line.slice(0, cut) != baseString) cut = firstNonWS(line);\n          self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));\n        }\n      } else {\n        for (var i = from.line; i < end; ++i) {\n          if (blankLines || nonWS.test(self.getLine(i)))\n            self.replaceRange(commentString + pad, Pos(i, 0));\n        }\n      }\n    });\n  });\n\n  CodeMirror.defineExtension(\"blockComment\", function(from, to, options) {\n    if (!options) options = noOptions;\n    var self = this, mode = getMode(self, from);\n    var startString = options.blockCommentStart || mode.blockCommentStart;\n    var endString = options.blockCommentEnd || mode.blockCommentEnd;\n    if (!startString || !endString) {\n      if ((options.lineComment || mode.lineComment) && options.fullLines != false)\n        self.lineComment(from, to, options);\n      return;\n    }\n    if (/\\bcomment\\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return\n\n    var end = Math.min(to.line, self.lastLine());\n    if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;\n\n    var pad = options.padding == null ? \" \" : options.padding;\n    if (from.line > end) return;\n\n    self.operation(function() {\n      if (options.fullLines != false) {\n        var lastLineHasText = nonWS.test(self.getLine(end));\n        self.replaceRange(pad + endString, Pos(end));\n        self.replaceRange(startString + pad, Pos(from.line, 0));\n        var lead = options.blockCommentLead || mode.blockCommentLead;\n        if (lead != null) for (var i = from.line + 1; i <= end; ++i)\n          if (i != end || lastLineHasText)\n            self.replaceRange(lead + pad, Pos(i, 0));\n      } else {\n        self.replaceRange(endString, to);\n        self.replaceRange(startString, from);\n      }\n    });\n  });\n\n  CodeMirror.defineExtension(\"uncomment\", function(from, to, options) {\n    if (!options) options = noOptions;\n    var self = this, mode = getMode(self, from);\n    var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end);\n\n    // Try finding line comments\n    var lineString = options.lineComment || mode.lineComment, lines = [];\n    var pad = options.padding == null ? \" \" : options.padding, didSomething;\n    lineComment: {\n      if (!lineString) break lineComment;\n      for (var i = start; i <= end; ++i) {\n        var line = self.getLine(i);\n        var found = line.indexOf(lineString);\n        if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;\n        if (found == -1 && nonWS.test(line)) break lineComment;\n        if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;\n        lines.push(line);\n      }\n      self.operation(function() {\n        for (var i = start; i <= end; ++i) {\n          var line = lines[i - start];\n          var pos = line.indexOf(lineString), endPos = pos + lineString.length;\n          if (pos < 0) continue;\n          if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;\n          didSomething = true;\n          self.replaceRange(\"\", Pos(i, pos), Pos(i, endPos));\n        }\n      });\n      if (didSomething) return true;\n    }\n\n    // Try block comments\n    var startString = options.blockCommentStart || mode.blockCommentStart;\n    var endString = options.blockCommentEnd || mode.blockCommentEnd;\n    if (!startString || !endString) return false;\n    var lead = options.blockCommentLead || mode.blockCommentLead;\n    var startLine = self.getLine(start), open = startLine.indexOf(startString)\n    if (open == -1) return false\n    var endLine = end == start ? startLine : self.getLine(end)\n    var close = endLine.indexOf(endString, end == start ? open + startString.length : 0);\n    var insideStart = Pos(start, open + 1), insideEnd = Pos(end, close + 1)\n    if (close == -1 ||\n        !/comment/.test(self.getTokenTypeAt(insideStart)) ||\n        !/comment/.test(self.getTokenTypeAt(insideEnd)) ||\n        self.getRange(insideStart, insideEnd, \"\\n\").indexOf(endString) > -1)\n      return false;\n\n    // Avoid killing block comments completely outside the selection.\n    // Positions of the last startString before the start of the selection, and the first endString after it.\n    var lastStart = startLine.lastIndexOf(startString, from.ch);\n    var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length);\n    if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false;\n    // Positions of the first endString after the end of the selection, and the last startString before it.\n    firstEnd = endLine.indexOf(endString, to.ch);\n    var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch);\n    lastStart = (firstEnd == -1 || almostLastStart == -1) ? -1 : to.ch + almostLastStart;\n    if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false;\n\n    self.operation(function() {\n      self.replaceRange(\"\", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),\n                        Pos(end, close + endString.length));\n      var openEnd = open + startString.length;\n      if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;\n      self.replaceRange(\"\", Pos(start, open), Pos(start, openEnd));\n      if (lead) for (var i = start + 1; i <= end; ++i) {\n        var line = self.getLine(i), found = line.indexOf(lead);\n        if (found == -1 || nonWS.test(line.slice(0, found))) continue;\n        var foundEnd = found + lead.length;\n        if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;\n        self.replaceRange(\"\", Pos(i, found), Pos(i, foundEnd));\n      }\n    });\n    return true;\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/comment/continuecomment.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  function continueComment(cm) {\n    if (cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n    var ranges = cm.listSelections(), mode, inserts = [];\n    for (var i = 0; i < ranges.length; i++) {\n      var pos = ranges[i].head\n      if (!/\\bcomment\\b/.test(cm.getTokenTypeAt(pos))) return CodeMirror.Pass;\n      var modeHere = cm.getModeAt(pos)\n      if (!mode) mode = modeHere;\n      else if (mode != modeHere) return CodeMirror.Pass;\n\n      var insert = null;\n      if (mode.blockCommentStart && mode.blockCommentContinue) {\n        var line = cm.getLine(pos.line).slice(0, pos.ch)\n        var end = line.lastIndexOf(mode.blockCommentEnd), found\n        if (end != -1 && end == pos.ch - mode.blockCommentEnd.length) {\n          // Comment ended, don't continue it\n        } else if ((found = line.lastIndexOf(mode.blockCommentStart)) > -1 && found > end) {\n          insert = line.slice(0, found)\n          if (/\\S/.test(insert)) {\n            insert = \"\"\n            for (var j = 0; j < found; ++j) insert += \" \"\n          }\n        } else if ((found = line.indexOf(mode.blockCommentContinue)) > -1 && !/\\S/.test(line.slice(0, found))) {\n          insert = line.slice(0, found)\n        }\n        if (insert != null) insert += mode.blockCommentContinue\n      }\n      if (insert == null && mode.lineComment && continueLineCommentEnabled(cm)) {\n        var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment);\n        if (found > -1) {\n          insert = line.slice(0, found);\n          if (/\\S/.test(insert)) insert = null;\n          else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\\s*/)[0];\n        }\n      }\n      if (insert == null) return CodeMirror.Pass;\n      inserts[i] = \"\\n\" + insert;\n    }\n\n    cm.operation(function() {\n      for (var i = ranges.length - 1; i >= 0; i--)\n        cm.replaceRange(inserts[i], ranges[i].from(), ranges[i].to(), \"+insert\");\n    });\n  }\n\n  function continueLineCommentEnabled(cm) {\n    var opt = cm.getOption(\"continueComments\");\n    if (opt && typeof opt == \"object\")\n      return opt.continueLineComment !== false;\n    return true;\n  }\n\n  CodeMirror.defineOption(\"continueComments\", null, function(cm, val, prev) {\n    if (prev && prev != CodeMirror.Init)\n      cm.removeKeyMap(\"continueComment\");\n    if (val) {\n      var key = \"Enter\";\n      if (typeof val == \"string\")\n        key = val;\n      else if (typeof val == \"object\" && val.key)\n        key = val.key;\n      var map = {name: \"continueComment\"};\n      map[key] = continueComment;\n      cm.addKeyMap(map);\n    }\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/dialog/dialog.css",
    "content": ".CodeMirror-dialog {\n  position: absolute;\n  left: 0; right: 0;\n  background: inherit;\n  z-index: 15;\n  padding: .1em .8em;\n  overflow: hidden;\n  color: inherit;\n}\n\n.CodeMirror-dialog-top {\n  border-bottom: 1px solid #eee;\n  top: 0;\n}\n\n.CodeMirror-dialog-bottom {\n  border-top: 1px solid #eee;\n  bottom: 0;\n}\n\n.CodeMirror-dialog input {\n  border: none;\n  outline: none;\n  background: transparent;\n  width: 20em;\n  color: inherit;\n  font-family: monospace;\n}\n\n.CodeMirror-dialog button {\n  font-size: 70%;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/addon/dialog/dialog.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Open simple dialogs on top of an editor. Relies on dialog.css.\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  function dialogDiv(cm, template, bottom) {\n    var wrap = cm.getWrapperElement();\n    var dialog;\n    dialog = wrap.appendChild(document.createElement(\"div\"));\n    if (bottom)\n      dialog.className = \"CodeMirror-dialog CodeMirror-dialog-bottom\";\n    else\n      dialog.className = \"CodeMirror-dialog CodeMirror-dialog-top\";\n\n    if (typeof template == \"string\") {\n      dialog.innerHTML = template;\n    } else { // Assuming it's a detached DOM element.\n      dialog.appendChild(template);\n    }\n    CodeMirror.addClass(wrap, 'dialog-opened');\n    return dialog;\n  }\n\n  function closeNotification(cm, newVal) {\n    if (cm.state.currentNotificationClose)\n      cm.state.currentNotificationClose();\n    cm.state.currentNotificationClose = newVal;\n  }\n\n  CodeMirror.defineExtension(\"openDialog\", function(template, callback, options) {\n    if (!options) options = {};\n\n    closeNotification(this, null);\n\n    var dialog = dialogDiv(this, template, options.bottom);\n    var closed = false, me = this;\n    function close(newVal) {\n      if (typeof newVal == 'string') {\n        inp.value = newVal;\n      } else {\n        if (closed) return;\n        closed = true;\n        CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');\n        dialog.parentNode.removeChild(dialog);\n        me.focus();\n\n        if (options.onClose) options.onClose(dialog);\n      }\n    }\n\n    var inp = dialog.getElementsByTagName(\"input\")[0], button;\n    if (inp) {\n      inp.focus();\n\n      if (options.value) {\n        inp.value = options.value;\n        if (options.selectValueOnOpen !== false) {\n          inp.select();\n        }\n      }\n\n      if (options.onInput)\n        CodeMirror.on(inp, \"input\", function(e) { options.onInput(e, inp.value, close);});\n      if (options.onKeyUp)\n        CodeMirror.on(inp, \"keyup\", function(e) {options.onKeyUp(e, inp.value, close);});\n\n      CodeMirror.on(inp, \"keydown\", function(e) {\n        if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }\n        if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {\n          inp.blur();\n          CodeMirror.e_stop(e);\n          close();\n        }\n        if (e.keyCode == 13) callback(inp.value, e);\n      });\n\n      if (options.closeOnBlur !== false) CodeMirror.on(inp, \"blur\", close);\n    } else if (button = dialog.getElementsByTagName(\"button\")[0]) {\n      CodeMirror.on(button, \"click\", function() {\n        close();\n        me.focus();\n      });\n\n      if (options.closeOnBlur !== false) CodeMirror.on(button, \"blur\", close);\n\n      button.focus();\n    }\n    return close;\n  });\n\n  CodeMirror.defineExtension(\"openConfirm\", function(template, callbacks, options) {\n    closeNotification(this, null);\n    var dialog = dialogDiv(this, template, options && options.bottom);\n    var buttons = dialog.getElementsByTagName(\"button\");\n    var closed = false, me = this, blurring = 1;\n    function close() {\n      if (closed) return;\n      closed = true;\n      CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');\n      dialog.parentNode.removeChild(dialog);\n      me.focus();\n    }\n    buttons[0].focus();\n    for (var i = 0; i < buttons.length; ++i) {\n      var b = buttons[i];\n      (function(callback) {\n        CodeMirror.on(b, \"click\", function(e) {\n          CodeMirror.e_preventDefault(e);\n          close();\n          if (callback) callback(me);\n        });\n      })(callbacks[i]);\n      CodeMirror.on(b, \"blur\", function() {\n        --blurring;\n        setTimeout(function() { if (blurring <= 0) close(); }, 200);\n      });\n      CodeMirror.on(b, \"focus\", function() { ++blurring; });\n    }\n  });\n\n  /*\n   * openNotification\n   * Opens a notification, that can be closed with an optional timer\n   * (default 5000ms timer) and always closes on click.\n   *\n   * If a notification is opened while another is opened, it will close the\n   * currently opened one and open the new one immediately.\n   */\n  CodeMirror.defineExtension(\"openNotification\", function(template, options) {\n    closeNotification(this, close);\n    var dialog = dialogDiv(this, template, options && options.bottom);\n    var closed = false, doneTimer;\n    var duration = options && typeof options.duration !== \"undefined\" ? options.duration : 5000;\n\n    function close() {\n      if (closed) return;\n      closed = true;\n      clearTimeout(doneTimer);\n      CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');\n      dialog.parentNode.removeChild(dialog);\n    }\n\n    CodeMirror.on(dialog, 'click', function(e) {\n      CodeMirror.e_preventDefault(e);\n      close();\n    });\n\n    if (duration)\n      doneTimer = setTimeout(close, duration);\n\n    return close;\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/display/autorefresh.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"))\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod)\n  else // Plain browser env\n    mod(CodeMirror)\n})(function(CodeMirror) {\n  \"use strict\"\n\n  CodeMirror.defineOption(\"autoRefresh\", false, function(cm, val) {\n    if (cm.state.autoRefresh) {\n      stopListening(cm, cm.state.autoRefresh)\n      cm.state.autoRefresh = null\n    }\n    if (val && cm.display.wrapper.offsetHeight == 0)\n      startListening(cm, cm.state.autoRefresh = {delay: val.delay || 250})\n  })\n\n  function startListening(cm, state) {\n    function check() {\n      if (cm.display.wrapper.offsetHeight) {\n        stopListening(cm, state)\n        if (cm.display.lastWrapHeight != cm.display.wrapper.clientHeight)\n          cm.refresh()\n      } else {\n        state.timeout = setTimeout(check, state.delay)\n      }\n    }\n    state.timeout = setTimeout(check, state.delay)\n    state.hurry = function() {\n      clearTimeout(state.timeout)\n      state.timeout = setTimeout(check, 50)\n    }\n    CodeMirror.on(window, \"mouseup\", state.hurry)\n    CodeMirror.on(window, \"keyup\", state.hurry)\n  }\n\n  function stopListening(_cm, state) {\n    clearTimeout(state.timeout)\n    CodeMirror.off(window, \"mouseup\", state.hurry)\n    CodeMirror.off(window, \"keyup\", state.hurry)\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/display/fullscreen.css",
    "content": ".CodeMirror-fullscreen {\n  position: fixed;\n  top: 0; left: 0; right: 0; bottom: 0;\n  height: auto;\n  z-index: 9;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/addon/display/fullscreen.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineOption(\"fullScreen\", false, function(cm, val, old) {\n    if (old == CodeMirror.Init) old = false;\n    if (!old == !val) return;\n    if (val) setFullscreen(cm);\n    else setNormal(cm);\n  });\n\n  function setFullscreen(cm) {\n    var wrap = cm.getWrapperElement();\n    cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,\n                                  width: wrap.style.width, height: wrap.style.height};\n    wrap.style.width = \"\";\n    wrap.style.height = \"auto\";\n    wrap.className += \" CodeMirror-fullscreen\";\n    document.documentElement.style.overflow = \"hidden\";\n    cm.refresh();\n  }\n\n  function setNormal(cm) {\n    var wrap = cm.getWrapperElement();\n    wrap.className = wrap.className.replace(/\\s*CodeMirror-fullscreen\\b/, \"\");\n    document.documentElement.style.overflow = \"\";\n    var info = cm.state.fullScreenRestore;\n    wrap.style.width = info.width; wrap.style.height = info.height;\n    window.scrollTo(info.scrollLeft, info.scrollTop);\n    cm.refresh();\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/display/panel.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  CodeMirror.defineExtension(\"addPanel\", function(node, options) {\n    options = options || {};\n\n    if (!this.state.panels) initPanels(this);\n\n    var info = this.state.panels;\n    var wrapper = info.wrapper;\n    var cmWrapper = this.getWrapperElement();\n    var replace = options.replace instanceof Panel && !options.replace.cleared;\n\n    if (options.after instanceof Panel && !options.after.cleared) {\n      wrapper.insertBefore(node, options.before.node.nextSibling);\n    } else if (options.before instanceof Panel && !options.before.cleared) {\n      wrapper.insertBefore(node, options.before.node);\n    } else if (replace) {\n      wrapper.insertBefore(node, options.replace.node);\n      info.panels++;\n      options.replace.clear();\n    } else if (options.position == \"bottom\") {\n      wrapper.appendChild(node);\n    } else if (options.position == \"before-bottom\") {\n      wrapper.insertBefore(node, cmWrapper.nextSibling);\n    } else if (options.position == \"after-top\") {\n      wrapper.insertBefore(node, cmWrapper);\n    } else {\n      wrapper.insertBefore(node, wrapper.firstChild);\n    }\n\n    var height = (options && options.height) || node.offsetHeight;\n    this._setSize(null, info.heightLeft -= height);\n    if (!replace) {\n      info.panels++;\n    }\n    if (options.stable && isAtTop(this, node))\n      this.scrollTo(null, this.getScrollInfo().top + height)\n\n    return new Panel(this, node, options, height);\n  });\n\n  function Panel(cm, node, options, height) {\n    this.cm = cm;\n    this.node = node;\n    this.options = options;\n    this.height = height;\n    this.cleared = false;\n  }\n\n  Panel.prototype.clear = function() {\n    if (this.cleared) return;\n    this.cleared = true;\n    var info = this.cm.state.panels;\n    this.cm._setSize(null, info.heightLeft += this.height);\n    if (this.options.stable && isAtTop(this.cm, this.node))\n      this.cm.scrollTo(null, this.cm.getScrollInfo().top - this.height)\n    info.wrapper.removeChild(this.node);\n    if (--info.panels == 0) removePanels(this.cm);\n  };\n\n  Panel.prototype.changed = function(height) {\n    var newHeight = height == null ? this.node.offsetHeight : height;\n    var info = this.cm.state.panels;\n    this.cm._setSize(null, info.heightLeft -= (newHeight - this.height));\n    this.height = newHeight;\n  };\n\n  function initPanels(cm) {\n    var wrap = cm.getWrapperElement();\n    var style = window.getComputedStyle ? window.getComputedStyle(wrap) : wrap.currentStyle;\n    var height = parseInt(style.height);\n    var info = cm.state.panels = {\n      setHeight: wrap.style.height,\n      heightLeft: height,\n      panels: 0,\n      wrapper: document.createElement(\"div\")\n    };\n    wrap.parentNode.insertBefore(info.wrapper, wrap);\n    var hasFocus = cm.hasFocus();\n    info.wrapper.appendChild(wrap);\n    if (hasFocus) cm.focus();\n\n    cm._setSize = cm.setSize;\n    if (height != null) cm.setSize = function(width, newHeight) {\n      if (newHeight == null) return this._setSize(width, newHeight);\n      info.setHeight = newHeight;\n      if (typeof newHeight != \"number\") {\n        var px = /^(\\d+\\.?\\d*)px$/.exec(newHeight);\n        if (px) {\n          newHeight = Number(px[1]);\n        } else {\n          info.wrapper.style.height = newHeight;\n          newHeight = info.wrapper.offsetHeight;\n          info.wrapper.style.height = \"\";\n        }\n      }\n      cm._setSize(width, info.heightLeft += (newHeight - height));\n      height = newHeight;\n    };\n  }\n\n  function removePanels(cm) {\n    var info = cm.state.panels;\n    cm.state.panels = null;\n\n    var wrap = cm.getWrapperElement();\n    info.wrapper.parentNode.replaceChild(wrap, info.wrapper);\n    wrap.style.height = info.setHeight;\n    cm.setSize = cm._setSize;\n    cm.setSize();\n  }\n\n  function isAtTop(cm, dom) {\n    for (var sibling = dom.nextSibling; sibling; sibling = sibling.nextSibling)\n      if (sibling == cm.getWrapperElement()) return true\n    return false\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/display/placeholder.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  CodeMirror.defineOption(\"placeholder\", \"\", function(cm, val, old) {\n    var prev = old && old != CodeMirror.Init;\n    if (val && !prev) {\n      cm.on(\"blur\", onBlur);\n      cm.on(\"change\", onChange);\n      cm.on(\"swapDoc\", onChange);\n      onChange(cm);\n    } else if (!val && prev) {\n      cm.off(\"blur\", onBlur);\n      cm.off(\"change\", onChange);\n      cm.off(\"swapDoc\", onChange);\n      clearPlaceholder(cm);\n      var wrapper = cm.getWrapperElement();\n      wrapper.className = wrapper.className.replace(\" CodeMirror-empty\", \"\");\n    }\n\n    if (val && !cm.hasFocus()) onBlur(cm);\n  });\n\n  function clearPlaceholder(cm) {\n    if (cm.state.placeholder) {\n      cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);\n      cm.state.placeholder = null;\n    }\n  }\n  function setPlaceholder(cm) {\n    clearPlaceholder(cm);\n    var elt = cm.state.placeholder = document.createElement(\"pre\");\n    elt.style.cssText = \"height: 0; overflow: visible\";\n    elt.style.direction = cm.getOption(\"direction\");\n    elt.className = \"CodeMirror-placeholder\";\n    var placeHolder = cm.getOption(\"placeholder\")\n    if (typeof placeHolder == \"string\") placeHolder = document.createTextNode(placeHolder)\n    elt.appendChild(placeHolder)\n    cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);\n  }\n\n  function onBlur(cm) {\n    if (isEmpty(cm)) setPlaceholder(cm);\n  }\n  function onChange(cm) {\n    var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);\n    wrapper.className = wrapper.className.replace(\" CodeMirror-empty\", \"\") + (empty ? \" CodeMirror-empty\" : \"\");\n\n    if (empty) setPlaceholder(cm);\n    else clearPlaceholder(cm);\n  }\n\n  function isEmpty(cm) {\n    return (cm.lineCount() === 1) && (cm.getLine(0) === \"\");\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/display/rulers.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineOption(\"rulers\", false, function(cm, val) {\n    if (cm.state.rulerDiv) {\n      cm.state.rulerDiv.parentElement.removeChild(cm.state.rulerDiv)\n      cm.state.rulerDiv = null\n      cm.off(\"refresh\", drawRulers)\n    }\n    if (val && val.length) {\n      cm.state.rulerDiv = cm.display.lineSpace.parentElement.insertBefore(document.createElement(\"div\"), cm.display.lineSpace)\n      cm.state.rulerDiv.className = \"CodeMirror-rulers\"\n      drawRulers(cm)\n      cm.on(\"refresh\", drawRulers)\n    }\n  });\n\n  function drawRulers(cm) {\n    cm.state.rulerDiv.textContent = \"\"\n    var val = cm.getOption(\"rulers\");\n    var cw = cm.defaultCharWidth();\n    var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), \"div\").left;\n    cm.state.rulerDiv.style.minHeight = (cm.display.scroller.offsetHeight + 30) + \"px\";\n    for (var i = 0; i < val.length; i++) {\n      var elt = document.createElement(\"div\");\n      elt.className = \"CodeMirror-ruler\";\n      var col, conf = val[i];\n      if (typeof conf == \"number\") {\n        col = conf;\n      } else {\n        col = conf.column;\n        if (conf.className) elt.className += \" \" + conf.className;\n        if (conf.color) elt.style.borderColor = conf.color;\n        if (conf.lineStyle) elt.style.borderLeftStyle = conf.lineStyle;\n        if (conf.width) elt.style.borderLeftWidth = conf.width;\n      }\n      elt.style.left = (left + col * cw) + \"px\";\n      cm.state.rulerDiv.appendChild(elt)\n    }\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/edit/closebrackets.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  var defaults = {\n    pairs: \"()[]{}''\\\"\\\"\",\n    triples: \"\",\n    explode: \"[]{}\"\n  };\n\n  var Pos = CodeMirror.Pos;\n\n  CodeMirror.defineOption(\"autoCloseBrackets\", false, function(cm, val, old) {\n    if (old && old != CodeMirror.Init) {\n      cm.removeKeyMap(keyMap);\n      cm.state.closeBrackets = null;\n    }\n    if (val) {\n      ensureBound(getOption(val, \"pairs\"))\n      cm.state.closeBrackets = val;\n      cm.addKeyMap(keyMap);\n    }\n  });\n\n  function getOption(conf, name) {\n    if (name == \"pairs\" && typeof conf == \"string\") return conf;\n    if (typeof conf == \"object\" && conf[name] != null) return conf[name];\n    return defaults[name];\n  }\n\n  var keyMap = {Backspace: handleBackspace, Enter: handleEnter};\n  function ensureBound(chars) {\n    for (var i = 0; i < chars.length; i++) {\n      var ch = chars.charAt(i), key = \"'\" + ch + \"'\"\n      if (!keyMap[key]) keyMap[key] = handler(ch)\n    }\n  }\n  ensureBound(defaults.pairs + \"`\")\n\n  function handler(ch) {\n    return function(cm) { return handleChar(cm, ch); };\n  }\n\n  function getConfig(cm) {\n    var deflt = cm.state.closeBrackets;\n    if (!deflt || deflt.override) return deflt;\n    var mode = cm.getModeAt(cm.getCursor());\n    return mode.closeBrackets || deflt;\n  }\n\n  function handleBackspace(cm) {\n    var conf = getConfig(cm);\n    if (!conf || cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n\n    var pairs = getOption(conf, \"pairs\");\n    var ranges = cm.listSelections();\n    for (var i = 0; i < ranges.length; i++) {\n      if (!ranges[i].empty()) return CodeMirror.Pass;\n      var around = charsAround(cm, ranges[i].head);\n      if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;\n    }\n    for (var i = ranges.length - 1; i >= 0; i--) {\n      var cur = ranges[i].head;\n      cm.replaceRange(\"\", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), \"+delete\");\n    }\n  }\n\n  function handleEnter(cm) {\n    var conf = getConfig(cm);\n    var explode = conf && getOption(conf, \"explode\");\n    if (!explode || cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n\n    var ranges = cm.listSelections();\n    for (var i = 0; i < ranges.length; i++) {\n      if (!ranges[i].empty()) return CodeMirror.Pass;\n      var around = charsAround(cm, ranges[i].head);\n      if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;\n    }\n    cm.operation(function() {\n      var linesep = cm.lineSeparator() || \"\\n\";\n      cm.replaceSelection(linesep + linesep, null);\n      cm.execCommand(\"goCharLeft\");\n      ranges = cm.listSelections();\n      for (var i = 0; i < ranges.length; i++) {\n        var line = ranges[i].head.line;\n        cm.indentLine(line, null, true);\n        cm.indentLine(line + 1, null, true);\n      }\n    });\n  }\n\n  function contractSelection(sel) {\n    var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;\n    return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),\n            head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};\n  }\n\n  function handleChar(cm, ch) {\n    var conf = getConfig(cm);\n    if (!conf || cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n\n    var pairs = getOption(conf, \"pairs\");\n    var pos = pairs.indexOf(ch);\n    if (pos == -1) return CodeMirror.Pass;\n    var triples = getOption(conf, \"triples\");\n\n    var identical = pairs.charAt(pos + 1) == ch;\n    var ranges = cm.listSelections();\n    var opening = pos % 2 == 0;\n\n    var type;\n    for (var i = 0; i < ranges.length; i++) {\n      var range = ranges[i], cur = range.head, curType;\n      var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));\n      if (opening && !range.empty()) {\n        curType = \"surround\";\n      } else if ((identical || !opening) && next == ch) {\n        if (identical && stringStartsAfter(cm, cur))\n          curType = \"both\";\n        else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)\n          curType = \"skipThree\";\n        else\n          curType = \"skip\";\n      } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&\n                 cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) {\n        if (cur.ch > 2 && /\\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass;\n        curType = \"addFour\";\n      } else if (identical) {\n        var prev = cur.ch == 0 ? \" \" : cm.getRange(Pos(cur.line, cur.ch - 1), cur)\n        if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = \"both\";\n        else return CodeMirror.Pass;\n      } else if (opening) {\n        curType = \"both\";\n      } else {\n        return CodeMirror.Pass;\n      }\n      if (!type) type = curType;\n      else if (type != curType) return CodeMirror.Pass;\n    }\n\n    var left = pos % 2 ? pairs.charAt(pos - 1) : ch;\n    var right = pos % 2 ? ch : pairs.charAt(pos + 1);\n    cm.operation(function() {\n      if (type == \"skip\") {\n        cm.execCommand(\"goCharRight\");\n      } else if (type == \"skipThree\") {\n        for (var i = 0; i < 3; i++)\n          cm.execCommand(\"goCharRight\");\n      } else if (type == \"surround\") {\n        var sels = cm.getSelections();\n        for (var i = 0; i < sels.length; i++)\n          sels[i] = left + sels[i] + right;\n        cm.replaceSelections(sels, \"around\");\n        sels = cm.listSelections().slice();\n        for (var i = 0; i < sels.length; i++)\n          sels[i] = contractSelection(sels[i]);\n        cm.setSelections(sels);\n      } else if (type == \"both\") {\n        cm.replaceSelection(left + right, null);\n        cm.triggerElectric(left + right);\n        cm.execCommand(\"goCharLeft\");\n      } else if (type == \"addFour\") {\n        cm.replaceSelection(left + left + left + left, \"before\");\n        cm.execCommand(\"goCharRight\");\n      }\n    });\n  }\n\n  function charsAround(cm, pos) {\n    var str = cm.getRange(Pos(pos.line, pos.ch - 1),\n                          Pos(pos.line, pos.ch + 1));\n    return str.length == 2 ? str : null;\n  }\n\n  function stringStartsAfter(cm, pos) {\n    var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))\n    return /\\bstring/.test(token.type) && token.start == pos.ch &&\n      (pos.ch == 0 || !/\\bstring/.test(cm.getTokenTypeAt(pos)))\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/edit/closetag.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**\n * Tag-closer extension for CodeMirror.\n *\n * This extension adds an \"autoCloseTags\" option that can be set to\n * either true to get the default behavior, or an object to further\n * configure its behavior.\n *\n * These are supported options:\n *\n * `whenClosing` (default true)\n *   Whether to autoclose when the '/' of a closing tag is typed.\n * `whenOpening` (default true)\n *   Whether to autoclose the tag when the final '>' of an opening\n *   tag is typed.\n * `dontCloseTags` (default is empty tags for HTML, none for XML)\n *   An array of tag names that should not be autoclosed.\n * `indentTags` (default is block tags for HTML, none for XML)\n *   An array of tag names that should, when opened, cause a\n *   blank line to be added inside the tag, and the blank line and\n *   closing line to be indented.\n *\n * See demos/closetag.html for a usage example.\n */\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../fold/xml-fold\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../fold/xml-fold\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  CodeMirror.defineOption(\"autoCloseTags\", false, function(cm, val, old) {\n    if (old != CodeMirror.Init && old)\n      cm.removeKeyMap(\"autoCloseTags\");\n    if (!val) return;\n    var map = {name: \"autoCloseTags\"};\n    if (typeof val != \"object\" || val.whenClosing)\n      map[\"'/'\"] = function(cm) { return autoCloseSlash(cm); };\n    if (typeof val != \"object\" || val.whenOpening)\n      map[\"'>'\"] = function(cm) { return autoCloseGT(cm); };\n    cm.addKeyMap(map);\n  });\n\n  var htmlDontClose = [\"area\", \"base\", \"br\", \"col\", \"command\", \"embed\", \"hr\", \"img\", \"input\", \"keygen\", \"link\", \"meta\", \"param\",\n                       \"source\", \"track\", \"wbr\"];\n  var htmlIndent = [\"applet\", \"blockquote\", \"body\", \"button\", \"div\", \"dl\", \"fieldset\", \"form\", \"frameset\", \"h1\", \"h2\", \"h3\", \"h4\",\n                    \"h5\", \"h6\", \"head\", \"html\", \"iframe\", \"layer\", \"legend\", \"object\", \"ol\", \"p\", \"select\", \"table\", \"ul\"];\n\n  function autoCloseGT(cm) {\n    if (cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n    var ranges = cm.listSelections(), replacements = [];\n    var opt = cm.getOption(\"autoCloseTags\");\n    for (var i = 0; i < ranges.length; i++) {\n      if (!ranges[i].empty()) return CodeMirror.Pass;\n      var pos = ranges[i].head, tok = cm.getTokenAt(pos);\n      var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;\n      if (inner.mode.name != \"xml\" || !state.tagName) return CodeMirror.Pass;\n\n      var html = inner.mode.configuration == \"html\";\n      var dontCloseTags = (typeof opt == \"object\" && opt.dontCloseTags) || (html && htmlDontClose);\n      var indentTags = (typeof opt == \"object\" && opt.indentTags) || (html && htmlIndent);\n\n      var tagName = state.tagName;\n      if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);\n      var lowerTagName = tagName.toLowerCase();\n      // Don't process the '>' at the end of an end-tag or self-closing tag\n      if (!tagName ||\n          tok.type == \"string\" && (tok.end != pos.ch || !/[\\\"\\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||\n          tok.type == \"tag\" && state.type == \"closeTag\" ||\n          tok.string.indexOf(\"/\") == (tok.string.length - 1) || // match something like <someTagName />\n          dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||\n          closingTagExists(cm, tagName, pos, state, true))\n        return CodeMirror.Pass;\n\n      var indent = indentTags && indexOf(indentTags, lowerTagName) > -1;\n      replacements[i] = {indent: indent,\n                         text: \">\" + (indent ? \"\\n\\n\" : \"\") + \"</\" + tagName + \">\",\n                         newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)};\n    }\n\n    var dontIndentOnAutoClose = (typeof opt == \"object\" && opt.dontIndentOnAutoClose);\n    for (var i = ranges.length - 1; i >= 0; i--) {\n      var info = replacements[i];\n      cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, \"+insert\");\n      var sel = cm.listSelections().slice(0);\n      sel[i] = {head: info.newPos, anchor: info.newPos};\n      cm.setSelections(sel);\n      if (!dontIndentOnAutoClose && info.indent) {\n        cm.indentLine(info.newPos.line, null, true);\n        cm.indentLine(info.newPos.line + 1, null, true);\n      }\n    }\n  }\n\n  function autoCloseCurrent(cm, typingSlash) {\n    var ranges = cm.listSelections(), replacements = [];\n    var head = typingSlash ? \"/\" : \"</\";\n    var opt = cm.getOption(\"autoCloseTags\");\n    var dontIndentOnAutoClose = (typeof opt == \"object\" && opt.dontIndentOnSlash);\n    for (var i = 0; i < ranges.length; i++) {\n      if (!ranges[i].empty()) return CodeMirror.Pass;\n      var pos = ranges[i].head, tok = cm.getTokenAt(pos);\n      var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;\n      if (typingSlash && (tok.type == \"string\" || tok.string.charAt(0) != \"<\" ||\n                          tok.start != pos.ch - 1))\n        return CodeMirror.Pass;\n      // Kludge to get around the fact that we are not in XML mode\n      // when completing in JS/CSS snippet in htmlmixed mode. Does not\n      // work for other XML embedded languages (there is no general\n      // way to go from a mixed mode to its current XML state).\n      var replacement;\n      if (inner.mode.name != \"xml\") {\n        if (cm.getMode().name == \"htmlmixed\" && inner.mode.name == \"javascript\")\n          replacement = head + \"script\";\n        else if (cm.getMode().name == \"htmlmixed\" && inner.mode.name == \"css\")\n          replacement = head + \"style\";\n        else\n          return CodeMirror.Pass;\n      } else {\n        if (!state.context || !state.context.tagName ||\n            closingTagExists(cm, state.context.tagName, pos, state))\n          return CodeMirror.Pass;\n        replacement = head + state.context.tagName;\n      }\n      if (cm.getLine(pos.line).charAt(tok.end) != \">\") replacement += \">\";\n      replacements[i] = replacement;\n    }\n    cm.replaceSelections(replacements);\n    ranges = cm.listSelections();\n    if (!dontIndentOnAutoClose) {\n        for (var i = 0; i < ranges.length; i++)\n            if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line)\n                cm.indentLine(ranges[i].head.line);\n    }\n  }\n\n  function autoCloseSlash(cm) {\n    if (cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n    return autoCloseCurrent(cm, true);\n  }\n\n  CodeMirror.commands.closeTag = function(cm) { return autoCloseCurrent(cm); };\n\n  function indexOf(collection, elt) {\n    if (collection.indexOf) return collection.indexOf(elt);\n    for (var i = 0, e = collection.length; i < e; ++i)\n      if (collection[i] == elt) return i;\n    return -1;\n  }\n\n  // If xml-fold is loaded, we use its functionality to try and verify\n  // whether a given tag is actually unclosed.\n  function closingTagExists(cm, tagName, pos, state, newTag) {\n    if (!CodeMirror.scanForClosingTag) return false;\n    var end = Math.min(cm.lastLine() + 1, pos.line + 500);\n    var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);\n    if (!nextClose || nextClose.tag != tagName) return false;\n    var cx = state.context;\n    // If the immediate wrapping context contains onCx instances of\n    // the same tag, a closing tag only exists if there are at least\n    // that many closing tags of that type following.\n    for (var onCx = newTag ? 1 : 0; cx && cx.tagName == tagName; cx = cx.prev) ++onCx;\n    pos = nextClose.to;\n    for (var i = 1; i < onCx; i++) {\n      var next = CodeMirror.scanForClosingTag(cm, pos, null, end);\n      if (!next || next.tag != tagName) return false;\n      pos = next.to;\n    }\n    return true;\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/edit/continuelist.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var listRE = /^(\\s*)(>[> ]*|[*+-] \\[[x ]\\]\\s|[*+-]\\s|(\\d+)([.)]))(\\s*)/,\n      emptyListRE = /^(\\s*)(>[> ]*|[*+-] \\[[x ]\\]|[*+-]|(\\d+)[.)])(\\s*)$/,\n      unorderedListRE = /[*+-]\\s/;\n\n  CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {\n    if (cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n    var ranges = cm.listSelections(), replacements = [];\n    for (var i = 0; i < ranges.length; i++) {\n      var pos = ranges[i].head;\n      var eolState = cm.getStateAfter(pos.line);\n      var inList = eolState.list !== false;\n      var inQuote = eolState.quote !== 0;\n\n      var line = cm.getLine(pos.line), match = listRE.exec(line);\n      var cursorBeforeBullet = /^\\s*$/.test(line.slice(0, pos.ch));\n      if (!ranges[i].empty() || (!inList && !inQuote) || !match || cursorBeforeBullet) {\n        cm.execCommand(\"newlineAndIndent\");\n        return;\n      }\n      if (emptyListRE.test(line)) {\n        if (!/>\\s*$/.test(line)) cm.replaceRange(\"\", {\n          line: pos.line, ch: 0\n        }, {\n          line: pos.line, ch: pos.ch + 1\n        });\n        replacements[i] = \"\\n\";\n      } else {\n        var indent = match[1], after = match[5];\n        var numbered = !(unorderedListRE.test(match[2]) || match[2].indexOf(\">\") >= 0);\n        var bullet = numbered ? (parseInt(match[3], 10) + 1) + match[4] : match[2].replace(\"x\", \" \");\n        replacements[i] = \"\\n\" + indent + bullet + after;\n\n        if (numbered) incrementRemainingMarkdownListNumbers(cm, pos);\n      }\n    }\n\n    cm.replaceSelections(replacements);\n  };\n\n  // Auto-updating Markdown list numbers when a new item is added to the\n  // middle of a list\n  function incrementRemainingMarkdownListNumbers(cm, pos) {\n    var startLine = pos.line, lookAhead = 0, skipCount = 0;\n    var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1];\n\n    do {\n      lookAhead += 1;\n      var nextLineNumber = startLine + lookAhead;\n      var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine);\n\n      if (nextItem) {\n        var nextIndent = nextItem[1];\n        var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount);\n        var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber;\n\n        if (startIndent === nextIndent && !isNaN(nextNumber)) {\n          if (newNumber === nextNumber) itemNumber = nextNumber + 1;\n          if (newNumber > nextNumber) itemNumber = newNumber + 1;\n          cm.replaceRange(\n            nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]),\n          {\n            line: nextLineNumber, ch: 0\n          }, {\n            line: nextLineNumber, ch: nextLine.length\n          });\n        } else {\n          if (startIndent.length > nextIndent.length) return;\n          // This doesn't run if the next line immediatley indents, as it is\n          // not clear of the users intention (new indented item or same level)\n          if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return;\n          skipCount += 1;\n        }\n      }\n    } while (nextItem);\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/edit/matchbrackets.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  var ie_lt8 = /MSIE \\d/.test(navigator.userAgent) &&\n    (document.documentMode == null || document.documentMode < 8);\n\n  var Pos = CodeMirror.Pos;\n\n  var matching = {\"(\": \")>\", \")\": \"(<\", \"[\": \"]>\", \"]\": \"[<\", \"{\": \"}>\", \"}\": \"{<\", \"<\": \">>\", \">\": \"<<\"};\n\n  function bracketRegex(config) {\n    return config && config.bracketRegex || /[(){}[\\]]/\n  }\n\n  function findMatchingBracket(cm, where, config) {\n    var line = cm.getLineHandle(where.line), pos = where.ch - 1;\n    var afterCursor = config && config.afterCursor\n    if (afterCursor == null)\n      afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)\n    var re = bracketRegex(config)\n\n    // A cursor is defined as between two characters, but in in vim command mode\n    // (i.e. not insert mode), the cursor is visually represented as a\n    // highlighted box on top of the 2nd character. Otherwise, we allow matches\n    // from before or after the cursor.\n    var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) ||\n        re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)];\n    if (!match) return null;\n    var dir = match.charAt(1) == \">\" ? 1 : -1;\n    if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;\n    var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));\n\n    var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);\n    if (found == null) return null;\n    return {from: Pos(where.line, pos), to: found && found.pos,\n            match: found && found.ch == match.charAt(0), forward: dir > 0};\n  }\n\n  // bracketRegex is used to specify which type of bracket to scan\n  // should be a regexp, e.g. /[[\\]]/\n  //\n  // Note: If \"where\" is on an open bracket, then this bracket is ignored.\n  //\n  // Returns false when no bracket was found, null when it reached\n  // maxScanLines and gave up\n  function scanForBracket(cm, where, dir, style, config) {\n    var maxScanLen = (config && config.maxScanLineLength) || 10000;\n    var maxScanLines = (config && config.maxScanLines) || 1000;\n\n    var stack = [];\n    var re = bracketRegex(config)\n    var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)\n                          : Math.max(cm.firstLine() - 1, where.line - maxScanLines);\n    for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {\n      var line = cm.getLine(lineNo);\n      if (!line) continue;\n      var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;\n      if (line.length > maxScanLen) continue;\n      if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);\n      for (; pos != end; pos += dir) {\n        var ch = line.charAt(pos);\n        if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {\n          var match = matching[ch];\n          if ((match.charAt(1) == \">\") == (dir > 0)) stack.push(ch);\n          else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};\n          else stack.pop();\n        }\n      }\n    }\n    return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;\n  }\n\n  function matchBrackets(cm, autoclear, config) {\n    // Disable brace matching in long lines, since it'll cause hugely slow updates\n    var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;\n    var marks = [], ranges = cm.listSelections();\n    for (var i = 0; i < ranges.length; i++) {\n      var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);\n      if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {\n        var style = match.match ? \"CodeMirror-matchingbracket\" : \"CodeMirror-nonmatchingbracket\";\n        marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));\n        if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)\n          marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));\n      }\n    }\n\n    if (marks.length) {\n      // Kludge to work around the IE bug from issue #1193, where text\n      // input stops going to the textare whever this fires.\n      if (ie_lt8 && cm.state.focused) cm.focus();\n\n      var clear = function() {\n        cm.operation(function() {\n          for (var i = 0; i < marks.length; i++) marks[i].clear();\n        });\n      };\n      if (autoclear) setTimeout(clear, 800);\n      else return clear;\n    }\n  }\n\n  function doMatchBrackets(cm) {\n    cm.operation(function() {\n      if (cm.state.matchBrackets.currentlyHighlighted) {\n        cm.state.matchBrackets.currentlyHighlighted();\n        cm.state.matchBrackets.currentlyHighlighted = null;\n      }\n      cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);\n    });\n  }\n\n  CodeMirror.defineOption(\"matchBrackets\", false, function(cm, val, old) {\n    if (old && old != CodeMirror.Init) {\n      cm.off(\"cursorActivity\", doMatchBrackets);\n      if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {\n        cm.state.matchBrackets.currentlyHighlighted();\n        cm.state.matchBrackets.currentlyHighlighted = null;\n      }\n    }\n    if (val) {\n      cm.state.matchBrackets = typeof val == \"object\" ? val : {};\n      cm.on(\"cursorActivity\", doMatchBrackets);\n    }\n  });\n\n  CodeMirror.defineExtension(\"matchBrackets\", function() {matchBrackets(this, true);});\n  CodeMirror.defineExtension(\"findMatchingBracket\", function(pos, config, oldConfig){\n    // Backwards-compatibility kludge\n    if (oldConfig || typeof config == \"boolean\") {\n      if (!oldConfig) {\n        config = config ? {strict: true} : null\n      } else {\n        oldConfig.strict = config\n        config = oldConfig\n      }\n    }\n    return findMatchingBracket(this, pos, config)\n  });\n  CodeMirror.defineExtension(\"scanForBracket\", function(pos, dir, style, config){\n    return scanForBracket(this, pos, dir, style, config);\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/edit/matchtags.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../fold/xml-fold\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../fold/xml-fold\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineOption(\"matchTags\", false, function(cm, val, old) {\n    if (old && old != CodeMirror.Init) {\n      cm.off(\"cursorActivity\", doMatchTags);\n      cm.off(\"viewportChange\", maybeUpdateMatch);\n      clear(cm);\n    }\n    if (val) {\n      cm.state.matchBothTags = typeof val == \"object\" && val.bothTags;\n      cm.on(\"cursorActivity\", doMatchTags);\n      cm.on(\"viewportChange\", maybeUpdateMatch);\n      doMatchTags(cm);\n    }\n  });\n\n  function clear(cm) {\n    if (cm.state.tagHit) cm.state.tagHit.clear();\n    if (cm.state.tagOther) cm.state.tagOther.clear();\n    cm.state.tagHit = cm.state.tagOther = null;\n  }\n\n  function doMatchTags(cm) {\n    cm.state.failedTagMatch = false;\n    cm.operation(function() {\n      clear(cm);\n      if (cm.somethingSelected()) return;\n      var cur = cm.getCursor(), range = cm.getViewport();\n      range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);\n      var match = CodeMirror.findMatchingTag(cm, cur, range);\n      if (!match) return;\n      if (cm.state.matchBothTags) {\n        var hit = match.at == \"open\" ? match.open : match.close;\n        if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: \"CodeMirror-matchingtag\"});\n      }\n      var other = match.at == \"close\" ? match.open : match.close;\n      if (other)\n        cm.state.tagOther = cm.markText(other.from, other.to, {className: \"CodeMirror-matchingtag\"});\n      else\n        cm.state.failedTagMatch = true;\n    });\n  }\n\n  function maybeUpdateMatch(cm) {\n    if (cm.state.failedTagMatch) doMatchTags(cm);\n  }\n\n  CodeMirror.commands.toMatchingTag = function(cm) {\n    var found = CodeMirror.findMatchingTag(cm, cm.getCursor());\n    if (found) {\n      var other = found.at == \"close\" ? found.open : found.close;\n      if (other) cm.extendSelection(other.to, other.from);\n    }\n  };\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/edit/trailingspace.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  CodeMirror.defineOption(\"showTrailingSpace\", false, function(cm, val, prev) {\n    if (prev == CodeMirror.Init) prev = false;\n    if (prev && !val)\n      cm.removeOverlay(\"trailingspace\");\n    else if (!prev && val)\n      cm.addOverlay({\n        token: function(stream) {\n          for (var l = stream.string.length, i = l; i && /\\s/.test(stream.string.charAt(i - 1)); --i) {}\n          if (i > stream.pos) { stream.pos = i; return null; }\n          stream.pos = l;\n          return \"trailingspace\";\n        },\n        name: \"trailingspace\"\n      });\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/fold/brace-fold.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.registerHelper(\"fold\", \"brace\", function(cm, start) {\n  var line = start.line, lineText = cm.getLine(line);\n  var tokenType;\n\n  function findOpening(openCh) {\n    for (var at = start.ch, pass = 0;;) {\n      var found = at <= 0 ? -1 : lineText.lastIndexOf(openCh, at - 1);\n      if (found == -1) {\n        if (pass == 1) break;\n        pass = 1;\n        at = lineText.length;\n        continue;\n      }\n      if (pass == 1 && found < start.ch) break;\n      tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1));\n      if (!/^(comment|string)/.test(tokenType)) return found + 1;\n      at = found - 1;\n    }\n  }\n\n  var startToken = \"{\", endToken = \"}\", startCh = findOpening(\"{\");\n  if (startCh == null) {\n    startToken = \"[\", endToken = \"]\";\n    startCh = findOpening(\"[\");\n  }\n\n  if (startCh == null) return;\n  var count = 1, lastLine = cm.lastLine(), end, endCh;\n  outer: for (var i = line; i <= lastLine; ++i) {\n    var text = cm.getLine(i), pos = i == line ? startCh : 0;\n    for (;;) {\n      var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);\n      if (nextOpen < 0) nextOpen = text.length;\n      if (nextClose < 0) nextClose = text.length;\n      pos = Math.min(nextOpen, nextClose);\n      if (pos == text.length) break;\n      if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == tokenType) {\n        if (pos == nextOpen) ++count;\n        else if (!--count) { end = i; endCh = pos; break outer; }\n      }\n      ++pos;\n    }\n  }\n  if (end == null || line == end) return;\n  return {from: CodeMirror.Pos(line, startCh),\n          to: CodeMirror.Pos(end, endCh)};\n});\n\nCodeMirror.registerHelper(\"fold\", \"import\", function(cm, start) {\n  function hasImport(line) {\n    if (line < cm.firstLine() || line > cm.lastLine()) return null;\n    var start = cm.getTokenAt(CodeMirror.Pos(line, 1));\n    if (!/\\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));\n    if (start.type != \"keyword\" || start.string != \"import\") return null;\n    // Now find closing semicolon, return its position\n    for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) {\n      var text = cm.getLine(i), semi = text.indexOf(\";\");\n      if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)};\n    }\n  }\n\n  var startLine = start.line, has = hasImport(startLine), prev;\n  if (!has || hasImport(startLine - 1) || ((prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1))\n    return null;\n  for (var end = has.end;;) {\n    var next = hasImport(end.line + 1);\n    if (next == null) break;\n    end = next.end;\n  }\n  return {from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), to: end};\n});\n\nCodeMirror.registerHelper(\"fold\", \"include\", function(cm, start) {\n  function hasInclude(line) {\n    if (line < cm.firstLine() || line > cm.lastLine()) return null;\n    var start = cm.getTokenAt(CodeMirror.Pos(line, 1));\n    if (!/\\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));\n    if (start.type == \"meta\" && start.string.slice(0, 8) == \"#include\") return start.start + 8;\n  }\n\n  var startLine = start.line, has = hasInclude(startLine);\n  if (has == null || hasInclude(startLine - 1) != null) return null;\n  for (var end = startLine;;) {\n    var next = hasInclude(end + 1);\n    if (next == null) break;\n    ++end;\n  }\n  return {from: CodeMirror.Pos(startLine, has + 1),\n          to: cm.clipPos(CodeMirror.Pos(end))};\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/fold/comment-fold.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.registerGlobalHelper(\"fold\", \"comment\", function(mode) {\n  return mode.blockCommentStart && mode.blockCommentEnd;\n}, function(cm, start) {\n  var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;\n  if (!startToken || !endToken) return;\n  var line = start.line, lineText = cm.getLine(line);\n\n  var startCh;\n  for (var at = start.ch, pass = 0;;) {\n    var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);\n    if (found == -1) {\n      if (pass == 1) return;\n      pass = 1;\n      at = lineText.length;\n      continue;\n    }\n    if (pass == 1 && found < start.ch) return;\n    if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1))) &&\n        (found == 0 || lineText.slice(found - endToken.length, found) == endToken ||\n         !/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found))))) {\n      startCh = found + startToken.length;\n      break;\n    }\n    at = found - 1;\n  }\n\n  var depth = 1, lastLine = cm.lastLine(), end, endCh;\n  outer: for (var i = line; i <= lastLine; ++i) {\n    var text = cm.getLine(i), pos = i == line ? startCh : 0;\n    for (;;) {\n      var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);\n      if (nextOpen < 0) nextOpen = text.length;\n      if (nextClose < 0) nextClose = text.length;\n      pos = Math.min(nextOpen, nextClose);\n      if (pos == text.length) break;\n      if (pos == nextOpen) ++depth;\n      else if (!--depth) { end = i; endCh = pos; break outer; }\n      ++pos;\n    }\n  }\n  if (end == null || line == end && endCh == startCh) return;\n  return {from: CodeMirror.Pos(line, startCh),\n          to: CodeMirror.Pos(end, endCh)};\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/fold/foldcode.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function doFold(cm, pos, options, force) {\n    if (options && options.call) {\n      var finder = options;\n      options = null;\n    } else {\n      var finder = getOption(cm, options, \"rangeFinder\");\n    }\n    if (typeof pos == \"number\") pos = CodeMirror.Pos(pos, 0);\n    var minSize = getOption(cm, options, \"minFoldSize\");\n\n    function getRange(allowFolded) {\n      var range = finder(cm, pos);\n      if (!range || range.to.line - range.from.line < minSize) return null;\n      var marks = cm.findMarksAt(range.from);\n      for (var i = 0; i < marks.length; ++i) {\n        if (marks[i].__isFold && force !== \"fold\") {\n          if (!allowFolded) return null;\n          range.cleared = true;\n          marks[i].clear();\n        }\n      }\n      return range;\n    }\n\n    var range = getRange(true);\n    if (getOption(cm, options, \"scanUp\")) while (!range && pos.line > cm.firstLine()) {\n      pos = CodeMirror.Pos(pos.line - 1, 0);\n      range = getRange(false);\n    }\n    if (!range || range.cleared || force === \"unfold\") return;\n\n    var myWidget = makeWidget(cm, options);\n    CodeMirror.on(myWidget, \"mousedown\", function(e) {\n      myRange.clear();\n      CodeMirror.e_preventDefault(e);\n    });\n    var myRange = cm.markText(range.from, range.to, {\n      replacedWith: myWidget,\n      clearOnEnter: getOption(cm, options, \"clearOnEnter\"),\n      __isFold: true\n    });\n    myRange.on(\"clear\", function(from, to) {\n      CodeMirror.signal(cm, \"unfold\", cm, from, to);\n    });\n    CodeMirror.signal(cm, \"fold\", cm, range.from, range.to);\n  }\n\n  function makeWidget(cm, options) {\n    var widget = getOption(cm, options, \"widget\");\n    if (typeof widget == \"string\") {\n      var text = document.createTextNode(widget);\n      widget = document.createElement(\"span\");\n      widget.appendChild(text);\n      widget.className = \"CodeMirror-foldmarker\";\n    } else if (widget) {\n      widget = widget.cloneNode(true)\n    }\n    return widget;\n  }\n\n  // Clumsy backwards-compatible interface\n  CodeMirror.newFoldFunction = function(rangeFinder, widget) {\n    return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };\n  };\n\n  // New-style interface\n  CodeMirror.defineExtension(\"foldCode\", function(pos, options, force) {\n    doFold(this, pos, options, force);\n  });\n\n  CodeMirror.defineExtension(\"isFolded\", function(pos) {\n    var marks = this.findMarksAt(pos);\n    for (var i = 0; i < marks.length; ++i)\n      if (marks[i].__isFold) return true;\n  });\n\n  CodeMirror.commands.toggleFold = function(cm) {\n    cm.foldCode(cm.getCursor());\n  };\n  CodeMirror.commands.fold = function(cm) {\n    cm.foldCode(cm.getCursor(), null, \"fold\");\n  };\n  CodeMirror.commands.unfold = function(cm) {\n    cm.foldCode(cm.getCursor(), null, \"unfold\");\n  };\n  CodeMirror.commands.foldAll = function(cm) {\n    cm.operation(function() {\n      for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)\n        cm.foldCode(CodeMirror.Pos(i, 0), null, \"fold\");\n    });\n  };\n  CodeMirror.commands.unfoldAll = function(cm) {\n    cm.operation(function() {\n      for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)\n        cm.foldCode(CodeMirror.Pos(i, 0), null, \"unfold\");\n    });\n  };\n\n  CodeMirror.registerHelper(\"fold\", \"combine\", function() {\n    var funcs = Array.prototype.slice.call(arguments, 0);\n    return function(cm, start) {\n      for (var i = 0; i < funcs.length; ++i) {\n        var found = funcs[i](cm, start);\n        if (found) return found;\n      }\n    };\n  });\n\n  CodeMirror.registerHelper(\"fold\", \"auto\", function(cm, start) {\n    var helpers = cm.getHelpers(start, \"fold\");\n    for (var i = 0; i < helpers.length; i++) {\n      var cur = helpers[i](cm, start);\n      if (cur) return cur;\n    }\n  });\n\n  var defaultOptions = {\n    rangeFinder: CodeMirror.fold.auto,\n    widget: \"\\u2194\",\n    minFoldSize: 0,\n    scanUp: false,\n    clearOnEnter: true\n  };\n\n  CodeMirror.defineOption(\"foldOptions\", null);\n\n  function getOption(cm, options, name) {\n    if (options && options[name] !== undefined)\n      return options[name];\n    var editorOptions = cm.options.foldOptions;\n    if (editorOptions && editorOptions[name] !== undefined)\n      return editorOptions[name];\n    return defaultOptions[name];\n  }\n\n  CodeMirror.defineExtension(\"foldOption\", function(options, name) {\n    return getOption(this, options, name);\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/fold/foldgutter.css",
    "content": ".CodeMirror-foldmarker {\n  color: blue;\n  text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px;\n  font-family: arial;\n  line-height: .3;\n  cursor: pointer;\n}\n.CodeMirror-foldgutter {\n  width: .7em;\n}\n.CodeMirror-foldgutter-open,\n.CodeMirror-foldgutter-folded {\n  cursor: pointer;\n}\n.CodeMirror-foldgutter-open:after {\n  content: \"\\25BE\";\n}\n.CodeMirror-foldgutter-folded:after {\n  content: \"\\25B8\";\n}\n"
  },
  {
    "path": "third_party/CodeMirror/addon/fold/foldgutter.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"./foldcode\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"./foldcode\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineOption(\"foldGutter\", false, function(cm, val, old) {\n    if (old && old != CodeMirror.Init) {\n      cm.clearGutter(cm.state.foldGutter.options.gutter);\n      cm.state.foldGutter = null;\n      cm.off(\"gutterClick\", onGutterClick);\n      cm.off(\"change\", onChange);\n      cm.off(\"viewportChange\", onViewportChange);\n      cm.off(\"fold\", onFold);\n      cm.off(\"unfold\", onFold);\n      cm.off(\"swapDoc\", onChange);\n    }\n    if (val) {\n      cm.state.foldGutter = new State(parseOptions(val));\n      updateInViewport(cm);\n      cm.on(\"gutterClick\", onGutterClick);\n      cm.on(\"change\", onChange);\n      cm.on(\"viewportChange\", onViewportChange);\n      cm.on(\"fold\", onFold);\n      cm.on(\"unfold\", onFold);\n      cm.on(\"swapDoc\", onChange);\n    }\n  });\n\n  var Pos = CodeMirror.Pos;\n\n  function State(options) {\n    this.options = options;\n    this.from = this.to = 0;\n  }\n\n  function parseOptions(opts) {\n    if (opts === true) opts = {};\n    if (opts.gutter == null) opts.gutter = \"CodeMirror-foldgutter\";\n    if (opts.indicatorOpen == null) opts.indicatorOpen = \"CodeMirror-foldgutter-open\";\n    if (opts.indicatorFolded == null) opts.indicatorFolded = \"CodeMirror-foldgutter-folded\";\n    return opts;\n  }\n\n  function isFolded(cm, line) {\n    var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0));\n    for (var i = 0; i < marks.length; ++i)\n      if (marks[i].__isFold && marks[i].find().from.line == line) return marks[i];\n  }\n\n  function marker(spec) {\n    if (typeof spec == \"string\") {\n      var elt = document.createElement(\"div\");\n      elt.className = spec + \" CodeMirror-guttermarker-subtle\";\n      return elt;\n    } else {\n      return spec.cloneNode(true);\n    }\n  }\n\n  function updateFoldInfo(cm, from, to) {\n    var opts = cm.state.foldGutter.options, cur = from;\n    var minSize = cm.foldOption(opts, \"minFoldSize\");\n    var func = cm.foldOption(opts, \"rangeFinder\");\n    cm.eachLine(from, to, function(line) {\n      var mark = null;\n      if (isFolded(cm, cur)) {\n        mark = marker(opts.indicatorFolded);\n      } else {\n        var pos = Pos(cur, 0);\n        var range = func && func(cm, pos);\n        if (range && range.to.line - range.from.line >= minSize)\n          mark = marker(opts.indicatorOpen);\n      }\n      cm.setGutterMarker(line, opts.gutter, mark);\n      ++cur;\n    });\n  }\n\n  function updateInViewport(cm) {\n    var vp = cm.getViewport(), state = cm.state.foldGutter;\n    if (!state) return;\n    cm.operation(function() {\n      updateFoldInfo(cm, vp.from, vp.to);\n    });\n    state.from = vp.from; state.to = vp.to;\n  }\n\n  function onGutterClick(cm, line, gutter) {\n    var state = cm.state.foldGutter;\n    if (!state) return;\n    var opts = state.options;\n    if (gutter != opts.gutter) return;\n    var folded = isFolded(cm, line);\n    if (folded) folded.clear();\n    else cm.foldCode(Pos(line, 0), opts.rangeFinder);\n  }\n\n  function onChange(cm) {\n    var state = cm.state.foldGutter;\n    if (!state) return;\n    var opts = state.options;\n    state.from = state.to = 0;\n    clearTimeout(state.changeUpdate);\n    state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600);\n  }\n\n  function onViewportChange(cm) {\n    var state = cm.state.foldGutter;\n    if (!state) return;\n    var opts = state.options;\n    clearTimeout(state.changeUpdate);\n    state.changeUpdate = setTimeout(function() {\n      var vp = cm.getViewport();\n      if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {\n        updateInViewport(cm);\n      } else {\n        cm.operation(function() {\n          if (vp.from < state.from) {\n            updateFoldInfo(cm, vp.from, state.from);\n            state.from = vp.from;\n          }\n          if (vp.to > state.to) {\n            updateFoldInfo(cm, state.to, vp.to);\n            state.to = vp.to;\n          }\n        });\n      }\n    }, opts.updateViewportTimeSpan || 400);\n  }\n\n  function onFold(cm, from) {\n    var state = cm.state.foldGutter;\n    if (!state) return;\n    var line = from.line;\n    if (line >= state.from && line < state.to)\n      updateFoldInfo(cm, line, line + 1);\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/fold/indent-fold.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nfunction lineIndent(cm, lineNo) {\n  var text = cm.getLine(lineNo)\n  var spaceTo = text.search(/\\S/)\n  if (spaceTo == -1 || /\\bcomment\\b/.test(cm.getTokenTypeAt(CodeMirror.Pos(lineNo, spaceTo + 1))))\n    return -1\n  return CodeMirror.countColumn(text, null, cm.getOption(\"tabSize\"))\n}\n\nCodeMirror.registerHelper(\"fold\", \"indent\", function(cm, start) {\n  var myIndent = lineIndent(cm, start.line)\n  if (myIndent < 0) return\n  var lastLineInFold = null\n\n  // Go through lines until we find a line that definitely doesn't belong in\n  // the block we're folding, or to the end.\n  for (var i = start.line + 1, end = cm.lastLine(); i <= end; ++i) {\n    var indent = lineIndent(cm, i)\n    if (indent == -1) {\n    } else if (indent > myIndent) {\n      // Lines with a greater indent are considered part of the block.\n      lastLineInFold = i;\n    } else {\n      // If this line has non-space, non-comment content, and is\n      // indented less or equal to the start line, it is the start of\n      // another block.\n      break;\n    }\n  }\n  if (lastLineInFold) return {\n    from: CodeMirror.Pos(start.line, cm.getLine(start.line).length),\n    to: CodeMirror.Pos(lastLineInFold, cm.getLine(lastLineInFold).length)\n  };\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/fold/markdown-fold.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.registerHelper(\"fold\", \"markdown\", function(cm, start) {\n  var maxDepth = 100;\n\n  function isHeader(lineNo) {\n    var tokentype = cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0));\n    return tokentype && /\\bheader\\b/.test(tokentype);\n  }\n\n  function headerLevel(lineNo, line, nextLine) {\n    var match = line && line.match(/^#+/);\n    if (match && isHeader(lineNo)) return match[0].length;\n    match = nextLine && nextLine.match(/^[=\\-]+\\s*$/);\n    if (match && isHeader(lineNo + 1)) return nextLine[0] == \"=\" ? 1 : 2;\n    return maxDepth;\n  }\n\n  var firstLine = cm.getLine(start.line), nextLine = cm.getLine(start.line + 1);\n  var level = headerLevel(start.line, firstLine, nextLine);\n  if (level === maxDepth) return undefined;\n\n  var lastLineNo = cm.lastLine();\n  var end = start.line, nextNextLine = cm.getLine(end + 2);\n  while (end < lastLineNo) {\n    if (headerLevel(end + 1, nextLine, nextNextLine) <= level) break;\n    ++end;\n    nextLine = nextNextLine;\n    nextNextLine = cm.getLine(end + 2);\n  }\n\n  return {\n    from: CodeMirror.Pos(start.line, firstLine.length),\n    to: CodeMirror.Pos(end, cm.getLine(end).length)\n  };\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/fold/xml-fold.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var Pos = CodeMirror.Pos;\n  function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }\n\n  var nameStartChar = \"A-Z_a-z\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD\";\n  var nameChar = nameStartChar + \"\\-\\:\\.0-9\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040\";\n  var xmlTagStart = new RegExp(\"<(/?)([\" + nameStartChar + \"][\" + nameChar + \"]*)\", \"g\");\n\n  function Iter(cm, line, ch, range) {\n    this.line = line; this.ch = ch;\n    this.cm = cm; this.text = cm.getLine(line);\n    this.min = range ? Math.max(range.from, cm.firstLine()) : cm.firstLine();\n    this.max = range ? Math.min(range.to - 1, cm.lastLine()) : cm.lastLine();\n  }\n\n  function tagAt(iter, ch) {\n    var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));\n    return type && /\\btag\\b/.test(type);\n  }\n\n  function nextLine(iter) {\n    if (iter.line >= iter.max) return;\n    iter.ch = 0;\n    iter.text = iter.cm.getLine(++iter.line);\n    return true;\n  }\n  function prevLine(iter) {\n    if (iter.line <= iter.min) return;\n    iter.text = iter.cm.getLine(--iter.line);\n    iter.ch = iter.text.length;\n    return true;\n  }\n\n  function toTagEnd(iter) {\n    for (;;) {\n      var gt = iter.text.indexOf(\">\", iter.ch);\n      if (gt == -1) { if (nextLine(iter)) continue; else return; }\n      if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }\n      var lastSlash = iter.text.lastIndexOf(\"/\", gt);\n      var selfClose = lastSlash > -1 && !/\\S/.test(iter.text.slice(lastSlash + 1, gt));\n      iter.ch = gt + 1;\n      return selfClose ? \"selfClose\" : \"regular\";\n    }\n  }\n  function toTagStart(iter) {\n    for (;;) {\n      var lt = iter.ch ? iter.text.lastIndexOf(\"<\", iter.ch - 1) : -1;\n      if (lt == -1) { if (prevLine(iter)) continue; else return; }\n      if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }\n      xmlTagStart.lastIndex = lt;\n      iter.ch = lt;\n      var match = xmlTagStart.exec(iter.text);\n      if (match && match.index == lt) return match;\n    }\n  }\n\n  function toNextTag(iter) {\n    for (;;) {\n      xmlTagStart.lastIndex = iter.ch;\n      var found = xmlTagStart.exec(iter.text);\n      if (!found) { if (nextLine(iter)) continue; else return; }\n      if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }\n      iter.ch = found.index + found[0].length;\n      return found;\n    }\n  }\n  function toPrevTag(iter) {\n    for (;;) {\n      var gt = iter.ch ? iter.text.lastIndexOf(\">\", iter.ch - 1) : -1;\n      if (gt == -1) { if (prevLine(iter)) continue; else return; }\n      if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }\n      var lastSlash = iter.text.lastIndexOf(\"/\", gt);\n      var selfClose = lastSlash > -1 && !/\\S/.test(iter.text.slice(lastSlash + 1, gt));\n      iter.ch = gt + 1;\n      return selfClose ? \"selfClose\" : \"regular\";\n    }\n  }\n\n  function findMatchingClose(iter, tag) {\n    var stack = [];\n    for (;;) {\n      var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);\n      if (!next || !(end = toTagEnd(iter))) return;\n      if (end == \"selfClose\") continue;\n      if (next[1]) { // closing tag\n        for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {\n          stack.length = i;\n          break;\n        }\n        if (i < 0 && (!tag || tag == next[2])) return {\n          tag: next[2],\n          from: Pos(startLine, startCh),\n          to: Pos(iter.line, iter.ch)\n        };\n      } else { // opening tag\n        stack.push(next[2]);\n      }\n    }\n  }\n  function findMatchingOpen(iter, tag) {\n    var stack = [];\n    for (;;) {\n      var prev = toPrevTag(iter);\n      if (!prev) return;\n      if (prev == \"selfClose\") { toTagStart(iter); continue; }\n      var endLine = iter.line, endCh = iter.ch;\n      var start = toTagStart(iter);\n      if (!start) return;\n      if (start[1]) { // closing tag\n        stack.push(start[2]);\n      } else { // opening tag\n        for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {\n          stack.length = i;\n          break;\n        }\n        if (i < 0 && (!tag || tag == start[2])) return {\n          tag: start[2],\n          from: Pos(iter.line, iter.ch),\n          to: Pos(endLine, endCh)\n        };\n      }\n    }\n  }\n\n  CodeMirror.registerHelper(\"fold\", \"xml\", function(cm, start) {\n    var iter = new Iter(cm, start.line, 0);\n    for (;;) {\n      var openTag = toNextTag(iter)\n      if (!openTag || iter.line != start.line) return\n      var end = toTagEnd(iter)\n      if (!end) return\n      if (!openTag[1] && end != \"selfClose\") {\n        var startPos = Pos(iter.line, iter.ch);\n        var endPos = findMatchingClose(iter, openTag[2]);\n        return endPos && cmp(endPos.from, startPos) > 0 ? {from: startPos, to: endPos.from} : null\n      }\n    }\n  });\n  CodeMirror.findMatchingTag = function(cm, pos, range) {\n    var iter = new Iter(cm, pos.line, pos.ch, range);\n    if (iter.text.indexOf(\">\") == -1 && iter.text.indexOf(\"<\") == -1) return;\n    var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);\n    var start = end && toTagStart(iter);\n    if (!end || !start || cmp(iter, pos) > 0) return;\n    var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};\n    if (end == \"selfClose\") return {open: here, close: null, at: \"open\"};\n\n    if (start[1]) { // closing tag\n      return {open: findMatchingOpen(iter, start[2]), close: here, at: \"close\"};\n    } else { // opening tag\n      iter = new Iter(cm, to.line, to.ch, range);\n      return {open: here, close: findMatchingClose(iter, start[2]), at: \"open\"};\n    }\n  };\n\n  CodeMirror.findEnclosingTag = function(cm, pos, range, tag) {\n    var iter = new Iter(cm, pos.line, pos.ch, range);\n    for (;;) {\n      var open = findMatchingOpen(iter, tag);\n      if (!open) break;\n      var forward = new Iter(cm, pos.line, pos.ch, range);\n      var close = findMatchingClose(forward, open.tag);\n      if (close) return {open: open, close: close};\n    }\n  };\n\n  // Used by addon/edit/closetag.js\n  CodeMirror.scanForClosingTag = function(cm, pos, name, end) {\n    var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);\n    return findMatchingClose(iter, name);\n  };\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/hint/anyword-hint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var WORD = /[\\w$]+/, RANGE = 500;\n\n  CodeMirror.registerHelper(\"hint\", \"anyword\", function(editor, options) {\n    var word = options && options.word || WORD;\n    var range = options && options.range || RANGE;\n    var cur = editor.getCursor(), curLine = editor.getLine(cur.line);\n    var end = cur.ch, start = end;\n    while (start && word.test(curLine.charAt(start - 1))) --start;\n    var curWord = start != end && curLine.slice(start, end);\n\n    var list = options && options.list || [], seen = {};\n    var re = new RegExp(word.source, \"g\");\n    for (var dir = -1; dir <= 1; dir += 2) {\n      var line = cur.line, endLine = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;\n      for (; line != endLine; line += dir) {\n        var text = editor.getLine(line), m;\n        while (m = re.exec(text)) {\n          if (line == cur.line && m[0] === curWord) continue;\n          if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) {\n            seen[m[0]] = true;\n            list.push(m[0]);\n          }\n        }\n      }\n    }\n    return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/hint/css-hint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../../mode/css/css\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../../mode/css/css\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var pseudoClasses = {link: 1, visited: 1, active: 1, hover: 1, focus: 1,\n                       \"first-letter\": 1, \"first-line\": 1, \"first-child\": 1,\n                       before: 1, after: 1, lang: 1};\n\n  CodeMirror.registerHelper(\"hint\", \"css\", function(cm) {\n    var cur = cm.getCursor(), token = cm.getTokenAt(cur);\n    var inner = CodeMirror.innerMode(cm.getMode(), token.state);\n    if (inner.mode.name != \"css\") return;\n\n    if (token.type == \"keyword\" && \"!important\".indexOf(token.string) == 0)\n      return {list: [\"!important\"], from: CodeMirror.Pos(cur.line, token.start),\n              to: CodeMirror.Pos(cur.line, token.end)};\n\n    var start = token.start, end = cur.ch, word = token.string.slice(0, end - start);\n    if (/[^\\w$_-]/.test(word)) {\n      word = \"\"; start = end = cur.ch;\n    }\n\n    var spec = CodeMirror.resolveMode(\"text/css\");\n\n    var result = [];\n    function add(keywords) {\n      for (var name in keywords)\n        if (!word || name.lastIndexOf(word, 0) == 0)\n          result.push(name);\n    }\n\n    var st = inner.state.state;\n    if (st == \"pseudo\" || token.type == \"variable-3\") {\n      add(pseudoClasses);\n    } else if (st == \"block\" || st == \"maybeprop\") {\n      add(spec.propertyKeywords);\n    } else if (st == \"prop\" || st == \"parens\" || st == \"at\" || st == \"params\") {\n      add(spec.valueKeywords);\n      add(spec.colorKeywords);\n    } else if (st == \"media\" || st == \"media_parens\") {\n      add(spec.mediaTypes);\n      add(spec.mediaFeatures);\n    }\n\n    if (result.length) return {\n      list: result,\n      from: CodeMirror.Pos(cur.line, start),\n      to: CodeMirror.Pos(cur.line, end)\n    };\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/hint/html-hint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"./xml-hint\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"./xml-hint\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var langs = \"ab aa af ak sq am ar an hy as av ae ay az bm ba eu be bn bh bi bs br bg my ca ch ce ny zh cv kw co cr hr cs da dv nl dz en eo et ee fo fj fi fr ff gl ka de el gn gu ht ha he hz hi ho hu ia id ie ga ig ik io is it iu ja jv kl kn kr ks kk km ki rw ky kv kg ko ku kj la lb lg li ln lo lt lu lv gv mk mg ms ml mt mi mr mh mn na nv nb nd ne ng nn no ii nr oc oj cu om or os pa pi fa pl ps pt qu rm rn ro ru sa sc sd se sm sg sr gd sn si sk sl so st es su sw ss sv ta te tg th ti bo tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa cy wo fy xh yi yo za zu\".split(\" \");\n  var targets = [\"_blank\", \"_self\", \"_top\", \"_parent\"];\n  var charsets = [\"ascii\", \"utf-8\", \"utf-16\", \"latin1\", \"latin1\"];\n  var methods = [\"get\", \"post\", \"put\", \"delete\"];\n  var encs = [\"application/x-www-form-urlencoded\", \"multipart/form-data\", \"text/plain\"];\n  var media = [\"all\", \"screen\", \"print\", \"embossed\", \"braille\", \"handheld\", \"print\", \"projection\", \"screen\", \"tty\", \"tv\", \"speech\",\n               \"3d-glasses\", \"resolution [>][<][=] [X]\", \"device-aspect-ratio: X/Y\", \"orientation:portrait\",\n               \"orientation:landscape\", \"device-height: [X]\", \"device-width: [X]\"];\n  var s = { attrs: {} }; // Simple tag, reused for a whole lot of tags\n\n  var data = {\n    a: {\n      attrs: {\n        href: null, ping: null, type: null,\n        media: media,\n        target: targets,\n        hreflang: langs\n      }\n    },\n    abbr: s,\n    acronym: s,\n    address: s,\n    applet: s,\n    area: {\n      attrs: {\n        alt: null, coords: null, href: null, target: null, ping: null,\n        media: media, hreflang: langs, type: null,\n        shape: [\"default\", \"rect\", \"circle\", \"poly\"]\n      }\n    },\n    article: s,\n    aside: s,\n    audio: {\n      attrs: {\n        src: null, mediagroup: null,\n        crossorigin: [\"anonymous\", \"use-credentials\"],\n        preload: [\"none\", \"metadata\", \"auto\"],\n        autoplay: [\"\", \"autoplay\"],\n        loop: [\"\", \"loop\"],\n        controls: [\"\", \"controls\"]\n      }\n    },\n    b: s,\n    base: { attrs: { href: null, target: targets } },\n    basefont: s,\n    bdi: s,\n    bdo: s,\n    big: s,\n    blockquote: { attrs: { cite: null } },\n    body: s,\n    br: s,\n    button: {\n      attrs: {\n        form: null, formaction: null, name: null, value: null,\n        autofocus: [\"\", \"autofocus\"],\n        disabled: [\"\", \"autofocus\"],\n        formenctype: encs,\n        formmethod: methods,\n        formnovalidate: [\"\", \"novalidate\"],\n        formtarget: targets,\n        type: [\"submit\", \"reset\", \"button\"]\n      }\n    },\n    canvas: { attrs: { width: null, height: null } },\n    caption: s,\n    center: s,\n    cite: s,\n    code: s,\n    col: { attrs: { span: null } },\n    colgroup: { attrs: { span: null } },\n    command: {\n      attrs: {\n        type: [\"command\", \"checkbox\", \"radio\"],\n        label: null, icon: null, radiogroup: null, command: null, title: null,\n        disabled: [\"\", \"disabled\"],\n        checked: [\"\", \"checked\"]\n      }\n    },\n    data: { attrs: { value: null } },\n    datagrid: { attrs: { disabled: [\"\", \"disabled\"], multiple: [\"\", \"multiple\"] } },\n    datalist: { attrs: { data: null } },\n    dd: s,\n    del: { attrs: { cite: null, datetime: null } },\n    details: { attrs: { open: [\"\", \"open\"] } },\n    dfn: s,\n    dir: s,\n    div: s,\n    dl: s,\n    dt: s,\n    em: s,\n    embed: { attrs: { src: null, type: null, width: null, height: null } },\n    eventsource: { attrs: { src: null } },\n    fieldset: { attrs: { disabled: [\"\", \"disabled\"], form: null, name: null } },\n    figcaption: s,\n    figure: s,\n    font: s,\n    footer: s,\n    form: {\n      attrs: {\n        action: null, name: null,\n        \"accept-charset\": charsets,\n        autocomplete: [\"on\", \"off\"],\n        enctype: encs,\n        method: methods,\n        novalidate: [\"\", \"novalidate\"],\n        target: targets\n      }\n    },\n    frame: s,\n    frameset: s,\n    h1: s, h2: s, h3: s, h4: s, h5: s, h6: s,\n    head: {\n      attrs: {},\n      children: [\"title\", \"base\", \"link\", \"style\", \"meta\", \"script\", \"noscript\", \"command\"]\n    },\n    header: s,\n    hgroup: s,\n    hr: s,\n    html: {\n      attrs: { manifest: null },\n      children: [\"head\", \"body\"]\n    },\n    i: s,\n    iframe: {\n      attrs: {\n        src: null, srcdoc: null, name: null, width: null, height: null,\n        sandbox: [\"allow-top-navigation\", \"allow-same-origin\", \"allow-forms\", \"allow-scripts\"],\n        seamless: [\"\", \"seamless\"]\n      }\n    },\n    img: {\n      attrs: {\n        alt: null, src: null, ismap: null, usemap: null, width: null, height: null,\n        crossorigin: [\"anonymous\", \"use-credentials\"]\n      }\n    },\n    input: {\n      attrs: {\n        alt: null, dirname: null, form: null, formaction: null,\n        height: null, list: null, max: null, maxlength: null, min: null,\n        name: null, pattern: null, placeholder: null, size: null, src: null,\n        step: null, value: null, width: null,\n        accept: [\"audio/*\", \"video/*\", \"image/*\"],\n        autocomplete: [\"on\", \"off\"],\n        autofocus: [\"\", \"autofocus\"],\n        checked: [\"\", \"checked\"],\n        disabled: [\"\", \"disabled\"],\n        formenctype: encs,\n        formmethod: methods,\n        formnovalidate: [\"\", \"novalidate\"],\n        formtarget: targets,\n        multiple: [\"\", \"multiple\"],\n        readonly: [\"\", \"readonly\"],\n        required: [\"\", \"required\"],\n        type: [\"hidden\", \"text\", \"search\", \"tel\", \"url\", \"email\", \"password\", \"datetime\", \"date\", \"month\",\n               \"week\", \"time\", \"datetime-local\", \"number\", \"range\", \"color\", \"checkbox\", \"radio\",\n               \"file\", \"submit\", \"image\", \"reset\", \"button\"]\n      }\n    },\n    ins: { attrs: { cite: null, datetime: null } },\n    kbd: s,\n    keygen: {\n      attrs: {\n        challenge: null, form: null, name: null,\n        autofocus: [\"\", \"autofocus\"],\n        disabled: [\"\", \"disabled\"],\n        keytype: [\"RSA\"]\n      }\n    },\n    label: { attrs: { \"for\": null, form: null } },\n    legend: s,\n    li: { attrs: { value: null } },\n    link: {\n      attrs: {\n        href: null, type: null,\n        hreflang: langs,\n        media: media,\n        sizes: [\"all\", \"16x16\", \"16x16 32x32\", \"16x16 32x32 64x64\"]\n      }\n    },\n    map: { attrs: { name: null } },\n    mark: s,\n    menu: { attrs: { label: null, type: [\"list\", \"context\", \"toolbar\"] } },\n    meta: {\n      attrs: {\n        content: null,\n        charset: charsets,\n        name: [\"viewport\", \"application-name\", \"author\", \"description\", \"generator\", \"keywords\"],\n        \"http-equiv\": [\"content-language\", \"content-type\", \"default-style\", \"refresh\"]\n      }\n    },\n    meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } },\n    nav: s,\n    noframes: s,\n    noscript: s,\n    object: {\n      attrs: {\n        data: null, type: null, name: null, usemap: null, form: null, width: null, height: null,\n        typemustmatch: [\"\", \"typemustmatch\"]\n      }\n    },\n    ol: { attrs: { reversed: [\"\", \"reversed\"], start: null, type: [\"1\", \"a\", \"A\", \"i\", \"I\"] } },\n    optgroup: { attrs: { disabled: [\"\", \"disabled\"], label: null } },\n    option: { attrs: { disabled: [\"\", \"disabled\"], label: null, selected: [\"\", \"selected\"], value: null } },\n    output: { attrs: { \"for\": null, form: null, name: null } },\n    p: s,\n    param: { attrs: { name: null, value: null } },\n    pre: s,\n    progress: { attrs: { value: null, max: null } },\n    q: { attrs: { cite: null } },\n    rp: s,\n    rt: s,\n    ruby: s,\n    s: s,\n    samp: s,\n    script: {\n      attrs: {\n        type: [\"text/javascript\"],\n        src: null,\n        async: [\"\", \"async\"],\n        defer: [\"\", \"defer\"],\n        charset: charsets\n      }\n    },\n    section: s,\n    select: {\n      attrs: {\n        form: null, name: null, size: null,\n        autofocus: [\"\", \"autofocus\"],\n        disabled: [\"\", \"disabled\"],\n        multiple: [\"\", \"multiple\"]\n      }\n    },\n    small: s,\n    source: { attrs: { src: null, type: null, media: null } },\n    span: s,\n    strike: s,\n    strong: s,\n    style: {\n      attrs: {\n        type: [\"text/css\"],\n        media: media,\n        scoped: null\n      }\n    },\n    sub: s,\n    summary: s,\n    sup: s,\n    table: s,\n    tbody: s,\n    td: { attrs: { colspan: null, rowspan: null, headers: null } },\n    textarea: {\n      attrs: {\n        dirname: null, form: null, maxlength: null, name: null, placeholder: null,\n        rows: null, cols: null,\n        autofocus: [\"\", \"autofocus\"],\n        disabled: [\"\", \"disabled\"],\n        readonly: [\"\", \"readonly\"],\n        required: [\"\", \"required\"],\n        wrap: [\"soft\", \"hard\"]\n      }\n    },\n    tfoot: s,\n    th: { attrs: { colspan: null, rowspan: null, headers: null, scope: [\"row\", \"col\", \"rowgroup\", \"colgroup\"] } },\n    thead: s,\n    time: { attrs: { datetime: null } },\n    title: s,\n    tr: s,\n    track: {\n      attrs: {\n        src: null, label: null, \"default\": null,\n        kind: [\"subtitles\", \"captions\", \"descriptions\", \"chapters\", \"metadata\"],\n        srclang: langs\n      }\n    },\n    tt: s,\n    u: s,\n    ul: s,\n    \"var\": s,\n    video: {\n      attrs: {\n        src: null, poster: null, width: null, height: null,\n        crossorigin: [\"anonymous\", \"use-credentials\"],\n        preload: [\"auto\", \"metadata\", \"none\"],\n        autoplay: [\"\", \"autoplay\"],\n        mediagroup: [\"movie\"],\n        muted: [\"\", \"muted\"],\n        controls: [\"\", \"controls\"]\n      }\n    },\n    wbr: s\n  };\n\n  var globalAttrs = {\n    accesskey: [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"],\n    \"class\": null,\n    contenteditable: [\"true\", \"false\"],\n    contextmenu: null,\n    dir: [\"ltr\", \"rtl\", \"auto\"],\n    draggable: [\"true\", \"false\", \"auto\"],\n    dropzone: [\"copy\", \"move\", \"link\", \"string:\", \"file:\"],\n    hidden: [\"hidden\"],\n    id: null,\n    inert: [\"inert\"],\n    itemid: null,\n    itemprop: null,\n    itemref: null,\n    itemscope: [\"itemscope\"],\n    itemtype: null,\n    lang: [\"en\", \"es\"],\n    spellcheck: [\"true\", \"false\"],\n    autocorrect: [\"true\", \"false\"],\n    autocapitalize: [\"true\", \"false\"],\n    style: null,\n    tabindex: [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"],\n    title: null,\n    translate: [\"yes\", \"no\"],\n    onclick: null,\n    rel: [\"stylesheet\", \"alternate\", \"author\", \"bookmark\", \"help\", \"license\", \"next\", \"nofollow\", \"noreferrer\", \"prefetch\", \"prev\", \"search\", \"tag\"]\n  };\n  function populate(obj) {\n    for (var attr in globalAttrs) if (globalAttrs.hasOwnProperty(attr))\n      obj.attrs[attr] = globalAttrs[attr];\n  }\n\n  populate(s);\n  for (var tag in data) if (data.hasOwnProperty(tag) && data[tag] != s)\n    populate(data[tag]);\n\n  CodeMirror.htmlSchema = data;\n  function htmlHint(cm, options) {\n    var local = {schemaInfo: data};\n    if (options) for (var opt in options) local[opt] = options[opt];\n    return CodeMirror.hint.xml(cm, local);\n  }\n  CodeMirror.registerHelper(\"hint\", \"html\", htmlHint);\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/hint/javascript-hint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  var Pos = CodeMirror.Pos;\n\n  function forEach(arr, f) {\n    for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);\n  }\n\n  function arrayContains(arr, item) {\n    if (!Array.prototype.indexOf) {\n      var i = arr.length;\n      while (i--) {\n        if (arr[i] === item) {\n          return true;\n        }\n      }\n      return false;\n    }\n    return arr.indexOf(item) != -1;\n  }\n\n  function scriptHint(editor, keywords, getToken, options) {\n    // Find the token at the cursor\n    var cur = editor.getCursor(), token = getToken(editor, cur);\n    if (/\\b(?:string|comment)\\b/.test(token.type)) return;\n    var innerMode = CodeMirror.innerMode(editor.getMode(), token.state);\n    if (innerMode.mode.helperType === \"json\") return;\n    token.state = innerMode.state;\n\n    // If it's not a 'word-style' token, ignore the token.\n    if (!/^[\\w$_]*$/.test(token.string)) {\n      token = {start: cur.ch, end: cur.ch, string: \"\", state: token.state,\n               type: token.string == \".\" ? \"property\" : null};\n    } else if (token.end > cur.ch) {\n      token.end = cur.ch;\n      token.string = token.string.slice(0, cur.ch - token.start);\n    }\n\n    var tprop = token;\n    // If it is a property, find out what it is a property of.\n    while (tprop.type == \"property\") {\n      tprop = getToken(editor, Pos(cur.line, tprop.start));\n      if (tprop.string != \".\") return;\n      tprop = getToken(editor, Pos(cur.line, tprop.start));\n      if (!context) var context = [];\n      context.push(tprop);\n    }\n    return {list: getCompletions(token, context, keywords, options),\n            from: Pos(cur.line, token.start),\n            to: Pos(cur.line, token.end)};\n  }\n\n  function javascriptHint(editor, options) {\n    return scriptHint(editor, javascriptKeywords,\n                      function (e, cur) {return e.getTokenAt(cur);},\n                      options);\n  };\n  CodeMirror.registerHelper(\"hint\", \"javascript\", javascriptHint);\n\n  function getCoffeeScriptToken(editor, cur) {\n  // This getToken, it is for coffeescript, imitates the behavior of\n  // getTokenAt method in javascript.js, that is, returning \"property\"\n  // type and treat \".\" as indepenent token.\n    var token = editor.getTokenAt(cur);\n    if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {\n      token.end = token.start;\n      token.string = '.';\n      token.type = \"property\";\n    }\n    else if (/^\\.[\\w$_]*$/.test(token.string)) {\n      token.type = \"property\";\n      token.start++;\n      token.string = token.string.replace(/\\./, '');\n    }\n    return token;\n  }\n\n  function coffeescriptHint(editor, options) {\n    return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options);\n  }\n  CodeMirror.registerHelper(\"hint\", \"coffeescript\", coffeescriptHint);\n\n  var stringProps = (\"charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight \" +\n                     \"toUpperCase toLowerCase split concat match replace search\").split(\" \");\n  var arrayProps = (\"length concat join splice push pop shift unshift slice reverse sort indexOf \" +\n                    \"lastIndexOf every some filter forEach map reduce reduceRight \").split(\" \");\n  var funcProps = \"prototype apply call bind\".split(\" \");\n  var javascriptKeywords = (\"break case catch class const continue debugger default delete do else export extends false finally for function \" +\n                  \"if in import instanceof new null return super switch this throw true try typeof var void while with yield\").split(\" \");\n  var coffeescriptKeywords = (\"and break catch class continue delete do else extends false finally for \" +\n                  \"if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes\").split(\" \");\n\n  function forAllProps(obj, callback) {\n    if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {\n      for (var name in obj) callback(name)\n    } else {\n      for (var o = obj; o; o = Object.getPrototypeOf(o))\n        Object.getOwnPropertyNames(o).forEach(callback)\n    }\n  }\n\n  function getCompletions(token, context, keywords, options) {\n    var found = [], start = token.string, global = options && options.globalScope || window;\n    function maybeAdd(str) {\n      if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str);\n    }\n    function gatherCompletions(obj) {\n      if (typeof obj == \"string\") forEach(stringProps, maybeAdd);\n      else if (obj instanceof Array) forEach(arrayProps, maybeAdd);\n      else if (obj instanceof Function) forEach(funcProps, maybeAdd);\n      forAllProps(obj, maybeAdd)\n    }\n\n    if (context && context.length) {\n      // If this is a property, see if it belongs to some object we can\n      // find in the current environment.\n      var obj = context.pop(), base;\n      if (obj.type && obj.type.indexOf(\"variable\") === 0) {\n        if (options && options.additionalContext)\n          base = options.additionalContext[obj.string];\n        if (!options || options.useGlobalScope !== false)\n          base = base || global[obj.string];\n      } else if (obj.type == \"string\") {\n        base = \"\";\n      } else if (obj.type == \"atom\") {\n        base = 1;\n      } else if (obj.type == \"function\") {\n        if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&\n            (typeof global.jQuery == 'function'))\n          base = global.jQuery();\n        else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function'))\n          base = global._();\n      }\n      while (base != null && context.length)\n        base = base[context.pop().string];\n      if (base != null) gatherCompletions(base);\n    } else {\n      // If not, just look in the global object and any local scope\n      // (reading into JS mode internals to get at the local and global variables)\n      for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);\n      for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name);\n      if (!options || options.useGlobalScope !== false)\n        gatherCompletions(global);\n      forEach(keywords, maybeAdd);\n    }\n    return found;\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/hint/show-hint.css",
    "content": ".CodeMirror-hints {\n  position: absolute;\n  z-index: 10;\n  overflow: hidden;\n  list-style: none;\n\n  margin: 0;\n  padding: 2px;\n\n  -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);\n  -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);\n  box-shadow: 2px 3px 5px rgba(0,0,0,.2);\n  border-radius: 3px;\n  border: 1px solid silver;\n\n  background: white;\n  font-size: 90%;\n  font-family: monospace;\n\n  max-height: 20em;\n  overflow-y: auto;\n}\n\n.CodeMirror-hint {\n  margin: 0;\n  padding: 0 4px;\n  border-radius: 2px;\n  white-space: pre;\n  color: black;\n  cursor: pointer;\n}\n\nli.CodeMirror-hint-active {\n  background: #08f;\n  color: white;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/addon/hint/show-hint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\nvar mac = /Mac/.test(navigator.platform);\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var HINT_ELEMENT_CLASS        = \"CodeMirror-hint\";\n  var ACTIVE_HINT_ELEMENT_CLASS = \"CodeMirror-hint-active\";\n\n  // This is the old interface, kept around for now to stay\n  // backwards-compatible.\n  CodeMirror.showHint = function(cm, getHints, options) {\n    if (!getHints) return cm.showHint(options);\n    if (options && options.async) getHints.async = true;\n    var newOpts = {hint: getHints};\n    if (options) for (var prop in options) newOpts[prop] = options[prop];\n    return cm.showHint(newOpts);\n  };\n\n  CodeMirror.defineExtension(\"showHint\", function(options) {\n    options = parseOptions(this, this.getCursor(\"start\"), options);\n    var selections = this.listSelections()\n    if (selections.length > 1) return;\n    // By default, don't allow completion when something is selected.\n    // A hint function can have a `supportsSelection` property to\n    // indicate that it can handle selections.\n    if (this.somethingSelected()) {\n      if (!options.hint.supportsSelection) return;\n      // Don't try with cross-line selections\n      for (var i = 0; i < selections.length; i++)\n        if (selections[i].head.line != selections[i].anchor.line) return;\n    }\n\n    if (this.state.completionActive) this.state.completionActive.close();\n    var completion = this.state.completionActive = new Completion(this, options);\n    if (!completion.options.hint) return;\n\n    CodeMirror.signal(this, \"startCompletion\", this);\n    completion.update(true);\n  });\n\n  CodeMirror.defineExtension(\"closeHint\", function() {\n    if (this.state.completionActive) this.state.completionActive.close()\n  })\n\n  function Completion(cm, options) {\n    this.cm = cm;\n    this.options = options;\n    this.widget = null;\n    this.debounce = 0;\n    this.tick = 0;\n    this.startPos = this.cm.getCursor(\"start\");\n    this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;\n\n    var self = this;\n    cm.on(\"cursorActivity\", this.activityFunc = function() { self.cursorActivity(); });\n  }\n\n  var requestAnimationFrame = window.requestAnimationFrame || function(fn) {\n    return setTimeout(fn, 1000/60);\n  };\n  var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;\n\n  Completion.prototype = {\n    close: function() {\n      if (!this.active()) return;\n      this.cm.state.completionActive = null;\n      this.tick = null;\n      this.cm.off(\"cursorActivity\", this.activityFunc);\n\n      if (this.widget && this.data) CodeMirror.signal(this.data, \"close\");\n      if (this.widget) this.widget.close();\n      CodeMirror.signal(this.cm, \"endCompletion\", this.cm);\n    },\n\n    active: function() {\n      return this.cm.state.completionActive == this;\n    },\n\n    pick: function(data, i) {\n      var completion = data.list[i];\n      if (completion.hint) completion.hint(this.cm, data, completion);\n      else this.cm.replaceRange(getText(completion), completion.from || data.from,\n                                completion.to || data.to, \"complete\");\n      CodeMirror.signal(data, \"pick\", completion);\n      this.close();\n    },\n\n    cursorActivity: function() {\n      if (this.debounce) {\n        cancelAnimationFrame(this.debounce);\n        this.debounce = 0;\n      }\n\n      var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);\n      if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||\n          pos.ch < this.startPos.ch || this.cm.somethingSelected() ||\n          (!pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {\n        this.close();\n      } else {\n        var self = this;\n        this.debounce = requestAnimationFrame(function() {self.update();});\n        if (this.widget) this.widget.disable();\n      }\n    },\n\n    update: function(first) {\n      if (this.tick == null) return\n      var self = this, myTick = ++this.tick\n      fetchHints(this.options.hint, this.cm, this.options, function(data) {\n        if (self.tick == myTick) self.finishUpdate(data, first)\n      })\n    },\n\n    finishUpdate: function(data, first) {\n      if (this.data) CodeMirror.signal(this.data, \"update\");\n\n      var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);\n      if (this.widget) this.widget.close();\n\n      this.data = data;\n\n      if (data && data.list.length) {\n        if (picked && data.list.length == 1) {\n          this.pick(data, 0);\n        } else {\n          this.widget = new Widget(this, data);\n          CodeMirror.signal(data, \"shown\");\n        }\n      }\n    }\n  };\n\n  function parseOptions(cm, pos, options) {\n    var editor = cm.options.hintOptions;\n    var out = {};\n    for (var prop in defaultOptions) out[prop] = defaultOptions[prop];\n    if (editor) for (var prop in editor)\n      if (editor[prop] !== undefined) out[prop] = editor[prop];\n    if (options) for (var prop in options)\n      if (options[prop] !== undefined) out[prop] = options[prop];\n    if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)\n    return out;\n  }\n\n  function getText(completion) {\n    if (typeof completion == \"string\") return completion;\n    else return completion.text;\n  }\n\n  function buildKeyMap(completion, handle) {\n    var baseMap = {\n      Up: function() {handle.moveFocus(-1);},\n      Down: function() {handle.moveFocus(1);},\n      PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},\n      PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},\n      Home: function() {handle.setFocus(0);},\n      End: function() {handle.setFocus(handle.length - 1);},\n      Enter: handle.pick,\n      Tab: handle.pick,\n      Esc: handle.close\n    };\n\n    if (mac) {\n      baseMap[\"Ctrl-P\"] = function() {handle.moveFocus(-1);};\n      baseMap[\"Ctrl-N\"] = function() {handle.moveFocus(1);};\n    }\n\n    var custom = completion.options.customKeys;\n    var ourMap = custom ? {} : baseMap;\n    function addBinding(key, val) {\n      var bound;\n      if (typeof val != \"string\")\n        bound = function(cm) { return val(cm, handle); };\n      // This mechanism is deprecated\n      else if (baseMap.hasOwnProperty(val))\n        bound = baseMap[val];\n      else\n        bound = val;\n      ourMap[key] = bound;\n    }\n    if (custom)\n      for (var key in custom) if (custom.hasOwnProperty(key))\n        addBinding(key, custom[key]);\n    var extra = completion.options.extraKeys;\n    if (extra)\n      for (var key in extra) if (extra.hasOwnProperty(key))\n        addBinding(key, extra[key]);\n    return ourMap;\n  }\n\n  function getHintElement(hintsElement, el) {\n    while (el && el != hintsElement) {\n      if (el.nodeName.toUpperCase() === \"LI\" && el.parentNode == hintsElement) return el;\n      el = el.parentNode;\n    }\n  }\n\n  function Widget(completion, data) {\n    this.completion = completion;\n    this.data = data;\n    this.picked = false;\n    var widget = this, cm = completion.cm;\n    var ownerDocument = cm.getInputField().ownerDocument;\n    var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow;\n\n    var hints = this.hints = ownerDocument.createElement(\"ul\");\n    var theme = completion.cm.options.theme;\n    hints.className = \"CodeMirror-hints \" + theme;\n    this.selectedHint = data.selectedHint || 0;\n\n    var completions = data.list;\n    for (var i = 0; i < completions.length; ++i) {\n      var elt = hints.appendChild(ownerDocument.createElement(\"li\")), cur = completions[i];\n      var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? \"\" : \" \" + ACTIVE_HINT_ELEMENT_CLASS);\n      if (cur.className != null) className = cur.className + \" \" + className;\n      elt.className = className;\n      if (cur.render) cur.render(elt, data, cur);\n      else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur)));\n      elt.hintId = i;\n    }\n\n    var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);\n    var left = pos.left, top = pos.bottom, below = true;\n    hints.style.left = left + \"px\";\n    hints.style.top = top + \"px\";\n    // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.\n    var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth);\n    var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight);\n    (completion.options.container || ownerDocument.body).appendChild(hints);\n    var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;\n    var scrolls = hints.scrollHeight > hints.clientHeight + 1\n    var startScroll = cm.getScrollInfo();\n\n    if (overlapY > 0) {\n      var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);\n      if (curTop - height > 0) { // Fits above cursor\n        hints.style.top = (top = pos.top - height) + \"px\";\n        below = false;\n      } else if (height > winH) {\n        hints.style.height = (winH - 5) + \"px\";\n        hints.style.top = (top = pos.bottom - box.top) + \"px\";\n        var cursor = cm.getCursor();\n        if (data.from.ch != cursor.ch) {\n          pos = cm.cursorCoords(cursor);\n          hints.style.left = (left = pos.left) + \"px\";\n          box = hints.getBoundingClientRect();\n        }\n      }\n    }\n    var overlapX = box.right - winW;\n    if (overlapX > 0) {\n      if (box.right - box.left > winW) {\n        hints.style.width = (winW - 5) + \"px\";\n        overlapX -= (box.right - box.left) - winW;\n      }\n      hints.style.left = (left = pos.left - overlapX) + \"px\";\n    }\n    if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)\n      node.style.paddingRight = cm.display.nativeBarWidth + \"px\"\n\n    cm.addKeyMap(this.keyMap = buildKeyMap(completion, {\n      moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },\n      setFocus: function(n) { widget.changeActive(n); },\n      menuSize: function() { return widget.screenAmount(); },\n      length: completions.length,\n      close: function() { completion.close(); },\n      pick: function() { widget.pick(); },\n      data: data\n    }));\n\n    if (completion.options.closeOnUnfocus) {\n      var closingOnBlur;\n      cm.on(\"blur\", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });\n      cm.on(\"focus\", this.onFocus = function() { clearTimeout(closingOnBlur); });\n    }\n\n    cm.on(\"scroll\", this.onScroll = function() {\n      var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();\n      var newTop = top + startScroll.top - curScroll.top;\n      var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop);\n      if (!below) point += hints.offsetHeight;\n      if (point <= editor.top || point >= editor.bottom) return completion.close();\n      hints.style.top = newTop + \"px\";\n      hints.style.left = (left + startScroll.left - curScroll.left) + \"px\";\n    });\n\n    CodeMirror.on(hints, \"dblclick\", function(e) {\n      var t = getHintElement(hints, e.target || e.srcElement);\n      if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}\n    });\n\n    CodeMirror.on(hints, \"click\", function(e) {\n      var t = getHintElement(hints, e.target || e.srcElement);\n      if (t && t.hintId != null) {\n        widget.changeActive(t.hintId);\n        if (completion.options.completeOnSingleClick) widget.pick();\n      }\n    });\n\n    CodeMirror.on(hints, \"mousedown\", function() {\n      setTimeout(function(){cm.focus();}, 20);\n    });\n\n    CodeMirror.signal(data, \"select\", completions[this.selectedHint], hints.childNodes[this.selectedHint]);\n    return true;\n  }\n\n  Widget.prototype = {\n    close: function() {\n      if (this.completion.widget != this) return;\n      this.completion.widget = null;\n      this.hints.parentNode.removeChild(this.hints);\n      this.completion.cm.removeKeyMap(this.keyMap);\n\n      var cm = this.completion.cm;\n      if (this.completion.options.closeOnUnfocus) {\n        cm.off(\"blur\", this.onBlur);\n        cm.off(\"focus\", this.onFocus);\n      }\n      cm.off(\"scroll\", this.onScroll);\n    },\n\n    disable: function() {\n      this.completion.cm.removeKeyMap(this.keyMap);\n      var widget = this;\n      this.keyMap = {Enter: function() { widget.picked = true; }};\n      this.completion.cm.addKeyMap(this.keyMap);\n    },\n\n    pick: function() {\n      this.completion.pick(this.data, this.selectedHint);\n    },\n\n    changeActive: function(i, avoidWrap) {\n      if (i >= this.data.list.length)\n        i = avoidWrap ? this.data.list.length - 1 : 0;\n      else if (i < 0)\n        i = avoidWrap ? 0  : this.data.list.length - 1;\n      if (this.selectedHint == i) return;\n      var node = this.hints.childNodes[this.selectedHint];\n      if (node) node.className = node.className.replace(\" \" + ACTIVE_HINT_ELEMENT_CLASS, \"\");\n      node = this.hints.childNodes[this.selectedHint = i];\n      node.className += \" \" + ACTIVE_HINT_ELEMENT_CLASS;\n      if (node.offsetTop < this.hints.scrollTop)\n        this.hints.scrollTop = node.offsetTop - 3;\n      else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)\n        this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;\n      CodeMirror.signal(this.data, \"select\", this.data.list[this.selectedHint], node);\n    },\n\n    screenAmount: function() {\n      return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;\n    }\n  };\n\n  function applicableHelpers(cm, helpers) {\n    if (!cm.somethingSelected()) return helpers\n    var result = []\n    for (var i = 0; i < helpers.length; i++)\n      if (helpers[i].supportsSelection) result.push(helpers[i])\n    return result\n  }\n\n  function fetchHints(hint, cm, options, callback) {\n    if (hint.async) {\n      hint(cm, callback, options)\n    } else {\n      var result = hint(cm, options)\n      if (result && result.then) result.then(callback)\n      else callback(result)\n    }\n  }\n\n  function resolveAutoHints(cm, pos) {\n    var helpers = cm.getHelpers(pos, \"hint\"), words\n    if (helpers.length) {\n      var resolved = function(cm, callback, options) {\n        var app = applicableHelpers(cm, helpers);\n        function run(i) {\n          if (i == app.length) return callback(null)\n          fetchHints(app[i], cm, options, function(result) {\n            if (result && result.list.length > 0) callback(result)\n            else run(i + 1)\n          })\n        }\n        run(0)\n      }\n      resolved.async = true\n      resolved.supportsSelection = true\n      return resolved\n    } else if (words = cm.getHelper(cm.getCursor(), \"hintWords\")) {\n      return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }\n    } else if (CodeMirror.hint.anyword) {\n      return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }\n    } else {\n      return function() {}\n    }\n  }\n\n  CodeMirror.registerHelper(\"hint\", \"auto\", {\n    resolve: resolveAutoHints\n  });\n\n  CodeMirror.registerHelper(\"hint\", \"fromList\", function(cm, options) {\n    var cur = cm.getCursor(), token = cm.getTokenAt(cur)\n    var term, from = CodeMirror.Pos(cur.line, token.start), to = cur\n    if (token.start < cur.ch && /\\w/.test(token.string.charAt(cur.ch - token.start - 1))) {\n      term = token.string.substr(0, cur.ch - token.start)\n    } else {\n      term = \"\"\n      from = cur\n    }\n    var found = [];\n    for (var i = 0; i < options.words.length; i++) {\n      var word = options.words[i];\n      if (word.slice(0, term.length) == term)\n        found.push(word);\n    }\n\n    if (found.length) return {list: found, from: from, to: to};\n  });\n\n  CodeMirror.commands.autocomplete = CodeMirror.showHint;\n\n  var defaultOptions = {\n    hint: CodeMirror.hint.auto,\n    completeSingle: true,\n    alignWithWord: true,\n    closeCharacters: /[\\s()\\[\\]{};:>,]/,\n    closeOnUnfocus: true,\n    completeOnSingleClick: true,\n    container: null,\n    customKeys: null,\n    extraKeys: null\n  };\n\n  CodeMirror.defineOption(\"hintOptions\", null);\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/hint/sql-hint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../../mode/sql/sql\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../../mode/sql/sql\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var tables;\n  var defaultTable;\n  var keywords;\n  var identifierQuote;\n  var CONS = {\n    QUERY_DIV: \";\",\n    ALIAS_KEYWORD: \"AS\"\n  };\n  var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos;\n\n  function isArray(val) { return Object.prototype.toString.call(val) == \"[object Array]\" }\n\n  function getKeywords(editor) {\n    var mode = editor.doc.modeOption;\n    if (mode === \"sql\") mode = \"text/x-sql\";\n    return CodeMirror.resolveMode(mode).keywords;\n  }\n\n  function getIdentifierQuote(editor) {\n    var mode = editor.doc.modeOption;\n    if (mode === \"sql\") mode = \"text/x-sql\";\n    return CodeMirror.resolveMode(mode).identifierQuote || \"`\";\n  }\n\n  function getText(item) {\n    return typeof item == \"string\" ? item : item.text;\n  }\n\n  function wrapTable(name, value) {\n    if (isArray(value)) value = {columns: value}\n    if (!value.text) value.text = name\n    return value\n  }\n\n  function parseTables(input) {\n    var result = {}\n    if (isArray(input)) {\n      for (var i = input.length - 1; i >= 0; i--) {\n        var item = input[i]\n        result[getText(item).toUpperCase()] = wrapTable(getText(item), item)\n      }\n    } else if (input) {\n      for (var name in input)\n        result[name.toUpperCase()] = wrapTable(name, input[name])\n    }\n    return result\n  }\n\n  function getTable(name) {\n    return tables[name.toUpperCase()]\n  }\n\n  function shallowClone(object) {\n    var result = {};\n    for (var key in object) if (object.hasOwnProperty(key))\n      result[key] = object[key];\n    return result;\n  }\n\n  function match(string, word) {\n    var len = string.length;\n    var sub = getText(word).substr(0, len);\n    return string.toUpperCase() === sub.toUpperCase();\n  }\n\n  function addMatches(result, search, wordlist, formatter) {\n    if (isArray(wordlist)) {\n      for (var i = 0; i < wordlist.length; i++)\n        if (match(search, wordlist[i])) result.push(formatter(wordlist[i]))\n    } else {\n      for (var word in wordlist) if (wordlist.hasOwnProperty(word)) {\n        var val = wordlist[word]\n        if (!val || val === true)\n          val = word\n        else\n          val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text\n        if (match(search, val)) result.push(formatter(val))\n      }\n    }\n  }\n\n  function cleanName(name) {\n    // Get rid name from identifierQuote and preceding dot(.)\n    if (name.charAt(0) == \".\") {\n      name = name.substr(1);\n    }\n    // replace doublicated identifierQuotes with single identifierQuotes\n    // and remove single identifierQuotes\n    var nameParts = name.split(identifierQuote+identifierQuote);\n    for (var i = 0; i < nameParts.length; i++)\n      nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote,\"g\"), \"\");\n    return nameParts.join(identifierQuote);\n  }\n\n  function insertIdentifierQuotes(name) {\n    var nameParts = getText(name).split(\".\");\n    for (var i = 0; i < nameParts.length; i++)\n      nameParts[i] = identifierQuote +\n        // doublicate identifierQuotes\n        nameParts[i].replace(new RegExp(identifierQuote,\"g\"), identifierQuote+identifierQuote) +\n        identifierQuote;\n    var escaped = nameParts.join(\".\");\n    if (typeof name == \"string\") return escaped;\n    name = shallowClone(name);\n    name.text = escaped;\n    return name;\n  }\n\n  function nameCompletion(cur, token, result, editor) {\n    // Try to complete table, column names and return start position of completion\n    var useIdentifierQuotes = false;\n    var nameParts = [];\n    var start = token.start;\n    var cont = true;\n    while (cont) {\n      cont = (token.string.charAt(0) == \".\");\n      useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote);\n\n      start = token.start;\n      nameParts.unshift(cleanName(token.string));\n\n      token = editor.getTokenAt(Pos(cur.line, token.start));\n      if (token.string == \".\") {\n        cont = true;\n        token = editor.getTokenAt(Pos(cur.line, token.start));\n      }\n    }\n\n    // Try to complete table names\n    var string = nameParts.join(\".\");\n    addMatches(result, string, tables, function(w) {\n      return useIdentifierQuotes ? insertIdentifierQuotes(w) : w;\n    });\n\n    // Try to complete columns from defaultTable\n    addMatches(result, string, defaultTable, function(w) {\n      return useIdentifierQuotes ? insertIdentifierQuotes(w) : w;\n    });\n\n    // Try to complete columns\n    string = nameParts.pop();\n    var table = nameParts.join(\".\");\n\n    var alias = false;\n    var aliasTable = table;\n    // Check if table is available. If not, find table by Alias\n    if (!getTable(table)) {\n      var oldTable = table;\n      table = findTableByAlias(table, editor);\n      if (table !== oldTable) alias = true;\n    }\n\n    var columns = getTable(table);\n    if (columns && columns.columns)\n      columns = columns.columns;\n\n    if (columns) {\n      addMatches(result, string, columns, function(w) {\n        var tableInsert = table;\n        if (alias == true) tableInsert = aliasTable;\n        if (typeof w == \"string\") {\n          w = tableInsert + \".\" + w;\n        } else {\n          w = shallowClone(w);\n          w.text = tableInsert + \".\" + w.text;\n        }\n        return useIdentifierQuotes ? insertIdentifierQuotes(w) : w;\n      });\n    }\n\n    return start;\n  }\n\n  function eachWord(lineText, f) {\n    var words = lineText.split(/\\s+/)\n    for (var i = 0; i < words.length; i++)\n      if (words[i]) f(words[i].replace(/[,;]/g, ''))\n  }\n\n  function findTableByAlias(alias, editor) {\n    var doc = editor.doc;\n    var fullQuery = doc.getValue();\n    var aliasUpperCase = alias.toUpperCase();\n    var previousWord = \"\";\n    var table = \"\";\n    var separator = [];\n    var validRange = {\n      start: Pos(0, 0),\n      end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length)\n    };\n\n    //add separator\n    var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV);\n    while(indexOfSeparator != -1) {\n      separator.push(doc.posFromIndex(indexOfSeparator));\n      indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1);\n    }\n    separator.unshift(Pos(0, 0));\n    separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));\n\n    //find valid range\n    var prevItem = null;\n    var current = editor.getCursor()\n    for (var i = 0; i < separator.length; i++) {\n      if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) {\n        validRange = {start: prevItem, end: separator[i]};\n        break;\n      }\n      prevItem = separator[i];\n    }\n\n    if (validRange.start) {\n      var query = doc.getRange(validRange.start, validRange.end, false);\n\n      for (var i = 0; i < query.length; i++) {\n        var lineText = query[i];\n        eachWord(lineText, function(word) {\n          var wordUpperCase = word.toUpperCase();\n          if (wordUpperCase === aliasUpperCase && getTable(previousWord))\n            table = previousWord;\n          if (wordUpperCase !== CONS.ALIAS_KEYWORD)\n            previousWord = word;\n        });\n        if (table) break;\n      }\n    }\n    return table;\n  }\n\n  CodeMirror.registerHelper(\"hint\", \"sql\", function(editor, options) {\n    tables = parseTables(options && options.tables)\n    var defaultTableName = options && options.defaultTable;\n    var disableKeywords = options && options.disableKeywords;\n    defaultTable = defaultTableName && getTable(defaultTableName);\n    keywords = getKeywords(editor);\n    identifierQuote = getIdentifierQuote(editor);\n\n    if (defaultTableName && !defaultTable)\n      defaultTable = findTableByAlias(defaultTableName, editor);\n\n    defaultTable = defaultTable || [];\n\n    if (defaultTable.columns)\n      defaultTable = defaultTable.columns;\n\n    var cur = editor.getCursor();\n    var result = [];\n    var token = editor.getTokenAt(cur), start, end, search;\n    if (token.end > cur.ch) {\n      token.end = cur.ch;\n      token.string = token.string.slice(0, cur.ch - token.start);\n    }\n\n    if (token.string.match(/^[.`\"\\w@]\\w*$/)) {\n      search = token.string;\n      start = token.start;\n      end = token.end;\n    } else {\n      start = end = cur.ch;\n      search = \"\";\n    }\n    if (search.charAt(0) == \".\" || search.charAt(0) == identifierQuote) {\n      start = nameCompletion(cur, token, result, editor);\n    } else {\n      addMatches(result, search, defaultTable, function(w) {return {text:w, className: \"CodeMirror-hint-table CodeMirror-hint-default-table\"};});\n      addMatches(\n          result,\n          search,\n          tables,\n          function(w) {\n              if (typeof w === 'object') {\n                  w.className =  \"CodeMirror-hint-table\";\n              } else {\n                  w = {text: w, className: \"CodeMirror-hint-table\"};\n              }\n\n              return w;\n          }\n      );\n      if (!disableKeywords)\n        addMatches(result, search, keywords, function(w) {return {text: w.toUpperCase(), className: \"CodeMirror-hint-keyword\"};});\n    }\n\n    return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/hint/xml-hint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var Pos = CodeMirror.Pos;\n\n  function getHints(cm, options) {\n    var tags = options && options.schemaInfo;\n    var quote = (options && options.quoteChar) || '\"';\n    if (!tags) return;\n    var cur = cm.getCursor(), token = cm.getTokenAt(cur);\n    if (token.end > cur.ch) {\n      token.end = cur.ch;\n      token.string = token.string.slice(0, cur.ch - token.start);\n    }\n    var inner = CodeMirror.innerMode(cm.getMode(), token.state);\n    if (inner.mode.name != \"xml\") return;\n    var result = [], replaceToken = false, prefix;\n    var tag = /\\btag\\b/.test(token.type) && !/>$/.test(token.string);\n    var tagName = tag && /^\\w/.test(token.string), tagStart;\n\n    if (tagName) {\n      var before = cm.getLine(cur.line).slice(Math.max(0, token.start - 2), token.start);\n      var tagType = /<\\/$/.test(before) ? \"close\" : /<$/.test(before) ? \"open\" : null;\n      if (tagType) tagStart = token.start - (tagType == \"close\" ? 2 : 1);\n    } else if (tag && token.string == \"<\") {\n      tagType = \"open\";\n    } else if (tag && token.string == \"</\") {\n      tagType = \"close\";\n    }\n\n    if (!tag && !inner.state.tagName || tagType) {\n      if (tagName)\n        prefix = token.string;\n      replaceToken = tagType;\n      var cx = inner.state.context, curTag = cx && tags[cx.tagName];\n      var childList = cx ? curTag && curTag.children : tags[\"!top\"];\n      if (childList && tagType != \"close\") {\n        for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].lastIndexOf(prefix, 0) == 0)\n          result.push(\"<\" + childList[i]);\n      } else if (tagType != \"close\") {\n        for (var name in tags)\n          if (tags.hasOwnProperty(name) && name != \"!top\" && name != \"!attrs\" && (!prefix || name.lastIndexOf(prefix, 0) == 0))\n            result.push(\"<\" + name);\n      }\n      if (cx && (!prefix || tagType == \"close\" && cx.tagName.lastIndexOf(prefix, 0) == 0))\n        result.push(\"</\" + cx.tagName + \">\");\n    } else {\n      // Attribute completion\n      var curTag = tags[inner.state.tagName], attrs = curTag && curTag.attrs;\n      var globalAttrs = tags[\"!attrs\"];\n      if (!attrs && !globalAttrs) return;\n      if (!attrs) {\n        attrs = globalAttrs;\n      } else if (globalAttrs) { // Combine tag-local and global attributes\n        var set = {};\n        for (var nm in globalAttrs) if (globalAttrs.hasOwnProperty(nm)) set[nm] = globalAttrs[nm];\n        for (var nm in attrs) if (attrs.hasOwnProperty(nm)) set[nm] = attrs[nm];\n        attrs = set;\n      }\n      if (token.type == \"string\" || token.string == \"=\") { // A value\n        var before = cm.getRange(Pos(cur.line, Math.max(0, cur.ch - 60)),\n                                 Pos(cur.line, token.type == \"string\" ? token.start : token.end));\n        var atName = before.match(/([^\\s\\u00a0=<>\\\"\\']+)=$/), atValues;\n        if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return;\n        if (typeof atValues == 'function') atValues = atValues.call(this, cm); // Functions can be used to supply values for autocomplete widget\n        if (token.type == \"string\") {\n          prefix = token.string;\n          var n = 0;\n          if (/['\"]/.test(token.string.charAt(0))) {\n            quote = token.string.charAt(0);\n            prefix = token.string.slice(1);\n            n++;\n          }\n          var len = token.string.length;\n          if (/['\"]/.test(token.string.charAt(len - 1))) {\n            quote = token.string.charAt(len - 1);\n            prefix = token.string.substr(n, len - 2);\n          }\n          replaceToken = true;\n        }\n        for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].lastIndexOf(prefix, 0) == 0)\n          result.push(quote + atValues[i] + quote);\n      } else { // An attribute name\n        if (token.type == \"attribute\") {\n          prefix = token.string;\n          replaceToken = true;\n        }\n        for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.lastIndexOf(prefix, 0) == 0))\n          result.push(attr);\n      }\n    }\n    return {\n      list: result,\n      from: replaceToken ? Pos(cur.line, tagStart == null ? token.start : tagStart) : cur,\n      to: replaceToken ? Pos(cur.line, token.end) : cur\n    };\n  }\n\n  CodeMirror.registerHelper(\"hint\", \"xml\", getHints);\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/lint/coffeescript-lint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Depends on coffeelint.js from http://www.coffeelint.org/js/coffeelint.js\n\n// declare global: coffeelint\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.registerHelper(\"lint\", \"coffeescript\", function(text) {\n  var found = [];\n  if (!window.coffeelint) {\n    if (window.console) {\n      window.console.error(\"Error: window.coffeelint not defined, CodeMirror CoffeeScript linting cannot run.\");\n    }\n    return found;\n  }\n  var parseError = function(err) {\n    var loc = err.lineNumber;\n    found.push({from: CodeMirror.Pos(loc-1, 0),\n                to: CodeMirror.Pos(loc, 0),\n                severity: err.level,\n                message: err.message});\n  };\n  try {\n    var res = coffeelint.lint(text);\n    for(var i = 0; i < res.length; i++) {\n      parseError(res[i]);\n    }\n  } catch(e) {\n    found.push({from: CodeMirror.Pos(e.location.first_line, 0),\n                to: CodeMirror.Pos(e.location.last_line, e.location.last_column),\n                severity: 'error',\n                message: e.message});\n  }\n  return found;\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/lint/css-lint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Depends on csslint.js from https://github.com/stubbornella/csslint\n\n// declare global: CSSLint\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.registerHelper(\"lint\", \"css\", function(text, options) {\n  var found = [];\n  if (!window.CSSLint) {\n    if (window.console) {\n        window.console.error(\"Error: window.CSSLint not defined, CodeMirror CSS linting cannot run.\");\n    }\n    return found;\n  }\n  var results = CSSLint.verify(text, options), messages = results.messages, message = null;\n  for ( var i = 0; i < messages.length; i++) {\n    message = messages[i];\n    var startLine = message.line -1, endLine = message.line -1, startCol = message.col -1, endCol = message.col;\n    found.push({\n      from: CodeMirror.Pos(startLine, startCol),\n      to: CodeMirror.Pos(endLine, endCol),\n      message: message.message,\n      severity : message.type\n    });\n  }\n  return found;\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/lint/html-lint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Depends on htmlhint.js from http://htmlhint.com/js/htmlhint.js\n\n// declare global: HTMLHint\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"htmlhint\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"htmlhint\"], mod);\n  else // Plain browser env\n    mod(CodeMirror, window.HTMLHint);\n})(function(CodeMirror, HTMLHint) {\n  \"use strict\";\n\n  var defaultRules = {\n    \"tagname-lowercase\": true,\n    \"attr-lowercase\": true,\n    \"attr-value-double-quotes\": true,\n    \"doctype-first\": false,\n    \"tag-pair\": true,\n    \"spec-char-escape\": true,\n    \"id-unique\": true,\n    \"src-not-empty\": true,\n    \"attr-no-duplication\": true\n  };\n\n  CodeMirror.registerHelper(\"lint\", \"html\", function(text, options) {\n    var found = [];\n    if (HTMLHint && !HTMLHint.verify) HTMLHint = HTMLHint.HTMLHint;\n    if (!HTMLHint) HTMLHint = window.HTMLHint;\n    if (!HTMLHint) {\n      if (window.console) {\n          window.console.error(\"Error: HTMLHint not found, not defined on window, or not available through define/require, CodeMirror HTML linting cannot run.\");\n      }\n      return found;\n    }\n    var messages = HTMLHint.verify(text, options && options.rules || defaultRules);\n    for (var i = 0; i < messages.length; i++) {\n      var message = messages[i];\n      var startLine = message.line - 1, endLine = message.line - 1, startCol = message.col - 1, endCol = message.col;\n      found.push({\n        from: CodeMirror.Pos(startLine, startCol),\n        to: CodeMirror.Pos(endLine, endCol),\n        message: message.message,\n        severity : message.type\n      });\n    }\n    return found;\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/lint/javascript-lint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n  // declare global: JSHINT\n\n  function validator(text, options) {\n    if (!window.JSHINT) {\n      if (window.console) {\n        window.console.error(\"Error: window.JSHINT not defined, CodeMirror JavaScript linting cannot run.\");\n      }\n      return [];\n    }\n    if (!options.indent) // JSHint error.character actually is a column index, this fixes underlining on lines using tabs for indentation\n      options.indent = 1; // JSHint default value is 4\n    JSHINT(text, options, options.globals);\n    var errors = JSHINT.data().errors, result = [];\n    if (errors) parseErrors(errors, result);\n    return result;\n  }\n\n  CodeMirror.registerHelper(\"lint\", \"javascript\", validator);\n\n  function parseErrors(errors, output) {\n    for ( var i = 0; i < errors.length; i++) {\n      var error = errors[i];\n      if (error) {\n        if (error.line <= 0) {\n          if (window.console) {\n            window.console.warn(\"Cannot display JSHint error (invalid line \" + error.line + \")\", error);\n          }\n          continue;\n        }\n\n        var start = error.character - 1, end = start + 1;\n        if (error.evidence) {\n          var index = error.evidence.substring(start).search(/.\\b/);\n          if (index > -1) {\n            end += index;\n          }\n        }\n\n        // Convert to format expected by validation service\n        var hint = {\n          message: error.reason,\n          severity: error.code ? (error.code.startsWith('W') ? \"warning\" : \"error\") : \"error\",\n          from: CodeMirror.Pos(error.line - 1, start),\n          to: CodeMirror.Pos(error.line - 1, end)\n        };\n\n        output.push(hint);\n      }\n    }\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/lint/json-lint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Depends on jsonlint.js from https://github.com/zaach/jsonlint\n\n// declare global: jsonlint\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.registerHelper(\"lint\", \"json\", function(text) {\n  var found = [];\n  if (!window.jsonlint) {\n    if (window.console) {\n      window.console.error(\"Error: window.jsonlint not defined, CodeMirror JSON linting cannot run.\");\n    }\n    return found;\n  }\n  // for jsonlint's web dist jsonlint is exported as an object with a single property parser, of which parseError\n  // is a subproperty\n  var jsonlint = window.jsonlint.parser || window.jsonlint\n  jsonlint.parseError = function(str, hash) {\n    var loc = hash.loc;\n    found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column),\n                to: CodeMirror.Pos(loc.last_line - 1, loc.last_column),\n                message: str});\n  };\n  try { jsonlint.parse(text); }\n  catch(e) {}\n  return found;\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/lint/lint.css",
    "content": "/* The lint marker gutter */\n.CodeMirror-lint-markers {\n  width: 16px;\n}\n\n.CodeMirror-lint-tooltip {\n  background-color: #ffd;\n  border: 1px solid black;\n  border-radius: 4px 4px 4px 4px;\n  color: black;\n  font-family: monospace;\n  font-size: 10pt;\n  overflow: hidden;\n  padding: 2px 5px;\n  position: fixed;\n  white-space: pre;\n  white-space: pre-wrap;\n  z-index: 100;\n  max-width: 600px;\n  opacity: 0;\n  transition: opacity .4s;\n  -moz-transition: opacity .4s;\n  -webkit-transition: opacity .4s;\n  -o-transition: opacity .4s;\n  -ms-transition: opacity .4s;\n}\n\n.CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning {\n  background-position: left bottom;\n  background-repeat: repeat-x;\n}\n\n.CodeMirror-lint-mark-error {\n  background-image:\n  url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==\")\n  ;\n}\n\n.CodeMirror-lint-mark-warning {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII=\");\n}\n\n.CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning {\n  background-position: center center;\n  background-repeat: no-repeat;\n  cursor: pointer;\n  display: inline-block;\n  height: 16px;\n  width: 16px;\n  vertical-align: middle;\n  position: relative;\n}\n\n.CodeMirror-lint-message-error, .CodeMirror-lint-message-warning {\n  padding-left: 18px;\n  background-position: top left;\n  background-repeat: no-repeat;\n}\n\n.CodeMirror-lint-marker-error, .CodeMirror-lint-message-error {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII=\");\n}\n\n.CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII=\");\n}\n\n.CodeMirror-lint-marker-multiple {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC\");\n  background-repeat: no-repeat;\n  background-position: right bottom;\n  width: 100%; height: 100%;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/addon/lint/lint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n  var GUTTER_ID = \"CodeMirror-lint-markers\";\n\n  function showTooltip(e, content) {\n    var tt = document.createElement(\"div\");\n    tt.className = \"CodeMirror-lint-tooltip\";\n    tt.appendChild(content.cloneNode(true));\n    document.body.appendChild(tt);\n\n    function position(e) {\n      if (!tt.parentNode) return CodeMirror.off(document, \"mousemove\", position);\n      tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + \"px\";\n      tt.style.left = (e.clientX + 5) + \"px\";\n    }\n    CodeMirror.on(document, \"mousemove\", position);\n    position(e);\n    if (tt.style.opacity != null) tt.style.opacity = 1;\n    return tt;\n  }\n  function rm(elt) {\n    if (elt.parentNode) elt.parentNode.removeChild(elt);\n  }\n  function hideTooltip(tt) {\n    if (!tt.parentNode) return;\n    if (tt.style.opacity == null) rm(tt);\n    tt.style.opacity = 0;\n    setTimeout(function() { rm(tt); }, 600);\n  }\n\n  function showTooltipFor(e, content, node) {\n    var tooltip = showTooltip(e, content);\n    function hide() {\n      CodeMirror.off(node, \"mouseout\", hide);\n      if (tooltip) { hideTooltip(tooltip); tooltip = null; }\n    }\n    var poll = setInterval(function() {\n      if (tooltip) for (var n = node;; n = n.parentNode) {\n        if (n && n.nodeType == 11) n = n.host;\n        if (n == document.body) return;\n        if (!n) { hide(); break; }\n      }\n      if (!tooltip) return clearInterval(poll);\n    }, 400);\n    CodeMirror.on(node, \"mouseout\", hide);\n  }\n\n  function LintState(cm, options, hasGutter) {\n    this.marked = [];\n    this.options = options;\n    this.timeout = null;\n    this.hasGutter = hasGutter;\n    this.onMouseOver = function(e) { onMouseOver(cm, e); };\n    this.waitingFor = 0\n  }\n\n  function parseOptions(_cm, options) {\n    if (options instanceof Function) return {getAnnotations: options};\n    if (!options || options === true) options = {};\n    return options;\n  }\n\n  function clearMarks(cm) {\n    var state = cm.state.lint;\n    if (state.hasGutter) cm.clearGutter(GUTTER_ID);\n    for (var i = 0; i < state.marked.length; ++i)\n      state.marked[i].clear();\n    state.marked.length = 0;\n  }\n\n  function makeMarker(labels, severity, multiple, tooltips) {\n    var marker = document.createElement(\"div\"), inner = marker;\n    marker.className = \"CodeMirror-lint-marker-\" + severity;\n    if (multiple) {\n      inner = marker.appendChild(document.createElement(\"div\"));\n      inner.className = \"CodeMirror-lint-marker-multiple\";\n    }\n\n    if (tooltips != false) CodeMirror.on(inner, \"mouseover\", function(e) {\n      showTooltipFor(e, labels, inner);\n    });\n\n    return marker;\n  }\n\n  function getMaxSeverity(a, b) {\n    if (a == \"error\") return a;\n    else return b;\n  }\n\n  function groupByLine(annotations) {\n    var lines = [];\n    for (var i = 0; i < annotations.length; ++i) {\n      var ann = annotations[i], line = ann.from.line;\n      (lines[line] || (lines[line] = [])).push(ann);\n    }\n    return lines;\n  }\n\n  function annotationTooltip(ann) {\n    var severity = ann.severity;\n    if (!severity) severity = \"error\";\n    var tip = document.createElement(\"div\");\n    tip.className = \"CodeMirror-lint-message-\" + severity;\n    if (typeof ann.messageHTML != 'undefined') {\n        tip.innerHTML = ann.messageHTML;\n    } else {\n        tip.appendChild(document.createTextNode(ann.message));\n    }\n    return tip;\n  }\n\n  function lintAsync(cm, getAnnotations, passOptions) {\n    var state = cm.state.lint\n    var id = ++state.waitingFor\n    function abort() {\n      id = -1\n      cm.off(\"change\", abort)\n    }\n    cm.on(\"change\", abort)\n    getAnnotations(cm.getValue(), function(annotations, arg2) {\n      cm.off(\"change\", abort)\n      if (state.waitingFor != id) return\n      if (arg2 && annotations instanceof CodeMirror) annotations = arg2\n      cm.operation(function() {updateLinting(cm, annotations)})\n    }, passOptions, cm);\n  }\n\n  function startLinting(cm) {\n    var state = cm.state.lint, options = state.options;\n    /*\n     * Passing rules in `options` property prevents JSHint (and other linters) from complaining\n     * about unrecognized rules like `onUpdateLinting`, `delay`, `lintOnChange`, etc.\n     */\n    var passOptions = options.options || options;\n    var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), \"lint\");\n    if (!getAnnotations) return;\n    if (options.async || getAnnotations.async) {\n      lintAsync(cm, getAnnotations, passOptions)\n    } else {\n      var annotations = getAnnotations(cm.getValue(), passOptions, cm);\n      if (!annotations) return;\n      if (annotations.then) annotations.then(function(issues) {\n        cm.operation(function() {updateLinting(cm, issues)})\n      });\n      else cm.operation(function() {updateLinting(cm, annotations)})\n    }\n  }\n\n  function updateLinting(cm, annotationsNotSorted) {\n    clearMarks(cm);\n    var state = cm.state.lint, options = state.options;\n\n    var annotations = groupByLine(annotationsNotSorted);\n\n    for (var line = 0; line < annotations.length; ++line) {\n      var anns = annotations[line];\n      if (!anns) continue;\n\n      var maxSeverity = null;\n      var tipLabel = state.hasGutter && document.createDocumentFragment();\n\n      for (var i = 0; i < anns.length; ++i) {\n        var ann = anns[i];\n        var severity = ann.severity;\n        if (!severity) severity = \"error\";\n        maxSeverity = getMaxSeverity(maxSeverity, severity);\n\n        if (options.formatAnnotation) ann = options.formatAnnotation(ann);\n        if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));\n\n        if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {\n          className: \"CodeMirror-lint-mark-\" + severity,\n          __annotation: ann\n        }));\n      }\n\n      if (state.hasGutter)\n        cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,\n                                                       state.options.tooltips));\n    }\n    if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);\n  }\n\n  function onChange(cm) {\n    var state = cm.state.lint;\n    if (!state) return;\n    clearTimeout(state.timeout);\n    state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);\n  }\n\n  function popupTooltips(annotations, e) {\n    var target = e.target || e.srcElement;\n    var tooltip = document.createDocumentFragment();\n    for (var i = 0; i < annotations.length; i++) {\n      var ann = annotations[i];\n      tooltip.appendChild(annotationTooltip(ann));\n    }\n    showTooltipFor(e, tooltip, target);\n  }\n\n  function onMouseOver(cm, e) {\n    var target = e.target || e.srcElement;\n    if (!/\\bCodeMirror-lint-mark-/.test(target.className)) return;\n    var box = target.getBoundingClientRect(), x = (box.left + box.right) / 2, y = (box.top + box.bottom) / 2;\n    var spans = cm.findMarksAt(cm.coordsChar({left: x, top: y}, \"client\"));\n\n    var annotations = [];\n    for (var i = 0; i < spans.length; ++i) {\n      var ann = spans[i].__annotation;\n      if (ann) annotations.push(ann);\n    }\n    if (annotations.length) popupTooltips(annotations, e);\n  }\n\n  CodeMirror.defineOption(\"lint\", false, function(cm, val, old) {\n    if (old && old != CodeMirror.Init) {\n      clearMarks(cm);\n      if (cm.state.lint.options.lintOnChange !== false)\n        cm.off(\"change\", onChange);\n      CodeMirror.off(cm.getWrapperElement(), \"mouseover\", cm.state.lint.onMouseOver);\n      clearTimeout(cm.state.lint.timeout);\n      delete cm.state.lint;\n    }\n\n    if (val) {\n      var gutters = cm.getOption(\"gutters\"), hasLintGutter = false;\n      for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;\n      var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);\n      if (state.options.lintOnChange !== false)\n        cm.on(\"change\", onChange);\n      if (state.options.tooltips != false && state.options.tooltips != \"gutter\")\n        CodeMirror.on(cm.getWrapperElement(), \"mouseover\", state.onMouseOver);\n\n      startLinting(cm);\n    }\n  });\n\n  CodeMirror.defineExtension(\"performLint\", function() {\n    if (this.state.lint) startLinting(this);\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/lint/yaml-lint.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\n// Depends on js-yaml.js from https://github.com/nodeca/js-yaml\n\n// declare global: jsyaml\n\nCodeMirror.registerHelper(\"lint\", \"yaml\", function(text) {\n  var found = [];\n  if (!window.jsyaml) {\n    if (window.console) {\n      window.console.error(\"Error: window.jsyaml not defined, CodeMirror YAML linting cannot run.\");\n    }\n    return found;\n  }\n  try { jsyaml.loadAll(text); }\n  catch(e) {\n      var loc = e.mark,\n          // js-yaml YAMLException doesn't always provide an accurate lineno\n          // e.g., when there are multiple yaml docs\n          // ---\n          // ---\n          // foo:bar\n          from = loc ? CodeMirror.Pos(loc.line, loc.column) : CodeMirror.Pos(0, 0),\n          to = from;\n      found.push({ from: from, to: to, message: e.message });\n  }\n  return found;\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/merge/merge.css",
    "content": ".CodeMirror-merge {\n  position: relative;\n  border: 1px solid #ddd;\n  white-space: pre;\n}\n\n.CodeMirror-merge, .CodeMirror-merge .CodeMirror {\n  height: 350px;\n}\n\n.CodeMirror-merge-2pane .CodeMirror-merge-pane { width: 47%; }\n.CodeMirror-merge-2pane .CodeMirror-merge-gap { width: 6%; }\n.CodeMirror-merge-3pane .CodeMirror-merge-pane { width: 31%; }\n.CodeMirror-merge-3pane .CodeMirror-merge-gap { width: 3.5%; }\n\n.CodeMirror-merge-pane {\n  display: inline-block;\n  white-space: normal;\n  vertical-align: top;\n}\n.CodeMirror-merge-pane-rightmost {\n  position: absolute;\n  right: 0px;\n  z-index: 1;\n}\n\n.CodeMirror-merge-gap {\n  z-index: 2;\n  display: inline-block;\n  height: 100%;\n  -moz-box-sizing: border-box;\n  box-sizing: border-box;\n  overflow: hidden;\n  border-left: 1px solid #ddd;\n  border-right: 1px solid #ddd;\n  position: relative;\n  background: #f8f8f8;\n}\n\n.CodeMirror-merge-scrolllock-wrap {\n  position: absolute;\n  bottom: 0; left: 50%;\n}\n.CodeMirror-merge-scrolllock {\n  position: relative;\n  left: -50%;\n  cursor: pointer;\n  color: #555;\n  line-height: 1;\n}\n.CodeMirror-merge-scrolllock:after {\n  content: \"\\21db\\00a0\\00a0\\21da\";\n}\n.CodeMirror-merge-scrolllock.CodeMirror-merge-scrolllock-enabled:after {\n  content: \"\\21db\\21da\";\n}\n\n.CodeMirror-merge-copybuttons-left, .CodeMirror-merge-copybuttons-right {\n  position: absolute;\n  left: 0; top: 0;\n  right: 0; bottom: 0;\n  line-height: 1;\n}\n\n.CodeMirror-merge-copy {\n  position: absolute;\n  cursor: pointer;\n  color: #44c;\n  z-index: 3;\n}\n\n.CodeMirror-merge-copy-reverse {\n  position: absolute;\n  cursor: pointer;\n  color: #44c;\n}\n\n.CodeMirror-merge-copybuttons-left .CodeMirror-merge-copy { left: 2px; }\n.CodeMirror-merge-copybuttons-right .CodeMirror-merge-copy { right: 2px; }\n\n.CodeMirror-merge-r-inserted, .CodeMirror-merge-l-inserted {\n  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12MwuCXy3+CWyH8GBgYGJgYkAABZbAQ9ELXurwAAAABJRU5ErkJggg==);\n  background-position: bottom left;\n  background-repeat: repeat-x;\n}\n\n.CodeMirror-merge-r-deleted, .CodeMirror-merge-l-deleted {\n  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12M4Kyb2/6yY2H8GBgYGJgYkAABURgPz6Ks7wQAAAABJRU5ErkJggg==);\n  background-position: bottom left;\n  background-repeat: repeat-x;\n}\n\n.CodeMirror-merge-r-chunk { background: #ffffe0; }\n.CodeMirror-merge-r-chunk-start { border-top: 1px solid #ee8; }\n.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #ee8; }\n.CodeMirror-merge-r-connect { fill: #ffffe0; stroke: #ee8; stroke-width: 1px; }\n\n.CodeMirror-merge-l-chunk { background: #eef; }\n.CodeMirror-merge-l-chunk-start { border-top: 1px solid #88e; }\n.CodeMirror-merge-l-chunk-end { border-bottom: 1px solid #88e; }\n.CodeMirror-merge-l-connect { fill: #eef; stroke: #88e; stroke-width: 1px; }\n\n.CodeMirror-merge-l-chunk.CodeMirror-merge-r-chunk { background: #dfd; }\n.CodeMirror-merge-l-chunk-start.CodeMirror-merge-r-chunk-start { border-top: 1px solid #4e4; }\n.CodeMirror-merge-l-chunk-end.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #4e4; }\n\n.CodeMirror-merge-collapsed-widget:before {\n  content: \"(...)\";\n}\n.CodeMirror-merge-collapsed-widget {\n  cursor: pointer;\n  color: #88b;\n  background: #eef;\n  border: 1px solid #ddf;\n  font-size: 90%;\n  padding: 0 3px;\n  border-radius: 4px;\n}\n.CodeMirror-merge-collapsed-line .CodeMirror-gutter-elt { display: none; }\n"
  },
  {
    "path": "third_party/CodeMirror/addon/merge/merge.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// declare global: diff_match_patch, DIFF_INSERT, DIFF_DELETE, DIFF_EQUAL\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\")); // Note non-packaged dependency diff_match_patch\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"diff_match_patch\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n  var Pos = CodeMirror.Pos;\n  var svgNS = \"http://www.w3.org/2000/svg\";\n\n  function DiffView(mv, type) {\n    this.mv = mv;\n    this.type = type;\n    this.classes = type == \"left\"\n      ? {chunk: \"CodeMirror-merge-l-chunk\",\n         start: \"CodeMirror-merge-l-chunk-start\",\n         end: \"CodeMirror-merge-l-chunk-end\",\n         insert: \"CodeMirror-merge-l-inserted\",\n         del: \"CodeMirror-merge-l-deleted\",\n         connect: \"CodeMirror-merge-l-connect\"}\n      : {chunk: \"CodeMirror-merge-r-chunk\",\n         start: \"CodeMirror-merge-r-chunk-start\",\n         end: \"CodeMirror-merge-r-chunk-end\",\n         insert: \"CodeMirror-merge-r-inserted\",\n         del: \"CodeMirror-merge-r-deleted\",\n         connect: \"CodeMirror-merge-r-connect\"};\n  }\n\n  DiffView.prototype = {\n    constructor: DiffView,\n    init: function(pane, orig, options) {\n      this.edit = this.mv.edit;\n      ;(this.edit.state.diffViews || (this.edit.state.diffViews = [])).push(this);\n      this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: !this.mv.options.allowEditingOriginals}, copyObj(options)));\n      if (this.mv.options.connect == \"align\") {\n        if (!this.edit.state.trackAlignable) this.edit.state.trackAlignable = new TrackAlignable(this.edit)\n        this.orig.state.trackAlignable = new TrackAlignable(this.orig)\n      }\n      this.lockButton.title = this.edit.phrase(\"Toggle locked scrolling\");\n\n      this.orig.state.diffViews = [this];\n      var classLocation = options.chunkClassLocation || \"background\";\n      if (Object.prototype.toString.call(classLocation) != \"[object Array]\") classLocation = [classLocation]\n      this.classes.classLocation = classLocation\n\n      this.diff = getDiff(asString(orig), asString(options.value), this.mv.options.ignoreWhitespace);\n      this.chunks = getChunks(this.diff);\n      this.diffOutOfDate = this.dealigned = false;\n      this.needsScrollSync = null\n\n      this.showDifferences = options.showDifferences !== false;\n    },\n    registerEvents: function(otherDv) {\n      this.forceUpdate = registerUpdate(this);\n      setScrollLock(this, true, false);\n      registerScroll(this, otherDv);\n    },\n    setShowDifferences: function(val) {\n      val = val !== false;\n      if (val != this.showDifferences) {\n        this.showDifferences = val;\n        this.forceUpdate(\"full\");\n      }\n    }\n  };\n\n  function ensureDiff(dv) {\n    if (dv.diffOutOfDate) {\n      dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue(), dv.mv.options.ignoreWhitespace);\n      dv.chunks = getChunks(dv.diff);\n      dv.diffOutOfDate = false;\n      CodeMirror.signal(dv.edit, \"updateDiff\", dv.diff);\n    }\n  }\n\n  var updating = false;\n  function registerUpdate(dv) {\n    var edit = {from: 0, to: 0, marked: []};\n    var orig = {from: 0, to: 0, marked: []};\n    var debounceChange, updatingFast = false;\n    function update(mode) {\n      updating = true;\n      updatingFast = false;\n      if (mode == \"full\") {\n        if (dv.svg) clear(dv.svg);\n        if (dv.copyButtons) clear(dv.copyButtons);\n        clearMarks(dv.edit, edit.marked, dv.classes);\n        clearMarks(dv.orig, orig.marked, dv.classes);\n        edit.from = edit.to = orig.from = orig.to = 0;\n      }\n      ensureDiff(dv);\n      if (dv.showDifferences) {\n        updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);\n        updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);\n      }\n\n      if (dv.mv.options.connect == \"align\")\n        alignChunks(dv);\n      makeConnections(dv);\n      if (dv.needsScrollSync != null) syncScroll(dv, dv.needsScrollSync)\n\n      updating = false;\n    }\n    function setDealign(fast) {\n      if (updating) return;\n      dv.dealigned = true;\n      set(fast);\n    }\n    function set(fast) {\n      if (updating || updatingFast) return;\n      clearTimeout(debounceChange);\n      if (fast === true) updatingFast = true;\n      debounceChange = setTimeout(update, fast === true ? 20 : 250);\n    }\n    function change(_cm, change) {\n      if (!dv.diffOutOfDate) {\n        dv.diffOutOfDate = true;\n        edit.from = edit.to = orig.from = orig.to = 0;\n      }\n      // Update faster when a line was added/removed\n      setDealign(change.text.length - 1 != change.to.line - change.from.line);\n    }\n    function swapDoc() {\n      dv.diffOutOfDate = true;\n      dv.dealigned = true;\n      update(\"full\");\n    }\n    dv.edit.on(\"change\", change);\n    dv.orig.on(\"change\", change);\n    dv.edit.on(\"swapDoc\", swapDoc);\n    dv.orig.on(\"swapDoc\", swapDoc);\n    if (dv.mv.options.connect == \"align\") {\n      CodeMirror.on(dv.edit.state.trackAlignable, \"realign\", setDealign)\n      CodeMirror.on(dv.orig.state.trackAlignable, \"realign\", setDealign)\n    }\n    dv.edit.on(\"viewportChange\", function() { set(false); });\n    dv.orig.on(\"viewportChange\", function() { set(false); });\n    update();\n    return update;\n  }\n\n  function registerScroll(dv, otherDv) {\n    dv.edit.on(\"scroll\", function() {\n      syncScroll(dv, true) && makeConnections(dv);\n    });\n    dv.orig.on(\"scroll\", function() {\n      syncScroll(dv, false) && makeConnections(dv);\n      if (otherDv) syncScroll(otherDv, true) && makeConnections(otherDv);\n    });\n  }\n\n  function syncScroll(dv, toOrig) {\n    // Change handler will do a refresh after a timeout when diff is out of date\n    if (dv.diffOutOfDate) {\n      if (dv.lockScroll && dv.needsScrollSync == null) dv.needsScrollSync = toOrig\n      return false\n    }\n    dv.needsScrollSync = null\n    if (!dv.lockScroll) return true;\n    var editor, other, now = +new Date;\n    if (toOrig) { editor = dv.edit; other = dv.orig; }\n    else { editor = dv.orig; other = dv.edit; }\n    // Don't take action if the position of this editor was recently set\n    // (to prevent feedback loops)\n    if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 250 > now) return false;\n\n    var sInfo = editor.getScrollInfo();\n    if (dv.mv.options.connect == \"align\") {\n      targetPos = sInfo.top;\n    } else {\n      var halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;\n      var mid = editor.lineAtHeight(midY, \"local\");\n      var around = chunkBoundariesAround(dv.chunks, mid, toOrig);\n      var off = getOffsets(editor, toOrig ? around.edit : around.orig);\n      var offOther = getOffsets(other, toOrig ? around.orig : around.edit);\n      var ratio = (midY - off.top) / (off.bot - off.top);\n      var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);\n\n      var botDist, mix;\n      // Some careful tweaking to make sure no space is left out of view\n      // when scrolling to top or bottom.\n      if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {\n        targetPos = targetPos * mix + sInfo.top * (1 - mix);\n      } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {\n        var otherInfo = other.getScrollInfo();\n        var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;\n        if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)\n          targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);\n      }\n    }\n\n    other.scrollTo(sInfo.left, targetPos);\n    other.state.scrollSetAt = now;\n    other.state.scrollSetBy = dv;\n    return true;\n  }\n\n  function getOffsets(editor, around) {\n    var bot = around.after;\n    if (bot == null) bot = editor.lastLine() + 1;\n    return {top: editor.heightAtLine(around.before || 0, \"local\"),\n            bot: editor.heightAtLine(bot, \"local\")};\n  }\n\n  function setScrollLock(dv, val, action) {\n    dv.lockScroll = val;\n    if (val && action != false) syncScroll(dv, DIFF_INSERT) && makeConnections(dv);\n    (val ? CodeMirror.addClass : CodeMirror.rmClass)(dv.lockButton, \"CodeMirror-merge-scrolllock-enabled\");\n  }\n\n  // Updating the marks for editor content\n\n  function removeClass(editor, line, classes) {\n    var locs = classes.classLocation\n    for (var i = 0; i < locs.length; i++) {\n      editor.removeLineClass(line, locs[i], classes.chunk);\n      editor.removeLineClass(line, locs[i], classes.start);\n      editor.removeLineClass(line, locs[i], classes.end);\n    }\n  }\n\n  function clearMarks(editor, arr, classes) {\n    for (var i = 0; i < arr.length; ++i) {\n      var mark = arr[i];\n      if (mark instanceof CodeMirror.TextMarker)\n        mark.clear();\n      else if (mark.parent)\n        removeClass(editor, mark, classes);\n    }\n    arr.length = 0;\n  }\n\n  // FIXME maybe add a margin around viewport to prevent too many updates\n  function updateMarks(editor, diff, state, type, classes) {\n    var vp = editor.getViewport();\n    editor.operation(function() {\n      if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {\n        clearMarks(editor, state.marked, classes);\n        markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);\n        state.from = vp.from; state.to = vp.to;\n      } else {\n        if (vp.from < state.from) {\n          markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);\n          state.from = vp.from;\n        }\n        if (vp.to > state.to) {\n          markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);\n          state.to = vp.to;\n        }\n      }\n    });\n  }\n\n  function addClass(editor, lineNr, classes, main, start, end) {\n    var locs = classes.classLocation, line = editor.getLineHandle(lineNr);\n    for (var i = 0; i < locs.length; i++) {\n      if (main) editor.addLineClass(line, locs[i], classes.chunk);\n      if (start) editor.addLineClass(line, locs[i], classes.start);\n      if (end) editor.addLineClass(line, locs[i], classes.end);\n    }\n    return line;\n  }\n\n  function markChanges(editor, diff, type, marks, from, to, classes) {\n    var pos = Pos(0, 0);\n    var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));\n    var cls = type == DIFF_DELETE ? classes.del : classes.insert;\n    function markChunk(start, end) {\n      var bfrom = Math.max(from, start), bto = Math.min(to, end);\n      for (var i = bfrom; i < bto; ++i)\n        marks.push(addClass(editor, i, classes, true, i == start, i == end - 1));\n      // When the chunk is empty, make sure a horizontal line shows up\n      if (start == end && bfrom == end && bto == end) {\n        if (bfrom)\n          marks.push(addClass(editor, bfrom - 1, classes, false, false, true));\n        else\n          marks.push(addClass(editor, bfrom, classes, false, true, false));\n      }\n    }\n\n    var chunkStart = 0, pending = false;\n    for (var i = 0; i < diff.length; ++i) {\n      var part = diff[i], tp = part[0], str = part[1];\n      if (tp == DIFF_EQUAL) {\n        var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);\n        moveOver(pos, str);\n        var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);\n        if (cleanTo > cleanFrom) {\n          if (pending) { markChunk(chunkStart, cleanFrom); pending = false }\n          chunkStart = cleanTo;\n        }\n      } else {\n        pending = true\n        if (tp == type) {\n          var end = moveOver(pos, str, true);\n          var a = posMax(top, pos), b = posMin(bot, end);\n          if (!posEq(a, b))\n            marks.push(editor.markText(a, b, {className: cls}));\n          pos = end;\n        }\n      }\n    }\n    if (pending) markChunk(chunkStart, pos.line + 1);\n  }\n\n  // Updating the gap between editor and original\n\n  function makeConnections(dv) {\n    if (!dv.showDifferences) return;\n\n    if (dv.svg) {\n      clear(dv.svg);\n      var w = dv.gap.offsetWidth;\n      attrs(dv.svg, \"width\", w, \"height\", dv.gap.offsetHeight);\n    }\n    if (dv.copyButtons) clear(dv.copyButtons);\n\n    var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();\n    var outerTop = dv.mv.wrap.getBoundingClientRect().top\n    var sTopEdit = outerTop - dv.edit.getScrollerElement().getBoundingClientRect().top + dv.edit.getScrollInfo().top\n    var sTopOrig = outerTop - dv.orig.getScrollerElement().getBoundingClientRect().top + dv.orig.getScrollInfo().top;\n    for (var i = 0; i < dv.chunks.length; i++) {\n      var ch = dv.chunks[i];\n      if (ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from &&\n          ch.origFrom <= vpOrig.to && ch.origTo >= vpOrig.from)\n        drawConnectorsForChunk(dv, ch, sTopOrig, sTopEdit, w);\n    }\n  }\n\n  function getMatchingOrigLine(editLine, chunks) {\n    var editStart = 0, origStart = 0;\n    for (var i = 0; i < chunks.length; i++) {\n      var chunk = chunks[i];\n      if (chunk.editTo > editLine && chunk.editFrom <= editLine) return null;\n      if (chunk.editFrom > editLine) break;\n      editStart = chunk.editTo;\n      origStart = chunk.origTo;\n    }\n    return origStart + (editLine - editStart);\n  }\n\n  // Combines information about chunks and widgets/markers to return\n  // an array of lines, in a single editor, that probably need to be\n  // aligned with their counterparts in the editor next to it.\n  function alignableFor(cm, chunks, isOrig) {\n    var tracker = cm.state.trackAlignable\n    var start = cm.firstLine(), trackI = 0\n    var result = []\n    for (var i = 0;; i++) {\n      var chunk = chunks[i]\n      var chunkStart = !chunk ? 1e9 : isOrig ? chunk.origFrom : chunk.editFrom\n      for (; trackI < tracker.alignable.length; trackI += 2) {\n        var n = tracker.alignable[trackI] + 1\n        if (n <= start) continue\n        if (n <= chunkStart) result.push(n)\n        else break\n      }\n      if (!chunk) break\n      result.push(start = isOrig ? chunk.origTo : chunk.editTo)\n    }\n    return result\n  }\n\n  // Given information about alignable lines in two editors, fill in\n  // the result (an array of three-element arrays) to reflect the\n  // lines that need to be aligned with each other.\n  function mergeAlignable(result, origAlignable, chunks, setIndex) {\n    var rI = 0, origI = 0, chunkI = 0, diff = 0\n    outer: for (;; rI++) {\n      var nextR = result[rI], nextO = origAlignable[origI]\n      if (!nextR && nextO == null) break\n\n      var rLine = nextR ? nextR[0] : 1e9, oLine = nextO == null ? 1e9 : nextO\n      while (chunkI < chunks.length) {\n        var chunk = chunks[chunkI]\n        if (chunk.origFrom <= oLine && chunk.origTo > oLine) {\n          origI++\n          rI--\n          continue outer;\n        }\n        if (chunk.editTo > rLine) {\n          if (chunk.editFrom <= rLine) continue outer;\n          break\n        }\n        diff += (chunk.origTo - chunk.origFrom) - (chunk.editTo - chunk.editFrom)\n        chunkI++\n      }\n      if (rLine == oLine - diff) {\n        nextR[setIndex] = oLine\n        origI++\n      } else if (rLine < oLine - diff) {\n        nextR[setIndex] = rLine + diff\n      } else {\n        var record = [oLine - diff, null, null]\n        record[setIndex] = oLine\n        result.splice(rI, 0, record)\n        origI++\n      }\n    }\n  }\n\n  function findAlignedLines(dv, other) {\n    var alignable = alignableFor(dv.edit, dv.chunks, false), result = []\n    if (other) for (var i = 0, j = 0; i < other.chunks.length; i++) {\n      var n = other.chunks[i].editTo\n      while (j < alignable.length && alignable[j] < n) j++\n      if (j == alignable.length || alignable[j] != n) alignable.splice(j++, 0, n)\n    }\n    for (var i = 0; i < alignable.length; i++)\n      result.push([alignable[i], null, null])\n\n    mergeAlignable(result, alignableFor(dv.orig, dv.chunks, true), dv.chunks, 1)\n    if (other)\n      mergeAlignable(result, alignableFor(other.orig, other.chunks, true), other.chunks, 2)\n\n    return result\n  }\n\n  function alignChunks(dv, force) {\n    if (!dv.dealigned && !force) return;\n    if (!dv.orig.curOp) return dv.orig.operation(function() {\n      alignChunks(dv, force);\n    });\n\n    dv.dealigned = false;\n    var other = dv.mv.left == dv ? dv.mv.right : dv.mv.left;\n    if (other) {\n      ensureDiff(other);\n      other.dealigned = false;\n    }\n    var linesToAlign = findAlignedLines(dv, other);\n\n    // Clear old aligners\n    var aligners = dv.mv.aligners;\n    for (var i = 0; i < aligners.length; i++)\n      aligners[i].clear();\n    aligners.length = 0;\n\n    var cm = [dv.edit, dv.orig], scroll = [];\n    if (other) cm.push(other.orig);\n    for (var i = 0; i < cm.length; i++)\n      scroll.push(cm[i].getScrollInfo().top);\n\n    for (var ln = 0; ln < linesToAlign.length; ln++)\n      alignLines(cm, linesToAlign[ln], aligners);\n\n    for (var i = 0; i < cm.length; i++)\n      cm[i].scrollTo(null, scroll[i]);\n  }\n\n  function alignLines(cm, lines, aligners) {\n    var maxOffset = 0, offset = [];\n    for (var i = 0; i < cm.length; i++) if (lines[i] != null) {\n      var off = cm[i].heightAtLine(lines[i], \"local\");\n      offset[i] = off;\n      maxOffset = Math.max(maxOffset, off);\n    }\n    for (var i = 0; i < cm.length; i++) if (lines[i] != null) {\n      var diff = maxOffset - offset[i];\n      if (diff > 1)\n        aligners.push(padAbove(cm[i], lines[i], diff));\n    }\n  }\n\n  function padAbove(cm, line, size) {\n    var above = true;\n    if (line > cm.lastLine()) {\n      line--;\n      above = false;\n    }\n    var elt = document.createElement(\"div\");\n    elt.className = \"CodeMirror-merge-spacer\";\n    elt.style.height = size + \"px\"; elt.style.minWidth = \"1px\";\n    return cm.addLineWidget(line, elt, {height: size, above: above, mergeSpacer: true, handleMouseEvents: true});\n  }\n\n  function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {\n    var flip = dv.type == \"left\";\n    var top = dv.orig.heightAtLine(chunk.origFrom, \"local\", true) - sTopOrig;\n    if (dv.svg) {\n      var topLpx = top;\n      var topRpx = dv.edit.heightAtLine(chunk.editFrom, \"local\", true) - sTopEdit;\n      if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }\n      var botLpx = dv.orig.heightAtLine(chunk.origTo, \"local\", true) - sTopOrig;\n      var botRpx = dv.edit.heightAtLine(chunk.editTo, \"local\", true) - sTopEdit;\n      if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }\n      var curveTop = \" C \" + w/2 + \" \" + topRpx + \" \" + w/2 + \" \" + topLpx + \" \" + (w + 2) + \" \" + topLpx;\n      var curveBot = \" C \" + w/2 + \" \" + botLpx + \" \" + w/2 + \" \" + botRpx + \" -1 \" + botRpx;\n      attrs(dv.svg.appendChild(document.createElementNS(svgNS, \"path\")),\n            \"d\", \"M -1 \" + topRpx + curveTop + \" L \" + (w + 2) + \" \" + botLpx + curveBot + \" z\",\n            \"class\", dv.classes.connect);\n    }\n    if (dv.copyButtons) {\n      var copy = dv.copyButtons.appendChild(elt(\"div\", dv.type == \"left\" ? \"\\u21dd\" : \"\\u21dc\",\n                                                \"CodeMirror-merge-copy\"));\n      var editOriginals = dv.mv.options.allowEditingOriginals;\n      copy.title = dv.edit.phrase(editOriginals ? \"Push to left\" : \"Revert chunk\");\n      copy.chunk = chunk;\n      copy.style.top = (chunk.origTo > chunk.origFrom ? top : dv.edit.heightAtLine(chunk.editFrom, \"local\") - sTopEdit) + \"px\";\n\n      if (editOriginals) {\n        var topReverse = dv.edit.heightAtLine(chunk.editFrom, \"local\") - sTopEdit;\n        var copyReverse = dv.copyButtons.appendChild(elt(\"div\", dv.type == \"right\" ? \"\\u21dd\" : \"\\u21dc\",\n                                                         \"CodeMirror-merge-copy-reverse\"));\n        copyReverse.title = \"Push to right\";\n        copyReverse.chunk = {editFrom: chunk.origFrom, editTo: chunk.origTo,\n                             origFrom: chunk.editFrom, origTo: chunk.editTo};\n        copyReverse.style.top = topReverse + \"px\";\n        dv.type == \"right\" ? copyReverse.style.left = \"2px\" : copyReverse.style.right = \"2px\";\n      }\n    }\n  }\n\n  function copyChunk(dv, to, from, chunk) {\n    if (dv.diffOutOfDate) return;\n    var origStart = chunk.origTo > from.lastLine() ? Pos(chunk.origFrom - 1) : Pos(chunk.origFrom, 0)\n    var origEnd = Pos(chunk.origTo, 0)\n    var editStart = chunk.editTo > to.lastLine() ? Pos(chunk.editFrom - 1) : Pos(chunk.editFrom, 0)\n    var editEnd = Pos(chunk.editTo, 0)\n    var handler = dv.mv.options.revertChunk\n    if (handler)\n      handler(dv.mv, from, origStart, origEnd, to, editStart, editEnd)\n    else\n      to.replaceRange(from.getRange(origStart, origEnd), editStart, editEnd)\n  }\n\n  // Merge view, containing 0, 1, or 2 diff views.\n\n  var MergeView = CodeMirror.MergeView = function(node, options) {\n    if (!(this instanceof MergeView)) return new MergeView(node, options);\n\n    this.options = options;\n    var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;\n\n    var hasLeft = origLeft != null, hasRight = origRight != null;\n    var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);\n    var wrap = [], left = this.left = null, right = this.right = null;\n    var self = this;\n\n    if (hasLeft) {\n      left = this.left = new DiffView(this, \"left\");\n      var leftPane = elt(\"div\", null, \"CodeMirror-merge-pane CodeMirror-merge-left\");\n      wrap.push(leftPane);\n      wrap.push(buildGap(left));\n    }\n\n    var editPane = elt(\"div\", null, \"CodeMirror-merge-pane CodeMirror-merge-editor\");\n    wrap.push(editPane);\n\n    if (hasRight) {\n      right = this.right = new DiffView(this, \"right\");\n      wrap.push(buildGap(right));\n      var rightPane = elt(\"div\", null, \"CodeMirror-merge-pane CodeMirror-merge-right\");\n      wrap.push(rightPane);\n    }\n\n    (hasRight ? rightPane : editPane).className += \" CodeMirror-merge-pane-rightmost\";\n\n    wrap.push(elt(\"div\", null, null, \"height: 0; clear: both;\"));\n\n    var wrapElt = this.wrap = node.appendChild(elt(\"div\", wrap, \"CodeMirror-merge CodeMirror-merge-\" + panes + \"pane\"));\n    this.edit = CodeMirror(editPane, copyObj(options));\n\n    if (left) left.init(leftPane, origLeft, options);\n    if (right) right.init(rightPane, origRight, options);\n    if (options.collapseIdentical)\n      this.editor().operation(function() {\n        collapseIdenticalStretches(self, options.collapseIdentical);\n      });\n    if (options.connect == \"align\") {\n      this.aligners = [];\n      alignChunks(this.left || this.right, true);\n    }\n    if (left) left.registerEvents(right)\n    if (right) right.registerEvents(left)\n\n\n    var onResize = function() {\n      if (left) makeConnections(left);\n      if (right) makeConnections(right);\n    };\n    CodeMirror.on(window, \"resize\", onResize);\n    var resizeInterval = setInterval(function() {\n      for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}\n      if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, \"resize\", onResize); }\n    }, 5000);\n  };\n\n  function buildGap(dv) {\n    var lock = dv.lockButton = elt(\"div\", null, \"CodeMirror-merge-scrolllock\");\n    var lockWrap = elt(\"div\", [lock], \"CodeMirror-merge-scrolllock-wrap\");\n    CodeMirror.on(lock, \"click\", function() { setScrollLock(dv, !dv.lockScroll); });\n    var gapElts = [lockWrap];\n    if (dv.mv.options.revertButtons !== false) {\n      dv.copyButtons = elt(\"div\", null, \"CodeMirror-merge-copybuttons-\" + dv.type);\n      CodeMirror.on(dv.copyButtons, \"click\", function(e) {\n        var node = e.target || e.srcElement;\n        if (!node.chunk) return;\n        if (node.className == \"CodeMirror-merge-copy-reverse\") {\n          copyChunk(dv, dv.orig, dv.edit, node.chunk);\n          return;\n        }\n        copyChunk(dv, dv.edit, dv.orig, node.chunk);\n      });\n      gapElts.unshift(dv.copyButtons);\n    }\n    if (dv.mv.options.connect != \"align\") {\n      var svg = document.createElementNS && document.createElementNS(svgNS, \"svg\");\n      if (svg && !svg.createSVGRect) svg = null;\n      dv.svg = svg;\n      if (svg) gapElts.push(svg);\n    }\n\n    return dv.gap = elt(\"div\", gapElts, \"CodeMirror-merge-gap\");\n  }\n\n  MergeView.prototype = {\n    constructor: MergeView,\n    editor: function() { return this.edit; },\n    rightOriginal: function() { return this.right && this.right.orig; },\n    leftOriginal: function() { return this.left && this.left.orig; },\n    setShowDifferences: function(val) {\n      if (this.right) this.right.setShowDifferences(val);\n      if (this.left) this.left.setShowDifferences(val);\n    },\n    rightChunks: function() {\n      if (this.right) { ensureDiff(this.right); return this.right.chunks; }\n    },\n    leftChunks: function() {\n      if (this.left) { ensureDiff(this.left); return this.left.chunks; }\n    }\n  };\n\n  function asString(obj) {\n    if (typeof obj == \"string\") return obj;\n    else return obj.getValue();\n  }\n\n  // Operations on diffs\n  var dmp;\n  function getDiff(a, b, ignoreWhitespace) {\n    if (!dmp) dmp = new diff_match_patch();\n\n    var diff = dmp.diff_main(a, b);\n    // The library sometimes leaves in empty parts, which confuse the algorithm\n    for (var i = 0; i < diff.length; ++i) {\n      var part = diff[i];\n      if (ignoreWhitespace ? !/[^ \\t]/.test(part[1]) : !part[1]) {\n        diff.splice(i--, 1);\n      } else if (i && diff[i - 1][0] == part[0]) {\n        diff.splice(i--, 1);\n        diff[i][1] += part[1];\n      }\n    }\n    return diff;\n  }\n\n  function getChunks(diff) {\n    var chunks = [];\n    if (!diff.length) return chunks;\n    var startEdit = 0, startOrig = 0;\n    var edit = Pos(0, 0), orig = Pos(0, 0);\n    for (var i = 0; i < diff.length; ++i) {\n      var part = diff[i], tp = part[0];\n      if (tp == DIFF_EQUAL) {\n        var startOff = !startOfLineClean(diff, i) || edit.line < startEdit || orig.line < startOrig ? 1 : 0;\n        var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;\n        moveOver(edit, part[1], null, orig);\n        var endOff = endOfLineClean(diff, i) ? 1 : 0;\n        var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;\n        if (cleanToEdit > cleanFromEdit) {\n          if (i) chunks.push({origFrom: startOrig, origTo: cleanFromOrig,\n                              editFrom: startEdit, editTo: cleanFromEdit});\n          startEdit = cleanToEdit; startOrig = cleanToOrig;\n        }\n      } else {\n        moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);\n      }\n    }\n    if (startEdit <= edit.line || startOrig <= orig.line)\n      chunks.push({origFrom: startOrig, origTo: orig.line + 1,\n                   editFrom: startEdit, editTo: edit.line + 1});\n    return chunks;\n  }\n\n  function endOfLineClean(diff, i) {\n    if (i == diff.length - 1) return true;\n    var next = diff[i + 1][1];\n    if ((next.length == 1 && i < diff.length - 2) || next.charCodeAt(0) != 10) return false;\n    if (i == diff.length - 2) return true;\n    next = diff[i + 2][1];\n    return (next.length > 1 || i == diff.length - 3) && next.charCodeAt(0) == 10;\n  }\n\n  function startOfLineClean(diff, i) {\n    if (i == 0) return true;\n    var last = diff[i - 1][1];\n    if (last.charCodeAt(last.length - 1) != 10) return false;\n    if (i == 1) return true;\n    last = diff[i - 2][1];\n    return last.charCodeAt(last.length - 1) == 10;\n  }\n\n  function chunkBoundariesAround(chunks, n, nInEdit) {\n    var beforeE, afterE, beforeO, afterO;\n    for (var i = 0; i < chunks.length; i++) {\n      var chunk = chunks[i];\n      var fromLocal = nInEdit ? chunk.editFrom : chunk.origFrom;\n      var toLocal = nInEdit ? chunk.editTo : chunk.origTo;\n      if (afterE == null) {\n        if (fromLocal > n) { afterE = chunk.editFrom; afterO = chunk.origFrom; }\n        else if (toLocal > n) { afterE = chunk.editTo; afterO = chunk.origTo; }\n      }\n      if (toLocal <= n) { beforeE = chunk.editTo; beforeO = chunk.origTo; }\n      else if (fromLocal <= n) { beforeE = chunk.editFrom; beforeO = chunk.origFrom; }\n    }\n    return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};\n  }\n\n  function collapseSingle(cm, from, to) {\n    cm.addLineClass(from, \"wrap\", \"CodeMirror-merge-collapsed-line\");\n    var widget = document.createElement(\"span\");\n    widget.className = \"CodeMirror-merge-collapsed-widget\";\n    widget.title = cm.phrase(\"Identical text collapsed. Click to expand.\");\n    var mark = cm.markText(Pos(from, 0), Pos(to - 1), {\n      inclusiveLeft: true,\n      inclusiveRight: true,\n      replacedWith: widget,\n      clearOnEnter: true\n    });\n    function clear() {\n      mark.clear();\n      cm.removeLineClass(from, \"wrap\", \"CodeMirror-merge-collapsed-line\");\n    }\n    if (mark.explicitlyCleared) clear();\n    CodeMirror.on(widget, \"click\", clear);\n    mark.on(\"clear\", clear);\n    CodeMirror.on(widget, \"click\", clear);\n    return {mark: mark, clear: clear};\n  }\n\n  function collapseStretch(size, editors) {\n    var marks = [];\n    function clear() {\n      for (var i = 0; i < marks.length; i++) marks[i].clear();\n    }\n    for (var i = 0; i < editors.length; i++) {\n      var editor = editors[i];\n      var mark = collapseSingle(editor.cm, editor.line, editor.line + size);\n      marks.push(mark);\n      mark.mark.on(\"clear\", clear);\n    }\n    return marks[0].mark;\n  }\n\n  function unclearNearChunks(dv, margin, off, clear) {\n    for (var i = 0; i < dv.chunks.length; i++) {\n      var chunk = dv.chunks[i];\n      for (var l = chunk.editFrom - margin; l < chunk.editTo + margin; l++) {\n        var pos = l + off;\n        if (pos >= 0 && pos < clear.length) clear[pos] = false;\n      }\n    }\n  }\n\n  function collapseIdenticalStretches(mv, margin) {\n    if (typeof margin != \"number\") margin = 2;\n    var clear = [], edit = mv.editor(), off = edit.firstLine();\n    for (var l = off, e = edit.lastLine(); l <= e; l++) clear.push(true);\n    if (mv.left) unclearNearChunks(mv.left, margin, off, clear);\n    if (mv.right) unclearNearChunks(mv.right, margin, off, clear);\n\n    for (var i = 0; i < clear.length; i++) {\n      if (clear[i]) {\n        var line = i + off;\n        for (var size = 1; i < clear.length - 1 && clear[i + 1]; i++, size++) {}\n        if (size > margin) {\n          var editors = [{line: line, cm: edit}];\n          if (mv.left) editors.push({line: getMatchingOrigLine(line, mv.left.chunks), cm: mv.left.orig});\n          if (mv.right) editors.push({line: getMatchingOrigLine(line, mv.right.chunks), cm: mv.right.orig});\n          var mark = collapseStretch(size, editors);\n          if (mv.options.onCollapse) mv.options.onCollapse(mv, line, size, mark);\n        }\n      }\n    }\n  }\n\n  // General utilities\n\n  function elt(tag, content, className, style) {\n    var e = document.createElement(tag);\n    if (className) e.className = className;\n    if (style) e.style.cssText = style;\n    if (typeof content == \"string\") e.appendChild(document.createTextNode(content));\n    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);\n    return e;\n  }\n\n  function clear(node) {\n    for (var count = node.childNodes.length; count > 0; --count)\n      node.removeChild(node.firstChild);\n  }\n\n  function attrs(elt) {\n    for (var i = 1; i < arguments.length; i += 2)\n      elt.setAttribute(arguments[i], arguments[i+1]);\n  }\n\n  function copyObj(obj, target) {\n    if (!target) target = {};\n    for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];\n    return target;\n  }\n\n  function moveOver(pos, str, copy, other) {\n    var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;\n    for (;;) {\n      var nl = str.indexOf(\"\\n\", at);\n      if (nl == -1) break;\n      ++out.line;\n      if (other) ++other.line;\n      at = nl + 1;\n    }\n    out.ch = (at ? 0 : out.ch) + (str.length - at);\n    if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);\n    return out;\n  }\n\n  // Tracks collapsed markers and line widgets, in order to be able to\n  // accurately align the content of two editors.\n\n  var F_WIDGET = 1, F_WIDGET_BELOW = 2, F_MARKER = 4\n\n  function TrackAlignable(cm) {\n    this.cm = cm\n    this.alignable = []\n    this.height = cm.doc.height\n    var self = this\n    cm.on(\"markerAdded\", function(_, marker) {\n      if (!marker.collapsed) return\n      var found = marker.find(1)\n      if (found != null) self.set(found.line, F_MARKER)\n    })\n    cm.on(\"markerCleared\", function(_, marker, _min, max) {\n      if (max != null && marker.collapsed)\n        self.check(max, F_MARKER, self.hasMarker)\n    })\n    cm.on(\"markerChanged\", this.signal.bind(this))\n    cm.on(\"lineWidgetAdded\", function(_, widget, lineNo) {\n      if (widget.mergeSpacer) return\n      if (widget.above) self.set(lineNo - 1, F_WIDGET_BELOW)\n      else self.set(lineNo, F_WIDGET)\n    })\n    cm.on(\"lineWidgetCleared\", function(_, widget, lineNo) {\n      if (widget.mergeSpacer) return\n      if (widget.above) self.check(lineNo - 1, F_WIDGET_BELOW, self.hasWidgetBelow)\n      else self.check(lineNo, F_WIDGET, self.hasWidget)\n    })\n    cm.on(\"lineWidgetChanged\", this.signal.bind(this))\n    cm.on(\"change\", function(_, change) {\n      var start = change.from.line, nBefore = change.to.line - change.from.line\n      var nAfter = change.text.length - 1, end = start + nAfter\n      if (nBefore || nAfter) self.map(start, nBefore, nAfter)\n      self.check(end, F_MARKER, self.hasMarker)\n      if (nBefore || nAfter) self.check(change.from.line, F_MARKER, self.hasMarker)\n    })\n    cm.on(\"viewportChange\", function() {\n      if (self.cm.doc.height != self.height) self.signal()\n    })\n  }\n\n  TrackAlignable.prototype = {\n    signal: function() {\n      CodeMirror.signal(this, \"realign\")\n      this.height = this.cm.doc.height\n    },\n\n    set: function(n, flags) {\n      var pos = -1\n      for (; pos < this.alignable.length; pos += 2) {\n        var diff = this.alignable[pos] - n\n        if (diff == 0) {\n          if ((this.alignable[pos + 1] & flags) == flags) return\n          this.alignable[pos + 1] |= flags\n          this.signal()\n          return\n        }\n        if (diff > 0) break\n      }\n      this.signal()\n      this.alignable.splice(pos, 0, n, flags)\n    },\n\n    find: function(n) {\n      for (var i = 0; i < this.alignable.length; i += 2)\n        if (this.alignable[i] == n) return i\n      return -1\n    },\n\n    check: function(n, flag, pred) {\n      var found = this.find(n)\n      if (found == -1 || !(this.alignable[found + 1] & flag)) return\n      if (!pred.call(this, n)) {\n        this.signal()\n        var flags = this.alignable[found + 1] & ~flag\n        if (flags) this.alignable[found + 1] = flags\n        else this.alignable.splice(found, 2)\n      }\n    },\n\n    hasMarker: function(n) {\n      var handle = this.cm.getLineHandle(n)\n      if (handle.markedSpans) for (var i = 0; i < handle.markedSpans.length; i++)\n        if (handle.markedSpans[i].mark.collapsed && handle.markedSpans[i].to != null)\n          return true\n      return false\n    },\n\n    hasWidget: function(n) {\n      var handle = this.cm.getLineHandle(n)\n      if (handle.widgets) for (var i = 0; i < handle.widgets.length; i++)\n        if (!handle.widgets[i].above && !handle.widgets[i].mergeSpacer) return true\n      return false\n    },\n\n    hasWidgetBelow: function(n) {\n      if (n == this.cm.lastLine()) return false\n      var handle = this.cm.getLineHandle(n + 1)\n      if (handle.widgets) for (var i = 0; i < handle.widgets.length; i++)\n        if (handle.widgets[i].above && !handle.widgets[i].mergeSpacer) return true\n      return false\n    },\n\n    map: function(from, nBefore, nAfter) {\n      var diff = nAfter - nBefore, to = from + nBefore, widgetFrom = -1, widgetTo = -1\n      for (var i = 0; i < this.alignable.length; i += 2) {\n        var n = this.alignable[i]\n        if (n == from && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetFrom = i\n        if (n == to && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetTo = i\n        if (n <= from) continue\n        else if (n < to) this.alignable.splice(i--, 2)\n        else this.alignable[i] += diff\n      }\n      if (widgetFrom > -1) {\n        var flags = this.alignable[widgetFrom + 1]\n        if (flags == F_WIDGET_BELOW) this.alignable.splice(widgetFrom, 2)\n        else this.alignable[widgetFrom + 1] = flags & ~F_WIDGET_BELOW\n      }\n      if (widgetTo > -1 && nAfter)\n        this.set(from + nAfter, F_WIDGET_BELOW)\n    }\n  }\n\n  function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }\n  function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }\n  function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }\n\n  function findPrevDiff(chunks, start, isOrig) {\n    for (var i = chunks.length - 1; i >= 0; i--) {\n      var chunk = chunks[i];\n      var to = (isOrig ? chunk.origTo : chunk.editTo) - 1;\n      if (to < start) return to;\n    }\n  }\n\n  function findNextDiff(chunks, start, isOrig) {\n    for (var i = 0; i < chunks.length; i++) {\n      var chunk = chunks[i];\n      var from = (isOrig ? chunk.origFrom : chunk.editFrom);\n      if (from > start) return from;\n    }\n  }\n\n  function goNearbyDiff(cm, dir) {\n    var found = null, views = cm.state.diffViews, line = cm.getCursor().line;\n    if (views) for (var i = 0; i < views.length; i++) {\n      var dv = views[i], isOrig = cm == dv.orig;\n      ensureDiff(dv);\n      var pos = dir < 0 ? findPrevDiff(dv.chunks, line, isOrig) : findNextDiff(dv.chunks, line, isOrig);\n      if (pos != null && (found == null || (dir < 0 ? pos > found : pos < found)))\n        found = pos;\n    }\n    if (found != null)\n      cm.setCursor(found, 0);\n    else\n      return CodeMirror.Pass;\n  }\n\n  CodeMirror.commands.goNextDiff = function(cm) {\n    return goNearbyDiff(cm, 1);\n  };\n  CodeMirror.commands.goPrevDiff = function(cm) {\n    return goNearbyDiff(cm, -1);\n  };\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/mode/loadmode.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), \"cjs\");\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], function(CM) { mod(CM, \"amd\"); });\n  else // Plain browser env\n    mod(CodeMirror, \"plain\");\n})(function(CodeMirror, env) {\n  if (!CodeMirror.modeURL) CodeMirror.modeURL = \"../mode/%N/%N.js\";\n\n  var loading = {};\n  function splitCallback(cont, n) {\n    var countDown = n;\n    return function() { if (--countDown == 0) cont(); };\n  }\n  function ensureDeps(mode, cont) {\n    var deps = CodeMirror.modes[mode].dependencies;\n    if (!deps) return cont();\n    var missing = [];\n    for (var i = 0; i < deps.length; ++i) {\n      if (!CodeMirror.modes.hasOwnProperty(deps[i]))\n        missing.push(deps[i]);\n    }\n    if (!missing.length) return cont();\n    var split = splitCallback(cont, missing.length);\n    for (var i = 0; i < missing.length; ++i)\n      CodeMirror.requireMode(missing[i], split);\n  }\n\n  CodeMirror.requireMode = function(mode, cont) {\n    if (typeof mode != \"string\") mode = mode.name;\n    if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);\n    if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);\n\n    var file = CodeMirror.modeURL.replace(/%N/g, mode);\n    if (env == \"plain\") {\n      var script = document.createElement(\"script\");\n      script.src = file;\n      var others = document.getElementsByTagName(\"script\")[0];\n      var list = loading[mode] = [cont];\n      CodeMirror.on(script, \"load\", function() {\n        ensureDeps(mode, function() {\n          for (var i = 0; i < list.length; ++i) list[i]();\n        });\n      });\n      others.parentNode.insertBefore(script, others);\n    } else if (env == \"cjs\") {\n      require(file);\n      cont();\n    } else if (env == \"amd\") {\n      requirejs([file], cont);\n    }\n  };\n\n  CodeMirror.autoLoadMode = function(instance, mode) {\n    if (!CodeMirror.modes.hasOwnProperty(mode))\n      CodeMirror.requireMode(mode, function() {\n        instance.setOption(\"mode\", instance.getOption(\"mode\"));\n      });\n  };\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/mode/multiplex.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.multiplexingMode = function(outer /*, others */) {\n  // Others should be {open, close, mode [, delimStyle] [, innerStyle]} objects\n  var others = Array.prototype.slice.call(arguments, 1);\n\n  function indexOf(string, pattern, from, returnEnd) {\n    if (typeof pattern == \"string\") {\n      var found = string.indexOf(pattern, from);\n      return returnEnd && found > -1 ? found + pattern.length : found;\n    }\n    var m = pattern.exec(from ? string.slice(from) : string);\n    return m ? m.index + from + (returnEnd ? m[0].length : 0) : -1;\n  }\n\n  return {\n    startState: function() {\n      return {\n        outer: CodeMirror.startState(outer),\n        innerActive: null,\n        inner: null\n      };\n    },\n\n    copyState: function(state) {\n      return {\n        outer: CodeMirror.copyState(outer, state.outer),\n        innerActive: state.innerActive,\n        inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)\n      };\n    },\n\n    token: function(stream, state) {\n      if (!state.innerActive) {\n        var cutOff = Infinity, oldContent = stream.string;\n        for (var i = 0; i < others.length; ++i) {\n          var other = others[i];\n          var found = indexOf(oldContent, other.open, stream.pos);\n          if (found == stream.pos) {\n            if (!other.parseDelimiters) stream.match(other.open);\n            state.innerActive = other;\n\n            // Get the outer indent, making sure to handle CodeMirror.Pass\n            var outerIndent = 0;\n            if (outer.indent) {\n              var possibleOuterIndent = outer.indent(state.outer, \"\", \"\");\n              if (possibleOuterIndent !== CodeMirror.Pass) outerIndent = possibleOuterIndent;\n            }\n\n            state.inner = CodeMirror.startState(other.mode, outerIndent);\n            return other.delimStyle && (other.delimStyle + \" \" + other.delimStyle + \"-open\");\n          } else if (found != -1 && found < cutOff) {\n            cutOff = found;\n          }\n        }\n        if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff);\n        var outerToken = outer.token(stream, state.outer);\n        if (cutOff != Infinity) stream.string = oldContent;\n        return outerToken;\n      } else {\n        var curInner = state.innerActive, oldContent = stream.string;\n        if (!curInner.close && stream.sol()) {\n          state.innerActive = state.inner = null;\n          return this.token(stream, state);\n        }\n        var found = curInner.close ? indexOf(oldContent, curInner.close, stream.pos, curInner.parseDelimiters) : -1;\n        if (found == stream.pos && !curInner.parseDelimiters) {\n          stream.match(curInner.close);\n          state.innerActive = state.inner = null;\n          return curInner.delimStyle && (curInner.delimStyle + \" \" + curInner.delimStyle + \"-close\");\n        }\n        if (found > -1) stream.string = oldContent.slice(0, found);\n        var innerToken = curInner.mode.token(stream, state.inner);\n        if (found > -1) stream.string = oldContent;\n\n        if (found == stream.pos && curInner.parseDelimiters)\n          state.innerActive = state.inner = null;\n\n        if (curInner.innerStyle) {\n          if (innerToken) innerToken = innerToken + \" \" + curInner.innerStyle;\n          else innerToken = curInner.innerStyle;\n        }\n\n        return innerToken;\n      }\n    },\n\n    indent: function(state, textAfter, line) {\n      var mode = state.innerActive ? state.innerActive.mode : outer;\n      if (!mode.indent) return CodeMirror.Pass;\n      return mode.indent(state.innerActive ? state.inner : state.outer, textAfter, line);\n    },\n\n    blankLine: function(state) {\n      var mode = state.innerActive ? state.innerActive.mode : outer;\n      if (mode.blankLine) {\n        mode.blankLine(state.innerActive ? state.inner : state.outer);\n      }\n      if (!state.innerActive) {\n        for (var i = 0; i < others.length; ++i) {\n          var other = others[i];\n          if (other.open === \"\\n\") {\n            state.innerActive = other;\n            state.inner = CodeMirror.startState(other.mode, mode.indent ? mode.indent(state.outer, \"\", \"\") : 0);\n          }\n        }\n      } else if (state.innerActive.close === \"\\n\") {\n        state.innerActive = state.inner = null;\n      }\n    },\n\n    electricChars: outer.electricChars,\n\n    innerMode: function(state) {\n      return state.inner ? {state: state.inner, mode: state.innerActive.mode} : {state: state.outer, mode: outer};\n    }\n  };\n};\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/mode/multiplex_test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  CodeMirror.defineMode(\"markdown_with_stex\", function(){\n    var inner = CodeMirror.getMode({}, \"stex\");\n    var outer = CodeMirror.getMode({}, \"markdown\");\n\n    var innerOptions = {\n      open: '$',\n      close: '$',\n      mode: inner,\n      delimStyle: 'delim',\n      innerStyle: 'inner'\n    };\n\n    return CodeMirror.multiplexingMode(outer, innerOptions);\n  });\n\n  var mode = CodeMirror.getMode({}, \"markdown_with_stex\");\n\n  function MT(name) {\n    test.mode(\n      name,\n      mode,\n      Array.prototype.slice.call(arguments, 1),\n      'multiplexing');\n  }\n\n  MT(\n    \"stexInsideMarkdown\",\n    \"[strong **Equation:**] [delim&delim-open $][inner&tag \\\\pi][delim&delim-close $]\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/addon/mode/overlay.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Utility function that allows modes to be combined. The mode given\n// as the base argument takes care of most of the normal mode\n// functionality, but a second (typically simple) mode is used, which\n// can override the style of text. Both modes get to parse all of the\n// text, but when both assign a non-null style to a piece of code, the\n// overlay wins, unless the combine argument was true and not overridden,\n// or state.overlay.combineTokens was true, in which case the styles are\n// combined.\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.overlayMode = function(base, overlay, combine) {\n  return {\n    startState: function() {\n      return {\n        base: CodeMirror.startState(base),\n        overlay: CodeMirror.startState(overlay),\n        basePos: 0, baseCur: null,\n        overlayPos: 0, overlayCur: null,\n        streamSeen: null\n      };\n    },\n    copyState: function(state) {\n      return {\n        base: CodeMirror.copyState(base, state.base),\n        overlay: CodeMirror.copyState(overlay, state.overlay),\n        basePos: state.basePos, baseCur: null,\n        overlayPos: state.overlayPos, overlayCur: null\n      };\n    },\n\n    token: function(stream, state) {\n      if (stream != state.streamSeen ||\n          Math.min(state.basePos, state.overlayPos) < stream.start) {\n        state.streamSeen = stream;\n        state.basePos = state.overlayPos = stream.start;\n      }\n\n      if (stream.start == state.basePos) {\n        state.baseCur = base.token(stream, state.base);\n        state.basePos = stream.pos;\n      }\n      if (stream.start == state.overlayPos) {\n        stream.pos = stream.start;\n        state.overlayCur = overlay.token(stream, state.overlay);\n        state.overlayPos = stream.pos;\n      }\n      stream.pos = Math.min(state.basePos, state.overlayPos);\n\n      // state.overlay.combineTokens always takes precedence over combine,\n      // unless set to null\n      if (state.overlayCur == null) return state.baseCur;\n      else if (state.baseCur != null &&\n               state.overlay.combineTokens ||\n               combine && state.overlay.combineTokens == null)\n        return state.baseCur + \" \" + state.overlayCur;\n      else return state.overlayCur;\n    },\n\n    indent: base.indent && function(state, textAfter, line) {\n      return base.indent(state.base, textAfter, line);\n    },\n    electricChars: base.electricChars,\n\n    innerMode: function(state) { return {state: state.base, mode: base}; },\n\n    blankLine: function(state) {\n      var baseToken, overlayToken;\n      if (base.blankLine) baseToken = base.blankLine(state.base);\n      if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay);\n\n      return overlayToken == null ?\n        baseToken :\n        (combine && baseToken != null ? baseToken + \" \" + overlayToken : overlayToken);\n    }\n  };\n};\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/mode/simple.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineSimpleMode = function(name, states) {\n    CodeMirror.defineMode(name, function(config) {\n      return CodeMirror.simpleMode(config, states);\n    });\n  };\n\n  CodeMirror.simpleMode = function(config, states) {\n    ensureState(states, \"start\");\n    var states_ = {}, meta = states.meta || {}, hasIndentation = false;\n    for (var state in states) if (state != meta && states.hasOwnProperty(state)) {\n      var list = states_[state] = [], orig = states[state];\n      for (var i = 0; i < orig.length; i++) {\n        var data = orig[i];\n        list.push(new Rule(data, states));\n        if (data.indent || data.dedent) hasIndentation = true;\n      }\n    }\n    var mode = {\n      startState: function() {\n        return {state: \"start\", pending: null,\n                local: null, localState: null,\n                indent: hasIndentation ? [] : null};\n      },\n      copyState: function(state) {\n        var s = {state: state.state, pending: state.pending,\n                 local: state.local, localState: null,\n                 indent: state.indent && state.indent.slice(0)};\n        if (state.localState)\n          s.localState = CodeMirror.copyState(state.local.mode, state.localState);\n        if (state.stack)\n          s.stack = state.stack.slice(0);\n        for (var pers = state.persistentStates; pers; pers = pers.next)\n          s.persistentStates = {mode: pers.mode,\n                                spec: pers.spec,\n                                state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state),\n                                next: s.persistentStates};\n        return s;\n      },\n      token: tokenFunction(states_, config),\n      innerMode: function(state) { return state.local && {mode: state.local.mode, state: state.localState}; },\n      indent: indentFunction(states_, meta)\n    };\n    if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop))\n      mode[prop] = meta[prop];\n    return mode;\n  };\n\n  function ensureState(states, name) {\n    if (!states.hasOwnProperty(name))\n      throw new Error(\"Undefined state \" + name + \" in simple mode\");\n  }\n\n  function toRegex(val, caret) {\n    if (!val) return /(?:)/;\n    var flags = \"\";\n    if (val instanceof RegExp) {\n      if (val.ignoreCase) flags = \"i\";\n      val = val.source;\n    } else {\n      val = String(val);\n    }\n    return new RegExp((caret === false ? \"\" : \"^\") + \"(?:\" + val + \")\", flags);\n  }\n\n  function asToken(val) {\n    if (!val) return null;\n    if (val.apply) return val\n    if (typeof val == \"string\") return val.replace(/\\./g, \" \");\n    var result = [];\n    for (var i = 0; i < val.length; i++)\n      result.push(val[i] && val[i].replace(/\\./g, \" \"));\n    return result;\n  }\n\n  function Rule(data, states) {\n    if (data.next || data.push) ensureState(states, data.next || data.push);\n    this.regex = toRegex(data.regex);\n    this.token = asToken(data.token);\n    this.data = data;\n  }\n\n  function tokenFunction(states, config) {\n    return function(stream, state) {\n      if (state.pending) {\n        var pend = state.pending.shift();\n        if (state.pending.length == 0) state.pending = null;\n        stream.pos += pend.text.length;\n        return pend.token;\n      }\n\n      if (state.local) {\n        if (state.local.end && stream.match(state.local.end)) {\n          var tok = state.local.endToken || null;\n          state.local = state.localState = null;\n          return tok;\n        } else {\n          var tok = state.local.mode.token(stream, state.localState), m;\n          if (state.local.endScan && (m = state.local.endScan.exec(stream.current())))\n            stream.pos = stream.start + m.index;\n          return tok;\n        }\n      }\n\n      var curState = states[state.state];\n      for (var i = 0; i < curState.length; i++) {\n        var rule = curState[i];\n        var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);\n        if (matches) {\n          if (rule.data.next) {\n            state.state = rule.data.next;\n          } else if (rule.data.push) {\n            (state.stack || (state.stack = [])).push(state.state);\n            state.state = rule.data.push;\n          } else if (rule.data.pop && state.stack && state.stack.length) {\n            state.state = state.stack.pop();\n          }\n\n          if (rule.data.mode)\n            enterLocalMode(config, state, rule.data.mode, rule.token);\n          if (rule.data.indent)\n            state.indent.push(stream.indentation() + config.indentUnit);\n          if (rule.data.dedent)\n            state.indent.pop();\n          var token = rule.token\n          if (token && token.apply) token = token(matches)\n          if (matches.length > 2 && rule.token && typeof rule.token != \"string\") {\n            state.pending = [];\n            for (var j = 2; j < matches.length; j++)\n              if (matches[j])\n                state.pending.push({text: matches[j], token: rule.token[j - 1]});\n            stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));\n            return token[0];\n          } else if (token && token.join) {\n            return token[0];\n          } else {\n            return token;\n          }\n        }\n      }\n      stream.next();\n      return null;\n    };\n  }\n\n  function cmp(a, b) {\n    if (a === b) return true;\n    if (!a || typeof a != \"object\" || !b || typeof b != \"object\") return false;\n    var props = 0;\n    for (var prop in a) if (a.hasOwnProperty(prop)) {\n      if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false;\n      props++;\n    }\n    for (var prop in b) if (b.hasOwnProperty(prop)) props--;\n    return props == 0;\n  }\n\n  function enterLocalMode(config, state, spec, token) {\n    var pers;\n    if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next)\n      if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p;\n    var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec);\n    var lState = pers ? pers.state : CodeMirror.startState(mode);\n    if (spec.persistent && !pers)\n      state.persistentStates = {mode: mode, spec: spec.spec, state: lState, next: state.persistentStates};\n\n    state.localState = lState;\n    state.local = {mode: mode,\n                   end: spec.end && toRegex(spec.end),\n                   endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),\n                   endToken: token && token.join ? token[token.length - 1] : token};\n  }\n\n  function indexOf(val, arr) {\n    for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true;\n  }\n\n  function indentFunction(states, meta) {\n    return function(state, textAfter, line) {\n      if (state.local && state.local.mode.indent)\n        return state.local.mode.indent(state.localState, textAfter, line);\n      if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1)\n        return CodeMirror.Pass;\n\n      var pos = state.indent.length - 1, rules = states[state.state];\n      scan: for (;;) {\n        for (var i = 0; i < rules.length; i++) {\n          var rule = rules[i];\n          if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {\n            var m = rule.regex.exec(textAfter);\n            if (m && m[0]) {\n              pos--;\n              if (rule.next || rule.push) rules = states[rule.next || rule.push];\n              textAfter = textAfter.slice(m[0].length);\n              continue scan;\n            }\n          }\n        }\n        break;\n      }\n      return pos < 0 ? 0 : state.indent[pos];\n    };\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/runmode/colorize.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"./runmode\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"./runmode\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var isBlock = /^(p|li|div|h\\\\d|pre|blockquote|td)$/;\n\n  function textContent(node, out) {\n    if (node.nodeType == 3) return out.push(node.nodeValue);\n    for (var ch = node.firstChild; ch; ch = ch.nextSibling) {\n      textContent(ch, out);\n      if (isBlock.test(node.nodeType)) out.push(\"\\n\");\n    }\n  }\n\n  CodeMirror.colorize = function(collection, defaultMode) {\n    if (!collection) collection = document.body.getElementsByTagName(\"pre\");\n\n    for (var i = 0; i < collection.length; ++i) {\n      var node = collection[i];\n      var mode = node.getAttribute(\"data-lang\") || defaultMode;\n      if (!mode) continue;\n\n      var text = [];\n      textContent(node, text);\n      node.innerHTML = \"\";\n      CodeMirror.runMode(text.join(\"\"), mode, node);\n\n      node.className += \" cm-s-default\";\n    }\n  };\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/runmode/runmode-standalone.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\nwindow.CodeMirror = {};\n\n(function() {\n\"use strict\";\n\nfunction splitLines(string){ return string.split(/\\r?\\n|\\r/); };\n\nfunction StringStream(string) {\n  this.pos = this.start = 0;\n  this.string = string;\n  this.lineStart = 0;\n}\nStringStream.prototype = {\n  eol: function() {return this.pos >= this.string.length;},\n  sol: function() {return this.pos == 0;},\n  peek: function() {return this.string.charAt(this.pos) || null;},\n  next: function() {\n    if (this.pos < this.string.length)\n      return this.string.charAt(this.pos++);\n  },\n  eat: function(match) {\n    var ch = this.string.charAt(this.pos);\n    if (typeof match == \"string\") var ok = ch == match;\n    else var ok = ch && (match.test ? match.test(ch) : match(ch));\n    if (ok) {++this.pos; return ch;}\n  },\n  eatWhile: function(match) {\n    var start = this.pos;\n    while (this.eat(match)){}\n    return this.pos > start;\n  },\n  eatSpace: function() {\n    var start = this.pos;\n    while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;\n    return this.pos > start;\n  },\n  skipToEnd: function() {this.pos = this.string.length;},\n  skipTo: function(ch) {\n    var found = this.string.indexOf(ch, this.pos);\n    if (found > -1) {this.pos = found; return true;}\n  },\n  backUp: function(n) {this.pos -= n;},\n  column: function() {return this.start - this.lineStart;},\n  indentation: function() {return 0;},\n  match: function(pattern, consume, caseInsensitive) {\n    if (typeof pattern == \"string\") {\n      var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};\n      var substr = this.string.substr(this.pos, pattern.length);\n      if (cased(substr) == cased(pattern)) {\n        if (consume !== false) this.pos += pattern.length;\n        return true;\n      }\n    } else {\n      var match = this.string.slice(this.pos).match(pattern);\n      if (match && match.index > 0) return null;\n      if (match && consume !== false) this.pos += match[0].length;\n      return match;\n    }\n  },\n  current: function(){return this.string.slice(this.start, this.pos);},\n  hideFirstChars: function(n, inner) {\n    this.lineStart += n;\n    try { return inner(); }\n    finally { this.lineStart -= n; }\n  },\n  lookAhead: function() { return null }\n};\nCodeMirror.StringStream = StringStream;\n\nCodeMirror.startState = function (mode, a1, a2) {\n  return mode.startState ? mode.startState(a1, a2) : true;\n};\n\nvar modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};\nCodeMirror.defineMode = function (name, mode) {\n  if (arguments.length > 2)\n    mode.dependencies = Array.prototype.slice.call(arguments, 2);\n  modes[name] = mode;\n};\nCodeMirror.defineMIME = function (mime, spec) { mimeModes[mime] = spec; };\nCodeMirror.resolveMode = function(spec) {\n  if (typeof spec == \"string\" && mimeModes.hasOwnProperty(spec)) {\n    spec = mimeModes[spec];\n  } else if (spec && typeof spec.name == \"string\" && mimeModes.hasOwnProperty(spec.name)) {\n    spec = mimeModes[spec.name];\n  }\n  if (typeof spec == \"string\") return {name: spec};\n  else return spec || {name: \"null\"};\n};\nCodeMirror.getMode = function (options, spec) {\n  spec = CodeMirror.resolveMode(spec);\n  var mfactory = modes[spec.name];\n  if (!mfactory) throw new Error(\"Unknown mode: \" + spec);\n  return mfactory(options, spec);\n};\nCodeMirror.registerHelper = CodeMirror.registerGlobalHelper = Math.min;\nCodeMirror.defineMode(\"null\", function() {\n  return {token: function(stream) {stream.skipToEnd();}};\n});\nCodeMirror.defineMIME(\"text/plain\", \"null\");\n\nCodeMirror.runMode = function (string, modespec, callback, options) {\n  var mode = CodeMirror.getMode({ indentUnit: 2 }, modespec);\n\n  if (callback.nodeType == 1) {\n    var tabSize = (options && options.tabSize) || 4;\n    var node = callback, col = 0;\n    node.innerHTML = \"\";\n    callback = function (text, style) {\n      if (text == \"\\n\") {\n        node.appendChild(document.createElement(\"br\"));\n        col = 0;\n        return;\n      }\n      var content = \"\";\n      // replace tabs\n      for (var pos = 0; ;) {\n        var idx = text.indexOf(\"\\t\", pos);\n        if (idx == -1) {\n          content += text.slice(pos);\n          col += text.length - pos;\n          break;\n        } else {\n          col += idx - pos;\n          content += text.slice(pos, idx);\n          var size = tabSize - col % tabSize;\n          col += size;\n          for (var i = 0; i < size; ++i) content += \" \";\n          pos = idx + 1;\n        }\n      }\n\n      if (style) {\n        var sp = node.appendChild(document.createElement(\"span\"));\n        sp.className = \"cm-\" + style.replace(/ +/g, \" cm-\");\n        sp.appendChild(document.createTextNode(content));\n      } else {\n        node.appendChild(document.createTextNode(content));\n      }\n    };\n  }\n\n  var lines = splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);\n  for (var i = 0, e = lines.length; i < e; ++i) {\n    if (i) callback(\"\\n\");\n    var stream = new CodeMirror.StringStream(lines[i]);\n    if (!stream.string && mode.blankLine) mode.blankLine(state);\n    while (!stream.eol()) {\n      var style = mode.token(stream, state);\n      callback(stream.current(), style, i, stream.start, state);\n      stream.start = stream.pos;\n    }\n  }\n};\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/addon/runmode/runmode.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.runMode = function(string, modespec, callback, options) {\n  var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);\n  var ie = /MSIE \\d/.test(navigator.userAgent);\n  var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);\n\n  if (callback.appendChild) {\n    var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;\n    var node = callback, col = 0;\n    node.innerHTML = \"\";\n    callback = function(text, style) {\n      if (text == \"\\n\") {\n        // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.\n        // Emitting a carriage return makes everything ok.\n        node.appendChild(document.createTextNode(ie_lt9 ? '\\r' : text));\n        col = 0;\n        return;\n      }\n      var content = \"\";\n      // replace tabs\n      for (var pos = 0;;) {\n        var idx = text.indexOf(\"\\t\", pos);\n        if (idx == -1) {\n          content += text.slice(pos);\n          col += text.length - pos;\n          break;\n        } else {\n          col += idx - pos;\n          content += text.slice(pos, idx);\n          var size = tabSize - col % tabSize;\n          col += size;\n          for (var i = 0; i < size; ++i) content += \" \";\n          pos = idx + 1;\n        }\n      }\n\n      if (style) {\n        var sp = node.appendChild(document.createElement(\"span\"));\n        sp.className = \"cm-\" + style.replace(/ +/g, \" cm-\");\n        sp.appendChild(document.createTextNode(content));\n      } else {\n        node.appendChild(document.createTextNode(content));\n      }\n    };\n  }\n\n  var lines = CodeMirror.splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);\n  for (var i = 0, e = lines.length; i < e; ++i) {\n    if (i) callback(\"\\n\");\n    var stream = new CodeMirror.StringStream(lines[i]);\n    if (!stream.string && mode.blankLine) mode.blankLine(state);\n    while (!stream.eol()) {\n      var style = mode.token(stream, state);\n      callback(stream.current(), style, i, stream.start, state);\n      stream.start = stream.pos;\n    }\n  }\n};\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/runmode/runmode.node.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/* Just enough of CodeMirror to run runMode under node.js */\n\nfunction splitLines(string){return string.split(/\\r\\n?|\\n/);};\n\n// Counts the column offset in a string, taking tabs into account.\n// Used mostly to find indentation.\nvar countColumn = exports.countColumn = function(string, end, tabSize, startIndex, startValue) {\n  if (end == null) {\n    end = string.search(/[^\\s\\u00a0]/);\n    if (end == -1) end = string.length;\n  }\n  for (var i = startIndex || 0, n = startValue || 0;;) {\n    var nextTab = string.indexOf(\"\\t\", i);\n    if (nextTab < 0 || nextTab >= end)\n      return n + (end - i);\n    n += nextTab - i;\n    n += tabSize - (n % tabSize);\n    i = nextTab + 1;\n  }\n};\n\nfunction StringStream(string, tabSize, context) {\n  this.pos = this.start = 0;\n  this.string = string;\n  this.tabSize = tabSize || 8;\n  this.lastColumnPos = this.lastColumnValue = 0;\n  this.lineStart = 0;\n  this.context = context\n};\n\nStringStream.prototype = {\n  eol: function() {return this.pos >= this.string.length;},\n  sol: function() {return this.pos == this.lineStart;},\n  peek: function() {return this.string.charAt(this.pos) || undefined;},\n  next: function() {\n    if (this.pos < this.string.length)\n      return this.string.charAt(this.pos++);\n  },\n  eat: function(match) {\n    var ch = this.string.charAt(this.pos);\n    if (typeof match == \"string\") var ok = ch == match;\n    else var ok = ch && (match.test ? match.test(ch) : match(ch));\n    if (ok) {++this.pos; return ch;}\n  },\n  eatWhile: function(match) {\n    var start = this.pos;\n    while (this.eat(match)){}\n    return this.pos > start;\n  },\n  eatSpace: function() {\n    var start = this.pos;\n    while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;\n    return this.pos > start;\n  },\n  skipToEnd: function() {this.pos = this.string.length;},\n  skipTo: function(ch) {\n    var found = this.string.indexOf(ch, this.pos);\n    if (found > -1) {this.pos = found; return true;}\n  },\n  backUp: function(n) {this.pos -= n;},\n  column: function() {\n    if (this.lastColumnPos < this.start) {\n      this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);\n      this.lastColumnPos = this.start;\n    }\n    return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);\n  },\n  indentation: function() {\n    return countColumn(this.string, null, this.tabSize) -\n      (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);\n  },\n  match: function(pattern, consume, caseInsensitive) {\n    if (typeof pattern == \"string\") {\n      var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};\n      var substr = this.string.substr(this.pos, pattern.length);\n      if (cased(substr) == cased(pattern)) {\n        if (consume !== false) this.pos += pattern.length;\n        return true;\n      }\n    } else {\n      var match = this.string.slice(this.pos).match(pattern);\n      if (match && match.index > 0) return null;\n      if (match && consume !== false) this.pos += match[0].length;\n      return match;\n    }\n  },\n  current: function(){return this.string.slice(this.start, this.pos);},\n  hideFirstChars: function(n, inner) {\n    this.lineStart += n;\n    try { return inner(); }\n    finally { this.lineStart -= n; }\n  },\n  lookAhead: function(n) {\n    var line = this.context.line + n\n    return line >= this.context.lines.length ? null : this.context.lines[line]\n  }\n};\nexports.StringStream = StringStream;\n\nexports.startState = function(mode, a1, a2) {\n  return mode.startState ? mode.startState(a1, a2) : true;\n};\n\nvar modes = exports.modes = {}, mimeModes = exports.mimeModes = {};\nexports.defineMode = function(name, mode) {\n  if (arguments.length > 2)\n    mode.dependencies = Array.prototype.slice.call(arguments, 2);\n  modes[name] = mode;\n};\nexports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; };\n\nexports.defineMode(\"null\", function() {\n  return {token: function(stream) {stream.skipToEnd();}};\n});\nexports.defineMIME(\"text/plain\", \"null\");\n\nexports.resolveMode = function(spec) {\n  if (typeof spec == \"string\" && mimeModes.hasOwnProperty(spec)) {\n    spec = mimeModes[spec];\n  } else if (spec && typeof spec.name == \"string\" && mimeModes.hasOwnProperty(spec.name)) {\n    spec = mimeModes[spec.name];\n  }\n  if (typeof spec == \"string\") return {name: spec};\n  else return spec || {name: \"null\"};\n};\n\nfunction copyObj(obj, target, overwrite) {\n  if (!target) target = {};\n  for (var prop in obj)\n    if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))\n      target[prop] = obj[prop];\n  return target;\n}\n\n// This can be used to attach properties to mode objects from\n// outside the actual mode definition.\nvar modeExtensions = exports.modeExtensions = {};\nexports.extendMode = function(mode, properties) {\n  var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});\n  copyObj(properties, exts);\n};\n\nexports.getMode = function(options, spec) {\n  var spec = exports.resolveMode(spec);\n  var mfactory = modes[spec.name];\n  if (!mfactory) return exports.getMode(options, \"text/plain\");\n  var modeObj = mfactory(options, spec);\n  if (modeExtensions.hasOwnProperty(spec.name)) {\n    var exts = modeExtensions[spec.name];\n    for (var prop in exts) {\n      if (!exts.hasOwnProperty(prop)) continue;\n      if (modeObj.hasOwnProperty(prop)) modeObj[\"_\" + prop] = modeObj[prop];\n      modeObj[prop] = exts[prop];\n    }\n  }\n  modeObj.name = spec.name;\n  if (spec.helperType) modeObj.helperType = spec.helperType;\n  if (spec.modeProps) for (var prop in spec.modeProps)\n    modeObj[prop] = spec.modeProps[prop];\n\n  return modeObj;\n};\n\nexports.innerMode = function(mode, state) {\n  var info;\n  while (mode.innerMode) {\n    info = mode.innerMode(state);\n    if (!info || info.mode == mode) break;\n    state = info.state;\n    mode = info.mode;\n  }\n  return info || {mode: mode, state: state};\n}\n\nexports.registerHelper = exports.registerGlobalHelper = Math.min;\n\nexports.runMode = function(string, modespec, callback, options) {\n  var mode = exports.getMode({indentUnit: 2}, modespec);\n  var lines = splitLines(string), state = (options && options.state) || exports.startState(mode);\n  var context = {lines: lines, line: 0}\n  for (var i = 0, e = lines.length; i < e; ++i, ++context.line) {\n    if (i) callback(\"\\n\");\n    var stream = new exports.StringStream(lines[i], 4, context);\n    if (!stream.string && mode.blankLine) mode.blankLine(state);\n    while (!stream.eol()) {\n      var style = mode.token(stream, state);\n      callback(stream.current(), style, i, stream.start, state);\n      stream.start = stream.pos;\n    }\n  }\n};\n\nrequire.cache[require.resolve(\"../../lib/codemirror\")] = require.cache[require.resolve(\"./runmode.node\")];\nrequire.cache[require.resolve(\"../../addon/runmode/runmode\")] = require.cache[require.resolve(\"./runmode.node\")];\n"
  },
  {
    "path": "third_party/CodeMirror/addon/scroll/annotatescrollbar.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineExtension(\"annotateScrollbar\", function(options) {\n    if (typeof options == \"string\") options = {className: options};\n    return new Annotation(this, options);\n  });\n\n  CodeMirror.defineOption(\"scrollButtonHeight\", 0);\n\n  function Annotation(cm, options) {\n    this.cm = cm;\n    this.options = options;\n    this.buttonHeight = options.scrollButtonHeight || cm.getOption(\"scrollButtonHeight\");\n    this.annotations = [];\n    this.doRedraw = this.doUpdate = null;\n    this.div = cm.getWrapperElement().appendChild(document.createElement(\"div\"));\n    this.div.style.cssText = \"position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none\";\n    this.computeScale();\n\n    function scheduleRedraw(delay) {\n      clearTimeout(self.doRedraw);\n      self.doRedraw = setTimeout(function() { self.redraw(); }, delay);\n    }\n\n    var self = this;\n    cm.on(\"refresh\", this.resizeHandler = function() {\n      clearTimeout(self.doUpdate);\n      self.doUpdate = setTimeout(function() {\n        if (self.computeScale()) scheduleRedraw(20);\n      }, 100);\n    });\n    cm.on(\"markerAdded\", this.resizeHandler);\n    cm.on(\"markerCleared\", this.resizeHandler);\n    if (options.listenForChanges !== false)\n      cm.on(\"change\", this.changeHandler = function() {\n        scheduleRedraw(250);\n      });\n  }\n\n  Annotation.prototype.computeScale = function() {\n    var cm = this.cm;\n    var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight - this.buttonHeight * 2) /\n      cm.getScrollerElement().scrollHeight\n    if (hScale != this.hScale) {\n      this.hScale = hScale;\n      return true;\n    }\n  };\n\n  Annotation.prototype.update = function(annotations) {\n    this.annotations = annotations;\n    this.redraw();\n  };\n\n  Annotation.prototype.redraw = function(compute) {\n    if (compute !== false) this.computeScale();\n    var cm = this.cm, hScale = this.hScale;\n\n    var frag = document.createDocumentFragment(), anns = this.annotations;\n\n    var wrapping = cm.getOption(\"lineWrapping\");\n    var singleLineH = wrapping && cm.defaultTextHeight() * 1.5;\n    var curLine = null, curLineObj = null;\n    function getY(pos, top) {\n      if (curLine != pos.line) {\n        curLine = pos.line;\n        curLineObj = cm.getLineHandle(curLine);\n      }\n      if ((curLineObj.widgets && curLineObj.widgets.length) ||\n          (wrapping && curLineObj.height > singleLineH))\n        return cm.charCoords(pos, \"local\")[top ? \"top\" : \"bottom\"];\n      var topY = cm.heightAtLine(curLineObj, \"local\");\n      return topY + (top ? 0 : curLineObj.height);\n    }\n\n    var lastLine = cm.lastLine()\n    if (cm.display.barWidth) for (var i = 0, nextTop; i < anns.length; i++) {\n      var ann = anns[i];\n      if (ann.to.line > lastLine) continue;\n      var top = nextTop || getY(ann.from, true) * hScale;\n      var bottom = getY(ann.to, false) * hScale;\n      while (i < anns.length - 1) {\n        if (anns[i + 1].to.line > lastLine) break;\n        nextTop = getY(anns[i + 1].from, true) * hScale;\n        if (nextTop > bottom + .9) break;\n        ann = anns[++i];\n        bottom = getY(ann.to, false) * hScale;\n      }\n      if (bottom == top) continue;\n      var height = Math.max(bottom - top, 3);\n\n      var elt = frag.appendChild(document.createElement(\"div\"));\n      elt.style.cssText = \"position: absolute; right: 0px; width: \" + Math.max(cm.display.barWidth - 1, 2) + \"px; top: \"\n        + (top + this.buttonHeight) + \"px; height: \" + height + \"px\";\n      elt.className = this.options.className;\n      if (ann.id) {\n        elt.setAttribute(\"annotation-id\", ann.id);\n      }\n    }\n    this.div.textContent = \"\";\n    this.div.appendChild(frag);\n  };\n\n  Annotation.prototype.clear = function() {\n    this.cm.off(\"refresh\", this.resizeHandler);\n    this.cm.off(\"markerAdded\", this.resizeHandler);\n    this.cm.off(\"markerCleared\", this.resizeHandler);\n    if (this.changeHandler) this.cm.off(\"change\", this.changeHandler);\n    this.div.parentNode.removeChild(this.div);\n  };\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/scroll/scrollpastend.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineOption(\"scrollPastEnd\", false, function(cm, val, old) {\n    if (old && old != CodeMirror.Init) {\n      cm.off(\"change\", onChange);\n      cm.off(\"refresh\", updateBottomMargin);\n      cm.display.lineSpace.parentNode.style.paddingBottom = \"\";\n      cm.state.scrollPastEndPadding = null;\n    }\n    if (val) {\n      cm.on(\"change\", onChange);\n      cm.on(\"refresh\", updateBottomMargin);\n      updateBottomMargin(cm);\n    }\n  });\n\n  function onChange(cm, change) {\n    if (CodeMirror.changeEnd(change).line == cm.lastLine())\n      updateBottomMargin(cm);\n  }\n\n  function updateBottomMargin(cm) {\n    var padding = \"\";\n    if (cm.lineCount() > 1) {\n      var totalH = cm.display.scroller.clientHeight - 30,\n          lastLineH = cm.getLineHandle(cm.lastLine()).height;\n      padding = (totalH - lastLineH) + \"px\";\n    }\n    if (cm.state.scrollPastEndPadding != padding) {\n      cm.state.scrollPastEndPadding = padding;\n      cm.display.lineSpace.parentNode.style.paddingBottom = padding;\n      cm.off(\"refresh\", updateBottomMargin);\n      cm.setSize();\n      cm.on(\"refresh\", updateBottomMargin);\n    }\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/scroll/simplescrollbars.css",
    "content": ".CodeMirror-simplescroll-horizontal div, .CodeMirror-simplescroll-vertical div {\n  position: absolute;\n  background: #ccc;\n  -moz-box-sizing: border-box;\n  box-sizing: border-box;\n  border: 1px solid #bbb;\n  border-radius: 2px;\n}\n\n.CodeMirror-simplescroll-horizontal, .CodeMirror-simplescroll-vertical {\n  position: absolute;\n  z-index: 6;\n  background: #eee;\n}\n\n.CodeMirror-simplescroll-horizontal {\n  bottom: 0; left: 0;\n  height: 8px;\n}\n.CodeMirror-simplescroll-horizontal div {\n  bottom: 0;\n  height: 100%;\n}\n\n.CodeMirror-simplescroll-vertical {\n  right: 0; top: 0;\n  width: 8px;\n}\n.CodeMirror-simplescroll-vertical div {\n  right: 0;\n  width: 100%;\n}\n\n\n.CodeMirror-overlayscroll .CodeMirror-scrollbar-filler, .CodeMirror-overlayscroll .CodeMirror-gutter-filler {\n  display: none;\n}\n\n.CodeMirror-overlayscroll-horizontal div, .CodeMirror-overlayscroll-vertical div {\n  position: absolute;\n  background: #bcd;\n  border-radius: 3px;\n}\n\n.CodeMirror-overlayscroll-horizontal, .CodeMirror-overlayscroll-vertical {\n  position: absolute;\n  z-index: 6;\n}\n\n.CodeMirror-overlayscroll-horizontal {\n  bottom: 0; left: 0;\n  height: 6px;\n}\n.CodeMirror-overlayscroll-horizontal div {\n  bottom: 0;\n  height: 100%;\n}\n\n.CodeMirror-overlayscroll-vertical {\n  right: 0; top: 0;\n  width: 6px;\n}\n.CodeMirror-overlayscroll-vertical div {\n  right: 0;\n  width: 100%;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/addon/scroll/simplescrollbars.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function Bar(cls, orientation, scroll) {\n    this.orientation = orientation;\n    this.scroll = scroll;\n    this.screen = this.total = this.size = 1;\n    this.pos = 0;\n\n    this.node = document.createElement(\"div\");\n    this.node.className = cls + \"-\" + orientation;\n    this.inner = this.node.appendChild(document.createElement(\"div\"));\n\n    var self = this;\n    CodeMirror.on(this.inner, \"mousedown\", function(e) {\n      if (e.which != 1) return;\n      CodeMirror.e_preventDefault(e);\n      var axis = self.orientation == \"horizontal\" ? \"pageX\" : \"pageY\";\n      var start = e[axis], startpos = self.pos;\n      function done() {\n        CodeMirror.off(document, \"mousemove\", move);\n        CodeMirror.off(document, \"mouseup\", done);\n      }\n      function move(e) {\n        if (e.which != 1) return done();\n        self.moveTo(startpos + (e[axis] - start) * (self.total / self.size));\n      }\n      CodeMirror.on(document, \"mousemove\", move);\n      CodeMirror.on(document, \"mouseup\", done);\n    });\n\n    CodeMirror.on(this.node, \"click\", function(e) {\n      CodeMirror.e_preventDefault(e);\n      var innerBox = self.inner.getBoundingClientRect(), where;\n      if (self.orientation == \"horizontal\")\n        where = e.clientX < innerBox.left ? -1 : e.clientX > innerBox.right ? 1 : 0;\n      else\n        where = e.clientY < innerBox.top ? -1 : e.clientY > innerBox.bottom ? 1 : 0;\n      self.moveTo(self.pos + where * self.screen);\n    });\n\n    function onWheel(e) {\n      var moved = CodeMirror.wheelEventPixels(e)[self.orientation == \"horizontal\" ? \"x\" : \"y\"];\n      var oldPos = self.pos;\n      self.moveTo(self.pos + moved);\n      if (self.pos != oldPos) CodeMirror.e_preventDefault(e);\n    }\n    CodeMirror.on(this.node, \"mousewheel\", onWheel);\n    CodeMirror.on(this.node, \"DOMMouseScroll\", onWheel);\n  }\n\n  Bar.prototype.setPos = function(pos, force) {\n    if (pos < 0) pos = 0;\n    if (pos > this.total - this.screen) pos = this.total - this.screen;\n    if (!force && pos == this.pos) return false;\n    this.pos = pos;\n    this.inner.style[this.orientation == \"horizontal\" ? \"left\" : \"top\"] =\n      (pos * (this.size / this.total)) + \"px\";\n    return true\n  };\n\n  Bar.prototype.moveTo = function(pos) {\n    if (this.setPos(pos)) this.scroll(pos, this.orientation);\n  }\n\n  var minButtonSize = 10;\n\n  Bar.prototype.update = function(scrollSize, clientSize, barSize) {\n    var sizeChanged = this.screen != clientSize || this.total != scrollSize || this.size != barSize\n    if (sizeChanged) {\n      this.screen = clientSize;\n      this.total = scrollSize;\n      this.size = barSize;\n    }\n\n    var buttonSize = this.screen * (this.size / this.total);\n    if (buttonSize < minButtonSize) {\n      this.size -= minButtonSize - buttonSize;\n      buttonSize = minButtonSize;\n    }\n    this.inner.style[this.orientation == \"horizontal\" ? \"width\" : \"height\"] =\n      buttonSize + \"px\";\n    this.setPos(this.pos, sizeChanged);\n  };\n\n  function SimpleScrollbars(cls, place, scroll) {\n    this.addClass = cls;\n    this.horiz = new Bar(cls, \"horizontal\", scroll);\n    place(this.horiz.node);\n    this.vert = new Bar(cls, \"vertical\", scroll);\n    place(this.vert.node);\n    this.width = null;\n  }\n\n  SimpleScrollbars.prototype.update = function(measure) {\n    if (this.width == null) {\n      var style = window.getComputedStyle ? window.getComputedStyle(this.horiz.node) : this.horiz.node.currentStyle;\n      if (style) this.width = parseInt(style.height);\n    }\n    var width = this.width || 0;\n\n    var needsH = measure.scrollWidth > measure.clientWidth + 1;\n    var needsV = measure.scrollHeight > measure.clientHeight + 1;\n    this.vert.node.style.display = needsV ? \"block\" : \"none\";\n    this.horiz.node.style.display = needsH ? \"block\" : \"none\";\n\n    if (needsV) {\n      this.vert.update(measure.scrollHeight, measure.clientHeight,\n                       measure.viewHeight - (needsH ? width : 0));\n      this.vert.node.style.bottom = needsH ? width + \"px\" : \"0\";\n    }\n    if (needsH) {\n      this.horiz.update(measure.scrollWidth, measure.clientWidth,\n                        measure.viewWidth - (needsV ? width : 0) - measure.barLeft);\n      this.horiz.node.style.right = needsV ? width + \"px\" : \"0\";\n      this.horiz.node.style.left = measure.barLeft + \"px\";\n    }\n\n    return {right: needsV ? width : 0, bottom: needsH ? width : 0};\n  };\n\n  SimpleScrollbars.prototype.setScrollTop = function(pos) {\n    this.vert.setPos(pos);\n  };\n\n  SimpleScrollbars.prototype.setScrollLeft = function(pos) {\n    this.horiz.setPos(pos);\n  };\n\n  SimpleScrollbars.prototype.clear = function() {\n    var parent = this.horiz.node.parentNode;\n    parent.removeChild(this.horiz.node);\n    parent.removeChild(this.vert.node);\n  };\n\n  CodeMirror.scrollbarModel.simple = function(place, scroll) {\n    return new SimpleScrollbars(\"CodeMirror-simplescroll\", place, scroll);\n  };\n  CodeMirror.scrollbarModel.overlay = function(place, scroll) {\n    return new SimpleScrollbars(\"CodeMirror-overlayscroll\", place, scroll);\n  };\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/search/jump-to-line.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Defines jumpToLine command. Uses dialog.js if present.\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../dialog/dialog\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../dialog/dialog\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function dialog(cm, text, shortText, deflt, f) {\n    if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});\n    else f(prompt(shortText, deflt));\n  }\n\n  function getJumpDialog(cm) {\n    return cm.phrase(\"Jump to line:\") + ' <input type=\"text\" style=\"width: 10em\" class=\"CodeMirror-search-field\"/> <span style=\"color: #888\" class=\"CodeMirror-search-hint\">' + cm.phrase(\"(Use line:column or scroll% syntax)\") + '</span>';\n  }\n\n  function interpretLine(cm, string) {\n    var num = Number(string)\n    if (/^[-+]/.test(string)) return cm.getCursor().line + num\n    else return num - 1\n  }\n\n  CodeMirror.commands.jumpToLine = function(cm) {\n    var cur = cm.getCursor();\n    dialog(cm, getJumpDialog(cm), cm.phrase(\"Jump to line:\"), (cur.line + 1) + \":\" + cur.ch, function(posStr) {\n      if (!posStr) return;\n\n      var match;\n      if (match = /^\\s*([\\+\\-]?\\d+)\\s*\\:\\s*(\\d+)\\s*$/.exec(posStr)) {\n        cm.setCursor(interpretLine(cm, match[1]), Number(match[2]))\n      } else if (match = /^\\s*([\\+\\-]?\\d+(\\.\\d+)?)\\%\\s*/.exec(posStr)) {\n        var line = Math.round(cm.lineCount() * Number(match[1]) / 100);\n        if (/^[-+]/.test(match[1])) line = cur.line + line + 1;\n        cm.setCursor(line - 1, cur.ch);\n      } else if (match = /^\\s*\\:?\\s*([\\+\\-]?\\d+)\\s*/.exec(posStr)) {\n        cm.setCursor(interpretLine(cm, match[1]), cur.ch);\n      }\n    });\n  };\n\n  CodeMirror.keyMap[\"default\"][\"Alt-G\"] = \"jumpToLine\";\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/search/match-highlighter.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Highlighting text that matches the selection\n//\n// Defines an option highlightSelectionMatches, which, when enabled,\n// will style strings that match the selection throughout the\n// document.\n//\n// The option can be set to true to simply enable it, or to a\n// {minChars, style, wordsOnly, showToken, delay} object to explicitly\n// configure it. minChars is the minimum amount of characters that should be\n// selected for the behavior to occur, and style is the token style to\n// apply to the matches. This will be prefixed by \"cm-\" to create an\n// actual CSS class name. If wordsOnly is enabled, the matches will be\n// highlighted only if the selected text is a word. showToken, when enabled,\n// will cause the current token to be highlighted when nothing is selected.\n// delay is used to specify how much time to wait, in milliseconds, before\n// highlighting the matches. If annotateScrollbar is enabled, the occurences\n// will be highlighted on the scrollbar via the matchesonscrollbar addon.\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"./matchesonscrollbar\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"./matchesonscrollbar\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var defaults = {\n    style: \"matchhighlight\",\n    minChars: 2,\n    delay: 100,\n    wordsOnly: false,\n    annotateScrollbar: false,\n    showToken: false,\n    trim: true\n  }\n\n  function State(options) {\n    this.options = {}\n    for (var name in defaults)\n      this.options[name] = (options && options.hasOwnProperty(name) ? options : defaults)[name]\n    this.overlay = this.timeout = null;\n    this.matchesonscroll = null;\n    this.active = false;\n  }\n\n  CodeMirror.defineOption(\"highlightSelectionMatches\", false, function(cm, val, old) {\n    if (old && old != CodeMirror.Init) {\n      removeOverlay(cm);\n      clearTimeout(cm.state.matchHighlighter.timeout);\n      cm.state.matchHighlighter = null;\n      cm.off(\"cursorActivity\", cursorActivity);\n      cm.off(\"focus\", onFocus)\n    }\n    if (val) {\n      var state = cm.state.matchHighlighter = new State(val);\n      if (cm.hasFocus()) {\n        state.active = true\n        highlightMatches(cm)\n      } else {\n        cm.on(\"focus\", onFocus)\n      }\n      cm.on(\"cursorActivity\", cursorActivity);\n    }\n  });\n\n  function cursorActivity(cm) {\n    var state = cm.state.matchHighlighter;\n    if (state.active || cm.hasFocus()) scheduleHighlight(cm, state)\n  }\n\n  function onFocus(cm) {\n    var state = cm.state.matchHighlighter\n    if (!state.active) {\n      state.active = true\n      scheduleHighlight(cm, state)\n    }\n  }\n\n  function scheduleHighlight(cm, state) {\n    clearTimeout(state.timeout);\n    state.timeout = setTimeout(function() {highlightMatches(cm);}, state.options.delay);\n  }\n\n  function addOverlay(cm, query, hasBoundary, style) {\n    var state = cm.state.matchHighlighter;\n    cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style));\n    if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) {\n      var searchFor = hasBoundary ? new RegExp(\"\\\\b\" + query.replace(/[\\\\\\[.+*?(){|^$]/g, \"\\\\$&\") + \"\\\\b\") : query;\n      state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false,\n        {className: \"CodeMirror-selection-highlight-scrollbar\"});\n    }\n  }\n\n  function removeOverlay(cm) {\n    var state = cm.state.matchHighlighter;\n    if (state.overlay) {\n      cm.removeOverlay(state.overlay);\n      state.overlay = null;\n      if (state.matchesonscroll) {\n        state.matchesonscroll.clear();\n        state.matchesonscroll = null;\n      }\n    }\n  }\n\n  function highlightMatches(cm) {\n    cm.operation(function() {\n      var state = cm.state.matchHighlighter;\n      removeOverlay(cm);\n      if (!cm.somethingSelected() && state.options.showToken) {\n        var re = state.options.showToken === true ? /[\\w$]/ : state.options.showToken;\n        var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start;\n        while (start && re.test(line.charAt(start - 1))) --start;\n        while (end < line.length && re.test(line.charAt(end))) ++end;\n        if (start < end)\n          addOverlay(cm, line.slice(start, end), re, state.options.style);\n        return;\n      }\n      var from = cm.getCursor(\"from\"), to = cm.getCursor(\"to\");\n      if (from.line != to.line) return;\n      if (state.options.wordsOnly && !isWord(cm, from, to)) return;\n      var selection = cm.getRange(from, to)\n      if (state.options.trim) selection = selection.replace(/^\\s+|\\s+$/g, \"\")\n      if (selection.length >= state.options.minChars)\n        addOverlay(cm, selection, false, state.options.style);\n    });\n  }\n\n  function isWord(cm, from, to) {\n    var str = cm.getRange(from, to);\n    if (str.match(/^\\w+$/) !== null) {\n        if (from.ch > 0) {\n            var pos = {line: from.line, ch: from.ch - 1};\n            var chr = cm.getRange(pos, from);\n            if (chr.match(/\\W/) === null) return false;\n        }\n        if (to.ch < cm.getLine(from.line).length) {\n            var pos = {line: to.line, ch: to.ch + 1};\n            var chr = cm.getRange(to, pos);\n            if (chr.match(/\\W/) === null) return false;\n        }\n        return true;\n    } else return false;\n  }\n\n  function boundariesAround(stream, re) {\n    return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) &&\n      (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos)));\n  }\n\n  function makeOverlay(query, hasBoundary, style) {\n    return {token: function(stream) {\n      if (stream.match(query) &&\n          (!hasBoundary || boundariesAround(stream, hasBoundary)))\n        return style;\n      stream.next();\n      stream.skipTo(query.charAt(0)) || stream.skipToEnd();\n    }};\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/search/matchesonscrollbar.css",
    "content": ".CodeMirror-search-match {\n  background: gold;\n  border-top: 1px solid orange;\n  border-bottom: 1px solid orange;\n  -moz-box-sizing: border-box;\n  box-sizing: border-box;\n  opacity: .5;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/addon/search/matchesonscrollbar.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"./searchcursor\"), require(\"../scroll/annotatescrollbar\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"./searchcursor\", \"../scroll/annotatescrollbar\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineExtension(\"showMatchesOnScrollbar\", function(query, caseFold, options) {\n    if (typeof options == \"string\") options = {className: options};\n    if (!options) options = {};\n    return new SearchAnnotation(this, query, caseFold, options);\n  });\n\n  function SearchAnnotation(cm, query, caseFold, options) {\n    this.cm = cm;\n    this.options = options;\n    var annotateOptions = {listenForChanges: false};\n    for (var prop in options) annotateOptions[prop] = options[prop];\n    if (!annotateOptions.className) annotateOptions.className = \"CodeMirror-search-match\";\n    this.annotation = cm.annotateScrollbar(annotateOptions);\n    this.query = query;\n    this.caseFold = caseFold;\n    this.gap = {from: cm.firstLine(), to: cm.lastLine() + 1};\n    this.matches = [];\n    this.update = null;\n\n    this.findMatches();\n    this.annotation.update(this.matches);\n\n    var self = this;\n    cm.on(\"change\", this.changeHandler = function(_cm, change) { self.onChange(change); });\n  }\n\n  var MAX_MATCHES = 1000;\n\n  SearchAnnotation.prototype.findMatches = function() {\n    if (!this.gap) return;\n    for (var i = 0; i < this.matches.length; i++) {\n      var match = this.matches[i];\n      if (match.from.line >= this.gap.to) break;\n      if (match.to.line >= this.gap.from) this.matches.splice(i--, 1);\n    }\n    var cursor = this.cm.getSearchCursor(this.query, CodeMirror.Pos(this.gap.from, 0), this.caseFold);\n    var maxMatches = this.options && this.options.maxMatches || MAX_MATCHES;\n    while (cursor.findNext()) {\n      var match = {from: cursor.from(), to: cursor.to()};\n      if (match.from.line >= this.gap.to) break;\n      this.matches.splice(i++, 0, match);\n      if (this.matches.length > maxMatches) break;\n    }\n    this.gap = null;\n  };\n\n  function offsetLine(line, changeStart, sizeChange) {\n    if (line <= changeStart) return line;\n    return Math.max(changeStart, line + sizeChange);\n  }\n\n  SearchAnnotation.prototype.onChange = function(change) {\n    var startLine = change.from.line;\n    var endLine = CodeMirror.changeEnd(change).line;\n    var sizeChange = endLine - change.to.line;\n    if (this.gap) {\n      this.gap.from = Math.min(offsetLine(this.gap.from, startLine, sizeChange), change.from.line);\n      this.gap.to = Math.max(offsetLine(this.gap.to, startLine, sizeChange), change.from.line);\n    } else {\n      this.gap = {from: change.from.line, to: endLine + 1};\n    }\n\n    if (sizeChange) for (var i = 0; i < this.matches.length; i++) {\n      var match = this.matches[i];\n      var newFrom = offsetLine(match.from.line, startLine, sizeChange);\n      if (newFrom != match.from.line) match.from = CodeMirror.Pos(newFrom, match.from.ch);\n      var newTo = offsetLine(match.to.line, startLine, sizeChange);\n      if (newTo != match.to.line) match.to = CodeMirror.Pos(newTo, match.to.ch);\n    }\n    clearTimeout(this.update);\n    var self = this;\n    this.update = setTimeout(function() { self.updateAfterChange(); }, 250);\n  };\n\n  SearchAnnotation.prototype.updateAfterChange = function() {\n    this.findMatches();\n    this.annotation.update(this.matches);\n  };\n\n  SearchAnnotation.prototype.clear = function() {\n    this.cm.off(\"change\", this.changeHandler);\n    this.annotation.clear();\n  };\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/search/search.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Define search commands. Depends on dialog.js or another\n// implementation of the openDialog method.\n\n// Replace works a little oddly -- it will do the replace on the next\n// Ctrl-G (or whatever is bound to findNext) press. You prevent a\n// replace by making sure the match is no longer selected when hitting\n// Ctrl-G.\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"./searchcursor\"), require(\"../dialog/dialog\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"./searchcursor\", \"../dialog/dialog\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function searchOverlay(query, caseInsensitive) {\n    if (typeof query == \"string\")\n      query = new RegExp(query.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, \"\\\\$&\"), caseInsensitive ? \"gi\" : \"g\");\n    else if (!query.global)\n      query = new RegExp(query.source, query.ignoreCase ? \"gi\" : \"g\");\n\n    return {token: function(stream) {\n      query.lastIndex = stream.pos;\n      var match = query.exec(stream.string);\n      if (match && match.index == stream.pos) {\n        stream.pos += match[0].length || 1;\n        return \"searching\";\n      } else if (match) {\n        stream.pos = match.index;\n      } else {\n        stream.skipToEnd();\n      }\n    }};\n  }\n\n  function SearchState() {\n    this.posFrom = this.posTo = this.lastQuery = this.query = null;\n    this.overlay = null;\n  }\n\n  function getSearchState(cm) {\n    return cm.state.search || (cm.state.search = new SearchState());\n  }\n\n  function queryCaseInsensitive(query) {\n    return typeof query == \"string\" && query == query.toLowerCase();\n  }\n\n  function getSearchCursor(cm, query, pos) {\n    // Heuristic: if the query string is all lowercase, do a case insensitive search.\n    return cm.getSearchCursor(query, pos, {caseFold: queryCaseInsensitive(query), multiline: true});\n  }\n\n  function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {\n    cm.openDialog(text, onEnter, {\n      value: deflt,\n      selectValueOnOpen: true,\n      closeOnEnter: false,\n      onClose: function() { clearSearch(cm); },\n      onKeyDown: onKeyDown\n    });\n  }\n\n  function dialog(cm, text, shortText, deflt, f) {\n    if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});\n    else f(prompt(shortText, deflt));\n  }\n\n  function confirmDialog(cm, text, shortText, fs) {\n    if (cm.openConfirm) cm.openConfirm(text, fs);\n    else if (confirm(shortText)) fs[0]();\n  }\n\n  function parseString(string) {\n    return string.replace(/\\\\(.)/g, function(_, ch) {\n      if (ch == \"n\") return \"\\n\"\n      if (ch == \"r\") return \"\\r\"\n      return ch\n    })\n  }\n\n  function parseQuery(query) {\n    var isRE = query.match(/^\\/(.*)\\/([a-z]*)$/);\n    if (isRE) {\n      try { query = new RegExp(isRE[1], isRE[2].indexOf(\"i\") == -1 ? \"\" : \"i\"); }\n      catch(e) {} // Not a regular expression after all, do a string search\n    } else {\n      query = parseString(query)\n    }\n    if (typeof query == \"string\" ? query == \"\" : query.test(\"\"))\n      query = /x^/;\n    return query;\n  }\n\n  function startSearch(cm, state, query) {\n    state.queryText = query;\n    state.query = parseQuery(query);\n    cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));\n    state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));\n    cm.addOverlay(state.overlay);\n    if (cm.showMatchesOnScrollbar) {\n      if (state.annotate) { state.annotate.clear(); state.annotate = null; }\n      state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));\n    }\n  }\n\n  function doSearch(cm, rev, persistent, immediate) {\n    var state = getSearchState(cm);\n    if (state.query) return findNext(cm, rev);\n    var q = cm.getSelection() || state.lastQuery;\n    if (q instanceof RegExp && q.source == \"x^\") q = null\n    if (persistent && cm.openDialog) {\n      var hiding = null\n      var searchNext = function(query, event) {\n        CodeMirror.e_stop(event);\n        if (!query) return;\n        if (query != state.queryText) {\n          startSearch(cm, state, query);\n          state.posFrom = state.posTo = cm.getCursor();\n        }\n        if (hiding) hiding.style.opacity = 1\n        findNext(cm, event.shiftKey, function(_, to) {\n          var dialog\n          if (to.line < 3 && document.querySelector &&\n              (dialog = cm.display.wrapper.querySelector(\".CodeMirror-dialog\")) &&\n              dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, \"window\").top)\n            (hiding = dialog).style.opacity = .4\n        })\n      };\n      persistentDialog(cm, getQueryDialog(cm), q, searchNext, function(event, query) {\n        var keyName = CodeMirror.keyName(event)\n        var extra = cm.getOption('extraKeys'), cmd = (extra && extra[keyName]) || CodeMirror.keyMap[cm.getOption(\"keyMap\")][keyName]\n        if (cmd == \"findNext\" || cmd == \"findPrev\" ||\n          cmd == \"findPersistentNext\" || cmd == \"findPersistentPrev\") {\n          CodeMirror.e_stop(event);\n          startSearch(cm, getSearchState(cm), query);\n          cm.execCommand(cmd);\n        } else if (cmd == \"find\" || cmd == \"findPersistent\") {\n          CodeMirror.e_stop(event);\n          searchNext(query, event);\n        }\n      });\n      if (immediate && q) {\n        startSearch(cm, state, q);\n        findNext(cm, rev);\n      }\n    } else {\n      dialog(cm, getQueryDialog(cm), \"Search for:\", q, function(query) {\n        if (query && !state.query) cm.operation(function() {\n          startSearch(cm, state, query);\n          state.posFrom = state.posTo = cm.getCursor();\n          findNext(cm, rev);\n        });\n      });\n    }\n  }\n\n  function findNext(cm, rev, callback) {cm.operation(function() {\n    var state = getSearchState(cm);\n    var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);\n    if (!cursor.find(rev)) {\n      cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));\n      if (!cursor.find(rev)) return;\n    }\n    cm.setSelection(cursor.from(), cursor.to());\n    cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);\n    state.posFrom = cursor.from(); state.posTo = cursor.to();\n    if (callback) callback(cursor.from(), cursor.to())\n  });}\n\n  function clearSearch(cm) {cm.operation(function() {\n    var state = getSearchState(cm);\n    state.lastQuery = state.query;\n    if (!state.query) return;\n    state.query = state.queryText = null;\n    cm.removeOverlay(state.overlay);\n    if (state.annotate) { state.annotate.clear(); state.annotate = null; }\n  });}\n\n\n  function getQueryDialog(cm)  {\n    return '<span class=\"CodeMirror-search-label\">' + cm.phrase(\"Search:\") + '</span> <input type=\"text\" style=\"width: 10em\" class=\"CodeMirror-search-field\"/> <span style=\"color: #888\" class=\"CodeMirror-search-hint\">' + cm.phrase(\"(Use /re/ syntax for regexp search)\") + '</span>';\n  }\n  function getReplaceQueryDialog(cm) {\n    return ' <input type=\"text\" style=\"width: 10em\" class=\"CodeMirror-search-field\"/> <span style=\"color: #888\" class=\"CodeMirror-search-hint\">' + cm.phrase(\"(Use /re/ syntax for regexp search)\") + '</span>';\n  }\n  function getReplacementQueryDialog(cm) {\n    return '<span class=\"CodeMirror-search-label\">' + cm.phrase(\"With:\") + '</span> <input type=\"text\" style=\"width: 10em\" class=\"CodeMirror-search-field\"/>';\n  }\n  function getDoReplaceConfirm(cm) {\n    return '<span class=\"CodeMirror-search-label\">' + cm.phrase(\"Replace?\") + '</span> <button>' + cm.phrase(\"Yes\") + '</button> <button>' + cm.phrase(\"No\") + '</button> <button>' + cm.phrase(\"All\") + '</button> <button>' + cm.phrase(\"Stop\") + '</button> ';\n  }\n\n  function replaceAll(cm, query, text) {\n    cm.operation(function() {\n      for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {\n        if (typeof query != \"string\") {\n          var match = cm.getRange(cursor.from(), cursor.to()).match(query);\n          cursor.replace(text.replace(/\\$(\\d)/g, function(_, i) {return match[i];}));\n        } else cursor.replace(text);\n      }\n    });\n  }\n\n  function replace(cm, all) {\n    if (cm.getOption(\"readOnly\")) return;\n    var query = cm.getSelection() || getSearchState(cm).lastQuery;\n    var dialogText = '<span class=\"CodeMirror-search-label\">' + (all ? cm.phrase(\"Replace all:\") : cm.phrase(\"Replace:\")) + '</span>';\n    dialog(cm, dialogText + getReplaceQueryDialog(cm), dialogText, query, function(query) {\n      if (!query) return;\n      query = parseQuery(query);\n      dialog(cm, getReplacementQueryDialog(cm), cm.phrase(\"Replace with:\"), \"\", function(text) {\n        text = parseString(text)\n        if (all) {\n          replaceAll(cm, query, text)\n        } else {\n          clearSearch(cm);\n          var cursor = getSearchCursor(cm, query, cm.getCursor(\"from\"));\n          var advance = function() {\n            var start = cursor.from(), match;\n            if (!(match = cursor.findNext())) {\n              cursor = getSearchCursor(cm, query);\n              if (!(match = cursor.findNext()) ||\n                  (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;\n            }\n            cm.setSelection(cursor.from(), cursor.to());\n            cm.scrollIntoView({from: cursor.from(), to: cursor.to()});\n            confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase(\"Replace?\"),\n                          [function() {doReplace(match);}, advance,\n                           function() {replaceAll(cm, query, text)}]);\n          };\n          var doReplace = function(match) {\n            cursor.replace(typeof query == \"string\" ? text :\n                           text.replace(/\\$(\\d)/g, function(_, i) {return match[i];}));\n            advance();\n          };\n          advance();\n        }\n      });\n    });\n  }\n\n  CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};\n  CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};\n  CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};\n  CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};\n  CodeMirror.commands.findNext = doSearch;\n  CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};\n  CodeMirror.commands.clearSearch = clearSearch;\n  CodeMirror.commands.replace = replace;\n  CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/search/searchcursor.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"))\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod)\n  else // Plain browser env\n    mod(CodeMirror)\n})(function(CodeMirror) {\n  \"use strict\"\n  var Pos = CodeMirror.Pos\n\n  function regexpFlags(regexp) {\n    var flags = regexp.flags\n    return flags != null ? flags : (regexp.ignoreCase ? \"i\" : \"\")\n      + (regexp.global ? \"g\" : \"\")\n      + (regexp.multiline ? \"m\" : \"\")\n  }\n\n  function ensureFlags(regexp, flags) {\n    var current = regexpFlags(regexp), target = current\n    for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1)\n      target += flags.charAt(i)\n    return current == target ? regexp : new RegExp(regexp.source, target)\n  }\n\n  function maybeMultiline(regexp) {\n    return /\\\\s|\\\\n|\\n|\\\\W|\\\\D|\\[\\^/.test(regexp.source)\n  }\n\n  function searchRegexpForward(doc, regexp, start) {\n    regexp = ensureFlags(regexp, \"g\")\n    for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) {\n      regexp.lastIndex = ch\n      var string = doc.getLine(line), match = regexp.exec(string)\n      if (match)\n        return {from: Pos(line, match.index),\n                to: Pos(line, match.index + match[0].length),\n                match: match}\n    }\n  }\n\n  function searchRegexpForwardMultiline(doc, regexp, start) {\n    if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start)\n\n    regexp = ensureFlags(regexp, \"gm\")\n    var string, chunk = 1\n    for (var line = start.line, last = doc.lastLine(); line <= last;) {\n      // This grows the search buffer in exponentially-sized chunks\n      // between matches, so that nearby matches are fast and don't\n      // require concatenating the whole document (in case we're\n      // searching for something that has tons of matches), but at the\n      // same time, the amount of retries is limited.\n      for (var i = 0; i < chunk; i++) {\n        if (line > last) break\n        var curLine = doc.getLine(line++)\n        string = string == null ? curLine : string + \"\\n\" + curLine\n      }\n      chunk = chunk * 2\n      regexp.lastIndex = start.ch\n      var match = regexp.exec(string)\n      if (match) {\n        var before = string.slice(0, match.index).split(\"\\n\"), inside = match[0].split(\"\\n\")\n        var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length\n        return {from: Pos(startLine, startCh),\n                to: Pos(startLine + inside.length - 1,\n                        inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),\n                match: match}\n      }\n    }\n  }\n\n  function lastMatchIn(string, regexp) {\n    var cutOff = 0, match\n    for (;;) {\n      regexp.lastIndex = cutOff\n      var newMatch = regexp.exec(string)\n      if (!newMatch) return match\n      match = newMatch\n      cutOff = match.index + (match[0].length || 1)\n      if (cutOff == string.length) return match\n    }\n  }\n\n  function searchRegexpBackward(doc, regexp, start) {\n    regexp = ensureFlags(regexp, \"g\")\n    for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) {\n      var string = doc.getLine(line)\n      if (ch > -1) string = string.slice(0, ch)\n      var match = lastMatchIn(string, regexp)\n      if (match)\n        return {from: Pos(line, match.index),\n                to: Pos(line, match.index + match[0].length),\n                match: match}\n    }\n  }\n\n  function searchRegexpBackwardMultiline(doc, regexp, start) {\n    regexp = ensureFlags(regexp, \"gm\")\n    var string, chunk = 1\n    for (var line = start.line, first = doc.firstLine(); line >= first;) {\n      for (var i = 0; i < chunk; i++) {\n        var curLine = doc.getLine(line--)\n        string = string == null ? curLine.slice(0, start.ch) : curLine + \"\\n\" + string\n      }\n      chunk *= 2\n\n      var match = lastMatchIn(string, regexp)\n      if (match) {\n        var before = string.slice(0, match.index).split(\"\\n\"), inside = match[0].split(\"\\n\")\n        var startLine = line + before.length, startCh = before[before.length - 1].length\n        return {from: Pos(startLine, startCh),\n                to: Pos(startLine + inside.length - 1,\n                        inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),\n                match: match}\n      }\n    }\n  }\n\n  var doFold, noFold\n  if (String.prototype.normalize) {\n    doFold = function(str) { return str.normalize(\"NFD\").toLowerCase() }\n    noFold = function(str) { return str.normalize(\"NFD\") }\n  } else {\n    doFold = function(str) { return str.toLowerCase() }\n    noFold = function(str) { return str }\n  }\n\n  // Maps a position in a case-folded line back to a position in the original line\n  // (compensating for codepoints increasing in number during folding)\n  function adjustPos(orig, folded, pos, foldFunc) {\n    if (orig.length == folded.length) return pos\n    for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) {\n      if (min == max) return min\n      var mid = (min + max) >> 1\n      var len = foldFunc(orig.slice(0, mid)).length\n      if (len == pos) return mid\n      else if (len > pos) max = mid\n      else min = mid + 1\n    }\n  }\n\n  function searchStringForward(doc, query, start, caseFold) {\n    // Empty string would match anything and never progress, so we\n    // define it to match nothing instead.\n    if (!query.length) return null\n    var fold = caseFold ? doFold : noFold\n    var lines = fold(query).split(/\\r|\\n\\r?/)\n\n    search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) {\n      var orig = doc.getLine(line).slice(ch), string = fold(orig)\n      if (lines.length == 1) {\n        var found = string.indexOf(lines[0])\n        if (found == -1) continue search\n        var start = adjustPos(orig, string, found, fold) + ch\n        return {from: Pos(line, adjustPos(orig, string, found, fold) + ch),\n                to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch)}\n      } else {\n        var cutFrom = string.length - lines[0].length\n        if (string.slice(cutFrom) != lines[0]) continue search\n        for (var i = 1; i < lines.length - 1; i++)\n          if (fold(doc.getLine(line + i)) != lines[i]) continue search\n        var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1]\n        if (endString.slice(0, lastLine.length) != lastLine) continue search\n        return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch),\n                to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))}\n      }\n    }\n  }\n\n  function searchStringBackward(doc, query, start, caseFold) {\n    if (!query.length) return null\n    var fold = caseFold ? doFold : noFold\n    var lines = fold(query).split(/\\r|\\n\\r?/)\n\n    search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) {\n      var orig = doc.getLine(line)\n      if (ch > -1) orig = orig.slice(0, ch)\n      var string = fold(orig)\n      if (lines.length == 1) {\n        var found = string.lastIndexOf(lines[0])\n        if (found == -1) continue search\n        return {from: Pos(line, adjustPos(orig, string, found, fold)),\n                to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold))}\n      } else {\n        var lastLine = lines[lines.length - 1]\n        if (string.slice(0, lastLine.length) != lastLine) continue search\n        for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++)\n          if (fold(doc.getLine(start + i)) != lines[i]) continue search\n        var top = doc.getLine(line + 1 - lines.length), topString = fold(top)\n        if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search\n        return {from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)),\n                to: Pos(line, adjustPos(orig, string, lastLine.length, fold))}\n      }\n    }\n  }\n\n  function SearchCursor(doc, query, pos, options) {\n    this.atOccurrence = false\n    this.doc = doc\n    pos = pos ? doc.clipPos(pos) : Pos(0, 0)\n    this.pos = {from: pos, to: pos}\n\n    var caseFold\n    if (typeof options == \"object\") {\n      caseFold = options.caseFold\n    } else { // Backwards compat for when caseFold was the 4th argument\n      caseFold = options\n      options = null\n    }\n\n    if (typeof query == \"string\") {\n      if (caseFold == null) caseFold = false\n      this.matches = function(reverse, pos) {\n        return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold)\n      }\n    } else {\n      query = ensureFlags(query, \"gm\")\n      if (!options || options.multiline !== false)\n        this.matches = function(reverse, pos) {\n          return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos)\n        }\n      else\n        this.matches = function(reverse, pos) {\n          return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos)\n        }\n    }\n  }\n\n  SearchCursor.prototype = {\n    findNext: function() {return this.find(false)},\n    findPrevious: function() {return this.find(true)},\n\n    find: function(reverse) {\n      var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to))\n\n      // Implements weird auto-growing behavior on null-matches for\n      // backwards-compatiblity with the vim code (unfortunately)\n      while (result && CodeMirror.cmpPos(result.from, result.to) == 0) {\n        if (reverse) {\n          if (result.from.ch) result.from = Pos(result.from.line, result.from.ch - 1)\n          else if (result.from.line == this.doc.firstLine()) result = null\n          else result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1)))\n        } else {\n          if (result.to.ch < this.doc.getLine(result.to.line).length) result.to = Pos(result.to.line, result.to.ch + 1)\n          else if (result.to.line == this.doc.lastLine()) result = null\n          else result = this.matches(reverse, Pos(result.to.line + 1, 0))\n        }\n      }\n\n      if (result) {\n        this.pos = result\n        this.atOccurrence = true\n        return this.pos.match || true\n      } else {\n        var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0)\n        this.pos = {from: end, to: end}\n        return this.atOccurrence = false\n      }\n    },\n\n    from: function() {if (this.atOccurrence) return this.pos.from},\n    to: function() {if (this.atOccurrence) return this.pos.to},\n\n    replace: function(newText, origin) {\n      if (!this.atOccurrence) return\n      var lines = CodeMirror.splitLines(newText)\n      this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin)\n      this.pos.to = Pos(this.pos.from.line + lines.length - 1,\n                        lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0))\n    }\n  }\n\n  CodeMirror.defineExtension(\"getSearchCursor\", function(query, pos, caseFold) {\n    return new SearchCursor(this.doc, query, pos, caseFold)\n  })\n  CodeMirror.defineDocExtension(\"getSearchCursor\", function(query, pos, caseFold) {\n    return new SearchCursor(this, query, pos, caseFold)\n  })\n\n  CodeMirror.defineExtension(\"selectMatches\", function(query, caseFold) {\n    var ranges = []\n    var cur = this.getSearchCursor(query, this.getCursor(\"from\"), caseFold)\n    while (cur.findNext()) {\n      if (CodeMirror.cmpPos(cur.to(), this.getCursor(\"to\")) > 0) break\n      ranges.push({anchor: cur.from(), head: cur.to()})\n    }\n    if (ranges.length)\n      this.setSelections(ranges, 0)\n  })\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/selection/active-line.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n  var WRAP_CLASS = \"CodeMirror-activeline\";\n  var BACK_CLASS = \"CodeMirror-activeline-background\";\n  var GUTT_CLASS = \"CodeMirror-activeline-gutter\";\n\n  CodeMirror.defineOption(\"styleActiveLine\", false, function(cm, val, old) {\n    var prev = old == CodeMirror.Init ? false : old;\n    if (val == prev) return\n    if (prev) {\n      cm.off(\"beforeSelectionChange\", selectionChange);\n      clearActiveLines(cm);\n      delete cm.state.activeLines;\n    }\n    if (val) {\n      cm.state.activeLines = [];\n      updateActiveLines(cm, cm.listSelections());\n      cm.on(\"beforeSelectionChange\", selectionChange);\n    }\n  });\n\n  function clearActiveLines(cm) {\n    for (var i = 0; i < cm.state.activeLines.length; i++) {\n      cm.removeLineClass(cm.state.activeLines[i], \"wrap\", WRAP_CLASS);\n      cm.removeLineClass(cm.state.activeLines[i], \"background\", BACK_CLASS);\n      cm.removeLineClass(cm.state.activeLines[i], \"gutter\", GUTT_CLASS);\n    }\n  }\n\n  function sameArray(a, b) {\n    if (a.length != b.length) return false;\n    for (var i = 0; i < a.length; i++)\n      if (a[i] != b[i]) return false;\n    return true;\n  }\n\n  function updateActiveLines(cm, ranges) {\n    var active = [];\n    for (var i = 0; i < ranges.length; i++) {\n      var range = ranges[i];\n      var option = cm.getOption(\"styleActiveLine\");\n      if (typeof option == \"object\" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())\n        continue\n      var line = cm.getLineHandleVisualStart(range.head.line);\n      if (active[active.length - 1] != line) active.push(line);\n    }\n    if (sameArray(cm.state.activeLines, active)) return;\n    cm.operation(function() {\n      clearActiveLines(cm);\n      for (var i = 0; i < active.length; i++) {\n        cm.addLineClass(active[i], \"wrap\", WRAP_CLASS);\n        cm.addLineClass(active[i], \"background\", BACK_CLASS);\n        cm.addLineClass(active[i], \"gutter\", GUTT_CLASS);\n      }\n      cm.state.activeLines = active;\n    });\n  }\n\n  function selectionChange(cm, sel) {\n    updateActiveLines(cm, sel.ranges);\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/selection/mark-selection.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Because sometimes you need to mark the selected *text*.\n//\n// Adds an option 'styleSelectedText' which, when enabled, gives\n// selected text the CSS class given as option value, or\n// \"CodeMirror-selectedtext\" when the value is not a string.\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineOption(\"styleSelectedText\", false, function(cm, val, old) {\n    var prev = old && old != CodeMirror.Init;\n    if (val && !prev) {\n      cm.state.markedSelection = [];\n      cm.state.markedSelectionStyle = typeof val == \"string\" ? val : \"CodeMirror-selectedtext\";\n      reset(cm);\n      cm.on(\"cursorActivity\", onCursorActivity);\n      cm.on(\"change\", onChange);\n    } else if (!val && prev) {\n      cm.off(\"cursorActivity\", onCursorActivity);\n      cm.off(\"change\", onChange);\n      clear(cm);\n      cm.state.markedSelection = cm.state.markedSelectionStyle = null;\n    }\n  });\n\n  function onCursorActivity(cm) {\n    if (cm.state.markedSelection)\n      cm.operation(function() { update(cm); });\n  }\n\n  function onChange(cm) {\n    if (cm.state.markedSelection && cm.state.markedSelection.length)\n      cm.operation(function() { clear(cm); });\n  }\n\n  var CHUNK_SIZE = 8;\n  var Pos = CodeMirror.Pos;\n  var cmp = CodeMirror.cmpPos;\n\n  function coverRange(cm, from, to, addAt) {\n    if (cmp(from, to) == 0) return;\n    var array = cm.state.markedSelection;\n    var cls = cm.state.markedSelectionStyle;\n    for (var line = from.line;;) {\n      var start = line == from.line ? from : Pos(line, 0);\n      var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;\n      var end = atEnd ? to : Pos(endLine, 0);\n      var mark = cm.markText(start, end, {className: cls});\n      if (addAt == null) array.push(mark);\n      else array.splice(addAt++, 0, mark);\n      if (atEnd) break;\n      line = endLine;\n    }\n  }\n\n  function clear(cm) {\n    var array = cm.state.markedSelection;\n    for (var i = 0; i < array.length; ++i) array[i].clear();\n    array.length = 0;\n  }\n\n  function reset(cm) {\n    clear(cm);\n    var ranges = cm.listSelections();\n    for (var i = 0; i < ranges.length; i++)\n      coverRange(cm, ranges[i].from(), ranges[i].to());\n  }\n\n  function update(cm) {\n    if (!cm.somethingSelected()) return clear(cm);\n    if (cm.listSelections().length > 1) return reset(cm);\n\n    var from = cm.getCursor(\"start\"), to = cm.getCursor(\"end\");\n\n    var array = cm.state.markedSelection;\n    if (!array.length) return coverRange(cm, from, to);\n\n    var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();\n    if (!coverStart || !coverEnd || to.line - from.line <= CHUNK_SIZE ||\n        cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)\n      return reset(cm);\n\n    while (cmp(from, coverStart.from) > 0) {\n      array.shift().clear();\n      coverStart = array[0].find();\n    }\n    if (cmp(from, coverStart.from) < 0) {\n      if (coverStart.to.line - from.line < CHUNK_SIZE) {\n        array.shift().clear();\n        coverRange(cm, from, coverStart.to, 0);\n      } else {\n        coverRange(cm, from, coverStart.from, 0);\n      }\n    }\n\n    while (cmp(to, coverEnd.to) < 0) {\n      array.pop().clear();\n      coverEnd = array[array.length - 1].find();\n    }\n    if (cmp(to, coverEnd.to) > 0) {\n      if (to.line - coverEnd.from.line < CHUNK_SIZE) {\n        array.pop().clear();\n        coverRange(cm, coverEnd.from, to);\n      } else {\n        coverRange(cm, coverEnd.to, to);\n      }\n    }\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/selection/selection-pointer.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineOption(\"selectionPointer\", false, function(cm, val) {\n    var data = cm.state.selectionPointer;\n    if (data) {\n      CodeMirror.off(cm.getWrapperElement(), \"mousemove\", data.mousemove);\n      CodeMirror.off(cm.getWrapperElement(), \"mouseout\", data.mouseout);\n      CodeMirror.off(window, \"scroll\", data.windowScroll);\n      cm.off(\"cursorActivity\", reset);\n      cm.off(\"scroll\", reset);\n      cm.state.selectionPointer = null;\n      cm.display.lineDiv.style.cursor = \"\";\n    }\n    if (val) {\n      data = cm.state.selectionPointer = {\n        value: typeof val == \"string\" ? val : \"default\",\n        mousemove: function(event) { mousemove(cm, event); },\n        mouseout: function(event) { mouseout(cm, event); },\n        windowScroll: function() { reset(cm); },\n        rects: null,\n        mouseX: null, mouseY: null,\n        willUpdate: false\n      };\n      CodeMirror.on(cm.getWrapperElement(), \"mousemove\", data.mousemove);\n      CodeMirror.on(cm.getWrapperElement(), \"mouseout\", data.mouseout);\n      CodeMirror.on(window, \"scroll\", data.windowScroll);\n      cm.on(\"cursorActivity\", reset);\n      cm.on(\"scroll\", reset);\n    }\n  });\n\n  function mousemove(cm, event) {\n    var data = cm.state.selectionPointer;\n    if (event.buttons == null ? event.which : event.buttons) {\n      data.mouseX = data.mouseY = null;\n    } else {\n      data.mouseX = event.clientX;\n      data.mouseY = event.clientY;\n    }\n    scheduleUpdate(cm);\n  }\n\n  function mouseout(cm, event) {\n    if (!cm.getWrapperElement().contains(event.relatedTarget)) {\n      var data = cm.state.selectionPointer;\n      data.mouseX = data.mouseY = null;\n      scheduleUpdate(cm);\n    }\n  }\n\n  function reset(cm) {\n    cm.state.selectionPointer.rects = null;\n    scheduleUpdate(cm);\n  }\n\n  function scheduleUpdate(cm) {\n    if (!cm.state.selectionPointer.willUpdate) {\n      cm.state.selectionPointer.willUpdate = true;\n      setTimeout(function() {\n        update(cm);\n        cm.state.selectionPointer.willUpdate = false;\n      }, 50);\n    }\n  }\n\n  function update(cm) {\n    var data = cm.state.selectionPointer;\n    if (!data) return;\n    if (data.rects == null && data.mouseX != null) {\n      data.rects = [];\n      if (cm.somethingSelected()) {\n        for (var sel = cm.display.selectionDiv.firstChild; sel; sel = sel.nextSibling)\n          data.rects.push(sel.getBoundingClientRect());\n      }\n    }\n    var inside = false;\n    if (data.mouseX != null) for (var i = 0; i < data.rects.length; i++) {\n      var rect = data.rects[i];\n      if (rect.left <= data.mouseX && rect.right >= data.mouseX &&\n          rect.top <= data.mouseY && rect.bottom >= data.mouseY)\n        inside = true;\n    }\n    var cursor = inside ? data.value : \"\";\n    if (cm.display.lineDiv.style.cursor != cursor)\n      cm.display.lineDiv.style.cursor = cursor;\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/tern/tern.css",
    "content": ".CodeMirror-Tern-completion {\n  padding-left: 22px;\n  position: relative;\n  line-height: 1.5;\n}\n.CodeMirror-Tern-completion:before {\n  position: absolute;\n  left: 2px;\n  bottom: 2px;\n  border-radius: 50%;\n  font-size: 12px;\n  font-weight: bold;\n  height: 15px;\n  width: 15px;\n  line-height: 16px;\n  text-align: center;\n  color: white;\n  -moz-box-sizing: border-box;\n  box-sizing: border-box;\n}\n.CodeMirror-Tern-completion-unknown:before {\n  content: \"?\";\n  background: #4bb;\n}\n.CodeMirror-Tern-completion-object:before {\n  content: \"O\";\n  background: #77c;\n}\n.CodeMirror-Tern-completion-fn:before {\n  content: \"F\";\n  background: #7c7;\n}\n.CodeMirror-Tern-completion-array:before {\n  content: \"A\";\n  background: #c66;\n}\n.CodeMirror-Tern-completion-number:before {\n  content: \"1\";\n  background: #999;\n}\n.CodeMirror-Tern-completion-string:before {\n  content: \"S\";\n  background: #999;\n}\n.CodeMirror-Tern-completion-bool:before {\n  content: \"B\";\n  background: #999;\n}\n\n.CodeMirror-Tern-completion-guess {\n  color: #999;\n}\n\n.CodeMirror-Tern-tooltip {\n  border: 1px solid silver;\n  border-radius: 3px;\n  color: #444;\n  padding: 2px 5px;\n  font-size: 90%;\n  font-family: monospace;\n  background-color: white;\n  white-space: pre-wrap;\n\n  max-width: 40em;\n  position: absolute;\n  z-index: 10;\n  -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);\n  -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);\n  box-shadow: 2px 3px 5px rgba(0,0,0,.2);\n\n  transition: opacity 1s;\n  -moz-transition: opacity 1s;\n  -webkit-transition: opacity 1s;\n  -o-transition: opacity 1s;\n  -ms-transition: opacity 1s;\n}\n\n.CodeMirror-Tern-hint-doc {\n  max-width: 25em;\n  margin-top: -3px;\n}\n\n.CodeMirror-Tern-fname { color: black; }\n.CodeMirror-Tern-farg { color: #70a; }\n.CodeMirror-Tern-farg-current { text-decoration: underline; }\n.CodeMirror-Tern-type { color: #07c; }\n.CodeMirror-Tern-fhint-guess { opacity: .7; }\n"
  },
  {
    "path": "third_party/CodeMirror/addon/tern/tern.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Glue code between CodeMirror and Tern.\n//\n// Create a CodeMirror.TernServer to wrap an actual Tern server,\n// register open documents (CodeMirror.Doc instances) with it, and\n// call its methods to activate the assisting functions that Tern\n// provides.\n//\n// Options supported (all optional):\n// * defs: An array of JSON definition data structures.\n// * plugins: An object mapping plugin names to configuration\n//   options.\n// * getFile: A function(name, c) that can be used to access files in\n//   the project that haven't been loaded yet. Simply do c(null) to\n//   indicate that a file is not available.\n// * fileFilter: A function(value, docName, doc) that will be applied\n//   to documents before passing them on to Tern.\n// * switchToDoc: A function(name, doc) that should, when providing a\n//   multi-file view, switch the view or focus to the named file.\n// * showError: A function(editor, message) that can be used to\n//   override the way errors are displayed.\n// * completionTip: Customize the content in tooltips for completions.\n//   Is passed a single argument—the completion's data as returned by\n//   Tern—and may return a string, DOM node, or null to indicate that\n//   no tip should be shown. By default the docstring is shown.\n// * typeTip: Like completionTip, but for the tooltips shown for type\n//   queries.\n// * responseFilter: A function(doc, query, request, error, data) that\n//   will be applied to the Tern responses before treating them\n//\n//\n// It is possible to run the Tern server in a web worker by specifying\n// these additional options:\n// * useWorker: Set to true to enable web worker mode. You'll probably\n//   want to feature detect the actual value you use here, for example\n//   !!window.Worker.\n// * workerScript: The main script of the worker. Point this to\n//   wherever you are hosting worker.js from this directory.\n// * workerDeps: An array of paths pointing (relative to workerScript)\n//   to the Acorn and Tern libraries and any Tern plugins you want to\n//   load. Or, if you minified those into a single script and included\n//   them in the workerScript, simply leave this undefined.\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n  // declare global: tern\n\n  CodeMirror.TernServer = function(options) {\n    var self = this;\n    this.options = options || {};\n    var plugins = this.options.plugins || (this.options.plugins = {});\n    if (!plugins.doc_comment) plugins.doc_comment = true;\n    this.docs = Object.create(null);\n    if (this.options.useWorker) {\n      this.server = new WorkerServer(this);\n    } else {\n      this.server = new tern.Server({\n        getFile: function(name, c) { return getFile(self, name, c); },\n        async: true,\n        defs: this.options.defs || [],\n        plugins: plugins\n      });\n    }\n    this.trackChange = function(doc, change) { trackChange(self, doc, change); };\n\n    this.cachedArgHints = null;\n    this.activeArgHints = null;\n    this.jumpStack = [];\n\n    this.getHint = function(cm, c) { return hint(self, cm, c); };\n    this.getHint.async = true;\n  };\n\n  CodeMirror.TernServer.prototype = {\n    addDoc: function(name, doc) {\n      var data = {doc: doc, name: name, changed: null};\n      this.server.addFile(name, docValue(this, data));\n      CodeMirror.on(doc, \"change\", this.trackChange);\n      return this.docs[name] = data;\n    },\n\n    delDoc: function(id) {\n      var found = resolveDoc(this, id);\n      if (!found) return;\n      CodeMirror.off(found.doc, \"change\", this.trackChange);\n      delete this.docs[found.name];\n      this.server.delFile(found.name);\n    },\n\n    hideDoc: function(id) {\n      closeArgHints(this);\n      var found = resolveDoc(this, id);\n      if (found && found.changed) sendDoc(this, found);\n    },\n\n    complete: function(cm) {\n      cm.showHint({hint: this.getHint});\n    },\n\n    showType: function(cm, pos, c) { showContextInfo(this, cm, pos, \"type\", c); },\n\n    showDocs: function(cm, pos, c) { showContextInfo(this, cm, pos, \"documentation\", c); },\n\n    updateArgHints: function(cm) { updateArgHints(this, cm); },\n\n    jumpToDef: function(cm) { jumpToDef(this, cm); },\n\n    jumpBack: function(cm) { jumpBack(this, cm); },\n\n    rename: function(cm) { rename(this, cm); },\n\n    selectName: function(cm) { selectName(this, cm); },\n\n    request: function (cm, query, c, pos) {\n      var self = this;\n      var doc = findDoc(this, cm.getDoc());\n      var request = buildRequest(this, doc, query, pos);\n      var extraOptions = request.query && this.options.queryOptions && this.options.queryOptions[request.query.type]\n      if (extraOptions) for (var prop in extraOptions) request.query[prop] = extraOptions[prop];\n\n      this.server.request(request, function (error, data) {\n        if (!error && self.options.responseFilter)\n          data = self.options.responseFilter(doc, query, request, error, data);\n        c(error, data);\n      });\n    },\n\n    destroy: function () {\n      closeArgHints(this)\n      if (this.worker) {\n        this.worker.terminate();\n        this.worker = null;\n      }\n    }\n  };\n\n  var Pos = CodeMirror.Pos;\n  var cls = \"CodeMirror-Tern-\";\n  var bigDoc = 250;\n\n  function getFile(ts, name, c) {\n    var buf = ts.docs[name];\n    if (buf)\n      c(docValue(ts, buf));\n    else if (ts.options.getFile)\n      ts.options.getFile(name, c);\n    else\n      c(null);\n  }\n\n  function findDoc(ts, doc, name) {\n    for (var n in ts.docs) {\n      var cur = ts.docs[n];\n      if (cur.doc == doc) return cur;\n    }\n    if (!name) for (var i = 0;; ++i) {\n      n = \"[doc\" + (i || \"\") + \"]\";\n      if (!ts.docs[n]) { name = n; break; }\n    }\n    return ts.addDoc(name, doc);\n  }\n\n  function resolveDoc(ts, id) {\n    if (typeof id == \"string\") return ts.docs[id];\n    if (id instanceof CodeMirror) id = id.getDoc();\n    if (id instanceof CodeMirror.Doc) return findDoc(ts, id);\n  }\n\n  function trackChange(ts, doc, change) {\n    var data = findDoc(ts, doc);\n\n    var argHints = ts.cachedArgHints;\n    if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) >= 0)\n      ts.cachedArgHints = null;\n\n    var changed = data.changed;\n    if (changed == null)\n      data.changed = changed = {from: change.from.line, to: change.from.line};\n    var end = change.from.line + (change.text.length - 1);\n    if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);\n    if (end >= changed.to) changed.to = end + 1;\n    if (changed.from > change.from.line) changed.from = change.from.line;\n\n    if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {\n      if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);\n    }, 200);\n  }\n\n  function sendDoc(ts, doc) {\n    ts.server.request({files: [{type: \"full\", name: doc.name, text: docValue(ts, doc)}]}, function(error) {\n      if (error) window.console.error(error);\n      else doc.changed = null;\n    });\n  }\n\n  // Completion\n\n  function hint(ts, cm, c) {\n    ts.request(cm, {type: \"completions\", types: true, docs: true, urls: true}, function(error, data) {\n      if (error) return showError(ts, cm, error);\n      var completions = [], after = \"\";\n      var from = data.start, to = data.end;\n      if (cm.getRange(Pos(from.line, from.ch - 2), from) == \"[\\\"\" &&\n          cm.getRange(to, Pos(to.line, to.ch + 2)) != \"\\\"]\")\n        after = \"\\\"]\";\n\n      for (var i = 0; i < data.completions.length; ++i) {\n        var completion = data.completions[i], className = typeToIcon(completion.type);\n        if (data.guess) className += \" \" + cls + \"guess\";\n        completions.push({text: completion.name + after,\n                          displayText: completion.displayName || completion.name,\n                          className: className,\n                          data: completion});\n      }\n\n      var obj = {from: from, to: to, list: completions};\n      var tooltip = null;\n      CodeMirror.on(obj, \"close\", function() { remove(tooltip); });\n      CodeMirror.on(obj, \"update\", function() { remove(tooltip); });\n      CodeMirror.on(obj, \"select\", function(cur, node) {\n        remove(tooltip);\n        var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;\n        if (content) {\n          tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,\n                                node.getBoundingClientRect().top + window.pageYOffset, content);\n          tooltip.className += \" \" + cls + \"hint-doc\";\n        }\n      });\n      c(obj);\n    });\n  }\n\n  function typeToIcon(type) {\n    var suffix;\n    if (type == \"?\") suffix = \"unknown\";\n    else if (type == \"number\" || type == \"string\" || type == \"bool\") suffix = type;\n    else if (/^fn\\(/.test(type)) suffix = \"fn\";\n    else if (/^\\[/.test(type)) suffix = \"array\";\n    else suffix = \"object\";\n    return cls + \"completion \" + cls + \"completion-\" + suffix;\n  }\n\n  // Type queries\n\n  function showContextInfo(ts, cm, pos, queryName, c) {\n    ts.request(cm, queryName, function(error, data) {\n      if (error) return showError(ts, cm, error);\n      if (ts.options.typeTip) {\n        var tip = ts.options.typeTip(data);\n      } else {\n        var tip = elt(\"span\", null, elt(\"strong\", null, data.type || \"not found\"));\n        if (data.doc)\n          tip.appendChild(document.createTextNode(\" — \" + data.doc));\n        if (data.url) {\n          tip.appendChild(document.createTextNode(\" \"));\n          var child = tip.appendChild(elt(\"a\", null, \"[docs]\"));\n          child.href = data.url;\n          child.target = \"_blank\";\n        }\n      }\n      tempTooltip(cm, tip, ts);\n      if (c) c();\n    }, pos);\n  }\n\n  // Maintaining argument hints\n\n  function updateArgHints(ts, cm) {\n    closeArgHints(ts);\n\n    if (cm.somethingSelected()) return;\n    var state = cm.getTokenAt(cm.getCursor()).state;\n    var inner = CodeMirror.innerMode(cm.getMode(), state);\n    if (inner.mode.name != \"javascript\") return;\n    var lex = inner.state.lexical;\n    if (lex.info != \"call\") return;\n\n    var ch, argPos = lex.pos || 0, tabSize = cm.getOption(\"tabSize\");\n    for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {\n      var str = cm.getLine(line), extra = 0;\n      for (var pos = 0;;) {\n        var tab = str.indexOf(\"\\t\", pos);\n        if (tab == -1) break;\n        extra += tabSize - (tab + extra) % tabSize - 1;\n        pos = tab + 1;\n      }\n      ch = lex.column - extra;\n      if (str.charAt(ch) == \"(\") {found = true; break;}\n    }\n    if (!found) return;\n\n    var start = Pos(line, ch);\n    var cache = ts.cachedArgHints;\n    if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)\n      return showArgHints(ts, cm, argPos);\n\n    ts.request(cm, {type: \"type\", preferFunction: true, end: start}, function(error, data) {\n      if (error || !data.type || !(/^fn\\(/).test(data.type)) return;\n      ts.cachedArgHints = {\n        start: start,\n        type: parseFnType(data.type),\n        name: data.exprName || data.name || \"fn\",\n        guess: data.guess,\n        doc: cm.getDoc()\n      };\n      showArgHints(ts, cm, argPos);\n    });\n  }\n\n  function showArgHints(ts, cm, pos) {\n    closeArgHints(ts);\n\n    var cache = ts.cachedArgHints, tp = cache.type;\n    var tip = elt(\"span\", cache.guess ? cls + \"fhint-guess\" : null,\n                  elt(\"span\", cls + \"fname\", cache.name), \"(\");\n    for (var i = 0; i < tp.args.length; ++i) {\n      if (i) tip.appendChild(document.createTextNode(\", \"));\n      var arg = tp.args[i];\n      tip.appendChild(elt(\"span\", cls + \"farg\" + (i == pos ? \" \" + cls + \"farg-current\" : \"\"), arg.name || \"?\"));\n      if (arg.type != \"?\") {\n        tip.appendChild(document.createTextNode(\":\\u00a0\"));\n        tip.appendChild(elt(\"span\", cls + \"type\", arg.type));\n      }\n    }\n    tip.appendChild(document.createTextNode(tp.rettype ? \") ->\\u00a0\" : \")\"));\n    if (tp.rettype) tip.appendChild(elt(\"span\", cls + \"type\", tp.rettype));\n    var place = cm.cursorCoords(null, \"page\");\n    var tooltip = ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip)\n    setTimeout(function() {\n      tooltip.clear = onEditorActivity(cm, function() {\n        if (ts.activeArgHints == tooltip) closeArgHints(ts) })\n    }, 20)\n  }\n\n  function parseFnType(text) {\n    var args = [], pos = 3;\n\n    function skipMatching(upto) {\n      var depth = 0, start = pos;\n      for (;;) {\n        var next = text.charAt(pos);\n        if (upto.test(next) && !depth) return text.slice(start, pos);\n        if (/[{\\[\\(]/.test(next)) ++depth;\n        else if (/[}\\]\\)]/.test(next)) --depth;\n        ++pos;\n      }\n    }\n\n    // Parse arguments\n    if (text.charAt(pos) != \")\") for (;;) {\n      var name = text.slice(pos).match(/^([^, \\(\\[\\{]+): /);\n      if (name) {\n        pos += name[0].length;\n        name = name[1];\n      }\n      args.push({name: name, type: skipMatching(/[\\),]/)});\n      if (text.charAt(pos) == \")\") break;\n      pos += 2;\n    }\n\n    var rettype = text.slice(pos).match(/^\\) -> (.*)$/);\n\n    return {args: args, rettype: rettype && rettype[1]};\n  }\n\n  // Moving to the definition of something\n\n  function jumpToDef(ts, cm) {\n    function inner(varName) {\n      var req = {type: \"definition\", variable: varName || null};\n      var doc = findDoc(ts, cm.getDoc());\n      ts.server.request(buildRequest(ts, doc, req), function(error, data) {\n        if (error) return showError(ts, cm, error);\n        if (!data.file && data.url) { window.open(data.url); return; }\n\n        if (data.file) {\n          var localDoc = ts.docs[data.file], found;\n          if (localDoc && (found = findContext(localDoc.doc, data))) {\n            ts.jumpStack.push({file: doc.name,\n                               start: cm.getCursor(\"from\"),\n                               end: cm.getCursor(\"to\")});\n            moveTo(ts, doc, localDoc, found.start, found.end);\n            return;\n          }\n        }\n        showError(ts, cm, \"Could not find a definition.\");\n      });\n    }\n\n    if (!atInterestingExpression(cm))\n      dialog(cm, \"Jump to variable\", function(name) { if (name) inner(name); });\n    else\n      inner();\n  }\n\n  function jumpBack(ts, cm) {\n    var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];\n    if (!doc) return;\n    moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);\n  }\n\n  function moveTo(ts, curDoc, doc, start, end) {\n    doc.doc.setSelection(start, end);\n    if (curDoc != doc && ts.options.switchToDoc) {\n      closeArgHints(ts);\n      ts.options.switchToDoc(doc.name, doc.doc);\n    }\n  }\n\n  // The {line,ch} representation of positions makes this rather awkward.\n  function findContext(doc, data) {\n    var before = data.context.slice(0, data.contextOffset).split(\"\\n\");\n    var startLine = data.start.line - (before.length - 1);\n    var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);\n\n    var text = doc.getLine(startLine).slice(start.ch);\n    for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)\n      text += \"\\n\" + doc.getLine(cur);\n    if (text.slice(0, data.context.length) == data.context) return data;\n\n    var cursor = doc.getSearchCursor(data.context, 0, false);\n    var nearest, nearestDist = Infinity;\n    while (cursor.findNext()) {\n      var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;\n      if (!dist) dist = Math.abs(from.ch - start.ch);\n      if (dist < nearestDist) { nearest = from; nearestDist = dist; }\n    }\n    if (!nearest) return null;\n\n    if (before.length == 1)\n      nearest.ch += before[0].length;\n    else\n      nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);\n    if (data.start.line == data.end.line)\n      var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));\n    else\n      var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);\n    return {start: nearest, end: end};\n  }\n\n  function atInterestingExpression(cm) {\n    var pos = cm.getCursor(\"end\"), tok = cm.getTokenAt(pos);\n    if (tok.start < pos.ch && tok.type == \"comment\") return false;\n    return /[\\w)\\]]/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));\n  }\n\n  // Variable renaming\n\n  function rename(ts, cm) {\n    var token = cm.getTokenAt(cm.getCursor());\n    if (!/\\w/.test(token.string)) return showError(ts, cm, \"Not at a variable\");\n    dialog(cm, \"New name for \" + token.string, function(newName) {\n      ts.request(cm, {type: \"rename\", newName: newName, fullDocs: true}, function(error, data) {\n        if (error) return showError(ts, cm, error);\n        applyChanges(ts, data.changes);\n      });\n    });\n  }\n\n  function selectName(ts, cm) {\n    var name = findDoc(ts, cm.doc).name;\n    ts.request(cm, {type: \"refs\"}, function(error, data) {\n      if (error) return showError(ts, cm, error);\n      var ranges = [], cur = 0;\n      var curPos = cm.getCursor();\n      for (var i = 0; i < data.refs.length; i++) {\n        var ref = data.refs[i];\n        if (ref.file == name) {\n          ranges.push({anchor: ref.start, head: ref.end});\n          if (cmpPos(curPos, ref.start) >= 0 && cmpPos(curPos, ref.end) <= 0)\n            cur = ranges.length - 1;\n        }\n      }\n      cm.setSelections(ranges, cur);\n    });\n  }\n\n  var nextChangeOrig = 0;\n  function applyChanges(ts, changes) {\n    var perFile = Object.create(null);\n    for (var i = 0; i < changes.length; ++i) {\n      var ch = changes[i];\n      (perFile[ch.file] || (perFile[ch.file] = [])).push(ch);\n    }\n    for (var file in perFile) {\n      var known = ts.docs[file], chs = perFile[file];;\n      if (!known) continue;\n      chs.sort(function(a, b) { return cmpPos(b.start, a.start); });\n      var origin = \"*rename\" + (++nextChangeOrig);\n      for (var i = 0; i < chs.length; ++i) {\n        var ch = chs[i];\n        known.doc.replaceRange(ch.text, ch.start, ch.end, origin);\n      }\n    }\n  }\n\n  // Generic request-building helper\n\n  function buildRequest(ts, doc, query, pos) {\n    var files = [], offsetLines = 0, allowFragments = !query.fullDocs;\n    if (!allowFragments) delete query.fullDocs;\n    if (typeof query == \"string\") query = {type: query};\n    query.lineCharPositions = true;\n    if (query.end == null) {\n      query.end = pos || doc.doc.getCursor(\"end\");\n      if (doc.doc.somethingSelected())\n        query.start = doc.doc.getCursor(\"start\");\n    }\n    var startPos = query.start || query.end;\n\n    if (doc.changed) {\n      if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&\n          doc.changed.to - doc.changed.from < 100 &&\n          doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {\n        files.push(getFragmentAround(doc, startPos, query.end));\n        query.file = \"#0\";\n        var offsetLines = files[0].offsetLines;\n        if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);\n        query.end = Pos(query.end.line - offsetLines, query.end.ch);\n      } else {\n        files.push({type: \"full\",\n                    name: doc.name,\n                    text: docValue(ts, doc)});\n        query.file = doc.name;\n        doc.changed = null;\n      }\n    } else {\n      query.file = doc.name;\n    }\n    for (var name in ts.docs) {\n      var cur = ts.docs[name];\n      if (cur.changed && cur != doc) {\n        files.push({type: \"full\", name: cur.name, text: docValue(ts, cur)});\n        cur.changed = null;\n      }\n    }\n\n    return {query: query, files: files};\n  }\n\n  function getFragmentAround(data, start, end) {\n    var doc = data.doc;\n    var minIndent = null, minLine = null, endLine, tabSize = 4;\n    for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {\n      var line = doc.getLine(p), fn = line.search(/\\bfunction\\b/);\n      if (fn < 0) continue;\n      var indent = CodeMirror.countColumn(line, null, tabSize);\n      if (minIndent != null && minIndent <= indent) continue;\n      minIndent = indent;\n      minLine = p;\n    }\n    if (minLine == null) minLine = min;\n    var max = Math.min(doc.lastLine(), end.line + 20);\n    if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))\n      endLine = max;\n    else for (endLine = end.line + 1; endLine < max; ++endLine) {\n      var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);\n      if (indent <= minIndent) break;\n    }\n    var from = Pos(minLine, 0);\n\n    return {type: \"part\",\n            name: data.name,\n            offsetLines: from.line,\n            text: doc.getRange(from, Pos(endLine, end.line == endLine ? null : 0))};\n  }\n\n  // Generic utilities\n\n  var cmpPos = CodeMirror.cmpPos;\n\n  function elt(tagname, cls /*, ... elts*/) {\n    var e = document.createElement(tagname);\n    if (cls) e.className = cls;\n    for (var i = 2; i < arguments.length; ++i) {\n      var elt = arguments[i];\n      if (typeof elt == \"string\") elt = document.createTextNode(elt);\n      e.appendChild(elt);\n    }\n    return e;\n  }\n\n  function dialog(cm, text, f) {\n    if (cm.openDialog)\n      cm.openDialog(text + \": <input type=text>\", f);\n    else\n      f(prompt(text, \"\"));\n  }\n\n  // Tooltips\n\n  function tempTooltip(cm, content, ts) {\n    if (cm.state.ternTooltip) remove(cm.state.ternTooltip);\n    var where = cm.cursorCoords();\n    var tip = cm.state.ternTooltip = makeTooltip(where.right + 1, where.bottom, content);\n    function maybeClear() {\n      old = true;\n      if (!mouseOnTip) clear();\n    }\n    function clear() {\n      cm.state.ternTooltip = null;\n      if (tip.parentNode) fadeOut(tip)\n      clearActivity()\n    }\n    var mouseOnTip = false, old = false;\n    CodeMirror.on(tip, \"mousemove\", function() { mouseOnTip = true; });\n    CodeMirror.on(tip, \"mouseout\", function(e) {\n      var related = e.relatedTarget || e.toElement\n      if (!related || !CodeMirror.contains(tip, related)) {\n        if (old) clear();\n        else mouseOnTip = false;\n      }\n    });\n    setTimeout(maybeClear, ts.options.hintDelay ? ts.options.hintDelay : 1700);\n    var clearActivity = onEditorActivity(cm, clear)\n  }\n\n  function onEditorActivity(cm, f) {\n    cm.on(\"cursorActivity\", f)\n    cm.on(\"blur\", f)\n    cm.on(\"scroll\", f)\n    cm.on(\"setDoc\", f)\n    return function() {\n      cm.off(\"cursorActivity\", f)\n      cm.off(\"blur\", f)\n      cm.off(\"scroll\", f)\n      cm.off(\"setDoc\", f)\n    }\n  }\n\n  function makeTooltip(x, y, content) {\n    var node = elt(\"div\", cls + \"tooltip\", content);\n    node.style.left = x + \"px\";\n    node.style.top = y + \"px\";\n    document.body.appendChild(node);\n    return node;\n  }\n\n  function remove(node) {\n    var p = node && node.parentNode;\n    if (p) p.removeChild(node);\n  }\n\n  function fadeOut(tooltip) {\n    tooltip.style.opacity = \"0\";\n    setTimeout(function() { remove(tooltip); }, 1100);\n  }\n\n  function showError(ts, cm, msg) {\n    if (ts.options.showError)\n      ts.options.showError(cm, msg);\n    else\n      tempTooltip(cm, String(msg), ts);\n  }\n\n  function closeArgHints(ts) {\n    if (ts.activeArgHints) {\n      if (ts.activeArgHints.clear) ts.activeArgHints.clear()\n      remove(ts.activeArgHints)\n      ts.activeArgHints = null\n    }\n  }\n\n  function docValue(ts, doc) {\n    var val = doc.doc.getValue();\n    if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);\n    return val;\n  }\n\n  // Worker wrapper\n\n  function WorkerServer(ts) {\n    var worker = ts.worker = new Worker(ts.options.workerScript);\n    worker.postMessage({type: \"init\",\n                        defs: ts.options.defs,\n                        plugins: ts.options.plugins,\n                        scripts: ts.options.workerDeps});\n    var msgId = 0, pending = {};\n\n    function send(data, c) {\n      if (c) {\n        data.id = ++msgId;\n        pending[msgId] = c;\n      }\n      worker.postMessage(data);\n    }\n    worker.onmessage = function(e) {\n      var data = e.data;\n      if (data.type == \"getFile\") {\n        getFile(ts, data.name, function(err, text) {\n          send({type: \"getFile\", err: String(err), text: text, id: data.id});\n        });\n      } else if (data.type == \"debug\") {\n        window.console.log(data.message);\n      } else if (data.id && pending[data.id]) {\n        pending[data.id](data.err, data.body);\n        delete pending[data.id];\n      }\n    };\n    worker.onerror = function(e) {\n      for (var id in pending) pending[id](e);\n      pending = {};\n    };\n\n    this.addFile = function(name, text) { send({type: \"add\", name: name, text: text}); };\n    this.delFile = function(name) { send({type: \"del\", name: name}); };\n    this.request = function(body, c) { send({type: \"req\", body: body}, c); };\n  }\n});\n"
  },
  {
    "path": "third_party/CodeMirror/addon/tern/worker.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// declare global: tern, server\n\nvar server;\n\nthis.onmessage = function(e) {\n  var data = e.data;\n  switch (data.type) {\n  case \"init\": return startServer(data.defs, data.plugins, data.scripts);\n  case \"add\": return server.addFile(data.name, data.text);\n  case \"del\": return server.delFile(data.name);\n  case \"req\": return server.request(data.body, function(err, reqData) {\n    postMessage({id: data.id, body: reqData, err: err && String(err)});\n  });\n  case \"getFile\":\n    var c = pending[data.id];\n    delete pending[data.id];\n    return c(data.err, data.text);\n  default: throw new Error(\"Unknown message type: \" + data.type);\n  }\n};\n\nvar nextId = 0, pending = {};\nfunction getFile(file, c) {\n  postMessage({type: \"getFile\", name: file, id: ++nextId});\n  pending[nextId] = c;\n}\n\nfunction startServer(defs, plugins, scripts) {\n  if (scripts) importScripts.apply(null, scripts);\n\n  server = new tern.Server({\n    getFile: getFile,\n    async: true,\n    defs: defs,\n    plugins: plugins\n  });\n}\n\nthis.console = {\n  log: function(v) { postMessage({type: \"debug\", message: v}); }\n};\n"
  },
  {
    "path": "third_party/CodeMirror/addon/wrap/hardwrap.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var Pos = CodeMirror.Pos;\n\n  function findParagraph(cm, pos, options) {\n    var startRE = options.paragraphStart || cm.getHelper(pos, \"paragraphStart\");\n    for (var start = pos.line, first = cm.firstLine(); start > first; --start) {\n      var line = cm.getLine(start);\n      if (startRE && startRE.test(line)) break;\n      if (!/\\S/.test(line)) { ++start; break; }\n    }\n    var endRE = options.paragraphEnd || cm.getHelper(pos, \"paragraphEnd\");\n    for (var end = pos.line + 1, last = cm.lastLine(); end <= last; ++end) {\n      var line = cm.getLine(end);\n      if (endRE && endRE.test(line)) { ++end; break; }\n      if (!/\\S/.test(line)) break;\n    }\n    return {from: start, to: end};\n  }\n\n  function findBreakPoint(text, column, wrapOn, killTrailingSpace) {\n    var at = column\n    while (at < text.length && text.charAt(at) == \" \") at++\n    for (; at > 0; --at)\n      if (wrapOn.test(text.slice(at - 1, at + 1))) break;\n    for (var first = true;; first = false) {\n      var endOfText = at;\n      if (killTrailingSpace)\n        while (text.charAt(endOfText - 1) == \" \") --endOfText;\n      if (endOfText == 0 && first) at = column;\n      else return {from: endOfText, to: at};\n    }\n  }\n\n  function wrapRange(cm, from, to, options) {\n    from = cm.clipPos(from); to = cm.clipPos(to);\n    var column = options.column || 80;\n    var wrapOn = options.wrapOn || /\\s\\S|-[^\\.\\d]/;\n    var killTrailing = options.killTrailingSpace !== false;\n    var changes = [], curLine = \"\", curNo = from.line;\n    var lines = cm.getRange(from, to, false);\n    if (!lines.length) return null;\n    var leadingSpace = lines[0].match(/^[ \\t]*/)[0];\n    if (leadingSpace.length >= column) column = leadingSpace.length + 1\n\n    for (var i = 0; i < lines.length; ++i) {\n      var text = lines[i], oldLen = curLine.length, spaceInserted = 0;\n      if (curLine && text && !wrapOn.test(curLine.charAt(curLine.length - 1) + text.charAt(0))) {\n        curLine += \" \";\n        spaceInserted = 1;\n      }\n      var spaceTrimmed = \"\";\n      if (i) {\n        spaceTrimmed = text.match(/^\\s*/)[0];\n        text = text.slice(spaceTrimmed.length);\n      }\n      curLine += text;\n      if (i) {\n        var firstBreak = curLine.length > column && leadingSpace == spaceTrimmed &&\n          findBreakPoint(curLine, column, wrapOn, killTrailing);\n        // If this isn't broken, or is broken at a different point, remove old break\n        if (!firstBreak || firstBreak.from != oldLen || firstBreak.to != oldLen + spaceInserted) {\n          changes.push({text: [spaceInserted ? \" \" : \"\"],\n                        from: Pos(curNo, oldLen),\n                        to: Pos(curNo + 1, spaceTrimmed.length)});\n        } else {\n          curLine = leadingSpace + text;\n          ++curNo;\n        }\n      }\n      while (curLine.length > column) {\n        var bp = findBreakPoint(curLine, column, wrapOn, killTrailing);\n        changes.push({text: [\"\", leadingSpace],\n                      from: Pos(curNo, bp.from),\n                      to: Pos(curNo, bp.to)});\n        curLine = leadingSpace + curLine.slice(bp.to);\n        ++curNo;\n      }\n    }\n    if (changes.length) cm.operation(function() {\n      for (var i = 0; i < changes.length; ++i) {\n        var change = changes[i];\n        if (change.text || CodeMirror.cmpPos(change.from, change.to))\n          cm.replaceRange(change.text, change.from, change.to);\n      }\n    });\n    return changes.length ? {from: changes[0].from, to: CodeMirror.changeEnd(changes[changes.length - 1])} : null;\n  }\n\n  CodeMirror.defineExtension(\"wrapParagraph\", function(pos, options) {\n    options = options || {};\n    if (!pos) pos = this.getCursor();\n    var para = findParagraph(this, pos, options);\n    return wrapRange(this, Pos(para.from, 0), Pos(para.to - 1), options);\n  });\n\n  CodeMirror.commands.wrapLines = function(cm) {\n    cm.operation(function() {\n      var ranges = cm.listSelections(), at = cm.lastLine() + 1;\n      for (var i = ranges.length - 1; i >= 0; i--) {\n        var range = ranges[i], span;\n        if (range.empty()) {\n          var para = findParagraph(cm, range.head, {});\n          span = {from: Pos(para.from, 0), to: Pos(para.to - 1)};\n        } else {\n          span = {from: range.from(), to: range.to()};\n        }\n        if (span.to.line >= at) continue;\n        at = span.from.line;\n        wrapRange(cm, span.from, span.to, {});\n      }\n    });\n  };\n\n  CodeMirror.defineExtension(\"wrapRange\", function(from, to, options) {\n    return wrapRange(this, from, to, options || {});\n  });\n\n  CodeMirror.defineExtension(\"wrapParagraphsInRange\", function(from, to, options) {\n    options = options || {};\n    var cm = this, paras = [];\n    for (var line = from.line; line <= to.line;) {\n      var para = findParagraph(cm, Pos(line, 0), options);\n      paras.push(para);\n      line = para.to;\n    }\n    var madeChange = false;\n    if (paras.length) cm.operation(function() {\n      for (var i = paras.length - 1; i >= 0; --i)\n        madeChange = madeChange || wrapRange(cm, Pos(paras[i].from, 0), Pos(paras[i].to - 1), options);\n    });\n    return madeChange;\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/bin/authors.sh",
    "content": "# Combine existing list of authors with everyone known in git, sort, add header.\ntail --lines=+3 AUTHORS > AUTHORS.tmp\ngit log --format='%aN' | grep -v \"Piët Delport\" >> AUTHORS.tmp\necho -e \"List of CodeMirror contributors. Updated before every release.\\n\" > AUTHORS\nsort -u AUTHORS.tmp | sed 's/Google Inc\\./Google LLC/' >> AUTHORS\nrm -f AUTHORS.tmp\n"
  },
  {
    "path": "third_party/CodeMirror/bin/lint",
    "content": "#!/usr/bin/env node\n\nprocess.exit(require(\"../test/lint\").ok ? 0 : 1);\n"
  },
  {
    "path": "third_party/CodeMirror/bin/release",
    "content": "#!/usr/bin/env node\n\nvar fs = require(\"fs\"), child = require(\"child_process\");\n\nvar number, bumpOnly;\n\nfor (var i = 2; i < process.argv.length; i++) {\n  if (process.argv[i] == \"-bump\") bumpOnly = true;\n  else if (/^\\d+\\.\\d+\\.\\d+$/.test(process.argv[i])) number = process.argv[i];\n  else { console.log(\"Bogus command line arg: \" + process.argv[i]); process.exit(1); }\n}\n\nif (!number) { console.log(\"Must give a version\"); process.exit(1); }\n\nfunction rewrite(file, f) {\n  fs.writeFileSync(file, f(fs.readFileSync(file, \"utf8\")), \"utf8\");\n}\n\nrewrite(\"src/edit/main.js\", function(lib) {\n  return lib.replace(/CodeMirror\\.version = \"\\d+\\.\\d+\\.\\d+\"/,\n                     \"CodeMirror.version = \\\"\" + number + \"\\\"\");\n});\nfunction rewriteJSON(pack) {\n  return pack.replace(/\"version\":\\s*\"\\d+\\.\\d+\\.\\d+\"/, \"\\\"version\\\": \\\"\" + number + \"\\\"\");\n}\nrewrite(\"package.json\", rewriteJSON);\nrewrite(\"doc/manual.html\", function(manual) {\n  return manual.replace(/>version \\d+\\.\\d+\\.\\d+<\\/span>/, \">version \" + number + \"</span>\");\n});\n\nif (bumpOnly) process.exit(0);\n\nchild.exec(\"bash bin/authors.sh\", function(){});\n\nrewrite(\"index.html\", function(index) {\n  return index.replace(/\\.zip\">\\d+\\.\\d+\\.\\d+<\\/a>/,\n                       \".zip\\\">\" + number + \"</a>\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/bin/source-highlight",
    "content": "#!/usr/bin/env node\n\n// Simple command-line code highlighting tool. Reads code from stdin,\n// spits html to stdout. For example:\n//\n//   echo 'function foo(a) { return a; }' | bin/source-highlight -s javascript\n//   bin/source-highlight -s \n\nvar fs = require(\"fs\");\n\nvar CodeMirror = require(\"../addon/runmode/runmode.node.js\");\nrequire(\"../mode/meta.js\");\n\nvar sPos = process.argv.indexOf(\"-s\");\nif (sPos == -1 || sPos == process.argv.length - 1) {\n   console.error(\"Usage: source-highlight -s language\");\n   process.exit(1);\n}\nvar lang = process.argv[sPos + 1].toLowerCase(), modeName = lang;\nvar found = CodeMirror.findModeByMIME(lang) || CodeMirror.findModeByName(lang)\nif (found) {\n  modeName = found.mode\n  lang = found.mime\n}\n\nif (!CodeMirror.modes[modeName])\n  require(\"../mode/\" + modeName + \"/\" + modeName + \".js\");\n\nfunction esc(str) {\n  return str.replace(/[<&]/g, function(ch) { return ch == \"&\" ? \"&amp;\" : \"&lt;\"; });\n}\n\nvar code = fs.readFileSync(\"/dev/stdin\", \"utf8\");\nvar curStyle = null, accum = \"\";\nfunction flush() {\n  if (curStyle) process.stdout.write(\"<span class=\\\"\" + curStyle.replace(/(^|\\s+)/g, \"$1cm-\") + \"\\\">\" + esc(accum) + \"</span>\");\n  else process.stdout.write(esc(accum));\n}\n\nCodeMirror.runMode(code, lang, function(text, style) {\n  if (style != curStyle) {\n    flush();\n    curStyle = style; accum = text;\n  } else {\n    accum += text;\n  }\n});\nflush();\n"
  },
  {
    "path": "third_party/CodeMirror/bin/upload-release.js",
    "content": "\"use strict\"\n\nlet version = process.argv[2]\nlet auth = process.argv[3]\n\nif (!auth) {\n  console.log(\"Usage: upload-release.js [TAG] [github-user:password]\")\n  process.exit(1)\n}\n\nrequire('child_process').exec(\"git --no-pager show -s --format='%s' \" + version, (error, stdout) => {\n  if (error) throw error\n  let message = stdout.split(\"\\n\").slice(2)\n  message = message.slice(0, message.indexOf(\"-----BEGIN PGP SIGNATURE-----\")).join(\"\\n\")\n\n  let req = require(\"https\").request({\n    host: \"api.github.com\",\n    auth: auth,\n    headers: {\"user-agent\": \"Release uploader\"},\n    path: \"/repos/codemirror/codemirror/releases\",\n    method: \"POST\"\n  }, res => {\n    if (res.statusCode >= 300) {\n      console.error(res.statusMessage)\n      res.on(\"data\", d => console.log(d.toString()))\n      res.on(\"end\", process.exit(1))\n    }\n  })\n  req.write(JSON.stringify({\n    tag_name: version,\n    name: version,\n    body: message\n  }))\n  req.end()\n})\n"
  },
  {
    "path": "third_party/CodeMirror/demo/activeline.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Active Line Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../addon/selection/active-line.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Active Line</a>\n  </ul>\n</div>\n\n<article>\n<h2>Active Line Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<rss xmlns:atom=\"http://www.w3.org/2005/Atom\" version=\"2.0\"\n     xmlns:georss=\"http://www.georss.org/georss\"\n     xmlns:twitter=\"http://api.twitter.com\">\n  <channel>\n    <title>Twitter / codemirror</title>\n    <link>http://twitter.com/codemirror</link>\n    <atom:link type=\"application/rss+xml\"\n               href=\"http://twitter.com/statuses/user_timeline/242283288.rss\" rel=\"self\"/>\n    <description>Twitter updates from CodeMirror / codemirror.</description>\n    <language>en-us</language>\n    <ttl>40</ttl>\n  <item>\n    <title>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This one\n      uses CodeMirror as its editor.</title>\n    <description>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This\n      one uses CodeMirror as its editor.</description>\n    <pubDate>Thu, 17 Mar 2011 23:34:47 +0000</pubDate>\n    <guid>http://twitter.com/codemirror/statuses/48527733722058752</guid>\n    <link>http://twitter.com/codemirror/statuses/48527733722058752</link>\n    <twitter:source>web</twitter:source>\n    <twitter:place/>\n  </item>\n  <item>\n    <title>codemirror: Posted a description of the CodeMirror 2 internals at\n      https://codemirror.net/2/internals.html</title>\n    <description>codemirror: Posted a description of the CodeMirror 2 internals at\n      https://codemirror.net/2/internals.html</description>\n    <pubDate>Wed, 02 Mar 2011 12:15:09 +0000</pubDate>\n    <guid>http://twitter.com/codemirror/statuses/42920879788789760</guid>\n    <link>http://twitter.com/codemirror/statuses/42920879788789760</link>\n    <twitter:source>web</twitter:source>\n    <twitter:place/>\n  </item>\n  </channel>\n</rss></textarea></form>\n\n    <script>\nvar nonEmpty = false;\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  mode: \"application/xml\",\n  styleActiveLine: true,\n  lineNumbers: true,\n  lineWrapping: true\n});\n\nfunction toggleSelProp() {\n  nonEmpty = !nonEmpty;\n  editor.setOption(\"styleActiveLine\", {nonEmpty: nonEmpty});\n  var label = nonEmpty ? 'Disable nonEmpty option' : 'Enable nonEmpty option';\n  document.getElementById('toggleButton').innerText = label;\n}\n</script>\n\n    <p>Styling the current cursor line.</p>\n\n    <button onclick=\"toggleSelProp()\" id=\"toggleButton\">Enable <code>nonEmpty</code> option</button>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/anywordhint.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Any Word Completion Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/hint/show-hint.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/hint/show-hint.js\"></script>\n<script src=\"../addon/hint/anyword-hint.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Any Word Completion</a>\n  </ul>\n</div>\n\n<article>\n<h2>Any Word Completion Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n(function() {\n  \"use strict\";\n\n  var WORD = /[\\w$]+/g, RANGE = 500;\n\n  CodeMirror.registerHelper(\"hint\", \"anyword\", function(editor, options) {\n    var word = options && options.word || WORD;\n    var range = options && options.range || RANGE;\n    var cur = editor.getCursor(), curLine = editor.getLine(cur.line);\n    var start = cur.ch, end = start;\n    while (end < curLine.length && word.test(curLine.charAt(end))) ++end;\n    while (start && word.test(curLine.charAt(start - 1))) --start;\n    var curWord = start != end && curLine.slice(start, end);\n\n    var list = [], seen = {};\n    function scan(dir) {\n      var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;\n      for (; line != end; line += dir) {\n        var text = editor.getLine(line), m;\n        word.lastIndex = 0;\n        while (m = word.exec(text)) {\n          if ((!curWord || m[0].indexOf(curWord) == 0) && !seen.hasOwnProperty(m[0])) {\n            seen[m[0]] = true;\n            list.push(m[0]);\n          }\n        }\n      }\n    }\n    scan(-1);\n    scan(1);\n    return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};\n  });\n})();\n</textarea></form>\n\n<p>Press <strong>ctrl-space</strong> to activate autocompletion. The\ncompletion uses\nthe <a href=\"../doc/manual.html#addon_anyword-hint\">anyword-hint.js</a>\nmodule, which simply looks at nearby words in the buffer and completes\nto those.</p>\n\n    <script>\n      CodeMirror.commands.autocomplete = function(cm) {\n        cm.showHint({hint: CodeMirror.hint.anyword});\n      }\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        extraKeys: {\"Ctrl-Space\": \"autocomplete\"}\n      });\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/bidi.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Bi-directional Text Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<style>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n  fieldset {border: none}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Bi-directional Text</a>\n  </ul>\n</div>\n\n<article>\n<h2>Bi-directional Text Demo</h2>\n<form><textarea id=\"code\" name=\"code\"><!-- Piece of the CodeMirror manual, 'translated' into Arabic by Google Translate -->\n<!-- قطعة من دليل CodeMirror، \"ترجم\" إلى العربية بواسطة جوجل ترجمة -->\n\n<dl>\n  <dt id=option_value><code>value (string or Doc)</code></dt>\n  <dd>قيمة البداية المحرر. يمكن أن تكون سلسلة، أو. كائن مستند.</dd>\n  <dt id=option_mode><code>mode (string or object)</code></dt>\n  <dd>وضع الاستخدام. عندما لا تعطى، وهذا الافتراضي إلى الطريقة الاولى\n  التي تم تحميلها. قد يكون من سلسلة، والتي إما أسماء أو ببساطة هو وضع\n  MIME نوع المرتبطة اسطة. بدلا من ذلك، قد يكون من كائن يحتوي على\n  خيارات التكوين لواسطة، مع <code>name</code> الخاصية التي وضع أسماء\n  (على سبيل المثال <code>{name: \"javascript\", json: true}</code>).\n  صفحات التجريبي لكل وضع تحتوي على معلومات حول ما معلمات تكوين وضع\n  يدعمها. يمكنك أن تطلب CodeMirror التي تم تعريفها طرق وأنواع MIME\n  الكشف على <code>CodeMirror.modes</code>\n  و <code>CodeMirror.mimeModes</code> الكائنات. وضع خرائط الأسماء\n  الأولى لمنشئات الخاصة بهم، وخرائط لأنواع MIME 2 المواصفات\n  واسطة.</dd>\n  <dt id=option_theme><code>theme (string)</code></dt>\n  <dd>موضوع لنمط المحرر مع. يجب عليك التأكد من الملف CSS تحديد\n  المقابلة <code>.cm-s-[name]</code> يتم تحميل أنماط (انظر\n  <a href=\"../theme/\"><code>theme</code></a> الدليل في التوزيع).\n  الافتراضي هو <code>\"default\"</code> ، والتي تم تضمينها في\n  الألوان <code>codemirror.css</code>. فمن الممكن استخدام فئات متعددة\n  في تطبيق السمات مرة واحدة على سبيل المثال <code>\"foo bar\"</code>\n  سيتم تعيين كل من <code>cm-s-foo</code> و <code>cm-s-bar</code>\n  الطبقات إلى المحرر.</dd>\n</dl>\n</textarea>\n  <fieldset>\n    Editor default direction:\n    <input type=\"radio\" id=\"ltr\" name=\"direction\"/><label for=\"ltr\">LTR</label>\n    <input type=\"radio\" id=\"rtl\" name=\"direction\"/><label for=\"rtl\">RTL</label>\n  </fieldset>\n  <fieldset>\n    HTML document direction:\n    <input type=\"radio\" id=\"htmlltr\" name=\"htmldirection\"/><label for=\"htmlltr\">LTR</label>\n    <input type=\"radio\" id=\"htmlrtl\" name=\"htmldirection\"/><label for=\"htmlrtl\">RTL</label>\n  </fieldset>\n  <fieldset>\n    <input type=\"checkbox\" id=\"rtlMoveVisually\"/><label for=\"rtlMoveVisually\">Use visual order for arrow key movement.</label>\n  </fieldset>\n</form>\n\n    <script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  mode: \"text/html\",\n  lineNumbers: true,\n  lineWrapping: true,\n  direction: \"rtl\"\n});\n\nvar dirRadios = {ltr: document.getElementById(\"ltr\"),\n                 rtl: document.getElementById(\"rtl\")};\ndirRadios[editor.getOption(\"direction\")].checked = true;\ndirRadios[\"rtl\"].onchange = dirRadios[\"ltr\"].onchange = function() {\n  editor.setOption(\"direction\", dirRadios[\"rtl\"].checked ? \"rtl\" : \"ltr\");\n};\n\nvar HtmlDirRadios = {ltr: document.getElementById(\"htmlltr\"),\n                 rtl: document.getElementById(\"htmlrtl\")};\nHtmlDirRadios[\"ltr\"].checked = true;\nHtmlDirRadios[\"rtl\"].onchange = HtmlDirRadios[\"ltr\"].onchange = function() {\n  document.dir = (HtmlDirRadios[\"rtl\"].checked ? \"rtl\" : \"ltr\");\n};\n\nvar moveCheckbox = document.getElementById(\"rtlMoveVisually\");\nmoveCheckbox.checked = editor.getOption(\"rtlMoveVisually\");\nmoveCheckbox.onchange = function() {\n  editor.setOption(\"rtlMoveVisually\", moveCheckbox.checked);\n};\n</script>\n\n  <p>Demonstration of bi-directional text support. See\n  the <a href=\"http://marijnhaverbeke.nl/blog/cursor-in-bidi-text.html\">related\n  blog post</a> for more background.</p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/btree.html",
    "content": "﻿<!doctype html>\n\n<title>CodeMirror: B-Tree visualization</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<style>\n      .lineblock { display: inline-block; margin: 1px; height: 5px; }\n      .CodeMirror {border: 1px solid #aaa; height: 400px}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">B-Tree visualization</a>\n  </ul>\n</div>\n\n<article>\n<h2>B-Tree visualization</h2>\n<form><textarea id=\"code\" name=\"code\">type here, see a summary of the document b-tree below</textarea></form>\n      <div style=\"display: inline-block; height: 402px; overflow-y: auto\" id=\"output\"></div>\n\n    <script id=\"me\">\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true,\n  lineWrapping: true\n});\nvar updateTimeout;\neditor.on(\"change\", function(cm) {\n  clearTimeout(updateTimeout);\n  updateTimeout = setTimeout(updateVisual, 200);\n});\nupdateVisual();\n\nfunction updateVisual() {\n  var out = document.getElementById(\"output\");\n  out.innerHTML = \"\";\n\n  function drawTree(out, node) {\n    if (node.lines) {\n      out.appendChild(document.createElement(\"div\")).innerHTML =\n        \"<b>leaf</b>: \" + node.lines.length + \" lines, \" + Math.round(node.height) + \" px\";\n      var lines = out.appendChild(document.createElement(\"div\"));\n      lines.style.lineHeight = \"6px\"; lines.style.marginLeft = \"10px\";\n      for (var i = 0; i < node.lines.length; ++i) {\n        var line = node.lines[i], lineElt = lines.appendChild(document.createElement(\"div\"));\n        lineElt.className = \"lineblock\";\n        var gray = Math.min(line.text.length * 3, 230), col = gray.toString(16);\n        if (col.length == 1) col = \"0\" + col;\n        lineElt.style.background = \"#\" + col + col + col;\n        lineElt.style.width = Math.max(Math.round(line.height / 3), 1) + \"px\";\n      }\n    } else {\n      out.appendChild(document.createElement(\"div\")).innerHTML =\n        \"<b>node</b>: \" + node.size + \" lines, \" + Math.round(node.height) + \" px\";\n      var sub = out.appendChild(document.createElement(\"div\"));\n      sub.style.paddingLeft = \"20px\";\n      for (var i = 0; i < node.children.length; ++i)\n        drawTree(sub, node.children[i]);\n    }\n  }\n  drawTree(out, editor.getDoc());\n}\n\nfunction fillEditor() {\n  var sc = document.getElementById(\"me\");\n  var doc = (sc.textContent || sc.innerText || sc.innerHTML).replace(/^\\s*/, \"\") + \"\\n\";\n  doc += doc; doc += doc; doc += doc; doc += doc; doc += doc; doc += doc;\n  editor.setValue(doc);\n}\n    </script>\n\n<p><button onclick=\"fillEditor()\">Add a lot of content</button></p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/buffers.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Multiple Buffer & Split View Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/css/css.js\"></script>\n<style id=style>\n      .CodeMirror {border: 1px solid black; height: 250px;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Multiple Buffer & Split View</a>\n  </ul>\n</div>\n\n<article>\n<h2>Multiple Buffer & Split View Demo</h2>\n\n\n    <div id=code_top></div>\n    <div>\n      Select buffer: <select id=buffers_top></select>\n      &nbsp; &nbsp; <button onclick=\"newBuf('top')\">New buffer</button>\n    </div>\n    <div id=code_bot></div>\n    <div>\n      Select buffer: <select id=buffers_bot></select>\n      &nbsp; &nbsp; <button onclick=\"newBuf('bot')\">New buffer</button>\n    </div>\n\n    <script id=script>\nvar sel_top = document.getElementById(\"buffers_top\");\nCodeMirror.on(sel_top, \"change\", function() {\n  selectBuffer(ed_top, sel_top.options[sel_top.selectedIndex].value);\n});\n\nvar sel_bot = document.getElementById(\"buffers_bot\");\nCodeMirror.on(sel_bot, \"change\", function() {\n  selectBuffer(ed_bot, sel_bot.options[sel_bot.selectedIndex].value);\n});\n\nvar buffers = {};\n\nfunction openBuffer(name, text, mode) {\n  buffers[name] = CodeMirror.Doc(text, mode);\n  var opt = document.createElement(\"option\");\n  opt.appendChild(document.createTextNode(name));\n  sel_top.appendChild(opt);\n  sel_bot.appendChild(opt.cloneNode(true));\n}\n\nfunction newBuf(where) {\n  var name = prompt(\"Name for the buffer\", \"*scratch*\");\n  if (name == null) return;\n  if (buffers.hasOwnProperty(name)) {\n    alert(\"There's already a buffer by that name.\");\n    return;\n  }\n  openBuffer(name, \"\", \"javascript\");\n  selectBuffer(where == \"top\" ? ed_top : ed_bot, name);\n  var sel = where == \"top\" ? sel_top : sel_bot;\n  sel.value = name;\n}\n\nfunction selectBuffer(editor, name) {\n  var buf = buffers[name];\n  if (buf.getEditor()) buf = buf.linkedDoc({sharedHist: true});\n  var old = editor.swapDoc(buf);\n  var linked = old.iterLinkedDocs(function(doc) {linked = doc;});\n  if (linked) {\n    // Make sure the document in buffers is the one the other view is looking at\n    for (var name in buffers) if (buffers[name] == old) buffers[name] = linked;\n    old.unlinkDoc(linked);\n  }\n  editor.focus();\n}\n\nfunction nodeContent(id) {\n  var node = document.getElementById(id), val = node.textContent || node.innerText;\n  val = val.slice(val.match(/^\\s*/)[0].length, val.length - val.match(/\\s*$/)[0].length) + \"\\n\";\n  return val;\n}\nopenBuffer(\"js\", nodeContent(\"script\"), \"javascript\");\nopenBuffer(\"css\", nodeContent(\"style\"), \"css\");\n\nvar ed_top = CodeMirror(document.getElementById(\"code_top\"), {lineNumbers: true});\nselectBuffer(ed_top, \"js\");\nvar ed_bot = CodeMirror(document.getElementById(\"code_bot\"), {lineNumbers: true});\nselectBuffer(ed_bot, \"js\");\n</script>\n\n    <p>Demonstration of\n    using <a href=\"../doc/manual.html#linkedDoc\">linked documents</a>\n    to provide a split view on a document, and\n    using <a href=\"../doc/manual.html#swapDoc\"><code>swapDoc</code></a>\n    to use a single editor to display multiple documents.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/changemode.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Mode-Changing Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/scheme/scheme.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid black;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Mode-Changing</a>\n  </ul>\n</div>\n\n<article>\n<h2>Mode-Changing Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n;; If there is Scheme code in here, the editor will be in Scheme mode.\n;; If you put in JS instead, it'll switch to JS mode.\n\n(define (double x)\n  (* x x))\n</textarea></form>\n\n<p>On changes to the content of the above editor, a (crude) script\ntries to auto-detect the language used, and switches the editor to\neither JavaScript or Scheme mode based on that.</p>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    mode: \"scheme\",\n    lineNumbers: true\n  });\n  var pending;\n  editor.on(\"change\", function() {\n    clearTimeout(pending);\n    pending = setTimeout(update, 400);\n  });\n  function looksLikeScheme(code) {\n    return !/^\\s*\\(\\s*function\\b/.test(code) && /^\\s*[;\\(]/.test(code);\n  }\n  function update() {\n    editor.setOption(\"mode\", looksLikeScheme(editor.getValue()) ? \"scheme\" : \"javascript\");\n  }\n</script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/closebrackets.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Closebrackets Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/edit/closebrackets.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid #888; border-bottom: 1px solid #888;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Closebrackets</a>\n  </ul>\n</div>\n\n<article>\n<h2>Closebrackets Demo</h2>\n<form><textarea id=\"code\" name=\"code\">function Grid(width, height) {\n  this.width = width;\n  this.height = height;\n  this.cells = new Array(width * height);\n}\nGrid.prototype.valueAt = function(point) {\n  return this.cells[point.y * this.width + point.x];\n};\nGrid.prototype.setValueAt = function(point, value) {\n  this.cells[point.y * this.width + point.x] = value;\n};\nGrid.prototype.isInside = function(point) {\n  return point.x >= 0 && point.y >= 0 &&\n         point.x < this.width && point.y < this.height;\n};\nGrid.prototype.moveValue = function(from, to) {\n  this.setValueAt(to, this.valueAt(from));\n  this.setValueAt(from, undefined);\n};</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {autoCloseBrackets: true});\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/closetag.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Close-Tag Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/edit/closetag.js\"></script>\n<script src=\"../addon/fold/xml-fold.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/css/css.js\"></script>\n<script src=\"../mode/htmlmixed/htmlmixed.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid #888; border-bottom: 1px solid #888;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Close-Tag</a>\n  </ul>\n</div>\n\n<article>\n<h2>Close-Tag Demo</h2>\n<form><textarea id=\"code\" name=\"code\"><html</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: 'text/html',\n        autoCloseTags: true\n      });\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/complete.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Autocomplete Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/hint/show-hint.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/hint/show-hint.js\"></script>\n<script src=\"../addon/hint/javascript-hint.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/markdown/markdown.js\"></script>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Autocomplete</a>\n  </ul>\n</div>\n\n<article>\n<h2>Autocomplete Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\nfunction getCompletions(token, context) {\n  var found = [], start = token.string;\n  function maybeAdd(str) {\n    if (str.indexOf(start) == 0) found.push(str);\n  }\n  function gatherCompletions(obj) {\n    if (typeof obj == \"string\") forEach(stringProps, maybeAdd);\n    else if (obj instanceof Array) forEach(arrayProps, maybeAdd);\n    else if (obj instanceof Function) forEach(funcProps, maybeAdd);\n    for (var name in obj) maybeAdd(name);\n  }\n\n  if (context) {\n    // If this is a property, see if it belongs to some object we can\n    // find in the current environment.\n    var obj = context.pop(), base;\n    if (obj.className == \"js-variable\")\n      base = window[obj.string];\n    else if (obj.className == \"js-string\")\n      base = \"\";\n    else if (obj.className == \"js-atom\")\n      base = 1;\n    while (base != null && context.length)\n      base = base[context.pop().string];\n    if (base != null) gatherCompletions(base);\n  }\n  else {\n    // If not, just look in the window object and any local scope\n    // (reading into JS mode internals to get at the local variables)\n    for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);\n    gatherCompletions(window);\n    forEach(keywords, maybeAdd);\n  }\n  return found;\n}\n</textarea></form>\n\n<p>Press <strong>ctrl-space</strong> to activate autocompletion. Built\non top of the <a href=\"../doc/manual.html#addon_show-hint\"><code>show-hint</code></a>\nand <a href=\"../doc/manual.html#addon_javascript-hint\"><code>javascript-hint</code></a>\naddons.</p>\n\n<form><textarea style=\"display: none\" id=\"synonyms\" name=\"synonyms\">\nHere, the completion use an asynchronous hinting functions to provide\nsynonyms for each words. If your browser support `Promises`, the\nhinting function can also return one.\n</textarea></form>\n\n<script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true,\n  extraKeys: {\"Ctrl-Space\": \"autocomplete\"},\n  mode: {name: \"javascript\", globalVars: true}\n});\n\nif (typeof Promise !== \"undefined\") {\n  var comp = [\n    [\"here\", \"hither\"],\n    [\"asynchronous\", \"nonsynchronous\"],\n    [\"completion\", \"achievement\", \"conclusion\", \"culmination\", \"expirations\"],\n    [\"hinting\", \"advive\", \"broach\", \"imply\"],\n    [\"function\",\"action\"],\n    [\"provide\", \"add\", \"bring\", \"give\"],\n    [\"synonyms\", \"equivalents\"],\n    [\"words\", \"token\"],\n    [\"each\", \"every\"],\n  ]\n\n  function synonyms(cm, option) {\n    return new Promise(function(accept) {\n      setTimeout(function() {\n        var cursor = cm.getCursor(), line = cm.getLine(cursor.line)\n        var start = cursor.ch, end = cursor.ch\n        while (start && /\\w/.test(line.charAt(start - 1))) --start\n        while (end < line.length && /\\w/.test(line.charAt(end))) ++end\n        var word = line.slice(start, end).toLowerCase()\n        for (var i = 0; i < comp.length; i++) if (comp[i].indexOf(word) != -1)\n          return accept({list: comp[i],\n                         from: CodeMirror.Pos(cursor.line, start),\n                         to: CodeMirror.Pos(cursor.line, end)})\n        return accept(null)\n      }, 100)\n    })\n  }\n\n  var editor2 = CodeMirror.fromTextArea(document.getElementById(\"synonyms\"), {\n    extraKeys: {\"Ctrl-Space\": \"autocomplete\"},\n    lineNumbers: true,\n    lineWrapping: true,\n    mode: \"text/x-markdown\",\n    hintOptions: {hint: synonyms}\n  })\n}\n</script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/emacs.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Emacs bindings demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/dialog/dialog.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/clike/clike.js\"></script>\n<script src=\"../keymap/emacs.js\"></script>\n<script src=\"../addon/edit/matchbrackets.js\"></script>\n<script src=\"../addon/comment/comment.js\"></script>\n<script src=\"../addon/dialog/dialog.js\"></script>\n<script src=\"../addon/search/searchcursor.js\"></script>\n<script src=\"../addon/search/search.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Emacs bindings</a>\n  </ul>\n</div>\n\n<article>\n<h2>Emacs bindings demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n#include \"syscalls.h\"\n/* getchar:  simple buffered version */\nint getchar(void)\n{\n  static char buf[BUFSIZ];\n  static char *bufp = buf;\n  static int n = 0;\n  if (n == 0) {  /* buffer is empty */\n    n = read(0, buf, sizeof buf);\n    bufp = buf;\n  }\n  return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n}\n</textarea></form>\n\n<p>The emacs keybindings are enabled by\nincluding <a href=\"../keymap/emacs.js\">keymap/emacs.js</a> and setting\nthe <code>keyMap</code> option to <code>\"emacs\"</code>. Because\nCodeMirror's internal API is quite different from Emacs, they are only\na loose approximation of actual emacs bindings, though.</p>\n\n<p>Also note that a lot of browsers disallow certain keys from being\ncaptured. For example, Chrome blocks both Ctrl-W and Ctrl-N, with the\nresult that idiomatic use of Emacs keys will constantly close your tab\nor open a new window.</p>\n\n    <script>\n      CodeMirror.commands.save = function() {\n        var elt = editor.getWrapperElement();\n        elt.style.background = \"#def\";\n        setTimeout(function() { elt.style.background = \"\"; }, 300);\n      };\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"text/x-csrc\",\n        matchBrackets: true,\n        keyMap: \"emacs\"\n      });\n    </script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/folding.html",
    "content": "<!doctype html>\n\n<head>\n  <title>CodeMirror: Code Folding Demo</title>\n  <meta charset=\"utf-8\"/>\n  <link rel=stylesheet href=\"../doc/docs.css\">\n\n  <style>\n    .some-css {\n      color: red;\n      line-height: 2;\n    }\n  </style>\n\n  <link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n  <link rel=\"stylesheet\" href=\"../addon/fold/foldgutter.css\" />\n  <script src=\"../lib/codemirror.js\"></script>\n  <script src=\"../addon/fold/foldcode.js\"></script>\n  <script src=\"../addon/fold/foldgutter.js\"></script>\n  <script src=\"../addon/fold/brace-fold.js\"></script>\n  <script src=\"../addon/fold/xml-fold.js\"></script>\n  <script src=\"../addon/fold/indent-fold.js\"></script>\n  <script src=\"../addon/fold/markdown-fold.js\"></script>\n  <script src=\"../addon/fold/comment-fold.js\"></script>\n  <script src=\"../mode/javascript/javascript.js\"></script>\n  <script src=\"../mode/xml/xml.js\"></script>\n  <script src=\"../mode/css/css.js\"></script>\n  <script src=\"../mode/htmlmixed/htmlmixed.js\"></script>\n  <script src=\"../mode/python/python.js\"></script>\n  <script src=\"../mode/markdown/markdown.js\"></script>\n  <style>\n    .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n  </style>\n</head>\n\n<body>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Code Folding</a>\n  </ul>\n</div>\n\n<article>\n  <h2>Code Folding Demo</h2>\n  <form>\n    <div style=\"max-width: 50em; margin-bottom: 1em\">JavaScript:<br>\n    <textarea id=\"code\" name=\"code\"></textarea></div>\n    <div style=\"max-width: 50em; margin-bottom: 1em\">HTML:<br>\n    <textarea id=\"code-html\" name=\"code-html\"></textarea></div>\n    <div style=\"max-width: 50em\">Python:<br>\n    <textarea id=\"code-python\" name=\"code\">\ndef foo():\n  do_some_stuff()\n  here\n  return None\n\nclass Bar:\n  __init__(self):\n    if True:\n      print(\"True\")\n    else:\n      print(\"False\")\n\n  this_code_makes_no_sense():\n    pass\n\n# A comment</textarea></div>\n    <div style=\"max-width: 50em\">Markdown:<br>\n    <textarea id=\"code-markdown\" name=\"code\"></textarea></div>\n  </form>\n  <script id=\"script\">\n/*\n * Demonstration of code folding\n */\nwindow.onload = function() {\n  var te = document.getElementById(\"code\");\n  var sc = document.getElementById(\"script\");\n  te.value = (sc.textContent || sc.innerText || sc.innerHTML).replace(/^\\s*/, \"\");\n  sc.innerHTML = \"\";\n  var te_html = document.getElementById(\"code-html\");\n  te_html.value = document.documentElement.innerHTML;\n  var te_python = document.getElementById(\"code-python\");\n  var te_markdown = document.getElementById(\"code-markdown\");\n  te_markdown.value = \"# Foo\\n## Bar\\n\\nblah blah\\n\\n## Baz\\n\\nblah blah\\n\\n# Quux\\n\\nblah blah\\n\"\n\n  window.editor = CodeMirror.fromTextArea(te, {\n    mode: \"javascript\",\n    lineNumbers: true,\n    lineWrapping: true,\n    extraKeys: {\"Ctrl-Q\": function(cm){ cm.foldCode(cm.getCursor()); }},\n    foldGutter: true,\n    gutters: [\"CodeMirror-linenumbers\", \"CodeMirror-foldgutter\"]\n  });\n  editor.foldCode(CodeMirror.Pos(13, 0));\n\n  window.editor_html = CodeMirror.fromTextArea(te_html, {\n    mode: \"text/html\",\n    lineNumbers: true,\n    lineWrapping: true,\n    extraKeys: {\"Ctrl-Q\": function(cm){ cm.foldCode(cm.getCursor()); }},\n    foldGutter: true,\n    gutters: [\"CodeMirror-linenumbers\", \"CodeMirror-foldgutter\"]\n  });\n  editor_html.foldCode(CodeMirror.Pos(0, 0));\n  editor_html.foldCode(CodeMirror.Pos(34, 0));\n\n  window.editor_python = CodeMirror.fromTextArea(te_python, {\n    mode: \"python\",\n    lineNumbers: true,\n    extraKeys: {\"Ctrl-Q\": function(cm){ cm.foldCode(cm.getCursor()); }},\n    foldGutter: true,\n    gutters: [\"CodeMirror-linenumbers\", \"CodeMirror-foldgutter\"]\n  });\n\n  window.editor_markdown = CodeMirror.fromTextArea(te_markdown, {\n    mode: \"markdown\",\n    lineNumbers: true,\n    lineWrapping: true,\n    extraKeys: {\"Ctrl-Q\": function(cm){ cm.foldCode(cm.getCursor()); }},\n    foldGutter: true,\n    gutters: [\"CodeMirror-linenumbers\", \"CodeMirror-foldgutter\"]\n  });\n};\n  </script>\n</article>\n</body>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/fullscreen.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Full Screen Editing</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/display/fullscreen.css\">\n<link rel=\"stylesheet\" href=\"../theme/night.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../addon/display/fullscreen.js\"></script>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Full Screen Editing</a>\n  </ul>\n</div>\n\n<article>\n<h2>Full Screen Editing</h2>\n<form><textarea id=\"code\" name=\"code\" rows=\"5\">\n<dl>\n  <dt id=\"option_indentWithTabs\"><code><strong>indentWithTabs</strong>: boolean</code></dt>\n  <dd>Whether, when indenting, the first N*<code>tabSize</code>\n  spaces should be replaced by N tabs. Default is false.</dd>\n\n  <dt id=\"option_electricChars\"><code><strong>electricChars</strong>: boolean</code></dt>\n  <dd>Configures whether the editor should re-indent the current\n  line when a character is typed that might change its proper\n  indentation (only works if the mode supports indentation).\n  Default is true.</dd>\n\n  <dt id=\"option_specialChars\"><code><strong>specialChars</strong>: RegExp</code></dt>\n  <dd>A regular expression used to determine which characters\n  should be replaced by a\n  special <a href=\"#option_specialCharPlaceholder\">placeholder</a>.\n  Mostly useful for non-printing special characters. The default\n  is <code>/[\\u0000-\\u0019\\u00ad\\u200b\\u2028\\u2029\\ufeff]/</code>.</dd>\n  <dt id=\"option_specialCharPlaceholder\"><code><strong>specialCharPlaceholder</strong>: function(char) → Element</code></dt>\n  <dd>A function that, given a special character identified by\n  the <a href=\"#option_specialChars\"><code>specialChars</code></a>\n  option, produces a DOM node that is used to represent the\n  character. By default, a red dot (<span style=\"color: red\">•</span>)\n  is shown, with a title tooltip to indicate the character code.</dd>\n\n  <dt id=\"option_rtlMoveVisually\"><code><strong>rtlMoveVisually</strong>: boolean</code></dt>\n  <dd>Determines whether horizontal cursor movement through\n  right-to-left (Arabic, Hebrew) text is visual (pressing the left\n  arrow moves the cursor left) or logical (pressing the left arrow\n  moves to the next lower index in the string, which is visually\n  right in right-to-left text). The default is <code>false</code>\n  on Windows, and <code>true</code> on other platforms.</dd>\n</dl>\n</textarea></form>\n  <script>\n    var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n      lineNumbers: true,\n      theme: \"night\",\n      extraKeys: {\n        \"F11\": function(cm) {\n          cm.setOption(\"fullScreen\", !cm.getOption(\"fullScreen\"));\n        },\n        \"Esc\": function(cm) {\n          if (cm.getOption(\"fullScreen\")) cm.setOption(\"fullScreen\", false);\n        }\n      }\n    });\n  </script>\n\n    <p>Demonstration of\n    the <a href=\"../doc/manual.html#addon_fullscreen\">fullscreen</a>\n    addon. Press <strong>F11</strong> when cursor is in the editor to\n    toggle full screen editing. <strong>Esc</strong> can also be used\n    to <i>exit</i> full screen editing.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/hardwrap.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Hard-wrapping Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/markdown/markdown.js\"></script>\n<script src=\"../addon/wrap/hardwrap.js\"></script>\n<style>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Hard-wrapping</a>\n  </ul>\n</div>\n\n<article>\n<h2>Hard-wrapping Demo</h2>\n<form><textarea id=\"code\" name=\"code\">Lorem ipsum dolor sit amet, vim augue dictas constituto ex,\nsit falli simul viderer te. Graeco scaevola maluisset sit\nut, in idque viris praesent sea. Ea sea eirmod indoctum\nrepudiare. Vel noluisse suscipit pericula ut. In ius nulla\nalienum molestie. Mei essent discere democritum id.\n\nEquidem ponderum expetendis ius in, mea an erroribus\nconstituto, congue timeam perfecto ad est. Ius ut primis\ntimeam, per in ullum mediocrem. An case vero labitur pri,\nvel dicit laoreet et. An qui prompta conclusionemque, eam\ntimeam sapientem in, cum dictas epicurei eu.\n\nUsu cu vide dictas deseruisse, eum choro graece adipiscing\nut. Cibo qualisque ius ad, et dicat scripta mea, eam nihil\nmentitum aliquando cu. Debet aperiam splendide at quo, ad\npaulo nostro commodo duo. Sea adhuc utinam conclusionemque\nid, quas doming malorum nec ad. Tollit eruditi vivendum ad\nius, eos soleat ignota ad.\n</textarea></form>\n\n<p>Demonstration of\nthe <a href=\"../doc/manual.html#addon_hardwrap\">hardwrap</a> addon.\nThe above editor has its change event hooked up to\nthe <code>wrapParagraphsInRange</code> method, so that the paragraphs\nare reflown as you are typing.</p>\n\n<script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  mode: \"markdown\",\n  lineNumbers: true,\n  extraKeys: {\n    \"Ctrl-Q\": function(cm) { cm.wrapParagraph(cm.getCursor(), options); }\n  }\n});\nvar wait, options = {column: 60}, changing = false;\neditor.on(\"change\", function(cm, change) {\n  if (changing) return;\n  clearTimeout(wait);\n  wait = setTimeout(function() {\n    changing = true;\n    cm.wrapParagraphsInRange(change.from, CodeMirror.changeEnd(change), options);\n    changing = false;\n  }, 200);\n});\n</script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/html5complete.html",
    "content": "<!doctype html>\n\n<head>\n  <title>CodeMirror: HTML completion demo</title>\n  <meta charset=\"utf-8\"/>\n  <link rel=stylesheet href=\"../doc/docs.css\">\n\n  <link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n  <link rel=\"stylesheet\" href=\"../addon/hint/show-hint.css\">\n  <script src=\"../lib/codemirror.js\"></script>\n  <script src=\"../addon/hint/show-hint.js\"></script>\n  <script src=\"../addon/hint/xml-hint.js\"></script>\n  <script src=\"../addon/hint/html-hint.js\"></script>\n  <script src=\"../mode/xml/xml.js\"></script>\n  <script src=\"../mode/javascript/javascript.js\"></script>\n  <script src=\"../mode/css/css.js\"></script>\n  <script src=\"../mode/htmlmixed/htmlmixed.js\"></script>\n  <style>\n    .CodeMirror {border-top: 1px solid #888; border-bottom: 1px solid #888;}\n  </style>\n</head>\n\n<body>\n  <div id=nav>\n    <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n    <ul>\n      <li><a href=\"../index.html\">Home</a>\n      <li><a href=\"../doc/manual.html\">Manual</a>\n      <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n    </ul>\n    <ul>\n      <li><a class=active href=\"#\">HTML completion</a>\n    </ul>\n  </div>\n\n  <article>\n    <h2>HTML completion demo</h2>\n\n    <p>Shows the <a href=\"xmlcomplete.html\">XML completer</a>\n    parameterized with information about the tags in HTML.\n    Press <strong>ctrl-space</strong> to activate completion.</p>\n\n    <div id=\"code\"></div>\n\n    <script>\n      window.onload = function() {\n        editor = CodeMirror(document.getElementById(\"code\"), {\n          mode: \"text/html\",\n          extraKeys: {\"Ctrl-Space\": \"autocomplete\"},\n          value: document.documentElement.innerHTML\n        });\n      };\n    </script>\n  </article>\n</body>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/indentwrap.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Indented wrapped line demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      .CodeMirror pre > * { text-indent: 0px; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Indented wrapped line</a>\n  </ul>\n</div>\n\n<article>\n<h2>Indented wrapped line demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n<!doctype html>\n<body>\n  <h2 id=\"overview\">Overview</h2>\n\n  <p>CodeMirror is a code-editor component that can be embedded in Web pages. The core library provides <em>only</em> the editor component, no accompanying buttons, auto-completion, or other IDE functionality. It does provide a rich API on top of which such functionality can be straightforwardly implemented. See the <a href=\"#addons\">add-ons</a> included in the distribution, and the <a href=\"https://github.com/jagthedrummer/codemirror-ui\">CodeMirror UI</a> project, for reusable implementations of extra features.</p>\n\n  <p>CodeMirror works with language-specific modes. Modes are JavaScript programs that help color (and optionally indent) text written in a given language. The distribution comes with a number of modes (see the <a href=\"../mode/\"><code>mode/</code></a> directory), and it isn't hard to <a href=\"#modeapi\">write new ones</a> for other languages.</p>\n</body>\n</textarea></form>\n\n    <p>This page uses a hack on top of the <code>\"renderLine\"</code>\n    event to make wrapped text line up with the base indentation of\n    the line.</p>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        lineWrapping: true,\n        mode: \"text/html\"\n      });\n      var charWidth = editor.defaultCharWidth(), basePadding = 4;\n      editor.on(\"renderLine\", function(cm, line, elt) {\n        var off = CodeMirror.countColumn(line.text, null, cm.getOption(\"tabSize\")) * charWidth;\n        elt.style.textIndent = \"-\" + off + \"px\";\n        elt.style.paddingLeft = (basePadding + off) + \"px\";\n      });\n      editor.refresh();\n    </script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/lint.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Linter Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/lint/lint.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/css/css.js\"></script>\n<script src=\"https://unpkg.com/jshint@2.9.6/dist/jshint.js\"></script>\n<script src=\"https://unpkg.com/jsonlint@1.6.3/web/jsonlint.js\"></script>\n<script src=\"https://unpkg.com/csslint@1.0.5/dist/csslint.js\"></script>\n<script src=\"../addon/lint/lint.js\"></script>\n<script src=\"../addon/lint/javascript-lint.js\"></script>\n<script src=\"../addon/lint/json-lint.js\"></script>\n<script src=\"../addon/lint/css-lint.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid black;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Linter</a>\n  </ul>\n</div>\n\n<article>\n<h2>Linter Demo</h2>\n\n\n    <p><textarea id=\"code-js\">var widgets = []\nfunction updateHints() {\n  editor.operation(function(){\n    for (var i = 0; i < widgets.length.; ++i)\n      editor.removeLineWidget(widgets[i]);\n    widgets.length = 0;\n\n    JSHINT(editor.getValue());\n    for (var i = 0; i < JSHINT.errors.length; ++i) {\n      var err = JSHINT.errors[i];\n      if (!err) continue;\n      var msg = document.createElement(\"div\");\n      var icon = msg.appendChild(document.createElement(\"span\"));\n      icon.innerHTML = \"!!\";\n      icon.className = \"lint-error-icon\";\n      msg.appendChild(document.createTextNode(err.reason));\n      msg.className = \"lint-error\";\n      widgets.push(editor.addLineWidget(err.line - 1, msg, {coverGutter: false, noHScroll: true}));\n    }\n  });\n  var info = editor.getScrollInfo();\n  var after = editor.charCoords({line: editor.getCursor().line + 1, ch: 0}, \"local\").top;\n  if (info.top + info.clientHeight < after)\n    editor.scrollTo(null, after - info.clientHeight + 3);\n}\n</textarea></p>\n\n    <p><textarea id=\"code-json\">[\n {\n  _id: \"post 1\",\n  \"author\": \"Bob\",\n  \"content\": \"...\",\n  \"page_views\": 5\n },\n {\n  \"_id\": \"post 2\",\n  \"author\": \"Bob\",\n  \"content\": \"...\",\n  \"page_views\": 9\n },\n {\n  \"_id\": \"post 3\",\n  \"author\": \"Bob\",\n  \"content\": \"...\",\n  \"page_views\": 8\n }\n]\n</textarea></p>\n\n    <p><textarea id=\"code-css\">@charset \"UTF-8\";\n\n@import url(\"booya.css\") print, screen;\n@import \"whatup.css\" screen;\n@import \"wicked.css\";\n\n/*Error*/\n@charset \"UTF-8\";\n\n\n@namespace \"http://www.w3.org/1999/xhtml\";\n@namespace svg \"http://www.w3.org/2000/svg\";\n\n/*Warning: empty ruleset */\n.foo {\n}\n\nh1 {\n    font-weight: bold;\n}\n\n/*Warning: qualified heading */\n.foo h1 {\n    font-weight: bold;\n}\n\n/*Warning: adjoining classes */\n.foo.bar {\n    zoom: 1;\n}\n\nli.inline {\n    width: 100%;  /*Warning: 100% can be problematic*/\n}\n\nli.last {\n  display: inline;\n  padding-left: 3px !important;\n  padding-right: 3px;\n  border-right: 0px;\n}\n\n@media print {\n    li.inline {\n      color: black;\n    }\n}\n\n@page {\n  margin: 10%;\n  counter-increment: page;\n\n  @top-center {\n    font-family: sans-serif;\n    font-weight: bold;\n    font-size: 2em;\n    content: counter(page);\n  }\n}\n</textarea></p>\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code-js\"), {\n    lineNumbers: true,\n    mode: \"javascript\",\n    gutters: [\"CodeMirror-lint-markers\"],\n    lint: true\n  });\n\n  var editor_json = CodeMirror.fromTextArea(document.getElementById(\"code-json\"), {\n    lineNumbers: true,\n    mode: \"application/json\",\n    gutters: [\"CodeMirror-lint-markers\"],\n    lint: true\n  });\n  \n  var editor_css = CodeMirror.fromTextArea(document.getElementById(\"code-css\"), {\n    lineNumbers: true,\n    mode: \"css\",\n    gutters: [\"CodeMirror-lint-markers\"],\n    lint: true\n  });\n</script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/loadmode.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Lazy Mode Loading Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/mode/loadmode.js\"></script>\n<script src=\"../mode/meta.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Lazy Mode Loading</a>\n  </ul>\n</div>\n\n<article>\n<h2>Lazy Mode Loading Demo</h2>\n<p style=\"color: gray\">Current mode: <span id=\"modeinfo\">text/plain</span></p>\n<form><textarea id=\"code\" name=\"code\">This is the editor.\n// It starts out in plain text mode,\n#  use the control below to load and apply a mode\n  \"you'll see the highlighting of\" this text /*change*/.\n</textarea></form>\n<p>Filename, mime, or mode name: <input type=text value=foo.js id=mode> <button type=button onclick=\"change()\">change mode</button></p>\n\n    <script>\nCodeMirror.modeURL = \"../mode/%N/%N.js\";\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true\n});\nvar modeInput = document.getElementById(\"mode\");\nCodeMirror.on(modeInput, \"keypress\", function(e) {\n  if (e.keyCode == 13) change();\n});\nfunction change() {\n  var val = modeInput.value, m, mode, spec;\n  if (m = /.+\\.([^.]+)$/.exec(val)) {\n    var info = CodeMirror.findModeByExtension(m[1]);\n    if (info) {\n      mode = info.mode;\n      spec = info.mime;\n    }\n  } else if (/\\//.test(val)) {\n    var info = CodeMirror.findModeByMIME(val);\n    if (info) {\n      mode = info.mode;\n      spec = val;\n    }\n  } else {\n    mode = spec = val;\n  }\n  if (mode) {\n    editor.setOption(\"mode\", spec);\n    CodeMirror.autoLoadMode(editor, mode);\n    document.getElementById(\"modeinfo\").textContent = spec;\n  } else {\n    alert(\"Could not find a mode corresponding to \" + val);\n  }\n}\n</script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/marker.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Breakpoint Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<style>\n      .breakpoints {width: .8em;}\n      .breakpoint { color: #822; }\n      .CodeMirror {border: 1px solid #aaa;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Breakpoint</a>\n  </ul>\n</div>\n\n<article>\n<h2>Breakpoint Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true,\n  gutters: [\"CodeMirror-linenumbers\", \"breakpoints\"]\n});\neditor.on(\"gutterClick\", function(cm, n) {\n  var info = cm.lineInfo(n);\n  cm.setGutterMarker(n, \"breakpoints\", info.gutterMarkers ? null : makeMarker());\n});\n\nfunction makeMarker() {\n  var marker = document.createElement(\"div\");\n  marker.style.color = \"#822\";\n  marker.innerHTML = \"●\";\n  return marker;\n}\n</textarea></form>\n\n<p>Click the line-number gutter to add or remove 'breakpoints'.</p>\n\n    <script>eval(document.getElementById(\"code\").value);</script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/markselection.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Selection Marking Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/search/searchcursor.js\"></script>\n<script src=\"../addon/selection/mark-selection.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      .CodeMirror-selected  { background-color: blue !important; }\n      .CodeMirror-selectedtext { color: white; }\n      .styled-background { background-color: #ff7; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Selection Marking</a>\n  </ul>\n</div>\n\n<article>\n<h2>Selection Marking Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\nSelect something from here. You'll see that the selection's foreground\ncolor changes to white! Since, by default, CodeMirror only puts an\nindependent \"marker\" layer behind the text, you'll need something like\nthis to change its colour.\n\nAlso notice that turning this addon on (with the default style) allows\nyou to safely give text a background color without screwing up the\nvisibility of the selection.</textarea></form>\n\n    <script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true,\n  styleSelectedText: true\n});\neditor.markText({line: 6, ch: 26}, {line: 6, ch: 42}, {className: \"styled-background\"});\n</script>\n\n    <p>Simple addon to easily mark (and style) selected text. <a href=\"../doc/manual.html#addon_mark-selection\">Docs</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/matchhighlighter.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Match Highlighter Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/scroll/annotatescrollbar.js\"></script>\n<script src=\"../addon/search/matchesonscrollbar.js\"></script>\n<script src=\"../addon/search/searchcursor.js\"></script>\n<script src=\"../addon/search/match-highlighter.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      .CodeMirror-focused .cm-matchhighlight {\n        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFklEQVQI12NgYGBgkKzc8x9CMDAwAAAmhwSbidEoSQAAAABJRU5ErkJggg==);\n        background-position: bottom;\n        background-repeat: repeat-x;\n      }\n      .cm-matchhighlight {background-color: lightgreen}\n      .CodeMirror-selection-highlight-scrollbar {background-color: green}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Match Highlighter</a>\n  </ul>\n</div>\n\n<article>\n<h2>Match Highlighter Demo</h2>\n<form><textarea id=\"code\" name=\"code\">Select this text: hardtospot\n  And everywhere else in your code where hardtospot appears will\nautomatically illuminate.  Give it a try!  No more hard to spot\nvariables - stay in context of your code all the time.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Ut pharetra\ninterdum dui eu pulvinar. Mauris maximus ligula venenatis tempus\ninterdum. Cras hendrerit, ipsum sed ultrices pharetra, ligula diam\nporttitor lacus, ac tempor eros est a massa. Nam orci elit, vulputate\nin tristique quis, consectetur vitae metus. Pellentesque et enim\nelementum, lobortis augue in, lacinia sapien. Morbi eu nunc semper,\nsagittis felis a, pellentesque mauris. Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit. Aenean quis diam turpis.\n\nFusce lobortis nisl quis aliquet euismod. Aenean vitae nulla non ipsum\nefficitur scelerisque. Curabitur auctor, lorem non rhoncus porttitor,\naugue ligula lacinia dolor, et vehicula magna lorem imperdiet velit.\nFusce risus sem, hardtospot commodo eleifend hendrerit vitae, mollis\nquis risus. Cras tincidunt, justo vitae hendrerit venenatis, urna\ndolor placerat tortor, eu lobortis lectus dolor in ligula. Nullam non\nerat non nisl vulputate ultrices sit amet vestibulum dolor. Quisque in\ntortor porta, pellentesque odio nec, malesuada nibh.\n\nIn a dui feugiat, ullamcorper urna in, accumsan magna. Donec egestas\nsem nec eros rhoncus, vel gravida purus ornare. Nulla orci mauris,\nporta nec pharetra sed, ornare et lorem. Donec luctus turpis nunc,\neget dictum felis mollis et.  Sed sodales hardtospot nunc vitae leo\nrhoncus imperdiet. Donec elementum malesuada velit quis placerat.\nProin accumsan lorem id nisi volutpat ullamcorper. Vivamus laoreet\ndolor ac sem malesuada, ac scelerisque ex efficitur. Aliquam tempus\nlibero velit, vel tristique augue vulputate nec.\n\nMauris ultrices leo felis, sit amet congue augue aliquam condimentum.\nVivamus purus leo, mattis vitae dignissim vel, ultricies ac ex. Mauris\neu dolor eu purus ultricies ultrices. Sed euismod feugiat ex et\nmattis. Morbi cursus laoreet pharetra. Donec eu dolor sodales,\nultricies nisi et, malesuada urna.  Praesent sit amet fringilla felis.\nNam rhoncus, est blandit auctor auctor, lorem ipsum laoreet ipsum,\nquis sodales libero odio in lorem. Phasellus odio dolor, elementum\nsagittis nibh non, fermentum semper libero. Mauris hendrerit\nhardtospot lectus sit amet commodo eleifend. Morbi pulvinar eget nisl\nat eleifend. Fusce eget porta erat, vitae lobortis libero.\n\nPhasellus sit amet massa in massa pharetra malesuada. Vestibulum at\nquam vel libero aliquam volutpat at ut dui. Praesent scelerisque vel\nmauris sit amet vehicula. Phasellus at mi nec ligula cursus interdum\nsit amet non quam. Aliquam tempus sollicitudin euismod. Nulla euismod\nmollis enim tincidunt placerat.  Proin ac scelerisque enim, quis\nsollicitudin metus. Pellentesque congue nec sapien ut rhoncus. Sed\neget ornare diam, ut consectetur ante. Aenean eleifend mauris quis\nornare accumsan. In hac habitasse hardtospot platea dictumst.\n\n</textarea></form>\n\n    <script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true,\n  // To highlight on scrollbars as well, pass annotateScrollbar in options\n  // as below.\n  highlightSelectionMatches: {showToken: /\\w/, annotateScrollbar: true}\n});\n</script>\n\n    <p>Search and highlight occurences of the selected text.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/matchtags.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Tag Matcher Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/fold/xml-fold.js\"></script>\n<script src=\"../addon/edit/matchtags.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Tag Matcher</a>\n  </ul>\n</div>\n\n<article>\n<h2>Tag Matcher Demo</h2>\n\n\n    <div id=\"editor\"></div>\n\n    <script>\nwindow.onload = function() {\n  editor = CodeMirror(document.getElementById(\"editor\"), {\n    value: \"<html>\\n  \" + document.documentElement.innerHTML + \"\\n</html>\",\n    mode: \"text/html\",\n    matchTags: {bothTags: true},\n    extraKeys: {\"Ctrl-J\": \"toMatchingTag\"}\n  });\n};\n    </script>\n\n    <p>Put the cursor on or inside a pair of tags to highlight them.\n    Press Ctrl-J to jump to the tag that matches the one under the\n    cursor.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/merge.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: merge view demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=stylesheet href=\"../lib/codemirror.css\">\n<link rel=stylesheet href=\"../addon/merge/merge.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../mode/css/css.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/htmlmixed/htmlmixed.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/diff_match_patch/20121119/diff_match_patch.js\"></script>\n<script src=\"../addon/merge/merge.js\"></script>\n<style>\n    .CodeMirror { line-height: 1.2; }\n    @media screen and (min-width: 1300px) {\n      article { max-width: 1000px; }\n      #nav { border-right: 499px solid transparent; }\n    }\n    span.clicky {\n      cursor: pointer;\n      background: #d70;\n      color: white;\n      padding: 0 3px;\n      border-radius: 3px;\n    }\n  </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">merge view</a>\n  </ul>\n</div>\n\n<article>\n<h2>merge view demo</h2>\n\n\n<div id=view></div>\n\n<p>The <a href=\"../doc/manual.html#addon_merge\"><code>merge</code></a>\naddon provides an interface for displaying and merging diffs,\neither <span class=clicky onclick=\"panes = 2; initUI()\">two-way</span>\nor <span class=clicky onclick=\"panes = 3; initUI()\">three-way</span>.\nThe left (or center) pane is editable, and the differences with the\nother pane(s) are <span class=clicky\nonclick=\"toggleDifferences()\">optionally</span> shown live as you edit\nit. In the two-way configuration, there are also options to pad changed\nsections to <span class=clicky onclick=\"connect = connect ? null :\n'align'; initUI()\">align</span> them, and to <span class=clicky\nonclick=\"collapse = !collapse; initUI()\">collapse</span> unchanged\nstretches of text.</p>\n\n<p>This addon depends on\nthe <a href=\"https://code.google.com/p/google-diff-match-patch/\">google-diff-match-patch</a>\nlibrary to compute the diffs.</p>\n\n<script>\nvar value, orig1, orig2, dv, panes = 2, highlight = true, connect = \"align\", collapse = false;\nfunction initUI() {\n  if (value == null) return;\n  var target = document.getElementById(\"view\");\n  target.innerHTML = \"\";\n  dv = CodeMirror.MergeView(target, {\n    value: value,\n    origLeft: panes == 3 ? orig1 : null,\n    orig: orig2,\n    lineNumbers: true,\n    mode: \"text/html\",\n    highlightDifferences: highlight,\n    connect: connect,\n    collapseIdentical: collapse\n  });\n}\n\nfunction toggleDifferences() {\n  dv.setShowDifferences(highlight = !highlight);\n}\n\nwindow.onload = function() {\n  value = document.documentElement.innerHTML;\n  orig1 = \"<!doctype html>\\n\\n\" + value.replace(/\\.\\.\\//g, \"codemirror/\").replace(\"yellow\", \"orange\");\n  orig2 = value.replace(/\\u003cscript/g, \"\\u003cscript type=text/javascript \")\n    .replace(\"white\", \"purple;\\n      font: comic sans;\\n      text-decoration: underline;\\n      height: 15em\");\n  initUI();\n  let d = document.createElement(\"div\"); d.style.cssText = \"width: 50px; margin: 7px; height: 14px\"; dv.editor().addLineWidget(57, d)\n};\n\nfunction mergeViewHeight(mergeView) {\n  function editorHeight(editor) {\n    if (!editor) return 0;\n    return editor.getScrollInfo().height;\n  }\n  return Math.max(editorHeight(mergeView.leftOriginal()),\n                  editorHeight(mergeView.editor()),\n                  editorHeight(mergeView.rightOriginal()));\n}\n\nfunction resize(mergeView) {\n  var height = mergeViewHeight(mergeView);\n  for(;;) {\n    if (mergeView.leftOriginal())\n      mergeView.leftOriginal().setSize(null, height);\n    mergeView.editor().setSize(null, height);\n    if (mergeView.rightOriginal())\n      mergeView.rightOriginal().setSize(null, height);\n\n    var newHeight = mergeViewHeight(mergeView);\n    if (newHeight >= height) break;\n    else height = newHeight;\n  }\n  mergeView.wrap.style.height = height + \"px\";\n}\n</script>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/multiplex.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Multiplexing Parser Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/mode/multiplex.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid black;}\n      .cm-delimit {color: #fa4;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Multiplexing Parser</a>\n  </ul>\n</div>\n\n<article>\n<h2>Multiplexing Parser Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n<html>\n  <body style=\"<<magic>>\">\n    <h1><< this is not <html >></h1>\n    <<\n        multiline\n        not html\n        at all : &amp;amp; <link/>\n    >>\n    <p>this is html again</p>\n  </body>\n</html>\n</textarea></form>\n\n    <script>\nCodeMirror.defineMode(\"demo\", function(config) {\n  return CodeMirror.multiplexingMode(\n    CodeMirror.getMode(config, \"text/html\"),\n    {open: \"<<\", close: \">>\",\n     mode: CodeMirror.getMode(config, \"text/plain\"),\n     delimStyle: \"delimit\"}\n    // .. more multiplexed styles can follow here\n  );\n});\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  mode: \"demo\",\n  lineNumbers: true,\n  lineWrapping: true\n});\n</script>\n\n    <p>Demonstration of a multiplexing mode, which, at certain\n    boundary strings, switches to one or more inner modes. The out\n    (HTML) mode does not get fed the content of the <code>&lt;&lt;\n    >></code> blocks. See\n    the <a href=\"../doc/manual.html#addon_multiplex\">manual</a> and\n    the <a href=\"../addon/mode/multiplex.js\">source</a> for more\n    information.</p>\n\n    <p>\n      <strong>Parsing/Highlighting Tests:</strong>\n      <a href=\"../test/index.html#multiplexing_*\">normal</a>,\n      <a href=\"../test/index.html#verbose,multiplexing_*\">verbose</a>.\n    </p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/mustache.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Overlay Parser Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/mode/overlay.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid black;}\n      .cm-mustache {color: #0ca;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Overlay Parser</a>\n  </ul>\n</div>\n\n<article>\n<h2>Overlay Parser Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n<html>\n  <body>\n    <h1>{{title}}</h1>\n    <p>These are links to {{things}}:</p>\n    <ul>{{#links}}\n      <li><a href=\"{{url}}\">{{text}}</a></li>\n    {{/links}}</ul>\n  </body>\n</html>\n</textarea></form>\n\n    <script>\nCodeMirror.defineMode(\"mustache\", function(config, parserConfig) {\n  var mustacheOverlay = {\n    token: function(stream, state) {\n      var ch;\n      if (stream.match(\"{{\")) {\n        while ((ch = stream.next()) != null)\n          if (ch == \"}\" && stream.next() == \"}\") {\n            stream.eat(\"}\");\n            return \"mustache\";\n          }\n      }\n      while (stream.next() != null && !stream.match(\"{{\", false)) {}\n      return null;\n    }\n  };\n  return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || \"text/html\"), mustacheOverlay);\n});\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {mode: \"mustache\"});\n</script>\n\n    <p>Demonstration of a mode that parses HTML, highlighting\n    the <a href=\"http://mustache.github.com/\">Mustache</a> templating\n    directives inside of it by using the code\n    in <a href=\"../addon/mode/overlay.js\"><code>overlay.js</code></a>. View\n    source to see the 15 lines of code needed to accomplish this.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/panel.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Panel Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../mode/htmlmixed/htmlmixed.js\"></script>\n<script src=\"../addon/display/panel.js\"></script>\n<style>\n  .border {\n    border: 1px solid #f7f7f7;\n  }\n  .add-panel {\n    background: orange;\n    padding: 3px 6px;\n    color: white !important; \n    border-radius: 3px;\n  }\n  .add-panel, .remove-panel {\n    cursor: pointer;\n  }\n  .remove-panel {\n    float: right;\n  }\n  .panel {\n    background: #f7f7f7;\n    padding: 3px 7px;\n    font-size: 0.85em;\n  }\n  .panel.top, .panel.after-top {\n    border-bottom: 1px solid #ddd;\n  }\n  .panel.bottom, .panel.before-bottom {\n    border-top: 1px solid #ddd;\n  }\n</style>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Panel</a>\n  </ul>\n</div>\n\n<article>\n\n<h2>Panel Demo</h2>\n\n<div class=\"border\">\n    <textarea id=\"code\" name=\"code\"></textarea>\n</div>\n\n<p>\n  The <a href=\"../doc/manual.html#addon_panel\"><code>panel</code></a>\n  addon allows you to display panels above or below an editor.\n  <br>\n  Click the links below to add panels at the given position:\n</p>\n\n<div id=\"demo\">\n<p>\n  <a class=\"add-panel\" onclick=\"addPanel('top')\">top</a>\n  <a class=\"add-panel\" onclick=\"addPanel('after-top')\">after-top</a>\n  <a class=\"add-panel\" onclick=\"addPanel('before-bottom')\">before-bottom</a>\n  <a class=\"add-panel\" onclick=\"addPanel('bottom')\">bottom</a>\n</p>\n<p>\n  You can also replace an existing panel:\n</p>\n<form onsubmit=\"return replacePanel(this);\" name=\"replace_panel\">\n  <input type=\"submit\" value=\"Replace panel n°\" />\n  <input type=\"number\" name=\"panel_id\" min=\"1\" value=\"1\" />\n</form>\n\n<script>\nvar textarea = document.getElementById(\"code\");\nvar demo = document.getElementById(\"demo\");\nvar numPanels = 0;\nvar panels = {};\nvar editor;\n\ntextarea.value = demo.innerHTML.trim();\neditor = CodeMirror.fromTextArea(textarea, {\n  lineNumbers: true,\n  mode: \"htmlmixed\"\n});\n\nfunction makePanel(where) {\n  var node = document.createElement(\"div\");\n  var id = ++numPanels;\n  var widget, close, label;\n\n  node.id = \"panel-\" + id;\n  node.className = \"panel \" + where;\n  close = node.appendChild(document.createElement(\"a\"));\n  close.setAttribute(\"title\", \"Remove me!\");\n  close.setAttribute(\"class\", \"remove-panel\");\n  close.textContent = \"✖\";\n  CodeMirror.on(close, \"mousedown\", function(e) {\n    e.preventDefault()\n    panels[node.id].clear();\n  });\n  label = node.appendChild(document.createElement(\"span\"));\n  label.textContent = \"I'm panel n°\" + id;\n  return node;\n}\nfunction addPanel(where) {\n  var node = makePanel(where);\n  panels[node.id] = editor.addPanel(node, {position: where, stable: true});\n}\n\naddPanel(\"top\");\naddPanel(\"bottom\");\n\nfunction replacePanel(form) {\n  var id = form.elements.panel_id.value;\n  var panel = panels[\"panel-\" + id];\n  var node = makePanel(\"\");\n\n  panels[node.id] = editor.addPanel(node, {replace: panel, position: \"after-top\", stable: true});\n  return false;\n}\n</script>\n\n</div>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/placeholder.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Placeholder demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/display/placeholder.js\"></script>\n<style>\n      .CodeMirror { border: 1px solid silver; }\n      .CodeMirror-empty { outline: 1px solid #c22; }\n      .CodeMirror-empty.CodeMirror-focused { outline: none; }\n      .CodeMirror pre.CodeMirror-placeholder { color: #999; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Placeholder</a>\n  </ul>\n</div>\n\n<article>\n<h2>Placeholder demo</h2>\n<form><textarea id=\"code\" name=\"code\" placeholder=\"Code goes here...\"></textarea></form>\n\n    <p>The <a href=\"../doc/manual.html#addon_placeholder\">placeholder</a>\n    plug-in adds an option <code>placeholder</code> that can be set to\n    make text appear in the editor when it is empty and not focused.\n    If the source textarea has a <code>placeholder</code> attribute,\n    it will automatically be inherited.</p>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true\n      });\n    </script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/preview.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: HTML5 preview</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=stylesheet href=../lib/codemirror.css>\n<script src=../lib/codemirror.js></script>\n<script src=../mode/xml/xml.js></script>\n<script src=../mode/javascript/javascript.js></script>\n<script src=../mode/css/css.js></script>\n<script src=../mode/htmlmixed/htmlmixed.js></script>\n<style type=text/css>\n      .CodeMirror {\n        float: left;\n        width: 50%;\n        border: 1px solid black;\n      }\n      iframe {\n        width: 49%;\n        float: left;\n        height: 300px;\n        border: 1px solid black;\n        border-left: 0px;\n      }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">HTML5 preview</a>\n  </ul>\n</div>\n\n<article>\n<h2>HTML5 preview</h2>\n\n    <textarea id=code name=code>\n<!doctype html>\n<html>\n  <head>\n    <meta charset=utf-8>\n    <title>HTML5 canvas demo</title>\n    <style>p {font-family: monospace;}</style>\n  </head>\n  <body>\n    <p>Canvas pane goes here:</p>\n    <canvas id=pane width=300 height=200></canvas>\n    <script>\n      var canvas = document.getElementById('pane');\n      var context = canvas.getContext('2d');\n\n      context.fillStyle = 'rgb(250,0,0)';\n      context.fillRect(10, 10, 55, 50);\n\n      context.fillStyle = 'rgba(0, 0, 250, 0.5)';\n      context.fillRect(30, 30, 55, 50);\n    </script>\n  </body>\n</html></textarea>\n    <iframe id=preview></iframe>\n    <script>\n      var delay;\n      // Initialize CodeMirror editor with a nice html5 canvas demo.\n      var editor = CodeMirror.fromTextArea(document.getElementById('code'), {\n        mode: 'text/html'\n      });\n      editor.on(\"change\", function() {\n        clearTimeout(delay);\n        delay = setTimeout(updatePreview, 300);\n      });\n      \n      function updatePreview() {\n        var previewFrame = document.getElementById('preview');\n        var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;\n        preview.open();\n        preview.write(editor.getValue());\n        preview.close();\n      }\n      setTimeout(updatePreview, 300);\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/requirejs.html",
    "content": "<!doctype html>\n\n<head>\n  <title>CodeMirror: HTML completion demo</title>\n  <meta charset=\"utf-8\"/>\n  <link rel=stylesheet href=\"../doc/docs.css\">\n\n  <link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n  <link rel=\"stylesheet\" href=\"../addon/hint/show-hint.css\">\n  <script src=\"//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.min.js\"></script>\n  <style>\n    .CodeMirror {border-top: 1px solid #888; border-bottom: 1px solid #888;}\n  </style>\n</head>\n\n<body>\n  <div id=nav>\n    <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n    <ul>\n      <li><a href=\"../index.html\">Home</a>\n      <li><a href=\"../doc/manual.html\">Manual</a>\n      <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n    </ul>\n    <ul>\n      <li><a class=active href=\"#\">HTML completion</a>\n    </ul>\n  </div>\n\n  <article>\n    <h2>RequireJS module loading demo</h2>\n\n    <p>This demo does the same thing as\n    the <a href=\"html5complete.html\">HTML5 completion demo</a>, but\n    loads its dependencies\n    with <a href=\"http://requirejs.org/\">Require.js</a>, rather than\n    explicitly. Press <strong>ctrl-space</strong> to activate\n    completion.</p>\n\n    <div id=\"code\"></div>\n\n    <button id=\"markdown\">Dynamically load Markdown mode</button>\n\n    <script>\n      require.config({\n        packages: [{\n          name: \"codemirror\",\n          location: \"../\",\n          main: \"lib/codemirror\"\n        }]\n      });\n      require([\"codemirror\", \"codemirror/mode/htmlmixed/htmlmixed\",\n               \"codemirror/addon/hint/show-hint\", \"codemirror/addon/hint/html-hint\",\n               \"codemirror/addon/mode/loadmode\"], function(CodeMirror) {\n        editor = CodeMirror(document.getElementById(\"code\"), {\n          mode: \"text/html\",\n          extraKeys: {\"Ctrl-Space\": \"autocomplete\"},\n          value: document.documentElement.innerHTML\n        });\n\n        CodeMirror.modeURL = \"codemirror/mode/%N/%N\";\n        document.getElementById(\"markdown\").addEventListener(\"click\", function() {\n          CodeMirror.requireMode(\"markdown\", function() {\n            editor.replaceRange(\"This is **Markdown**.\\n\\n\", {line: 0, ch: 0});\n            editor.setOption(\"mode\", \"markdown\");\n          });\n        });\n      });\n    </script>\n  </article>\n</body>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/resize.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Autoresize Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/css/css.js\"></script>\n<style>\n      .CodeMirror {\n        border: 1px solid #eee;\n        height: auto;\n      }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Autoresize</a>\n  </ul>\n</div>\n\n<article>\n<h2>Autoresize Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n.CodeMirror {\n  border: 1px solid #eee;\n  height: auto;\n}\n</textarea></form>\n\n<p>By setting an editor's <code>height</code> style\nto <code>auto</code> and giving\nthe <a href=\"../doc/manual.html#option_viewportMargin\"><code>viewportMargin</code></a>\na value of <code>Infinity</code>, CodeMirror can be made to\nautomatically resize to fit its content.</p>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        viewportMargin: Infinity\n      });\n    </script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/rulers.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Ruler Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/display/rulers.js\"></script>\n<style>\n  .CodeMirror {border-top: 1px solid #888; border-bottom: 1px solid #888;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Ruler demo</a>\n  </ul>\n</div>\n\n<article>\n<h2>Ruler Demo</h2>\n\n<script>\n  var nums = \"0123456789\", space = \"          \";\n  var colors = [\"#fcc\", \"#f5f577\", \"#cfc\", \"#aff\", \"#ccf\", \"#fcf\"];\n  var rulers = [], value = \"\";\n  for (var i = 1; i <= 6; i++) {\n    rulers.push({color: colors[i], column: i * 10, lineStyle: \"dashed\"});\n    for (var j = 1; j < i; j++) value += space;\n    value += nums + \"\\n\";\n  }\n  var editor = CodeMirror(document.body.lastChild, {\n    rulers: rulers,\n    value: value + value + value,\n    lineNumbers: true\n});\n</script>\n\n<p>Demonstration of\nthe <a href=\"../doc/manual.html#addon_rulers\">rulers</a> addon, which\ndisplays vertical lines at given column offsets.</p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/runmode.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Mode Runner Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/runmode/runmode.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Mode Runner</a>\n  </ul>\n</div>\n\n<article>\n<h2>Mode Runner Demo</h2>\n\n\n    <textarea id=\"code\" style=\"width: 90%; height: 7em; border: 1px solid black; padding: .2em .4em;\">\n<foobar>\n  <blah>Enter your xml here and press the button below to display\n    it as highlighted by the CodeMirror XML mode</blah>\n  <tag2 foo=\"2\" bar=\"&amp;quot;bar&amp;quot;\"/>\n</foobar></textarea><br>\n    <button onclick=\"doHighlight();\">Highlight!</button>\n    <pre id=\"output\" class=\"cm-s-default\"></pre>\n\n    <script>\nfunction doHighlight() {\n  CodeMirror.runMode(document.getElementById(\"code\").value, \"application/xml\",\n                     document.getElementById(\"output\"));\n}\n</script>\n\n    <p>Running a CodeMirror mode outside of the editor.\n    The <code>CodeMirror.runMode</code> function, defined\n    in <code><a href=\"../addon/runmode/runmode.js\">addon/runmode/runmode.js</a></code> takes the following arguments:</p>\n\n    <dl>\n      <dt><code>text (string)</code></dt>\n      <dd>The document to run through the highlighter.</dd>\n      <dt><code>mode (<a href=\"../doc/manual.html#option_mode\">mode spec</a>)</code></dt>\n      <dd>The mode to use (must be loaded as normal).</dd>\n      <dt><code>output (function or DOM node)</code></dt>\n      <dd>If this is a function, it will be called for each token with\n      two arguments, the token's text and the token's style class (may\n      be <code>null</code> for unstyled tokens). If it is a DOM node,\n      the tokens will be converted to <code>span</code> elements as in\n      an editor, and inserted into the node\n      (through <code>innerHTML</code>).</dd>\n    </dl>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/search.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Search/Replace Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/dialog/dialog.css\">\n<link rel=\"stylesheet\" href=\"../addon/search/matchesonscrollbar.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../addon/dialog/dialog.js\"></script>\n<script src=\"../addon/search/searchcursor.js\"></script>\n<script src=\"../addon/search/search.js\"></script>\n<script src=\"../addon/scroll/annotatescrollbar.js\"></script>\n<script src=\"../addon/search/matchesonscrollbar.js\"></script>\n<script src=\"../addon/search/jump-to-line.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      dt {font-family: monospace; color: #666;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Search/Replace</a>\n  </ul>\n</div>\n\n<article>\n<h2>Search/Replace Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n<dl>\n  <dt id=\"option_indentWithTabs\"><code><strong>indentWithTabs</strong>: boolean</code></dt>\n  <dd>Whether, when indenting, the first N*<code>tabSize</code>\n  spaces should be replaced by N tabs. Default is false.</dd>\n\n  <dt id=\"option_electricChars\"><code><strong>electricChars</strong>: boolean</code></dt>\n  <dd>Configures whether the editor should re-indent the current\n  line when a character is typed that might change its proper\n  indentation (only works if the mode supports indentation).\n  Default is true.</dd>\n\n  <dt id=\"option_specialChars\"><code><strong>specialChars</strong>: RegExp</code></dt>\n  <dd>A regular expression used to determine which characters\n  should be replaced by a\n  special <a href=\"#option_specialCharPlaceholder\">placeholder</a>.\n  Mostly useful for non-printing special characters. The default\n  is <code>/[\\u0000-\\u0019\\u00ad\\u200b\\u2028\\u2029\\ufeff]/</code>.</dd>\n  <dt id=\"option_specialCharPlaceholder\"><code><strong>specialCharPlaceholder</strong>: function(char) → Element</code></dt>\n  <dd>A function that, given a special character identified by\n  the <a href=\"#option_specialChars\"><code>specialChars</code></a>\n  option, produces a DOM node that is used to represent the\n  character. By default, a red dot (<span style=\"color: red\">•</span>)\n  is shown, with a title tooltip to indicate the character code.</dd>\n\n  <dt id=\"option_rtlMoveVisually\"><code><strong>rtlMoveVisually</strong>: boolean</code></dt>\n  <dd>Determines whether horizontal cursor movement through\n  right-to-left (Arabic, Hebrew) text is visual (pressing the left\n  arrow moves the cursor left) or logical (pressing the left arrow\n  moves to the next lower index in the string, which is visually\n  right in right-to-left text). The default is <code>false</code>\n  on Windows, and <code>true</code> on other platforms.</dd>\n</dl>\n</textarea></form>\n\n    <script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  mode: \"text/html\",\n  lineNumbers: true,\n  extraKeys: {\"Alt-F\": \"findPersistent\"}\n});\n</script>\n\n    <p>Demonstration of primitive search/replace functionality. The\n    keybindings (which can be configured with custom keymaps) are:</p>\n    <dl>\n      <dt>Ctrl-F / Cmd-F</dt><dd>Start searching</dd>\n      <dt>Ctrl-G / Cmd-G</dt><dd>Find next</dd>\n      <dt>Shift-Ctrl-G / Shift-Cmd-G</dt><dd>Find previous</dd>\n      <dt>Shift-Ctrl-F / Cmd-Option-F</dt><dd>Replace</dd>\n      <dt>Shift-Ctrl-R / Shift-Cmd-Option-F</dt><dd>Replace all</dd>\n      <dt>Alt-F</dt><dd>Persistent search (dialog doesn't autoclose,\n      enter to find next, Shift-Enter to find previous)</dd>\n      <dt>Alt-G</dt><dd>Jump to line</dd>\n    </dl>\n    <p>Searching is enabled by\n    including <a href=\"../addon/search/search.js\">addon/search/search.js</a>\n    and <a href=\"../addon/search/searchcursor.js\">addon/search/searchcursor.js</a>.\n    Jump to line - including <a href=\"../addon/search/jump-to-line.js\">addon/search/jump-to-line.js</a>.</p>\n    <p>For good-looking input dialogs, you also want to include\n    <a href=\"../addon/dialog/dialog.js\">addon/dialog/dialog.js</a>\n    and <a href=\"../addon/dialog/dialog.css\">addon/dialog/dialog.css</a>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/simplemode.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Simple Mode Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/mode/simple.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<style>\n  .CodeMirror {border: 1px solid silver; margin-bottom: 1em; }\n  dt { text-indent: -2em; padding-left: 2em; margin-top: 1em; }\n  dd { margin-left: 1.5em; margin-bottom: 1em; }\n  dt {margin-top: 1em;}\n</style>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Simple Mode</a>\n  </ul>\n</div>\n\n<article>\n<h2>Simple Mode Demo</h2>\n\n<p>The <a href=\"../addon/mode/simple.js\"><code>mode/simple</code></a>\naddon allows CodeMirror modes to be specified using a relatively simple\ndeclarative format. This format is not as powerful as writing code\ndirectly against the <a href=\"../doc/manual.html#modeapi\">mode\ninterface</a>, but is a lot easier to get started with, and\nsufficiently expressive for many simple language modes.</p>\n\n<p>This interface is still in flux. It is unlikely to be scrapped or\noverhauled completely, so do start writing code against it, but\ndetails might change as it stabilizes, and you might have to tweak\nyour code when upgrading.</p>\n\n<p>Simple modes (loosely based on\nthe <a href=\"https://github.com/mozilla/skywriter/wiki/Common-JavaScript-Syntax-Highlighting-Specification\">Common\nJavaScript Syntax Highlighting Specification</a>, which never took\noff), are state machines, where each state has a number of rules that\nmatch tokens. A rule describes a type of token that may occur in the\ncurrent state, and possibly a transition to another state caused by\nthat token.</p>\n\n<p>The <code>CodeMirror.defineSimpleMode(name, states)</code> method\ntakes a mode name and an object that describes the mode's states. The\neditor below shows an example of such a mode (and is itself\nhighlighted by the mode shown in it).</p>\n\n<div id=\"code\"></div>\n\n<p>Each state is an array of rules. A rule may have the following properties:</p>\n\n<dl>\n  <dt><code><strong>regex</strong>: string | RegExp</code></dt>\n  <dd>The regular expression that matches the token. May be a string\n  or a regex object. When a regex, the <code>ignoreCase</code> flag\n  will be taken into account when matching the token. This regex\n  has to capture groups when the <code>token</code> property is\n  an array. If it captures groups, it must capture <em>all</em> of the string\n  (since JS provides no way to find out where a group matched).</dd>\n  <dt><code><strong>token</strong></code>: string | array&lt;string&gt; | null</dt>\n  <dd>An optional token style. Multiple styles can be specified by\n  separating them with dots or spaces. When this property holds an array of token styles,\n  the <code>regex</code> for this rule must capture a group for each array item.\n  </dd>\n  <dt><code><strong>sol</strong></code>: boolean</dt>\n  <dd>When true, this token will only match at the start of the line.\n  (The <code>^</code> regexp marker doesn't work as you'd expect in\n  this context because of limitations in JavaScript's RegExp\n  API.)</dd>\n  <dt><code><strong>next</strong>: string</code></dt>\n  <dd>When a <code>next</code> property is present, the mode will\n  transfer to the state named by the property when the token is\n  encountered.</dd>\n  <dt><code><strong>push</strong>: string</code></dt>\n  <dd>Like <code>next</code>, but instead replacing the current state\n  by the new state, the current state is kept on a stack, and can be\n  returned to with the <code>pop</code> directive.</dd>\n  <dt><code><strong>pop</strong>: bool</code></dt>\n  <dd>When true, and there is another state on the state stack, will\n  cause the mode to pop that state off the stack and transition to\n  it.</dd>\n  <dt><code><strong>mode</strong>: {spec, end, persistent}</code></dt>\n  <dd>Can be used to embed another mode inside a mode. When present,\n  must hold an object with a <code>spec</code> property that describes\n  the embedded mode, and an optional <code>end</code> end property\n  that specifies the regexp that will end the extent of the mode. When\n  a <code>persistent</code> property is set (and true), the nested\n  mode's state will be preserved between occurrences of the mode.</dd>\n  <dt><code><strong>indent</strong>: bool</code></dt>\n  <dd>When true, this token changes the indentation to be one unit\n  more than the current line's indentation.</dd>\n  <dt><code><strong>dedent</strong>: bool</code></dt>\n  <dd>When true, this token will pop one scope off the indentation\n  stack.</dd>\n  <dt><code><strong>dedentIfLineStart</strong>: bool</code></dt>\n  <dd>If a token has its <code>dedent</code> property set, it will, by\n  default, cause lines where it appears at the start to be dedented.\n  Set this property to false to prevent that behavior.</dd>\n</dl>\n\n<p>The <code>meta</code> property of the states object is special, and\nwill not be interpreted as a state. Instead, properties set on it will\nbe set on the mode, which is useful for properties\nlike <a href=\"../doc/manual.html#addon_comment\"><code>lineComment</code></a>,\nwhich sets the comment style for a mode. The simple mode addon also\nrecognizes a few such properties:</p>\n\n<dl>\n  <dt><code><strong>dontIndentStates</strong>: array&lt;string&gt;</code></dt>\n  <dd>An array of states in which the mode's auto-indentation should\n  not take effect. Usually used for multi-line comment and string\n  states.</dd>\n</dl>\n\n<script id=\"modecode\">/* Example definition of a simple mode that understands a subset of\n * JavaScript:\n */\n\nCodeMirror.defineSimpleMode(\"simplemode\", {\n  // The start state contains the rules that are intially used\n  start: [\n    // The regex matches the token, the token property contains the type\n    {regex: /\"(?:[^\\\\]|\\\\.)*?(?:\"|$)/, token: \"string\"},\n    // You can match multiple tokens at once. Note that the captured\n    // groups must span the whole string in this case\n    {regex: /(function)(\\s+)([a-z$][\\w$]*)/,\n     token: [\"keyword\", null, \"variable-2\"]},\n    // Rules are matched in the order in which they appear, so there is\n    // no ambiguity between this one and the one above\n    {regex: /(?:function|var|return|if|for|while|else|do|this)\\b/,\n     token: \"keyword\"},\n    {regex: /true|false|null|undefined/, token: \"atom\"},\n    {regex: /0x[a-f\\d]+|[-+]?(?:\\.\\d+|\\d+\\.?\\d*)(?:e[-+]?\\d+)?/i,\n     token: \"number\"},\n    {regex: /\\/\\/.*/, token: \"comment\"},\n    {regex: /\\/(?:[^\\\\]|\\\\.)*?\\//, token: \"variable-3\"},\n    // A next property will cause the mode to move to a different state\n    {regex: /\\/\\*/, token: \"comment\", next: \"comment\"},\n    {regex: /[-+\\/*=<>!]+/, token: \"operator\"},\n    // indent and dedent properties guide autoindentation\n    {regex: /[\\{\\[\\(]/, indent: true},\n    {regex: /[\\}\\]\\)]/, dedent: true},\n    {regex: /[a-z$][\\w$]*/, token: \"variable\"},\n    // You can embed other modes with the mode property. This rule\n    // causes all code between << and >> to be highlighted with the XML\n    // mode.\n    {regex: /<</, token: \"meta\", mode: {spec: \"xml\", end: />>/}}\n  ],\n  // The multi-line comment state.\n  comment: [\n    {regex: /.*?\\*\\//, token: \"comment\", next: \"start\"},\n    {regex: /.*/, token: \"comment\"}\n  ],\n  // The meta property contains global information about the mode. It\n  // can contain properties like lineComment, which are supported by\n  // all modes, and also directives like dontIndentStates, which are\n  // specific to simple modes.\n  meta: {\n    dontIndentStates: [\"comment\"],\n    lineComment: \"//\"\n  }\n});\n</script>\n\n<script>\nvar sc = document.getElementById(\"modecode\");\nvar code = document.getElementById(\"code\");\nvar editor = CodeMirror(code, {\n  value: (sc.textContent || sc.innerText || sc.innerHTML),\n  mode: \"simplemode\"\n});\n</script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/simplescrollbars.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Simple Scrollbar Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/scroll/simplescrollbars.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/markdown/markdown.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../addon/scroll/simplescrollbars.js\"></script>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Simple Scrollbar</a>\n  </ul>\n</div>\n\n<article>\n<h2>Simple Scrollbar Demo</h2>\n<form><textarea id=\"code\" name=\"code\"># Custom Scrollbars\n\nThis is a piece of text that creates scrollbars\n\nLorem ipsum dolor sit amet, turpis nec facilisis neque vestibulum adipiscing, magna nunc est luctus orci a,\naliquam duis ad volutpat nostra. Vestibulum ultricies suspendisse commodo volutpat pede sed. Bibendum odio\ndignissim, ad vitae mollis ac sed nibh quis, suspendisse diam, risus quas blandit phasellus luctus nec,\ninteger nunc vitae posuere scelerisque. Lobortis quam porta conubia nulla. Et nisl ac, imperdiet vitae ac.\nParturient sit. Et vestibulum euismod, rutrum nunc libero mauris purus convallis. Cum id adipiscing et eget\npretium rutrum, ultrices sapien magnis fringilla sit lorem, eu vitae scelerisque ipsum aliquet, magna sed\nfusce vel.\n\nLectus ultricies libero dolor convallis, sed etiam vel hendrerit egestas viverra, at urna mauris, eget\nvulputate dolor voluptatem, nulla eget sollicitudin. Sed tincidunt, elit sociis. Mattis mi tortor dui id\nsodales mi, maecenas nam fringilla risus turpis mauris praesent, imperdiet maecenas ultrices nonummy tellus\nquis est. Scelerisque nec pharetra quis varius fringilla. Varius vestibulum non dictum pharetra, tincidunt in\nvestibulum iaculis molestie, id condimentum blandit elit urna magna pulvinar, quam suspendisse pellentesque\ndonec. Vel amet ad ac. Nec aut viverra, morbi mi neque massa, turpis enim proin. Tellus eu, fermentum velit\nest convallis aliquam velit, rutrum in diam lacus, praesent tempor pellentesque dictum semper augue. Felis\nexplicabo massa amet lectus phasellus dolor. Ut lorem quis arcu neque felis ultricies, senectus vitae\ncurabitur sed pellentesque et, id sed risus in sed ac accumsan, blandit arcu quam duis nunc.\n\nSed leo sollicitudin odio vitae, purus sit egestas, justo eros inceptos auctor fermentum lectus. Ligula luctus\nturpis, quod massa vitae elementum orci, nullam fringilla elit tortor. Justo ante tempor amet quam posuere\nvolutpat. Facilisis pede erat ut hac ultrices ipsum, wisi duis sit metus. Dolor vitae est sed sed vitae. Sed\neu ligula, morbi vestibulum nunc nibh velit ut taciti, ligula elit semper sagittis in, auctor arcu vel eget.\nMauris at vitae nec suspendisse et, aenean proin blandit suscipit. Morbi quam, dolor ultricies. Viverra\ntempus. Suspendisse sit dapibus, ac fuga aenean, magna nisl nonummy augue posuere, dictum ut fuga velit\nparturient augue interdum, mattis sit tellus.\n\nVehicula commodo tempus curabitur eros, lacinia erat vulputate lorem vel fermentum donec, lectus sed conubia\nid pellentesque. Vel senectus donec pede aliquet dolor sit, nec vivamus justo placerat interdum maecenas,\nsodales euismod. Quis netus sapien amet, vestibulum quam nec amet lacinia, quis aliquet, tempor vivamus tellus\nenim, suscipit quis eleifend. Amet class phasellus orci pretium, risus in nulla. Neque sit ullamcorper,\nultricies platea id nec suspendisse ac. Et elementum. Dictum nam, ut dui fermentum egestas facilisis elit\naugue, adipiscing donec ipsum erat nam pellentesque convallis, vestibulum vestibulum risus id nulla ut mauris,\ncurabitur aute aptent. Ultrices orci wisi dui ipsum praesent, pharetra felis eu quis. Est fringilla etiam,\nmaxime sem dapibus et eget, mi enim dignissim nec pretium, augue vehicula, volutpat proin. Et occaecati\nlobortis viverra, cum in sed, vivamus tellus. Libero at malesuada est vivamus leo tortor.\n</textarea></form>\n\n<p>The <a href=\"../doc/manual.html#addon_simplescrollbars\"><code>simplescrollbars</code></a> addon defines two\nstyles of non-native scrollbars: <a href=\"javascript:editor.setOption('scrollbarStyle', 'simple')\"><code>\"simple\"</code></a> and <a href=\"javascript:editor.setOption('scrollbarStyle', 'overlay')\"><code>\"overlay\"</code></a> (click to try), which can be passed to\nthe <a href=\"../doc/manual.html#option_scrollbarStyle\"><code>scrollbarStyle</code></a> option. These implement\nthe scrollbar using DOM elements, allowing more control over\nits <a href=\"../addon/scroll/simplescrollbars.css\">appearance</a>.</p>\n\n  <script>\n    var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n      lineNumbers: true,\n      scrollbarStyle: \"simple\"\n    });\n  </script>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/spanaffectswrapping_shim.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Automatically derive odd wrapping behavior for your browser</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Automatically derive odd wrapping behavior for your browser</a>\n  </ul>\n</div>\n\n<article>\n<h2>Automatically derive odd wrapping behavior for your browser</h2>\n\n\n    <p>This is a hack to automatically derive\n    a <code>spanAffectsWrapping</code> regexp for a browser. See the\n    comments above that variable\n    in <a href=\"../lib/codemirror.js\"><code>lib/codemirror.js</code></a>\n    for some more details.</p>\n\n    <div style=\"white-space: pre-wrap; width: 50px;\" id=\"area\"></div>\n    <pre id=\"output\"></pre>\n\n    <script id=\"script\">\n      var a = document.getElementById(\"area\"), bad = Object.create(null);\n      var chars = \"a~`!@#$%^&*()-_=+}{[]\\\\|'\\\"/?.>,<:;\", l = chars.length;\n      for (var x = 0; x < l; ++x) for (var y = 0; y < l; ++y) {\n        var s1 = \"foooo\" + chars.charAt(x), s2 = chars.charAt(y) + \"br\";\n        a.appendChild(document.createTextNode(s1 + s2));\n        var h1 = a.offsetHeight;\n        a.innerHTML = \"\";\n        a.appendChild(document.createElement(\"span\")).appendChild(document.createTextNode(s1));\n        a.appendChild(document.createElement(\"span\")).appendChild(document.createTextNode(s2));\n        if (a.offsetHeight != h1)\n          bad[chars.charAt(x)] = (bad[chars.charAt(x)] || \"\") + chars.charAt(y);\n        a.innerHTML = \"\";\n      }\n\n      var re = \"\";\n      function toREElt(str) {\n        if (str.length > 1) {\n          var invert = false;\n          if (str.length > chars.length * .6) {\n            invert = true;\n            var newStr = \"\";\n            for (var i = 0; i < l; ++i) if (str.indexOf(chars.charAt(i)) == -1) newStr += chars.charAt(i);\n            str = newStr;\n          }\n          str = str.replace(/[\\-\\.\\]\\\"\\'\\\\\\/\\^a]/g, function(orig) { return orig == \"a\" ? \"\\\\w\" : \"\\\\\" + orig; });\n          return \"[\" + (invert ? \"^\" : \"\") + str + \"]\";\n        } else if (str == \"a\") {\n          return \"\\\\w\";\n        } else if (/[?$*()+{}[\\]\\.|/\\'\\\"]/.test(str)) {\n          return \"\\\\\" + str;\n        } else {\n          return str;\n        }\n      }\n\n      var newRE = \"\";\n      for (;;) {\n        var left = null;\n        for (var left in bad) break;\n        if (left == null) break;\n        var right = bad[left];\n        delete bad[left];\n        for (var other in bad) if (bad[other] == right) {\n          left += other;\n          delete bad[other];\n        }\n        newRE += (newRE ? \"|\" : \"\") + toREElt(left) + toREElt(right);\n      }\n\n      document.getElementById(\"output\").appendChild(document.createTextNode(\"Your regexp is: \" + (newRE || \"^$\")));\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/sublime.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Sublime Text bindings demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/fold/foldgutter.css\">\n<link rel=\"stylesheet\" href=\"../addon/dialog/dialog.css\">\n<link rel=\"stylesheet\" href=\"../theme/monokai.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/search/searchcursor.js\"></script>\n<script src=\"../addon/search/search.js\"></script>\n<script src=\"../addon/dialog/dialog.js\"></script>\n<script src=\"../addon/edit/matchbrackets.js\"></script>\n<script src=\"../addon/edit/closebrackets.js\"></script>\n<script src=\"../addon/comment/comment.js\"></script>\n<script src=\"../addon/wrap/hardwrap.js\"></script>\n<script src=\"../addon/fold/foldcode.js\"></script>\n<script src=\"../addon/fold/brace-fold.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../keymap/sublime.js\"></script>\n<style>\n  .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee; line-height: 1.3; height: 500px}\n  .CodeMirror-linenumbers { padding: 0 8px; }\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Sublime bindings</a>\n  </ul>\n</div>\n\n<article>\n<h2>Sublime Text bindings demo</h2>\n\n<p>The <code>sublime</code> keymap defines many Sublime Text-specific\nbindings for CodeMirror. See the code below for an overview.</p>\n\n<p>Enable the keymap by\nloading <a href=\"../keymap/sublime.js\"><code>keymap/sublime.js</code></a>\nand setting\nthe <a href=\"../doc/manual.html#option_keyMap\"><code>keyMap</code></a>\noption to <code>\"sublime\"</code>.</p>\n\n<p>(A lot of the search functionality is still missing.)\n\n<script>\n  var value = \"// The bindings defined specifically in the Sublime Text mode\\nvar bindings = {\\n\";\n  var map = CodeMirror.keyMap.sublime;\n  for (var key in map) {\n    var val = map[key];\n    if (key != \"fallthrough\" && val != \"...\" && (!/find/.test(val) || /findUnder/.test(val)))\n      value += \"  \\\"\" + key + \"\\\": \\\"\" + val + \"\\\",\\n\";\n  }\n  value += \"}\\n\\n// The implementation of joinLines\\n\";\n  value += CodeMirror.commands.joinLines.toString().replace(/^function\\s*\\(/, \"function joinLines(\").replace(/\\n  /g, \"\\n\") + \"\\n\";\n  var editor = CodeMirror(document.body.getElementsByTagName(\"article\")[0], {\n    value: value,\n    lineNumbers: true,\n    mode: \"javascript\",\n    keyMap: \"sublime\",\n    autoCloseBrackets: true,\n    matchBrackets: true,\n    showCursorWhenSelecting: true,\n    theme: \"monokai\",\n    tabSize: 2\n  });\n</script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/tern.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Tern Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/dialog/dialog.css\">\n<link rel=\"stylesheet\" href=\"../addon/hint/show-hint.css\">\n<link rel=\"stylesheet\" href=\"../addon/tern/tern.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../addon/dialog/dialog.js\"></script>\n<script src=\"../addon/hint/show-hint.js\"></script>\n<script src=\"../addon/tern/tern.js\"></script>\n<script src=\"//ternjs.net/node_modules/acorn/dist/acorn.js\"></script>\n<script src=\"//ternjs.net/node_modules/acorn-loose/dist/acorn-loose.js\"></script>\n<script src=\"//ternjs.net/node_modules/acorn-walk/dist/walk.js\"></script>\n<script src=\"//ternjs.net/doc/demo/polyfill.js\"></script>\n<script src=\"//ternjs.net/lib/signal.js\"></script>\n<script src=\"//ternjs.net/lib/tern.js\"></script>\n<script src=\"//ternjs.net/lib/def.js\"></script>\n<script src=\"//ternjs.net/lib/comment.js\"></script>\n<script src=\"//ternjs.net/lib/infer.js\"></script>\n<script src=\"//ternjs.net/plugin/doc_comment.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid #ddd;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Tern</a>\n  </ul>\n</div>\n\n<article>\n<h2>Tern Demo</h2>\n<form><textarea id=\"code\" name=\"code\">// Use ctrl-space to complete something\n// Put the cursor in or after an expression, press ctrl-o to\n// find its type\n\nvar foo = [\"array\", \"of\", \"strings\"];\nvar bar = foo.slice(0, 2).join(\"\").split(\"a\")[0];\n\n// Works for locally defined types too.\n\nfunction CTor() { this.size = 10; }\nCTor.prototype.hallo = \"hallo\";\n\nvar baz = new CTor;\nbaz.\n\n// You can press ctrl-q when the cursor is on a variable name to\n// rename it. Try it with CTor...\n\n// When the cursor is in an argument list, the arguments are\n// shown below the editor.\n\n[1].reduce(  );\n\n// And a little more advanced code...\n\n(function(exports) {\n  exports.randomElt = function(arr) {\n    return arr[Math.floor(arr.length * Math.random())];\n  };\n  exports.strList = \"foo\".split(\"\");\n  exports.intList = exports.strList.map(function(s) { return s.charCodeAt(0); });\n})(window.myMod = {});\n\nvar randomStr = myMod.randomElt(myMod.strList);\nvar randomInt = myMod.randomElt(myMod.intList);\n</textarea></form>\n\n<p>Demonstrates integration of <a href=\"http://ternjs.net/\">Tern</a>\nand CodeMirror. The following keys are bound:</p>\n\n<dl>\n  <dt>Ctrl-Space</dt><dd>Autocomplete</dd>\n  <dt>Ctrl-O</dt><dd>Find docs for the expression at the cursor</dd>\n  <dt>Ctrl-I</dt><dd>Find type at cursor</dd>\n  <dt>Alt-.</dt><dd>Jump to definition (Alt-, to jump back)</dd>\n  <dt>Ctrl-Q</dt><dd>Rename variable</dd>\n  <dt>Ctrl-.</dt><dd>Select all occurrences of a variable</dd>\n</dl>\n\n<p>Documentation is sparse for now. See the top of\nthe <a href=\"../addon/tern/tern.js\">script</a> for a rough API\noverview.</p>\n\n<script>\n  function getURL(url, c) {\n    var xhr = new XMLHttpRequest();\n    xhr.open(\"get\", url, true);\n    xhr.send();\n    xhr.onreadystatechange = function() {\n      if (xhr.readyState != 4) return;\n      if (xhr.status < 400) return c(null, xhr.responseText);\n      var e = new Error(xhr.responseText || \"No response\");\n      e.status = xhr.status;\n      c(e);\n    };\n  }\n\n  var server;\n  getURL(\"//ternjs.net/defs/ecmascript.json\", function(err, code) {\n    if (err) throw new Error(\"Request for ecmascript.json: \" + err);\n    server = new CodeMirror.TernServer({defs: [JSON.parse(code)]});\n    editor.setOption(\"extraKeys\", {\n      \"Ctrl-Space\": function(cm) { server.complete(cm); },\n      \"Ctrl-I\": function(cm) { server.showType(cm); },\n      \"Ctrl-O\": function(cm) { server.showDocs(cm); },\n      \"Alt-.\": function(cm) { server.jumpToDef(cm); },\n      \"Alt-,\": function(cm) { server.jumpBack(cm); },\n      \"Ctrl-Q\": function(cm) { server.rename(cm); },\n      \"Ctrl-.\": function(cm) { server.selectName(cm); }\n    })\n    editor.on(\"cursorActivity\", function(cm) { server.updateArgHints(cm); });\n  });\n\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    mode: \"javascript\"\n  });\n</script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/theme.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Theme Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../theme/3024-day.css\">\n<link rel=\"stylesheet\" href=\"../theme/3024-night.css\">\n<link rel=\"stylesheet\" href=\"../theme/abcdef.css\">\n<link rel=\"stylesheet\" href=\"../theme/ambiance.css\">\n<link rel=\"stylesheet\" href=\"../theme/base16-dark.css\">\n<link rel=\"stylesheet\" href=\"../theme/bespin.css\">\n<link rel=\"stylesheet\" href=\"../theme/base16-light.css\">\n<link rel=\"stylesheet\" href=\"../theme/blackboard.css\">\n<link rel=\"stylesheet\" href=\"../theme/cobalt.css\">\n<link rel=\"stylesheet\" href=\"../theme/colorforth.css\">\n<link rel=\"stylesheet\" href=\"../theme/dracula.css\">\n<link rel=\"stylesheet\" href=\"../theme/duotone-dark.css\">\n<link rel=\"stylesheet\" href=\"../theme/duotone-light.css\">\n<link rel=\"stylesheet\" href=\"../theme/eclipse.css\">\n<link rel=\"stylesheet\" href=\"../theme/elegant.css\">\n<link rel=\"stylesheet\" href=\"../theme/erlang-dark.css\">\n<link rel=\"stylesheet\" href=\"../theme/gruvbox-dark.css\">\n<link rel=\"stylesheet\" href=\"../theme/hopscotch.css\">\n<link rel=\"stylesheet\" href=\"../theme/icecoder.css\">\n<link rel=\"stylesheet\" href=\"../theme/isotope.css\">\n<link rel=\"stylesheet\" href=\"../theme/lesser-dark.css\">\n<link rel=\"stylesheet\" href=\"../theme/liquibyte.css\">\n<link rel=\"stylesheet\" href=\"../theme/lucario.css\">\n<link rel=\"stylesheet\" href=\"../theme/material.css\">\n<link rel=\"stylesheet\" href=\"../theme/mbo.css\">\n<link rel=\"stylesheet\" href=\"../theme/mdn-like.css\">\n<link rel=\"stylesheet\" href=\"../theme/midnight.css\">\n<link rel=\"stylesheet\" href=\"../theme/monokai.css\">\n<link rel=\"stylesheet\" href=\"../theme/neat.css\">\n<link rel=\"stylesheet\" href=\"../theme/neo.css\">\n<link rel=\"stylesheet\" href=\"../theme/night.css\">\n<link rel=\"stylesheet\" href=\"../theme/oceanic-next.css\">\n<link rel=\"stylesheet\" href=\"../theme/panda-syntax.css\">\n<link rel=\"stylesheet\" href=\"../theme/paraiso-dark.css\">\n<link rel=\"stylesheet\" href=\"../theme/paraiso-light.css\">\n<link rel=\"stylesheet\" href=\"../theme/pastel-on-dark.css\">\n<link rel=\"stylesheet\" href=\"../theme/railscasts.css\">\n<link rel=\"stylesheet\" href=\"../theme/rubyblue.css\">\n<link rel=\"stylesheet\" href=\"../theme/seti.css\">\n<link rel=\"stylesheet\" href=\"../theme/shadowfox.css\">\n<link rel=\"stylesheet\" href=\"../theme/solarized.css\">\n<link rel=\"stylesheet\" href=\"../theme/the-matrix.css\">\n<link rel=\"stylesheet\" href=\"../theme/tomorrow-night-bright.css\">\n<link rel=\"stylesheet\" href=\"../theme/tomorrow-night-eighties.css\">\n<link rel=\"stylesheet\" href=\"../theme/ttcn.css\">\n<link rel=\"stylesheet\" href=\"../theme/twilight.css\">\n<link rel=\"stylesheet\" href=\"../theme/vibrant-ink.css\">\n<link rel=\"stylesheet\" href=\"../theme/xq-dark.css\">\n<link rel=\"stylesheet\" href=\"../theme/xq-light.css\">\n<link rel=\"stylesheet\" href=\"../theme/yeti.css\">\n<link rel=\"stylesheet\" href=\"../theme/idea.css\">\n<link rel=\"stylesheet\" href=\"../theme/darcula.css\">\n<link rel=\"stylesheet\" href=\"../theme/zenburn.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../addon/selection/active-line.js\"></script>\n<script src=\"../addon/edit/matchbrackets.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid black; font-size:13px}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Theme</a>\n  </ul>\n</div>\n\n<article>\n<h2>Theme Demo</h2>\n<form><textarea id=\"code\" name=\"code\">\nfunction findSequence(goal) {\n  function find(start, history) {\n    if (start == goal)\n      return history;\n    else if (start > goal)\n      return null;\n    else\n      return find(start + 5, \"(\" + history + \" + 5)\") ||\n             find(start * 3, \"(\" + history + \" * 3)\");\n  }\n  return find(1, \"1\");\n}</textarea></form>\n\n<p>Select a theme: <select onchange=\"selectTheme()\" id=select>\n    <option selected>default</option>\n    <option>3024-day</option>\n    <option>3024-night</option>\n    <option>abcdef</option>\n    <option>ambiance</option>\n    <option>base16-dark</option>\n    <option>base16-light</option>\n    <option>bespin</option>\n    <option>blackboard</option>\n    <option>cobalt</option>\n    <option>colorforth</option>\n    <option>darcula</option>\n    <option>dracula</option>\n    <option>duotone-dark</option>\n    <option>duotone-light</option>\n    <option>eclipse</option>\n    <option>elegant</option>\n    <option>erlang-dark</option>\n    <option>gruvbox-dark</option>\n    <option>hopscotch</option>\n    <option>icecoder</option>\n    <option>idea</option>\n    <option>isotope</option>\n    <option>lesser-dark</option>\n    <option>liquibyte</option>\n    <option>lucario</option>\n    <option>material</option>\n    <option>mbo</option>\n    <option>mdn-like</option>\n    <option>midnight</option>\n    <option>monokai</option>\n    <option>neat</option>\n    <option>neo</option>\n    <option>night</option>\n    <option>oceanic-next</option>\n    <option>panda-syntax</option>\n    <option>paraiso-dark</option>\n    <option>paraiso-light</option>\n    <option>pastel-on-dark</option>\n    <option>railscasts</option>\n    <option>rubyblue</option>\n    <option>seti</option>\n    <option>shadowfox</option>\n    <option>solarized dark</option>\n    <option>solarized light</option>\n    <option>the-matrix</option>\n    <option>tomorrow-night-bright</option>\n    <option>tomorrow-night-eighties</option>\n    <option>ttcn</option>\n    <option>twilight</option>\n    <option>vibrant-ink</option>\n    <option>xq-dark</option>\n    <option>xq-light</option>\n    <option>yeti</option>\n    <option>zenburn</option>\n</select>\n</p>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    styleActiveLine: true,\n    matchBrackets: true\n  });\n  var input = document.getElementById(\"select\");\n  function selectTheme() {\n    var theme = input.options[input.selectedIndex].textContent;\n    editor.setOption(\"theme\", theme);\n    location.hash = \"#\" + theme;\n  }\n  var choice = (location.hash && location.hash.slice(1)) ||\n               (document.location.search &&\n                decodeURIComponent(document.location.search.slice(1)));\n  if (choice) {\n    input.value = choice;\n    editor.setOption(\"theme\", choice);\n  }\n  CodeMirror.on(window, \"hashchange\", function() {\n    var theme = location.hash.slice(1);\n    if (theme) { input.value = theme; selectTheme(); }\n  });\n</script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/trailingspace.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Trailing Whitespace Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/edit/trailingspace.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      .cm-trailingspace {\n        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAYAAAB/qH1jAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QUXCToH00Y1UgAAACFJREFUCNdjPMDBUc/AwNDAAAFMTAwMDA0OP34wQgX/AQBYgwYEx4f9lQAAAABJRU5ErkJggg==);\n        background-position: bottom left;\n        background-repeat: repeat-x;\n      }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Trailing Whitespace</a>\n  </ul>\n</div>\n\n<article>\n<h2>Trailing Whitespace Demo</h2>\n<form><textarea id=\"code\" name=\"code\">This text  \n has some\t \ntrailing whitespace!</textarea></form>\n\n    <script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true,\n  showTrailingSpace: true\n});\n</script>\n\n<p>Uses\nthe <a href=\"../doc/manual.html#addon_trailingspace\">trailingspace</a>\naddon to highlight trailing whitespace.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/variableheight.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Variable Height Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/markdown/markdown.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid silver; border-width: 1px 2px; }\n      .cm-header { font-family: arial; }\n      .cm-header-1 { font-size: 150%; }\n      .cm-header-2 { font-size: 130%; }\n      .cm-header-3 { font-size: 120%; }\n      .cm-header-4 { font-size: 110%; }\n      .cm-header-5 { font-size: 100%; }\n      .cm-header-6 { font-size: 90%; }\n      .cm-strong { font-size: 140%; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Variable Height</a>\n  </ul>\n</div>\n\n<article>\n<h2>Variable Height Demo</h2>\n<form><textarea id=\"code\" name=\"code\"># A First Level Header\n\n**Bold** text in a normal-size paragraph.\n\nAnd a very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long, wrapped line with a piece of **big** text inside of it.\n\n## A Second Level Header\n\nNow is the time for all good men to come to\nthe aid of their country. This is just a\nregular paragraph.\n\nThe quick brown fox jumped over the lazy\ndog's back.\n\n### Header 3\n\n> This is a blockquote.\n> \n> This is the second paragraph in the blockquote.\n>\n> ## This is an H2 in a blockquote       \n</textarea></form>\n    <script id=\"script\">\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        lineWrapping: true,\n        mode: \"markdown\"\n      });\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/vim.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Vim bindings demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/dialog/dialog.css\">\n<link rel=\"stylesheet\" href=\"../theme/midnight.css\">\n<link rel=\"stylesheet\" href=\"../theme/solarized.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/dialog/dialog.js\"></script>\n<script src=\"../addon/search/searchcursor.js\"></script>\n<script src=\"../mode/clike/clike.js\"></script>\n<script src=\"../addon/edit/matchbrackets.js\"></script>\n<script src=\"../keymap/vim.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Vim bindings</a>\n  </ul>\n</div>\n\n<article>\n<h2>Vim bindings demo</h2>\n\n<p><strong style=\"color: #c33; text-decoration: none\">Note:</strong> The CodeMirror vim bindings do not have an\nactive maintainer. That means that if you report bugs in it, they are\nlikely to go unanswered. It also means that if you want to help, you\nare very welcome to look\nat <a href=\"https://github.com/codemirror/codemirror/issues?q=is%3Aissue+is%3Aopen+label%3Avim\">the\nopen issues</a> and see which ones you can solve.</p>\n\n<form><textarea id=\"code\" name=\"code\">\n#include \"syscalls.h\"\n/* getchar:  simple buffered version */\nint getchar(void)\n{\n  static char buf[BUFSIZ];\n  static char *bufp = buf;\n  static int n = 0;\n  if (n == 0) {  /* buffer is empty */\n    n = read(0, buf, sizeof buf);\n    bufp = buf;\n  }\n  return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n}\n</textarea></form>\n<div style=\"font-size: 13px; width: 300px; height: 30px;\">Key buffer: <span id=\"command-display\"></span></div>\n\n<p>The vim keybindings are enabled by including <code><a\nhref=\"../keymap/vim.js\">keymap/vim.js</a></code> and setting the\n<code>keyMap</code> option to <code>vim</code>.</p>\n\n<p><strong>Features</strong></p>\n\n<ul>\n  <li>All common motions and operators, including text objects</li>\n  <li>Operator motion orthogonality</li>\n  <li>Visual mode - characterwise, linewise, blockwise</li>\n  <li>Full macro support (q, @)</li>\n  <li>Incremental highlighted search (/, ?, #, *, g#, g*)</li>\n  <li>Search/replace with confirm (:substitute, :%s)</li>\n  <li>Search history</li>\n  <li>Jump lists (Ctrl-o, Ctrl-i)</li>\n  <li>Key/command mapping with API (:map, :nmap, :vmap)</li>\n  <li>Sort (:sort)</li>\n  <li>Marks (`, ')</li>\n  <li>:global</li>\n  <li>Insert mode behaves identical to base CodeMirror</li>\n  <li>Cross-buffer yank/paste</li>\n</ul>\n\n<p>For the full list of key mappings and Ex commands, refer to the\n<code>defaultKeymap</code> and <code>defaultExCommandMap</code> at the\ntop of <code><a href=\"../keymap/vim.js\">keymap/vim.js</a></code>.\n\n<p>Note that while the vim mode tries to emulate the most useful\nfeatures of vim as faithfully as possible, it does not strive to\nbecome a complete vim implementation</p>\n\n    <script>\n      CodeMirror.commands.save = function(){ alert(\"Saving\"); };\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"text/x-csrc\",\n        keyMap: \"vim\",\n        matchBrackets: true,\n        showCursorWhenSelecting: true,\n        inputStyle: \"contenteditable\"\n      });\n      var commandDisplay = document.getElementById('command-display');\n      var keys = '';\n      CodeMirror.on(editor, 'vim-keypress', function(key) {\n        keys = keys + key;\n        commandDisplay.innerHTML = keys;\n      });\n      CodeMirror.on(editor, 'vim-command-done', function(e) {\n        keys = '';\n        commandDisplay.innerHTML = keys;\n      });\n    </script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/visibletabs.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Visible tabs demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/clike/clike.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}\n      .cm-tab {\n         background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);\n         background-position: right;\n         background-repeat: no-repeat;\n      }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Visible tabs</a>\n  </ul>\n</div>\n\n<article>\n<h2>Visible tabs demo</h2>\n<form><textarea id=\"code\" name=\"code\">\n#include \"syscalls.h\"\n/* getchar:  simple buffered version */\nint getchar(void)\n{\n\tstatic char buf[BUFSIZ];\n\tstatic char *bufp = buf;\n\tstatic int n = 0;\n\tif (n == 0) {  /* buffer is empty */\n\t\tn = read(0, buf, sizeof buf);\n\t\tbufp = buf;\n\t}\n\treturn (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n}\n</textarea></form>\n\n<p>Tabs inside the editor are spans with the\nclass <code>cm-tab</code>, and can be styled.</p>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        tabSize: 4,\n        indentUnit: 4,\n        indentWithTabs: true,\n        mode: \"text/x-csrc\"\n      });\n    </script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/widget.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Inline Widget Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jshint/2.9.5/jshint.min.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid black;}\n      .lint-error {font-family: arial; font-size: 70%; background: #ffa; color: #a00; padding: 2px 5px 3px; }\n      .lint-error-icon {color: white; background-color: red; font-weight: bold; border-radius: 50%; padding: 0 3px; margin-right: 7px;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Inline Widget</a>\n  </ul>\n</div>\n\n<article>\n<h2>Inline Widget Demo</h2>\n\n\n    <div id=code></div>\n    <script id=\"script\">var widgets = []\nfunction updateHints() {\n  editor.operation(function(){\n    for (var i = 0; i < widgets.length; ++i)\n      editor.removeLineWidget(widgets[i]);\n    widgets.length = 0;\n\n    JSHINT(editor.getValue());\n    for (var i = 0; i < JSHINT.errors.length; ++i) {\n      var err = JSHINT.errors[i];\n      if (!err) continue;\n      var msg = document.createElement(\"div\");\n      var icon = msg.appendChild(document.createElement(\"span\"));\n      icon.innerHTML = \"!!\";\n      icon.className = \"lint-error-icon\";\n      msg.appendChild(document.createTextNode(err.reason));\n      msg.className = \"lint-error\";\n      widgets.push(editor.addLineWidget(err.line - 1, msg, {coverGutter: false, noHScroll: true}));\n    }\n  });\n  var info = editor.getScrollInfo();\n  var after = editor.charCoords({line: editor.getCursor().line + 1, ch: 0}, \"local\").top;\n  if (info.top + info.clientHeight < after)\n    editor.scrollTo(null, after - info.clientHeight + 3);\n}\n\nwindow.onload = function() {\n  var sc = document.getElementById(\"script\");\n  var content = sc.textContent || sc.innerText || sc.innerHTML;\n\n  window.editor = CodeMirror(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    mode: \"javascript\",\n    value: content\n  });\n\n  var waiting;\n  editor.on(\"change\", function() {\n    clearTimeout(waiting);\n    waiting = setTimeout(updateHints, 500);\n  });\n\n  setTimeout(updateHints, 100);\n};\n\n\"long line to create a horizontal scrollbar, in order to test whether the (non-inline) widgets stay in place when scrolling to the right\";\n</script>\n<p>This demo runs <a href=\"http://jshint.com\">JSHint</a> over the code\nin the editor (which is the script used on this page), and\ninserts <a href=\"../doc/manual.html#addLineWidget\">line widgets</a> to\ndisplay the warnings that JSHint comes up with.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/demo/xmlcomplete.html",
    "content": "﻿<!doctype html>\n\n<title>CodeMirror: XML Autocomplete Demo</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../addon/hint/show-hint.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../addon/hint/show-hint.js\"></script>\n<script src=\"../addon/hint/xml-hint.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<style>\n      .CodeMirror { border: 1px solid #eee; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">XML Autocomplete</a>\n  </ul>\n</div>\n\n<article>\n<h2>XML Autocomplete Demo</h2>\n<form><textarea id=\"code\" name=\"code\"><!-- write some xml below -->\n</textarea></form>\n\n    <p>Press <strong>ctrl-space</strong>, or type a '&lt;' character to\n    activate autocompletion. This demo defines a simple schema that\n    guides completion. The schema can be customized—see\n    the <a href=\"../doc/manual.html#addon_xml-hint\">manual</a>.</p>\n\n    <p>Development of the <code>xml-hint</code> addon was kindly\n    sponsored\n    by <a href=\"http://www.xperiment.mobi\">www.xperiment.mobi</a>.</p>\n\n    <script>\n      var dummy = {\n        attrs: {\n          color: [\"red\", \"green\", \"blue\", \"purple\", \"white\", \"black\", \"yellow\"],\n          size: [\"large\", \"medium\", \"small\"],\n          description: null\n        },\n        children: []\n      };\n\n      var tags = {\n        \"!top\": [\"top\"],\n        \"!attrs\": {\n          id: null,\n          class: [\"A\", \"B\", \"C\"]\n        },\n        top: {\n          attrs: {\n            lang: [\"en\", \"de\", \"fr\", \"nl\"],\n            freeform: null\n          },\n          children: [\"animal\", \"plant\"]\n        },\n        animal: {\n          attrs: {\n            name: null,\n            isduck: [\"yes\", \"no\"]\n          },\n          children: [\"wings\", \"feet\", \"body\", \"head\", \"tail\"]\n        },\n        plant: {\n          attrs: {name: null},\n          children: [\"leaves\", \"stem\", \"flowers\"]\n        },\n        wings: dummy, feet: dummy, body: dummy, head: dummy, tail: dummy,\n        leaves: dummy, stem: dummy, flowers: dummy\n      };\n\n      function completeAfter(cm, pred) {\n        var cur = cm.getCursor();\n        if (!pred || pred()) setTimeout(function() {\n          if (!cm.state.completionActive)\n            cm.showHint({completeSingle: false});\n        }, 100);\n        return CodeMirror.Pass;\n      }\n\n      function completeIfAfterLt(cm) {\n        return completeAfter(cm, function() {\n          var cur = cm.getCursor();\n          return cm.getRange(CodeMirror.Pos(cur.line, cur.ch - 1), cur) == \"<\";\n        });\n      }\n\n      function completeIfInTag(cm) {\n        return completeAfter(cm, function() {\n          var tok = cm.getTokenAt(cm.getCursor());\n          if (tok.type == \"string\" && (!/['\"]/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1)) return false;\n          var inner = CodeMirror.innerMode(cm.getMode(), tok.state).state;\n          return inner.tagName;\n        });\n      }\n\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"xml\",\n        lineNumbers: true,\n        extraKeys: {\n          \"'<'\": completeAfter,\n          \"'/'\": completeIfAfterLt,\n          \"' '\": completeIfInTag,\n          \"'='\": completeIfInTag,\n          \"Ctrl-Space\": \"autocomplete\"\n        },\n        hintOptions: {schemaInfo: tags}\n      });\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/doc/activebookmark.js",
    "content": "// Kludge in HTML5 tag recognition in IE8\ndocument.createElement(\"section\");\ndocument.createElement(\"article\");\n\n(function() {\n  if (!window.addEventListener) return;\n  var pending = false, prevVal = null;\n\n  function updateSoon() {\n    if (!pending) {\n      pending = true;\n      setTimeout(update, 250);\n    }\n  }\n\n  function update() {\n    pending = false;\n    var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"), found;\n    for (var i = 0; i < marks.length; ++i) {\n      var mark = marks[i], m;\n      if (mark.getAttribute(\"data-default\")) {\n        if (found == null) found = i;\n      } else if (m = mark.href.match(/#(.*)/)) {\n        var ref = document.getElementById(m[1]);\n        if (ref && ref.getBoundingClientRect().top < 50)\n          found = i;\n      }\n    }\n    if (found != null && found != prevVal) {\n      prevVal = found;\n      var lis = document.getElementById(\"nav\").getElementsByTagName(\"li\");\n      for (var i = 0; i < lis.length; ++i) lis[i].className = \"\";\n      for (var i = 0; i < marks.length; ++i) {\n        if (found == i) {\n          marks[i].className = \"active\";\n          for (var n = marks[i]; n; n = n.parentNode)\n            if (n.nodeName == \"LI\") n.className = \"active\";\n        } else {\n          marks[i].className = \"\";\n        }\n      }\n    }\n  }\n\n  window.addEventListener(\"scroll\", updateSoon);\n  window.addEventListener(\"load\", updateSoon);\n  window.addEventListener(\"hashchange\", function() {\n    setTimeout(function() {\n      var hash = document.location.hash, found = null, m;\n      var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\");\n      for (var i = 0; i < marks.length; i++)\n        if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; }\n      if (found != null) for (var i = 0; i < marks.length; i++)\n        marks[i].className = i == found ? \"active\" : \"\";\n    }, 300);\n  });\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/doc/docs.css",
    "content": "@font-face {\n  font-family: 'Source Sans Pro';\n  font-style: normal;\n  font-weight: 400;\n  src: local('Source Sans Pro'), local('SourceSansPro-Regular'), url(//themes.googleusercontent.com/static/fonts/sourcesanspro/v5/ODelI1aHBYDBqgeIAH2zlBM0YzuT7MdOe03otPbuUS0.woff) format('woff');\n}\n\nbody, html { margin: 0; padding: 0; height: 100%; }\nsection, article { display: block; padding: 0; }\n\nbody {\n  background: #f8f8f8;\n  font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif;\n  line-height: 1.5;\n}\n\np { margin-top: 0; }\n\nh2, h3, h1 {\n  font-weight: normal;\n  margin-bottom: .7em;\n}\nh1 { font-size: 140%; }\nh2 { font-size: 120%; }\nh3 { font-size: 110%; }\narticle > h2:first-child, section:first-child > h2 { margin-top: 0; }\n\n#nav h1 {\n  margin-right: 12px;\n  margin-top: 0;\n  margin-bottom: 2px;\n  color: #d30707;\n  letter-spacing: .5px;\n}\n\na, a:visited, a:link, .quasilink {\n  color: #A21313;\n}\n\nem {\n  padding-right: 2px;\n}\n\n.quasilink {\n  cursor: pointer;\n}\n\narticle {\n  max-width: 700px;\n  margin: 0 0 0 160px;\n  border-left: 2px solid #E30808;\n  border-right: 1px solid #ddd;\n  padding: 30px 50px 100px 50px;\n  background: white;\n  z-index: 2;\n  position: relative;\n  min-height: 100%;\n  box-sizing: border-box;\n  -moz-box-sizing: border-box;\n}\n\n#nav {\n  position: fixed;\n  padding-top: 30px;\n  max-height: 100%;\n  box-sizing: -moz-border-box;\n  box-sizing: border-box;\n  overflow-y: auto;\n  left: 0; right: none;\n  width: 160px;\n  text-align: right;\n  z-index: 1;\n}\n\n@media screen and (min-width: 1000px) {\n  article {\n    margin: 0 auto;\n  }\n  #nav {\n    right: 50%;\n    width: auto;\n    border-right: 349px solid transparent;\n  }\n}\n\n#nav ul {\n  display: block;\n  margin: 0; padding: 0;\n  margin-bottom: 32px;\n}\n\n#nav a {\n  text-decoration: none;\n}\n\n#nav li {\n  display: block;\n  margin-bottom: 4px;\n}\n\n#nav li ul {\n  font-size: 80%;\n  margin-bottom: 0;\n  display: none;\n}\n\n#nav li.active ul {\n  display: block;\n}\n\n#nav li li a {\n  padding-right: 20px;\n  display: inline-block;\n}\n\n#nav ul a {\n  color: black;\n  padding: 0 7px 1px 11px;\n}\n\n#nav ul a.active, #nav ul a:hover {\n  border-bottom: 1px solid #E30808;\n  margin-bottom: -1px;\n  color: #E30808;\n}\n\n#logo {\n  border: 0;\n  margin-right: 12px;\n  margin-bottom: 25px;\n}\n\nsection {\n  border-top: 1px solid #E30808;\n  margin: 1.5em 0;\n}\n\nsection.first {\n  border: none;\n  margin-top: 0;\n}\n\n#demo {\n  position: relative;\n}\n\n#demolist {\n  position: absolute;\n  right: 5px;\n  top: 5px;\n  z-index: 25;\n}\n\n.yinyang {\n  position: absolute;\n  top: -10px;\n  left: 0; right: 0;\n  margin: auto;\n  display: block;\n  height: 120px;\n}\n\n.actions {\n  margin: 1em 0 0;\n  min-height: 100px;\n  position: relative;\n}\n\n.actionspicture {\n  pointer-events: none;\n  position: absolute;\n  height: 100px;\n  top: 0; left: 0; right: 0;\n}\n\n.actionlink {\n  pointer-events: auto;\n  font-family: arial;\n  font-size: 80%;\n  font-weight: bold;\n  position: absolute;\n  top: 0; bottom: 0;\n  line-height: 1;\n  height: 1em;\n  margin: auto;\n}\n\n.actionlink.download {\n  color: white;\n  right: 50%;\n  margin-right: 13px;\n  text-shadow: -1px 1px 3px #b00, -1px -1px 3px #b00, 1px 0px 3px #b00;\n}\n\n.actionlink.fund {\n  color: #b00;\n  left: 50%;\n  margin-left: 15px;\n}\n\n.actionlink:hover {\n  text-decoration: underline;\n}\n\n.actionlink a {\n  color: inherit;\n}\n\n.actionsleft {\n  float: left;\n}\n\n.actionsright {\n  float: right;\n  text-align: right;\n}\n\n@media screen and (max-width: 800px) {\n  .actions {\n    padding-top: 120px;\n  }\n  .actionsleft, .actionsright {\n    float: none;\n    text-align: left;\n    margin-bottom: 1em;\n  }\n}\n\nth {\n  text-decoration: underline;\n  font-weight: normal;\n  text-align: left;\n}\n\n#features ul {\n  list-style: none;\n  margin: 0 0 1em;\n  padding: 0 0 0 1.2em;\n}\n\n#features li:before {\n  content: \"-\";\n  width: 1em;\n  display: inline-block;\n  padding: 0;\n  margin: 0;\n  margin-left: -1em;\n}\n\n.rel {\n  margin-bottom: 0;\n}\n.rel-note {\n  margin-top: 0;\n  color: #555;\n}\n\npre {\n  padding-left: 15px;\n  border-left: 2px solid #ddd;\n}\n\ncode {\n  padding: 0 2px;\n}\n\nstrong {\n  text-decoration: underline;\n  font-weight: normal;\n}\n\n.field {\n  border: 1px solid #A21313;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/doc/internals.html",
    "content": "﻿<!doctype html>\n\n<title>CodeMirror: Internals</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"docs.css\">\n<style>dl dl {margin: 0;} .update {color: #d40 !important}</style>\n<script src=\"activebookmark.js\"></script>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"#top\">Introduction</a></li>\n    <li><a href=\"#approach\">General Approach</a></li>\n    <li><a href=\"#input\">Input</a></li>\n    <li><a href=\"#selection\">Selection</a></li>\n    <li><a href=\"#update\">Intelligent Updating</a></li>\n    <li><a href=\"#parse\">Parsing</a></li>\n    <li><a href=\"#summary\">What Gives?</a></li>\n    <li><a href=\"#btree\">Content Representation</a></li>\n    <li><a href=\"#keymap\">Key Maps</a></li>\n  </ul>\n</div>\n\n<article>\n\n<h2 id=top>(Re-) Implementing A Syntax-Highlighting Editor in JavaScript</h2>\n\n<p style=\"font-size: 85%\" id=\"intro\">\n  <strong>Topic:</strong> JavaScript, code editor implementation<br>\n  <strong>Author:</strong> Marijn Haverbeke<br>\n  <strong>Date:</strong> March 2nd 2011 (updated November 13th 2011)\n</p>\n\n<p style=\"padding: 0 3em 0 2em\"><strong>Caution</strong>: this text was written briefly after\nversion 2 was initially written. It no longer (even including the\nupdate at the bottom) fully represents the current implementation. I'm\nleaving it here as a historic document. For more up-to-date\ninformation, look at the entries\ntagged <a href=\"http://marijnhaverbeke.nl/blog/#cm-internals\">cm-internals</a>\non my blog.</p>\n\n<p>This is a followup to\nmy <a href=\"https://codemirror.net/story.html\">Brutal Odyssey to the\nDark Side of the DOM Tree</a> story. That one describes the\nmind-bending process of implementing (what would become) CodeMirror 1.\nThis one describes the internals of CodeMirror 2, a complete rewrite\nand rethink of the old code base. I wanted to give this piece another\nHunter Thompson copycat subtitle, but somehow that would be out of\nplace—the process this time around was one of straightforward\nengineering, requiring no serious mind-bending whatsoever.</p>\n\n<p>So, what is wrong with CodeMirror 1? I'd estimate, by mailing list\nactivity and general search-engine presence, that it has been\nintegrated into about a thousand systems by now. The most prominent\none, since a few weeks,\nbeing <a href=\"http://googlecode.blogspot.com/2011/01/make-quick-fixes-quicker-on-google.html\">Google\ncode's project hosting</a>. It works, and it's being used widely.</p>\n\n<p>Still, I did not start replacing it because I was bored. CodeMirror\n1 was heavily reliant on <code>designMode</code>\nor <code>contentEditable</code> (depending on the browser). Neither of\nthese are well specified (HTML5 tries\nto <a href=\"http://www.w3.org/TR/html5/editing.html#contenteditable\">specify</a>\ntheir basics), and, more importantly, they tend to be one of the more\nobscure and buggy areas of browser functionality—CodeMirror, by using\nthis functionality in a non-typical way, was constantly running up\nagainst browser bugs. WebKit wouldn't show an empty line at the end of\nthe document, and in some releases would suddenly get unbearably slow.\nFirefox would show the cursor in the wrong place. Internet Explorer\nwould insist on linkifying everything that looked like a URL or email\naddress, a behaviour that can't be turned off. Some bugs I managed to\nwork around (which was often a frustrating, painful process), others,\nsuch as the Firefox cursor placement, I gave up on, and had to tell\nuser after user that they were known problems, but not something I\ncould help.</p>\n\n<p>Also, there is the fact that <code>designMode</code> (which seemed\nto be less buggy than <code>contentEditable</code> in Webkit and\nFirefox, and was thus used by CodeMirror 1 in those browsers) requires\na frame. Frames are another tricky area. It takes some effort to\nprevent getting tripped up by domain restrictions, they don't\ninitialize synchronously, behave strangely in response to the back\nbutton, and, on several browsers, can't be moved around the DOM\nwithout having them re-initialize. They did provide a very nice way to\nnamespace the library, though—CodeMirror 1 could freely pollute the\nnamespace inside the frame.</p>\n\n<p>Finally, working with an editable document means working with\nselection in arbitrary DOM structures. Internet Explorer (8 and\nbefore) has an utterly different (and awkward) selection API than all\nof the other browsers, and even among the different implementations of\n<code>document.selection</code>, details about how exactly a selection\nis represented vary quite a bit. Add to that the fact that Opera's\nselection support tended to be very buggy until recently, and you can\nimagine why CodeMirror 1 contains 700 lines of selection-handling\ncode.</p>\n\n<p>And that brings us to the main issue with the CodeMirror 1\ncode base: The proportion of browser-bug-workarounds to real\napplication code was getting dangerously high. By building on top of a\nfew dodgy features, I put the system in a vulnerable position—any\nincompatibility and bugginess in these features, I had to paper over\nwith my own code. Not only did I have to do some serious stunt-work to\nget it to work on older browsers (as detailed in the\nprevious <a href=\"https://codemirror.net/story.html\">story</a>), things\nalso kept breaking in newly released versions, requiring me to come up\nwith <em>new</em> scary hacks in order to keep up. This was starting\nto lose its appeal.</p>\n\n<section id=approach>\n  <h2>General Approach</h2>\n\n<p>What CodeMirror 2 does is try to sidestep most of the hairy hacks\nthat came up in version 1. I owe a lot to the\n<a href=\"http://ace.ajax.org\">ACE</a> editor for inspiration on how to\napproach this.</p>\n\n<p>I absolutely did not want to be completely reliant on key events to\ngenerate my input. Every JavaScript programmer knows that key event\ninformation is horrible and incomplete. Some people (most awesomely\nMihai Bazon with <a href=\"http://ymacs.org\">Ymacs</a>) have been able\nto build more or less functioning editors by directly reading key\nevents, but it takes a lot of work (the kind of never-ending, fragile\nwork I described earlier), and will never be able to properly support\nthings like multi-keystoke international character\ninput. <a href=\"#keymap\" class=\"update\">[see below for caveat]</a></p>\n\n<p>So what I do is focus a hidden textarea, and let the browser\nbelieve that the user is typing into that. What we show to the user is\na DOM structure we built to represent his document. If this is updated\nquickly enough, and shows some kind of believable cursor, it feels\nlike a real text-input control.</p>\n\n<p>Another big win is that this DOM representation does not have to\nspan the whole document. Some CodeMirror 1 users insisted that they\nneeded to put a 30 thousand line XML document into CodeMirror. Putting\nall that into the DOM takes a while, especially since, for some\nreason, an editable DOM tree is slower than a normal one on most\nbrowsers. If we have full control over what we show, we must only\nensure that the visible part of the document has been added, and can\ndo the rest only when needed. (Fortunately, the <code>onscroll</code>\nevent works almost the same on all browsers, and lends itself well to\ndisplaying things only as they are scrolled into view.)</p>\n</section>\n<section id=\"input\">\n  <h2>Input</h2>\n\n<p>ACE uses its hidden textarea only as a text input shim, and does\nall cursor movement and things like text deletion itself by directly\nhandling key events. CodeMirror's way is to let the browser do its\nthing as much as possible, and not, for example, define its own set of\nkey bindings. One way to do this would have been to have the whole\ndocument inside the hidden textarea, and after each key event update\nthe display DOM to reflect what's in that textarea.</p>\n\n<p>That'd be simple, but it is not realistic. For even medium-sized\ndocument the editor would be constantly munging huge strings, and get\nterribly slow. What CodeMirror 2 does is put the current selection,\nalong with an extra line on the top and on the bottom, into the\ntextarea.</p>\n\n<p>This means that the arrow keys (and their ctrl-variations), home,\nend, etcetera, do not have to be handled specially. We just read the\ncursor position in the textarea, and update our cursor to match it.\nAlso, copy and paste work pretty much for free, and people get their\nnative key bindings, without any special work on my part. For example,\nI have emacs key bindings configured for Chrome and Firefox. There is\nno way for a script to detect this. <a class=\"update\"\nhref=\"#keymap\">[no longer the case]</a></p>\n\n<p>Of course, since only a small part of the document sits in the\ntextarea, keys like page up and ctrl-end won't do the right thing.\nCodeMirror is catching those events and handling them itself.</p>\n</section>\n<section id=\"selection\">\n  <h2>Selection</h2>\n\n<p>Getting and setting the selection range of a textarea in modern\nbrowsers is trivial—you just use the <code>selectionStart</code>\nand <code>selectionEnd</code> properties. On IE you have to do some\ninsane stuff with temporary ranges and compensating for the fact that\nmoving the selection by a 'character' will treat \\r\\n as a single\ncharacter, but even there it is possible to build functions that\nreliably set and get the selection range.</p>\n\n<p>But consider this typical case: When I'm somewhere in my document,\npress shift, and press the up arrow, something gets selected. Then, if\nI, still holding shift, press the up arrow again, the top of my\nselection is adjusted. The selection remembers where its <em>head</em>\nand its <em>anchor</em> are, and moves the head when we shift-move.\nThis is a generally accepted property of selections, and done right by\nevery editing component built in the past twenty years.</p>\n\n<p>But not something that the browser selection APIs expose.</p>\n\n<p>Great. So when someone creates an 'upside-down' selection, the next\ntime CodeMirror has to update the textarea, it'll re-create the\nselection as an 'upside-up' selection, with the anchor at the top, and\nthe next cursor motion will behave in an unexpected way—our second\nup-arrow press in the example above will not do anything, since it is\ninterpreted in exactly the same way as the first.</p>\n\n<p>No problem. We'll just, ehm, detect that the selection is\nupside-down (you can tell by the way it was created), and then, when\nan upside-down selection is present, and a cursor-moving key is\npressed in combination with shift, we quickly collapse the selection\nin the textarea to its start, allow the key to take effect, and then\ncombine its new head with its old anchor to get the <em>real</em>\nselection.</p>\n\n<p>In short, scary hacks could not be avoided entirely in CodeMirror\n2.</p>\n\n<p>And, the observant reader might ask, how do you even know that a\nkey combo is a cursor-moving combo, if you claim you support any\nnative key bindings? Well, we don't, but we can learn. The editor\nkeeps a set known cursor-movement combos (initialized to the\npredictable defaults), and updates this set when it observes that\npressing a certain key had (only) the effect of moving the cursor.\nThis, of course, doesn't work if the first time the key is used was\nfor extending an inverted selection, but it works most of the\ntime.</p>\n</section>\n<section id=\"update\">\n  <h2>Intelligent Updating</h2>\n\n<p>One thing that always comes up when you have a complicated internal\nstate that's reflected in some user-visible external representation\n(in this case, the displayed code and the textarea's content) is\nkeeping the two in sync. The naive way is to just update the display\nevery time you change your state, but this is not only error prone\n(you'll forget), it also easily leads to duplicate work on big,\ncomposite operations. Then you start passing around flags indicating\nwhether the display should be updated in an attempt to be efficient\nagain and, well, at that point you might as well give up completely.</p>\n\n<p>I did go down that road, but then switched to a much simpler model:\nsimply keep track of all the things that have been changed during an\naction, and then, only at the end, use this information to update the\nuser-visible display.</p>\n\n<p>CodeMirror uses a concept of <em>operations</em>, which start by\ncalling a specific set-up function that clears the state and end by\ncalling another function that reads this state and does the required\nupdating. Most event handlers, and all the user-visible methods that\nchange state are wrapped like this. There's a method\ncalled <code>operation</code> that accepts a function, and returns\nanother function that wraps the given function as an operation.</p>\n\n<p>It's trivial to extend this (as CodeMirror does) to detect nesting,\nand, when an operation is started inside an operation, simply\nincrement the nesting count, and only do the updating when this count\nreaches zero again.</p>\n\n<p>If we have a set of changed ranges and know the currently shown\nrange, we can (with some awkward code to deal with the fact that\nchanges can add and remove lines, so we're dealing with a changing\ncoordinate system) construct a map of the ranges that were left\nintact. We can then compare this map with the part of the document\nthat's currently visible (based on scroll offset and editor height) to\ndetermine whether something needs to be updated.</p>\n\n<p>CodeMirror uses two update algorithms—a full refresh, where it just\ndiscards the whole part of the DOM that contains the edited text and\nrebuilds it, and a patch algorithm, where it uses the information\nabout changed and intact ranges to update only the out-of-date parts\nof the DOM. When more than 30 percent (which is the current heuristic,\nmight change) of the lines need to be updated, the full refresh is\nchosen (since it's faster to do than painstakingly finding and\nupdating all the changed lines), in the other case it does the\npatching (so that, if you scroll a line or select another character,\nthe whole screen doesn't have to be\nre-rendered). <span class=\"update\">[the full-refresh\nalgorithm was dropped, it wasn't really faster than the patching\none]</span></p>\n\n<p>All updating uses <code>innerHTML</code> rather than direct DOM\nmanipulation, since that still seems to be by far the fastest way to\nbuild documents. There's a per-line function that combines the\nhighlighting, <a href=\"manual.html#markText\">marking</a>, and\nselection info for that line into a snippet of HTML. The patch updater\nuses this to reset individual lines, the refresh updater builds an\nHTML chunk for the whole visible document at once, and then uses a\nsingle <code>innerHTML</code> update to do the refresh.</p>\n</section>\n<section id=\"parse\">\n  <h2>Parsers can be Simple</h2>\n\n<p>When I wrote CodeMirror 1, I\nthought <a href=\"https://codemirror.net/story.html#parser\">interruptable\nparsers</a> were a hugely scary and complicated thing, and I used a\nbunch of heavyweight abstractions to keep this supposed complexity\nunder control: parsers\nwere <a href=\"http://bob.pythonmac.org/archives/2005/07/06/iteration-in-javascript/\">iterators</a>\nthat consumed input from another iterator, and used funny\nclosure-resetting tricks to copy and resume themselves.</p>\n\n<p>This made for a rather nice system, in that parsers formed strictly\nseparate modules, and could be composed in predictable ways.\nUnfortunately, it was quite slow (stacking three or four iterators on\ntop of each other), and extremely intimidating to people not used to a\nfunctional programming style.</p>\n\n<p>With a few small changes, however, we can keep all those\nadvantages, but simplify the API and make the whole thing less\nindirect and inefficient. CodeMirror\n2's <a href=\"manual.html#modeapi\">mode API</a> uses explicit state\nobjects, and makes the parser/tokenizer a function that simply takes a\nstate and a character stream abstraction, advances the stream one\ntoken, and returns the way the token should be styled. This state may\nbe copied, optionally in a mode-defined way, in order to be able to\ncontinue a parse at a given point. Even someone who's never touched a\nlambda in his life can understand this approach. Additionally, far\nfewer objects are allocated in the course of parsing now.</p>\n\n<p>The biggest speedup comes from the fact that the parsing no longer\nhas to touch the DOM though. In CodeMirror 1, on an older browser, you\ncould <em>see</em> the parser work its way through the document,\nmanaging some twenty lines in each 50-millisecond time slice it got. It\nwas reading its input from the DOM, and updating the DOM as it went\nalong, which any experienced JavaScript programmer will immediately\nspot as a recipe for slowness. In CodeMirror 2, the parser usually\nfinishes the whole document in a single 100-millisecond time slice—it\nmanages some 1500 lines during that time on Chrome. All it has to do\nis munge strings, so there is no real reason for it to be slow\nanymore.</p>\n</section>\n<section id=\"summary\">\n  <h2>What Gives?</h2>\n\n<p>Given all this, what can you expect from CodeMirror 2?</p>\n\n<ul>\n\n<li><strong>Small.</strong> the base library is\nsome <span class=\"update\">45k</span> when minified\nnow, <span class=\"update\">17k</span> when gzipped. It's smaller than\nits own logo.</li>\n\n<li><strong>Lightweight.</strong> CodeMirror 2 initializes very\nquickly, and does almost no work when it is not focused. This means\nyou can treat it almost like a textarea, have multiple instances on a\npage without trouble.</li>\n\n<li><strong>Huge document support.</strong> Since highlighting is\nreally fast, and no DOM structure is being built for non-visible\ncontent, you don't have to worry about locking up your browser when a\nuser enters a megabyte-sized document.</li>\n\n<li><strong>Extended API.</strong> Some things kept coming up in the\nmailing list, such as marking pieces of text or lines, which were\nextremely hard to do with CodeMirror 1. The new version has proper\nsupport for these built in.</li>\n\n<li><strong>Tab support.</strong> Tabs inside editable documents were,\nfor some reason, a no-go. At least six different people announced they\nwere going to add tab support to CodeMirror 1, none survived (I mean,\nnone delivered a working version). CodeMirror 2 no longer removes tabs\nfrom your document.</li>\n\n<li><strong>Sane styling.</strong> <code>iframe</code> nodes aren't\nreally known for respecting document flow. Now that an editor instance\nis a plain <code>div</code> element, it is much easier to size it to\nfit the surrounding elements. You don't even have to make it scroll if\nyou do not <a href=\"../demo/resize.html\">want to</a>.</li>\n\n</ul>\n\n<p>On the downside, a CodeMirror 2 instance is <em>not</em> a native\neditable component. Though it does its best to emulate such a\ncomponent as much as possible, there is functionality that browsers\njust do not allow us to hook into. Doing select-all from the context\nmenu, for example, is not currently detected by CodeMirror.</p>\n\n<p id=\"changes\" style=\"margin-top: 2em;\"><span style=\"font-weight:\nbold\">[Updates from November 13th 2011]</span> Recently, I've made\nsome changes to the codebase that cause some of the text above to no\nlonger be current. I've left the text intact, but added markers at the\npassages that are now inaccurate. The new situation is described\nbelow.</p>\n</section>\n<section id=\"btree\">\n  <h2>Content Representation</h2>\n\n<p>The original implementation of CodeMirror 2 represented the\ndocument as a flat array of line objects. This worked well—splicing\narrays will require the part of the array after the splice to be\nmoved, but this is basically just a simple <code>memmove</code> of a\nbunch of pointers, so it is cheap even for huge documents.</p>\n\n<p>However, I recently added line wrapping and code folding (line\ncollapsing, basically). Once lines start taking up a non-constant\namount of vertical space, looking up a line by vertical position\n(which is needed when someone clicks the document, and to determine\nthe visible part of the document during scrolling) can only be done\nwith a linear scan through the whole array, summing up line heights as\nyou go. Seeing how I've been going out of my way to make big documents\nfast, this is not acceptable.</p>\n\n<p>The new representation is based on a B-tree. The leaves of the tree\ncontain arrays of line objects, with a fixed minimum and maximum size,\nand the non-leaf nodes simply hold arrays of child nodes. Each node\nstores both the amount of lines that live below them and the vertical\nspace taken up by these lines. This allows the tree to be indexed both\nby line number and by vertical position, and all access has\nlogarithmic complexity in relation to the document size.</p>\n\n<p>I gave line objects and tree nodes parent pointers, to the node\nabove them. When a line has to update its height, it can simply walk\nthese pointers to the top of the tree, adding or subtracting the\ndifference in height from each node it encounters. The parent pointers\nalso make it cheaper (in complexity terms, the difference is probably\ntiny in normal-sized documents) to find the current line number when\ngiven a line object. In the old approach, the whole document array had\nto be searched. Now, we can just walk up the tree and count the sizes\nof the nodes coming before us at each level.</p>\n\n<p>I chose B-trees, not regular binary trees, mostly because they\nallow for very fast bulk insertions and deletions. When there is a big\nchange to a document, it typically involves adding, deleting, or\nreplacing a chunk of subsequent lines. In a regular balanced tree, all\nthese inserts or deletes would have to be done separately, which could\nbe really expensive. In a B-tree, to insert a chunk, you just walk\ndown the tree once to find where it should go, insert them all in one\nshot, and then break up the node if needed. This breaking up might\ninvolve breaking up nodes further up, but only requires a single pass\nback up the tree. For deletion, I'm somewhat lax in keeping things\nbalanced—I just collapse nodes into a leaf when their child count goes\nbelow a given number. This means that there are some weird editing\npatterns that may result in a seriously unbalanced tree, but even such\nan unbalanced tree will perform well, unless you spend a day making\nstrangely repeating edits to a really big document.</p>\n</section>\n<section id=\"keymap\">\n  <h2>Keymaps</h2>\n\n<p><a href=\"#approach\">Above</a>, I claimed that directly catching key\nevents for things like cursor movement is impractical because it\nrequires some browser-specific kludges. I then proceeded to explain\nsome awful <a href=\"#selection\">hacks</a> that were needed to make it\npossible for the selection changes to be detected through the\ntextarea. In fact, the second hack is about as bad as the first.</p>\n\n<p>On top of that, in the presence of user-configurable tab sizes and\ncollapsed and wrapped lines, lining up cursor movement in the textarea\nwith what's visible on the screen becomes a nightmare. Thus, I've\ndecided to move to a model where the textarea's selection is no longer\ndepended on.</p>\n\n<p>So I moved to a model where all cursor movement is handled by my\nown code. This adds support for a goal column, proper interaction of\ncursor movement with collapsed lines, and makes it possible for\nvertical movement to move through wrapped lines properly, instead of\njust treating them like non-wrapped lines.</p>\n\n<p>The key event handlers now translate the key event into a string,\nsomething like <code>Ctrl-Home</code> or <code>Shift-Cmd-R</code>, and\nuse that string to look up an action to perform. To make keybinding\ncustomizable, this lookup goes through\na <a href=\"manual.html#option_keyMap\">table</a>, using a scheme that\nallows such tables to be chained together (for example, the default\nMac bindings fall through to a table named 'emacsy', which defines\nbasic Emacs-style bindings like <code>Ctrl-F</code>, and which is also\nused by the custom Emacs bindings).</p>\n\n<p>A new\noption <a href=\"manual.html#option_extraKeys\"><code>extraKeys</code></a>\nallows ad-hoc keybindings to be defined in a much nicer way than what\nwas possible with the\nold <a href=\"manual.html#option_onKeyEvent\"><code>onKeyEvent</code></a>\ncallback. You simply provide an object mapping key identifiers to\nfunctions, instead of painstakingly looking at raw key events.</p>\n\n<p>Built-in commands map to strings, rather than functions, for\nexample <code>\"goLineUp\"</code> is the default action bound to the up\narrow key. This allows new keymaps to refer to them without\nduplicating any code. New commands can be defined by assigning to\nthe <code>CodeMirror.commands</code> object, which maps such commands\nto functions.</p>\n\n<p>The hidden textarea now only holds the current selection, with no\nextra characters around it. This has a nice advantage: polling for\ninput becomes much, much faster. If there's a big selection, this text\ndoes not have to be read from the textarea every time—when we poll,\njust noticing that something is still selected is enough to tell us\nthat no new text was typed.</p>\n\n<p>The reason that cheap polling is important is that many browsers do\nnot fire useful events on IME (input method engine) input, which is\nthe thing where people inputting a language like Japanese or Chinese\nuse multiple keystrokes to create a character or sequence of\ncharacters. Most modern browsers fire <code>input</code> when the\ncomposing is finished, but many don't fire anything when the character\nis updated <em>during</em> composition. So we poll, whenever the\neditor is focused, to provide immediate updates of the display.</p>\n\n</section>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/doc/manual.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: User Manual</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"docs.css\">\n<script src=\"activebookmark.js\"></script>\n\n<script src=\"../lib/codemirror.js\"></script>\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../addon/runmode/runmode.js\"></script>\n<script src=\"../addon/runmode/colorize.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../mode/css/css.js\"></script>\n<script src=\"../mode/htmlmixed/htmlmixed.js\"></script>\n<style>\n  dt { text-indent: -2em; padding-left: 2em; margin-top: 1em; }\n  dd { margin-left: 1.5em; margin-bottom: 1em; }\n  dt {margin-top: 1em;}\n  dd dl, dd dt, dd dd, dd ul { margin-top: 0; margin-bottom: 0; }\n  dt + dt { margin-top: 0; }\n  dt.command { position: relative; }\n  span.keybinding { position: absolute; right: 0; font-size: 80%; color: #555; text-indent: 0; }\n</style>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"logo.png\"></a>\n  <ul>\n    <li><a href=\"../index.html\">Home</a></li>\n    <li><a href=\"#overview\" class=active data-default=\"true\">Manual</a></li>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a></li>\n  </ul>\n  <ul>\n    <li><a href=\"#usage\">Basic Usage</a></li>\n    <li><a href=\"#config\">Configuration</a></li>\n    <li><a href=\"#events\">Events</a></li>\n    <li><a href=\"#keymaps\">Key maps</a></li>\n    <li><a href=\"#commands\">Commands</a></li>\n    <li><a href=\"#styling\">Customized Styling</a></li>\n    <li><a href=\"#api\">Programming API</a>\n      <ul>\n        <li><a href=\"#api_constructor\">Constructor</a></li>\n        <li><a href=\"#api_content\">Content manipulation</a></li>\n        <li><a href=\"#api_selection\">Selection</a></li>\n        <li><a href=\"#api_configuration\">Configuration</a></li>\n        <li><a href=\"#api_doc\">Document management</a></li>\n        <li><a href=\"#api_history\">History</a></li>\n        <li><a href=\"#api_marker\">Text-marking</a></li>\n        <li><a href=\"#api_decoration\">Widget, gutter, and decoration</a></li>\n        <li><a href=\"#api_sizing\">Sizing, scrolling, and positioning</a></li>\n        <li><a href=\"#api_mode\">Mode, state, and tokens</a></li>\n        <li><a href=\"#api_misc\">Miscellaneous methods</a></li>\n        <li><a href=\"#api_static\">Static properties</a></li>\n      </ul>\n    </li>\n    <li><a href=\"#addons\">Addons</a></li>\n    <li><a href=\"#modeapi\">Writing CodeMirror Modes</a></li>\n    <li><a href=\"#vimapi\">Vim Mode API</a>\n      <ul>\n        <li><a href=\"#vimapi_configuration\">Configuration</a></li>\n        <li><a href=\"#vimapi_extending\">Extending VIM</a></li>\n      </ul>\n    </li>\n  </ul>\n</div>\n\n<article>\n\n<section class=first id=overview>\n    <h2 style=\"position: relative\">\n      User manual and reference guide\n      <span style=\"color: #888; font-size: 1rem; position: absolute; right: 0; bottom: 0\">version 5.43.0</span>\n    </h2>\n\n    <p>CodeMirror is a code-editor component that can be embedded in\n    Web pages. The core library provides <em>only</em> the editor\n    component, no accompanying buttons, auto-completion, or other IDE\n    functionality. It does provide a rich API on top of which such\n    functionality can be straightforwardly implemented. See\n    the <a href=\"#addons\">addons</a> included in the distribution,\n    and the <a href=\"https://github.com/codemirror/CodeMirror/wiki/CodeMirror-addons\">list\n    of externally hosted addons</a>, for reusable\n    implementations of extra features.</p>\n\n    <p>CodeMirror works with language-specific modes. Modes are\n    JavaScript programs that help color (and optionally indent) text\n    written in a given language. The distribution comes with a number\n    of modes (see the <a href=\"../mode/\"><code>mode/</code></a>\n    directory), and it isn't hard to <a href=\"#modeapi\">write new\n    ones</a> for other languages.</p>\n</section>\n\n<section id=usage>\n    <h2>Basic Usage</h2>\n\n    <p>The easiest way to use CodeMirror is to simply load the script\n    and style sheet found under <code>lib/</code> in the distribution,\n    plus a mode script from one of the <code>mode/</code> directories.\n    For example:</p>\n\n    <pre data-lang=\"text/html\">&lt;script src=\"lib/codemirror.js\">&lt;/script>\n&lt;link rel=\"stylesheet\" href=\"lib/codemirror.css\">\n&lt;script src=\"mode/javascript/javascript.js\">&lt;/script></pre>\n\n    <p>(Alternatively, use a module loader. <a href=\"#modloader\">More\n    about that later.</a>)</p>\n\n    <p>Having done this, an editor instance can be created like\n    this:</p>\n\n    <pre data-lang=\"javascript\">var myCodeMirror = CodeMirror(document.body);</pre>\n\n    <p>The editor will be appended to the document body, will start\n    empty, and will use the mode that we loaded. To have more control\n    over the new editor, a configuration object can be passed\n    to <a href=\"#CodeMirror\"><code>CodeMirror</code></a> as a second\n    argument:</p>\n\n    <pre data-lang=\"javascript\">var myCodeMirror = CodeMirror(document.body, {\n  value: \"function myScript(){return 100;}\\n\",\n  mode:  \"javascript\"\n});</pre>\n\n    <p>This will initialize the editor with a piece of code already in\n    it, and explicitly tell it to use the JavaScript mode (which is\n    useful when multiple modes are loaded).\n    See <a href=\"#config\">below</a> for a full discussion of the\n    configuration options that CodeMirror accepts.</p>\n\n    <p>In cases where you don't want to append the editor to an\n    element, and need more control over the way it is inserted, the\n    first argument to the <code>CodeMirror</code> function can also\n    be a function that, when given a DOM element, inserts it into the\n    document somewhere. This could be used to, for example, replace a\n    textarea with a real editor:</p>\n\n    <pre data-lang=\"javascript\">var myCodeMirror = CodeMirror(function(elt) {\n  myTextArea.parentNode.replaceChild(elt, myTextArea);\n}, {value: myTextArea.value});</pre>\n\n    <p>However, for this use case, which is a common way to use\n    CodeMirror, the library provides a much more powerful\n    shortcut:</p>\n\n    <pre data-lang=\"javascript\">var myCodeMirror = CodeMirror.fromTextArea(myTextArea);</pre>\n\n    <p>This will, among other things, ensure that the textarea's value\n    is updated with the editor's contents when the form (if it is part\n    of a form) is submitted. See the <a href=\"#fromTextArea\">API\n    reference</a> for a full description of this method.</p>\n\n    <h3 id=modloader>Module loaders</h3>\n\n    <p>The files in the CodeMirror distribution contain shims for\n    loading them (and their dependencies) in AMD or CommonJS\n    environments. If the variables <code>exports</code>\n    and <code>module</code> exist and have type object, CommonJS-style\n    require will be used. If not, but there is a\n    function <code>define</code> with an <code>amd</code> property\n    present, AMD-style (RequireJS) will be used.</p>\n\n    <p>It is possible to\n    use <a href=\"http://browserify.org/\">Browserify</a> or similar\n    tools to statically build modules using CodeMirror. Alternatively,\n    use <a href=\"http://requirejs.org/\">RequireJS</a> to dynamically\n    load dependencies at runtime. Both of these approaches have the\n    advantage that they don't use the global namespace and can, thus,\n    do things like load multiple versions of CodeMirror alongside each\n    other.</p>\n\n    <p>Here's a simple example of using RequireJS to load CodeMirror:</p>\n\n    <pre data-lang=\"javascript\">require([\n  \"cm/lib/codemirror\", \"cm/mode/htmlmixed/htmlmixed\"\n], function(CodeMirror) {\n  CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    mode: \"htmlmixed\"\n  });\n});</pre>\n\n    <p>It will automatically load the modes that the mixed HTML mode\n    depends on (XML, JavaScript, and CSS). Do <em>not</em> use\n    RequireJS' <code>paths</code> option to configure the path to\n    CodeMirror, since it will break loading submodules through\n    relative paths. Use\n    the <a href=\"http://requirejs.org/docs/api.html#packages\"><code>packages</code></a>\n    configuration option instead, as in:</p>\n\n    <pre data-lang=javascript>require.config({\n  packages: [{\n    name: \"codemirror\",\n    location: \"../path/to/codemirror\",\n    main: \"lib/codemirror\"\n  }]\n});</pre>\n\n</section>\n\n<section id=config>\n    <h2>Configuration</h2>\n\n    <p>Both the <a href=\"#CodeMirror\"><code>CodeMirror</code></a>\n    function and its <code>fromTextArea</code> method take as second\n    (optional) argument an object containing configuration options.\n    Any option not supplied like this will be taken\n    from <a href=\"#defaults\"><code>CodeMirror.defaults</code></a>, an\n    object containing the default options. You can update this object\n    to change the defaults on your page.</p>\n\n    <p>Options are not checked in any way, so setting bogus option\n    values is bound to lead to odd errors.</p>\n\n    <p>These are the supported options:</p>\n\n    <dl>\n      <dt id=\"option_value\"><code><strong>value</strong>: string|CodeMirror.Doc</code></dt>\n      <dd>The starting value of the editor. Can be a string, or\n      a <a href=\"#api_doc\">document object</a>.</dd>\n\n      <dt id=\"option_mode\"><code><strong>mode</strong>: string|object</code></dt>\n      <dd>The mode to use. When not given, this will default to the\n      first mode that was loaded. It may be a string, which either\n      simply names the mode or is\n      a <a href=\"http://en.wikipedia.org/wiki/MIME\">MIME</a> type\n      associated with the mode. Alternatively, it may be an object\n      containing configuration options for the mode, with\n      a <code>name</code> property that names the mode (for\n      example <code>{name: \"javascript\", json: true}</code>). The demo\n      pages for each mode contain information about what configuration\n      parameters the mode supports. You can ask CodeMirror which modes\n      and MIME types have been defined by inspecting\n      the <code>CodeMirror.modes</code>\n      and <code>CodeMirror.mimeModes</code> objects. The first maps\n      mode names to their constructors, and the second maps MIME types\n      to mode specs.</dd>\n\n      <dt id=\"option_lineSeparator\"><code><strong>lineSeparator</strong>: string|null</code></dt>\n      <dd>Explicitly set the line separator for the editor. By default\n      (value <code>null</code>), the document will be split on CRLFs\n      as well as lone CRs and LFs, and a single LF will be used as\n      line separator in all output (such\n      as <a href=\"#getValue\"><code>getValue</code></a>). When a\n      specific string is given, lines will only be split on that\n      string, and output will, by default, use that same\n      separator.</dd>\n\n      <dt id=\"option_theme\"><code><strong>theme</strong>: string</code></dt>\n      <dd>The theme to style the editor with. You must make sure the\n      CSS file defining the corresponding <code>.cm-s-[name]</code>\n      styles is loaded (see\n      the <a href=\"../theme/\"><code>theme</code></a> directory in the\n      distribution). The default is <code>\"default\"</code>, for which\n      colors are included in <code>codemirror.css</code>. It is\n      possible to use multiple theming classes at once—for\n      example <code>\"foo bar\"</code> will assign both\n      the <code>cm-s-foo</code> and the <code>cm-s-bar</code> classes\n      to the editor.</dd>\n\n      <dt id=\"option_indentUnit\"><code><strong>indentUnit</strong>: integer</code></dt>\n      <dd>How many spaces a block (whatever that means in the edited\n      language) should be indented. The default is 2.</dd>\n\n      <dt id=\"option_smartIndent\"><code><strong>smartIndent</strong>: boolean</code></dt>\n      <dd>Whether to use the context-sensitive indentation that the\n      mode provides (or just indent the same as the line before).\n      Defaults to true.</dd>\n\n      <dt id=\"option_tabSize\"><code><strong>tabSize</strong>: integer</code></dt>\n      <dd>The width of a tab character. Defaults to 4.</dd>\n\n      <dt id=\"option_indentWithTabs\"><code><strong>indentWithTabs</strong>: boolean</code></dt>\n      <dd>Whether, when indenting, the first N*<code>tabSize</code>\n      spaces should be replaced by N tabs. Default is false.</dd>\n\n      <dt id=\"option_electricChars\"><code><strong>electricChars</strong>: boolean</code></dt>\n      <dd>Configures whether the editor should re-indent the current\n      line when a character is typed that might change its proper\n      indentation (only works if the mode supports indentation).\n      Default is true.</dd>\n\n      <dt id=\"option_specialChars\"><code><strong>specialChars</strong>: RegExp</code></dt>\n      <dd>A regular expression used to determine which characters\n      should be replaced by a\n      special <a href=\"#option_specialCharPlaceholder\">placeholder</a>.\n      Mostly useful for non-printing special characters. The default\n      is <code>/[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u061c\\u200b-\\u200f\\u2028\\u2029\\ufeff]/</code>.</dd>\n      <dt id=\"option_specialCharPlaceholder\"><code><strong>specialCharPlaceholder</strong>: function(char) → Element</code></dt>\n      <dd>A function that, given a special character identified by\n      the <a href=\"#option_specialChars\"><code>specialChars</code></a>\n      option, produces a DOM node that is used to represent the\n      character. By default, a red dot (<span style=\"color: red\">•</span>)\n      is shown, with a title tooltip to indicate the character code.</dd>\n\n      <dt id=\"option_direction\"><code><strong>direction</strong>: \"ltr\" | \"rtl\"</code></dt>\n      <dd>Flips overall layout and selects base paragraph direction to\n      be left-to-right or right-to-left.  Default is \"ltr\".\n      CodeMirror applies the Unicode Bidirectional Algorithm to each\n      line, but does not autodetect base direction — it's set to the\n      editor direction for all lines.  The resulting order is\n      sometimes wrong when base direction doesn't match user intent\n      (for example, leading and trailing punctuation jumps to the\n      wrong side of the line).  Therefore, it's helpful for\n      multilingual input to let users toggle this option.\n\n      <dt id=\"option_rtlMoveVisually\"><code><strong>rtlMoveVisually</strong>: boolean</code></dt>\n      <dd>Determines whether horizontal cursor movement through\n      right-to-left (Arabic, Hebrew) text is visual (pressing the left\n      arrow moves the cursor left) or logical (pressing the left arrow\n      moves to the next lower index in the string, which is visually\n      right in right-to-left text). The default is <code>false</code>\n      on Windows, and <code>true</code> on other platforms.</dd>\n\n      <dt id=\"option_keyMap\"><code><strong>keyMap</strong>: string</code></dt>\n      <dd>Configures the key map to use. The default\n      is <code>\"default\"</code>, which is the only key map defined\n      in <code>codemirror.js</code> itself. Extra key maps are found in\n      the <a href=\"../keymap/\"><code>key map</code></a> directory. See\n      the <a href=\"#keymaps\">section on key maps</a> for more\n      information.</dd>\n\n      <dt id=\"option_extraKeys\"><code><strong>extraKeys</strong>: object</code></dt>\n      <dd>Can be used to specify extra key bindings for the editor,\n      alongside the ones defined\n      by <a href=\"#option_keyMap\"><code>keyMap</code></a>. Should be\n      either null, or a valid <a href=\"#keymaps\">key map</a> value.</dd>\n\n      <dt id=\"option_configureMouse\"><code><strong>configureMouse</strong>: fn(cm: CodeMirror, repeat: \"single\" | \"double\" | \"triple\", event: Event) → Object</code></dt>\n      <dd>Allows you to configure the behavior of mouse selection and\n      dragging. The function is called when the left mouse button is\n      pressed. The returned object may have the following properties:\n        <dl>\n          <dt><code><strong>unit</strong>: \"char\" | \"word\" | \"line\" | \"rectangle\" | fn(CodeMirror, Pos) → {from: Pos, to: Pos}</code></dt>\n          <dd>The unit by which to select. May be one of the built-in\n          units or a function that takes a position and returns a\n          range around that, for a custom unit. The default is to\n          return <code>\"word\"</code> for double\n          clicks, <code>\"line\"</code> for triple\n          clicks, <code>\"rectangle\"</code> for alt-clicks (or, on\n          Chrome OS, meta-shift-clicks), and <code>\"single\"</code>\n          otherwise.</dd>\n          <dt><code><strong>extend</strong>: bool</code></dt>\n          <dd>Whether to extend the existing selection range or start\n          a new one. By default, this is enabled when shift\n          clicking.</dd>\n          <dt><code><strong>addNew</strong>: bool</code></dt>\n          <dd>When enabled, this adds a new range to the existing\n          selection, rather than replacing it. The default behavior is\n          to enable this for command-click on Mac OS, and\n          control-click on other platforms.</dd>\n          <dt><code><strong>moveOnDrag</strong>: bool</code></dt>\n          <dd>When the mouse even drags content around inside the\n          editor, this controls whether it is copied (false) or moved\n          (true). By default, this is enabled by alt-clicking on Mac\n          OS, and ctrl-clicking elsewhere.</dd>\n        </dl>\n      </dd>\n\n      <dt id=\"option_lineWrapping\"><code><strong>lineWrapping</strong>: boolean</code></dt>\n      <dd>Whether CodeMirror should scroll or wrap for long lines.\n      Defaults to <code>false</code> (scroll).</dd>\n\n      <dt id=\"option_lineNumbers\"><code><strong>lineNumbers</strong>: boolean</code></dt>\n      <dd>Whether to show line numbers to the left of the editor.</dd>\n\n      <dt id=\"option_firstLineNumber\"><code><strong>firstLineNumber</strong>: integer</code></dt>\n      <dd>At which number to start counting lines. Default is 1.</dd>\n\n      <dt id=\"option_lineNumberFormatter\"><code><strong>lineNumberFormatter</strong>: function(line: integer) → string</code></dt>\n      <dd>A function used to format line numbers. The function is\n      passed the line number, and should return a string that will be\n      shown in the gutter.</dd>\n\n      <dt id=\"option_gutters\"><code><strong>gutters</strong>: array&lt;string&gt;</code></dt>\n      <dd>Can be used to add extra gutters (beyond or instead of the\n      line number gutter). Should be an array of CSS class names, each\n      of which defines a <code>width</code> (and optionally a\n      background), and which will be used to draw the background of\n      the gutters. <em>May</em> include\n      the <code>CodeMirror-linenumbers</code> class, in order to\n      explicitly set the position of the line number gutter (it will\n      default to be to the right of all other gutters). These class\n      names are the keys passed\n      to <a href=\"#setGutterMarker\"><code>setGutterMarker</code></a>.</dd>\n\n      <dt id=\"option_fixedGutter\"><code><strong>fixedGutter</strong>: boolean</code></dt>\n      <dd>Determines whether the gutter scrolls along with the content\n      horizontally (false) or whether it stays fixed during horizontal\n      scrolling (true, the default).</dd>\n\n      <dt id=\"option_scrollbarStyle\"><code><strong>scrollbarStyle</strong>: string</code></dt>\n      <dd>Chooses a scrollbar implementation. The default\n      is <code>\"native\"</code>, showing native scrollbars. The core\n      library also provides the <code>\"null\"</code> style, which\n      completely hides the\n      scrollbars. <a href=\"#addon_simplescrollbars\">Addons</a> can\n      implement additional scrollbar models.</dd>\n\n      <dt id=\"option_coverGutterNextToScrollbar\"><code><strong>coverGutterNextToScrollbar</strong>: boolean</code></dt>\n      <dd>When <a href=\"#option_fixedGutter\"><code>fixedGutter</code></a>\n      is on, and there is a horizontal scrollbar, by default the\n      gutter will be visible to the left of this scrollbar. If this\n      option is set to true, it will be covered by an element with\n      class <code>CodeMirror-gutter-filler</code>.</dd>\n\n      <dt id=\"option_inputStyle\"><code><strong>inputStyle</strong>: string</code></dt>\n      <dd>Selects the way CodeMirror handles input and focus. The core\n      library defines the <code>\"textarea\"</code>\n      and <code>\"contenteditable\"</code> input models. On mobile\n      browsers, the default is <code>\"contenteditable\"</code>. On\n      desktop browsers, the default is <code>\"textarea\"</code>.\n      Support for IME and screen readers is better in\n      the <code>\"contenteditable\"</code> model. The intention is to\n      make it the default on modern desktop browsers in the\n      future.</dd>\n\n      <dt id=\"option_readOnly\"><code><strong>readOnly</strong>: boolean|string</code></dt>\n      <dd>This disables editing of the editor content by the user. If\n      the special value <code>\"nocursor\"</code> is given (instead of\n      simply <code>true</code>), focusing of the editor is also\n      disallowed.</dd>\n\n      <dt id=\"option_showCursorWhenSelecting\"><code><strong>showCursorWhenSelecting</strong>: boolean</code></dt>\n      <dd>Whether the cursor should be drawn when a selection is\n      active. Defaults to false.</dd>\n\n      <dt id=\"option_lineWiseCopyCut\"><code><strong>lineWiseCopyCut</strong>: boolean</code></dt>\n      <dd>When enabled, which is the default, doing copy or cut when\n      there is no selection will copy or cut the whole lines that have\n      cursors on them.</dd>\n\n      <dt id=\"option_pasteLinesPerSelection\"><code><strong>pasteLinesPerSelection</strong>: boolean</code></dt>\n      <dd>When pasting something from an external source (not from the\n      editor itself), if the number of lines matches the number of\n      selection, CodeMirror will by default insert one line per\n      selection. You can set this to <code>false</code> to disable\n      that behavior.</dd>\n\n      <dt id=\"option_selectionsMayTouch\"><code><strong>selectionsMayTouch</strong>: boolean</code></dt>\n      <dd>Determines whether multiple selections are joined as soon as\n      they touch (the default) or only when they overlap (true).</dd>\n\n      <dt id=\"option_undoDepth\"><code><strong>undoDepth</strong>: integer</code></dt>\n      <dd>The maximum number of undo levels that the editor stores.\n      Note that this includes selection change events. Defaults to\n      200.</dd>\n\n      <dt id=\"option_historyEventDelay\"><code><strong>historyEventDelay</strong>: integer</code></dt>\n      <dd>The period of inactivity (in milliseconds) that will cause a\n      new history event to be started when typing or deleting.\n      Defaults to 1250.</dd>\n\n      <dt id=\"option_tabindex\"><code><strong>tabindex</strong>: integer</code></dt>\n      <dd>The <a href=\"http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex\">tab\n      index</a> to assign to the editor. If not given, no tab index\n      will be assigned.</dd>\n\n      <dt id=\"option_autofocus\"><code><strong>autofocus</strong>: boolean</code></dt>\n      <dd>Can be used to make CodeMirror focus itself on\n      initialization. Defaults to off.\n      When <a href=\"#fromTextArea\"><code>fromTextArea</code></a> is\n      used, and no explicit value is given for this option, it will be\n      set to true when either the source textarea is focused, or it\n      has an <code>autofocus</code> attribute and no other element is\n      focused.</dd>\n\n      <dt id=\"option_phrases\"><code><strong>phrases</strong>: ?object</code></dt>\n      <dd>Some addons run user-visible strings (such as labels in the\n      interface) through the <a href=\"#phrase\"><code>phrase</code></a>\n      method to allow for translation. This option determines the\n      return value of that method. When it is null or an object that\n      doesn't have a property named by the input string, that string\n      is returned. Otherwise, the value of the property corresponding\n      to that string is returned.</dd>\n    </dl>\n\n    <p>Below this a few more specialized, low-level options are\n    listed. These are only useful in very specific situations, you\n    might want to skip them the first time you read this manual.</p>\n\n    <dl>\n      <dt id=\"option_dragDrop\"><code><strong>dragDrop</strong>: boolean</code></dt>\n      <dd>Controls whether drag-and-drop is enabled. On by default.</dd>\n\n      <dt id=\"option_allowDropFileTypes\"><code><strong>allowDropFileTypes</strong>: array&lt;string&gt;</code></dt>\n      <dd>When set (default is <code>null</code>) only files whose\n      type is in the array can be dropped into the editor. The strings\n      should be MIME types, and will be checked against\n      the <a href=\"https://w3c.github.io/FileAPI/#dfn-type\"><code>type</code></a>\n      of the <code>File</code> object as reported by the browser.</dd>\n\n      <dt id=\"option_cursorBlinkRate\"><code><strong>cursorBlinkRate</strong>: number</code></dt>\n      <dd>Half-period in milliseconds used for cursor blinking. The default blink\n      rate is 530ms. By setting this to zero, blinking can be disabled. A\n      negative value hides the cursor entirely.</dd>\n\n      <dt id=\"option_cursorScrollMargin\"><code><strong>cursorScrollMargin</strong>: number</code></dt>\n      <dd>How much extra space to always keep above and below the\n      cursor when approaching the top or bottom of the visible view in\n      a scrollable document. Default is 0.</dd>\n\n      <dt id=\"option_cursorHeight\"><code><strong>cursorHeight</strong>: number</code></dt>\n      <dd>Determines the height of the cursor. Default is 1, meaning\n      it spans the whole height of the line. For some fonts (and by\n      some tastes) a smaller height (for example <code>0.85</code>),\n      which causes the cursor to not reach all the way to the bottom\n      of the line, looks better</dd>\n\n      <dt id=\"option_resetSelectionOnContextMenu\"><code><strong>resetSelectionOnContextMenu</strong>: boolean</code></dt>\n      <dd>Controls whether, when the context menu is opened with a\n      click outside of the current selection, the cursor is moved to\n      the point of the click. Defaults to <code>true</code>.</dd>\n\n      <dt id=\"option_workTime\"><code id=\"option_wordkDelay\"><strong>workTime</strong>, <strong>workDelay</strong>: number</code></dt>\n      <dd>Highlighting is done by a pseudo background-thread that will\n      work for <code>workTime</code> milliseconds, and then use\n      timeout to sleep for <code>workDelay</code> milliseconds. The\n      defaults are 200 and 300, you can change these options to make\n      the highlighting more or less aggressive.</dd>\n\n      <dt id=\"option_pollInterval\"><code><strong>pollInterval</strong>: number</code></dt>\n      <dd>Indicates how quickly CodeMirror should poll its input\n      textarea for changes (when focused). Most input is captured by\n      events, but some things, like IME input on some browsers, don't\n      generate events that allow CodeMirror to properly detect it.\n      Thus, it polls. Default is 100 milliseconds.</dd>\n\n      <dt id=\"option_flattenSpans\"><code><strong>flattenSpans</strong>: boolean</code></dt>\n      <dd>By default, CodeMirror will combine adjacent tokens into a\n      single span if they have the same class. This will result in a\n      simpler DOM tree, and thus perform better. With some kinds of\n      styling (such as rounded corners), this will change the way the\n      document looks. You can set this option to false to disable this\n      behavior.</dd>\n\n      <dt id=\"option_addModeClass\"><code><strong>addModeClass</strong>: boolean</code></dt>\n      <dd>When enabled (off by default), an extra CSS class will be\n      added to each token, indicating the\n      (<a href=\"#innerMode\">inner</a>) mode that produced it, prefixed\n      with <code>\"cm-m-\"</code>. For example, tokens from the XML mode\n      will get the <code>cm-m-xml</code> class.</dd>\n\n      <dt id=\"option_maxHighlightLength\"><code><strong>maxHighlightLength</strong>: number</code></dt>\n      <dd>When highlighting long lines, in order to stay responsive,\n      the editor will give up and simply style the rest of the line as\n      plain text when it reaches a certain position. The default is\n      10 000. You can set this to <code>Infinity</code> to turn off\n      this behavior.</dd>\n\n      <dt id=\"option_viewportMargin\"><code><strong>viewportMargin</strong>: integer</code></dt>\n      <dd>Specifies the amount of lines that are rendered above and\n      below the part of the document that's currently scrolled into\n      view. This affects the amount of updates needed when scrolling,\n      and the amount of work that such an update does. You should\n      usually leave it at its default, 10. Can be set\n      to <code>Infinity</code> to make sure the whole document is\n      always rendered, and thus the browser's text search works on it.\n      This <em>will</em> have bad effects on performance of big\n      documents.</dd>\n      \n      <dt id=\"option_spellcheck\"><code><strong>spellcheck</strong>: boolean</code></dt>\n      <dd>Specifies whether or not spellcheck will be enabled on the input.</dd>\n      \n      <dt id=\"option_autocorrect\"><code><strong>autocorrect</strong>: boolean</code></dt>\n      <dd>Specifies whether or not autocorrect will be enabled on the input.</dd>\n      \n      <dt id=\"option_autocapitalize\"><code><strong>autocapitalize</strong>: boolean</code></dt>\n      <dd>Specifies whether or not autocapitalization will be enabled on the input.</dd>\n    </dl>\n</section>\n\n<section id=events>\n    <h2>Events</h2>\n\n    <p>Various CodeMirror-related objects emit events, which allow\n    client code to react to various situations. Handlers for such\n    events can be registered with the <a href=\"#on\"><code>on</code></a>\n    and <a href=\"#off\"><code>off</code></a> methods on the objects\n    that the event fires on. To fire your own events,\n    use <code>CodeMirror.signal(target, name, args...)</code>,\n    where <code>target</code> is a non-DOM-node object.</p>\n\n    <p>An editor instance fires the following events.\n    The <code>instance</code> argument always refers to the editor\n    itself.</p>\n\n    <dl>\n      <dt id=\"event_change\"><code><strong>\"change\"</strong> (instance: CodeMirror, changeObj: object)</code></dt>\n      <dd>Fires every time the content of the editor is changed.\n      The <code>changeObj</code> is a <code>{from, to, text, removed,\n      origin}</code> object containing information about the changes\n      that occurred as second argument. <code>from</code>\n      and <code>to</code> are the positions (in the pre-change\n      coordinate system) where the change started and ended (for\n      example, it might be <code>{ch:0, line:18}</code> if the\n      position is at the beginning of line #19). <code>text</code> is\n      an array of strings representing the text that replaced the\n      changed range (split by line). <code>removed</code> is the text\n      that used to be between <code>from</code> and <code>to</code>,\n      which is overwritten by this change. This event is\n      fired <em>before</em> the end of\n      an <a href=\"#operation\">operation</a>, before the DOM updates\n      happen.</dd>\n\n      <dt id=\"event_changes\"><code><strong>\"changes\"</strong> (instance: CodeMirror, changes: array&lt;object&gt;)</code></dt>\n      <dd>Like the <a href=\"#event_change\"><code>\"change\"</code></a>\n      event, but batched per <a href=\"#operation\">operation</a>,\n      passing an array containing all the changes that happened in the\n      operation. This event is fired after the operation finished, and\n      display changes it makes will trigger a new operation.</dd>\n\n      <dt id=\"event_beforeChange\"><code><strong>\"beforeChange\"</strong> (instance: CodeMirror, changeObj: object)</code></dt>\n      <dd>This event is fired before a change is applied, and its\n      handler may choose to modify or cancel the change.\n      The <code>changeObj</code> object\n      has <code>from</code>, <code>to</code>, and <code>text</code>\n      properties, as with\n      the <a href=\"#event_change\"><code>\"change\"</code></a> event. It\n      also has a <code>cancel()</code> method, which can be called to\n      cancel the change, and, <strong>if</strong> the change isn't\n      coming from an undo or redo event, an <code>update(from, to,\n      text)</code> method, which may be used to modify the change.\n      Undo or redo changes can't be modified, because they hold some\n      metainformation for restoring old marked ranges that is only\n      valid for that specific change. All three arguments\n      to <code>update</code> are optional, and can be left off to\n      leave the existing value for that field\n      intact. <strong>Note:</strong> you may not do anything from\n      a <code>\"beforeChange\"</code> handler that would cause changes\n      to the document or its visualization. Doing so will, since this\n      handler is called directly from the bowels of the CodeMirror\n      implementation, probably cause the editor to become\n      corrupted.</dd>\n\n      <dt id=\"event_cursorActivity\"><code><strong>\"cursorActivity\"</strong> (instance: CodeMirror)</code></dt>\n      <dd>Will be fired when the cursor or selection moves, or any\n      change is made to the editor content.</dd>\n\n      <dt id=\"event_keyHandled\"><code><strong>\"keyHandled\"</strong> (instance: CodeMirror, name: string, event: Event)</code></dt>\n      <dd>Fired after a key is handled through a\n      key map. <code>name</code> is the name of the handled key (for\n      example <code>\"Ctrl-X\"</code> or <code>\"'q'\"</code>),\n      and <code>event</code> is the DOM <code>keydown</code>\n      or <code>keypress</code> event.</dd>\n\n      <dt id=\"event_inputRead\"><code><strong>\"inputRead\"</strong> (instance: CodeMirror, changeObj: object)</code></dt>\n      <dd>Fired whenever new input is read from the hidden textarea\n      (typed or pasted by the user).</dd>\n\n      <dt id=\"event_electricInput\"><code><strong>\"electricInput\"</strong> (instance: CodeMirror, line: integer)</code></dt>\n      <dd>Fired if text input matched the\n      mode's <a href=\"#option_electricChars\">electric</a> patterns,\n      and this caused the line's indentation to change.</dd>\n\n      <dt id=\"event_beforeSelectionChange\"><code><strong>\"beforeSelectionChange\"</strong> (instance: CodeMirror, obj: {ranges, origin, update})</code></dt>\n      <dd>This event is fired before the selection is moved. Its\n      handler may inspect the set of selection ranges, present as an\n      array of <code>{anchor, head}</code> objects in\n      the <code>ranges</code> property of the <code>obj</code>\n      argument, and optionally change them by calling\n      the <code>update</code> method on this object, passing an array\n      of ranges in the same format. The object also contains\n      an <code>origin</code> property holding the origin string passed\n      to the selection-changing method, if any. Handlers for this\n      event have the same restriction\n      as <a href=\"#event_beforeChange\"><code>\"beforeChange\"</code></a>\n      handlers — they should not do anything to directly update the\n      state of the editor.</dd>\n\n      <dt id=\"event_viewportChange\"><code><strong>\"viewportChange\"</strong> (instance: CodeMirror, from: number, to: number)</code></dt>\n      <dd>Fires whenever the <a href=\"#getViewport\">view port</a> of\n      the editor changes (due to scrolling, editing, or any other\n      factor). The <code>from</code> and <code>to</code> arguments\n      give the new start and end of the viewport.</dd>\n\n      <dt id=\"event_swapDoc\"><code><strong>\"swapDoc\"</strong> (instance: CodeMirror, oldDoc: Doc)</code></dt>\n      <dd>This is signalled when the editor's document is replaced\n      using the <a href=\"#swapDoc\"><code>swapDoc</code></a>\n      method.</dd>\n\n      <dt id=\"event_gutterClick\"><code><strong>\"gutterClick\"</strong> (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)</code></dt>\n      <dd>Fires when the editor gutter (the line-number area) is\n      clicked. Will pass the editor instance as first argument, the\n      (zero-based) number of the line that was clicked as second\n      argument, the CSS class of the gutter that was clicked as third\n      argument, and the raw <code>mousedown</code> event object as\n      fourth argument.</dd>\n\n      <dt id=\"event_gutterContextMenu\"><code><strong>\"gutterContextMenu\"</strong> (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)</code></dt>\n      <dd>Fires when the editor gutter (the line-number area)\n      receives a <code>contextmenu</code> event. Will pass the editor\n      instance as first argument, the (zero-based) number of the line\n      that was clicked as second argument, the CSS class of the\n      gutter that was clicked as third argument, and the raw\n      <code>contextmenu</code> mouse event object as fourth argument.\n      You can <code>preventDefault</code> the event, to signal that\n      CodeMirror should do no further handling.</dd>\n\n      <dt id=\"event_focus\"><code><strong>\"focus\"</strong> (instance: CodeMirror, event: Event)</code></dt>\n      <dd>Fires whenever the editor is focused.</dd>\n\n      <dt id=\"event_blur\"><code><strong>\"blur\"</strong> (instance: CodeMirror, event: Event)</code></dt>\n      <dd>Fires whenever the editor is unfocused.</dd>\n\n      <dt id=\"event_scroll\"><code><strong>\"scroll\"</strong> (instance: CodeMirror)</code></dt>\n      <dd>Fires when the editor is scrolled.</dd>\n\n      <dt id=\"event_refresh\"><code><strong>\"refresh\"</strong> (instance: CodeMirror)</code></dt>\n      <dd>Fires when the editor is <a href=\"#refresh\">refreshed</a>\n      or <a href=\"#setSize\">resized</a>. Mostly useful to invalidate\n      cached values that depend on the editor or character size.</dd>\n\n      <dt id=\"event_optionChange\"><code><strong>\"optionChange\"</strong> (instance: CodeMirror, option: string)</code></dt>\n      <dd>Dispatched every time an option is changed with <a href=\"#setOption\"><code>setOption</code></a>.</dd>\n\n      <dt id=\"event_scrollCursorIntoView\"><code><strong>\"scrollCursorIntoView\"</strong> (instance: CodeMirror, event: Event)</code></dt>\n      <dd>Fires when the editor tries to scroll its cursor into view.\n      Can be hooked into to take care of additional scrollable\n      containers around the editor. When the event object has\n      its <code>preventDefault</code> method called, CodeMirror will\n      not itself try to scroll the window.</dd>\n\n      <dt id=\"event_update\"><code><strong>\"update\"</strong> (instance: CodeMirror)</code></dt>\n      <dd>Will be fired whenever CodeMirror updates its DOM display.</dd>\n\n      <dt id=\"event_renderLine\"><code><strong>\"renderLine\"</strong> (instance: CodeMirror, line: LineHandle, element: Element)</code></dt>\n      <dd>Fired whenever a line is (re-)rendered to the DOM. Fired\n      right after the DOM element is built, <em>before</em> it is\n      added to the document. The handler may mess with the style of\n      the resulting element, or add event handlers, but\n      should <em>not</em> try to change the state of the editor.</dd>\n\n      <dt id=\"event_dom\"><code><strong>\"mousedown\"</strong>,\n      <strong>\"dblclick\"</strong>, <strong>\"touchstart\"</strong>, <strong>\"contextmenu\"</strong>,\n      <strong>\"keydown\"</strong>, <strong>\"keypress\"</strong>,\n      <strong>\"keyup\"</strong>, <strong>\"cut\"</strong>, <strong>\"copy\"</strong>, <strong>\"paste\"</strong>,\n      <strong>\"dragstart\"</strong>, <strong>\"dragenter\"</strong>,\n      <strong>\"dragover\"</strong>, <strong>\"dragleave\"</strong>,\n      <strong>\"drop\"</strong>\n      (instance: CodeMirror, event: Event)</code></dt>\n      <dd>Fired when CodeMirror is handling a DOM event of this type.\n      You can <code>preventDefault</code> the event, or give it a\n      truthy <code>codemirrorIgnore</code> property, to signal that\n      CodeMirror should do no further handling.</dd>\n    </dl>\n\n    <p>Document objects (instances\n    of <a href=\"#Doc\"><code>CodeMirror.Doc</code></a>) emit the\n    following events:</p>\n\n    <dl>\n      <dt id=\"event_doc_change\"><code><strong>\"change\"</strong> (doc: CodeMirror.Doc, changeObj: object)</code></dt>\n      <dd>Fired whenever a change occurs to the\n      document. <code>changeObj</code> has a similar type as the\n      object passed to the\n      editor's <a href=\"#event_change\"><code>\"change\"</code></a>\n      event.</dd>\n\n      <dt id=\"event_doc_beforeChange\"><code><strong>\"beforeChange\"</strong> (doc: CodeMirror.Doc, change: object)</code></dt>\n      <dd>See the <a href=\"#event_beforeChange\">description of the\n      same event</a> on editor instances.</dd>\n\n      <dt id=\"event_doc_cursorActivity\"><code><strong>\"cursorActivity\"</strong> (doc: CodeMirror.Doc)</code></dt>\n      <dd>Fired whenever the cursor or selection in this document\n      changes.</dd>\n\n      <dt id=\"event_doc_beforeSelectionChange\"><code><strong>\"beforeSelectionChange\"</strong> (doc: CodeMirror.Doc, selection: {head, anchor})</code></dt>\n      <dd>Equivalent to\n      the <a href=\"#event_beforeSelectionChange\">event by the same\n      name</a> as fired on editor instances.</dd>\n    </dl>\n\n    <p>Line handles (as returned by, for\n    example, <a href=\"#getLineHandle\"><code>getLineHandle</code></a>)\n    support these events:</p>\n\n    <dl>\n      <dt id=\"event_delete\"><code><strong>\"delete\"</strong> ()</code></dt>\n      <dd>Will be fired when the line object is deleted. A line object\n      is associated with the <em>start</em> of the line. Mostly useful\n      when you need to find out when your <a href=\"#setGutterMarker\">gutter\n      markers</a> on a given line are removed.</dd>\n      <dt id=\"event_line_change\"><code><strong>\"change\"</strong> (line: LineHandle, changeObj: object)</code></dt>\n      <dd>Fires when the line's text content is changed in any way\n      (but the line is not deleted outright). The <code>change</code>\n      object is similar to the one passed\n      to <a href=\"#event_change\">change event</a> on the editor\n      object.</dd>\n    </dl>\n\n    <p>Marked range handles (<code>CodeMirror.TextMarker</code>), as returned\n    by <a href=\"#markText\"><code>markText</code></a>\n    and <a href=\"#setBookmark\"><code>setBookmark</code></a>, emit the\n    following events:</p>\n\n    <dl>\n      <dt id=\"event_beforeCursorEnter\"><code><strong>\"beforeCursorEnter\"</strong> ()</code></dt>\n      <dd>Fired when the cursor enters the marked range. From this\n      event handler, the editor state may be inspected\n      but <em>not</em> modified, with the exception that the range on\n      which the event fires may be cleared.</dd>\n      <dt id=\"event_clear\"><code><strong>\"clear\"</strong> (from: {line, ch}, to: {line, ch})</code></dt>\n      <dd>Fired when the range is cleared, either through cursor\n      movement in combination\n      with <a href=\"#mark_clearOnEnter\"><code>clearOnEnter</code></a>\n      or through a call to its <code>clear()</code> method. Will only\n      be fired once per handle. Note that deleting the range through\n      text editing does not fire this event, because an undo action\n      might bring the range back into existence. <code>from</code>\n      and <code>to</code> give the part of the document that the range\n      spanned when it was cleared.</dd>\n      <dt id=\"event_hide\"><code><strong>\"hide\"</strong> ()</code></dt>\n      <dd>Fired when the last part of the marker is removed from the\n      document by editing operations.</dd>\n      <dt id=\"event_unhide\"><code><strong>\"unhide\"</strong> ()</code></dt>\n      <dd>Fired when, after the marker was removed by editing, a undo\n      operation brought the marker back.</dd>\n    </dl>\n\n    <p>Line widgets (<code>CodeMirror.LineWidget</code>), returned\n    by <a href=\"#addLineWidget\"><code>addLineWidget</code></a>, fire\n    these events:</p>\n\n    <dl>\n      <dt id=\"event_redraw\"><code><strong>\"redraw\"</strong> ()</code></dt>\n      <dd>Fired whenever the editor re-adds the widget to the DOM.\n      This will happen once right after the widget is added (if it is\n      scrolled into view), and then again whenever it is scrolled out\n      of view and back in again, or when changes to the editor options\n      or the line the widget is on require the widget to be\n      redrawn.</dd>\n    </dl>\n</section>\n\n<section id=keymaps>\n    <h2>Key Maps</h2>\n\n    <p>Key maps are ways to associate keys and mouse buttons with\n    functionality. A key map is an object mapping strings that\n    identify the buttons to functions that implement their\n    functionality.</p>\n\n    <p>The CodeMirror distributions comes\n    with <a href=\"../demo/emacs.html\">Emacs</a>, <a href=\"../demo/vim.html\">Vim</a>,\n    and <a href=\"../demo/sublime.html\">Sublime Text</a>-style keymaps.</p>\n\n    <p>Keys are identified either by name or by character.\n    The <code>CodeMirror.keyNames</code> object defines names for\n    common keys and associates them with their key codes. Examples of\n    names defined here are <code>Enter</code>, <code>F5</code>,\n    and <code>Q</code>. These can be prefixed\n    with <code>Shift-</code>, <code>Cmd-</code>, <code>Ctrl-</code>,\n    and <code>Alt-</code> to specify a modifier. So for\n    example, <code>Shift-Ctrl-Space</code> would be a valid key\n    identifier.</p>\n\n    <p>Common example: map the Tab key to insert spaces instead of a tab\n    character.</p>\n\n    <pre data-lang=\"javascript\">\neditor.setOption(\"extraKeys\", {\n  Tab: function(cm) {\n    var spaces = Array(cm.getOption(\"indentUnit\") + 1).join(\" \");\n    cm.replaceSelection(spaces);\n  }\n});</pre>\n\n    <p>Alternatively, a character can be specified directly by\n    surrounding it in single quotes, for example <code>'$'</code>\n    or <code>'q'</code>. Due to limitations in the way browsers fire\n    key events, these may not be prefixed with modifiers.</p>\n\n    <p>To bind mouse buttons, use the names `LeftClick`,\n    `MiddleClick`, and `RightClick`. These can also be prefixed with\n    modifiers, and in addition, the word `Double` or `Triple` can be\n    put before `Click` (as in `LeftDoubleClick`) to bind a double- or\n    triple-click. The function for such a binding is passed the\n    position that was clicked as second argument.</p>\n\n    <p id=\"normalizeKeyMap\">Multi-stroke key bindings can be specified\n    by separating the key names by spaces in the property name, for\n    example <code>Ctrl-X Ctrl-V</code>. When a map contains\n    multi-stoke bindings or keys with modifiers that are not specified\n    in the default order (<code>Shift-Cmd-Ctrl-Alt</code>), you must\n    call <code>CodeMirror.normalizeKeyMap</code> on it before it can\n    be used. This function takes a keymap and modifies it to normalize\n    modifier order and properly recognize multi-stroke bindings. It\n    will return the keymap itself.</p>\n\n    <p>The <code>CodeMirror.keyMap</code> object associates key maps\n    with names. User code and key map definitions can assign extra\n    properties to this object. Anywhere where a key map is expected, a\n    string can be given, which will be looked up in this object. It\n    also contains the <code>\"default\"</code> key map holding the\n    default bindings.</p>\n\n    <p>The values of properties in key maps can be either functions of\n    a single argument (the CodeMirror instance), strings, or\n    <code>false</code>. Strings refer\n    to <a href=\"#commands\">commands</a>, which are described below. If\n    the property is set to <code>false</code>, CodeMirror leaves\n    handling of the key up to the browser. A key handler function may\n    return <code>CodeMirror.Pass</code> to indicate that it has\n    decided not to handle the key, and other handlers (or the default\n    behavior) should be given a turn.</p>\n\n    <p>Keys mapped to command names that start with the\n    characters <code>\"go\"</code> or to functions that have a\n    truthy <code>motion</code> property (which should be used for\n    cursor-movement actions) will be fired even when an\n    extra <code>Shift</code> modifier is present (i.e. <code>\"Up\":\n    \"goLineUp\"</code> matches both up and shift-up). This is used to\n    easily implement shift-selection.</p>\n\n    <p>Key maps can defer to each other by defining\n    a <code>fallthrough</code> property. This indicates that when a\n    key is not found in the map itself, one or more other maps should\n    be searched. It can hold either a single key map or an array of\n    key maps.</p>\n\n    <p>When a key map needs to set something up when it becomes\n    active, or tear something down when deactivated, it can\n    contain <code>attach</code> and/or <code>detach</code> properties,\n    which should hold functions that take the editor instance and the\n    next or previous keymap. Note that this only works for the\n    <a href=\"#option_keyMap\">top-level keymap</a>, not for fallthrough\n    maps or maps added\n    with <a href=\"#option_extraKeys\"><code>extraKeys</code></a>\n    or <a href=\"#addKeyMap\"><code>addKeyMap</code></a>.</p>\n</section>\n\n<section id=commands>\n    <h2>Commands</h2>\n\n    <p>Commands are parameter-less actions that can be performed on an\n    editor. Their main use is for key bindings. Commands are defined by\n    adding properties to the <code>CodeMirror.commands</code> object.\n    A number of common commands are defined by the library itself,\n    most of them used by the default key bindings. The value of a\n    command property must be a function of one argument (an editor\n    instance).</p>\n\n    <p>Some of the commands below are referenced in the default\n    key map, but not defined by the core library. These are intended to\n    be defined by user code or addons.</p>\n\n    <p>Commands can also be run with\n    the <a href=\"#execCommand\"><code>execCommand</code></a>\n    method.</p>\n\n    <dl>\n      <dt class=command id=command_selectAll><code><strong>selectAll</strong></code><span class=keybinding>Ctrl-A (PC), Cmd-A (Mac)</span></dt>\n      <dd>Select the whole content of the editor.</dd>\n\n      <dt class=command id=command_singleSelection><code><strong>singleSelection</strong></code><span class=keybinding>Esc</span></dt>\n      <dd>When multiple selections are present, this deselects all but\n      the primary selection.</dd>\n\n      <dt class=command id=command_killLine><code><strong>killLine</strong></code><span class=keybinding>Ctrl-K (Mac)</span></dt>\n      <dd>Emacs-style line killing. Deletes the part of the line after\n      the cursor. If that consists only of whitespace, the newline at\n      the end of the line is also deleted.</dd>\n\n      <dt class=command id=command_deleteLine><code><strong>deleteLine</strong></code><span class=keybinding>Ctrl-D (PC), Cmd-D (Mac)</span></dt>\n      <dd>Deletes the whole line under the cursor, including newline at the end.</dd>\n\n      <dt class=command id=command_delLineLeft><code><strong>delLineLeft</strong></code></dt>\n      <dd>Delete the part of the line before the cursor.</dd>\n\n      <dt class=command id=command_delWrappedLineLeft><code><strong>delWrappedLineLeft</strong></code><span class=keybinding>Cmd-Backspace (Mac)</span></dt>\n      <dd>Delete the part of the line from the left side of the visual line the cursor is on to the cursor.</dd>\n\n      <dt class=command id=command_delWrappedLineRight><code><strong>delWrappedLineRight</strong></code><span class=keybinding>Cmd-Delete (Mac)</span></dt>\n      <dd>Delete the part of the line from the cursor to the right side of the visual line the cursor is on.</dd>\n\n      <dt class=command id=command_undo><code><strong>undo</strong></code><span class=keybinding>Ctrl-Z (PC), Cmd-Z (Mac)</span></dt>\n      <dd>Undo the last change. Note that, because browsers still\n      don't make it possible for scripts to react to or customize the\n      context menu, selecting undo (or redo) from the context menu in\n      a CodeMirror instance does not work.</dd>\n\n      <dt class=command id=command_redo><code><strong>redo</strong></code><span class=keybinding>Ctrl-Y (PC), Shift-Cmd-Z (Mac), Cmd-Y (Mac)</span></dt>\n      <dd>Redo the last undone change.</dd>\n\n      <dt class=command id=command_undoSelection><code><strong>undoSelection</strong></code><span class=keybinding>Ctrl-U (PC), Cmd-U (Mac)</span></dt>\n      <dd>Undo the last change to the selection, or if there are no\n      selection-only changes at the top of the history, undo the last\n      change.</dd>\n\n      <dt class=command id=command_redoSelection><code><strong>redoSelection</strong></code><span class=keybinding>Alt-U (PC), Shift-Cmd-U (Mac)</span></dt>\n      <dd>Redo the last change to the selection, or the last text change if\n      no selection changes remain.</dd>\n\n      <dt class=command id=command_goDocStart><code><strong>goDocStart</strong></code><span class=keybinding>Ctrl-Home (PC), Cmd-Up (Mac), Cmd-Home (Mac)</span></dt>\n      <dd>Move the cursor to the start of the document.</dd>\n\n      <dt class=command id=command_goDocEnd><code><strong>goDocEnd</strong></code><span class=keybinding>Ctrl-End (PC), Cmd-End (Mac), Cmd-Down (Mac)</span></dt>\n      <dd>Move the cursor to the end of the document.</dd>\n\n      <dt class=command id=command_goLineStart><code><strong>goLineStart</strong></code><span class=keybinding>Alt-Left (PC), Ctrl-A (Mac)</span></dt>\n      <dd>Move the cursor to the start of the line.</dd>\n\n      <dt class=command id=command_goLineStartSmart><code><strong>goLineStartSmart</strong></code><span class=keybinding>Home</span></dt>\n      <dd>Move to the start of the text on the line, or if we are\n      already there, to the actual start of the line (including\n      whitespace).</dd>\n\n      <dt class=command id=command_goLineEnd><code><strong>goLineEnd</strong></code><span class=keybinding>Alt-Right (PC), Ctrl-E (Mac)</span></dt>\n      <dd>Move the cursor to the end of the line.</dd>\n\n      <dt class=command id=command_goLineRight><code><strong>goLineRight</strong></code><span class=keybinding>Cmd-Right (Mac)</span></dt>\n      <dd>Move the cursor to the right side of the visual line it is on.</dd>\n\n      <dt class=command id=command_goLineLeft><code><strong>goLineLeft</strong></code><span class=keybinding>Cmd-Left (Mac)</span></dt>\n      <dd>Move the cursor to the left side of the visual line it is on. If\n      this line is wrapped, that may not be the start of the line.</dd>\n\n      <dt class=command id=command_goLineLeftSmart><code><strong>goLineLeftSmart</strong></code></dt>\n      <dd>Move the cursor to the left side of the visual line it is\n      on. If that takes it to the start of the line, behave\n      like <a href=\"#command_goLineStartSmart\"><code>goLineStartSmart</code></a>.</dd>\n\n      <dt class=command id=command_goLineUp><code><strong>goLineUp</strong></code><span class=keybinding>Up, Ctrl-P (Mac)</span></dt>\n      <dd>Move the cursor up one line.</dd>\n\n      <dt class=command id=command_goLineDown><code><strong>goLineDown</strong></code><span class=keybinding>Down, Ctrl-N (Mac)</span></dt>\n      <dd>Move down one line.</dd>\n\n      <dt class=command id=command_goPageUp><code><strong>goPageUp</strong></code><span class=keybinding>PageUp, Shift-Ctrl-V (Mac)</span></dt>\n      <dd>Move the cursor up one screen, and scroll up by the same distance.</dd>\n\n      <dt class=command id=command_goPageDown><code><strong>goPageDown</strong></code><span class=keybinding>PageDown, Ctrl-V (Mac)</span></dt>\n      <dd>Move the cursor down one screen, and scroll down by the same distance.</dd>\n\n      <dt class=command id=command_goCharLeft><code><strong>goCharLeft</strong></code><span class=keybinding>Left, Ctrl-B (Mac)</span></dt>\n      <dd>Move the cursor one character left, going to the previous line\n      when hitting the start of line.</dd>\n\n      <dt class=command id=command_goCharRight><code><strong>goCharRight</strong></code><span class=keybinding>Right, Ctrl-F (Mac)</span></dt>\n      <dd>Move the cursor one character right, going to the next line\n      when hitting the end of line.</dd>\n\n      <dt class=command id=command_goColumnLeft><code><strong>goColumnLeft</strong></code></dt>\n      <dd>Move the cursor one character left, but don't cross line boundaries.</dd>\n\n      <dt class=command id=command_goColumnRight><code><strong>goColumnRight</strong></code></dt>\n      <dd>Move the cursor one character right, don't cross line boundaries.</dd>\n\n      <dt class=command id=command_goWordLeft><code><strong>goWordLeft</strong></code><span class=keybinding>Alt-B (Mac)</span></dt>\n      <dd>Move the cursor to the start of the previous word.</dd>\n\n      <dt class=command id=command_goWordRight><code><strong>goWordRight</strong></code><span class=keybinding>Alt-F (Mac)</span></dt>\n      <dd>Move the cursor to the end of the next word.</dd>\n\n      <dt class=command id=command_goGroupLeft><code><strong>goGroupLeft</strong></code><span class=keybinding>Ctrl-Left (PC), Alt-Left (Mac)</span></dt>\n      <dd>Move to the left of the group before the cursor. A group is\n      a stretch of word characters, a stretch of punctuation\n      characters, a newline, or a stretch of <em>more than one</em>\n      whitespace character.</dd>\n\n      <dt class=command id=command_goGroupRight><code><strong>goGroupRight</strong></code><span class=keybinding>Ctrl-Right (PC), Alt-Right (Mac)</span></dt>\n      <dd>Move to the right of the group after the cursor\n      (see <a href=\"#command_goGroupLeft\">above</a>).</dd>\n\n      <dt class=command id=command_delCharBefore><code><strong>delCharBefore</strong></code><span class=keybinding>Shift-Backspace, Ctrl-H (Mac)</span></dt>\n      <dd>Delete the character before the cursor.</dd>\n\n      <dt class=command id=command_delCharAfter><code><strong>delCharAfter</strong></code><span class=keybinding>Delete, Ctrl-D (Mac)</span></dt>\n      <dd>Delete the character after the cursor.</dd>\n\n      <dt class=command id=command_delWordBefore><code><strong>delWordBefore</strong></code><span class=keybinding>Alt-Backspace (Mac)</span></dt>\n      <dd>Delete up to the start of the word before the cursor.</dd>\n\n      <dt class=command id=command_delWordAfter><code><strong>delWordAfter</strong></code><span class=keybinding>Alt-D (Mac)</span></dt>\n      <dd>Delete up to the end of the word after the cursor.</dd>\n\n      <dt class=command id=command_delGroupBefore><code><strong>delGroupBefore</strong></code><span class=keybinding>Ctrl-Backspace (PC), Alt-Backspace (Mac)</span></dt>\n      <dd>Delete to the left of the <a href=\"#command_goGroupLeft\">group</a> before the cursor.</dd>\n\n      <dt class=command id=command_delGroupAfter><code><strong>delGroupAfter</strong></code><span class=keybinding>Ctrl-Delete (PC), Ctrl-Alt-Backspace (Mac), Alt-Delete (Mac)</span></dt>\n      <dd>Delete to the start of the <a href=\"#command_goGroupLeft\">group</a> after the cursor.</dd>\n\n      <dt class=command id=command_indentAuto><code><strong>indentAuto</strong></code><span class=keybinding>Shift-Tab</span></dt>\n      <dd>Auto-indent the current line or selection.</dd>\n\n      <dt class=command id=command_indentMore><code><strong>indentMore</strong></code><span class=keybinding>Ctrl-] (PC), Cmd-] (Mac)</span></dt>\n      <dd>Indent the current line or selection by one <a href=\"#option_indentUnit\">indent unit</a>.</dd>\n\n      <dt class=command id=command_indentLess><code><strong>indentLess</strong></code><span class=keybinding>Ctrl-[ (PC), Cmd-[ (Mac)</span></dt>\n      <dd>Dedent the current line or selection by one <a href=\"#option_indentUnit\">indent unit</a>.</dd>\n\n      <dt class=command id=command_insertTab><code><strong>insertTab</strong></code></dt>\n      <dd>Insert a tab character at the cursor.</dd>\n\n      <dt class=command id=command_insertSoftTab><code><strong>insertSoftTab</strong></code></dt>\n      <dd>Insert the amount of spaces that match the width a tab at\n      the cursor position would have.</dd>\n\n      <dt class=command id=command_defaultTab><code><strong>defaultTab</strong></code><span class=keybinding>Tab</span></dt>\n      <dd>If something is selected, indent it by\n      one <a href=\"#option_indentUnit\">indent unit</a>. If nothing is\n      selected, insert a tab character.</dd>\n\n      <dt class=command id=command_transposeChars><code><strong>transposeChars</strong></code><span class=keybinding>Ctrl-T (Mac)</span></dt>\n      <dd>Swap the characters before and after the cursor.</dd>\n\n      <dt class=command id=command_newlineAndIndent><code><strong>newlineAndIndent</strong></code><span class=keybinding>Enter</span></dt>\n      <dd>Insert a newline and auto-indent the new line.</dd>\n\n      <dt class=command id=command_toggleOverwrite><code><strong>toggleOverwrite</strong></code><span class=keybinding>Insert</span></dt>\n      <dd>Flip the <a href=\"#toggleOverwrite\">overwrite</a> flag.</dd>\n\n      <dt class=command id=command_save><code><strong>save</strong></code><span class=keybinding>Ctrl-S (PC), Cmd-S (Mac)</span></dt>\n      <dd>Not defined by the core library, only referred to in\n      key maps. Intended to provide an easy way for user code to define\n      a save command.</dd>\n\n      <dt class=command id=command_find><code><strong>find</strong></code><span class=keybinding>Ctrl-F (PC), Cmd-F (Mac)</span></dt>\n      <dt class=command id=command_findNext><code><strong>findNext</strong></code><span class=keybinding>Ctrl-G (PC), Cmd-G (Mac)</span></dt>\n      <dt class=command id=command_findPrev><code><strong>findPrev</strong></code><span class=keybinding>Shift-Ctrl-G (PC), Shift-Cmd-G (Mac)</span></dt>\n      <dt class=command id=command_replace><code><strong>replace</strong></code><span class=keybinding>Shift-Ctrl-F (PC), Cmd-Alt-F (Mac)</span></dt>\n      <dt class=command id=command_replaceAll><code><strong>replaceAll</strong></code><span class=keybinding>Shift-Ctrl-R (PC), Shift-Cmd-Alt-F (Mac)</span></dt>\n      <dd>Not defined by the core library, but defined in\n      the <a href=\"#addon_search\">search addon</a> (or custom client\n      addons).</dd>\n\n    </dl>\n\n</section>\n\n<section id=styling>\n    <h2>Customized Styling</h2>\n\n    <p>Up to a certain extent, CodeMirror's look can be changed by\n    modifying style sheet files. The style sheets supplied by modes\n    simply provide the colors for that mode, and can be adapted in a\n    very straightforward way. To style the editor itself, it is\n    possible to alter or override the styles defined\n    in <a href=\"../lib/codemirror.css\"><code>codemirror.css</code></a>.</p>\n\n    <p>Some care must be taken there, since a lot of the rules in this\n    file are necessary to have CodeMirror function properly. Adjusting\n    colors should be safe, of course, and with some care a lot of\n    other things can be changed as well. The CSS classes defined in\n    this file serve the following roles:</p>\n\n    <dl>\n      <dt id=\"class_CodeMirror\"><code><strong>CodeMirror</strong></code></dt>\n      <dd>The outer element of the editor. This should be used for the\n      editor width, height, borders and positioning. Can also be used\n      to set styles that should hold for everything inside the editor\n      (such as font and font size), or to set a background. Setting\n      this class' <code>height</code> style to <code>auto</code> will\n      make the editor <a href=\"../demo/resize.html\">resize to fit its\n      content</a> (it is recommended to also set\n      the <a href=\"#option_viewportMargin\"><code>viewportMargin</code>\n      option</a> to <code>Infinity</code> when doing this.</dd>\n\n      <dt id=\"class_CodeMirror_focused\"><code><strong>CodeMirror-focused</strong></code></dt>\n      <dd>Whenever the editor is focused, the top element gets this\n      class. This is used to hide the cursor and give the selection a\n      different color when the editor is not focused.</dd>\n\n      <dt id=\"class_CodeMirror_gutters\"><code><strong>CodeMirror-gutters</strong></code></dt>\n      <dd>This is the backdrop for all gutters. Use it to set the\n      default gutter background color, and optionally add a border on\n      the right of the gutters.</dd>\n\n      <dt id=\"class_CodeMirror_linenumbers\"><code><strong>CodeMirror-linenumbers</strong></code></dt>\n      <dd>Use this for giving a background or width to the line number\n      gutter.</dd>\n\n      <dt id=\"class_CodeMirror_linenumber\"><code><strong>CodeMirror-linenumber</strong></code></dt>\n      <dd>Used to style the actual individual line numbers. These\n      won't be children of the <code>CodeMirror-linenumbers</code>\n      (plural) element, but rather will be absolutely positioned to\n      overlay it. Use this to set alignment and text properties for\n      the line numbers.</dd>\n\n      <dt id=\"class_CodeMirror_lines\"><code><strong>CodeMirror-lines</strong></code></dt>\n      <dd>The visible lines. This is where you specify vertical\n      padding for the editor content.</dd>\n\n      <dt id=\"class_CodeMirror_cursor\"><code><strong>CodeMirror-cursor</strong></code></dt>\n      <dd>The cursor is a block element that is absolutely positioned.\n      You can make it look whichever way you want.</dd>\n\n      <dt id=\"class_CodeMirror_selected\"><code><strong>CodeMirror-selected</strong></code></dt>\n      <dd>The selection is represented by <code>span</code> elements\n      with this class.</dd>\n\n      <dt id=\"class_CodeMirror_matchingbracket\"><code><strong>CodeMirror-matchingbracket</strong></code>,\n        <code><strong>CodeMirror-nonmatchingbracket</strong></code></dt>\n      <dd>These are used to style matched (or unmatched) brackets.</dd>\n    </dl>\n\n    <p>If your page's style sheets do funky things to\n    all <code>div</code> or <code>pre</code> elements (you probably\n    shouldn't do that), you'll have to define rules to cancel these\n    effects out again for elements under the <code>CodeMirror</code>\n    class.</p>\n\n    <p>Themes are also simply CSS files, which define colors for\n    various syntactic elements. See the files in\n    the <a href=\"../theme/\"><code>theme</code></a> directory.</p>\n</section>\n\n<section id=api>\n    <h2>Programming API</h2>\n\n    <p>A lot of CodeMirror features are only available through its\n    API. Thus, you need to write code (or\n    use <a href=\"#addons\">addons</a>) if you want to expose them to\n    your users.</p>\n\n    <p>Whenever points in the document are represented, the API uses\n    objects with <code>line</code> and <code>ch</code> properties.\n    Both are zero-based. CodeMirror makes sure to 'clip' any positions\n    passed by client code so that they fit inside the document, so you\n    shouldn't worry too much about sanitizing your coordinates. If you\n    give <code>ch</code> a value of <code>null</code>, or don't\n    specify it, it will be replaced with the length of the specified\n    line. Such positions may also have a <code>sticky</code> property\n    holding <code>\"before\"</code> or <code>\"after\"</code>, whether the\n    position is associated with the character before or after it. This\n    influences, for example, where the cursor is drawn on a\n    line-break or bidi-direction boundary.</p>\n\n    <p>Methods prefixed with <code>doc.</code> can, unless otherwise\n    specified, be called both on <code>CodeMirror</code> (editor)\n    instances and <code>CodeMirror.Doc</code> instances. Methods\n    prefixed with <code>cm.</code> are <em>only</em> available\n    on <code>CodeMirror</code> instances.</p>\n\n    <h3 id=\"api_constructor\">Constructor</h3>\n\n    <p id=\"CodeMirror\">Constructing an editor instance is done with\n    the <code><strong>CodeMirror</strong>(place: Element|fn(Element),\n    ?option: object)</code> constructor. If the <code>place</code>\n    argument is a DOM element, the editor will be appended to it. If\n    it is a function, it will be called, and is expected to place the\n    editor into the document. <code>options</code> may be an element\n    mapping <a href=\"#config\">option names</a> to values. The options\n    that it doesn't explicitly specify (or all options, if it is not\n    passed) will be taken\n    from <a href=\"#defaults\"><code>CodeMirror.defaults</code></a>.</p>\n\n    <p>Note that the options object passed to the constructor will be\n    mutated when the instance's options\n    are <a href=\"#setOption\">changed</a>, so you shouldn't share such\n    objects between instances.</p>\n\n    <p>See <a href=\"#fromTextArea\"><code>CodeMirror.fromTextArea</code></a>\n    for another way to construct an editor instance.</p>\n\n    <h3 id=\"api_content\">Content manipulation methods</h3>\n\n    <dl>\n      <dt id=\"getValue\"><code><strong>doc.getValue</strong>(?separator: string) → string</code></dt>\n      <dd>Get the current editor content. You can pass it an optional\n      argument to specify the string to be used to separate lines\n      (defaults to <code>\"\\n\"</code>).</dd>\n      <dt id=\"setValue\"><code><strong>doc.setValue</strong>(content: string)</code></dt>\n      <dd>Set the editor content.</dd>\n\n      <dt id=\"getRange\"><code><strong>doc.getRange</strong>(from: {line, ch}, to: {line, ch}, ?separator: string) → string</code></dt>\n      <dd>Get the text between the given points in the editor, which\n      should be <code>{line, ch}</code> objects. An optional third\n      argument can be given to indicate the line separator string to\n      use (defaults to <code>\"\\n\"</code>).</dd>\n      <dt id=\"replaceRange\"><code><strong>doc.replaceRange</strong>(replacement: string, from: {line, ch}, to: {line, ch}, ?origin: string)</code></dt>\n      <dd>Replace the part of the document between <code>from</code>\n      and <code>to</code> with the given string. <code>from</code>\n      and <code>to</code> must be <code>{line, ch}</code>\n      objects. <code>to</code> can be left off to simply insert the\n      string at position <code>from</code>. When <code>origin</code>\n      is given, it will be passed on\n      to <a href=\"#event_change\"><code>\"change\"</code> events</a>, and\n      its first letter will be used to determine whether this change\n      can be merged with previous history events, in the way described\n      for <a href=\"#selection_origin\">selection origins</a>.</dd>\n\n      <dt id=\"getLine\"><code><strong>doc.getLine</strong>(n: integer) → string</code></dt>\n      <dd>Get the content of line <code>n</code>.</dd>\n\n      <dt id=\"lineCount\"><code><strong>doc.lineCount</strong>() → integer</code></dt>\n      <dd>Get the number of lines in the editor.</dd>\n      <dt id=\"firstLine\"><code><strong>doc.firstLine</strong>() → integer</code></dt>\n      <dd>Get the number of first line in the editor. This will\n      usually be zero but for <a href=\"#linkedDoc_from\">linked sub-views</a>,\n      or <a href=\"#api_doc\">documents</a> instantiated with a non-zero\n      first line, it might return other values.</dd>\n      <dt id=\"lastLine\"><code><strong>doc.lastLine</strong>() → integer</code></dt>\n      <dd>Get the number of last line in the editor. This will\n      usually be <code>doc.lineCount() - 1</code>,\n      but for <a href=\"#linkedDoc_from\">linked sub-views</a>,\n      it might return other values.</dd>\n\n      <dt id=\"getLineHandle\"><code><strong>doc.getLineHandle</strong>(num: integer) → LineHandle</code></dt>\n      <dd>Fetches the line handle for the given line number.</dd>\n      <dt id=\"getLineNumber\"><code><strong>doc.getLineNumber</strong>(handle: LineHandle) → integer</code></dt>\n      <dd>Given a line handle, returns the current position of that\n      line (or <code>null</code> when it is no longer in the\n      document).</dd>\n      <dt id=\"eachLine\"><code><strong>doc.eachLine</strong>(f: (line: LineHandle))</code></dt>\n      <dt><code><strong>doc.eachLine</strong>(start: integer, end: integer, f: (line: LineHandle))</code></dt>\n      <dd>Iterate over the whole document, or if <code>start</code>\n      and <code>end</code> line numbers are given, the range\n      from <code>start</code> up to (not including) <code>end</code>,\n      and call <code>f</code> for each line, passing the line handle.\n      This is a faster way to visit a range of line handlers than\n      calling <a href=\"#getLineHandle\"><code>getLineHandle</code></a>\n      for each of them. Note that line handles have\n      a <code>text</code> property containing the line's content (as a\n      string).</dd>\n\n      <dt id=\"markClean\"><code><strong>doc.markClean</strong>()</code></dt>\n      <dd>Set the editor content as 'clean', a flag that it will\n      retain until it is edited, and which will be set again when such\n      an edit is undone again. Useful to track whether the content\n      needs to be saved. This function is deprecated in favor\n      of <a href=\"#changeGeneration\"><code>changeGeneration</code></a>,\n      which allows multiple subsystems to track different notions of\n      cleanness without interfering.</dd>\n      <dt id=\"changeGeneration\"><code><strong>doc.changeGeneration</strong>(?closeEvent: boolean) → integer</code></dt>\n      <dd>Returns a number that can later be passed\n      to <a href=\"#isClean\"><code>isClean</code></a> to test whether\n      any edits were made (and not undone) in the meantime.\n      If <code>closeEvent</code> is true, the current history event\n      will be ‘closed’, meaning it can't be combined with further\n      changes (rapid typing or deleting events are typically\n      combined).</dd>\n      <dt id=\"isClean\"><code><strong>doc.isClean</strong>(?generation: integer) → boolean</code></dt>\n      <dd>Returns whether the document is currently clean — not\n      modified since initialization or the last call\n      to <a href=\"#markClean\"><code>markClean</code></a> if no\n      argument is passed, or since the matching call\n      to <a href=\"#changeGeneration\"><code>changeGeneration</code></a>\n      if a generation value is given.</dd>\n    </dl>\n\n    <h3 id=\"api_selection\">Cursor and selection methods</h3>\n\n    <dl>\n      <dt id=\"getSelection\"><code><strong>doc.getSelection</strong>(?lineSep: string) → string</code></dt>\n      <dd>Get the currently selected code. Optionally pass a line\n      separator to put between the lines in the output. When multiple\n      selections are present, they are concatenated with instances\n      of <code>lineSep</code> in between.</dd>\n      <dt id=\"getSelections\"><code><strong>doc.getSelections</strong>(?lineSep: string) → array&lt;string&gt;</code></dt>\n      <dd>Returns an array containing a string for each selection,\n      representing the content of the selections.</dd>\n\n      <dt id=\"replaceSelection\"><code><strong>doc.replaceSelection</strong>(replacement: string, ?select: string)</code></dt>\n      <dd>Replace the selection(s) with the given string. By default,\n      the new selection ends up after the inserted text. The\n      optional <code>select</code> argument can be used to change\n      this—passing <code>\"around\"</code> will cause the new text to be\n      selected, passing <code>\"start\"</code> will collapse the\n      selection to the start of the inserted text.</dd>\n      <dt id=\"replaceSelections\"><code><strong>doc.replaceSelections</strong>(replacements: array&lt;string&gt;, ?select: string)</code></dt>\n      <dd>The length of the given array should be the same as the\n      number of active selections. Replaces the content of the\n      selections with the strings in the array.\n      The <code>select</code> argument works the same as\n      in <a href=\"#replaceSelection\"><code>replaceSelection</code></a>.</dd>\n\n      <dt id=\"getCursor\"><code><strong>doc.getCursor</strong>(?start: string) → {line, ch}</code></dt>\n      <dd>Retrieve one end of the <em>primary</em>\n      selection. <code>start</code> is an optional string indicating\n      which end of the selection to return. It may\n      be <code>\"from\"</code>, <code>\"to\"</code>, <code>\"head\"</code>\n      (the side of the selection that moves when you press\n      shift+arrow), or <code>\"anchor\"</code> (the fixed side of the\n      selection). Omitting the argument is the same as\n      passing <code>\"head\"</code>. A <code>{line, ch}</code> object\n      will be returned.</dd>\n      <dt id=\"listSelections\"><code><strong>doc.listSelections</strong>() → array&lt;{anchor, head}&gt;</code></dt>\n      <dd>Retrieves a list of all current selections. These will\n      always be sorted, and never overlap (overlapping selections are\n      merged). Each object in the array contains <code>anchor</code>\n      and <code>head</code> properties referring to <code>{line,\n      ch}</code> objects.</dd>\n\n      <dt id=\"somethingSelected\"><code><strong>doc.somethingSelected</strong>() → boolean</code></dt>\n      <dd>Return true if any text is selected.</dd>\n      <dt id=\"setCursor\"><code><strong>doc.setCursor</strong>(pos: {line, ch}|number, ?ch: number, ?options: object)</code></dt>\n      <dd>Set the cursor position. You can either pass a\n      single <code>{line, ch}</code> object, or the line and the\n      character as two separate parameters. Will replace all\n      selections with a single, empty selection at the given position.\n      The supported options are the same as for <a href=\"#setSelection\"><code>setSelection</code></a>.</dd>\n\n      <dt id=\"setSelection\"><code><strong>doc.setSelection</strong>(anchor: {line, ch}, ?head: {line, ch}, ?options: object)</code></dt>\n      <dd>Set a single selection range. <code>anchor</code>\n      and <code>head</code> should be <code>{line, ch}</code>\n      objects. <code>head</code> defaults to <code>anchor</code> when\n      not given. These options are supported:\n      <dl>\n        <dt id=\"selection_scroll\"><code><strong>scroll</strong>: boolean</code></dt>\n        <dd>Determines whether the selection head should be scrolled\n        into view. Defaults to true.</dd>\n        <dt id=\"selection_origin\"><code><strong>origin</strong>: string</code></dt>\n        <dd>Determines whether the selection history event may be\n        merged with the previous one. When an origin starts with the\n        character <code>+</code>, and the last recorded selection had\n        the same origin and was similar (close\n        in <a href=\"#option_historyEventDelay\">time</a>, both\n        collapsed or both non-collapsed), the new one will replace the\n        old one. When it starts with <code>*</code>, it will always\n        replace the previous event (if that had the same origin).\n        Built-in motion uses the <code>\"+move\"</code> origin. User input uses the <code>\"+input\"</code> origin.</dd>\n        <dt id=\"selection_bias\"><code><strong>bias</strong>: number</code></dt>\n        <dd>Determine the direction into which the selection endpoints\n        should be adjusted when they fall inside\n        an <a href=\"#mark_atomic\">atomic</a> range. Can be either -1\n        (backward) or 1 (forward). When not given, the bias will be\n        based on the relative position of the old selection—the editor\n        will try to move further away from that, to prevent getting\n        stuck.</dd>\n      </dl></dd>\n\n      <dt id=\"setSelections\"><code><strong>doc.setSelections</strong>(ranges: array&lt;{anchor, head}&gt;, ?primary: integer, ?options: object)</code></dt>\n      <dd>Sets a new set of selections. There must be at least one\n      selection in the given array. When <code>primary</code> is a\n      number, it determines which selection is the primary one. When\n      it is not given, the primary index is taken from the previous\n      selection, or set to the last range if the previous selection\n      had less ranges than the new one. Supports the same options\n      as <a href=\"#setSelection\"><code>setSelection</code></a>.</dd>\n      <dt id=\"addSelection\"><code><strong>doc.addSelection</strong>(anchor: {line, ch}, ?head: {line, ch})</code></dt>\n      <dd>Adds a new selection to the existing set of selections, and\n      makes it the primary selection.</dd>\n\n      <dt id=\"extendSelection\"><code><strong>doc.extendSelection</strong>(from: {line, ch}, ?to: {line, ch}, ?options: object)</code></dt>\n      <dd>Similar\n      to <a href=\"#setSelection\"><code>setSelection</code></a>, but\n      will, if shift is held or\n      the <a href=\"#setExtending\">extending</a> flag is set, move the\n      head of the selection while leaving the anchor at its current\n      place. <code>to</code> is optional, and can be passed to ensure\n      a region (for example a word or paragraph) will end up selected\n      (in addition to whatever lies between that region and the\n      current anchor). When multiple selections are present, all but\n      the primary selection will be dropped by this method.\n      Supports the same options as <a href=\"#setSelection\"><code>setSelection</code></a>.</dd>\n      <dt id=\"extendSelections\"><code><strong>doc.extendSelections</strong>(heads: array&lt;{line, ch}&gt;, ?options: object)</code></dt>\n      <dd>An equivalent\n      of <a href=\"#extendSelection\"><code>extendSelection</code></a>\n      that acts on all selections at once.</dd>\n      <dt id=\"extendSelectionsBy\"><code><strong>doc.extendSelectionsBy</strong>(f: function(range: {anchor, head}) → {line, ch}), ?options: object)</code></dt>\n      <dd>Applies the given function to all existing selections, and\n      calls <a href=\"#extendSelections\"><code>extendSelections</code></a>\n      on the result.</dd>\n      <dt id=\"setExtending\"><code><strong>doc.setExtending</strong>(value: boolean)</code></dt>\n      <dd>Sets or clears the 'extending' flag, which acts similar to\n      the shift key, in that it will cause cursor movement and calls\n      to <a href=\"#extendSelection\"><code>extendSelection</code></a>\n      to leave the selection anchor in place.</dd>\n      <dt id=\"getExtending\"><code><strong>doc.getExtending</strong>() → boolean</code></dt>\n      <dd>Get the value of the 'extending' flag.</dd>\n\n      <dt id=\"hasFocus\"><code><strong>cm.hasFocus</strong>() → boolean</code></dt>\n      <dd>Tells you whether the editor currently has focus.</dd>\n\n      <dt id=\"findPosH\"><code><strong>cm.findPosH</strong>(start: {line, ch}, amount: integer, unit: string, visually: boolean) → {line, ch, ?hitSide: boolean}</code></dt>\n      <dd>Used to find the target position for horizontal cursor\n      motion. <code>start</code> is a <code>{line, ch}</code>\n      object, <code>amount</code> an integer (may be negative),\n      and <code>unit</code> one of the\n      string <code>\"char\"</code>, <code>\"column\"</code>,\n      or <code>\"word\"</code>. Will return a position that is produced\n      by moving <code>amount</code> times the distance specified\n      by <code>unit</code>. When <code>visually</code> is true, motion\n      in right-to-left text will be visual rather than logical. When\n      the motion was clipped by hitting the end or start of the\n      document, the returned value will have a <code>hitSide</code>\n      property set to true.</dd>\n      <dt id=\"findPosV\"><code><strong>cm.findPosV</strong>(start: {line, ch}, amount: integer, unit: string) → {line, ch, ?hitSide: boolean}</code></dt>\n      <dd>Similar to <a href=\"#findPosH\"><code>findPosH</code></a>,\n      but used for vertical motion. <code>unit</code> may\n      be <code>\"line\"</code> or <code>\"page\"</code>. The other\n      arguments and the returned value have the same interpretation as\n      they have in <code>findPosH</code>.</dd>\n\n      <dt id=\"findWordAt\"><code><strong>cm.findWordAt</strong>(pos: {line, ch}) → {anchor: {line, ch}, head: {line, ch}}</code></dt>\n      <dd>Returns the start and end of the 'word' (the stretch of\n      letters, whitespace, or punctuation) at the given position.</dd>\n    </dl>\n\n    <h3 id=\"api_configuration\">Configuration methods</h3>\n\n    <dl>\n      <dt id=\"setOption\"><code><strong>cm.setOption</strong>(option: string, value: any)</code></dt>\n      <dd>Change the configuration of the editor. <code>option</code>\n      should the name of an <a href=\"#config\">option</a>,\n      and <code>value</code> should be a valid value for that\n      option.</dd>\n      <dt id=\"getOption\"><code><strong>cm.getOption</strong>(option: string) → any</code></dt>\n      <dd>Retrieves the current value of the given option for this\n      editor instance.</dd>\n\n      <dt id=\"addKeyMap\"><code><strong>cm.addKeyMap</strong>(map: object, bottom: boolean)</code></dt>\n      <dd>Attach an additional <a href=\"#keymaps\">key map</a> to the\n      editor. This is mostly useful for addons that need to register\n      some key handlers without trampling on\n      the <a href=\"#option_extraKeys\"><code>extraKeys</code></a>\n      option. Maps added in this way have a higher precedence than\n      the <code>extraKeys</code>\n      and <a href=\"#option_keyMap\"><code>keyMap</code></a> options,\n      and between them, the maps added earlier have a lower precedence\n      than those added later, unless the <code>bottom</code> argument\n      was passed, in which case they end up below other key maps added\n      with this method.</dd>\n      <dt id=\"removeKeyMap\"><code><strong>cm.removeKeyMap</strong>(map: object)</code></dt>\n      <dd>Disable a keymap added\n      with <a href=\"#addKeyMap\"><code>addKeyMap</code></a>. Either\n      pass in the key map object itself, or a string, which will be\n      compared against the <code>name</code> property of the active\n      key maps.</dd>\n\n      <dt id=\"addOverlay\"><code><strong>cm.addOverlay</strong>(mode: string|object, ?options: object)</code></dt>\n      <dd>Enable a highlighting overlay. This is a stateless mini-mode\n      that can be used to add extra highlighting. For example,\n      the <a href=\"../demo/search.html\">search addon</a> uses it to\n      highlight the term that's currently being\n      searched. <code>mode</code> can be a <a href=\"#option_mode\">mode\n      spec</a> or a mode object (an object with\n      a <a href=\"#token\"><code>token</code></a> method).\n      The <code>options</code> parameter is optional. If given, it\n      should be an object, optionally containing the following options:\n        <dl>\n          <dt><code><strong>opaque</strong>: bool</code></dt>\n          <dd>Defaults to off, but can be given to allow the overlay\n          styling, when not <code>null</code>, to override the styling of\n          the base mode entirely, instead of the two being applied\n          together.</dd>\n          <dt><code><strong>priority</strong>: number</code></dt>\n          <dd>Determines the ordering in which the overlays are\n          applied. Those with high priority are applied after those\n          with lower priority, and able to override the opaqueness of\n          the ones that come before. Defaults to 0.</dd>\n        </dl>\n      </dd>\n\n      <dt id=\"removeOverlay\"><code><strong>cm.removeOverlay</strong>(mode: string|object)</code></dt>\n      <dd>Pass this the exact value passed for the <code>mode</code>\n      parameter to <a href=\"#addOverlay\"><code>addOverlay</code></a>,\n      or a string that corresponds to the <code>name</code> property of\n      that value, to remove an overlay again.</dd>\n\n      <dt id=\"on\"><code><strong>cm.on</strong>(type: string, func: (...args))</code></dt>\n      <dd>Register an event handler for the given event type (a\n      string) on the editor instance. There is also\n      a <code>CodeMirror.on(object, type, func)</code> version\n      that allows registering of events on any object.</dd>\n      <dt id=\"off\"><code><strong>cm.off</strong>(type: string, func: (...args))</code></dt>\n      <dd>Remove an event handler on the editor instance. An\n      equivalent <code>CodeMirror.off(object, type,\n      func)</code> also exists.</dd>\n    </dl>\n\n    <h3 id=\"api_doc\">Document management methods</h3>\n\n    <p id=\"Doc\">Each editor is associated with an instance\n    of <code>CodeMirror.Doc</code>, its document. A document\n    represents the editor content, plus a selection, an undo history,\n    and a <a href=\"#option_mode\">mode</a>. A document can only be\n    associated with a single editor at a time. You can create new\n    documents by calling the <code>CodeMirror.Doc(text: string, mode:\n    Object, firstLineNumber: ?number, lineSeparator: ?string)</code>\n    constructor. The last three arguments are optional and can be used\n    to set a mode for the document, make it start at a line number\n    other than 0, and set a specific line separator respectively.</p>\n\n    <dl>\n      <dt id=\"getDoc\"><code><strong>cm.getDoc</strong>() → Doc</code></dt>\n      <dd>Retrieve the currently active document from an editor.</dd>\n      <dt id=\"getEditor\"><code><strong>doc.getEditor</strong>() → CodeMirror</code></dt>\n      <dd>Retrieve the editor associated with a document. May\n      return <code>null</code>.</dd>\n\n      <dt id=\"swapDoc\"><code><strong>cm.swapDoc</strong>(doc: CodeMirror.Doc) → Doc</code></dt>\n      <dd>Attach a new document to the editor. Returns the old\n      document, which is now no longer associated with an editor.</dd>\n\n      <dt id=\"copy\"><code><strong>doc.copy</strong>(copyHistory: boolean) → Doc</code></dt>\n      <dd>Create an identical copy of the given doc.\n      When <code>copyHistory</code> is true, the history will also be\n      copied. Can not be called directly on an editor.</dd>\n\n      <dt id=\"linkedDoc\"><code><strong>doc.linkedDoc</strong>(options: object) → Doc</code></dt>\n      <dd>Create a new document that's linked to the target document.\n      Linked documents will stay in sync (changes to one are also\n      applied to the other) until <a href=\"#unlinkDoc\">unlinked</a>.\n      These are the options that are supported:\n        <dl>\n          <dt id=\"linkedDoc_sharedHist\"><code><strong>sharedHist</strong>: boolean</code></dt>\n          <dd>When turned on, the linked copy will share an undo\n          history with the original. Thus, something done in one of\n          the two can be undone in the other, and vice versa.</dd>\n          <dt id=\"linkedDoc_from\"><code><strong>from</strong>: integer</code></dt>\n          <dt id=\"linkedDoc_to\"><code><strong>to</strong>: integer</code></dt>\n          <dd>Can be given to make the new document a subview of the\n          original. Subviews only show a given range of lines. Note\n          that line coordinates inside the subview will be consistent\n          with those of the parent, so that for example a subview\n          starting at line 10 will refer to its first line as line 10,\n          not 0.</dd>\n          <dt id=\"linkedDoc_mode\"><code><strong>mode</strong>: string|object</code></dt>\n          <dd>By default, the new document inherits the mode of the\n          parent. This option can be set to\n          a <a href=\"#option_mode\">mode spec</a> to give it a\n          different mode.</dd>\n        </dl></dd>\n      <dt id=\"unlinkDoc\"><code><strong>doc.unlinkDoc</strong>(doc: CodeMirror.Doc)</code></dt>\n      <dd>Break the link between two documents. After calling this,\n      changes will no longer propagate between the documents, and, if\n      they had a shared history, the history will become\n      separate.</dd>\n      <dt id=\"iterLinkedDocs\"><code><strong>doc.iterLinkedDocs</strong>(function: (doc: CodeMirror.Doc, sharedHist: boolean))</code></dt>\n      <dd>Will call the given function for all documents linked to the\n      target document. It will be passed two arguments, the linked document\n      and a boolean indicating whether that document shares history\n      with the target.</dd>\n    </dl>\n\n    <h3 id=\"api_history\">History-related methods</h3>\n\n    <dl>\n      <dt id=\"undo\"><code><strong>doc.undo</strong>()</code></dt>\n      <dd>Undo one edit (if any undo events are stored).</dd>\n      <dt id=\"redo\"><code><strong>doc.redo</strong>()</code></dt>\n      <dd>Redo one undone edit.</dd>\n\n      <dt id=\"undoSelection\"><code><strong>doc.undoSelection</strong>()</code></dt>\n      <dd>Undo one edit or selection change.</dd>\n      <dt id=\"redoSelection\"><code><strong>doc.redoSelection</strong>()</code></dt>\n      <dd>Redo one undone edit or selection change.</dd>\n\n      <dt id=\"historySize\"><code><strong>doc.historySize</strong>() → {undo: integer, redo: integer}</code></dt>\n      <dd>Returns an object with <code>{undo, redo}</code> properties,\n      both of which hold integers, indicating the amount of stored\n      undo and redo operations.</dd>\n      <dt id=\"clearHistory\"><code><strong>doc.clearHistory</strong>()</code></dt>\n      <dd>Clears the editor's undo history.</dd>\n      <dt id=\"getHistory\"><code><strong>doc.getHistory</strong>() → object</code></dt>\n      <dd>Get a (JSON-serializable) representation of the undo history.</dd>\n      <dt id=\"setHistory\"><code><strong>doc.setHistory</strong>(history: object)</code></dt>\n      <dd>Replace the editor's undo history with the one provided,\n      which must be a value as returned\n      by <a href=\"#getHistory\"><code>getHistory</code></a>. Note that\n      this will have entirely undefined results if the editor content\n      isn't also the same as it was when <code>getHistory</code> was\n      called.</dd>\n    </dl>\n\n    <h3 id=\"api_marker\">Text-marking methods</h3>\n\n    <dl>\n      <dt id=\"markText\"><code><strong>doc.markText</strong>(from: {line, ch}, to: {line, ch}, ?options: object) → TextMarker</code></dt>\n      <dd>Can be used to mark a range of text with a specific CSS\n      class name. <code>from</code> and <code>to</code> should\n      be <code>{line, ch}</code> objects. The <code>options</code>\n      parameter is optional. When given, it should be an object that\n      may contain the following configuration options:\n      <dl>\n        <dt id=\"mark_className\"><code><strong>className</strong>: string</code></dt>\n        <dd>Assigns a CSS class to the marked stretch of text.</dd>\n        <dt id=\"mark_inclusiveLeft\"><code><strong>inclusiveLeft</strong>: boolean</code></dt>\n        <dd>Determines whether\n        text inserted on the left of the marker will end up inside\n        or outside of it.</dd>\n        <dt id=\"mark_inclusiveRight\"><code><strong>inclusiveRight</strong>: boolean</code></dt>\n        <dd>Like <code>inclusiveLeft</code>,\n        but for the right side.</dd>\n        <dt id=\"mark_atomic\"><code><strong>atomic</strong>: boolean</code></dt>\n        <dd>Atomic ranges act as a single unit when cursor movement is\n        concerned—i.e. it is impossible to place the cursor inside of\n        them. In atomic ranges, <code>inclusiveLeft</code>\n        and <code>inclusiveRight</code> have a different meaning—they\n        will prevent the cursor from being placed respectively\n        directly before and directly after the range.</dd>\n        <dt id=\"mark_collapsed\"><code><strong>collapsed</strong>: boolean</code></dt>\n        <dd>Collapsed ranges do not show up in the display. Setting a\n        range to be collapsed will automatically make it atomic.</dd>\n        <dt id=\"mark_clearOnEnter\"><code><strong>clearOnEnter</strong>: boolean</code></dt>\n        <dd>When enabled, will cause the mark to clear itself whenever\n        the cursor enters its range. This is mostly useful for\n        text-replacement widgets that need to 'snap open' when the\n        user tries to edit them. The\n        <a href=\"#event_clear\"><code>\"clear\"</code></a> event\n        fired on the range handle can be used to be notified when this\n        happens.</dd>\n        <dt id=\"mark_clearWhenEmpty\"><code><strong>clearWhenEmpty</strong>: boolean</code></dt>\n        <dd>Determines whether the mark is automatically cleared when\n        it becomes empty. Default is true.</dd>\n        <dt id=\"mark_replacedWith\"><code><strong>replacedWith</strong>: Element</code></dt>\n        <dd>Use a given node to display this range. Implies both\n        collapsed and atomic. The given DOM node <em>must</em> be an\n        inline element (as opposed to a block element).</dd>\n        <dt><code><strong>handleMouseEvents</strong>: boolean</code></dt>\n        <dd>When <code>replacedWith</code> is given, this determines\n        whether the editor will capture mouse and drag events\n        occurring in this widget. Default is false—the events will be\n        left alone for the default browser handler, or specific\n        handlers on the widget, to capture.</dd>\n        <dt id=\"mark_readOnly\"><code><strong>readOnly</strong>: boolean</code></dt>\n        <dd>A read-only span can, as long as it is not cleared, not be\n        modified except by\n        calling <a href=\"#setValue\"><code>setValue</code></a> to reset\n        the whole document. <em>Note:</em> adding a read-only span\n        currently clears the undo history of the editor, because\n        existing undo events being partially nullified by read-only\n        spans would corrupt the history (in the current\n        implementation).</dd>\n        <dt id=\"mark_addToHistory\"><code><strong>addToHistory</strong>: boolean</code></dt>\n        <dd>When set to true (default is false), adding this marker\n        will create an event in the undo history that can be\n        individually undone (clearing the marker).</dd>\n        <dt id=\"mark_startStyle\"><code><strong>startStyle</strong>: string</code></dt><dd>Can be used to specify\n        an extra CSS class to be applied to the leftmost span that\n        is part of the marker.</dd>\n        <dt id=\"mark_endStyle\"><code><strong>endStyle</strong>: string</code></dt><dd>Equivalent\n        to <code>startStyle</code>, but for the rightmost span.</dd>\n        <dt id=\"mark_css\"><code><strong>css</strong>: string</code></dt>\n        <dd>A string of CSS to be applied to the covered text. For example <code>\"color: #fe3\"</code>.</dd>\n        <dt id=\"mark_attributes\"><code><strong>attributes</strong>: object</code></dt>\n        <dd>When given, add the attributes in the given object to the\n        elements created for the marked text. Adding <code>class</code> or\n        <code>style</code> attributes this way is not supported.</dd>\n        <dt id=\"mark_shared\"><code><strong>shared</strong>: boolean</code></dt><dd>When the\n        target document is <a href=\"#linkedDoc\">linked</a> to other\n        documents, you can set <code>shared</code> to true to make the\n        marker appear in all documents. By default, a marker appears\n        only in its target document.</dd>\n      </dl>\n      The method will return an object that represents the marker\n      (with constructor <code>CodeMirror.TextMarker</code>), which\n      exposes three methods:\n      <code><strong>clear</strong>()</code>, to remove the mark,\n      <code><strong>find</strong>()</code>, which returns\n      a <code>{from, to}</code> object (both holding document\n      positions), indicating the current position of the marked range,\n      or <code>undefined</code> if the marker is no longer in the\n      document, and finally <code><strong>changed</strong>()</code>,\n      which you can call if you've done something that might change\n      the size of the marker (for example changing the content of\n      a <a href=\"#mark_replacedWith\"><code>replacedWith</code></a>\n      node), and want to cheaply update the display.</dd>\n\n      <dt id=\"setBookmark\"><code><strong>doc.setBookmark</strong>(pos: {line, ch}, ?options: object) → TextMarker</code></dt>\n      <dd>Inserts a bookmark, a handle that follows the text around it\n      as it is being edited, at the given position. A bookmark has two\n      methods <code>find()</code> and <code>clear()</code>. The first\n      returns the current position of the bookmark, if it is still in\n      the document, and the second explicitly removes the bookmark.\n      The options argument is optional. If given, the following\n      properties are recognized:\n      <dl>\n        <dt><code><strong>widget</strong>: Element</code></dt><dd>Can be used to display a DOM\n        node at the current location of the bookmark (analogous to\n        the <a href=\"#mark_replacedWith\"><code>replacedWith</code></a>\n        option to <a href=\"#markText\"><code>markText</code></a>).</dd>\n        <dt><code><strong>insertLeft</strong>: boolean</code></dt><dd>By default, text typed\n        when the cursor is on top of the bookmark will end up to the\n        right of the bookmark. Set this option to true to make it go\n        to the left instead.</dd>\n        <dt><code><strong>shared</strong>: boolean</code></dt><dd>See\n        the corresponding <a href=\"#mark_shared\">option</a>\n        to <code>markText</code>.</dd>\n        <dt><code><strong>handleMouseEvents</strong>: boolean</code></dt>\n        <dd>As with <a href=\"#markText\"><code>markText</code></a>,\n        this determines whether mouse events on the widget inserted\n        for this bookmark are handled by CodeMirror. The default is\n        false.</dd>\n      </dl></dd>\n\n      <dt id=\"findMarks\"><code><strong>doc.findMarks</strong>(from: {line, ch}, to: {line, ch}) → array&lt;TextMarker&gt;</code></dt>\n      <dd>Returns an array of all the bookmarks and marked ranges\n      found between the given positions (non-inclusive).</dd>\n      <dt id=\"findMarksAt\"><code><strong>doc.findMarksAt</strong>(pos: {line, ch}) → array&lt;TextMarker&gt;</code></dt>\n      <dd>Returns an array of all the bookmarks and marked ranges\n      present at the given position.</dd>\n      <dt id=\"getAllMarks\"><code><strong>doc.getAllMarks</strong>() → array&lt;TextMarker&gt;</code></dt>\n      <dd>Returns an array containing all marked ranges in the document.</dd>\n    </dl>\n\n    <h3 id=\"api_decoration\">Widget, gutter, and decoration methods</h3>\n\n    <dl>\n      <dt id=\"setGutterMarker\"><code><strong>doc.setGutterMarker</strong>(line: integer|LineHandle, gutterID: string, value: Element) → LineHandle</code></dt>\n      <dd>Sets the gutter marker for the given gutter (identified by\n      its CSS class, see\n      the <a href=\"#option_gutters\"><code>gutters</code></a> option)\n      to the given value. Value can be either <code>null</code>, to\n      clear the marker, or a DOM element, to set it. The DOM element\n      will be shown in the specified gutter next to the specified\n      line.</dd>\n\n      <dt id=\"clearGutter\"><code><strong>doc.clearGutter</strong>(gutterID: string)</code></dt>\n      <dd>Remove all gutter markers in\n      the <a href=\"#option_gutters\">gutter</a> with the given ID.</dd>\n\n      <dt id=\"addLineClass\"><code><strong>doc.addLineClass</strong>(line: integer|LineHandle, where: string, class: string) → LineHandle</code></dt>\n      <dd>Set a CSS class name for the given line. <code>line</code>\n      can be a number or a line handle. <code>where</code> determines\n      to which element this class should be applied, can can be one\n      of <code>\"text\"</code> (the text element, which lies in front of\n      the selection), <code>\"background\"</code> (a background element\n      that will be behind the selection), <code>\"gutter\"</code> (the\n      line's gutter space), or <code>\"wrap\"</code> (the wrapper node\n      that wraps all of the line's elements, including gutter\n      elements). <code>class</code> should be the name of the class to\n      apply.</dd>\n\n      <dt id=\"removeLineClass\"><code><strong>doc.removeLineClass</strong>(line: integer|LineHandle, where: string, class: string) → LineHandle</code></dt>\n      <dd>Remove a CSS class from a line. <code>line</code> can be a\n      line handle or number. <code>where</code> should be one\n      of <code>\"text\"</code>, <code>\"background\"</code>,\n      or <code>\"wrap\"</code>\n      (see <a href=\"#addLineClass\"><code>addLineClass</code></a>). <code>class</code>\n      can be left off to remove all classes for the specified node, or\n      be a string to remove only a specific class.</dd>\n\n      <dt id=\"lineInfo\"><code><strong>doc.lineInfo</strong>(line: integer|LineHandle) → object</code></dt>\n      <dd>Returns the line number, text content, and marker status of\n      the given line, which can be either a number or a line handle.\n      The returned object has the structure <code>{line, handle, text,\n      gutterMarkers, textClass, bgClass, wrapClass, widgets}</code>,\n      where <code>gutterMarkers</code> is an object mapping gutter IDs\n      to marker elements, and <code>widgets</code> is an array\n      of <a href=\"#addLineWidget\">line widgets</a> attached to this\n      line, and the various class properties refer to classes added\n      with <a href=\"#addLineClass\"><code>addLineClass</code></a>.</dd>\n\n      <dt id=\"addWidget\"><code><strong>cm.addWidget</strong>(pos: {line, ch}, node: Element, scrollIntoView: boolean)</code></dt>\n      <dd>Puts <code>node</code>, which should be an absolutely\n      positioned DOM node, into the editor, positioned right below the\n      given <code>{line, ch}</code> position.\n      When <code>scrollIntoView</code> is true, the editor will ensure\n      that the entire node is visible (if possible). To remove the\n      widget again, simply use DOM methods (move it somewhere else, or\n      call <code>removeChild</code> on its parent).</dd>\n\n      <dt id=\"addLineWidget\"><code><strong>doc.addLineWidget</strong>(line: integer|LineHandle, node: Element, ?options: object) → LineWidget</code></dt>\n      <dd>Adds a line widget, an element shown below a line, spanning\n      the whole of the editor's width, and moving the lines below it\n      downwards. <code>line</code> should be either an integer or a\n      line handle, and <code>node</code> should be a DOM node, which\n      will be displayed below the given line. <code>options</code>,\n      when given, should be an object that configures the behavior of\n      the widget. The following options are supported (all default to\n      false):\n        <dl>\n          <dt><code><strong>coverGutter</strong>: boolean</code></dt>\n          <dd>Whether the widget should cover the gutter.</dd>\n          <dt><code><strong>noHScroll</strong>: boolean</code></dt>\n          <dd>Whether the widget should stay fixed in the face of\n          horizontal scrolling.</dd>\n          <dt><code><strong>above</strong>: boolean</code></dt>\n          <dd>Causes the widget to be placed above instead of below\n          the text of the line.</dd>\n          <dt><code><strong>handleMouseEvents</strong>: boolean</code></dt>\n          <dd>Determines whether the editor will capture mouse and\n          drag events occurring in this widget. Default is false—the\n          events will be left alone for the default browser handler,\n          or specific handlers on the widget, to capture.</dd>\n          <dt><code><strong>insertAt</strong>: integer</code></dt>\n          <dd>By default, the widget is added below other widgets for\n          the line. This option can be used to place it at a different\n          position (zero for the top, N to put it after the Nth other\n          widget). Note that this only has effect once, when the\n          widget is created.\n        </dl>\n      Note that the widget node will become a descendant of nodes with\n      CodeMirror-specific CSS classes, and those classes might in some\n      cases affect it. This method returns an object that represents\n      the widget placement. It'll have a <code>line</code> property\n      pointing at the line handle that it is associated with, and the following methods:\n        <dl>\n          <dt id=\"widget_clear\"><code><strong>clear</strong>()</code></dt><dd>Removes the widget.</dd>\n          <dt id=\"widget_changed\"><code><strong>changed</strong>()</code></dt><dd>Call\n          this if you made some change to the widget's DOM node that\n          might affect its height. It'll force CodeMirror to update\n          the height of the line that contains the widget.</dd>\n        </dl>\n      </dd>\n    </dl>\n\n    <h3 id=\"api_sizing\">Sizing, scrolling and positioning methods</h3>\n\n    <dl>\n      <dt id=\"setSize\"><code><strong>cm.setSize</strong>(width: number|string, height: number|string)</code></dt>\n      <dd>Programmatically set the size of the editor (overriding the\n      applicable <a href=\"#css-resize\">CSS\n      rules</a>). <code>width</code> and <code>height</code>\n      can be either numbers (interpreted as pixels) or CSS units\n      (<code>\"100%\"</code>, for example). You can\n      pass <code>null</code> for either of them to indicate that that\n      dimension should not be changed.</dd>\n\n      <dt id=\"scrollTo\"><code><strong>cm.scrollTo</strong>(x: number, y: number)</code></dt>\n      <dd>Scroll the editor to a given (pixel) position. Both\n      arguments may be left as <code>null</code>\n      or <code>undefined</code> to have no effect.</dd>\n      <dt id=\"getScrollInfo\"><code><strong>cm.getScrollInfo</strong>() → {left, top, width, height, clientWidth, clientHeight}</code></dt>\n      <dd>Get an <code>{left, top, width, height, clientWidth,\n      clientHeight}</code> object that represents the current scroll\n      position, the size of the scrollable area, and the size of the\n      visible area (minus scrollbars).</dd>\n      <dt id=\"scrollIntoView\"><code><strong>cm.scrollIntoView</strong>(what: {line, ch}|{left, top, right, bottom}|{from, to}|null, ?margin: number)</code></dt>\n      <dd>Scrolls the given position into view. <code>what</code> may\n      be <code>null</code> to scroll the cursor into view,\n      a <code>{line, ch}</code> position to scroll a character into\n      view, a <code>{left, top, right, bottom}</code> pixel range (in\n      editor-local coordinates), or a range <code>{from, to}</code>\n      containing either two character positions or two pixel squares.\n      The <code>margin</code> parameter is optional. When given, it\n      indicates the amount of vertical pixels around the given area\n      that should be made visible as well.</dd>\n\n      <dt id=\"cursorCoords\"><code><strong>cm.cursorCoords</strong>(where: boolean|{line, ch}, mode: string) → {left, top, bottom}</code></dt>\n      <dd>Returns an <code>{left, top, bottom}</code> object\n      containing the coordinates of the cursor position.\n      If <code>mode</code> is <code>\"local\"</code>, they will be\n      relative to the top-left corner of the editable document. If it\n      is <code>\"page\"</code> or not given, they are relative to the\n      top-left corner of the page. If <code>mode</code>\n      is <code>\"window\"</code>, the coordinates are relative to the\n      top-left corner of the currently visible (scrolled)\n      window. <code>where</code> can be a boolean indicating whether\n      you want the start (<code>true</code>) or the end\n      (<code>false</code>) of the selection, or, if a <code>{line,\n      ch}</code> object is given, it specifies the precise position at\n      which you want to measure.</dd>\n      <dt id=\"charCoords\"><code><strong>cm.charCoords</strong>(pos: {line, ch}, ?mode: string) → {left, right, top, bottom}</code></dt>\n      <dd>Returns the position and dimensions of an arbitrary\n      character. <code>pos</code> should be a <code>{line, ch}</code>\n      object. This differs from <code>cursorCoords</code> in that\n      it'll give the size of the whole character, rather than just the\n      position that the cursor would have when it would sit at that\n      position.</dd>\n      <dt id=\"coordsChar\"><code><strong>cm.coordsChar</strong>(object: {left, top}, ?mode: string) → {line, ch}</code></dt>\n      <dd>Given an <code>{left, top}</code> object (e.g. coordinates of a mouse event) returns\n      the <code>{line, ch}</code> position that corresponds to it. The\n      optional <code>mode</code> parameter determines relative to what\n      the coordinates are interpreted. It may\n      be <code>\"window\"</code>, <code>\"page\"</code> (the default),\n      or <code>\"local\"</code>.</dd>\n      <dt id=\"lineAtHeight\"><code><strong>cm.lineAtHeight</strong>(height: number, ?mode: string) → number</code></dt>\n      <dd>Computes the line at the given pixel\n      height. <code>mode</code> can be one of the same strings\n      that <a href=\"#coordsChar\"><code>coordsChar</code></a>\n      accepts.</dd>\n      <dt id=\"heightAtLine\"><code><strong>cm.heightAtLine</strong>(line: integer|LineHandle, ?mode: string, ?includeWidgets: bool) → number</code></dt>\n      <dd>Computes the height of the top of a line, in the coordinate\n      system specified by <code>mode</code>\n      (see <a href=\"#coordsChar\"><code>coordsChar</code></a>), which\n      defaults to <code>\"page\"</code>. When a line below the bottom of\n      the document is specified, the returned value is the bottom of\n      the last line in the document. By default, the position of the\n      actual text is returned. If `includeWidgets` is true and the\n      line has line widgets, the position above the first line widget\n      is returned.</dd>\n      <dt id=\"defaultTextHeight\"><code><strong>cm.defaultTextHeight</strong>() → number</code></dt>\n      <dd>Returns the line height of the default font for the editor.</dd>\n      <dt id=\"defaultCharWidth\"><code><strong>cm.defaultCharWidth</strong>() → number</code></dt>\n      <dd>Returns the pixel width of an 'x' in the default font for\n      the editor. (Note that for non-monospace fonts, this is mostly\n      useless, and even for monospace fonts, non-ascii characters\n      might have a different width).</dd>\n\n      <dt id=\"getViewport\"><code><strong>cm.getViewport</strong>() → {from: number, to: number}</code></dt>\n      <dd>Returns a <code>{from, to}</code> object indicating the\n      start (inclusive) and end (exclusive) of the currently rendered\n      part of the document. In big documents, when most content is\n      scrolled out of view, CodeMirror will only render the visible\n      part, and a margin around it. See also\n      the <a href=\"#event_viewportChange\"><code>viewportChange</code></a>\n      event.</dd>\n\n      <dt id=\"refresh\"><code><strong>cm.refresh</strong>()</code></dt>\n      <dd>If your code does something to change the size of the editor\n      element (window resizes are already listened for), or unhides\n      it, you should probably follow up by calling this method to\n      ensure CodeMirror is still looking as intended. See also\n      the <a href=\"#addon_autorefresh\">autorefresh addon</a>.</dd>\n    </dl>\n\n    <h3 id=\"api_mode\">Mode, state, and token-related methods</h3>\n\n    <p>When writing language-aware functionality, it can often be\n    useful to hook into the knowledge that the CodeMirror language\n    mode has. See <a href=\"#modeapi\">the section on modes</a> for a\n    more detailed description of how these work.</p>\n\n    <dl>\n      <dt id=\"getMode\"><code><strong>doc.getMode</strong>() → object</code></dt>\n      <dd>Gets the (outer) mode object for the editor. Note that this\n      is distinct from <code>getOption(\"mode\")</code>, which gives you\n      the mode specification, rather than the resolved, instantiated\n      <a href=\"#defineMode\">mode object</a>.</dd>\n\n      <dt id=\"getModeAt\"><code><strong>cm.getModeAt</strong>(pos: {line, ch}) → object</code></dt>\n      <dd>Gets the inner mode at a given position. This will return\n      the same as <a href=\"#getMode\"><code>getMode</code></a> for\n      simple modes, but will return an inner mode for nesting modes\n      (such as <code>htmlmixed</code>).</dd>\n\n      <dt id=\"getTokenAt\"><code><strong>cm.getTokenAt</strong>(pos: {line, ch}, ?precise: boolean) → object</code></dt>\n      <dd>Retrieves information about the token the current mode found\n      before the given position (a <code>{line, ch}</code> object). The\n      returned object has the following properties:\n      <dl>\n        <dt><code><strong>start</strong></code></dt><dd>The character (on the given line) at which the token starts.</dd>\n        <dt><code><strong>end</strong></code></dt><dd>The character at which the token ends.</dd>\n        <dt><code><strong>string</strong></code></dt><dd>The token's string.</dd>\n        <dt><code><strong>type</strong></code></dt><dd>The token type the mode assigned\n        to the token, such as <code>\"keyword\"</code>\n        or <code>\"comment\"</code> (may also be null).</dd>\n        <dt><code><strong>state</strong></code></dt><dd>The mode's state at the end of this token.</dd>\n      </dl>\n      If <code>precise</code> is true, the token will be guaranteed to be accurate based on recent edits. If false or\n      not specified, the token will use cached state information, which will be faster but might not be accurate if\n      edits were recently made and highlighting has not yet completed.\n      </dd>\n\n      <dt id=\"getLineTokens\"><code><strong>cm.getLineTokens</strong>(line: integer, ?precise: boolean) → array&lt;{start, end, string, type, state}&gt;</code></dt>\n      <dd>This is similar\n      to <a href=\"#getTokenAt\"><code>getTokenAt</code></a>, but\n      collects all tokens for a given line into an array. It is much\n      cheaper than repeatedly calling <code>getTokenAt</code>, which\n      re-parses the part of the line before the token for every call.</dd>\n\n      <dt id=\"getTokenTypeAt\"><code><strong>cm.getTokenTypeAt</strong>(pos: {line, ch}) → string</code></dt>\n      <dd>This is a (much) cheaper version\n      of <a href=\"#getTokenAt\"><code>getTokenAt</code></a> useful for\n      when you just need the type of the token at a given position,\n      and no other information. Will return <code>null</code> for\n      unstyled tokens, and a string, potentially containing multiple\n      space-separated style names, otherwise.</dd>\n\n      <dt id=\"getHelpers\"><code><strong>cm.getHelpers</strong>(pos: {line, ch}, type: string) → array&lt;helper&gt;</code></dt>\n      <dd>Fetch the set of applicable helper values for the given\n      position. Helpers provide a way to look up functionality\n      appropriate for a mode. The <code>type</code> argument provides\n      the helper namespace (see\n      <a href=\"#registerHelper\"><code>registerHelper</code></a>), in\n      which the values will be looked up. When the mode itself has a\n      property that corresponds to the <code>type</code>, that\n      directly determines the keys that are used to look up the helper\n      values (it may be either a single string, or an array of\n      strings). Failing that, the mode's <code>helperType</code>\n      property and finally the mode's name are used.</dd>\n      <dd>For example, the JavaScript mode has a\n      property <code>fold</code> containing <code>\"brace\"</code>. When\n      the <code>brace-fold</code> addon is loaded, that defines a\n      helper named <code>brace</code> in the <code>fold</code>\n      namespace. This is then used by\n      the <a href=\"#addon_foldcode\"><code>foldcode</code></a> addon to\n      figure out that it can use that folding function to fold\n      JavaScript code.</dd>\n      <dd>When any <a href=\"#registerGlobalHelper\">'global'</a>\n      helpers are defined for the given namespace, their predicates\n      are called on the current mode and editor, and all those that\n      declare they are applicable will also be added to the array that\n      is returned.</dd>\n\n      <dt id=\"getHelper\"><code><strong>cm.getHelper</strong>(pos: {line, ch}, type: string) → helper</code></dt>\n      <dd>Returns the first applicable helper value.\n      See <a href=\"#getHelpers\"><code>getHelpers</code></a>.</dd>\n\n      <dt id=\"getStateAfter\"><code><strong>cm.getStateAfter</strong>(?line: integer, ?precise: boolean) → object</code></dt>\n      <dd>Returns the mode's parser state, if any, at the end of the\n      given line number. If no line number is given, the state at the\n      end of the document is returned. This can be useful for storing\n      parsing errors in the state, or getting other kinds of\n      contextual information for a line. <code>precise</code> is defined\n      as in <code>getTokenAt()</code>.</dd>\n    </dl>\n\n    <h3 id=\"api_misc\">Miscellaneous methods</h3>\n\n    <dl>\n      <dt id=\"operation\"><code><strong>cm.operation</strong>(func: () → any) → any</code></dt>\n      <dd>CodeMirror internally buffers changes and only updates its\n      DOM structure after it has finished performing some operation.\n      If you need to perform a lot of operations on a CodeMirror\n      instance, you can call this method with a function argument. It\n      will call the function, buffering up all changes, and only doing\n      the expensive update after the function returns. This can be a\n      lot faster. The return value from this method will be the return\n      value of your function.</dd>\n\n      <dt id=\"startOperation\"><code><strong>cm.startOperation</strong>()</code></dt>\n      <dt id=\"endOperation\"><code><strong>cm.endOperation</strong>()</code></dt>\n      <dd>In normal circumstances, use the above <code>operation</code>\n      method. But if you want to buffer operations happening asynchronously,\n      or that can't all be wrapped in a callback function, you can\n      call <code>startOperation</code> to tell CodeMirror to start\n      buffering changes, and <code>endOperation</code> to actually\n      render all the updates. <em>Be careful:</em> if you use this\n      API and forget to call <code>endOperation</code>, the editor will\n      just never update.</dd>\n\n      <dt id=\"indentLine\"><code><strong>cm.indentLine</strong>(line: integer, ?dir: string|integer)</code></dt>\n      <dd>Adjust the indentation of the given line. The second\n      argument (which defaults to <code>\"smart\"</code>) may be one of:\n        <dl>\n          <dt><code><strong>\"prev\"</strong></code></dt>\n          <dd>Base indentation on the indentation of the previous line.</dd>\n          <dt><code><strong>\"smart\"</strong></code></dt>\n          <dd>Use the mode's smart indentation if available, behave\n          like <code>\"prev\"</code> otherwise.</dd>\n          <dt><code><strong>\"add\"</strong></code></dt>\n          <dd>Increase the indentation of the line by\n          one <a href=\"#option_indentUnit\">indent unit</a>.</dd>\n          <dt><code><strong>\"subtract\"</strong></code></dt>\n          <dd>Reduce the indentation of the line.</dd>\n          <dt><code><strong>&lt;integer></strong></code></dt>\n          <dd>Add (positive number) or reduce (negative number) the\n          indentation by the given amount of spaces.</dd>\n        </dl></dd>\n\n      <dt id=\"toggleOverwrite\"><code><strong>cm.toggleOverwrite</strong>(?value: boolean)</code></dt>\n      <dd>Switches between overwrite and normal insert mode (when not\n      given an argument), or sets the overwrite mode to a specific\n      state (when given an argument).</dd>\n\n      <dt id=\"isReadOnly\"><code><strong>cm.isReadOnly</strong>() → boolean</code></dt>\n      <dd>Tells you whether the editor's content can be edited by the\n      user.</dd>\n\n      <dt id=\"lineSeparator\"><code><strong>doc.lineSeparator</strong>()</code></dt>\n      <dd>Returns the preferred line separator string for this\n      document, as per the <a href=\"#option_lineSeparator\">option</a>\n      by the same name. When that option is <code>null</code>, the\n      string <code>\"\\n\"</code> is returned.</dd>\n\n      <dt id=\"execCommand\"><code><strong>cm.execCommand</strong>(name: string)</code></dt>\n      <dd>Runs the <a href=\"#commands\">command</a> with the given name on the editor.</dd>\n\n      <dt id=\"posFromIndex\"><code><strong>doc.posFromIndex</strong>(index: integer) → {line, ch}</code></dt>\n      <dd>Calculates and returns a <code>{line, ch}</code> object for a\n      zero-based <code>index</code> who's value is relative to the start of the\n      editor's text. If the <code>index</code> is out of range of the text then\n      the returned object is clipped to start or end of the text\n      respectively.</dd>\n      <dt id=\"indexFromPos\"><code><strong>doc.indexFromPos</strong>(object: {line, ch}) → integer</code></dt>\n      <dd>The reverse of <a href=\"#posFromIndex\"><code>posFromIndex</code></a>.</dd>\n\n      <dt id=\"focus\"><code><strong>cm.focus</strong>()</code></dt>\n      <dd>Give the editor focus.</dd>\n\n      <dt id=\"phrase\"><code><strong>cm.phrase</strong>(text: string) → string</code></dt>\n      <dd>Allow the given string to be translated with\n      the <a href=\"#option_phrases\"><code>phrases</code>\n      option</a>.</dd>\n\n      <dt id=\"getInputField\"><code><strong>cm.getInputField</strong>() → Element</code></dt>\n      <dd>Returns the input field for the editor. Will be a textarea\n      or an editable div, depending on the value of\n      the <a href=\"#option_inputStyle\"><code>inputStyle</code></a>\n      option.</dd>\n      <dt id=\"getWrapperElement\"><code><strong>cm.getWrapperElement</strong>() → Element</code></dt>\n      <dd>Returns the DOM node that represents the editor, and\n      controls its size. Remove this from your tree to delete an\n      editor instance.</dd>\n      <dt id=\"getScrollerElement\"><code><strong>cm.getScrollerElement</strong>() → Element</code></dt>\n      <dd>Returns the DOM node that is responsible for the scrolling\n      of the editor.</dd>\n      <dt id=\"getGutterElement\"><code><strong>cm.getGutterElement</strong>() → Element</code></dt>\n      <dd>Fetches the DOM node that contains the editor gutters.</dd>\n    </dl>\n\n    <h3 id=\"api_static\">Static properties</h3>\n    <p>The <code>CodeMirror</code> object itself provides\n    several useful properties.</p>\n\n    <dl>\n      <dt id=\"version\"><code><strong>CodeMirror.version</strong>: string</code></dt>\n      <dd>It contains a string that indicates the version of the\n      library. This is a triple of\n      integers <code>\"major.minor.patch\"</code>,\n      where <code>patch</code> is zero for releases, and something\n      else (usually one) for dev snapshots.</dd>\n\n      <dt id=\"fromTextArea\"><code><strong>CodeMirror.fromTextArea</strong>(textArea: TextAreaElement, ?config: object)</code></dt>\n      <dd>This method provides another way to initialize an editor. It\n      takes a textarea DOM node as first argument and an optional\n      configuration object as second. It will replace the textarea\n      with a CodeMirror instance, and wire up the form of that\n      textarea (if any) to make sure the editor contents are put into\n      the textarea when the form is submitted. The text in the\n      textarea will provide the content for the editor. A CodeMirror\n      instance created this way has three additional methods:\n      <dl>\n        <dt id=\"save\"><code><strong>cm.save</strong>()</code></dt>\n        <dd>Copy the content of the editor into the textarea.</dd>\n\n        <dt id=\"toTextArea\"><code><strong>cm.toTextArea</strong>()</code></dt>\n        <dd>Remove the editor, and restore the original textarea (with\n        the editor's current content). If you dynamically create and\n        destroy editors made with `fromTextArea`, without destroying\n        the form they are part of, you should make sure to call\n        `toTextArea` to remove the editor, or its `\"submit\"` handler\n        on the form will cause a memory leak.</dd>\n\n        <dt id=\"getTextArea\"><code><strong>cm.getTextArea</strong>() → TextAreaElement</code></dt>\n        <dd>Returns the textarea that the instance was based on.</dd>\n      </dl>\n      </dd>\n\n      <dt id=\"defaults\"><code><strong>CodeMirror.defaults</strong>: object</code></dt>\n      <dd>An object containing default values for\n      all <a href=\"#config\">options</a>. You can assign to its\n      properties to modify defaults (though this won't affect editors\n      that have already been created).</dd>\n\n      <dt id=\"defineExtension\"><code><strong>CodeMirror.defineExtension</strong>(name: string, value: any)</code></dt>\n      <dd>If you want to define extra methods in terms of the\n      CodeMirror API, it is possible to\n      use <code>defineExtension</code>. This will cause the given\n      value (usually a method) to be added to all CodeMirror instances\n      created from then on.</dd>\n\n      <dt id=\"defineDocExtension\"><code><strong>CodeMirror.defineDocExtension</strong>(name: string, value: any)</code></dt>\n      <dd>Like <a href=\"#defineExtension\"><code>defineExtension</code></a>,\n      but the method will be added to the interface\n      for <a href=\"#Doc\"><code>Doc</code></a> objects instead.</dd>\n\n      <dt id=\"defineOption\"><code><strong>CodeMirror.defineOption</strong>(name: string,\n      default: any, updateFunc: function)</code></dt>\n      <dd>Similarly, <code>defineOption</code> can be used to define new options for\n      CodeMirror. The <code>updateFunc</code> will be called with the\n      editor instance and the new value when an editor is initialized,\n      and whenever the option is modified\n      through <a href=\"#setOption\"><code>setOption</code></a>.</dd>\n\n      <dt id=\"defineInitHook\"><code><strong>CodeMirror.defineInitHook</strong>(func: function)</code></dt>\n      <dd>If your extension just needs to run some\n      code whenever a CodeMirror instance is initialized,\n      use <code>CodeMirror.defineInitHook</code>. Give it a function as\n      its only argument, and from then on, that function will be called\n      (with the instance as argument) whenever a new CodeMirror instance\n      is initialized.</dd>\n\n      <dt id=\"registerHelper\"><code><strong>CodeMirror.registerHelper</strong>(type: string, name: string, value: helper)</code></dt>\n      <dd>Registers a helper value with the given <code>name</code> in\n      the given namespace (<code>type</code>). This is used to define\n      functionality that may be looked up by mode. Will create (if it\n      doesn't already exist) a property on the <code>CodeMirror</code>\n      object for the given <code>type</code>, pointing to an object\n      that maps names to values. I.e. after\n      doing <code>CodeMirror.registerHelper(\"hint\", \"foo\",\n      myFoo)</code>, the value <code>CodeMirror.hint.foo</code> will\n      point to <code>myFoo</code>.</dd>\n\n      <dt id=\"registerGlobalHelper\"><code><strong>CodeMirror.registerGlobalHelper</strong>(type: string, name: string, predicate: fn(mode, CodeMirror), value: helper)</code></dt>\n      <dd>Acts\n      like <a href=\"#registerHelper\"><code>registerHelper</code></a>,\n      but also registers this helper as 'global', meaning that it will\n      be included by <a href=\"#getHelpers\"><code>getHelpers</code></a>\n      whenever the given <code>predicate</code> returns true when\n      called with the local mode and editor.</dd>\n\n      <dt id=\"Pos\"><code><strong>CodeMirror.Pos</strong>(line: integer, ?ch: integer, ?sticky: string)</code></dt>\n      <dd>A constructor for the objects that are used to represent\n      positions in editor documents. <code>sticky</code> defaults to\n      null, but can be set to <code>\"before\"</code>\n      or <code>\"after\"</code> to make the position explicitly\n      associate with the character before or after it.</dd>\n\n      <dt id=\"changeEnd\"><code><strong>CodeMirror.changeEnd</strong>(change: object) → {line, ch}</code></dt>\n      <dd>Utility function that computes an end position from a change\n      (an object with <code>from</code>, <code>to</code>,\n      and <code>text</code> properties, as passed to\n      various <a href=\"#event_change\">event handlers</a>). The\n      returned position will be the end of the changed\n      range, <em>after</em> the change is applied.</dd>\n\n      <dt id=\"countColumn\"><code><strong>CodeMirror.countColumn</strong>(line: string, index: number, tabSize: number) → number</code></dt>\n      <dd>Find the column position at a given string index using a given tabsize.</dd>\n    </dl>\n</section>\n\n<section id=addons>\n    <h2 id=\"addons\">Addons</h2>\n\n    <p>The <code>addon</code> directory in the distribution contains a\n    number of reusable components that implement extra editor\n    functionality (on top of extension functions\n    like <a href=\"#defineOption\"><code>defineOption</code></a>, <a href=\"#defineExtension\"><code>defineExtension</code></a>,\n    and <a href=\"#registerHelper\"><code>registerHelper</code></a>). In\n    brief, they are:</p>\n\n    <dl>\n      <dt id=\"addon_dialog\"><a href=\"../addon/dialog/dialog.js\"><code>dialog/dialog.js</code></a></dt>\n      <dd>Provides a very simple way to query users for text input.\n      Adds the <strong><code>openDialog(template, callback, options) →\n      closeFunction</code></strong> method to CodeMirror instances,\n      which can be called with an HTML fragment or a detached DOM\n      node that provides the prompt (should include an <code>input</code>\n      or <code>button</code> tag), and a callback function that is called\n      when the user presses enter. It returns a function <code>closeFunction</code>\n      which, if called, will close the dialog immediately.\n      <strong><code>openDialog</code></strong> takes the following options:\n        <dl>\n          <dt><code><strong>closeOnEnter</strong>: bool</code></dt>\n          <dd>If true, the dialog will be closed when the user presses\n          enter in the input. Defaults to <code>true</code>.</dd>\n          <dt><code><strong>closeOnBlur</strong>: bool</code></dt>\n          <dd>Determines whether the dialog is closed when it loses focus. Defaults to <code>true</code>.</dd>\n          <dt><code><strong>onKeyDown</strong>: fn(event: KeyboardEvent, value: string, close: fn()) → bool</code></dt>\n          <dd>An event handler that will be called whenever <code>keydown</code> fires in the\n          dialog's input. If your callback returns <code>true</code>,\n          the dialog will not do any further processing of the event.</dd>\n          <dt><code><strong>onKeyUp</strong>: fn(event: KeyboardEvent, value: string, close: fn()) → bool</code></dt>\n          <dd>Same as <code>onKeyDown</code> but for the\n          <code>keyup</code> event.</dd>\n          <dt><code><strong>onInput</strong>: fn(event: InputEvent, value: string, close: fn()) → bool</code></dt>\n          <dd>Same as <code>onKeyDown</code> but for the\n          <code>input</code> event.</dd>\n          <dt><code><strong>onClose</strong>: fn(instance)</code>:</dt>\n          <dd>A callback that will be called after the dialog has been closed and\n          removed from the DOM. No return value.</dd>\n        </dl>\n\n      <p>Also adds an <strong><code>openNotification(template, options) →\n      closeFunction</code></strong> function that simply shows an HTML\n      fragment as a notification at the top of the editor. It takes a\n      single option: <code>duration</code>, the amount of time after\n      which the notification will be automatically closed. If <code>\n      duration</code> is zero, the dialog will not be closed automatically.</p>\n\n      <p>Depends on <code>addon/dialog/dialog.css</code>.</p></dd>\n\n      <dt id=\"addon_searchcursor\"><a href=\"../addon/search/searchcursor.js\"><code>search/searchcursor.js</code></a></dt>\n      <dd>Adds the <code>getSearchCursor(query, start, options) →\n      cursor</code> method to CodeMirror instances, which can be used\n      to implement search/replace functionality. <code>query</code>\n      can be a regular expression or a string. <code>start</code>\n      provides the starting position of the search. It can be\n      a <code>{line, ch}</code> object, or can be left off to default\n      to the start of the document. <code>options</code> is an\n      optional object, which can contain the property `caseFold:\n      false` to disable case folding when matching a string, or the\n      property `multiline: disable` to disable multi-line matching for\n      regular expressions (which may help performance). A search\n      cursor has the following methods:\n        <dl>\n          <dt><code><strong>findNext</strong>() → boolean</code></dt>\n          <dt><code><strong>findPrevious</strong>() → boolean</code></dt>\n          <dd>Search forward or backward from the current position.\n          The return value indicates whether a match was found. If\n          matching a regular expression, the return value will be the\n          array returned by the <code>match</code> method, in case you\n          want to extract matched groups.</dd>\n          <dt><code><strong>from</strong>() → {line, ch}</code></dt>\n          <dt><code><strong>to</strong>() → {line, ch}</code></dt>\n          <dd>These are only valid when the last call\n          to <code>findNext</code> or <code>findPrevious</code> did\n          not return false. They will return <code>{line, ch}</code>\n          objects pointing at the start and end of the match.</dd>\n          <dt><code><strong>replace</strong>(text: string, ?origin: string)</code></dt>\n          <dd>Replaces the currently found match with the given text\n          and adjusts the cursor position to reflect the\n          replacement.</dd>\n        </dl></dd>\n\n      <dt id=\"addon_search\"><a href=\"../addon/search/search.js\"><code>search/search.js</code></a></dt>\n      <dd>Implements the search commands. CodeMirror has keys bound to\n      these by default, but will not do anything with them unless an\n      implementation is provided. Depends\n      on <code>searchcursor.js</code>, and will make use\n      of <a href=\"#addon_dialog\"><code>openDialog</code></a> when\n      available to make prompting for search queries less ugly.</dd>\n\n      <dt id=\"addon_jump-to-line\"><a href=\"../addon/search/jump-to-line.js\"><code>search/jump-to-line.js</code></a></dt>\n      <dd>Implements a <code>jumpToLine</code> command and binding <code>Alt-G</code> to it.\n      Accepts <code>linenumber</code>, <code>+/-linenumber</code>, <code>line:char</code>,\n      <code>scroll%</code> and <code>:linenumber</code> formats.\n      This will make use of <a href=\"#addon_dialog\"><code>openDialog</code></a>\n      when available to make prompting for line number neater.</dd>\n\n      <dt id=\"addon_matchesonscrollbar\"><a href=\"../addon/search/matchesonscrollbar.js\"><code>search/matchesonscrollbar.js</code></a></dt>\n      <dd>Adds a <code>showMatchesOnScrollbar</code> method to editor\n      instances, which should be given a query (string or regular\n      expression), optionally a case-fold flag (only applicable for\n      strings), and optionally a class name (defaults\n      to <code>CodeMirror-search-match</code>) as arguments. When\n      called, matches of the given query will be displayed on the\n      editor's vertical scrollbar. The method returns an object with\n      a <code>clear</code> method that can be called to remove the\n      matches. Depends on\n      the <a href=\"#addon_annotatescrollbar\"><code>annotatescrollbar</code></a>\n      addon, and\n      the <a href=\"../addon/search/matchesonscrollbar.css\"><code>matchesonscrollbar.css</code></a>\n      file provides a default (transparent yellowish) definition of\n      the CSS class applied to the matches. Note that the matches are\n      only perfectly aligned if your scrollbar does not have buttons\n      at the top and bottom. You can use\n      the <a href=\"#addon_simplescrollbars\"><code>simplescrollbar</code></a>\n      addon to make sure of this. If this addon is loaded,\n      the <a href=\"#addon_search\"><code>search</code></a> addon will\n      automatically use it.</dd>\n\n      <dt id=\"addon_matchbrackets\"><a href=\"../addon/edit/matchbrackets.js\"><code>edit/matchbrackets.js</code></a></dt>\n      <dd>Defines an option <code>matchBrackets</code> which, when set\n      to true or an options object, causes matching brackets to be\n      highlighted whenever the cursor is next to them. It also adds a\n      method <code>matchBrackets</code> that forces this to happen\n      once, and a method <code>findMatchingBracket</code> that can be\n      used to run the bracket-finding algorithm that this uses\n      internally. It takes a start position and an optional config\n      object. By default, it will find the match to a matchable\n      character either before or after the cursor (preferring the one\n      before), but you can control its behavior with these options:\n        <dl>\n          <dt><strong><code>afterCursor</code></strong></dt>\n          <dd>Only use the character after the start position, never the one before it.</dd>\n          <dt><strong><code>strict</code></strong></dt>\n          <dd>Causes only matches where both brackets are at the same side of the start position to be considered.</dd>\n          <dt><strong><code>maxScanLines</code></strong></dt>\n          <dd>Stop after scanning this amount of lines without a successful match. Defaults to 1000.</dd>\n          <dt><strong><code>maxScanLineLength</code></strong></dt>\n          <dd>Ignore lines longer than this. Defaults to 10000.</dd>\n          <dt><strong><code>maxHighlightLineLength</code></strong></dt>\n          <dd>Don't highlight a bracket in a line longer than this. Defaults to 1000.</dd>\n        </dl></dd>\n\n      <dt id=\"addon_closebrackets\"><a href=\"../addon/edit/closebrackets.js\"><code>edit/closebrackets.js</code></a></dt>\n      <dd>Defines an option <code>autoCloseBrackets</code> that will\n      auto-close brackets and quotes when typed. By default, it'll\n      auto-close <code>()[]{}''\"\"</code>, but you can pass it a string\n      similar to that (containing pairs of matching characters), or an\n      object with <code>pairs</code> and\n      optionally <code>explode</code> properties to customize\n      it. <code>explode</code> should be a similar string that gives\n      the pairs of characters that, when enter is pressed between\n      them, should have the second character also moved to its own\n      line. By default, if the active mode has\n      a <code>closeBrackets</code> property, that overrides the\n      configuration given in the option. But you can add\n      an <code>override</code> property with a truthy value to\n      override mode-specific\n      configuration. <a href=\"../demo/closebrackets.html\">Demo\n      here</a>.</dd>\n\n      <dt id=\"addon_matchtags\"><a href=\"../addon/edit/matchtags.js\"><code>edit/matchtags.js</code></a></dt>\n      <dd>Defines an option <code>matchTags</code> that, when enabled,\n      will cause the tags around the cursor to be highlighted (using\n      the <code>CodeMirror-matchingtag</code> class). Also\n      defines\n      a <a href=\"#commands\">command</a> <code>toMatchingTag</code>,\n      which you can bind a key to in order to jump to the tag matching\n      the one under the cursor. Depends on\n      the <code>addon/fold/xml-fold.js</code>\n      addon. <a href=\"../demo/matchtags.html\">Demo here.</a></dd>\n\n      <dt id=\"addon_trailingspace\"><a href=\"../addon/edit/trailingspace.js\"><code>edit/trailingspace.js</code></a></dt>\n      <dd>Adds an option <code>showTrailingSpace</code> which, when\n      enabled, adds the CSS class <code>cm-trailingspace</code> to\n      stretches of whitespace at the end of lines.\n      The <a href=\"../demo/trailingspace.html\">demo</a> has a nice\n      squiggly underline style for this class.</dd>\n\n      <dt id=\"addon_closetag\"><a href=\"../addon/edit/closetag.js\"><code>edit/closetag.js</code></a></dt>\n      <dd>Defines an <code>autoCloseTags</code> option that will\n      auto-close XML tags when '<code>&gt;</code>' or '<code>/</code>'\n      is typed, and\n      a <code>closeTag</code> <a href=\"#commands\">command</a> that\n      closes the nearest open tag. Depends on\n      the <code>fold/xml-fold.js</code> addon. See\n      the <a href=\"../demo/closetag.html\">demo</a>.</dd>\n\n      <dt id=\"addon_continuelist\"><a href=\"../addon/edit/continuelist.js\"><code>edit/continuelist.js</code></a></dt>\n      <dd>Markdown specific. Defines\n      a <code>\"newlineAndIndentContinueMarkdownList\"</code> <a href=\"#commands\">command</a>\n      that can be bound to <code>enter</code> to automatically\n      insert the leading characters for continuing a list. See\n      the <a href=\"../mode/markdown/index.html\">Markdown mode\n      demo</a>.</dd>\n\n      <dt id=\"addon_comment\"><a href=\"../addon/comment/comment.js\"><code>comment/comment.js</code></a></dt>\n      <dd>Addon for commenting and uncommenting code. Adds four\n      methods to CodeMirror instances:\n      <dl>\n        <dt id=\"toggleComment\"><code><strong>toggleComment</strong>(?options: object)</code></dt>\n        <dd>Tries to uncomment the current selection, and if that\n        fails, line-comments it.</dd>\n        <dt id=\"lineComment\"><code><strong>lineComment</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>\n        <dd>Set the lines in the given range to be line comments. Will\n        fall back to <code>blockComment</code> when no line comment\n        style is defined for the mode.</dd>\n        <dt id=\"blockComment\"><code><strong>blockComment</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>\n        <dd>Wrap the code in the given range in a block comment. Will\n        fall back to <code>lineComment</code> when no block comment\n        style is defined for the mode.</dd>\n        <dt id=\"uncomment\"><code><strong>uncomment</strong>(from: {line, ch}, to: {line, ch}, ?options: object) → boolean</code></dt>\n        <dd>Try to uncomment the given range.\n          Returns <code>true</code> if a comment range was found and\n          removed, <code>false</code> otherwise.</dd>\n      </dl>\n      The <code>options</code> object accepted by these methods may\n      have the following properties:\n      <dl>\n        <dt><code>blockCommentStart, blockCommentEnd, blockCommentLead, lineComment: string</code></dt>\n        <dd>Override the <a href=\"#mode_comment\">comment string\n        properties</a> of the mode with custom comment strings.</dd>\n        <dt><code><strong>padding</strong>: string</code></dt>\n        <dd>A string that will be inserted after opening and leading\n        markers, and before closing comment markers. Defaults to a\n        single space.</dd>\n        <dt><code><strong>commentBlankLines</strong>: boolean</code></dt>\n        <dd>Whether, when adding line comments, to also comment lines\n        that contain only whitespace.</dd>\n        <dt><code><strong>indent</strong>: boolean</code></dt>\n        <dd>When adding line comments and this is turned on, it will\n        align the comment block to the current indentation of the\n        first line of the block.</dd>\n        <dt><code><strong>fullLines</strong>: boolean</code></dt>\n        <dd>When block commenting, this controls whether the whole\n        lines are indented, or only the precise range that is given.\n        Defaults to <code>true</code>.</dd>\n      </dl>\n      The addon also defines\n      a <code>toggleComment</code> <a href=\"#commands\">command</a>,\n      which is a shorthand command for calling\n      <code>toggleComment</code> with no options.</dd>\n\n      <dt id=\"addon_foldcode\"><a href=\"../addon/fold/foldcode.js\"><code>fold/foldcode.js</code></a></dt>\n      <dd>Helps with code folding. Adds a <code>foldCode</code> method\n      to editor instances, which will try to do a code fold starting\n      at the given line, or unfold the fold that is already present.\n      The method takes as first argument the position that should be\n      folded (may be a line number or\n      a <a href=\"#Pos\"><code>Pos</code></a>), and as second optional\n      argument either a range-finder function, or an options object,\n      supporting the following properties:\n      <dl>\n        <dt><code><strong>rangeFinder</strong>: fn(CodeMirror, Pos)</code></dt>\n        <dd id=\"helper_fold_auto\">The function that is used to find\n        foldable ranges. If this is not directly passed, it will\n        default to <code>CodeMirror.fold.auto</code>, which\n        uses <a href=\"#getHelpers\"><code>getHelpers</code></a> with\n        a <code>\"fold\"</code> type to find folding functions\n        appropriate for the local mode. There are files in\n        the <a href=\"../addon/fold/\"><code>addon/fold/</code></a>\n        directory providing <code>CodeMirror.fold.brace</code>, which\n        finds blocks in brace languages (JavaScript, C, Java,\n        etc), <code>CodeMirror.fold.indent</code>, for languages where\n        indentation determines block structure (Python, Haskell),\n        and <code>CodeMirror.fold.xml</code>, for XML-style languages,\n        and <code>CodeMirror.fold.comment</code>, for folding comment\n        blocks.</dd>\n        <dt><code><strong>widget</strong>: string|Element</code></dt>\n        <dd>The widget to show for folded ranges. Can be either a\n        string, in which case it'll become a span with\n        class <code>CodeMirror-foldmarker</code>, or a DOM node.</dd>\n        <dt><code><strong>scanUp</strong>: boolean</code></dt>\n        <dd>When true (default is false), the addon will try to find\n        foldable ranges on the lines above the current one if there\n        isn't an eligible one on the given line.</dd>\n        <dt><code><strong>minFoldSize</strong>: integer</code></dt>\n        <dd>The minimum amount of lines that a fold should span to be\n        accepted. Defaults to 0, which also allows single-line\n        folds.</dd>\n      </dl>\n      See <a href=\"../demo/folding.html\">the demo</a> for an\n      example.</dd>\n\n      <dt id=\"addon_foldgutter\"><a href=\"../addon/fold/foldgutter.js\"><code>fold/foldgutter.js</code></a></dt>\n      <dd>Provides an option <code>foldGutter</code>, which can be\n      used to create a gutter with markers indicating the blocks that\n      can be folded. Create a gutter using\n      the <a href=\"#option_gutters\"><code>gutters</code></a> option,\n      giving it the class <code>CodeMirror-foldgutter</code> or\n      something else if you configure the addon to use a different\n      class, and this addon will show markers next to folded and\n      foldable blocks, and handle clicks in this gutter. Note that\n      CSS styles should be applied to make the gutter, and the fold\n      markers within it, visible. A default set of CSS styles are\n      available in:\n      <a href=\"../addon/fold/foldgutter.css\">\n        <code>addon/fold/foldgutter.css</code>\n      </a>.\n      The option\n      can be either set to <code>true</code>, or an object containing\n      the following optional option fields:\n      <dl>\n        <dt><code><strong>gutter</strong>: string</code></dt>\n        <dd>The CSS class of the gutter. Defaults\n        to <code>\"CodeMirror-foldgutter\"</code>. You will have to\n        style this yourself to give it a width (and possibly a\n        background). See the default gutter style rules above.</dd>\n        <dt><code><strong>indicatorOpen</strong>: string | Element</code></dt>\n        <dd>A CSS class or DOM element to be used as the marker for\n        open, foldable blocks. Defaults\n        to <code>\"CodeMirror-foldgutter-open\"</code>.</dd>\n        <dt><code><strong>indicatorFolded</strong>: string | Element</code></dt>\n        <dd>A CSS class or DOM element to be used as the marker for\n        folded blocks. Defaults to <code>\"CodeMirror-foldgutter-folded\"</code>.</dd>\n        <dt><code><strong>rangeFinder</strong>: fn(CodeMirror, Pos)</code></dt>\n        <dd>The range-finder function to use when determining whether\n        something can be folded. When not\n        given, <a href=\"#helper_fold_auto\"><code>CodeMirror.fold.auto</code></a>\n        will be used as default.</dd>\n      </dl>\n      The <code>foldOptions</code> editor option can be set to an\n      object to provide an editor-wide default configuration.\n      Demo <a href=\"../demo/folding.html\">here</a>.</dd>\n\n      <dt id=\"addon_runmode\"><a href=\"../addon/runmode/runmode.js\"><code>runmode/runmode.js</code></a></dt>\n      <dd>Can be used to run a CodeMirror mode over text without\n      actually opening an editor instance.\n      See <a href=\"../demo/runmode.html\">the demo</a> for an example.\n      There are alternate versions of the file available for\n      running <a href=\"../addon/runmode/runmode-standalone.js\">stand-alone</a>\n      (without including all of CodeMirror) and\n      for <a href=\"../addon/runmode/runmode.node.js\">running under\n      node.js</a> (see <code>bin/source-highlight</code> for an example of using the latter).</dd>\n\n      <dt id=\"addon_colorize\"><a href=\"../addon/runmode/colorize.js\"><code>runmode/colorize.js</code></a></dt>\n      <dd>Provides a convenient way to syntax-highlight code snippets\n      in a webpage. Depends on\n      the <a href=\"#addon_runmode\"><code>runmode</code></a> addon (or\n      its standalone variant). Provides\n      a <code>CodeMirror.colorize</code> function that can be called\n      with an array (or other array-ish collection) of DOM nodes that\n      represent the code snippets. By default, it'll get\n      all <code>pre</code> tags. Will read the <code>data-lang</code>\n      attribute of these nodes to figure out their language, and\n      syntax-color their content using the relevant CodeMirror mode\n      (you'll have to load the scripts for the relevant modes\n      yourself). A second argument may be provided to give a default\n      mode, used when no language attribute is found for a node. Used\n      in this manual to highlight example code.</dd>\n\n      <dt id=\"addon_overlay\"><a href=\"../addon/mode/overlay.js\"><code>mode/overlay.js</code></a></dt>\n      <dd>Mode combinator that can be used to extend a mode with an\n      'overlay' — a secondary mode is run over the stream, along with\n      the base mode, and can color specific pieces of text without\n      interfering with the base mode.\n      Defines <code>CodeMirror.overlayMode</code>, which is used to\n      create such a mode. See <a href=\"../demo/mustache.html\">this\n      demo</a> for a detailed example.</dd>\n\n      <dt id=\"addon_multiplex\"><a href=\"../addon/mode/multiplex.js\"><code>mode/multiplex.js</code></a></dt>\n      <dd>Mode combinator that can be used to easily 'multiplex'\n      between several modes.\n      Defines <code>CodeMirror.multiplexingMode</code> which, when\n      given as first argument a mode object, and as other arguments\n      any number of <code>{open, close, mode [, delimStyle, innerStyle, parseDelimiters]}</code>\n      objects, will return a mode object that starts parsing using the\n      mode passed as first argument, but will switch to another mode\n      as soon as it encounters a string that occurs in one of\n      the <code>open</code> fields of the passed objects. When in a\n      sub-mode, it will go back to the top mode again when\n      the <code>close</code> string is encountered.\n      Pass <code>\"\\n\"</code> for <code>open</code> or <code>close</code>\n      if you want to switch on a blank line.\n      <ul><li>When <code>delimStyle</code> is specified, it will be the token\n      style returned for the delimiter tokens (as well as\n      <code>[delimStyle]-open</code> on the opening token and\n      <code>[delimStyle]-close</code> on the closing token).</li>\n      <li>When <code>innerStyle</code> is specified, it will be the token\n      style added for each inner mode token.</li>\n      <li>When <code>parseDelimiters</code> is true, the content of\n      the delimiters will also be passed to the inner mode.\n      (And <code>delimStyle</code> is ignored.)</li></ul> The outer\n      mode will not see the content between the delimiters.\n      See <a href=\"../demo/multiplex.html\">this demo</a> for an\n      example.</dd>\n\n      <dt id=\"addon_show-hint\"><a href=\"../addon/hint/show-hint.js\"><code>hint/show-hint.js</code></a></dt>\n      <dd>Provides a framework for showing autocompletion hints.\n      Defines <code>editor.showHint</code>, which takes an optional\n      options object, and pops up a widget that allows the user to\n      select a completion. Finding hints is done with a hinting\n      functions (the <code>hint</code> option), which is a function\n      that take an editor instance and options object, and return\n      a <code>{list, from, to}</code> object, where <code>list</code>\n      is an array of strings or objects (the completions),\n      and <code>from</code> and <code>to</code> give the start and end\n      of the token that is being completed as <code>{line, ch}</code>\n      objects. An optional <code>selectedHint</code> property (an\n      integer) can be added to the completion object to control the\n      initially selected hint.</dd>\n      <dd>If no hinting function is given, the addon will\n      use <code>CodeMirror.hint.auto</code>, which\n      calls <a href=\"#getHelpers\"><code>getHelpers</code></a> with\n      the <code>\"hint\"</code> type to find applicable hinting\n      functions, and tries them one by one. If that fails, it looks\n      for a <code>\"hintWords\"</code> helper to fetch a list of\n      completable words for the mode, and\n      uses <code>CodeMirror.hint.fromList</code> to complete from\n      those.</dd>\n      <dd>When completions aren't simple strings, they should be\n      objects with the following properties:\n      <dl>\n        <dt><code><strong>text</strong>: string</code></dt>\n        <dd>The completion text. This is the only required\n        property.</dd>\n        <dt><code><strong>displayText</strong>: string</code></dt>\n        <dd>The text that should be displayed in the menu.</dd>\n        <dt><code><strong>className</strong>: string</code></dt>\n        <dd>A CSS class name to apply to the completion's line in the\n        menu.</dd>\n        <dt><code><strong>render</strong>: fn(Element, self, data)</code></dt>\n        <dd>A method used to create the DOM structure for showing the\n        completion by appending it to its first argument.</dd>\n        <dt><code><strong>hint</strong>: fn(CodeMirror, self, data)</code></dt>\n        <dd>A method used to actually apply the completion, instead of\n        the default behavior.</dd>\n        <dt><code><strong>from</strong>: {line, ch}</code></dt>\n        <dd>Optional <code>from</code> position that will be used by <code>pick()</code> instead\n        of the global one passed with the full list of completions.</dd>\n        <dt><code><strong>to</strong>: {line, ch}</code></dt>\n        <dd>Optional <code>to</code> position that will be used by <code>pick()</code> instead\n        of the global one passed with the full list of completions.</dd>\n      </dl></dd>\n\n      <dd>The plugin understands the following options, which may be\n      either passed directly in the argument to <code>showHint</code>,\n      or provided by setting an <code>hintOptions</code> editor\n      option to an object (the former takes precedence). The options\n      object will also be passed along to the hinting function, which\n      may understand additional options.\n      <dl>\n        <dt><code><strong>hint</strong>: function</code></dt>\n        <dd>A hinting function, as specified above. It is possible to\n        set the <code>async</code> property on a hinting function to\n        true, in which case it will be called with\n        arguments <code>(cm, callback, ?options)</code>, and the\n        completion interface will only be popped up when the hinting\n        function calls the callback, passing it the object holding the\n        completions.\n        The hinting function can also return a promise, and the completion\n        interface will only be popped when the promise resolves.\n        By default, hinting only works when there is no\n        selection. You can give a hinting function\n        a <code>supportsSelection</code> property with a truthy value\n        to indicate that it supports selections.</dd>\n        <dt><code><strong>completeSingle</strong>: boolean</code></dt>\n        <dd>Determines whether, when only a single completion is\n        available, it is completed without showing the dialog.\n        Defaults to true.</dd>\n        <dt><code><strong>alignWithWord</strong>: boolean</code></dt>\n        <dd>Whether the pop-up should be horizontally aligned with the\n        start of the word (true, default), or with the cursor (false).</dd>\n        <dt><code><strong>closeOnUnfocus</strong>: boolean</code></dt>\n        <dd>When enabled (which is the default), the pop-up will close\n        when the editor is unfocused.</dd>\n        <dt><code><strong>customKeys</strong>: keymap</code></dt>\n        <dd>Allows you to provide a custom key map of keys to be active\n        when the pop-up is active. The handlers will be called with an\n        extra argument, a handle to the completion menu, which\n        has <code>moveFocus(n)</code>, <code>setFocus(n)</code>, <code>pick()</code>,\n        and <code>close()</code> methods (see the source for details),\n        that can be used to change the focused element, pick the\n        current element or close the menu. Additionally <code>menuSize()</code>\n        can give you access to the size of the current dropdown menu,\n        <code>length</code> give you the number of available completions, and\n        <code>data</code> give you full access to the completion returned by the\n        hinting function.</dd>\n        <dt><code><strong>extraKeys</strong>: keymap</code></dt>\n        <dd>Like <code>customKeys</code> above, but the bindings will\n        be added to the set of default bindings, instead of replacing\n        them.</dd>\n      </dl>\n      The following events will be fired on the completions object\n      during completion:\n      <dl>\n        <dt><code><strong>\"shown\"</strong> ()</code></dt>\n        <dd>Fired when the pop-up is shown.</dd>\n        <dt><code><strong>\"select\"</strong> (completion, Element)</code></dt>\n        <dd>Fired when a completion is selected. Passed the completion\n        value (string or object) and the DOM node that represents it\n        in the menu.</dd>\n        <dt><code><strong>\"pick\"</strong> (completion)</code></dt>\n        <dd>Fired when a completion is picked. Passed the completion value\n        (string or object).</dd>\n        <dt><code><strong>\"close\"</strong> ()</code></dt>\n        <dd>Fired when the completion is finished.</dd>\n      </dl>\n      This addon depends on styles\n      from <code>addon/hint/show-hint.css</code>. Check\n      out <a href=\"../demo/complete.html\">the demo</a> for an\n      example.</dd>\n\n      <dt id=\"addon_javascript-hint\"><a href=\"../addon/hint/javascript-hint.js\"><code>hint/javascript-hint.js</code></a></dt>\n      <dd>Defines a simple hinting function for JavaScript\n      (<code>CodeMirror.hint.javascript</code>) and CoffeeScript\n      (<code>CodeMirror.hint.coffeescript</code>) code. This will\n      simply use the JavaScript environment that the editor runs in as\n      a source of information about objects and their properties.</dd>\n\n      <dt id=\"addon_xml-hint\"><a href=\"../addon/hint/xml-hint.js\"><code>hint/xml-hint.js</code></a></dt>\n      <dd>Defines <code>CodeMirror.hint.xml</code>, which produces\n      hints for XML tagnames, attribute names, and attribute values,\n      guided by a <code>schemaInfo</code> option (a property of the\n      second argument passed to the hinting function, or the third\n      argument passed to <code>CodeMirror.showHint</code>).<br>The\n      schema info should be an object mapping tag names to information\n      about these tags, with optionally a <code>\"!top\"</code> property\n      containing a list of the names of valid top-level tags. The\n      values of the properties should be objects with optional\n      properties <code>children</code> (an array of valid child\n      element names, omit to simply allow all tags to appear)\n      and <code>attrs</code> (an object mapping attribute names\n      to <code>null</code> for free-form attributes, and an array of\n      valid values for restricted\n      attributes). <a href=\"../demo/xmlcomplete.html\">Demo\n      here.</a></dd>\n\n      <dt id=\"addon_html-hint\"><a href=\"../addon/hint/html-hint.js\"><code>hint/html-hint.js</code></a></dt>\n      <dd>Provides schema info to\n      the <a href=\"#addon_xml-hint\">xml-hint</a> addon for HTML\n      documents. Defines a schema\n      object <code>CodeMirror.htmlSchema</code> that you can pass to\n      as a <code>schemaInfo</code> option, and\n      a <code>CodeMirror.hint.html</code> hinting function that\n      automatically calls <code>CodeMirror.hint.xml</code> with this\n      schema data. See\n      the <a href=\"../demo/html5complete.html\">demo</a>.</dd>\n\n      <dt id=\"addon_css-hint\"><a href=\"../addon/hint/css-hint.js\"><code>hint/css-hint.js</code></a></dt>\n      <dd>A hinting function for CSS, SCSS, or LESS code.\n      Defines <code>CodeMirror.hint.css</code>.</dd>\n\n      <dt id=\"addon_anyword-hint\"><a href=\"../addon/hint/anyword-hint.js\"><code>hint/anyword-hint.js</code></a></dt>\n      <dd>A very simple hinting function\n      (<code>CodeMirror.hint.anyword</code>) that simply looks for\n      words in the nearby code and completes to those. Takes two\n      optional options, <code>word</code>, a regular expression that\n      matches words (sequences of one or more character),\n      and <code>range</code>, which defines how many lines the addon\n      should scan when completing (defaults to 500).</dd>\n\n      <dt id=\"addon_sql-hint\"><a href=\"../addon/hint/sql-hint.js\"><code>hint/sql-hint.js</code></a></dt>\n      <dd>A simple SQL hinter. Defines <code>CodeMirror.hint.sql</code>.\n      Takes two optional options, <code>tables</code>, a object with\n      table names as keys and array of respective column names as values,\n      and <code>defaultTable</code>, a string corresponding to a\n      table name in <code>tables</code> for autocompletion.</dd>\n\n      <dt id=\"addon_match-highlighter\"><a href=\"../addon/search/match-highlighter.js\"><code>search/match-highlighter.js</code></a></dt>\n      <dd>Adds a <code>highlightSelectionMatches</code> option that\n      can be enabled to highlight all instances of a currently\n      selected word. Can be set either to true or to an object\n      containing the following options: <code>minChars</code>, for the\n      minimum amount of selected characters that triggers a highlight\n      (default 2), <code>style</code>, for the style to be used to\n      highlight the matches (default <code>\"matchhighlight\"</code>,\n      which will correspond to CSS\n      class <code>cm-matchhighlight</code>), <code>trim</code>, which\n      controls whether whitespace is trimmed from the selection,\n      and <code>showToken</code> which can be set to <code>true</code>\n      or to a regexp matching the characters that make up a word. When\n      enabled, it causes the current word to be highlighted when\n      nothing is selected (defaults to off).\n      Demo <a href=\"../demo/matchhighlighter.html\">here</a>.</dd>\n\n      <dt id=\"addon_lint\"><a href=\"../addon/lint/lint.js\"><code>lint/lint.js</code></a></dt>\n      <dd>Defines an interface component for showing linting warnings,\n      with pluggable warning sources\n      (see <a href=\"../addon/lint/html-lint.js\"><code>html-lint.js</code></a>,\n      <a href=\"../addon/lint/json-lint.js\"><code>json-lint.js</code></a>,\n      <a href=\"../addon/lint/javascript-lint.js\"><code>javascript-lint.js</code></a>,\n      <a href=\"../addon/lint/coffeescript-lint.js\"><code>coffeescript-lint.js</code></a>,\n      and <a href=\"../addon/lint/css-lint.js\"><code>css-lint.js</code></a>\n      in the same directory). Defines a <code>lint</code> option that\n      can be set to an annotation source (for\n      example <code>CodeMirror.lint.javascript</code>), to an options\n      object (in which case the <code>getAnnotations</code> field is\n      used as annotation source), or simply to <code>true</code>. When\n      no annotation source is\n      specified, <a href=\"#getHelper\"><code>getHelper</code></a> with\n      type <code>\"lint\"</code> is used to find an annotation function.\n      An annotation source function should, when given a document\n      string, an options object, and an editor instance, return an\n      array of <code>{message, severity, from, to}</code> objects\n      representing problems. When the function has\n      an <code>async</code> property with a truthy value, it will be\n      called with an additional second argument, which is a callback\n      to pass the array to.\n      The linting function can also return a promise, in that case the linter\n      will only be executed when the promise resolves.\n      By default, the linter will run (debounced) whenever the document is changed.\n      You can pass a <code>lintOnChange: false</code> option to disable that.\n      Depends on <code>addon/lint/lint.css</code>. A demo can be\n      found <a href=\"../demo/lint.html\">here</a>.</dd>\n\n      <dt id=\"addon_mark-selection\"><a href=\"../addon/selection/mark-selection.js\"><code>selection/mark-selection.js</code></a></dt>\n      <dd>Causes the selected text to be marked with the CSS class\n      <code>CodeMirror-selectedtext</code> when the <code>styleSelectedText</code> option\n      is enabled. Useful to change the colour of the selection (in addition to the background),\n      like in <a href=\"../demo/markselection.html\">this demo</a>.</dd>\n\n      <dt id=\"addon_active-line\"><a href=\"../addon/selection/active-line.js\"><code>selection/active-line.js</code></a></dt>\n      <dd>Defines a <code>styleActiveLine</code> option that, when\n      enabled, gives the wrapper of the line that contains the cursor\n      the class <code>CodeMirror-activeline</code>, adds a background\n      with the class <code>CodeMirror-activeline-background</code>,\n      and adds the class <code>CodeMirror-activeline-gutter</code> to\n      the line's gutter space is enabled. The option's value may be a\n      boolean or an object specifying the following options:\n        <dl>\n          <dt><code><strong>nonEmpty</strong>: bool</code></dt>\n          <dd>Controls whether single-line selections, or just cursor\n          selections, are styled. Defaults to false (only cursor\n          selections).</dd>\n        </dl>\n      See the <a href=\"../demo/activeline.html\">demo</a>.</dd>\n\n      <dt id=\"addon_selection-pointer\"><a href=\"../addon/selection/selection-pointer.js\"><code>selection/selection-pointer.js</code></a></dt>\n      <dd>Defines a <code>selectionPointer</code> option which you can\n      use to control the mouse cursor appearance when hovering over\n      the selection. It can be set to a string,\n      like <code>\"pointer\"</code>, or to true, in which case\n      the <code>\"default\"</code> (arrow) cursor will be used. You can\n      see a demo <a href=\"../mode/htmlmixed/index.html\">here</a>.</dd>\n\n      <dt id=\"addon_loadmode\"><a href=\"../addon/mode/loadmode.js\"><code>mode/loadmode.js</code></a></dt>\n      <dd>Defines a <code>CodeMirror.requireMode(modename,\n      callback)</code> function that will try to load a given mode and\n      call the callback when it succeeded. You'll have to\n      set <code>CodeMirror.modeURL</code> to a string that mode paths\n      can be constructed from, for\n      example <code>\"mode/%N/%N.js\"</code>—the <code>%N</code>'s will\n      be replaced with the mode name. Also\n      defines <code>CodeMirror.autoLoadMode(instance, mode)</code>,\n      which will ensure the given mode is loaded and cause the given\n      editor instance to refresh its mode when the loading\n      succeeded. See the <a href=\"../demo/loadmode.html\">demo</a>.</dd>\n\n      <dt id=\"addon_meta\"><a href=\"../mode/meta.js\"><code>mode/meta.js</code></a></dt>\n      <dd>Provides meta-information about all the modes in the\n      distribution in a single file.\n      Defines <code>CodeMirror.modeInfo</code>, an array of objects\n      with <code>{name, mime, mode}</code> properties,\n      where <code>name</code> is the human-readable\n      name, <code>mime</code> the MIME type, and <code>mode</code> the\n      name of the mode file that defines this MIME. There are optional\n      properties <code>mimes</code>, which holds an array of MIME\n      types for modes with multiple MIMEs associated,\n      and <code>ext</code>, which holds an array of file extensions\n      associated with this mode. Four convenience\n      functions, <code>CodeMirror.findModeByMIME</code>,\n      <code>CodeMirror.findModeByExtension</code>,\n      <code>CodeMirror.findModeByFileName</code>\n      and <code>CodeMirror.findModeByName</code> are provided, which\n      return such an object given a MIME, extension, file name or mode name\n      string. Note that, for historical reasons, this file resides in the\n      top-level <code>mode</code> directory, not\n      under <code>addon</code>. <a href=\"../demo/loadmode.html\">Demo</a>.</dd>\n\n      <dt id=\"addon_continuecomment\"><a href=\"../addon/comment/continuecomment.js\"><code>comment/continuecomment.js</code></a></dt>\n      <dd>Adds a <code>continueComments</code> option, which sets whether the\n      editor will make the next line continue a comment when you press Enter\n      inside a comment block. Can be set to a boolean to enable/disable this\n      functionality. Set to a string, it will continue comments using a custom\n      shortcut. Set to an object, it will use the <code>key</code> property for\n      a custom shortcut and the boolean <code>continueLineComment</code>\n      property to determine whether single-line comments should be continued\n      (defaulting to <code>true</code>).</dd>\n\n      <dt id=\"addon_placeholder\"><a href=\"../addon/display/placeholder.js\"><code>display/placeholder.js</code></a></dt>\n      <dd>Adds a <code>placeholder</code> option that can be used to\n      make content appear in the editor when it is empty and not\n      focused. It can hold either a string or a DOM node. Also gives\n      the editor a <code>CodeMirror-empty</code> CSS class whenever it\n      doesn't contain any text.\n      See <a href=\"../demo/placeholder.html\">the demo</a>.</dd>\n\n      <dt id=\"addon_fullscreen\"><a href=\"../addon/display/fullscreen.js\"><code>display/fullscreen.js</code></a></dt>\n      <dd>Defines an option <code>fullScreen</code> that, when set\n      to <code>true</code>, will make the editor full-screen (as in,\n      taking up the whole browser window). Depends\n      on <a href=\"../addon/display/fullscreen.css\"><code>fullscreen.css</code></a>. <a href=\"../demo/fullscreen.html\">Demo\n      here</a>.</dd>\n\n      <dt id=\"addon_autorefresh\"><a href=\"../addon/display/autorefresh.js\"><code>display/autorefresh.js</code></a></dt>\n      <dd>This addon can be useful when initializing an editor in a\n      hidden DOM node, in cases where it is difficult to\n      call <a href=\"#refresh\"><code>refresh</code></a> when the editor\n      becomes visible. It defines an option <code>autoRefresh</code>\n      which you can set to true to ensure that, if the editor wasn't\n      visible on initialization, it will be refreshed the first time\n      it becomes visible. This is done by polling every 250\n      milliseconds (you can pass a value like <code>{delay:\n      500}</code> as the option value to configure this). Note that\n      this addon will only refresh the editor <em>once</em> when it\n      first becomes visible, and won't take care of further restyling\n      and resizing.</dd>\n\n      <dt id=\"addon_simplescrollbars\"><a href=\"../addon/scroll/simplescrollbars.js\"><code>scroll/simplescrollbars.js</code></a></dt>\n      <dd>Defines two additional scrollbar\n      models, <code>\"simple\"</code> and <code>\"overlay\"</code>\n      (see <a href=\"../demo/simplescrollbars.html\">demo</a>) that can\n      be selected with\n      the <a href=\"#option_scrollbarStyle\"><code>scrollbarStyle</code></a>\n      option. Depends\n      on <a href=\"../addon/scroll/simplescrollbars.css\"><code>simplescrollbars.css</code></a>,\n      which can be further overridden to style your own\n      scrollbars.</dd>\n\n      <dt id=\"addon_annotatescrollbar\"><a href=\"../addon/scroll/annotatescrollbar.js\"><code>scroll/annotatescrollbar.js</code></a></dt>\n      <dd>Provides functionality for showing markers on the scrollbar\n      to call out certain parts of the document. Adds a\n      method <code>annotateScrollbar</code> to editor instances that\n      can be called, with a CSS class name as argument, to create a\n      set of annotations. The method returns an object\n      whose <code>update</code> method can be called with a sorted array\n      of <code>{from: Pos, to: Pos}</code> objects marking the ranges\n      to be highlighted. To detach the annotations, call the\n      object's <code>clear</code> method.</dd>\n\n      <dt id=\"addon_rulers\"><a href=\"../addon/display/rulers.js\"><code>display/rulers.js</code></a></dt>\n      <dd>Adds a <code>rulers</code> option, which can be used to show\n      one or more vertical rulers in the editor. The option, if\n      defined, should be given an array of <code>{column [, className,\n      color, lineStyle, width]}</code> objects or numbers (which\n      indicate a column). The ruler will be displayed at the column\n      indicated by the number or the <code>column</code> property.\n      The <code>className</code> property can be used to assign a\n      custom style to a ruler. <a href=\"../demo/rulers.html\">Demo\n      here</a>.</dd>\n\n      <dt id=\"addon_panel\"><a href=\"../addon/display/panel.js\"><code>display/panel.js</code></a></dt>\n      <dd>Defines an <code>addPanel</code> method for CodeMirror\n      instances, which places a DOM node above or below an editor, and\n      shrinks the editor to make room for the node. The method takes\n      as first argument as DOM node, and as second an optional options\n      object. The <code>Panel</code> object returned by this method\n      has a <code>clear</code> method that is used to remove the\n      panel, and a <code>changed</code> method that can be used to\n      notify the addon when the size of the panel's DOM node has\n      changed.<br/>\n      The method accepts the following options:\n      <dl>\n        <dt><code><strong>position</strong>: string</code></dt>\n        <dd>Controls the position of the newly added panel. The\n        following values are recognized:\n          <dl>\n            <dt><code><strong>top</strong> (default)</code></dt>\n            <dd>Adds the panel at the very top.</dd>\n            <dt><code><strong>after-top</strong></code></dt>\n            <dd>Adds the panel at the bottom of the top panels.</dd>\n            <dt><code><strong>bottom</strong></code></dt>\n            <dd>Adds the panel at the very bottom.</dd>\n            <dt><code><strong>before-bottom</strong></code></dt>\n            <dd>Adds the panel at the top of the bottom panels.</dd>\n          </dl>\n        </dd>\n        <dt><code><strong>before</strong>: Panel</code></dt>\n        <dd>The new panel will be added before the given panel.</dd>\n        <dt><code><strong>after</strong>: Panel</code></dt>\n        <dd>The new panel will be added after the given panel.</dd>\n        <dt><code><strong>replace</strong>: Panel</code></dt>\n        <dd>The new panel will replace the given panel.</dd>\n        <dt><code><strong>stable</strong>: bool</code></dt>\n        <dd>Whether to scroll the editor to keep the text's vertical\n        position stable, when adding a panel above it. Defaults to false.</dd>\n      </dl>\n      When using the <code>after</code>, <code>before</code> or <code>replace</code> options,\n      if the panel doesn't exists or has been removed,\n      the value of the <code>position</code> option will be used as a fallback.\n      <br>\n      A demo of the addon is available <a href=\"../demo/panel.html\">here</a>.\n      </dd>\n\n      <dt id=\"addon_hardwrap\"><a href=\"../addon/wrap/hardwrap.js\"><code>wrap/hardwrap.js</code></a></dt>\n      <dd>Addon to perform hard line wrapping/breaking for paragraphs\n      of text. Adds these methods to editor instances:\n        <dl>\n          <dt><code><strong>wrapParagraph</strong>(?pos: {line, ch}, ?options: object)</code></dt>\n          <dd>Wraps the paragraph at the given position.\n          If <code>pos</code> is not given, it defaults to the cursor\n          position.</dd>\n          <dt><code><strong>wrapRange</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>\n          <dd>Wraps the given range as one big paragraph.</dd>\n          <dt><code><strong>wrapParagraphsInRange</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>\n          <dd>Wraps the paragraphs in (and overlapping with) the\n          given range individually.</dd>\n        </dl>\n        The following options are recognized:\n        <dl>\n          <dt><code><strong>paragraphStart</strong>, <strong>paragraphEnd</strong>: RegExp</code></dt>\n          <dd>Blank lines are always considered paragraph boundaries.\n          These options can be used to specify a pattern that causes\n          lines to be considered the start or end of a paragraph.</dd>\n          <dt><code><strong>column</strong>: number</code></dt>\n          <dd>The column to wrap at. Defaults to 80.</dd>\n          <dt><code><strong>wrapOn</strong>: RegExp</code></dt>\n          <dd>A regular expression that matches only those\n          two-character strings that allow wrapping. By default, the\n          addon wraps on whitespace and after dash characters.</dd>\n          <dt><code><strong>killTrailingSpace</strong>: boolean</code></dt>\n          <dd>Whether trailing space caused by wrapping should be\n          preserved, or deleted. Defaults to true.</dd>\n        </dl>\n        A demo of the addon is available <a href=\"../demo/hardwrap.html\">here</a>.\n      </dd>\n\n      <dt id=\"addon_merge\"><a href=\"../addon/merge/merge.js\"><code>merge/merge.js</code></a></dt>\n      <dd>Implements an interface for merging changes, using either a\n      2-way or a 3-way view. The <code>CodeMirror.MergeView</code>\n      constructor takes arguments similar to\n      the <a href=\"#CodeMirror\"><code>CodeMirror</code></a>\n      constructor, first a node to append the interface to, and then\n      an options object. Options are passed through to the editors\n      inside the view. These extra options are recognized:\n        <dl>\n          <dt><code><strong>origLeft</strong></code> and <code><strong>origRight</strong>: string</code></dt>\n          <dd>If given these provide original versions of the\n          document, which will be shown to the left and right of the\n          editor in non-editable CodeMirror instances. The merge\n          interface will highlight changes between the editable\n          document and the original(s). To create a 2-way (as opposed\n          to 3-way) merge view, provide only one of them.</dd>\n          <dt><code><strong>revertButtons</strong>: boolean</code></dt>\n          <dd>Determines whether buttons that allow the user to revert\n          changes are shown. Defaults to true.</dd>\n          <dt><code><strong>revertChunk</strong>: fn(mv: MergeView, from: CodeMirror, fromStart: Pos, fromEnd: Pos, to: CodeMirror, toStart: Pos, toEnd: Pos)</code></dt>\n          <dd>Can be used to define custom behavior when the user\n          reverts a changed chunk.</dd>\n          <dt><code><strong>connect</strong>: string</code></dt>\n          <dd>Sets the style used to connect changed chunks of code.\n          By default, connectors are drawn. When this is set\n          to <code>\"align\"</code>, the smaller chunk is padded to\n          align with the bigger chunk instead.</dd>\n          <dt><code><strong>collapseIdentical</strong>: boolean|number</code></dt>\n          <dd>When true (default is false), stretches of unchanged\n          text will be collapsed. When a number is given, this\n          indicates the amount of lines to leave visible around such\n          stretches (which defaults to 2).</dd>\n          <dt><code><strong>allowEditingOriginals</strong>: boolean</code></dt>\n          <dd>Determines whether the original editor allows editing.\n          Defaults to false.</dd>\n          <dt><code><strong>showDifferences</strong>: boolean</code></dt>\n          <dd>When true (the default), changed pieces of text are\n          highlighted.</dd>\n          <dt><code><strong>chunkClassLocation</strong>: string|Array</code></dt>\n          <dd>By default the chunk highlights are added\n          using <a href=\"#addLineClass\"><code>addLineClass</code></a>\n          with \"background\". Override this to customize it to be any\n          valid `where` parameter or an Array of valid `where`\n          parameters.</dd>\n        </dl>\n        The addon also defines commands <code>\"goNextDiff\"</code>\n        and <code>\"goPrevDiff\"</code> to quickly jump to the next\n        changed chunk. <a href=\"../demo/merge.html\">Demo\n        here</a>.</dd>\n\n      <dt id=\"addon_tern\"><a href=\"../addon/tern/tern.js\"><code>tern/tern.js</code></a></dt>\n      <dd>Provides integration with\n      the <a href=\"http://ternjs.net\">Tern</a> JavaScript analysis\n      engine, for completion, definition finding, and minor\n      refactoring help. See the <a href=\"../demo/tern.html\">demo</a>\n      for a very simple integration. For more involved scenarios, see\n      the comments at the top of\n      the <a href=\"../addon/tern/tern.js\">addon</a> and the\n      implementation of the\n      (multi-file) <a href=\"http://ternjs.net/doc/demo.html\">demonstration\n      on the Tern website</a>.</dd>\n    </dl>\n</section>\n\n<section id=modeapi>\n    <h2>Writing CodeMirror Modes</h2>\n\n    <p>Modes typically consist of a single JavaScript file. This file\n    defines, in the simplest case, a lexer (tokenizer) for your\n    language—a function that takes a character stream as input,\n    advances it past a token, and returns a style for that token. More\n    advanced modes can also handle indentation for the language.</p>\n\n    <p>This section describes the low-level mode interface. Many modes\n    are written directly against this, since it offers a lot of\n    control, but for a quick mode definition, you might want to use\n    the <a href=\"../demo/simplemode.html\">simple mode addon</a>.</p>\n\n    <p id=\"defineMode\">The mode script should\n    call <code><strong>CodeMirror.defineMode</strong></code> to\n    register itself with CodeMirror. This function takes two\n    arguments. The first should be the name of the mode, for which you\n    should use a lowercase string, preferably one that is also the\n    name of the files that define the mode (i.e. <code>\"xml\"</code> is\n    defined in <code>xml.js</code>). The second argument should be a\n    function that, given a CodeMirror configuration object (the thing\n    passed to the <code>CodeMirror</code> function) and an optional\n    mode configuration object (as in\n    the <a href=\"#option_mode\"><code>mode</code></a> option), returns\n    a mode object.</p>\n\n    <p>Typically, you should use this second argument\n    to <code>defineMode</code> as your module scope function (modes\n    should not leak anything into the global scope!), i.e. write your\n    whole mode inside this function.</p>\n\n    <p>The main responsibility of a mode script is <em>parsing</em>\n    the content of the editor. Depending on the language and the\n    amount of functionality desired, this can be done in really easy\n    or extremely complicated ways. Some parsers can be stateless,\n    meaning that they look at one element (<em>token</em>) of the code\n    at a time, with no memory of what came before. Most, however, will\n    need to remember something. This is done by using a <em>state\n    object</em>, which is an object that is always passed when\n    reading a token, and which can be mutated by the tokenizer.</p>\n\n    <p id=\"startState\">Modes that use a state must define\n    a <code><strong>startState</strong></code> method on their mode\n    object. This is a function of no arguments that produces a state\n    object to be used at the start of a document.</p>\n\n    <p id=\"token\">The most important part of a mode object is\n    its <code><strong>token</strong>(stream, state)</code> method. All\n    modes must define this method. It should read one token from the\n    stream it is given as an argument, optionally update its state,\n    and return a style string, or <code>null</code> for tokens that do\n    not have to be styled. For your styles, you are encouraged to use\n    the 'standard' names defined in the themes (without\n    the <code>cm-</code> prefix). If that fails, it is also possible\n    to come up with your own and write your own CSS theme file.<p>\n\n    <p id=\"token_style_line\">A typical token string would\n    be <code>\"variable\"</code> or <code>\"comment\"</code>. Multiple\n    styles can be returned (separated by spaces), for\n    example <code>\"string error\"</code> for a thing that looks like a\n    string but is invalid somehow (say, missing its closing quote).\n    When a style is prefixed by <code>\"line-\"</code>\n    or <code>\"line-background-\"</code>, the style will be applied to\n    the whole line, analogous to what\n    the <a href=\"#addLineClass\"><code>addLineClass</code></a> method\n    does—styling the <code>\"text\"</code> in the simple case, and\n    the <code>\"background\"</code> element\n    when <code>\"line-background-\"</code> is prefixed.</p>\n\n    <p id=\"StringStream\">The stream object that's passed\n    to <code>token</code> encapsulates a line of code (tokens may\n    never span lines) and our current position in that line. It has\n    the following API:</p>\n\n    <dl>\n      <dt><code><strong>eol</strong>() → boolean</code></dt>\n      <dd>Returns true only if the stream is at the end of the\n      line.</dd>\n      <dt><code><strong>sol</strong>() → boolean</code></dt>\n      <dd>Returns true only if the stream is at the start of the\n      line.</dd>\n\n      <dt><code><strong>peek</strong>() → string</code></dt>\n      <dd>Returns the next character in the stream without advancing\n      it. Will return a <code>null</code> at the end of the\n      line.</dd>\n      <dt><code><strong>next</strong>() → string</code></dt>\n      <dd>Returns the next character in the stream and advances it.\n      Also returns <code>null</code> when no more characters are\n      available.</dd>\n\n      <dt><code><strong>eat</strong>(match: string|regexp|function(char: string) → boolean) → string</code></dt>\n      <dd><code>match</code> can be a character, a regular expression,\n      or a function that takes a character and returns a boolean. If\n      the next character in the stream 'matches' the given argument,\n      it is consumed and returned. Otherwise, <code>undefined</code>\n      is returned.</dd>\n      <dt><code><strong>eatWhile</strong>(match: string|regexp|function(char: string) → boolean) → boolean</code></dt>\n      <dd>Repeatedly calls <code>eat</code> with the given argument,\n      until it fails. Returns true if any characters were eaten.</dd>\n      <dt><code><strong>eatSpace</strong>() → boolean</code></dt>\n      <dd>Shortcut for <code>eatWhile</code> when matching\n      white-space.</dd>\n      <dt><code><strong>skipToEnd</strong>()</code></dt>\n      <dd>Moves the position to the end of the line.</dd>\n      <dt><code><strong>skipTo</strong>(str: string) → boolean</code></dt>\n      <dd>Skips to the start of the next occurrence of the given string, if\n      found on the current line (doesn't advance the stream if the\n      string does not occur on the line). Returns true if the\n      string was found.</dd>\n      <dt><code><strong>match</strong>(pattern: string, ?consume: boolean, ?caseFold: boolean) → boolean</code></dt>\n      <dt><code><strong>match</strong>(pattern: regexp, ?consume: boolean) → array&lt;string&gt;</code></dt>\n      <dd>Act like a\n      multi-character <code>eat</code>—if <code>consume</code> is true\n      or not given—or a look-ahead that doesn't update the stream\n      position—if it is false. <code>pattern</code> can be either a\n      string or a regular expression starting with <code>^</code>.\n      When it is a string, <code>caseFold</code> can be set to true to\n      make the match case-insensitive. When successfully matching a\n      regular expression, the returned value will be the array\n      returned by <code>match</code>, in case you need to extract\n      matched groups.</dd>\n\n      <dt><code><strong>backUp</strong>(n: integer)</code></dt>\n      <dd>Backs up the stream <code>n</code> characters. Backing it up\n      further than the start of the current token will cause things to\n      break, so be careful.</dd>\n      <dt><code><strong>column</strong>() → integer</code></dt>\n      <dd>Returns the column (taking into account tabs) at which the\n      current token starts.</dd>\n      <dt><code><strong>indentation</strong>() → integer</code></dt>\n      <dd>Tells you how far the current line has been indented, in\n      spaces. Corrects for tab characters.</dd>\n\n      <dt><code><strong>current</strong>() → string</code></dt>\n      <dd>Get the string between the start of the current token and\n      the current stream position.</dd>\n\n      <dt><code><strong>lookAhead</strong>(n: number) → ?string</code></dt>\n      <dd>Get the line <code>n</code> (&gt;0) lines after the current\n      one, in order to scan ahead across line boundaries. Note that\n      you want to do this carefully, since looking far ahead will make\n      mode state caching much less effective.</dd>\n\n      <dt id=\"baseToken\"><code><strong>baseToken</strong>() → ?{type: ?string, size: number}</code></dt>\n      <dd>Modes added\n      through <a href=\"#addOverlay\"><code>addOverlay</code></a>\n      (and <em>only</em> such modes) can use this method to inspect\n      the current token produced by the underlying mode.</dd>\n    </dl>\n\n    <p id=\"blankLine\">By default, blank lines are simply skipped when\n    tokenizing a document. For languages that have significant blank\n    lines, you can define\n    a <code><strong>blankLine</strong>(state)</code> method on your\n    mode that will get called whenever a blank line is passed over, so\n    that it can update the parser state.</p>\n\n    <p id=\"copyState\">Because state object are mutated, and CodeMirror\n    needs to keep valid versions of a state around so that it can\n    restart a parse at any line, copies must be made of state objects.\n    The default algorithm used is that a new state object is created,\n    which gets all the properties of the old object. Any properties\n    which hold arrays get a copy of these arrays (since arrays tend to\n    be used as mutable stacks). When this is not correct, for example\n    because a mode mutates non-array properties of its state object, a\n    mode object should define\n    a <code><strong>copyState</strong></code> method, which is given a\n    state and should return a safe copy of that state.</p>\n\n    <p id=\"indent\">If you want your mode to provide smart indentation\n    (through the <a href=\"#indentLine\"><code>indentLine</code></a>\n    method and the <code>indentAuto</code>\n    and <code>newlineAndIndent</code> commands, to which keys can be\n    <a href=\"#option_extraKeys\">bound</a>), you must define\n    an <code><strong>indent</strong>(state, textAfter)</code> method\n    on your mode object.</p>\n\n    <p>The indentation method should inspect the given state object,\n    and optionally the <code>textAfter</code> string, which contains\n    the text on the line that is being indented, and return an\n    integer, the amount of spaces to indent. It should usually take\n    the <a href=\"#option_indentUnit\"><code>indentUnit</code></a>\n    option into account. An indentation method may\n    return <code>CodeMirror.Pass</code> to indicate that it\n    could not come up with a precise indentation.</p>\n\n    <p id=\"mode_comment\">To work well with\n    the <a href=\"#addon_comment\">commenting addon</a>, a mode may\n    define <code><strong>lineComment</strong></code> (string that\n    starts a line\n    comment), <code><strong>blockCommentStart</strong></code>, <code><strong>blockCommentEnd</strong></code>\n    (strings that start and end block comments),\n    and <code>blockCommentLead</code> (a string to put at the start of\n    continued lines in a block comment). All of these are\n    optional.</p>\n\n    <p id=\"electricChars\">Finally, a mode may define either\n    an <code>electricChars</code> or an <code>electricInput</code>\n    property, which are used to automatically reindent the line when\n    certain patterns are typed and\n    the <a href=\"#option_electricChars\"><code>electricChars</code></a>\n    option is enabled. <code>electricChars</code> may be a string, and\n    will trigger a reindent whenever one of the characters in that\n    string are typed. Often, it is more appropriate to\n    use <code>electricInput</code>, which should hold a regular\n    expression, and will trigger indentation when the part of the\n    line <em>before</em> the cursor matches the expression. It should\n    usually end with a <code>$</code> character, so that it only\n    matches when the indentation-changing pattern was just typed, not when something was\n    typed after the pattern.</p>\n\n    <p>So, to summarize, a mode <em>must</em> provide\n    a <code>token</code> method, and it <em>may</em>\n    provide <code>startState</code>, <code>copyState</code>,\n    and <code>indent</code> methods. For an example of a trivial mode,\n    see the <a href=\"../mode/diff/diff.js\">diff mode</a>, for a more\n    involved example, see the <a href=\"../mode/clike/clike.js\">C-like\n    mode</a>.</p>\n\n    <p>Sometimes, it is useful for modes to <em>nest</em>—to have one\n    mode delegate work to another mode. An example of this kind of\n    mode is the <a href=\"../mode/htmlmixed/htmlmixed.js\">mixed-mode HTML\n    mode</a>. To implement such nesting, it is usually necessary to\n    create mode objects and copy states yourself. To create a mode\n    object, there are <code>CodeMirror.getMode(options,\n    parserConfig)</code>, where the first argument is a configuration\n    object as passed to the mode constructor function, and the second\n    argument is a mode specification as in\n    the <a href=\"#option_mode\"><code>mode</code></a> option. To copy a\n    state object, call <code>CodeMirror.copyState(mode, state)</code>,\n    where <code>mode</code> is the mode that created the given\n    state.</p>\n\n    <p id=\"innerMode\">In a nested mode, it is recommended to add an\n    extra method, <code><strong>innerMode</strong></code> which, given\n    a state object, returns a <code>{state, mode}</code> object with\n    the inner mode and its state for the current position. These are\n    used by utility scripts such as the <a href=\"#addon_closetag\">tag\n    closer</a> to get context information. Use\n    the <code>CodeMirror.innerMode</code> helper function to, starting\n    from a mode and a state, recursively walk down to the innermost\n    mode and state.</p>\n\n    <p>To make indentation work properly in a nested parser, it is\n    advisable to give the <code>startState</code> method of modes that\n    are intended to be nested an optional argument that provides the\n    base indentation for the block of code. The JavaScript and CSS\n    parser do this, for example, to allow JavaScript and CSS code\n    inside the mixed-mode HTML mode to be properly indented.</p>\n\n    <p id=\"defineMIME\">It is possible, and encouraged, to associate\n    your mode, or a certain configuration of your mode, with\n    a <a href=\"http://en.wikipedia.org/wiki/MIME\">MIME</a> type. For\n    example, the JavaScript mode associates itself\n    with <code>text/javascript</code>, and its JSON variant\n    with <code>application/json</code>. To do this,\n    call <code><strong>CodeMirror.defineMIME</strong>(mime,\n    modeSpec)</code>, where <code>modeSpec</code> can be a string or\n    object specifying a mode, as in\n    the <a href=\"#option_mode\"><code>mode</code></a> option.</p>\n\n    <p>If a mode specification wants to add some properties to the\n    resulting mode object, typically for use\n    with <a href=\"#getHelpers\"><code>getHelpers</code></a>, it may\n    contain a <code>modeProps</code> property, which holds an object.\n    This object's properties will be copied to the actual mode\n    object.</p>\n\n    <p id=\"extendMode\">Sometimes, it is useful to add or override mode\n    object properties from external code.\n    The <code><strong>CodeMirror.extendMode</strong></code> function\n    can be used to add properties to mode objects produced for a\n    specific mode. Its first argument is the name of the mode, its\n    second an object that specifies the properties that should be\n    added. This is mostly useful to add utilities that can later be\n    looked up through <a href=\"#getMode\"><code>getMode</code></a>.</p>\n</section>\n\n<section id=\"vimapi\">\n    <h2>VIM Mode API</h2>\n\n    <p>CodeMirror has a robust VIM mode that attempts to faithfully\n    emulate VIM's most useful features. It can be enabled by\n    including <a href=\"../keymap/vim.js\"><code>keymap/vim.js</code>\n    </a> and setting the <code>keyMap</code> option to\n    <code>\"vim\"</code>.</p>\n\n    <h3 id=\"vimapi_configuration\">Configuration</h3>\n\n    <p>VIM mode accepts configuration options for customizing\n    behavior at run time. These methods can be called at any time\n    and will affect all existing CodeMirror instances unless\n    specified otherwise. The methods are exposed on the\n    <code><strong>CodeMirror.Vim</strong></code> object.</p>\n\n    <dl>\n      <dt id=\"vimapi_setOption\"><code><strong>setOption(name: string, value: any, ?cm: CodeMirror, ?cfg: object)</strong></code></dt>\n      <dd>Sets the value of a VIM option. <code>name</code> should\n      be the name of an option. If <code>cfg.scope</code> is not set\n      and <code>cm</code> is provided, then sets the global and\n      instance values of the option. Otherwise, sets either the\n      global or instance value of the option depending on whether\n      <code>cfg.scope</code> is <code>global</code> or\n      <code>local</code>.</dd>\n      <dt id=\"vimapi_getOption\"><code><strong>getOption(name: string, ?cm: CodeMirror: ?cfg: object)</strong></code></dt>\n      <dd>Gets the current value of a VIM option. If\n      <code>cfg.scope</code> is not set and <code>cm</code> is\n      provided, then gets the instance value of the option, falling\n      back to the global value if not set. If <code>cfg.scope</code> is provided, then gets the <code>global</code> or\n      <code>local</code> value without checking the other.</dd>\n\n      <dt id=\"vimapi_map\"><code><strong>map(lhs: string, rhs: string, ?context: string)</strong></code></dt>\n      <dd>Maps a key sequence to another key sequence. Implements\n      VIM's <code>:map</code> command. To map ; to : in VIM would be\n      <code><strong>:map ; :</strong></code>. That would translate to\n      <code><strong>CodeMirror.Vim.map(';', ':');</strong></code>.\n      The <code>context</code> can be <code>normal</code>,\n      <code>visual</code>, or <code>insert</code>, which correspond\n      to <code>:nmap</code>, <code>:vmap</code>, and\n      <code>:imap</code>\n      respectively.</dd>\n\n      <dt id=\"vimapi_mapCommand\"><code><strong>mapCommand(keys: string, type: string, name: string, ?args: object, ?extra: object)</strong></code></dt>\n      <dd>Maps a key sequence to a <code>motion</code>,\n      <code>operator</code>, or <code>action</code> type command.\n      The args object is passed through to the command when it is\n      invoked by the provided key sequence.\n      <code>extras.context</code> can be <code>normal</code>,\n      <code>visual</code>, or <code>insert</code>, to map the key\n      sequence only in the corresponding mode.\n      <code>extras.isEdit</code> is applicable only to actions,\n      determining whether it is recorded for replay for the\n      <code>.</code> single-repeat command.\n    </dl>\n\n    <h3 id=\"vimapi_extending\">Extending VIM</h3>\n\n    <p>CodeMirror's VIM mode implements a large subset of VIM's core\n    editing functionality. But since there's always more to be\n    desired, there is a set of APIs for extending VIM's\n    functionality. As with the configuration API, the methods are\n    exposed on <code><strong>CodeMirror.Vim</strong></code> and may\n    be called at any time.</p>\n\n    <dl>\n      <dt id=\"vimapi_defineOption\"><code><strong>defineOption(name: string, default: any, type: string, ?aliases: array&lt;string&gt;, ?callback: function (?value: any, ?cm: CodeMirror) → ?any)</strong></code></dt>\n      <dd>Defines a VIM style option and makes it available to the\n      <code>:set</code> command. Type can be <code>boolean</code> or\n      <code>string</code>, used for validation and by\n      <code>:set</code> to determine which syntax to accept. If a\n      <code>callback</code> is passed in, VIM does not store the value of the\n      option itself, but instead uses the callback as a setter/getter. If the\n      first argument to the callback is <code>undefined</code>, then the\n      callback should return the value of the option. Otherwise, it should set\n      instead. Since VIM options have global and instance values, whether a\n      <code>CodeMirror</code> instance is passed in denotes whether the global\n      or local value should be used. Consequently, it's possible for the\n      callback to be called twice for a single <code>setOption</code> or\n      <code>getOption</code> call. Note that right now, VIM does not support\n      defining buffer-local options that do not have global values. If an\n      option should not have a global value, either always ignore the\n      <code>cm</code> parameter in the callback, or always pass in a\n      <code>cfg.scope</code> to <code>setOption</code> and\n      <code>getOption</code>.</dd>\n\n      <dt id=\"vimapi_defineMotion\"><code><strong>defineMotion(name: string, fn: function(cm: CodeMirror, head: {line, ch}, ?motionArgs: object}) → {line, ch})</strong></code></dt>\n      <dd>Defines a motion command for VIM. The motion should return\n      the desired result position of the cursor. <code>head</code>\n      is the current position of the cursor. It can differ from\n      <code>cm.getCursor('head')</code> if VIM is in visual mode.\n      <code>motionArgs</code> is the object passed into\n      <strong><code>mapCommand()</code></strong>.</dd>\n\n      <dt id=\"vimapi_defineOperator\"><strong><code>defineOperator(name: string, fn: function(cm: CodeMirror, ?operatorArgs: object, ranges: array&lt;{anchor, head}&gt;) → ?{line, ch})</code></strong></dt>\n      <dd>Defines an operator command, similar to <strong><code>\n      defineMotion</code></strong>. <code>ranges</code> is the range\n      of text the operator should operate on. If the cursor should\n      be set to a certain position after the operation finishes, it\n      can return a cursor object.</dd>\n\n      <dt id=\"vimapi_defineActon\"><strong><code>defineAction(name: string, fn: function(cm: CodeMirror, ?actionArgs: object))</code></strong></dt>\n      <dd>Defines an action command, similar to\n      <strong><code>defineMotion</code></strong>. Action commands\n      can have arbitrary behavior, making them more flexible than\n      motions and operators, at the loss of orthogonality.</dd>\n\n      <dt id=\"vimapi_defineEx\"><strong><code>defineEx(name: string, ?prefix: string, fn: function(cm: CodeMirror, ?params: object))</code></strong></dt>\n      <dd>Defines an Ex command, and maps it to <code>:name</code>.\n      If a prefix is provided, it, and any prefixed substring of the\n      <code>name</code> beginning with the <code>prefix</code> can\n      be used to invoke the command. If the <code>prefix</code> is\n      falsy, then <code>name</code> is used as the prefix. <code>\n      params.argString</code> contains the part of the prompted\n      string after the command name. <code>params.args</code> is\n      <code>params.argString</code> split by whitespace. If the\n      command was prefixed with a\n      <code><strong><a href=\"http://vimdoc.sourceforge.net/htmldoc/cmdline.html#cmdline-ranges\">line range</a></strong></code>,\n      <code>params.line</code> and <code>params.lineEnd</code> will\n      be set.\n    </dl>\n\n</section>\n\n</article>\n\n<script>setTimeout(function(){CodeMirror.colorize();}, 20);</script>\n"
  },
  {
    "path": "third_party/CodeMirror/doc/realworld.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Real-world Uses</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"docs.css\">\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Real-world uses</a>\n  </ul>\n</div>\n\n<article>\n\n<h2>CodeMirror real-world uses</h2>\n\n    <p>Create a <a href=\"https://github.com/codemirror/codemirror\">pull\n    request</a> if you'd like your project to be added to this list.</p>\n\n    <ul>\n      <li><a href=\"http://brackets.io\">Adobe Brackets</a> (code editor)</li>\n      <li><a href=\"http://alm.tools\">ALM Tools</a> (TypeScript powered IDE)</li>\n      <li><a href=\"http://amber-lang.net/\">Amber</a> (JavaScript-based Smalltalk system)</li>\n      <li><a href=\"http://apeye.org/\">APEye</a> (tool for testing &amp; documenting APIs)</li>\n      <li><a href=\"https://github.com/google/appengine-codiad\">Appengine Codiad</a></li>\n      <li><a href=\"https://chrome.google.com/webstore/detail/better-text-viewer/lcaidopdffhfemoefoaadecppnjdknkc\">Better Text Viewer</a> (plain text reader app for Chrome)</li>\n      <li><a href=\"http://blog.bitbucket.org/2013/05/14/edit-your-code-in-the-cloud-with-bitbucket/\">Bitbucket</a> (code hosting)</li>\n      <li><a href=\"https://blogger.googleblog.com/2013/04/improvements-to-blogger-template-html.html\">Blogger's theme editor</a></li>\n      <li><a href=\"http://bluegriffon.org/\">BlueGriffon</a> (HTML editor)</li>\n      <li><a href=\"https://bnfplayground.pauliankline.com/\">BNF Playground</a> (grammar workbench)</li>\n      <li><a href=\"https://github.com/isdampe/BosonEditorExperimental\">Boson Editor</a> (code editor)</li>\n      <li><a href=\"http://cargocollective.com/\">Cargo Collective</a> (creative publishing platform)</li>\n      <li><a href=\"https://developers.google.com/chrome-developer-tools/\">Chrome DevTools</a></li>\n      <li><a href=\"http://clickhelp.co/\">ClickHelp</a> (technical writing tool)</li>\n      <li><a href=\"http://code.world/\">CodeWorld</a> (Haskell playground)</li>\n      <li><a href=\"http://complete-ly.appspot.com/playground/code.playground.html\">Complete.ly playground</a></li>\n      <li><a href=\"https://codeanywhere.com/\">Codeanywhere</a> (multi-platform cloud editor)</li>\n      <li><a href=\"http://drupal.org/project/cpn\">Code per Node</a> (Drupal module)</li>\n      <li><a href=\"https://codebitt.com/\">CodeBitt</a> (Code snippet sharing)</li>\n      <li><a href=\"http://www.codebugapp.com/\">Codebug</a> (PHP Xdebug front-end)</li>\n      <li><a href=\"http://codefights.com/\">CodeFights</a> (practice programming)</li>\n      <li><a href=\"https://github.com/angelozerr/CodeMirror-Eclipse\">CodeMirror Eclipse</a> (embed CM in Eclipse)</li>\n      <li><a href=\"http://emmet.io/blog/codemirror-movie/\">CodeMirror movie</a> (scripted editing demos)</li>\n      <li><a href=\"http://code.google.com/p/codemirror2-gwt/\">CodeMirror2-GWT</a> (Google Web Toolkit wrapper)</li>\n      <li><a href=\"http://www.crunchzilla.com/code-monster\">Code Monster</a> & <a href=\"http://www.crunchzilla.com/code-maven\">Code Maven</a> (learning environment)</li>\n      <li><a href=\"http://codepen.io\">Codepen</a> (gallery of animations)</li>\n      <li><a href=\"https://coderpad.io/\">Coderpad</a> (interviewing tool)</li>\n      <li><a href=\"http://sasstwo.codeschool.com/levels/1/challenges/1\">Code School</a> (online tech learning environment)</li>\n      <li><a href=\"http://code-snippets.bungeshea.com/\">Code Snippets</a> (WordPress snippet management plugin)</li>\n      <li><a href=\"http://antonmi.github.io/code_together/\">Code together</a> (collaborative editing)</li>\n      <li><a href=\"http://codev.it/\">Codev</a> (collaborative IDE)</li>\n      <li><a href=\"https://www.codevolve.com/\">Codevolve</a> (programming lessons as-a-service)</li>\n      <li><a href=\"http://www.codezample.com\">CodeZample</a> (code snippet sharing)</li>\n      <li><a href=\"http://codio.com\">Codio</a> (Web IDE)</li>\n      <li><a href=\"https://www.codiva.io/\">Codiva.io</a> (Online Java Compiler and IDE with auto-completion and error highlighting)</li>\n      <li><a href=\"http://www.communitycodecamp.com/\">Community Code Camp</a> (code snippet sharing)</li>\n      <li><a href=\"http://www.compilejava.net/\">compilejava.net</a> (online Java sandbox)</li>\n      <li><a href=\"http://www.ckwnc.com/\">CKWNC</a> (UML editor)</li>\n      <li><a href=\"http://www.crossui.com/\">CrossUI</a> (cross-platform UI builder)</li>\n      <li><a href=\"http://rsnous.com/cruncher/\">Cruncher</a> (notepad with calculation features)</li>\n      <li><a href=\"http://www.crudzilla.com/\">Crudzilla</a> (self-hosted web IDE)</li>\n      <li><a href=\"http://cssdeck.com/\">CSSDeck</a> (CSS showcase)</li>\n      <li><a href=\"http://ireneros.com/deck/deck.js-codemirror/introduction/#textarea-code\">Deck.js integration</a> (slides with editors)</li>\n      <li><a href=\"http://www.dbninja.com\">DbNinja</a> (MySQL access interface)</li>\n      <li><a href=\"http://www.ecsspert.com/\">eCSSpert</a> (CSS demos and experiments)</li>\n      <li><a href=\"https://edabit.com\">Edabit</a> (coding challenges)</li>\n      <li><a href=\"http://elm-lang.org/Examples.elm\">Elm language examples</a></li>\n      <li><a href=\"http://eloquentjavascript.net/chapter1.html\">Eloquent JavaScript</a> (book)</li>\n      <li><a href=\"http://emmet.io\">Emmet</a> (fast XML editing)</li>\n      <li><a href=\"https://github.com/espruino/EspruinoWebIDE\">Espruino Web IDE</a> (Chrome App for writing code on Espruino devices)</li>\n      <li><a href=\"http://www.fastfig.com/\">Fastfig</a> (online computation/math tool)</li>\n      <li><a href=\"https://metacpan.org/module/Farabi\">Farabi</a> (modern Perl IDE)</li>\n      <li><a href=\"http://blog.pamelafox.org/2012/02/interactive-html5-slides-with-fathomjs.html\">FathomJS integration</a> (slides with editors, again)</li>\n      <li><a href=\"http://fiddlesalad.com/\">Fiddle Salad</a> (web development environment)</li>\n      <li><a href=\"https://github.com/simogeo/Filemanager\">Filemanager</a></li>\n      <li><a href=\"https://hacks.mozilla.org/2013/11/firefox-developer-tools-episode-27-edit-as-html-codemirror-more/\">Firefox Developer Tools</a></li>\n      <li><a href=\"http://www.firepad.io\">Firepad</a> (collaborative text editor)</li>\n      <li><a href=\"https://gerritcodereview.com/\">Gerrit</a>'s diff view and inline editor</li>\n      <li><a href=\"https://github.com/maks/git-crx\">Git Crx</a> (Chrome App for browsing local git repos)</li>\n      <li><a href=\"https://github.com/github/android\">GitHub's Android app</a></li>\n      <li><a href=\"https://github.com/\">Github</a>'s in-browser edit feature</li>\n      <li><a href=\"https://glitch.com/\">Glitch</a> (community-driven app building)</li>\n      <li><a href=\"http://tour.golang.org\">Go language tour</a></li>\n      <li><a href=\"https://script.google.com/\">Google Apps Script</a></li>\n      <li><a href=\"http://web.uvic.ca/~siefkenj/graphit/graphit.html\">Graphit</a> (function graphing)</li>\n      <li><a href=\"https://hackmd.io\">HackMD</a> (Realtime collaborative markdown notes on all platforms)</li>\n      <li><a href=\"http://www.handcraft.com/\">Handcraft</a> (HTML prototyping)</li>\n      <li><a href=\"http://hawkee.com/\">Hawkee</a></li>\n      <li><a href=\"http://try.haxe.org\">Haxe</a> (Haxe Playground) </li>\n      <li><a href=\"http://haxpad.com/\">HaxPad</a> (editor for Win RT)</li>\n      <li><a href=\"http://megafonweblab.github.com/histone-javascript/\">Histone template engine playground</a></li>\n      <li><a href=\"http://www.homegenie.it/docs/automation_getstarted.php\">Homegenie</a> (home automation server)</li>\n      <li><a href=\"http://icecoder.net\">ICEcoder</a> (web IDE)</li>\n      <li><a href=\"http://ipython.org/\">IPython</a> (interactive computing shell)</li>\n      <li><a href=\"https://joelpinheiro.github.io/itrading/\">iTrading</a> (Algorithmic Trading)</li>\n      <li><a href=\"http://i-mos.org/imos/\">i-MOS</a> (modeling and simulation platform)</li>\n      <li><a href=\"http://www.janvas.com/\">Janvas</a> (vector graphics editor)</li>\n      <li><a href=\"https://code.wetrafa.xyz/\">JdBEdit</a> (web IDE)</li>\n      <li><a href=\"http://extensions.joomla.org/extensions/edition/editors/8723\">Joomla plugin</a></li>\n      <li><a href=\"http://jqfundamentals.com/\">jQuery fundamentals</a> (interactive tutorial)</li>\n      <li><a href=\"http://jsbin.com\">jsbin.com</a> (JS playground)</li>\n      <li><a href=\"http://tool.jser.com/preprocessor\">JSER preprocessor</a></li>\n      <li><a href=\"https://github.com/kucherenko/jscpd\">jscpd</a> (code duplication detector)</li>\n      <li><a href=\"http://jsfiddle.net\">JSFiddle</a> (another JS playground)</li>\n      <li><a href=\"http://www.jshint.com/\">JSHint</a> (JS linter)</li>\n      <li><a href=\"http://jumpseller.com/\">Jumpseller</a> (online store builder)</li>\n      <li><a href=\"http://kl1p.com/cmtest/1\">kl1p</a> (paste service)</li>\n      <li><a href=\"http://www.kodhus.com/kodity/\">Kodit</a></li>\n      <li><a href=\"http://kodtest.com/\">Kodtest</a> (HTML/JS/CSS playground)</li>\n      <li><a href=\"http://try.kotlinlang.org\">Kotlin</a> (web-based mini-IDE for Kotlin)</li>\n      <li><a href=\"http://lighttable.com/\">Light Table</a> (experimental IDE)</li>\n      <li><a href=\"http://liveweave.com/\">Liveweave</a> (HTML/CSS/JS scratchpad)</li>\n      <li><a href=\"https://github.com/TuvaLabs/markdown-delight-editor\">Markdown Delight Editor</a> (extensible markdown editor polymer component)</li>\n      <li><a href=\"http://marklighteditor.com/\">Marklight editor</a> (lightweight markup editor)</li>\n      <li><a href=\"http://www.mergely.com/\">Mergely</a> (interactive diffing)</li>\n      <li><a href=\"http://www.iunbug.com/mihtool\">MIHTool</a> (iOS web-app debugging tool)</li>\n      <li><a href=\"http://mscgen.js.org/index.html\">mscgen_js</a> (online sequence chart editor)</li>\n      <li><a href=\"http://mvcplayground.apphb.com/\">MVC Playground</a></li>\n      <li><a href=\"http://www.navigatecms.com\">Navigate CMS</a></li>\n      <li><a href=\"https://github.com/soliton4/nodeMirror\">nodeMirror</a> (IDE project)</li>\n      <li><a href=\"https://notex.ch\">NoTex</a> (rST authoring)</li>\n      <li><a href=\"https://nteract.io\">nteract</a> (interactive literate coding notebook)</li>\n      <li><a href=\"http://oakoutliner.com\">Oak</a> (online outliner)</li>\n      <li><a href=\"http://www.greycampus.com/opencampus\">OpenCampus</a></li>\n      <li><a href=\"http://clrhome.org/asm/\">ORG</a> (z80 assembly IDE)</li>\n      <li><a href=\"https://github.com/mamacdon/orion-codemirror\">Orion-CodeMirror integration</a> (running CodeMirror modes in Orion)</li>\n      <li><a href=\"http://paperjs.org/\">Paper.js</a> (graphics scripting)</li>\n      <li><a href=\"http://pharaoh.js.org/\">Pharaoh</a> (browser &amp; desktop editor for the classroom)</li>\n      <li><a href=\"http://prinbit.com/\">PrinBit</a> (collaborative coding tool)</li>\n      <li><a href=\"https://www.pramp.com/ref/codemirror\">Pramp</a> (free platform to practice mock interviews and coding problems)</li>\n      <li><a href=\"http://prose.io/\">Prose.io</a> (github content editor)</li>\n      <li><a href=\"https://pypi.python.org/pypi/PubliForge/\">PubliForge</a> (online publishing system)</li>\n      <li><a href=\"http://www.puzzlescript.net/\">Puzzlescript</a> (puzzle game engine)</li>\n      <li><a href=\"https://chrome.google.com/webstore/detail/quantum/hmnlklahndgbhdoclhdnoafhafbhmnkm?hl=en-US\">Quantum</a> (code editor for Chrome OS)</li>\n      <li><a href=\"http://ariya.ofilabs.com/2011/09/hybrid-webnative-desktop-codemirror.html\">Qt+Webkit integration</a> (building a desktop CodeMirror app)</li>\n      <li><a href=\"http://www.quivive-file-manager.com\">Quivive File Manager</a></li>\n      <li><a href=\"http://rascalmicro.com/docs/basic-tutorial-getting-started.html\">Rascal</a> (tiny computer)</li>\n      <li><a href=\"https://www.realtime.io/\">RealTime.io</a> (Internet-of-Things infrastructure)</li>\n      <li><a href=\"http://refork.com/\">Refork</a> (animation demo gallery and sharing)</li>\n      <li><a href=\"http://sagecell.sagemath.org\">SageMathCell</a> (interactive mathematical software)</li>\n      <li><a href=\"https://cloud.sagemath.com/\">SageMathCloud</a> (interactive mathematical software environment)</li>\n      <li><a href=\"https://github.com/szekelymilan/salvare\">salvare</a> (real-time collaborative code editor)</li>\n      <li><a href=\"https://chrome.google.com/webstore/detail/servephp/mnpikomdchjhkhbhmbboehfdjkobbfpo\">ServePHP</a> (PHP code testing in Chrome dev tools)</li>\n      <li><a href=\"http://scala-lang.org/blog/2017/02/20/introducing-scastie.html\">Scastie</a> (Scala playground)</li>\n      <li><a href=\"https://www.shadertoy.com/\">Shadertoy</a> (shader sharing)</li>\n      <li><a href=\"http://www.sketchpatch.net/labs/livecodelabIntro.html\">sketchPatch Livecodelab</a></li>\n      <li><a href=\"http://www.skulpt.org/\">Skulpt</a> (in-browser Python environment)</li>\n      <li><a href=\"https://www.sourcelair.com\">SourceLair</a> (in-browser IDE for Django, Node.js, PHP and HTML5)</li>\n      <li><a href=\"http://snaptomato.appspot.com/editor.html\">Snap Tomato</a> (HTML editing/testing page)</li>\n      <li><a href=\"http://snippets.pro/\">Snippets.pro</a> (code snippet sharing)</li>\n      <li><a href=\"http://www.solidshops.com/\">SolidShops</a> (hosted e-commerce platform)</li>\n      <li><a href=\"http://www.cemetech.net/sc/\">SourceCoder 3</a> (online calculator IDE and editor)</li>\n      <li><a href=\"http://sqlfiddle.com\">SQLFiddle</a> (SQL playground)</li>\n      <li><a href=\"http://www.subte.org/page/programar-ta-te-ti-online/\">SubTe</a> (AI bot programming environment)</li>\n      <li><a href=\"http://xuanji.appspot.com/isicp/\">Structure and Interpretation of Computer Programs</a>, Interactive Version</li>\n      <li><a href=\"http://syframework.alwaysdata.net\">SyBox</a> (PHP playground)</li>\n      <li><a href=\"http://www.tagspaces.org/\">TagSpaces</a> (personal data manager)</li>\n      <li><a href=\"https://textbox.io/\">Textbox.io</a> (WYSIWYG rich text editor)</a></li>\n      <li><a href=\"https://thefiletree.com\">The File Tree</a> (collab editor)</li>\n      <li><a href=\"http://www.mapbox.com/tilemill/\">TileMill</a> (map design tool)</li>\n      <li><a href=\"http://doc.tiki.org/Syntax+Highlighter\">Tiki</a> (wiki CMS groupware)</li>\n      <li><a href=\"http://www.toolsverse.com/products/data-explorer/\">Toolsverse Data Explorer</a> (database management)</li>\n      <li><a href=\"http://blog.englard.net/post/39608000629/codeintumblr\">Tumblr code highlighting shim</a></li>\n      <li><a href=\"http://turbopy.com/\">TurboPY</a> (web publishing framework)</li>\n      <li><a href=\"http://cruise.eecs.uottawa.ca/umpleonline/\">UmpleOnline</a> (model-oriented programming tool)</li>\n      <li><a href=\"https://upsource.jetbrains.com/idea-ce/file/idea-ce-7706e7832aa9e2fd0c2decdb5cbef2225692c696/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorFactoryImpl.java\">Upsource</a> (code browser and review tool)</li>\n      <li><a href=\"https://github.com/mgaitan/waliki\">Waliki</a> (wiki engine)</li>\n      <li><a href=\"http://wamer.net/\">Wamer</a> (web application builder)</li>\n      <li><a href=\"https://github.com/brettz9/webappfind\">webappfind</a> (windows file bindings for webapps)</li>\n      <li><a href=\"http://www.webglacademy.com/\">WebGL academy</a> (learning WebGL)</li>\n      <li><a href=\"http://webglplayground.net/\">WebGL playground</a></li>\n      <li><a href=\"https://www.webkit.org/blog/2518/state-of-web-inspector/#source-code\">WebKit Web inspector</a></li>\n      <li><a href=\"http://www.wescheme.org/\">WeScheme</a> (learning tool)</li>\n      <li><a href=\"https://github.com/b3log/wide\">Wide</a> (golang web IDE)</li>\n      <li><a href=\"http://wordpress.org/extend/plugins/codemirror-for-codeeditor/\">WordPress plugin</a></li>\n      <li><a href=\"https://www.writelatex.com\">writeLaTeX</a> (Collaborative LaTeX Editor)</li>\n      <li><a href=\"http://www.xosystem.org/home/applications_websites/xosystem_website/xoside_EN.php\">XOSide</a> (online editor)</li>\n      <li><a href=\"http://videlibri.sourceforge.net/cgi-bin/xidelcgi\">XQuery tester</a></li>\n      <li><a href=\"http://q42jaap.github.io/xsd2codemirror/\">xsd2codemirror</a> (convert XSD to CM XML completion info)</li>\n      <li><a href=\"http://www.yacas.org/yacas_online/yacas_online.html\">Yacas Online</a> (interactive mathematical software)</li>\n    </ul>\n\n</article>\n\n"
  },
  {
    "path": "third_party/CodeMirror/doc/releases.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Release History</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"docs.css\">\n<script src=\"activebookmark.js\"></script>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active data-default=\"true\" href=\"#v5\">Version 5.x</a>\n    <li><a href=\"#v4\">Version 4.x</a>\n    <li><a href=\"#v3\">Version 3.x</a>\n    <li><a href=\"#v2\">Version 2.x</a>\n    <li><a href=\"#v1\">Version 0.x</a>\n  </ul>\n</div>\n\n<article>\n\n<h2>Release notes and version history</h2>\n\n<section id=v5 class=first>\n\n  <h2>Version 5.x</h2>\n\n  <p class=\"rel\">21-01-2019: <a href=\"https://codemirror.net/codemirror-5.43.0.zip\">Version 5.43.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix mistakes in passing through the arguments to <code>indent</code> in several wrapping modes.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Fix parsing for a number of new and obscure TypeScript features.</li>\n    <li><a href=\"https://codemirror.net/mode/ruby\">ruby mode</a>: Support indented end tokens for heredoc strings.</li>\n    <li>New options <code>autocorrect</code> and <code>autocapitalize</code> to turn on those browser features.</li>\n  </ul>\n\n  <p class=\"rel\">21-12-2018: <a href=\"https://codemirror.net/codemirror-5.42.2.zip\">Version 5.42.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix problem where canceling a change via the <code>&quot;beforeChange&quot;</code> event could corrupt the textarea input.</li>\n    <li>Fix issues that sometimes caused the context menu hack to fail, or even leave visual artifacts on IE.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Make it possible to select text between angle brackets.</li>\n    <li><a href=\"https://codemirror.net/mode/css/\">css mode</a>: Fix tokenizing of CSS variables.</li>\n    <li><a href=\"https://codemirror.net/mode/python/\">python mode</a>: Fix another bug in tokenizing of format strings.</li>\n    <li><a href=\"https://codemirror.net/mode/soy/\">soy mode</a>: More accurate highlighting.</li>\n  </ul>\n\n  <p class=\"rel\">20-11-2018: <a href=\"https://codemirror.net/codemirror-5.42.0.zip\">Version 5.42.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>The <a href=\"https://codemirror.net/doc/manual.html#markText\"><code>markText</code> method</a> now takes an <a href=\"https://codemirror.net/doc/manual.html#mark_attributes\"><code>attributes</code></a> option that can be used to add attributes text's HTML representation.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Add support for the <code>=</code> binding.</li>\n    <li>Fix an issue where wide characters could cause lines to be come wider than the editor's horizontal scroll width.</li>\n    <li>Optimize handling of window resize events.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_show-hint\">show-hint addon</a>: Don't assume the hints are shown in the same document the library was loaded in.</li>\n    <li><a href=\"https://codemirror.net/mode/python/\">python mode</a>: Fix bug where a string inside a template string broke highlighting.</li>\n    <li><a href=\"https://codemirror.net/mode/swift\">swift mode</a>: Support multi-line strings.</li>\n  </ul>\n\n  <p class=\"rel\">25-10-2018: <a href=\"https://codemirror.net/codemirror-5.41.0.zip\">Version 5.41.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>A new <a href=\"https://codemirror.net/doc/manual.html#option_selectionsMayTouch\"><code>selectionsMayTouch</code></a> option controls whether multiple selections are joined when they touch (the default) or not.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Add <code>noremap</code> binding command.</li>\n    <li>Fix firing of <a href=\"https://codemirror.net/doc/manual.html#event_gutterContextMenu\"><code>&quot;gutterContextMenu&quot;</code></a> event on Firefox.</li>\n    <li>Solve an issue where copying multiple selections might mess with subsequent typing.</li>\n    <li>Don't crash when <a href=\"https://codemirror.net/doc/manual.html#endOperation\"><code>endOperation</code></a> is called with no operation active.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Fix insert mode repeat after visualBlock edits.</li>\n    <li><a href=\"https://codemirror.net/mode/scheme/index.html\">scheme mode</a>: Improve highlighting of quoted expressions.</li>\n    <li><a href=\"https://codemirror.net/mode/soy/\">soy mode</a>: Support injected data and <code>@param</code> in comments.</li>\n    <li><a href=\"https://codemirror.net/mode/clike/\">objective c mode</a>: Improve conformance to the actual language.</li>\n  </ul>\n\n  <p class=\"rel\">20-09-2018: <a href=\"https://codemirror.net/codemirror-5.40.2.zip\">Version 5.40.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix firing of <code>gutterContextMenu</code> event on Firefox.</li>\n    <li>Add <code>hintWords</code> (basic completion) helper to <a href=\"https://codemirror.net/mode/clojure/index.html\">clojure</a>, <a href=\"https://codemirror.net/mode/mllike/index.html\">mllike</a>, <a href=\"https://codemirror.net/mode/julia/\">julia</a>, <a href=\"https://codemirror.net/mode/shell/\">shell</a>, and <a href=\"https://codemirror.net/mode/r/\">r</a> modes.</li>\n    <li><a href=\"https://codemirror.net/mode/clojure/index.html\">clojure mode</a>: Clean up and improve.</li>\n  </ul>\n\n  <p class=\"rel\">25-08-2018: <a href=\"https://codemirror.net/codemirror-5.40.0.zip\">Version 5.40.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New method <a href=\"https://codemirror.net/doc/manual.html#phrase\"><code>phrase</code></a> and option <a href=\"https://codemirror.net/doc/manual.html#option_phrases\"><code>phrases</code></a> to make translating UI text in addons easier.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_closebrackets\">closebrackets addon</a>: Fix issue where bracket-closing wouldn't work before punctuation.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_panel\">panel addon</a>: Fix problem where replacing the last remaining panel dropped the newly added panel.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_hardwrap\">hardwrap addon</a>: Fix an infinite loop when the indention is greater than the target column.</li>\n    <li><a href=\"https://codemirror.net/mode/jinja2/\">jinja2</a> and <a href=\"https://codemirror.net/mode/markdown/\">markdown</a> modes: Add comment metadata.</li>\n  </ul>\n\n  <p class=\"rel\">20-07-2018: <a href=\"https://codemirror.net/codemirror-5.39.2.zip\">Version 5.39.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix issue where when you pass the document as a <code>Doc</code> instance to the <code>CodeMirror</code> constructor, the <code>mode</code> option was ignored.</li>\n    <li>Fix bug where line height could be computed wrong with a line widget below a collapsed line.</li>\n    <li>Fix overeager <code>.npmignore</code> dropping the <code>bin/source-highlight</code> utility from the distribution.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_show-hint\">show-hint addon</a>: Fix behavior when backspacing to the start of the line with completions open.</li>\n  </ul>\n\n  <p class=\"rel\">20-06-2018: <a href=\"https://codemirror.net/codemirror-5.39.0.zip\">Version 5.39.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix issue that in some circumstances caused content to be clipped off at the bottom after a resize.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Improve handling of blank lines in HTML tags.</li>\n    <li><a href=\"https://codemirror.net/mode/stex/\">stex mode</a>: Add an <code>inMathMode</code> option to start the mode in math mode.</li>\n  </ul>\n\n  <p class=\"rel\">21-05-2018: <a href=\"https://codemirror.net/codemirror-5.38.0.zip\">Version 5.38.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Improve reliability of noticing a missing mouseup event during dragging.</li>\n    <li>Make sure <code>getSelection</code> is always called on the correct document.</li>\n    <li>Fix interpretation of line breaks and non-breaking spaces inserted by renderer in contentEditable mode.</li>\n    <li>Work around some browsers inexplicably making the fake scrollbars focusable.</li>\n    <li>Make sure <code>coordsChar</code> doesn't return positions inside collapsed ranges.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Support block scopes, bindingless catch, bignum suffix, <code>s</code> regexp flag.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Adjust a wasteful regexp.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_show-hint\">show-hint addon</a>: Allow opening the control without any item selected.</li>\n    <li>New theme: <a href=\"https://codemirror.net/demo/theme.html#darcula\">darcula</a>.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_dialog\">dialog addon</a>: Add a CSS class (<code>dialog-opened</code>) to the editor when a dialog is open.</li>\n  </ul>\n\n  <p class=\"rel\">20-04-2018: <a href=\"https://codemirror.net/codemirror-5.37.0.zip\">Version 5.37.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Suppress keypress events during composition, for platforms that don't properly do this themselves.</li>\n    <li><a href=\"https://codemirror.net/demo/folding.html\">xml-fold addon</a>: Improve handling of line-wrapped opening tags.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Improve TypeScript support.</li>\n    <li><a href=\"https://codemirror.net/mode/python/\">python mode</a>: Highlight expressions inside format strings.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Add support for '(' and ')' movement.</li>\n    <li>New themes: <a href=\"https://codemirror.net/demo/theme.html#idea\">idea</a>, <a href=\"https://codemirror.net/demo/theme.html#ssms\">ssms</a>, <a href=\"https://codemirror.net/demo/theme.html#gruvbox-dark\">gruvbox-dark</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-03-2018: <a href=\"https://codemirror.net/codemirror-5.36.0.zip\">Version 5.36.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Make sure all document-level event handlers are registered on the document that the editor is part of.</li>\n    <li>Fix issue that prevented edits whose origin starts with <code>+</code> from being combined in history events for an editor-less document.</li>\n    <li><a href=\"https://codemirror.net/demo/multiplex.html\">multiplex addon</a>: Improve handling of indentation.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_merge\">merge addon</a>: Use CSS <code>:after</code> element to style the scroll-lock icon.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_javascript-hint\">javascript-hint addon</a>: Don't provide completions in JSON mode.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_continuelist\">continuelist addon</a>: Fix numbering error.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_show-hint\">show-hint addon</a>: Make <code>fromList</code> completion strategy act on the current token up to the cursor, rather than the entire token.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Fix a regexp with potentially exponental complexity.</li>\n    <li>New theme: <a href=\"https://codemirror.net/demo/theme.html#lucario\">lucario</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-02-2018: <a href=\"https://codemirror.net/codemirror-5.35.0.zip\">Version 5.35.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix problem where selection undo might change read-only documents.</li>\n    <li>Fix crash when calling <code>addLineWidget</code> on a document that has no attached editor.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_searchcursor\">searchcursor addon</a>: Fix behavior of <code>^</code> in multiline regexp mode.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_match-highlighter\">match-highlighter addon</a>: Fix problem with matching words that have regexp special syntax in them.</li>\n    <li><a href=\"https://codemirror.net/demo/sublime.html\">sublime bindings</a>: Fix <code>addCursorToSelection</code> for short lines.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Support alternative delimiters in replace command.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Support TypeScript intersection types, dynamic <code>import</code>.</li>\n    <li><a href=\"https://codemirror.net/mode/stex/\">stex mode</a>: Fix parsing of <code>\\(</code> <code>\\)</code> delimiters, recognize more atom arguments.</li>\n    <li><a href=\"https://codemirror.net/mode/haskell/\">haskell mode</a>: Highlight more builtins, support <code>&lt;*</code> and <code>*&gt;</code>.</li>\n    <li><a href=\"https://codemirror.net/mode/sql/\">sql mode</a>: Make it possible to disable backslash escapes in strings for dialects that don't have them, do this for MS SQL.</li>\n    <li><a href=\"https://codemirror.net/mode/dockerfile/\">dockerfile mode</a>: Highlight strings and ports, recognize more instructions.</li>\n  </ul>\n\n  <p class=\"rel\">29-01-2018: <a href=\"https://codemirror.net/codemirror-5.34.0.zip\">Version 5.34.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Fix a problem where inline styles would persist across list items.</li>\n    <li><a href=\"https://codemirror.net/demo/sublime.html\">sublime bindings</a>: Fix the <code>toggleBookmark</code> command.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_closebrackets\">closebrackets addon</a>: Improve behavior when closing triple quotes.</li>\n    <li><a href=\"https://codemirror.net/demo/folding.html\">xml-fold addon</a>: Fix folding of line-broken XML tags.</li>\n    <li><a href=\"https://codemirror.net/mode/shell/\">shell mode</a>: Better handling of nested quoting.</li>\n    <li><a href=\"https://codemirror.net/demo/lint.html\">javascript-lint addon</a>: Clean up and simplify.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_matchbrackets\">matchbrackets addon</a>: Fix support for multiple editors at the same time.</li>\n    <li>New themes: <a href=\"https://codemirror.net/demo/theme.html#oceanic-next\">oceanic-next</a> and <a href=\"https://codemirror.net/demo/theme.html#shadowfox\">shadowfox</a>.</li>\n  </ul>\n\n  <p class=\"rel\">21-12-2017: <a href=\"https://codemirror.net/codemirror-5.33.0.zip\">Version 5.33.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_lint\">lint addon</a>: Make updates more efficient.</li>\n    <li><a href=\"https://codemirror.net/mode/css/\">css mode</a>: The mode is now properly case-insensitive.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_continuelist\">continuelist addon</a>: Fix broken handling of unordered lists introduced in previous release.</li>\n    <li><a href=\"https://codemirror.net/mode/swift\">swift</a> and <a href=\"https://codemirror.net/mode/clike/\">scala</a> modes: Support nested block comments.</li>\n    <li><a href=\"https://codemirror.net/mode/mllike/index.html\">mllike mode</a>: Improve OCaml support.</li>\n    <li><a href=\"https://codemirror.net/demo/sublime.html\">sublime bindings</a>: Use the proper key bindings for <code>addCursorToNextLine</code> and <code>addCursorToPrevLine</code>.</li>\n    <li><a href=\"https://codemirror.net/mode/jsx/index.html\">jsx mode</a>: Support JSX fragments.</li>\n    <li><a href=\"https://codemirror.net/demo/closetag.html\">closetag addon</a>: Add an option to disable auto-indenting.</li>\n  </ul>\n\n  <p class=\"rel\">22-11-2017: <a href=\"https://codemirror.net/codemirror-5.32.0.zip\">Version 5.32.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Increase contrast on default bracket-matching colors.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Recognize TypeScript type parameters for calls, type guards, and type parameter defaults. Improve handling of <code>enum</code> and <code>module</code> keywords.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_comment\">comment addon</a>: Fix bug when uncommenting a comment that spans all but the last selected line.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_searchcursor\">searchcursor addon</a>: Fix bug in case folding.</li>\n    <li><a href=\"https://codemirror.net/demo/emacs.html\">emacs bindings</a>: Prevent single-character deletions from resetting the kill ring.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_closebrackets\">closebrackets addon</a>: Tweak quote matching behavior.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_continuelist\">continuelist addon</a>: Increment ordered list numbers when adding one.</li>\n  </ul>\n\n  <p class=\"rel\">20-10-2017: <a href=\"https://codemirror.net/codemirror-5.31.0.zip\">Version 5.31.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Modes added with <a href=\"https://codemirror.net/doc/manual.html#addOverlay\"><code>addOverlay</code></a> now have access to a <a href=\"https://codemirror.net/doc/manual.html#baseToken\"><code>baseToken</code></a> method on their input stream, giving access to the tokens of the underlying mode.</li>\n    <li>Further improve selection drawing and cursor motion in right-to-left documents.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Fix ctrl-w behavior, support quote-dot and backtick-dot marks, make the wide cursor visible in contentEditable <a href=\"https://codemirror.net/doc/manual.html#option_contentEditable\">input mode</a>.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_continuecomment\">continuecomment addon</a>: Fix bug when pressing enter after a single-line block comment.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Fix issue with leaving indented fenced code blocks.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Fix bad parsing of operators without spaces between them. Fix some corner cases around semicolon insertion and regexps.</li>\n  </ul>\n\n  <p class=\"rel\">20-09-2017: <a href=\"https://codemirror.net/codemirror-5.30.0.zip\">Version 5.30.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fixed a number of issues with drawing right-to-left selections and mouse selection in bidirectional text.</li>\n    <li><a href=\"https://codemirror.net/demo/search/\">search addon</a>: Fix crash when restarting search after doing empty search.</li>\n    <li><a href=\"http://cm/doc/manual.html#addon_mark-selection\">mark-selection addon</a>: Fix off-by-one bug.</li>\n    <li><a href=\"https://codemirror.net/demo/tern.html\">tern addon</a>: Fix bad request made when editing at the bottom of a large document.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Improve parsing in a number of corner cases.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Fix crash when a sub-mode doesn't support indentation, allow uppercase X in task lists.</li>\n    <li><a href=\"https://codemirror.net/mode/gfm/\">gfm mode</a>: Don't highlight SHA1 'hashes' without numbers to avoid false positives.</li>\n    <li><a href=\"https://codemirror.net/mode/soy/\">soy mode</a>: Support injected data and <code>@param</code> in comments.</li>\n    <li><a href=\"https://codemirror.net/demo/simplemode.html\">simple mode addon</a>: Allow groups in regexps when <code>token</code> isn't an array.</li>\n  </ul>\n\n  <p class=\"rel\">24-08-2017: <a href=\"https://codemirror.net/codemirror-5.29.0.zip\">Version 5.29.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix crash in contentEditable input style when editing near a bookmark.</li>\n    <li>Make sure change origins are preserved when splitting changes on <a href=\"https://codemirror.net/doc/manual.html#mark_readOnly\">read-only marks</a>.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: More support for TypeScript syntax.</li>\n    <li><a href=\"https://codemirror.net/mode/d/\">d mode</a>: Support nested comments.</li>\n    <li><a href=\"https://codemirror.net/mode/python/\">python mode</a>: Improve tokenizing of operators.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Further improve CommonMark conformance.</li>\n    <li><a href=\"https://codemirror.net/mode/css/\">css mode</a>: Don't run comment tokens through the mode's state machine.</li>\n    <li><a href=\"https://codemirror.net/mode/shell/\">shell mode</a>: Allow strings to span lines.</li>\n    <li><a href=\"https://codemirror.net/demo/search/\">search addon</a>: Fix crash in persistent search when <code>extraKeys</code> is null.</li>\n  </ul>\n\n  <p class=\"rel\">21-07-2017: <a href=\"https://codemirror.net/codemirror-5.28.0.zip\">Version 5.28.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix copying of, or replacing editor content with, a single dash character when copying a big selection in some corner cases.</li>\n    <li>Make <a href=\"https://codemirror.net/doc/manual.html#command_goLineLeft\"><code>&quot;goLineLeft&quot;</code></a>/<code>&quot;goLineRight&quot;</code> behave better on wrapped lines.</li>\n    <li><a href=\"https://codemirror.net/mode/sql/\">sql mode</a>: Fix tokenizing of multi-dot operator and allow digits in subfield names.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_searchcursor\">searchcursor addon</a>: Fix infinite loop on some composed character inputs.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Make list parsing more CommonMark-compliant.</li>\n    <li><a href=\"https://codemirror.net/mode/gfm/\">gfm mode</a>: Highlight colon syntax for emoji.</li>\n  </ul>\n\n  <p class=\"rel\">29-06-2017: <a href=\"https://codemirror.net/codemirror-5.27.4.zip\">Version 5.27.4</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix crash when using mode lookahead.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Don't block inner mode's indentation support.</li>\n  </ul>\n\n  <p class=\"rel\">22-06-2017: <a href=\"https://codemirror.net/codemirror-5.27.2.zip\">Version 5.27.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix crash in the <a href=\"https://codemirror.net/demo/simplemode.html\">simple mode</a> addon.</li>\n  </ul>\n\n  <p class=\"rel\">22-06-2017: <a href=\"https://codemirror.net/codemirror-5.27.0.zip\">Version 5.27.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix infinite loop in forced display update.</li>\n    <li>Properly disable the hidden textarea when <code>readOnly</code> is <code>&quot;nocursor&quot;</code>.</li>\n    <li>Calling the <code>Doc</code> constructor without <code>new</code> works again.</li>\n    <li><a href=\"https://codemirror.net/mode/sql/\">sql mode</a>: Handle nested comments.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Improve support for TypeScript syntax.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Fix bug where markup was ignored on indented paragraph lines.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Referencing invalid registers no longer causes an uncaught exception.</li>\n    <li><a href=\"https://codemirror.net/mode/rust/\">rust mode</a>: Add the correct MIME type.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_matchbrackets\">matchbrackets addon</a>: Document options.</li>\n    <li>Mouse button clicks can now be bound in keymaps by using names like <code>&quot;LeftClick&quot;</code> or <code>&quot;Ctrl-Alt-MiddleTripleClick&quot;</code>. When bound to a function, that function will be passed the position of the click as second argument.</li>\n    <li>The behavior of mouse selection and dragging can now be customized with the <a href=\"https://codemirror.net/doc/manual.html#option_configureMouse\"><code>configureMouse</code></a> option.</li>\n    <li>Modes can now look ahead across line boundaries with the <a href=\"https://codemirror.net/doc/manual.html#StringStream\"><code>StringStream</code></a><code>.lookahead</code> method.</li>\n    <li>Introduces a <code>&quot;type&quot;</code> token type, makes modes that recognize types output it, and add styling for it to the themes.</li>\n    <li>New <a href=\"https://codemirror.net/doc/manual.html#option_pasteLinesPerSelection\"><code>pasteLinesPerSelection</code></a> option to control the behavior of pasting multiple lines into multiple selections.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_searchcursor\">searchcursor addon</a>: Support multi-line regular expression matches, and normalize strings when matching.</li>\n  </ul>\n\n  <p class=\"rel\">22-05-2017: <a href=\"https://codemirror.net/codemirror-5.26.0.zip\">Version 5.26.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>In textarea-mode, don't reset the input field during composition.</li>\n    <li>More careful restoration of selections in widgets, during editor redraw.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Parse line offsets in line or range specs.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: More TypeScript parsing fixes.</li>\n    <li><a href=\"https://codemirror.net/mode/julia/\">julia mode</a>: Fix issue where the mode gets stuck.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Understand cross-line links, parse all bracketed things as links.</li>\n    <li><a href=\"https://codemirror.net/mode/soy/\">soy mode</a>: Support single-quoted strings.</li>\n    <li><a href=\"https://codemirror.net/mode/go/\">go mode</a>: Don't try to indent inside strings or comments.</li>\n  </ul>\n\n  <p class=\"rel\">20-04-2017: <a href=\"https://codemirror.net/codemirror-5.25.2.zip\">Version 5.25.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Better handling of selections that cover the whole viewport in contentEditable-mode.</li>\n    <li>No longer accidentally scroll the editor into view when calling <code>setValue</code>.</li>\n    <li>Work around Chrome Android bug when converting screen coordinates to editor positions.</li>\n    <li>Make sure long-clicking a selection sets a cursor and doesn't show the editor losing focus.</li>\n    <li>Fix issue where pointer events were incorrectly disabled on Chrome's overlay scrollbars.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Recognize annotations and TypeScript-style type parameters.</li>\n    <li><a href=\"https://codemirror.net/mode/shell/\">shell mode</a>: Handle nested braces.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Make parsing of strong/em delimiters CommonMark-compliant.</li>\n  </ul>\n\n  <p class=\"rel\">20-03-2017: <a href=\"https://codemirror.net/codemirror-5.25.0.zip\">Version 5.25.0</a>:</p>\n\n  <ul class=rel-note>\n    <li>In contentEditable-mode, properly locate changes that repeat a character when inserted with IME.</li>\n    <li>Fix handling of selections bigger than the viewport in contentEditable mode.</li>\n    <li>Improve handling of changes that insert or delete lines in contentEditable mode.</li>\n    <li>Count Unicode control characters 0x80 to 0x9F as special (non-printing) chars.</li>\n    <li>Fix handling of shadow DOM roots when finding the active element.</li>\n    <li>Add <code>role=presentation</code> to more DOM elements to improve screen reader support.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_merge\">merge addon</a>: Make aligning of unchanged chunks more robust.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_comment\">comment addon</a>: Fix comment-toggling on a block of text that starts and ends in a (differnet) block comment.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Improve support for TypeScript syntax.</li>\n    <li><a href=\"https://codemirror.net/mode/r/\">r mode</a>: Fix indentation after semicolon-less statements.</li>\n    <li><a href=\"https://codemirror.net/mode/shell/\">shell mode</a>: Properly handle escaped parentheses in parenthesized expressions.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Fix a few bugs around leaving fenced code blocks.</li>\n    <li><a href=\"https://codemirror.net/mode/soy/\">soy mode</a>: Improve indentation.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_lint\">lint addon</a>: Support asynchronous linters that return promises.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_continuelist\">continuelist addon</a>: Support continuing task lists.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Make Y behave like yy.</li>\n    <li><a href=\"https://codemirror.net/mode/sql/\">sql mode</a>: Support sqlite dialect.</li>\n  </ul>\n\n  <p class=\"rel\">22-02-2017: <a href=\"https://codemirror.net/codemirror-5.24.2.zip\">Version 5.24.2</a>:</p>\n\n  <ul class=rel-note>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Support computed class method names.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_merge\">merge addon</a>: Improve aligning of unchanged code in the presence of marks and line widgets.</li>\n  </ul>\n\n  <p class=\"rel\">20-02-2017: <a href=\"https://codemirror.net/codemirror-5.24.0.zip\">Version 5.24.0</a>:</p>\n\n  <ul class=rel-note>\n    <li>Positions now support a <code>sticky</code> property which determines whether they should be associated with the character before (value <code>\"before\"</code>) or after (value <code>\"after\"</code>) them.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Make it possible to remove built-in bindings through the API.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_comment\">comment addon</a>: Support a per-mode <code>useInnerComments</code> option to optionally suppress descending to the inner modes to get comment strings.</li>\n    <li>A cursor directly before a line-wrapping break is now drawn before or after the line break depending on which direction you arrived from.</li>\n    <li>Visual cursor motion in line-wrapped right-to-left text should be much more correct.</li>\n    <li>Fix bug in handling of read-only marked text.</li>\n    <li><a href=\"https://codemirror.net/mode/shell/\">shell mode</a>: Properly tokenize nested parentheses.</li>\n    <li><a href=\"https://codemirror.net/mode/python/\">python mode</a>: Support underscores in number literals.</li>\n    <li><a href=\"https://codemirror.net/mode/sass/\">sass mode</a>: Uses the full list of CSS properties and keywords from the CSS mode, rather than defining its own incomplete subset. Now depends on the css mode.</li>\n    <li><a href=\"https://codemirror.net/mode/css/\">css mode</a>: Expose <code>lineComment</code> property for LESS and SCSS dialects. Recognize vendor prefixes on pseudo-elements.</li>\n    <li><a href=\"https://codemirror.net/mode/julia/\">julia mode</a>: Properly indent <code>elseif</code> lines.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Properly recognize the end of fenced code blocks when inside other markup.</li>\n    <li><a href=\"https://codemirror.net/mode/clike/\">scala mode</a>: Improve handling of operators containing <code>#</code>, <code>@</code>, and <code>:</code> chars.</li>\n    <li><a href=\"https://codemirror.net/mode/xml/\">xml mode</a>: Allow dashes in HTML tag names.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Improve parsing of async methods, TypeScript-style comma-separated superclass lists.</li>\n    <li><a href=\"https://codemirror.net/demo/folding.html\">indent-fold addon</a>: Ignore comment lines.</li>\n  </ul>\n\n  <p class=\"rel\">19-01-2017: <a href=\"https://codemirror.net/codemirror-5.23.0.zip\">Version 5.23.0</a>:</p>\n\n  <ul class=rel-note>\n    <li>Presentation-related elements DOM elements are now marked as such to help screen readers.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Be more picky about what HTML tags look like to avoid false positives.</li>\n    <li><code>findModeByMIME</code> now understands <code>+json</code> and <code>+xml</code> MIME suffixes.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_closebrackets\">closebrackets addon</a>: Add support for an <code>override</code> option to ignore language-specific defaults.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_panel\">panel addon</a>: Add a <code>stable</code> option that auto-scrolls the content to keep it in the same place when inserting/removing a panel.</li>\n  </ul>\n\n  <p class=\"rel\">20-12-2016: <a href=\"https://codemirror.net/codemirror-5.22.0.zip\">Version 5.22.0</a>:</p>\n\n  <ul class=rel-note>\n    <li><a href=\"https://codemirror.net/demo/sublime.html\">sublime bindings</a>: Make <code>selectBetweenBrackets</code> work with multiple cursors.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Fix issues with parsing complex TypeScript types, imports, and exports.</li>\n    <li>A contentEditable editor instance with autofocus enabled no longer crashes during initializing.</li>\n    <li><a href=\"https://codemirror.net/demo/emacs.html\">emacs bindings</a>: Export <code>CodeMirror.emacs</code> to allow other addons to hook into Emacs-style functionality.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_active-line\">active-line addon</a>: Add <code>nonEmpty</code> option.</li>\n    <li>New event: <a href=\"https://codemirror.net/doc/manual.html#event_optionChange\"><code>optionChange</code></a>.</li>\n  </ul>\n\n  <p class=\"rel\">21-11-2016: <a href=\"https://codemirror.net/codemirror-5.21.0.zip\">Version 5.21.0</a>:</p>\n\n  <ul class=rel-note>\n    <li>Tapping/clicking the editor in <a href=\"https://codemirror.net/doc/manual.html#option_inputStyle\">contentEditable mode</a> on Chrome now puts the cursor at the tapped position.</li>\n    <li>Fix various crashes and misbehaviors when reading composition events in <a href=\"https://codemirror.net/doc/manual.html#option_inputStyle\">contentEditable mode</a>.</li>\n    <li>Catches and ignores an IE 'Unspecified Error' when creating an editor in an iframe before there is a <code>&lt;body&gt;</code>.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_merge\">merge addon</a>: Fix several issues in the chunk-aligning feature.</li>\n    <li><a href=\"https://codemirror.net/mode/verilog\">verilog mode</a>: Rewritten to address various issues.</li>\n    <li><a href=\"https://codemirror.net/mode/julia\">julia mode</a>: Recognize Julia 0.5 syntax.</li>\n    <li><a href=\"https://codemirror.net/mode/swift\">swift mode</a>: Various fixes and adjustments to current syntax.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown\">markdown mode</a>: Allow lists without a blank line above them.</li>\n    <li>The <a href=\"https://codemirror.net/doc/manual.html#setGutterMarker\"><code>setGutterMarker</code></a>, <a href=\"https://codemirror.net/doc/manual.html#clearGutter\"><code>clearGutter</code></a>, and <a href=\"https://codemirror.net/doc/manual.html#lineInfo\"><code>lineInfo</code></a> methods are now available on <code>Doc</code> objects.</li>\n    <li>The <a href=\"https://codemirror.net/doc/manual.html#heightAtLine\"><code>heightAtLine</code></a> method now takes an extra argument to allow finding the height at the top of the line's line widgets.</li>\n    <li><a href=\"https://codemirror.net/mode/ruby\">ruby mode</a>: <code>else</code> and <code>elsif</code> are now immediately indented.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Bind Ctrl-T and Ctrl-D to in- and dedent in insert mode.</li>\n  </ul>\n\n  <p class=\"rel\">20-10-2016: <a href=\"https://codemirror.net/codemirror-5.20.0.zip\">Version 5.20.0</a>:</p>\n\n  <ul class=rel-note>\n    <li>Make <code>newlineAndIndent</code> command work with multiple cursors on the same line.</li>\n    <li>Make sure keypress events for backspace are ignored.</li>\n    <li>Tokens styled with overlays no longer get a nonsense <code>cm-cm-overlay</code> class.</li>\n    <li>Line endings for pasted content are now normalized to the editor's <a href=\"https://codemirror.net/doc/manual.html#option_lineSeparator\">preferred ending</a>.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript\">javascript mode</a>: Improve support for class expressions. Support TypeScript optional class properties, the <code>abstract</code> keyword, and return type declarations for arrow functions.</li>\n    <li><a href=\"https://codemirror.net/mode/css\">css mode</a>: Fix highlighting of mixed-case keywords.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_closebrackets\">closebrackets addon</a>: Improve behavior when typing a quote before a string.</li>\n    <li>The core is now maintained as a number of small files, using ES6 syntax and modules, under the <code>src/</code> directory. A git checkout no longer contains a working <code>codemirror.js</code> until you <code>npm build</code> (but when installing from NPM, it is included).</li>\n    <li>The <a href=\"https://codemirror.net/doc/manual.html#event_refresh\"><code>refresh</code></a> event is now documented and stable.</li>\n  </ul>\n\n  <p class=\"rel\">20-09-2016: <a href=\"https://codemirror.net/codemirror-5.19.0.zip\">Version 5.19.0</a>:</p>\n\n  <ul class=rel-note>\n    <li><a href=\"https://codemirror.net/mode/erlang\">erlang mode</a>: Fix mode crash when trying to read an empty context.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_comment\">comment addon</a>: Fix broken behavior when toggling comments inside a comment.</li>\n    <li>xml-fold addon: Fix a null-dereference bug.</li>\n    <li>Page up and page down now do something even in single-line documents.</li>\n    <li>Fix an issue where the cursor position could be off in really long (~8000 character) tokens.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript\">javascript mode</a>: Better indentation when semicolons are missing. Better support for TypeScript classes, optional parameters, and the <code>type</code> keyword.</li>\n    <li>The <a href=\"https://codemirror.net/doc/manual.html#event_blur\"><code>blur</code></a> and <a href=\"https://codemirror.net/doc/manual.html#event_focus\"><code>focus</code></a> events now pass the DOM event to their handlers.</li>\n  </ul>\n\n  <p class=\"rel\">23-08-2016: <a href=\"https://codemirror.net/codemirror-5.18.2.zip\">Version 5.18.2</a>:</p>\n\n  <ul class=rel-note>\n    <li><a href=\"https://codemirror.net/mode/vue\">vue mode</a>: Fix outdated references to renamed Pug mode dependency.</li>\n  </ul>\n\n  <p class=\"rel\">22-08-2016: <a href=\"https://codemirror.net/codemirror-5.18.0.zip\">Version 5.18.0</a>:</p>\n\n  <ul class=rel-note>\n    <li>Make sure <a href=\"https://codemirror.net/doc/manual.html#addLineClass\">gutter backgrounds</a> stick to the rest of the gutter during horizontal scrolling.</li>\n    <li>The contenteditable <a href=\"https://codemirror.net/doc/manual.html#option_inputStyle\"><code>inputStyle</code></a> now properly supports pasting on pre-Edge IE versions.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript\">javascript mode</a>: Fix some small parsing bugs and improve TypeScript support.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_matchbrackets\">matchbrackets addon</a>: Fix bug where active highlighting was left in editor when the addon was disabled.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_match-highlighter\">match-highlighter addon</a>: Only start highlighting things when the editor gains focus.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_javascript-hint\">javascript-hint addon</a>: Also complete non-enumerable properties.</li>\n    <li>The <a href=\"https://codemirror.net/doc/manual.html#addOverlay\"><code>addOverlay</code></a> method now supports a <code>priority</code> option to control the order in which overlays are applied.</li>\n    <li>MIME types that end in <code>+json</code> now default to the JSON mode when the MIME itself is not defined.</li>\n    <li>The mode formerly known as Jade was renamed to <a href=\"https://codemirror.net/mode/pug\">Pug</a>.</li>\n    <li>The <a href=\"https://codemirror.net/mode/python\">Python mode</a> now defaults to Python 3 (rather than 2) syntax.</li>\n  </ul>\n\n  <p class=\"rel\">19-07-2016: <a href=\"https://codemirror.net/codemirror-5.17.0.zip\">Version 5.17.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix problem with wrapped trailing whitespace displaying incorrectly.</li>\n    <li>Prevent IME dialog from overlapping typed content in Chrome.</li>\n    <li>Improve measuring of characters near a line wrap.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript\">javascript mode</a>: Improve support for <code>async</code>, allow trailing commas in <code>import</code> lists.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Fix backspace in replace mode.</li>\n    <li><a href=\"https://codemirror.net/demo/sublime.html\">sublime bindings</a>: Fix some key bindings on OS X to match Sublime Text.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown\">markdown mode</a>: Add more classes to image links in highlight-formatting mode.</li>\n  </ul>\n\n  <p class=\"rel\">20-06-2016: <a href=\"https://codemirror.net/codemirror-5.16.0.zip\">Version 5.16.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix glitches when dragging content caused by the drop indicator receiving mouse events.</li>\n    <li>Make Control-drag work on Firefox.</li>\n    <li>Make clicking or selection-dragging at the end of a wrapped line select the right position.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_show-hint\">show-hint addon</a>: Prevent widget scrollbar from hiding part of the hint text.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_rulers\">rulers addon</a>: Prevent rulers from forcing a horizontal editor scrollbar.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_search\">search addon</a>: Automatically bind search-related keys in persistent dialog.</li>\n    <li><a href=\"https://codemirror.net/demo/sublime.html\">sublime keymap</a>: Add a multi-cursor aware smart backspace binding.</li>\n  </ul>\n\n  <p class=\"rel\">20-05-2016: <a href=\"https://codemirror.net/codemirror-5.15.2.zip\">Version 5.15.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix a critical document corruption bug that occurs when a document is gradually grown.</li>\n  </ul>\n\n  <p class=\"rel\">20-05-2016: <a href=\"https://codemirror.net/codemirror-5.15.0.zip\">Version 5.15.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix bug that caused the selection to reset when focusing the editor in contentEditable input mode.</li>\n    <li>Fix issue where not all ASCII control characters were being replaced by placeholders.</li>\n    <li>Remove the assumption that all modes have a <code>startState</code> method from several wrapping modes.</li>\n    <li>Fix issue where the editor would complain about overlapping collapsed ranges when there weren't any.</li>\n    <li>Optimize document tree building when loading or pasting huge chunks of content.</li>\n    <li>Explicitly bind Ctrl-O on OS X to make that binding (“open line”) act as expected.</li>\n    <li>Pasting <a href=\"https://codemirror.net/doc/manual.html#option_lineWiseCopyCut\">linewise-copied</a> content when there is no selection now inserts the lines above the current line.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">markdown mode</a>: Fix several issues in matching link targets.</li>\n    <li><a href=\"https://codemirror.net/mode/clike/\">clike mode</a>: Improve indentation of C++ template declarations.</li>\n    <li><a href=\"https://codemirror.net/mode/javascript/\">javascript mode</a>: Support <code>async</code>/<code>await</code> and improve support for TypeScript type syntax.</li>\n  </ul>\n\n  <p class=\"rel\">20-04-2016: <a href=\"https://codemirror.net/codemirror-5.14.0.zip\">Version 5.14.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><a href=\"https://codemirror.net/doc/manual.html#posFromIndex\"><code>posFromIndex</code></a> and <a href=\"https://codemirror.net/doc/manual.html#indexFromPos\"><code>indexFromPos</code></a> now take <a href=\"https://codemirror.net/doc/manual.html#option_lineSeparator\"><code>lineSeparator</code></a> into account</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Only call <code>.save()</code> when it is actually available</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_comment\">comment addon</a>: Be careful not to mangle multi-line strings</li>\n    <li><a href=\"https://codemirror.net/mode/python/index.html\">Python mode</a>: Improve distinguishing of decorators from <code>@</code> operators</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#findMarks\"><code>findMarks</code></a>: No longer return marks that touch but don't overlap given range</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">vim bindings</a>: Add yank command</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_match-highlighter\">match-highlighter addon</a>: Add <code>trim</code> option to disable ignoring of whitespace</li>\n    <li><a href=\"https://codemirror.net/mode/powershell/index.html\">PowerShell mode</a>: Added</li>\n    <li><a href=\"https://codemirror.net/mode/yacas/index.html\">Yacas mode</a>: Added</li>\n    <li><a href=\"https://codemirror.net/mode/webidl/index.html\">Web IDL mode</a>: Added</li>\n    <li><a href=\"https://codemirror.net/mode/sas/index.html\">SAS mode</a>: Added</li>\n    <li><a href=\"https://codemirror.net/mode/mbox/index.html\">mbox mode</a>: Added</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.13.4...5.14.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">21-03-2016: <a href=\"https://codemirror.net/codemirror-5.13.2.zip\">Version 5.13.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Solves a problem where the gutter would sometimes not extend all the way to the end of the document.</li>\n  </ul>\n\n  <p class=\"rel\">21-03-2016: <a href=\"https://codemirror.net/codemirror-5.13.zip\">Version 5.13</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New DOM event forwarded: <a href=\"https://codemirror.net/doc/manual.html#event_dom\"><code>&quot;dragleave&quot;</code></a>.</li>\n    <li><a href=\"https://codemirror.net/mode/protobuf/index.html\">protobuf mode</a>: Newly added.</li>\n    <li>Fix problem where <a href=\"https://codemirror.net/doc/manual.html#findMarks\"><code>findMarks</code></a> sometimes failed to find multi-line marks.</li>\n    <li>Fix crash that showed up when atomic ranges and bidi text were combined.</li>\n    <li><a href=\"https://codemirror.net/demo/complete.html\">show-hint addon</a>: Completion widgets no longer close when the line indented or dedented.</li>\n    <li><a href=\"https://codemirror.net/demo/merge.html\">merge addon</a>: Fix bug when merging chunks at the end of the file.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_placeholder\">placeholder addon</a>: No longer gets confused by <a href=\"https://codemirror.net/doc/manual.html#swapDoc\"><code>swapDoc</code></a>.</li>\n    <li><a href=\"https://codemirror.net/doc/manual.html#addon_simplescrollbars\">simplescrollbars addon</a>: Fix invalid state when deleting at end of document.</li>\n    <li><a href=\"https://codemirror.net/mode/clike/index.html\">clike mode</a>: No longer gets confused when a comment starts after an operator.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/index.html\">markdown mode</a>: Now supports CommonMark-style flexible list indentation.</li>\n    <li><a href=\"https://codemirror.net/mode/dylan/index.html\">dylan mode</a>: Several improvements and fixes.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.12.0...5.13.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">19-02-2016: <a href=\"https://codemirror.net/codemirror-5.12.zip\">Version 5.12</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><a href=\"https://codemirror.net/demo/vim.html\">Vim bindings</a>: Ctrl-Q is now an alias for Ctrl-V.</li>\n    <li><a href=\"https://codemirror.net/demo/vim.html\">Vim bindings</a>: The Vim API now exposes an <code>unmap</code> method to unmap bindings.</li>\n    <li><a href=\"https://codemirror.net/demo/activeline.html\">active-line addon</a>: This addon can now style the active line's gutter.</li>\n    <li><a href=\"https://codemirror.net/mode/fcl/\">FCL mode</a>: Newly added.</li>\n    <li><a href=\"https://codemirror.net/mode/sql/\">SQL mode</a>: Now has a Postgresql dialect.</li>\n    <li>Fix <a href=\"https://github.com/codemirror/CodeMirror/issues/3781\">issue</a> where trying to scroll to a horizontal position outside of the document's width could cause the gutter to be positioned incorrectly.</li>\n    <li>Use absolute, rather than fixed positioning in the context-menu intercept hack, to work around a <a href=\"https://github.com/codemirror/CodeMirror/issues/3238\">problem</a> when the editor is inside a transformed parent container.</li>\n    <li>Solve a <a href=\"https://github.com/codemirror/CodeMirror/issues/3821\">problem</a> where the horizontal scrollbar could hide text in Firefox.</li>\n    <li>Fix a <a href=\"https://github.com/codemirror/CodeMirror/issues/3834\">bug</a> that caused phantom scroll space under the text in some situations.</li>\n    <li><a href=\"https://codemirror.net/demo/sublime.html\">Sublime Text bindings</a>: Bind delete-line to Shift-Ctrl-K on OS X.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">Markdown mode</a>: Fix <a href=\"https://github.com/codemirror/CodeMirror/issues/3787\">issue</a> where the mode would keep state related to fenced code blocks in an unsafe way, leading to occasional corrupted parses.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">Markdown mode</a>: Ignore backslashes in code fragments.</li>\n    <li><a href=\"https://codemirror.net/mode/markdown/\">Markdown mode</a>: Use whichever mode is registered as <code>text/html</code> to parse HTML.</li>\n    <li><a href=\"https://codemirror.net/mode/clike/\">Clike mode</a>: Improve indentation of Scala <code>=&gt;</code> functions.</li>\n    <li><a href=\"https://codemirror.net/mode/python/\">Python mode</a>: Improve indentation of bracketed code.</li>\n    <li><a href=\"https://codemirror.net/mode/htmlmixed/\">HTMLMixed mode</a>: Support multi-line opening tags for sub-languages (<code>&lt;script&gt;</code>, <code>&lt;style&gt;</code>, etc).</li>\n    <li><a href=\"https://codemirror.net/mode/spreadsheet/\">Spreadsheet mode</a>: Fix bug where the mode did not advance the stream when finding a backslash.</li>\n    <li><a href=\"https://codemirror.net/mode/xml/\">XML mode</a>: The mode now takes a <code>matchClosing</code> option to configure whether mismatched closing tags should be highlighted as errors.</li>\n  </ul>\n\n  <p class=\"rel\">20-01-2016: <a href=\"https://codemirror.net/codemirror-5.11.zip\">Version 5.11</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/jsx/index.html\">JSX</a>, <a href=\"../mode/haskell-literate/index.html\">literate Haskell</a></li>\n    <li>The editor now forwards more <a href=\"manual.html#event_dom\">DOM events</a>: <code>cut</code>, <code>copy</code>, <code>paste</code>, and <code>touchstart</code>. It will also forward <code>mousedown</code> for drag events</li>\n    <li>Fixes a bug where bookmarks next to collapsed spans were not rendered</li>\n    <li>The <a href=\"../mode/swift/index.html\">Swift</a> mode now supports auto-indentation</li>\n    <li>Frontmatters in the <a href=\"../mode/yaml-frontmatter/index.html\">YAML frontmatter</a> mode are now optional as intended</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.10.0...5.11.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">21-12-2015: <a href=\"https://codemirror.net/codemirror-5.10.zip\">Version 5.10</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Modify the way <a href=\"manual.html#mark_atomic\">atomic ranges</a> are skipped by selection to try and make it less surprising.</li>\n    <li>The <a href=\"../mode/swift/index.html\">Swift mode</a> was rewritten.</li>\n    <li>New addon: <a href=\"manual.html#addon_jump-to-line\">jump-to-line</a>.</li>\n    <li>New method: <a href=\"manual.html#isReadOnly\"><code>isReadOnly</code></a>.</li>\n    <li>The <a href=\"manual.html#addon_show-hint\">show-hint addon</a> now defaults to picking completions on single click.</li>\n    <li>The object passed to <a href=\"manual.html#event_beforeSelectionChange\"><code>&quot;beforeSelectionChange&quot;</code></a> events now has an <code>origin</code> property.</li>\n    <li>New mode: <a href=\"../mode/crystal/index.html\">Crystal</a>.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.9.0...5.10.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">23-11-2015: <a href=\"https://codemirror.net/codemirror-5.9.zip\">Version 5.9</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Improve the way overlay (OS X-style) scrollbars are handled</li>\n    <li>Make <a href=\"manual.html#addon_annotatescrollbar\">annotatescrollbar</a> and scrollpastend addons work properly together</li>\n    <li>Make <a href=\"manual.html#addon_show-hint\">show-hint</a> addon select options on single click by default, move selection to hovered item</li>\n    <li>Properly fold comments that include block-comment-start markers</li>\n    <li>Many small language mode fixes</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.8.0...5.9.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">20-10-2015: <a href=\"https://codemirror.net/codemirror-5.8.zip\">Version 5.8</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fixes an infinite loop in\n    the <a href=\"manual.html#addon_hardwrap\">hardwrap\n    addon</a></li>\n    <li>New modes: <a href=\"../mode/nsis/index.html\">NSIS</a>, <a href=\"../mode/clike/index.html\">Ceylon</a></li>\n    <li>The Kotlin mode is now a <a href=\"../mode/clike/index.html\">clike</a> dialect, rather than a stand-alone mode</li>\n    <li>New option: <a href=\"manual.html#option_allowDropFileTypes\"><code>allowDropFileTypes</code></a>. Binary files can no longer be dropped into CodeMirror</li>\n    <li>New themes: <a href=\"../demo/theme.html#bespin\">bespin</a>, <a href=\"../demo/theme.html#hopscotch\">hopscotch</a>, <a href=\"../demo/theme.html#isotope\">isotope</a>, <a href=\"../demo/theme.html#railscasts\">railscasts</a></li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.7.0...5.8.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">20-09-2015: <a href=\"https://codemirror.net/codemirror-5.7.zip\">Version 5.7</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/vue/index.html\">Vue</a>, <a href=\"../mode/oz/index.html\">Oz</a>, <a href=\"../mode/mscgen/index.html\">MscGen</a> (and dialects), <a href=\"../mode/css/gss.html\">Closure Stylesheets</a></li>\n    <li>Implement <a href=\"http://commonmark.org\">CommonMark</a>-style flexible list indent and cross-line code spans in <a href=\"../mode/markdown/index.html\">Markdown</a> mode</li>\n    <li>Add a replace-all button to the <a href=\"manual.html#addon_search\">search addon</a>, and make the persistent search dialog transparent when it obscures the match</li>\n    <li>Handle <code>acync</code>/<code>await</code> and ocal and binary numbers in <a href=\"../mode/javascript/index.html\">JavaScript mode</a></li>\n    <li>Fix various issues with the <a href=\"../mode/haxe/index.html\">Haxe mode</a></li>\n    <li>Make the <a href=\"manual.html#addon_closebrackets\">closebrackets addon</a> select only the wrapped text when wrapping selection in brackets</li>\n    <li>Tokenize properties as properties in the <a href=\"../mode/coffeescript/index.html\">CoffeeScript mode</a></li>\n    <li>The <a href=\"manual.html#addon_placeholder\">placeholder addon</a> now accepts a DOM node as well as a string placeholder</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.6.0...5.7.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">20-08-2015: <a href=\"https://codemirror.net/codemirror-5.6.zip\">Version 5.6</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix bug where you could paste into a <code>readOnly</code> editor</li>\n    <li>Show a cursor at the drop location when dragging over the editor</li>\n    <li>The <a href=\"../mode/rust/index.html\">Rust mode</a> was rewritten to handle modern Rust</li>\n    <li>The editor and theme CSS was cleaned up. Some selectors are now less specific than before</li>\n    <li>New theme: <a href=\"../demo/theme.html#abcdef\">abcdef</a></li>\n    <li>Lines longer than <a href=\"manual.html#option_maxHighlightLength\"><code>maxHighlightLength</code></a> are now less likely to mess up indentation</li>\n    <li>New addons: <a href=\"manual.html#addon_autorefresh\"><code>autorefresh</code></a> for refreshing an editor the first time it becomes visible, and <code>html-lint</code> for using <a href=\"http://htmlhint.com/\">HTMLHint</a></li>\n    <li>The <a href=\"manual.html#addon_search\"><code>search</code></a> addon now recognizes <code>\\r</code> and <code>\\n</code> in pattern and replacement input</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.5.0...5.6.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">20-07-2015: <a href=\"https://codemirror.net/codemirror-5.5.zip\">Version 5.5</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New option: <a href=\"manual.html#option_lineSeparator\"><code>lineSeparator</code></a> (with corresponding <a href=\"manual.html#lineSeparator\">method</a>)\n    <li>New themes: <a href=\"../demo/theme.html#dracula\">dracula</a>, <a href=\"../demo/theme.html#seti\">seti</a>, <a href=\"../demo/theme.html#yeti\">yeti</a>, <a href=\"../demo/theme.html#material\">material</a>, and <a href=\"../demo/theme.html#icecoder\">icecoder</a></li>\n    <li>New modes: <a href=\"../mode/brainfuck/index.html\">Brainfuck</a>, <a href=\"../mode/vhdl/index.html\">VHDL</a>, Squirrel (<a href=\"../mode/clike/index.html\">clike</a> dialect)</li>\n    <li>Define a <code>findPersistent</code> command in\n    the <a href=\"../demo/search.html\">search</a> addon, for a dialog\n    that stays open as you cycle through matches</li>\n    <li>From this release on, the NPM module doesn't include documentation and demos</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.4.0...5.5.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">25-06-2015: <a href=\"https://codemirror.net/codemirror-5.4.zip\">Version 5.4</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/twig/index.html\">Twig</a>, <a href=\"../mode/elm/index.html\">Elm</a>, <a href=\"../mode/factor/index.html\">Factor</a>, <a href=\"../mode/swift/index.html\">Swift</a></li>\n    <li>Prefer clipboard API (if available) when pasting</li>\n    <li>Refined definition highlighting in <a href=\"../mode/clike/index.html\">clike</a> mode</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.3.0...5.4.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">20-05-2015: <a href=\"https://codemirror.net/codemirror-5.3.zip\">Version 5.3</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix several regressions in the <a href=\"manual.html#addon_show-hint\"><code>show-hint</code></a> addon (<code>completeSingle</code> option, <code>\"shown\"</code> and <code>\"close\"</code> events)</li>\n    <li>The <a href=\"../demo/vim.html\">vim mode</a> API was <a href=\"manual.html#vimapi\">documented</a></li>\n    <li>New modes: <a href=\"../mode/asn.1/index.html\">ASN.1</a>, <a href=\"../mode/ttcn/index.html\">TTCN</a>, and <a href=\"../mode/ttcn-cfg/index.html\">TTCN-CFG</a></li>\n    <li>The <a href=\"../mode/clike/index.html\">clike</a> mode can now deep-indent <code>switch</code> statements, and roughly recognizes types and defined identifiers</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.2.0...5.3.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">20-04-2015: <a href=\"https://codemirror.net/codemirror-5.2.zip\">Version 5.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix several race conditions\n    in <a href=\"manual.html#addon_show-hint\"><code>show-hint</code></a>'s\n    asynchronous mode</li>\n    <li>Fix backspace binding in <a href=\"../demo/sublime.html\">Sublime bindings</a></li>\n    <li>Change the way IME is handled in the <code>\"textarea\"</code> <a href=\"manual.html#option_inputStyle\">input style</a></li>\n\n    <li>New modes: <a href=\"../mode/mumps/index.html\">MUMPS</a>, <a href=\"../mode/handlebars/index.html\">Handlebars</a></li>\n    <li>Rewritten modes: <a href=\"../mode/django/index.html\">Django</a>, <a href=\"../mode/z80/index.html\">Z80</a></li>\n    <li>New theme: <a href=\"../demo/theme.html#liquibyte\">Liquibyte</a></li>\n    <li>New option: <a href=\"manual.html#option_lineWiseCopyCut\"><code>lineWiseCopyCut</code></a></li>\n    <li>The <a href=\"../demo/vim.html\">Vim mode</a> now supports buffer-local options and the <code>filetype</code> setting</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.1.0...5.2.0\">list of patches</a></li>\n  </ul>\n\n  <p class=\"rel\">23-03-2015: <a href=\"https://codemirror.net/codemirror-5.1.zip\">Version 5.1</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/asciiarmor/index.html\">ASCII armor</a> (PGP data), <a href=\"../mode/troff/index.html\">Troff</a>, and <a href=\"../mode/cmake/index.html\">CMake</a>.</li>\n    <li>Remove SmartyMixed mode, rewrite <a href=\"../mode/smarty/index.html\">Smarty</a> mode to supersede it.</li>\n    <li>New commands in the <a href=\"manual.html#addon_merge\">merge\n    addon</a>: <code>goNextDiff</code> and <code>goPrevDiff</code>.</li>\n    <li>The <a href=\"manual.html#addon_closebrackets\">closebrackets addon</a> can now be configured per mode.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/5.0.0...5.1.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-02-2015: <a href=\"https://codemirror.net/codemirror-5.0.zip\">Version 5.0</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Experimental mobile support (tested on iOS, Android Chrome, stock Android browser)</li>\n    <li>New option <a href=\"manual.html#option_inputStyle\"><code>inputStyle</code></a> to switch between hidden textarea and contenteditable input.</li>\n    <li>The <a href=\"manual.html#getInputField\"><code>getInputField</code></a>\n    method is no longer guaranteed to return a textarea.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.13.0...5.0.0\">list of patches</a>.</li>\n  </ul>\n\n</section>\n\n<section id=v4 class=first>\n\n  <h2>Version 4.x</h2>\n\n  <p class=\"rel\">20-02-2015: <a href=\"https://codemirror.net/codemirror-4.13.zip\">Version 4.13</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix the way the <a href=\"../demo/closetag.html\"><code>closetag</code></a> demo handles the slash character.</li>\n    <li>New modes: <a href=\"../mode/forth/index.html\">Forth</a>, <a href=\"../mode/stylus/index.html\">Stylus</a>.</li>\n    <li>Make the <a href=\"../mode/css/index.html\">CSS mode</a> understand some modern CSS extensions.</li>\n    <li>Have the <a href=\"../mode/clike/index.html\">Scala mode</a> handle symbols and triple-quoted strings.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.12.0...4.13.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">22-01-2015: <a href=\"https://codemirror.net/codemirror-4.12.zip\">Version 4.12</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>The <a href=\"manual.html#addon_closetag\"><code>closetag</code></a>\n    addon now defines a <code>\"closeTag\"</code> command.</li>\n    <li>Adds a <code>findModeByFileName</code> to the <a href=\"manual.html#addon_meta\">mode metadata</a>\n    addon.</li>\n    <li><a href=\"../demo/simplemode.html\">Simple mode</a> rules can\n    now contain a <code>sol</code> property to only match at the start\n    of a line.</li>\n    <li>New\n    addon: <a href=\"manual.html#addon_selection-pointer\"><code>selection-pointer</code></a>\n    to style the mouse cursor over the selection.</li>\n    <li>Improvements to the <a href=\"../mode/sass/index.html\">Sass mode</a>'s indentation.</li>\n    <li>The <a href=\"../demo/vim.html\">Vim keymap</a>'s search functionality now\n    supports <a href=\"manual.html#addon_matchesonscrollbar\">scrollbar\n    annotation</a>.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.11.0...4.12.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">9-01-2015: <a href=\"https://codemirror.net/codemirror-4.11.zip\">Version 4.11</a>:</p>\n\n  <p class=\"rel-note\">Unfortunately, 4.10 did not take care of the\n  Firefox scrolling issue entirely. This release adds two more patches\n  to address that.</p>\n\n  <p class=\"rel\">29-12-2014: <a href=\"https://codemirror.net/codemirror-4.10.zip\">Version 4.10</a>:</p>\n\n  <p class=\"rel-note\">Emergency single-patch update to 4.9. Fixes\n  Firefox-specific problem where the cursor could end up behind the\n  horizontal scrollbar.</p>\n\n  <p class=\"rel\">23-12-2014: <a href=\"https://codemirror.net/codemirror-4.9.zip\">Version 4.9</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Overhauled scroll bar handling.\n    Add pluggable <a href=\"../demo/simplescrollbars.html\">scrollbar\n    implementations</a>.</li>\n    <li>Tweaked behavior for\n    the <a href=\"manual.html#addon_show-hint\">completion addons</a> to\n    not take text after cursor into account.</li>\n    <li>Two new optional features in\n    the <a href=\"manual.html#addon_merge\">merge addon</a>: aligning\n    editors, and folding unchanged text.</li>\n    <li>New\n    modes: <a href=\"../mode/dart/index.html\">Dart</a>, <a href=\"../mode/ebnf/index.html\">EBNF</a>, <a href=\"../mode/spreadsheet/index.html\">spreadsheet</a>,\n    and <a href=\"../mode/soy/index.html\">Soy</a>.</li>\n    <li>New <a href=\"../demo/panel.html\">addon</a> to show persistent panels below/above an editor.</li>\n    <li>New themes: <a href=\"../demo/theme.html#zenburn\">zenburn</a>\n    and <a href=\"../demo/theme.html#tomorrow-night-bright\">tomorrow night\n    bright</a>.</li>\n    <li>Allow ctrl-click to clear existing cursors.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.8.0...4.9.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">22-11-2014: <a href=\"https://codemirror.net/codemirror-4.8.zip\">Version 4.8</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Built-in support for <a href=\"manual.html#normalizeKeyMap\">multi-stroke key bindings</a>.</li>\n    <li>New method: <a href=\"manual.html#getLineTokens\"><code>getLineTokens</code></a>.</li>\n    <li>New modes: <a href=\"../mode/dockerfile/index.html\">dockerfile</a>, <a href=\"../mode/idl/index.html\">IDL</a>, <a href=\"../mode/clike/index.html\">Objective C</a> (crude).</li>\n    <li>Support styling of gutter backgrounds, allow <code>\"gutter\"</code> styles in <a href=\"manual.html#addLineClass\"><code>addLineClass</code></a>.</li>\n    <li>Many improvements to the <a href=\"../demo/vim.html\">Vim mode</a>, rewritten visual mode.</li>\n    <li>Improvements to modes: <a href=\"../mode/gfm/index.html\">gfm</a> (strikethrough), <a href=\"../mode/sparql/index.html\">SPARQL</a> (version 1.1 support), and <a href=\"../mode/stex/index.html\">sTeX</a> (no more runaway math mode).\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.7.0...4.8.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-10-2014: <a href=\"https://codemirror.net/codemirror-4.7.zip\">Version 4.7</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><strong>Incompatible</strong>:\n    The <a href=\"../demo/lint.html\">lint addon</a> now passes the\n    editor's value as first argument to asynchronous lint functions,\n    for consistency. The editor is still passed, as fourth\n    argument.</li>\n    <li>Improved handling of unicode identifiers in modes for\n    languages that support them.</li>\n    <li>More mode\n    improvements: <a href=\"../mode/coffeescript/index.html\">CoffeeScript</a>\n    (indentation), <a href=\"../mode/verilog/index.html\">Verilog</a>\n    (indentation), <a href=\"../mode/clike/index.html\">Scala</a>\n    (indentation, triple-quoted strings),\n    and <a href=\"../mode/php/index.html\">PHP</a> (interpolated\n    variables in heredoc strings).</li>\n    <li>New modes: <a href=\"../mode/textile/index.html\">Textile</a> and <a href=\"../mode/tornado/index.html\">Tornado templates</a>.</li>\n    <li>Experimental new <a href=\"../demo/simplemode.html\">way to define modes</a>.</li>\n    <li>Improvements to the <a href=\"../demo/vim.html\">Vim\n    bindings</a>: Arbitrary insert mode key mappings are now possible,\n    and text objects are supported in visual mode.</li>\n    <li>The mode <a href=\"../mode/meta.js\">meta-information file</a>\n    now includes information about file extensions,\n    and <a href=\"manual.html#addon_meta\">helper\n    functions</a> <code>findModeByMIME</code>\n    and <code>findModeByExtension</code>.</li>\n    <li>New logo!</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.6.0...4.7.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">19-09-2014: <a href=\"https://codemirror.net/codemirror-4.6.zip\">Version 4.6</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New mode: <a href=\"../mode/modelica/index.html\">Modelica</a></li>\n    <li>New method: <a href=\"manual.html#findWordAt\"><code>findWordAt</code></a></li>\n    <li>Make it easier to <a href=\"../demo/markselection.html\">use text background styling</a></li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.5.0...4.6.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">21-08-2014: <a href=\"https://codemirror.net/codemirror-4.5.zip\">Version 4.5</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix several serious bugs with horizontal scrolling</li>\n    <li>New mode: <a href=\"../mode/slim/index.html\">Slim</a></li>\n    <li>New command: <a href=\"manual.html#command_goLineLeftSmart\"><code>goLineLeftSmart</code></a></li>\n    <li>More fixes and extensions for the <a href=\"../demo/vim.html\">Vim</a> visual block mode</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.4.0...4.5.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">21-07-2014: <a href=\"https://codemirror.net/codemirror-4.4.zip\">Version 4.4</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><strong>Note:</strong> Some events might now fire in slightly\n    different order (<code>\"change\"</code> is still guaranteed to fire\n    before <code>\"cursorActivity\"</code>)</li>\n    <li>Nested operations in multiple editors are now synced (complete\n    at same time, reducing DOM reflows)</li>\n    <li>Visual block mode for <a href=\"../demo/vim.html\">vim</a> (&lt;C-v>) is nearly complete</li>\n    <li>New mode: <a href=\"../mode/kotlin/index.html\">Kotlin</a></li>\n    <li>Better multi-selection paste for text copied from multiple CodeMirror selections</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.3.0...4.4.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">23-06-2014: <a href=\"https://codemirror.net/codemirror-4.3.zip\">Version 4.3</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Several <a href=\"../demo/vim.html\">vim bindings</a>\n    improvements: search and exCommand history, global flag\n    for <code>:substitute</code>, <code>:global</code> command.\n    <li>Allow hiding the cursor by\n    setting <a href=\"manual.html#option_cursorBlinkRate\"><code>cursorBlinkRate</code></a>\n    to a negative value.</li>\n    <li>Make gutter markers themeable, use this in foldgutter.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.2.0...4.3.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">19-05-2014: <a href=\"https://codemirror.net/codemirror-4.2.zip\">Version 4.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix problem where some modes were broken by the fact that empty tokens were forbidden.</li>\n    <li>Several fixes to context menu handling.</li>\n    <li>On undo, scroll <em>change</em>, not cursor, into view.</li>\n    <li>Rewritten <a href=\"../mode/jade/index.html\">Jade</a> mode.</li>\n    <li>Various improvements to <a href=\"../mode/shell/index.html\">Shell</a> (support for more syntax) and <a href=\"../mode/python/index.html\">Python</a> (better indentation) modes.</li>\n    <li>New mode: <a href=\"../mode/cypher/index.html\">Cypher</a>.</li>\n    <li>New theme: <a href=\"../demo/theme.html#neo\">Neo</a>.</li>\n    <li>Support direct styling options (color, line style, width) in the <a href=\"manual.html#addon_rulers\">rulers</a> addon.</li>\n    <li>Recognize per-editor configuration for the <a href=\"manual.html#addon_show-hint\">show-hint</a> and <a href=\"manual.html#addon_foldcode\">foldcode</a> addons.</li>\n    <li>More intelligent scanning for existing close tags in <a href=\"manual.html#addon_closetag\">closetag</a> addon.</li>\n    <li>In the <a href=\"../demo/vim.html\">Vim bindings</a>: Fix bracket matching, support case conversion in visual mode, visual paste, append action.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.1.0...4.2.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">22-04-2014: <a href=\"https://codemirror.net/codemirror-4.1.zip\">Version 4.1</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><em>Slightly incompatible</em>:\n    The <a href=\"manual.html#event_cursorActivity\"><code>\"cursorActivity\"</code></a>\n    event now fires after all other events for the operation (and only\n    for handlers that were actually registered at the time the\n    activity happened).</li>\n    <li>New command: <a href=\"manual.html#command_insertSoftTab\"><code>insertSoftTab</code></a>.</li>\n    <li>New mode: <a href=\"../mode/django/index.html\">Django</a>.</li>\n    <li>Improved modes: <a href=\"../mode/verilog/index.html\">Verilog</a> (rewritten), <a href=\"../mode/jinja2/index.html\">Jinja2</a>, <a href=\"../mode/haxe/index.html\">Haxe</a>, <a href=\"../mode/php/index.html\">PHP</a> (string interpolation highlighted), <a href=\"../mode/javascript/index.html\">JavaScript</a> (indentation of trailing else, template strings), <a href=\"../mode/livescript/index.html\">LiveScript</a> (multi-line strings).</li>\n    <li>Many small issues from the 3.x→4.x transition were found and fixed.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/4.0.3...4.1.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-03-2014: <a href=\"https://codemirror.net/codemirror-4.0.zip\">Version 4.0</a>:</p>\n\n  <p class=\"rel-note\">This is a new major version of CodeMirror. There\n  are a few <strong>incompatible</strong> changes in the API. Upgrade\n  with care, and read the <a href=\"upgrade_v4.html\">upgrading\n  guide</a>.</p>\n\n  <ul class=\"rel-note\">\n    <li>Multiple selections (ctrl-click, alt-drag, <a href=\"manual.html#setSelections\">API</a>).</li>\n    <li>Sublime Text <a href=\"../demo/sublime.html\">bindings</a>.</li>\n    <li><a href=\"manual.html#modloader\">Module loader shims</a> wrapped around all modules.</li>\n    <li>Selection <a href=\"manual.html#command_undoSelection\">undo</a>/<a href=\"manual.html#command_redoSelection\">redo</a>.</li>\n    <li>Improved character measuring (faster, handles wrapped lines more robustly).</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/3.23.0...4.0.3\">list of patches</a>.</li>\n  </ul>\n\n</section>\n\n<section id=v3>\n\n  <h2>Version 3.x</h2>\n\n  <p class=\"rel\">22-04-2014: <a href=\"https://codemirror.net/codemirror-3.24.zip\">Version 3.24</a>:</p>\n\n  <p class=\"rel-note\">Merges the improvements from 4.1 that could\n  easily be applied to the 3.x code. Also improves the way the editor\n  size is updated when line widgets change.</p>\n\n  <p class=\"rel\">20-03-2014: <a href=\"https://codemirror.net/codemirror-3.23.zip\">Version 3.23</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>In the <a href=\"../mode/xml/index.html\">XML mode</a>,\n    add <code>brackets</code> style to angle brackets, fix\n    case-sensitivity of tags for HTML.</li>\n    <li>New mode: <a href=\"../mode/dylan/index.html\">Dylan</a>.</li>\n    <li>Many improvements to the <a href=\"../demo/vim.html\">Vim bindings</a>.</li>\n  </ul>\n\n  <p class=\"rel\">21-02-2014: <a href=\"https://codemirror.net/codemirror-3.22.zip\">Version 3.22</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Adds the <a href=\"manual.html#findMarks\"><code>findMarks</code></a> method.</li>\n    <li>New addons: <a href=\"manual.html#addon_rulers\">rulers</a>, markdown-fold, yaml-lint.</li>\n    <li>New theme: <a href=\"../demo/theme.html#mdn-like\">mdn-like</a>.</li>\n    <li>New mode: <a href=\"../mode/solr/index.html\">Solr</a>.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/3.21.0...3.22.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">16-01-2014: <a href=\"https://codemirror.net/codemirror-3.21.zip\">Version 3.21</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Auto-indenting a block will no longer add trailing whitespace to blank lines.</li>\n    <li>Marking text has a new option <a href=\"manual.html#markText\"><code>clearWhenEmpty</code></a> to control auto-removal.</li>\n    <li>Several bugfixes in the handling of bidirectional text.</li>\n    <li>The <a href=\"../mode/xml/index.html\">XML</a> and <a href=\"../mode/css/index.html\">CSS</a> modes were largely rewritten. <a href=\"../mode/css/less.html\">LESS</a> support was added to the CSS mode.</li>\n    <li>The OCaml mode was moved to an <a href=\"../mode/mllike/index.html\">mllike</a> mode, F# support added.</li>\n    <li>Make it possible to fetch multiple applicable helper values with <a href=\"manual.html#getHelpers\"><code>getHelpers</code></a>, and to register helpers matched on predicates with <a href=\"manual.html#registerGlobalHelper\"><code>registerGlobalHelper</code></a>.</li>\n    <li>New theme <a href=\"../demo/theme.html#pastel-on-dark\">pastel-on-dark</a>.</li>\n    <li>Better ECMAScript 6 support in <a href=\"../mode/javascript/index.html\">JavaScript</a> mode.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/3.20.0...3.21.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">21-11-2013: <a href=\"https://codemirror.net/codemirror-3.20.zip\">Version 3.20</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/julia/index.html\">Julia</a> and <a href=\"../mode/pegjs/index.html\">PEG.js</a>.</li>\n    <li>Support ECMAScript 6 in the <a href=\"../mode/javascript/index.html\">JavaScript mode</a>.</li>\n    <li>Improved indentation for the <a href=\"../mode/coffeescript/index.html\">CoffeeScript mode</a>.</li>\n    <li>Make non-printable-character representation <a href=\"manual.html#option_specialChars\">configurable</a>.</li>\n    <li>Add ‘notification’ functionality to <a href=\"manual.html#addon_dialog\">dialog</a> addon.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/3.19.0...3.20.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">21-10-2013: <a href=\"https://codemirror.net/codemirror-3.19.zip\">Version 3.19</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/eiffel/index.html\">Eiffel</a>, <a href=\"../mode/gherkin/index.html\">Gherkin</a>, <a href=\"../mode/sql/?mime=text/x-mssql\">MSSQL dialect</a>.</li>\n    <li>New addons: <a href=\"manual.html#addon_hardwrap\">hardwrap</a>, <a href=\"manual.html#addon_sql-hint\">sql-hint</a>.</li>\n    <li>New theme: <a href=\"../demo/theme.html#mbo\">MBO</a>.</li>\n    <li>Add <a href=\"manual.html#token_style_line\">support</a> for line-level styling from mode tokenizers.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/3.18.0...3.19.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">23-09-2013: <a href=\"https://codemirror.net/codemirror-3.18.zip\">Version 3.18</a>:</p>\n\n  <p class=\"rel-note\">Emergency release to fix a problem in 3.17\n  where <code>.setOption(\"lineNumbers\", false)</code> would raise an\n  error.</p>\n\n  <p class=\"rel\">23-09-2013: <a href=\"https://codemirror.net/codemirror-3.17.zip\">Version 3.17</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/fortran/index.html\">Fortran</a>, <a href=\"../mode/octave/index.html\">Octave</a> (Matlab), <a href=\"../mode/toml/index.html\">TOML</a>, and <a href=\"../mode/dtd/index.html\">DTD</a>.</li>\n    <li>New addons: <a href=\"../addon/lint/css-lint.js\"><code>css-lint</code></a>, <a href=\"manual.html#addon_css-hint\"><code>css-hint</code></a>.</li>\n    <li>Improve resilience to CSS 'frameworks' that globally mess up <code>box-sizing</code>.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/3.16.0...3.17.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">21-08-2013: <a href=\"https://codemirror.net/codemirror-3.16.zip\">Version 3.16</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>The whole codebase is now under a single <a href=\"../LICENSE\">license</a> file.</li>\n    <li>The project page was overhauled and redesigned.</li>\n    <li>New themes: <a href=\"../demo/theme.html#paraiso-dark\">Paraiso</a> (<a href=\"../demo/theme.html#paraiso-light\">light</a>), <a href=\"../demo/theme.html#the-matrix\">The Matrix</a>.</li>\n    <li>Improved interaction between themes and <a href=\"manual.html#addon_active-line\">active-line</a>/<a href=\"manual.html#addon_matchbrackets\">matchbrackets</a> addons.</li>\n    <li>New <a href=\"manual.html#addon_foldcode\">folding</a> function <code>CodeMirror.fold.comment</code>.</li>\n    <li>Added <a href=\"manual.html#addon_fullscreen\">fullscreen</a> addon.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/3.15.0...3.16.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">29-07-2013: <a href=\"https://codemirror.net/codemirror-3.15.zip\">Version 3.15</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/jade/index.html\">Jade</a>, <a href=\"../mode/nginx/index.html\">Nginx</a>.</li>\n    <li>New addons: <a href=\"../demo/tern.html\">Tern</a>, <a href=\"manual.html#addon_matchtags\">matchtags</a>, and <a href=\"manual.html#addon_foldgutter\">foldgutter</a>.</li>\n    <li>Introduced <a href=\"manual.html#getHelper\"><em>helper</em></a> concept (<a href=\"https://groups.google.com/forum/#!msg/codemirror/cOc0xvUUEUU/nLrX1-qnidgJ\">context</a>).</li>\n    <li>New method: <a href=\"manual.html#getModeAt\"><code>getModeAt</code></a>.</li>\n    <li>New themes: base16 <a href=\"../demo/theme.html#base16-dark\">dark</a>/<a href=\"../demo/theme.html#base16-light\">light</a>, 3024 <a href=\"../demo/theme.html#3024-night\">dark</a>/<a href=\"../demo/theme.html#3024-day\">light</a>, <a href=\"../demo/theme.html#tomorrow-night-eighties\">tomorrow-night</a>.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/3.14.0...3.15.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-06-2013: <a href=\"https://codemirror.net/codemirror-3.14.zip\">Version 3.14</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New\n    addons: <a href=\"manual.html#addon_trailingspace\">trailing\n    space highlight</a>, <a href=\"manual.html#addon_xml-hint\">XML\n    completion</a> (rewritten),\n    and <a href=\"manual.html#addon_merge\">diff merging</a>.</li>\n    <li><a href=\"manual.html#markText\"><code>markText</code></a>\n    and <a href=\"manual.html#addLineWidget\"><code>addLineWidget</code></a>\n    now take a <code>handleMouseEvents</code> option.</li>\n    <li>New methods: <a href=\"manual.html#lineAtHeight\"><code>lineAtHeight</code></a>,\n    <a href=\"manual.html#getTokenTypeAt\"><code>getTokenTypeAt</code></a>.</li>\n    <li>More precise cleanness-tracking\n    using <a href=\"manual.html#changeGeneration\"><code>changeGeneration</code></a>\n    and <a href=\"manual.html#isClean\"><code>isClean</code></a>.</li>\n    <li>Many extensions to <a href=\"../demo/emacs.html\">Emacs</a> mode\n    (prefixes, more navigation units, and more).</li>\n    <li>New\n    events <a href=\"manual.html#event_keyHandled\"><code>\"keyHandled\"</code></a>\n    and <a href=\"manual.html#event_inputRead\"><code>\"inputRead\"</code></a>.</li>\n    <li>Various improvements to <a href=\"../mode/ruby/index.html\">Ruby</a>,\n    <a href=\"../mode/smarty/index.html\">Smarty</a>, <a href=\"../mode/sql/index.html\">SQL</a>,\n    and <a href=\"../demo/vim.html\">Vim</a> modes.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/3.13.0...3.14.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-05-2013: <a href=\"https://codemirror.net/codemirror-3.13.zip\">Version 3.13</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/cobol/index.html\">COBOL</a> and <a href=\"../mode/haml/index.html\">HAML</a>.</li>\n    <li>New options: <a href=\"manual.html#option_cursorScrollMargin\"><code>cursorScrollMargin</code></a> and <a href=\"manual.html#option_coverGutterNextToScrollbar\"><code>coverGutterNextToScrollbar</code></a>.</li>\n    <li>New addon: <a href=\"manual.html#addon_comment\">commenting</a>.</li>\n    <li>More features added to the <a href=\"../demo/vim.html\">Vim keymap</a>.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v3.12...3.13.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">19-04-2013: <a href=\"https://codemirror.net/codemirror-3.12.zip\">Version 3.12</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New mode: <a href=\"../mode/gas/index.html\">GNU assembler</a>.</li>\n    <li>New\n    options: <a href=\"manual.html#option_maxHighlightLength\"><code>maxHighlightLength</code></a>\n    and <a href=\"manual.html#option_historyEventDelay\"><code>historyEventDelay</code></a>.</li>\n    <li>Added <a href=\"manual.html#mark_addToHistory\"><code>addToHistory</code></a>\n    option for <code>markText</code>.</li>\n    <li>Various fixes to JavaScript tokenization and indentation corner cases.</li>\n    <li>Further improvements to the vim mode.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v3.11...v3.12\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-03-2013: <a href=\"https://codemirror.net/codemirror-3.11.zip\">Version 3.11</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><strong>Removed code:</strong> <code>collapserange</code>,\n    <code>formatting</code>, and <code>simple-hint</code>\n    addons. <code>plsql</code> and <code>mysql</code> modes\n    (use <a href=\"../mode/sql/index.html\"><code>sql</code></a> mode).</li>\n    <li><strong>Moved code:</strong> the range-finding functions for folding now have <a href=\"../addon/fold/\">their own files</a>.</li>\n    <li><strong>Changed interface:</strong>\n    the <a href=\"manual.html#addon_continuecomment\"><code>continuecomment</code></a>\n    addon now exposes an option, rather than a command.</li>\n    <li>New\n    modes: <a href=\"../mode/css/scss.html\">SCSS</a>, <a href=\"../mode/tcl/index.html\">Tcl</a>, <a href=\"../mode/livescript/index.html\">LiveScript</a>,\n    and <a href=\"../mode/mirc/index.html\">mIRC</a>.</li>\n    <li>New addons: <a href=\"../demo/placeholder.html\"><code>placeholder</code></a>, <a href=\"../demo/html5complete.html\">HTML completion</a>.</li>\n    <li>New\n    methods: <a href=\"manual.html#hasFocus\"><code>hasFocus</code></a>, <a href=\"manual.html#defaultCharWidth\"><code>defaultCharWidth</code></a>.</li>\n    <li>New events: <a href=\"manual.html#event_beforeCursorEnter\"><code>beforeCursorEnter</code></a>, <a href=\"manual.html#event_renderLine\"><code>renderLine</code></a>.</li>\n    <li>Many improvements to the <a href=\"manual.html#addon_show-hint\"><code>show-hint</code></a> completion\n    dialog addon.</li>\n    <li>Tweak behavior of by-word cursor motion.</li>\n    <li>Further improvements to the <a href=\"../demo/vim.html\">vim mode</a>.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v3.1...v3.11\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">21-02-2013: <a href=\"https://codemirror.net/codemirror-3.1.zip\">Version 3.1</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><strong>Incompatible:</strong> key handlers may\n    now <em>return</em>, rather\n    than <em>throw</em> <code>CodeMirror.Pass</code> to signal they\n    didn't handle the key.</li>\n    <li>Make documents a <a href=\"manual.html#api_doc\">first-class\n    construct</a>, support split views and subviews.</li>\n    <li>Add a <a href=\"manual.html#addon_show-hint\">new module</a>\n    for showing completion hints.\n    Deprecate <code>simple-hint.js</code>.</li>\n    <li>Extend <a href=\"../mode/htmlmixed/index.html\">htmlmixed mode</a>\n    to allow custom handling of script types.</li>\n    <li>Support an <code>insertLeft</code> option\n    to <a href=\"manual.html#setBookmark\"><code>setBookmark</code></a>.</li>\n    <li>Add an <a href=\"manual.html#eachLine\"><code>eachLine</code></a>\n    method to iterate over a document.</li>\n    <li>New addon modules: <a href=\"../demo/markselection.html\">selection\n    marking</a>, <a href=\"../demo/lint.html\">linting</a>,\n    and <a href=\"../demo/closebrackets.html\">automatic bracket\n    closing</a>.</li>\n    <li>Add <a href=\"manual.html#event_beforeChange\"><code>\"beforeChange\"</code></a>\n    and <a href=\"manual.html#event_beforeSelectionChange\"><code>\"beforeSelectionChange\"</code></a>\n    events.</li>\n    <li>Add <a href=\"manual.html#event_hide\"><code>\"hide\"</code></a>\n    and <a href=\"manual.html#event_unhide\"><code>\"unhide\"</code></a>\n    events to marked ranges.</li>\n    <li>Fix <a href=\"manual.html#coordsChar\"><code>coordsChar</code></a>'s\n    interpretation of its argument to match the documentation.</li>\n    <li>New modes: <a href=\"../mode/turtle/index.html\">Turtle</a>\n    and <a href=\"../mode/q/index.html\">Q</a>.</li>\n    <li>Further improvements to the <a href=\"../demo/vim.html\">vim mode</a>.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v3.01...v3.1\">list of patches</a>.</li>\n  </ul>\n\n\n  <p class=\"rel\">25-01-2013: <a href=\"https://codemirror.net/codemirror-3.02.zip\">Version 3.02</a>:</p>\n\n  <p class=\"rel-note\">Single-bugfix release. Fixes a problem that\n  prevents CodeMirror instances from being garbage-collected after\n  they become unused.</p>\n\n  <p class=\"rel\">21-01-2013: <a href=\"https://codemirror.net/codemirror-3.01.zip\">Version 3.01</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Move all add-ons into an organized directory structure\n    under <a href=\"../addon/\"><code>/addon</code></a>. <strong>You might have to adjust your\n    paths.</strong></li>\n    <li>New\n    modes: <a href=\"../mode/d/index.html\">D</a>, <a href=\"../mode/sass/index.html\">Sass</a>, <a href=\"../mode/apl/index.html\">APL</a>, <a href=\"../mode/sql/index.html\">SQL</a>\n    (configurable), and <a href=\"../mode/asterisk/index.html\">Asterisk</a>.</li>\n    <li>Several bugfixes in right-to-left text support.</li>\n    <li>Add <a href=\"manual.html#option_rtlMoveVisually\"><code>rtlMoveVisually</code></a> option.</li>\n    <li>Improvements to vim keymap.</li>\n    <li>Add built-in (lightweight) <a href=\"manual.html#addOverlay\">overlay mode</a> support.</li>\n    <li>Support <code>showIfHidden</code> option for <a href=\"manual.html#addLineWidget\">line widgets</a>.</li>\n    <li>Add simple <a href=\"manual.html#addon_python-hint\">Python hinter</a>.</li>\n    <li>Bring back the <a href=\"manual.html#option_fixedGutter\"><code>fixedGutter</code></a> option.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v3.0...v3.01\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">10-12-2012: <a href=\"https://codemirror.net/codemirror-3.0.zip\">Version 3.0</a>:</p>\n\n  <p class=\"rel-note\"><strong>New major version</strong>. Only\n  partially backwards-compatible. See\n  the <a href=\"upgrade_v3.html\">upgrading guide</a> for more\n  information. Changes since release candidate 2:</p>\n\n  <ul class=\"rel-note\">\n    <li>Rewritten VIM mode.</li>\n    <li>Fix a few minor scrolling and sizing issues.</li>\n    <li>Work around Safari segfault when dragging.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v3.0rc2...v3.0\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-11-2012: <a href=\"https://codemirror.net/codemirror-3.0rc2.zip\">Version 3.0, release candidate 2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New mode: <a href=\"../mode/http/index.html\">HTTP</a>.</li>\n    <li>Improved handling of selection anchor position.</li>\n    <li>Improve IE performance on longer lines.</li>\n    <li>Reduce gutter glitches during horiz. scrolling.</li>\n    <li>Add <a href=\"manual.html#addKeyMap\"><code>addKeyMap</code></a> and <a href=\"manual.html#removeKeyMap\"><code>removeKeyMap</code></a> methods.</li>\n    <li>Rewrite <code>formatting</code> and <code>closetag</code> add-ons.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v3.0rc1...v3.0rc2\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-11-2012: <a href=\"https://codemirror.net/codemirror-3.0rc1.zip\">Version 3.0, release candidate 1</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New theme: <a href=\"../demo/theme.html#solarized%20light\">Solarized</a>.</li>\n    <li>Introduce <a href=\"manual.html#addLineClass\"><code>addLineClass</code></a>\n    and <a href=\"manual.html#removeLineClass\"><code>removeLineClass</code></a>,\n    drop <code>setLineClass</code>.</li>\n    <li>Add a <em>lot</em> of\n    new <a href=\"manual.html#markText\">options for marked text</a>\n    (read-only, atomic, collapsed, widget replacement).</li>\n    <li>Remove the old code folding interface in favour of these new ranges.</li>\n    <li>Add <a href=\"manual.html#isClean\"><code>isClean</code></a>/<a href=\"manual.html#markClean\"><code>markClean</code></a> methods.</li>\n    <li>Remove <code>compoundChange</code> method, use better undo-event-combining heuristic.</li>\n    <li>Improve scrolling performance smoothness.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v3.0beta2...v3.0rc1\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">22-10-2012: <a href=\"https://codemirror.net/codemirror-3.0beta2.zip\">Version 3.0, beta 2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Fix page-based coordinate computation.</li>\n    <li>Fix firing of <a href=\"manual.html#event_gutterClick\"><code>gutterClick</code></a> event.</li>\n    <li>Add <a href=\"manual.html#option_cursorHeight\"><code>cursorHeight</code></a> option.</li>\n    <li>Fix bi-directional text regression.</li>\n    <li>Add <a href=\"manual.html#option_viewportMargin\"><code>viewportMargin</code></a> option.</li>\n    <li>Directly handle mousewheel events (again, hopefully better).</li>\n    <li>Make vertical cursor movement more robust (through widgets, big line gaps).</li>\n    <li>Add <a href=\"manual.html#option_flattenSpans\"><code>flattenSpans</code></a> option.</li>\n    <li>Many optimizations. Poor responsiveness should be fixed.</li>\n    <li>Initialization in hidden state works again.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v3.0beta1...v3.0beta2\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">19-09-2012: <a href=\"https://codemirror.net/codemirror-3.0beta1.zip\">Version 3.0, beta 1</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Bi-directional text support.</li>\n    <li>More powerful gutter model.</li>\n    <li>Support for arbitrary text/widget height.</li>\n    <li>In-line widgets.</li>\n    <li>Generalized event handling.</li>\n  </ul>\n\n</section>\n\n<section id=v2>\n\n  <h2>Version 2.x</h2>\n\n  <p class=\"rel\">21-01-2013: <a href=\"https://codemirror.net/codemirror-2.38.zip\">Version 2.38</a>:</p>\n\n  <p class=\"rel-note\">Integrate some bugfixes, enhancements to the vim keymap, and new\n  modes\n  (<a href=\"../mode/d/index.html\">D</a>, <a href=\"../mode/sass/index.html\">Sass</a>, <a href=\"../mode/apl/index.html\">APL</a>)\n  from the v3 branch.</p>\n\n  <p class=\"rel\">20-12-2012: <a href=\"https://codemirror.net/codemirror-2.37.zip\">Version 2.37</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New mode: <a href=\"../mode/sql/index.html\">SQL</a> (will replace <a href=\"../mode/plsql/index.html\">plsql</a> and <a href=\"../mode/mysql/index.html\">mysql</a> modes).</li>\n    <li>Further work on the new VIM mode.</li>\n    <li>Fix Cmd/Ctrl keys on recent Operas on OS X.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v2.36...v2.37\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">20-11-2012: <a href=\"https://codemirror.net/codemirror-2.36.zip\">Version 2.36</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New mode: <a href=\"../mode/z80/index.html\">Z80 assembly</a>.</li>\n    <li>New theme: <a href=\"../demo/theme.html#twilight\">Twilight</a>.</li>\n    <li>Add command-line compression helper.</li>\n    <li>Make <a href=\"manual.html#scrollIntoView\"><code>scrollIntoView</code></a> public.</li>\n    <li>Add <a href=\"manual.html#defaultTextHeight\"><code>defaultTextHeight</code></a> method.</li>\n    <li>Various extensions to the vim keymap.</li>\n    <li>Make <a href=\"../mode/php/index.html\">PHP mode</a> build on <a href=\"../mode/htmlmixed/index.html\">mixed HTML mode</a>.</li>\n    <li>Add <a href=\"manual.html#addon_continuecomment\">comment-continuing</a> add-on.</li>\n    <li>Full <a href=\"../https://github.com/codemirror/CodeMirror/compare/v2.35...v2.36\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">22-10-2012: <a href=\"https://codemirror.net/codemirror-2.35.zip\">Version 2.35</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New (sub) mode: <a href=\"../mode/javascript/typescript.html\">TypeScript</a>.</li>\n    <li>Don't overwrite (insert key) when pasting.</li>\n    <li>Fix several bugs in <a href=\"manual.html#markText\"><code>markText</code></a>/undo interaction.</li>\n    <li>Better indentation of JavaScript code without semicolons.</li>\n    <li>Add <a href=\"manual.html#defineInitHook\"><code>defineInitHook</code></a> function.</li>\n    <li>Full <a href=\"https://github.com/codemirror/CodeMirror/compare/v2.34...v2.35\">list of patches</a>.</li>\n  </ul>\n\n  <p class=\"rel\">19-09-2012: <a href=\"https://codemirror.net/codemirror-2.34.zip\">Version 2.34</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New mode: <a href=\"../mode/commonlisp/index.html\">Common Lisp</a>.</li>\n    <li>Fix right-click select-all on most browsers.</li>\n    <li>Change the way highlighting happens:<br>&nbsp; Saves memory and CPU cycles.<br>&nbsp; <code>compareStates</code> is no longer needed.<br>&nbsp; <code>onHighlightComplete</code> no longer works.</li>\n    <li>Integrate mode (Markdown, XQuery, CSS, sTex) tests in central testsuite.</li>\n    <li>Add a <a href=\"manual.html#version\"><code>CodeMirror.version</code></a> property.</li>\n    <li>More robust handling of nested modes in <a href=\"../demo/formatting.html\">formatting</a> and <a href=\"../demo/closetag.html\">closetag</a> plug-ins.</li>\n    <li>Un/redo now preserves <a href=\"manual.html#markText\">marked text</a> and bookmarks.</li>\n    <li><a href=\"https://github.com/codemirror/CodeMirror/compare/v2.33...v2.34\">Full list</a> of patches.</li>\n  </ul>\n\n  <p class=\"rel\">23-08-2012: <a href=\"https://codemirror.net/codemirror-2.33.zip\">Version 2.33</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New mode: <a href=\"../mode/sieve/index.html\">Sieve</a>.</li>\n    <li>New <a href=\"manual.html#getViewport\"><code>getViewPort</code></a> and <a href=\"manual.html#option_onViewportChange\"><code>onViewportChange</code></a> API.</li>\n    <li><a href=\"manual.html#option_cursorBlinkRate\">Configurable</a> cursor blink rate.</li>\n    <li>Make binding a key to <code>false</code> disabling handling (again).</li>\n    <li>Show non-printing characters as red dots.</li>\n    <li>More tweaks to the scrolling model.</li>\n    <li>Expanded testsuite. Basic linter added.</li>\n    <li>Remove most uses of <code>innerHTML</code>. Remove <code>CodeMirror.htmlEscape</code>.</li>\n    <li><a href=\"https://github.com/codemirror/CodeMirror/compare/v2.32...v2.33\">Full list</a> of patches.</li>\n  </ul>\n\n  <p class=\"rel\">23-07-2012: <a href=\"https://codemirror.net/codemirror-2.32.zip\">Version 2.32</a>:</p>\n\n  <p class=\"rel-note\">Emergency fix for a bug where an editor with\n  line wrapping on IE will break when there is <em>no</em>\n  scrollbar.</p>\n\n  <p class=\"rel\">20-07-2012: <a href=\"https://codemirror.net/codemirror-2.31.zip\">Version 2.31</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New modes: <a href=\"../mode/ocaml/index.html\">OCaml</a>, <a href=\"../mode/haxe/index.html\">Haxe</a>, and <a href=\"../mode/vb/index.html\">VB.NET</a>.</li>\n    <li>Several fixes to the new scrolling model.</li>\n    <li>Add a <a href=\"manual.html#setSize\"><code>setSize</code></a> method for programmatic resizing.</li>\n    <li>Add <a href=\"manual.html#getHistory\"><code>getHistory</code></a> and <a href=\"manual.html#setHistory\"><code>setHistory</code></a> methods.</li>\n    <li>Allow custom line separator string in <a href=\"manual.html#getValue\"><code>getValue</code></a> and <a href=\"manual.html#getRange\"><code>getRange</code></a>.</li>\n    <li>Support double- and triple-click drag, double-clicking whitespace.</li>\n    <li>And more... <a href=\"https://github.com/codemirror/CodeMirror/compare/v2.3...v2.31\">(all patches)</a></li>\n  </ul>\n\n  <p class=\"rel\">22-06-2012: <a href=\"https://codemirror.net/codemirror-2.3.zip\">Version 2.3</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><strong>New scrollbar implementation</strong>. Should flicker less. Changes DOM structure of the editor.</li>\n    <li>New theme: <a href=\"../demo/theme.html#vibrant-ink\">vibrant-ink</a>.</li>\n    <li>Many extensions to the VIM keymap (including text objects).</li>\n    <li>Add <a href=\"../demo/multiplex.html\">mode-multiplexing</a> utility script.</li>\n    <li>Fix bug where right-click paste works in read-only mode.</li>\n    <li>Add a <a href=\"manual.html#getScrollInfo\"><code>getScrollInfo</code></a> method.</li>\n    <li>Lots of other <a href=\"https://github.com/codemirror/CodeMirror/compare/v2.25...v2.3\">fixes</a>.</li>\n  </ul>\n\n  <p class=\"rel\">23-05-2012: <a href=\"https://codemirror.net/codemirror-2.25.zip\">Version 2.25</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>New mode: <a href=\"../mode/erlang/index.html\">Erlang</a>.</li>\n    <li><strong>Remove xmlpure mode</strong> (use <a href=\"../mode/xml/index.html\">xml.js</a>).</li>\n    <li>Fix line-wrapping in Opera.</li>\n    <li>Fix X Windows middle-click paste in Chrome.</li>\n    <li>Fix bug that broke pasting of huge documents.</li>\n    <li>Fix backspace and tab key repeat in Opera.</li>\n  </ul>\n\n  <p class=\"rel\">23-04-2012: <a href=\"https://codemirror.net/codemirror-2.24.zip\">Version 2.24</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li><strong>Drop support for Internet Explorer 6</strong>.</li>\n    <li>New\n    modes: <a href=\"../mode/shell/index.html\">Shell</a>, <a href=\"../mode/tiki/index.html\">Tiki\n    wiki</a>, <a href=\"../mode/pig/index.html\">Pig Latin</a>.</li>\n    <li>New themes: <a href=\"../demo/theme.html#ambiance\">Ambiance</a>, <a href=\"../demo/theme.html#blackboard\">Blackboard</a>.</li>\n    <li>More control over drag/drop\n    with <a href=\"manual.html#option_dragDrop\"><code>dragDrop</code></a>\n    and <a href=\"manual.html#option_onDragEvent\"><code>onDragEvent</code></a>\n    options.</li>\n    <li>Make HTML mode a bit less pedantic.</li>\n    <li>Add <a href=\"manual.html#compoundChange\"><code>compoundChange</code></a> API method.</li>\n    <li>Several fixes in undo history and line hiding.</li>\n    <li>Remove (broken) support for <code>catchall</code> in key maps,\n    add <code>nofallthrough</code> boolean field instead.</li>\n  </ul>\n\n  <p class=\"rel\">26-03-2012: <a href=\"https://codemirror.net/codemirror-2.23.zip\">Version 2.23</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Change <strong>default binding for tab</strong> <a href=\"javascript:void(document.getElementById('tabbinding').style.display='')\">[more]</a>\n      <div style=\"display: none\" id=tabbinding>\n        Starting in 2.23, these bindings are default:\n        <ul><li>Tab: Insert tab character</li>\n          <li>Shift-tab: Reset line indentation to default</li>\n          <li>Ctrl/Cmd-[: Reduce line indentation (old tab behaviour)</li>\n          <li>Ctrl/Cmd-]: Increase line indentation (old shift-tab behaviour)</li>\n        </ul>\n      </div>\n    </li>\n    <li>New modes: <a href=\"../mode/xquery/index.html\">XQuery</a> and <a href=\"../mode/vbscript/index.html\">VBScript</a>.</li>\n    <li>Two new themes: <a href=\"../mode/less/index.html\">lesser-dark</a> and <a href=\"../mode/xquery/index.html\">xq-dark</a>.</li>\n    <li>Differentiate between background and text styles in <a href=\"manual.html#setLineClass\"><code>setLineClass</code></a>.</li>\n    <li>Fix drag-and-drop in IE9+.</li>\n    <li>Extend <a href=\"manual.html#charCoords\"><code>charCoords</code></a>\n    and <a href=\"manual.html#cursorCoords\"><code>cursorCoords</code></a> with a <code>mode</code> argument.</li>\n    <li>Add <a href=\"manual.html#option_autofocus\"><code>autofocus</code></a> option.</li>\n    <li>Add <a href=\"manual.html#findMarksAt\"><code>findMarksAt</code></a> method.</li>\n  </ul>\n\n  <p class=\"rel\">27-02-2012: <a href=\"https://codemirror.net/codemirror-2.22.zip\">Version 2.22</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Allow <a href=\"manual.html#keymaps\">key handlers</a> to pass up events, allow binding characters.</li>\n    <li>Add <a href=\"manual.html#option_autoClearEmptyLines\"><code>autoClearEmptyLines</code></a> option.</li>\n    <li>Properly use tab stops when rendering tabs.</li>\n    <li>Make PHP mode more robust.</li>\n    <li>Support indentation blocks in <a href=\"manual.html#addon_foldcode\">code folder</a>.</li>\n    <li>Add a script for <a href=\"manual.html#addon_match-highlighter\">highlighting instances of the selection</a>.</li>\n    <li>New <a href=\"../mode/properties/index.html\">.properties</a> mode.</li>\n    <li>Fix many bugs.</li>\n  </ul>\n\n  <p class=\"rel\">27-01-2012: <a href=\"https://codemirror.net/codemirror-2.21.zip\">Version 2.21</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Added <a href=\"../mode/less/index.html\">LESS</a>, <a href=\"../mode/mysql/index.html\">MySQL</a>,\n    <a href=\"../mode/go/index.html\">Go</a>, and <a href=\"../mode/verilog/index.html\">Verilog</a> modes.</li>\n    <li>Add <a href=\"manual.html#option_smartIndent\"><code>smartIndent</code></a>\n    option.</li>\n    <li>Support a cursor in <a href=\"manual.html#option_readOnly\"><code>readOnly</code></a>-mode.</li>\n    <li>Support assigning multiple styles to a token.</li>\n    <li>Use a new approach to drawing the selection.</li>\n    <li>Add <a href=\"manual.html#scrollTo\"><code>scrollTo</code></a> method.</li>\n    <li>Allow undo/redo events to span non-adjacent lines.</li>\n    <li>Lots and lots of bugfixes.</li>\n  </ul>\n\n  <p class=\"rel\">20-12-2011: <a href=\"https://codemirror.net/codemirror-2.2.zip\">Version 2.2</a>:</p>\n\n  <ul class=\"rel-note\">\n    <li>Slightly incompatible API changes. Read <a href=\"upgrade_v2.2.html\">this</a>.</li>\n    <li>New approach\n    to <a href=\"manual.html#option_extraKeys\">binding</a> keys,\n    support for <a href=\"manual.html#option_keyMap\">custom\n    bindings</a>.</li>\n    <li>Support for overwrite (insert).</li>\n    <li><a href=\"manual.html#option_tabSize\">Custom-width</a>\n    and <a href=\"../demo/visibletabs.html\">stylable</a> tabs.</li>\n    <li>Moved more code into <a href=\"manual.html#addons\">add-on scripts</a>.</li>\n    <li>Support for sane vertical cursor movement in wrapped lines.</li>\n    <li>More reliable handling of\n    editing <a href=\"manual.html#markText\">marked text</a>.</li>\n    <li>Add minimal <a href=\"../demo/emacs.html\">emacs</a>\n    and <a href=\"../demo/vim.html\">vim</a> bindings.</li>\n    <li>Rename <code>coordsFromIndex</code>\n    to <a href=\"manual.html#posFromIndex\"><code>posFromIndex</code></a>,\n    add <a href=\"manual.html#indexFromPos\"><code>indexFromPos</code></a>\n    method.</li>\n  </ul>\n\n  <p class=\"rel\">21-11-2011: <a href=\"https://codemirror.net/codemirror-2.18.zip\">Version 2.18</a>:</p>\n  <p class=\"rel-note\">Fixes <code>TextMarker.clear</code>, which is broken in 2.17.</p>\n\n  <p class=\"rel\">21-11-2011: <a href=\"https://codemirror.net/codemirror-2.17.zip\">Version 2.17</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add support for <a href=\"manual.html#option_lineWrapping\">line\n    wrapping</a> and <a href=\"manual.html#hideLine\">code\n    folding</a>.</li>\n    <li>Add <a href=\"../mode/gfm/index.html\">Github-style Markdown</a> mode.</li>\n    <li>Add <a href=\"../theme/monokai.css\">Monokai</a>\n    and <a href=\"../theme/rubyblue.css\">Rubyblue</a> themes.</li>\n    <li>Add <a href=\"manual.html#setBookmark\"><code>setBookmark</code></a> method.</li>\n    <li>Move some of the demo code into reusable components\n    under <a href=\"../addon/\"><code>lib/util</code></a>.</li>\n    <li>Make screen-coord-finding code faster and more reliable.</li>\n    <li>Fix drag-and-drop in Firefox.</li>\n    <li>Improve support for IME.</li>\n    <li>Speed up content rendering.</li>\n    <li>Fix browser's built-in search in Webkit.</li>\n    <li>Make double- and triple-click work in IE.</li>\n    <li>Various fixes to modes.</li>\n  </ul>\n\n  <p class=\"rel\">27-10-2011: <a href=\"https://codemirror.net/codemirror-2.16.zip\">Version 2.16</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add <a href=\"../mode/perl/index.html\">Perl</a>, <a href=\"../mode/rust/index.html\">Rust</a>, <a href=\"../mode/tiddlywiki/index.html\">TiddlyWiki</a>, and <a href=\"../mode/groovy/index.html\">Groovy</a> modes.</li>\n    <li>Dragging text inside the editor now moves, rather than copies.</li>\n    <li>Add a <a href=\"manual.html#coordsFromIndex\"><code>coordsFromIndex</code></a> method.</li>\n    <li><strong>API change</strong>: <code>setValue</code> now no longer clears history. Use <a href=\"manual.html#clearHistory\"><code>clearHistory</code></a> for that.</li>\n    <li><strong>API change</strong>: <a href=\"manual.html#markText\"><code>markText</code></a> now\n    returns an object with <code>clear</code> and <code>find</code>\n    methods. Marked text is now more robust when edited.</li>\n    <li>Fix editing code with tabs in Internet Explorer.</li>\n  </ul>\n\n  <p class=\"rel\">26-09-2011: <a href=\"https://codemirror.net/codemirror-2.15.zip\">Version 2.15</a>:</p>\n  <p class=\"rel-note\">Fix bug that snuck into 2.14: Clicking the\n  character that currently has the cursor didn't re-focus the\n  editor.</p>\n\n  <p class=\"rel\">26-09-2011: <a href=\"https://codemirror.net/codemirror-2.14.zip\">Version 2.14</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add <a href=\"../mode/clojure/index.html\">Clojure</a>, <a href=\"../mode/pascal/index.html\">Pascal</a>, <a href=\"../mode/ntriples/index.html\">NTriples</a>, <a href=\"../mode/jinja2/index.html\">Jinja2</a>, and <a href=\"../mode/markdown/index.html\">Markdown</a> modes.</li>\n    <li>Add <a href=\"../theme/cobalt.css\">Cobalt</a> and <a href=\"../theme/eclipse.css\">Eclipse</a> themes.</li>\n    <li>Add a <a href=\"manual.html#option_fixedGutter\"><code>fixedGutter</code></a> option.</li>\n    <li>Fix bug with <code>setValue</code> breaking cursor movement.</li>\n    <li>Make gutter updates much more efficient.</li>\n    <li>Allow dragging of text out of the editor (on modern browsers).</li>\n  </ul>\n\n\n  <p class=\"rel\">23-08-2011: <a href=\"https://codemirror.net/codemirror-2.13.zip\">Version 2.13</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add <a href=\"../mode/ruby/index.html\">Ruby</a>, <a href=\"../mode/r/index.html\">R</a>, <a href=\"../mode/coffeescript/index.html\">CoffeeScript</a>, and <a href=\"../mode/velocity/index.html\">Velocity</a> modes.</li>\n    <li>Add <a href=\"manual.html#getGutterElement\"><code>getGutterElement</code></a> to API.</li>\n    <li>Several fixes to scrolling and positioning.</li>\n    <li>Add <a href=\"manual.html#option_smartHome\"><code>smartHome</code></a> option.</li>\n    <li>Add an experimental <a href=\"../mode/xmlpure/index.html\">pure XML</a> mode.</li>\n  </ul>\n\n  <p class=\"rel\">25-07-2011: <a href=\"https://codemirror.net/codemirror-2.12.zip\">Version 2.12</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add a <a href=\"../mode/sparql/index.html\">SPARQL</a> mode.</li>\n    <li>Fix bug with cursor jumping around in an unfocused editor in IE.</li>\n    <li>Allow key and mouse events to bubble out of the editor. Ignore widget clicks.</li>\n    <li>Solve cursor flakiness after undo/redo.</li>\n    <li>Fix block-reindent ignoring the last few lines.</li>\n    <li>Fix parsing of multi-line attrs in XML mode.</li>\n    <li>Use <code>innerHTML</code> for HTML-escaping.</li>\n    <li>Some fixes to indentation in C-like mode.</li>\n    <li>Shrink horiz scrollbars when long lines removed.</li>\n    <li>Fix width feedback loop bug that caused the width of an inner DIV to shrink.</li>\n  </ul>\n\n  <p class=\"rel\">04-07-2011: <a href=\"https://codemirror.net/codemirror-2.11.zip\">Version 2.11</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add a <a href=\"../mode/scheme/index.html\">Scheme mode</a>.</li>\n    <li>Add a <code>replace</code> method to search cursors, for cursor-preserving replacements.</li>\n    <li>Make the <a href=\"../mode/clike/index.html\">C-like mode</a> mode more customizable.</li>\n    <li>Update XML mode to spot mismatched tags.</li>\n    <li>Add <code>getStateAfter</code> API and <code>compareState</code> mode API methods for finer-grained mode magic.</li>\n    <li>Add a <code>getScrollerElement</code> API method to manipulate the scrolling DIV.</li>\n    <li>Fix drag-and-drop for Firefox.</li>\n    <li>Add a C# configuration for the <a href=\"../mode/clike/index.html\">C-like mode</a>.</li>\n    <li>Add <a href=\"../demo/fullscreen.html\">full-screen editing</a> and <a href=\"../demo/changemode.html\">mode-changing</a> demos.</li>\n  </ul>\n\n  <p class=\"rel\">07-06-2011: <a href=\"https://codemirror.net/codemirror-2.1.zip\">Version 2.1</a>:</p>\n  <p class=\"rel-note\">Add\n  a <a href=\"manual.html#option_theme\">theme</a> system\n  (<a href=\"../demo/theme.html\">demo</a>). Note that this is not\n  backwards-compatible—you'll have to update your styles and\n  modes!</p>\n\n  <p class=\"rel\">07-06-2011: <a href=\"https://codemirror.net/codemirror-2.02.zip\">Version 2.02</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add a <a href=\"../mode/lua/index.html\">Lua mode</a>.</li>\n    <li>Fix reverse-searching for a regexp.</li>\n    <li>Empty lines can no longer break highlighting.</li>\n    <li>Rework scrolling model (the outer wrapper no longer does the scrolling).</li>\n    <li>Solve horizontal jittering on long lines.</li>\n    <li>Add <a href=\"../demo/runmode.html\">runmode.js</a>.</li>\n    <li>Immediately re-highlight text when typing.</li>\n    <li>Fix problem with 'sticking' horizontal scrollbar.</li>\n  </ul>\n\n  <p class=\"rel\">26-05-2011: <a href=\"https://codemirror.net/codemirror-2.01.zip\">Version 2.01</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add a <a href=\"../mode/smalltalk/index.html\">Smalltalk mode</a>.</li>\n    <li>Add a <a href=\"../mode/rst/index.html\">reStructuredText mode</a>.</li>\n    <li>Add a <a href=\"../mode/python/index.html\">Python mode</a>.</li>\n    <li>Add a <a href=\"../mode/plsql/index.html\">PL/SQL mode</a>.</li>\n    <li><code>coordsChar</code> now works</li>\n    <li>Fix a problem where <code>onCursorActivity</code> interfered with <code>onChange</code>.</li>\n    <li>Fix a number of scrolling and mouse-click-position glitches.</li>\n    <li>Pass information about the changed lines to <code>onChange</code>.</li>\n    <li>Support cmd-up/down on OS X.</li>\n    <li>Add triple-click line selection.</li>\n    <li>Don't handle shift when changing the selection through the API.</li>\n    <li>Support <code>\"nocursor\"</code> mode for <code>readOnly</code> option.</li>\n    <li>Add an <code>onHighlightComplete</code> option.</li>\n    <li>Fix the context menu for Firefox.</li>\n  </ul>\n\n  <p class=\"rel\">28-03-2011: <a href=\"https://codemirror.net/codemirror-2.0.zip\">Version 2.0</a>:</p>\n  <p class=\"rel-note\">CodeMirror 2 is a complete rewrite that's\n  faster, smaller, simpler to use, and less dependent on browser\n  quirks. See <a href=\"internals.html\">this</a>\n  and <a href=\"http://groups.google.com/group/codemirror/browse_thread/thread/5a8e894024a9f580\">this</a>\n  for more information.</p>\n\n  <p class=\"rel\">22-02-2011: <a href=\"https://github.com/codemirror/codemirror/tree/beta2\">Version 2.0 beta 2</a>:</p>\n  <p class=\"rel-note\">Somewhat more mature API, lots of bugs shaken out.</p>\n\n  <p class=\"rel\">17-02-2011: <a href=\"https://codemirror.net/codemirror-0.94.zip\">Version 0.94</a>:</p>\n  <ul class=\"rel-note\">\n    <li><code>tabMode: \"spaces\"</code> was modified slightly (now indents when something is selected).</li>\n    <li>Fixes a bug that would cause the selection code to break on some IE versions.</li>\n    <li>Disabling spell-check on WebKit browsers now works.</li>\n  </ul>\n\n  <p class=\"rel\">08-02-2011: <a href=\"https://codemirror.net/\">Version 2.0 beta 1</a>:</p>\n  <p class=\"rel-note\">CodeMirror 2 is a complete rewrite of\n  CodeMirror, no longer depending on an editable frame.</p>\n\n  <p class=\"rel\">19-01-2011: <a href=\"https://codemirror.net/codemirror-0.93.zip\">Version 0.93</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Added a <a href=\"contrib/regex/index.html\">Regular Expression</a> parser.</li>\n    <li>Fixes to the PHP parser.</li>\n    <li>Support for regular expression in search/replace.</li>\n    <li>Add <code>save</code> method to instances created with <code>fromTextArea</code>.</li>\n    <li>Add support for MS T-SQL in the SQL parser.</li>\n    <li>Support use of CSS classes for highlighting brackets.</li>\n    <li>Fix yet another hang with line-numbering in hidden editors.</li>\n  </ul>\n</section>\n\n<section id=v1>\n\n  <h2>Version 0.x</h2>\n\n  <p class=\"rel\">28-03-2011: <a href=\"https://codemirror.net/codemirror-1.0.zip\">Version 1.0</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Fix error when debug history overflows.</li>\n    <li>Refine handling of C# verbatim strings.</li>\n    <li>Fix some issues with JavaScript indentation.</li>\n  </ul>\n\n  <p class=\"rel\">17-12-2010: <a href=\"https://codemirror.net/codemirror-0.92.zip\">Version 0.92</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Make CodeMirror work in XHTML documents.</li>\n    <li>Fix bug in handling of backslashes in Python strings.</li>\n    <li>The <code>styleNumbers</code> option is now officially\n    supported and documented.</li>\n    <li><code>onLineNumberClick</code> option added.</li>\n    <li>More consistent names <code>onLoad</code> and\n    <code>onCursorActivity</code> callbacks. Old names still work, but\n    are deprecated.</li>\n    <li>Add a <a href=\"contrib/freemarker/index.html\">Freemarker</a> mode.</li>\n  </ul>\n\n  <p class=\"rel\">11-11-2010: <a\n  href=\"https://codemirror.net/codemirror-0.91.zip\">Version 0.91</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Adds support for <a href=\"contrib/java\">Java</a>.</li>\n    <li>Small additions to the <a href=\"contrib/php\">PHP</a> and <a href=\"contrib/sql\">SQL</a> parsers.</li>\n    <li>Work around various <a href=\"https://bugs.webkit.org/show_bug.cgi?id=47806\">Webkit</a> <a href=\"https://bugs.webkit.org/show_bug.cgi?id=23474\">issues</a>.</li>\n    <li>Fix <code>toTextArea</code> to update the code in the textarea.</li>\n    <li>Add a <code>noScriptCaching</code> option (hack to ease development).</li>\n    <li>Make sub-modes of <a href=\"mixedtest.html\">HTML mixed</a> mode configurable.</li>\n  </ul>\n\n  <p class=\"rel\">02-10-2010: <a\n  href=\"https://codemirror.net/codemirror-0.9.zip\">Version 0.9</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add support for searching backwards.</li>\n    <li>There are now parsers for <a href=\"contrib/scheme/index.html\">Scheme</a>, <a href=\"contrib/xquery/index.html\">XQuery</a>, and <a href=\"contrib/ometa/index.html\">OmetaJS</a>.</li>\n    <li>Makes <code>height: \"dynamic\"</code> more robust.</li>\n    <li>Fixes bug where paste did not work on OS X.</li>\n    <li>Add a <code>enterMode</code> and <code>electricChars</code> options to make indentation even more customizable.</li>\n    <li>Add <code>firstLineNumber</code> option.</li>\n    <li>Fix bad handling of <code>@media</code> rules by the CSS parser.</li>\n    <li>Take a new, more robust approach to working around the invisible-last-line bug in WebKit.</li>\n  </ul>\n\n  <p class=\"rel\">22-07-2010: <a\n  href=\"https://codemirror.net/codemirror-0.8.zip\">Version 0.8</a>:</p>\n  <ul class=\"rel-note\">\n    <li>Add a <code>cursorCoords</code> method to find the screen\n    coordinates of the cursor.</li>\n    <li>A number of fixes and support for more syntax in the PHP parser.</li>\n    <li>Fix indentation problem with JSON-mode JS parser in Webkit.</li>\n    <li>Add a <a href=\"compress.html\">minification</a> UI.</li>\n    <li>Support a <code>height: dynamic</code> mode, where the editor's\n    height will adjust to the size of its content.</li>\n    <li>Better support for IME input mode.</li>\n    <li>Fix JavaScript parser getting confused when seeing a no-argument\n    function call.</li>\n    <li>Have CSS parser see the difference between selectors and other\n    identifiers.</li>\n    <li>Fix scrolling bug when pasting in a horizontally-scrolled\n    editor.</li>\n    <li>Support <code>toTextArea</code> method in instances created with\n    <code>fromTextArea</code>.</li>\n    <li>Work around new Opera cursor bug that causes the cursor to jump\n    when pressing backspace at the end of a line.</li>\n  </ul>\n\n  <p class=\"rel\">27-04-2010: <a\n  href=\"https://codemirror.net/codemirror-0.67.zip\">Version\n  0.67</a>:</p>\n  <p class=\"rel-note\">More consistent page-up/page-down behaviour\n  across browsers. Fix some issues with hidden editors looping forever\n  when line-numbers were enabled. Make PHP parser parse\n  <code>\"\\\\\"</code> correctly. Have <code>jumpToLine</code> work on\n  line handles, and add <code>cursorLine</code> function to fetch the\n  line handle where the cursor currently is. Add new\n  <code>setStylesheet</code> function to switch style-sheets in a\n  running editor.</p>\n\n  <p class=\"rel\">01-03-2010: <a\n  href=\"https://codemirror.net/codemirror-0.66.zip\">Version\n  0.66</a>:</p>\n  <p class=\"rel-note\">Adds <code>removeLine</code> method to API.\n  Introduces the <a href=\"contrib/plsql/index.html\">PLSQL parser</a>.\n  Marks XML errors by adding (rather than replacing) a CSS class, so\n  that they can be disabled by modifying their style. Fixes several\n  selection bugs, and a number of small glitches.</p>\n\n  <p class=\"rel\">12-11-2009: <a\n  href=\"https://codemirror.net/codemirror-0.65.zip\">Version\n  0.65</a>:</p>\n  <p class=\"rel-note\">Add support for having both line-wrapping and\n  line-numbers turned on, make paren-highlighting style customisable\n  (<code>markParen</code> and <code>unmarkParen</code> config\n  options), work around a selection bug that Opera\n  <em>re</em>introduced in version 10.</p>\n\n  <p class=\"rel\">23-10-2009: <a\n  href=\"https://codemirror.net/codemirror-0.64.zip\">Version\n  0.64</a>:</p>\n  <p class=\"rel-note\">Solves some issues introduced by the\n  paste-handling changes from the previous release. Adds\n  <code>setSpellcheck</code>, <code>setTextWrapping</code>,\n  <code>setIndentUnit</code>, <code>setUndoDepth</code>,\n  <code>setTabMode</code>, and <code>setLineNumbers</code> to\n  customise a running editor. Introduces an <a\n  href=\"contrib/sql/index.html\">SQL</a> parser. Fixes a few small\n  problems in the <a href=\"contrib/python/index.html\">Python</a>\n  parser. And, as usual, add workarounds for various newly discovered\n  browser incompatibilities.</p>\n\n  <p class=\"rel\">31-08-2009: <a href=\"https://codemirror.net/codemirror-0.63.zip\">Version 0.63</a>:</p>\n  <p class=\"rel-note\"> Overhaul of paste-handling (less fragile), fixes for several\n  serious IE8 issues (cursor jumping, end-of-document bugs) and a number\n  of small problems.</p>\n\n  <p class=\"rel\">30-05-2009: <a href=\"https://codemirror.net/codemirror-0.62.zip\">Version 0.62</a>:</p>\n  <p class=\"rel-note\">Introduces <a href=\"contrib/python/index.html\">Python</a>\n  and <a href=\"contrib/lua/index.html\">Lua</a> parsers. Add\n  <code>setParser</code> (on-the-fly mode changing) and\n  <code>clearHistory</code> methods. Make parsing passes time-based\n  instead of lines-based (see the <code>passTime</code> option).</p>\n\n</section>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/doc/reporting.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Reporting Bugs</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"docs.css\">\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Reporting bugs</a>\n  </ul>\n</div>\n\n<article>\n\n<h2>Reporting bugs effectively</h2>\n\n<div class=\"left\">\n\n<p>So you found a problem in CodeMirror. By all means, report it! Bug\nreports from users are the main drive behind improvements to\nCodeMirror. But first, please read over these points:</p>\n\n<ol>\n  <li>CodeMirror is maintained by volunteers. They don't owe you\n  anything, so be polite. Reports with an indignant or belligerent\n  tone tend to be moved to the bottom of the pile.</li>\n\n  <li>Include information about <strong>the browser in which the\n  problem occurred</strong>. Even if you tested several browsers, and\n  the problem occurred in all of them, mention this fact in the bug\n  report. Also include browser version numbers and the operating\n  system that you're on.</li>\n\n  <li>Mention which release of CodeMirror you're using. Preferably,\n  try also with the current development snapshot, to ensure the\n  problem has not already been fixed.</li>\n\n  <li>Mention very precisely what went wrong. \"X is broken\" is not a\n  good bug report. What did you expect to happen? What happened\n  instead? Describe the exact steps a maintainer has to take to reproduce\n  the error. We can not fix something that we can not observe.</li>\n\n  <li>If the problem can not be reproduced in any of the demos\n  included in the CodeMirror distribution, please provide an HTML\n  document that demonstrates the problem. The best way to do this is\n  to go to <a href=\"http://jsbin.com/ihunin/1/edit\">jsbin.com</a>, enter\n  it there, press save, and include the resulting link in your bug\n  report.</li>\n</ol>\n\n</div>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/doc/upgrade_v2.2.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Version 2.2 upgrade guide</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"docs.css\">\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">2.2 upgrade guide</a>\n  </ul>\n</div>\n\n<article>\n\n<h2>Upgrading to v2.2</h2>\n\n<p>There are a few things in the 2.2 release that require some care\nwhen upgrading.</p>\n\n<h3>No more default.css</h3>\n\n<p>The default theme is now included\nin <a href=\"../lib/codemirror.css\"><code>codemirror.css</code></a>, so\nyou do not have to included it separately anymore. (It was tiny, so\neven if you're not using it, the extra data overhead is negligible.)\n\n<h3>Different key customization</h3>\n\n<p>CodeMirror has moved to a system\nwhere <a href=\"manual.html#option_keyMap\">keymaps</a> are used to\nbind behavior to keys. This means <a href=\"../demo/emacs.html\">custom\nbindings</a> are now possible.</p>\n\n<p>Three options that influenced key\nbehavior, <code>tabMode</code>, <code>enterMode</code>,\nand <code>smartHome</code>, are no longer supported. Instead, you can\nprovide custom bindings to influence the way these keys act. This is\ndone through the\nnew <a href=\"manual.html#option_extraKeys\"><code>extraKeys</code></a>\noption, which can hold an object mapping key names to functionality. A\nsimple example would be:</p>\n\n<pre>  extraKeys: {\n    \"Ctrl-S\": function(instance) { saveText(instance.getValue()); },\n    \"Ctrl-/\": \"undo\"\n  }</pre>\n\n<p>Keys can be mapped either to functions, which will be given the\neditor instance as argument, or to strings, which are mapped through\nfunctions through the <code>CodeMirror.commands</code> table, which\ncontains all the built-in editing commands, and can be inspected and\nextended by external code.</p>\n\n<p>By default, the <code>Home</code> key is bound to\nthe <code>\"goLineStartSmart\"</code> command, which moves the cursor to\nthe first non-whitespace character on the line. You can set do this to\nmake it always go to the very start instead:</p>\n\n<pre>  extraKeys: {\"Home\": \"goLineStart\"}</pre>\n\n<p>Similarly, <code>Enter</code> is bound\nto <code>\"newlineAndIndent\"</code> by default. You can bind it to\nsomething else to get different behavior. To disable special handling\ncompletely and only get a newline character inserted, you can bind it\nto <code>false</code>:</p>\n\n<pre>  extraKeys: {\"Enter\": false}</pre>\n\n<p>The same works for <code>Tab</code>. If you don't want CodeMirror\nto handle it, bind it to <code>false</code>. The default behaviour is\nto indent the current line more (<code>\"indentMore\"</code> command),\nand indent it less when shift is held (<code>\"indentLess\"</code>).\nThere are also <code>\"indentAuto\"</code> (smart indent)\nand <code>\"insertTab\"</code> commands provided for alternate\nbehaviors. Or you can write your own handler function to do something\ndifferent altogether.</p>\n\n<h3>Tabs</h3>\n\n<p>Handling of tabs changed completely. The display width of tabs can\nnow be set with the <code>tabSize</code> option, and tabs can\nbe <a href=\"../demo/visibletabs.html\">styled</a> by setting CSS rules\nfor the <code>cm-tab</code> class.</p>\n\n<p>The default width for tabs is now 4, as opposed to the 8 that is\nhard-wired into browsers. If you are relying on 8-space tabs, make\nsure you explicitly set <code>tabSize: 8</code> in your options.</p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/doc/upgrade_v3.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Version 3 upgrade guide</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"docs.css\">\n<script src=\"../lib/codemirror.js\"></script>\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<script src=\"../addon/runmode/runmode.js\"></script>\n<script src=\"../addon/runmode/colorize.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../mode/css/css.js\"></script>\n<script src=\"../mode/htmlmixed/htmlmixed.js\"></script>\n<script src=\"activebookmark.js\"></script>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#upgrade\">Upgrade guide</a>\n    <li><a href=\"#dom\">DOM structure</a></li>\n    <li><a href=\"#gutters\">Gutter model</a></li>\n    <li><a href=\"#events\">Event handling</a></li>\n    <li><a href=\"#marktext\">markText method arguments</a></li>\n    <li><a href=\"#folding\">Line folding</a></li>\n    <li><a href=\"#lineclass\">Line CSS classes</a></li>\n    <li><a href=\"#positions\">Position properties</a></li>\n    <li><a href=\"#matchbrackets\">Bracket matching</a></li>\n    <li><a href=\"#modes\">Mode management</a></li>\n    <li><a href=\"#new\">New features</a></li>\n  </ul>\n</div>\n\n<article>\n\n<h2 id=upgrade>Upgrading to version 3</h2>\n\n<p>Version 3 does not depart too much from 2.x API, and sites that use\nCodeMirror in a very simple way might be able to upgrade without\ntrouble. But it does introduce a number of incompatibilities. Please\nat least skim this text before upgrading.</p>\n\n<p>Note that <strong>version 3 drops full support for Internet\nExplorer 7</strong>. The editor will mostly work on that browser, but\nit'll be significantly glitchy.</p>\n\n<section id=dom>\n  <h2>DOM structure</h2>\n\n<p>This one is the most likely to cause problems. The internal\nstructure of the editor has changed quite a lot, mostly to implement a\nnew scrolling model.</p>\n\n<p>Editor height is now set on the outer wrapper element (CSS\nclass <code>CodeMirror</code>), not on the scroller element\n(<code>CodeMirror-scroll</code>).</p>\n\n<p>Other nodes were moved, dropped, and added. If you have any code\nthat makes assumptions about the internal DOM structure of the editor,\nyou'll have to re-test it and probably update it to work with v3.</p>\n\n<p>See the <a href=\"manual.html#styling\">styling section</a> of the\nmanual for more information.</p>\n</section>\n<section id=gutters>\n  <h2>Gutter model</h2>\n\n<p>In CodeMirror 2.x, there was a single gutter, and line markers\ncreated with <code>setMarker</code> would have to somehow coexist with\nthe line numbers (if present). Version 3 allows you to specify an\narray of gutters, <a href=\"manual.html#option_gutters\">by class\nname</a>,\nuse <a href=\"manual.html#setGutterMarker\"><code>setGutterMarker</code></a>\nto add or remove markers in individual gutters, and clear whole\ngutters\nwith <a href=\"manual.html#clearGutter\"><code>clearGutter</code></a>.\nGutter markers are now specified as DOM nodes, rather than HTML\nsnippets.</p>\n\n<p>The gutters no longer horizontally scrolls along with the content.\nThe <code>fixedGutter</code> option was removed (since it is now the\nonly behavior).</p>\n\n<pre data-lang=\"text/html\">\n&lt;style>\n  /* Define a gutter style */\n  .note-gutter { width: 3em; background: cyan; }\n&lt;/style>\n&lt;script>\n  // Create an instance with two gutters -- line numbers and notes\n  var cm = new CodeMirror(document.body, {\n    gutters: [\"note-gutter\", \"CodeMirror-linenumbers\"],\n    lineNumbers: true\n  });\n  // Add a note to line 0\n  cm.setGutterMarker(0, \"note-gutter\", document.createTextNode(\"hi\"));\n&lt;/script>\n</pre>\n</section>\n<section id=events>\n  <h2>Event handling</h2>\n\n<p>Most of the <code>onXYZ</code> options have been removed. The same\neffect is now obtained by calling\nthe <a href=\"manual.html#on\"><code>on</code></a> method with a string\nidentifying the event type. Multiple handlers can now be registered\n(and individually unregistered) for an event, and objects such as line\nhandlers now also expose events. See <a href=\"manual.html#events\">the\nfull list here</a>.</p>\n\n<p>(The <code>onKeyEvent</code> and <code>onDragEvent</code> options,\nwhich act more as hooks than as event handlers, are still there in\ntheir old form.)</p>\n\n<pre data-lang=\"javascript\">\ncm.on(\"change\", function(cm, change) {\n  console.log(\"something changed! (\" + change.origin + \")\");\n});\n</pre>\n</section>\n<section id=marktext>\n  <h2>markText method arguments</h2>\n\n<p>The <a href=\"manual.html#markText\"><code>markText</code></a> method\n(which has gained some interesting new features, such as creating\natomic and read-only spans, or replacing spans with widgets) no longer\ntakes the CSS class name as a separate argument, but makes it an\noptional field in the options object instead.</p>\n\n<pre data-lang=\"javascript\">\n// Style first ten lines, and forbid the cursor from entering them\ncm.markText({line: 0, ch: 0}, {line: 10, ch: 0}, {\n  className: \"magic-text\",\n  inclusiveLeft: true,\n  atomic: true\n});\n</pre>\n</section>\n<section id=folding>\n  <h2>Line folding</h2>\n\n<p>The interface for hiding lines has been\nremoved. <a href=\"manual.html#markText\"><code>markText</code></a> can\nnow be used to do the same in a more flexible and powerful way.</p>\n\n<p>The <a href=\"../demo/folding.html\">folding script</a> has been\nupdated to use the new interface, and should now be more robust.</p>\n\n<pre data-lang=\"javascript\">\n// Fold a range, replacing it with the text \"??\"\nvar range = cm.markText({line: 4, ch: 2}, {line: 8, ch: 1}, {\n  replacedWith: document.createTextNode(\"??\"),\n  // Auto-unfold when cursor moves into the range\n  clearOnEnter: true\n});\n// Get notified when auto-unfolding\nCodeMirror.on(range, \"clear\", function() {\n  console.log(\"boom\");\n});\n</pre>\n</section>\n<section id=lineclass>\n  <h2>Line CSS classes</h2>\n\n<p>The <code>setLineClass</code> method has been replaced\nby <a href=\"manual.html#addLineClass\"><code>addLineClass</code></a>\nand <a href=\"manual.html#removeLineClass\"><code>removeLineClass</code></a>,\nwhich allow more modular control over the classes attached to a line.</p>\n\n<pre data-lang=\"javascript\">\nvar marked = cm.addLineClass(10, \"background\", \"highlighted-line\");\nsetTimeout(function() {\n  cm.removeLineClass(marked, \"background\", \"highlighted-line\");\n});\n</pre>\n</section>\n<section id=positions>\n  <h2>Position properties</h2>\n\n<p>All methods that take or return objects that represent screen\npositions now use <code>{left, top, bottom, right}</code> properties\n(not always all of them) instead of the <code>{x, y, yBot}</code> used\nby some methods in v2.x.</p>\n\n<p>Affected methods\nare <a href=\"manual.html#cursorCoords\"><code>cursorCoords</code></a>, <a href=\"manual.html#charCoords\"><code>charCoords</code></a>, <a href=\"manual.html#coordsChar\"><code>coordsChar</code></a>,\nand <a href=\"manual.html#getScrollInfo\"><code>getScrollInfo</code></a>.</p>\n</section>\n<section id=matchbrackets>\n  <h2>Bracket matching no longer in core</h2>\n\n<p>The <a href=\"manual.html#addon_matchbrackets\"><code>matchBrackets</code></a>\noption is no longer defined in the core editor.\nLoad <code>addon/edit/matchbrackets.js</code> to enable it.</p>\n</section>\n<section id=modes>\n  <h2>Mode management</h2>\n\n<p>The <code>CodeMirror.listModes</code>\nand <code>CodeMirror.listMIMEs</code> functions, used for listing\ndefined modes, are gone. You are now encouraged to simply\ninspect <code>CodeMirror.modes</code> (mapping mode names to mode\nconstructors) and <code>CodeMirror.mimeModes</code> (mapping MIME\nstrings to mode specs).</p>\n</section>\n<section id=new>\n  <h2>New features</h2>\n\n<p>Some more reasons to upgrade to version 3.</p>\n\n<ul>\n  <li>Bi-directional text support. CodeMirror will now mostly do the\n  right thing when editing Arabic or Hebrew text.</li>\n  <li>Arbitrary line heights. Using fonts with different heights\n  inside the editor (whether off by one pixel or fifty) is now\n  supported and handled gracefully.</li>\n  <li>In-line widgets. See <a href=\"../demo/widget.html\">the demo</a>\n  and <a href=\"manual.html#addLineWidget\">the docs</a>.</li>\n  <li>Defining custom options\n  with <a href=\"manual.html#defineOption\"><code>CodeMirror.defineOption</code></a>.</li>\n</ul>\n</section>\n</article>\n\n<script>setTimeout(function(){CodeMirror.colorize();}, 20);</script>\n"
  },
  {
    "path": "third_party/CodeMirror/doc/upgrade_v4.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Version 4 upgrade guide</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"docs.css\">\n<script src=\"activebookmark.js\"></script>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#upgrade\">Upgrade guide</a>\n    <li><a href=\"#multisel\">Multiple selections</a>\n    <li><a href=\"#beforeSelectionChange\">The beforeSelectionChange event</a>\n    <li><a href=\"#replaceSelection\">replaceSelection and collapsing</a>\n    <li><a href=\"#changeEvent\">change event data</a>\n    <li><a href=\"#showIfHidden\">showIfHidden option to line widgets</a>\n    <li><a href=\"#module\">Module loaders</a>\n    <li><a href=\"#shareddata\">Mutating shared data structures</a></li>\n    <li><a href=\"#deprecated\">Deprecated interfaces dropped</a>\n  </ul>\n</div>\n\n<article>\n\n<h2 id=upgrade>Upgrading to version 4</h2>\n\n<p>CodeMirror 4's interface is <em>very</em> close version 3, but it\ndoes fix a few awkward details in a backwards-incompatible ways. At\nleast skim the text below before upgrading.</p>\n\n<section id=multisel><h2>Multiple selections</h2>\n\n<p>The main new feature in version 4 is multiple selections. The\nsingle-selection variants of methods are still there, but now\ntypically act only on the <em>primary</em> selection (usually the last\none added).</p>\n\n<p>The exception to this\nis <a href=\"manual.html#getSelection\"><strong><code>getSelection</code></strong></a>,\nwhich will now return the content of <em>all</em> selections\n(separated by newlines, or whatever <code>lineSep</code> parameter you passed\nit).</p>\n\n</section>\n\n<section id=beforeSelectionChange><h2>The beforeSelectionChange event</h2>\n\n<p>This event still exists, but the object it is passed has\na <a href=\"manual.html#event_beforeSelectionChange\">completely new\ninterface</a>, because such changes now concern multiple\nselections.</p>\n\n</section>\n\n<section id=replaceSelection><h2>replaceSelection's collapsing behavior</h2>\n\n<p>By\ndefault, <a href=\"manual.html#replaceSelection\"><code>replaceSelection</code></a>\nwould leave the newly inserted text selected. This is only rarely what\nyou want, and also (slightly) more expensive in the new model, so the\ndefault was changed to <code>\"end\"</code>, meaning the old behavior\nmust be explicitly specified by passing a second argument\nof <code>\"around\"</code>.</p>\n\n</section>\n\n<section id=changeEvent><h2>change event data</h2>\n\n<p>Rather than forcing client code to follow <code>next</code>\npointers from one change object to the next, the library will now\nsimply fire\nmultiple <a href=\"manual.html#event_change\"><code>\"change\"</code></a>\nevents. Existing code will probably continue to work unmodified.</p>\n\n</section>\n\n<section id=showIfHidden><h2>showIfHidden option to line widgets</h2>\n\n<p>This option, which conceptually caused line widgets to be visible\neven if their line was hidden, was never really well-defined, and was\nbuggy from the start. It would be a rather expensive feature, both in\ncode complexity and run-time performance, to implement properly. It\nhas been dropped entirely in 4.0.</p>\n\n</section>\n\n<section id=module><h2>Module loaders</h2>\n\n<p>All modules in the CodeMirror distribution are now wrapped in a\nshim function to make them compatible with both AMD\n(<a href=\"http://requirejs.org\">requirejs</a>) and CommonJS (as used\nby <a href=\"http://nodejs.org/\">node</a>\nand <a href=\"http://browserify.org/\">browserify</a>) module loaders.\nWhen neither of these is present, they fall back to simply using the\nglobal <code>CodeMirror</code> variable.</p>\n\n<p>If you have a module loader present in your environment, CodeMirror\nwill attempt to use it, and you might need to change the way you load\nCodeMirror modules.</p>\n\n</section>\n\n<section id=shareddata><h2>Mutating shared data structures</h2>\n\n<p>Data structures produced by the library should not be mutated\nunless explicitly allowed, in general. This is slightly more strict in\n4.0 than it was in earlier versions, which copied the position objects\nreturned by <a href=\"manual.html#getCursor\"><code>getCursor</code></a>\nfor nebulous, historic reasons. In 4.0, mutating these\nobjects <em>will</em> corrupt your editor's selection.</p>\n\n</section>\n\n<section id=deprecated><h2>Deprecated interfaces dropped</h2>\n\n<p>A few properties and methods that have been deprecated for a while\nare now gone. Most notably, the <code>onKeyEvent</code>\nand <code>onDragEvent</code> options (use the\ncorresponding <a href=\"manual.html#event_dom\">events</a> instead).</p>\n\n<p>Two silly methods, which were mostly there to stay close to the 0.x\nAPI, <code>setLine</code> and <code>removeLine</code> are now gone.\nUse the more\nflexible <a href=\"manual.html#replaceRange\"><code>replaceRange</code></a>\nmethod instead.</p>\n\n<p>The long names for folding and completing functions\n(<code>CodeMirror.braceRangeFinder</code>, <code>CodeMirror.javascriptHint</code>,\netc) are also gone\n(use <code>CodeMirror.fold.brace</code>, <code>CodeMirror.hint.javascript</code>).</p>\n\n<p>The <code>className</code> property in the return value\nof <a href=\"manual.html#getTokenAt\"><code>getTokenAt</code></a>, which\nhas been superseded by the <code>type</code> property, is also no\nlonger present.</p>\n\n</section>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror</title>\n<meta charset=\"utf-8\"/>\n\n<link rel=stylesheet href=\"lib/codemirror.css\">\n<link rel=stylesheet href=\"doc/docs.css\">\n<script src=\"lib/codemirror.js\"></script>\n<script src=\"mode/xml/xml.js\"></script>\n<script src=\"mode/javascript/javascript.js\"></script>\n<script src=\"mode/css/css.js\"></script>\n<script src=\"mode/htmlmixed/htmlmixed.js\"></script>\n<script src=\"addon/edit/matchbrackets.js\"></script>\n\n<script src=\"doc/activebookmark.js\"></script>\n\n<style>\n  .CodeMirror { height: auto; border: 1px solid #ddd; }\n  .CodeMirror-scroll { max-height: 200px; }\n  .CodeMirror pre { padding-left: 7px; line-height: 1.25; }\n  .banner { background: #ffc; padding: 6px; border-bottom: 2px solid silver;  }\n  .banner div { margin: 0 auto; max-width: 700px; text-align: center; }\n</style>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"doc/logo.png\"></a>\n\n  <ul>\n    <li><a class=active data-default=\"true\" href=\"#description\">Home</a>\n    <li><a href=\"doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n    <li><a href=\"https://codemirror.net/6/\">Version 6</a>\n  </ul>\n  <ul>\n    <li><a href=\"#features\">Features</a>\n    <li><a href=\"#community\">Community</a>\n    <li><a href=\"#browsersupport\">Browser support</a>\n  </ul>\n</div>\n\n<article>\n\n<section id=description class=first>\n  <p><strong>CodeMirror</strong> is a versatile text editor\n  implemented in JavaScript for the browser. It is specialized for\n  editing code, and comes with a number of <a href=\"mode/index.html\">language modes</a> and <a href=\"doc/manual.html#addons\">addons</a>\n  that implement more advanced editing functionality.</p>\n\n  <p>A rich <a href=\"doc/manual.html#api\">programming API</a> and a\n  CSS <a href=\"doc/manual.html#styling\">theming</a> system are\n  available for customizing CodeMirror to fit your application, and\n  extending it with new functionality.</p>\n</section>\n\n<section id=demo>\n  <h2>This is CodeMirror</h2>\n  <form style=\"position: relative; margin-top: .5em;\"><textarea id=demotext>\n<!-- Create a simple CodeMirror instance -->\n<link rel=\"stylesheet\" href=\"lib/codemirror.css\">\n<script src=\"lib/codemirror.js\"></script>\n<script>\n  var editor = CodeMirror.fromTextArea(myTextarea, {\n    lineNumbers: true\n  });\n</script></textarea>\n  <select id=\"demolist\" onchange=\"document.location = this.options[this.selectedIndex].value;\">\n    <option value=\"#\">Other demos...</option>\n    <option value=\"demo/complete.html\">Autocompletion</option>\n    <option value=\"demo/folding.html\">Code folding</option>\n    <option value=\"demo/theme.html\">Themes</option>\n    <option value=\"mode/htmlmixed/index.html\">Mixed language modes</option>\n    <option value=\"demo/bidi.html\">Bi-directional text</option>\n    <option value=\"demo/variableheight.html\">Variable font sizes</option>\n    <option value=\"demo/search.html\">Search interface</option>\n    <option value=\"demo/vim.html\">Vim bindings</option>\n    <option value=\"demo/emacs.html\">Emacs bindings</option>\n    <option value=\"demo/sublime.html\">Sublime Text bindings</option>\n    <option value=\"demo/tern.html\">Tern integration</option>\n    <option value=\"demo/merge.html\">Merge/diff interface</option>\n    <option value=\"demo/fullscreen.html\">Full-screen editor</option>\n    <option value=\"demo/simplescrollbars.html\">Custom scrollbars</option>\n  </select></form>\n  <script>\n    var editor = CodeMirror.fromTextArea(document.getElementById(\"demotext\"), {\n      lineNumbers: true,\n      mode: \"text/html\",\n      matchBrackets: true\n    });\n  </script>\n\n  <div class=actions>\n    <div class=actionspicture>\n      <img src=\"doc/yinyang.png\" class=yinyang>\n      <div class=\"actionlink download\">\n        <a href=\"https://codemirror.net/codemirror.zip\">DOWNLOAD</a>\n      </div>\n      <div class=\"actionlink fund\">\n        <a href=\"https://marijnhaverbeke.nl/fund/\">FUND</a>\n      </div>\n    </div>\n    <div class=actionsleft>\n      Get the current version: <a href=\"https://codemirror.net/codemirror.zip\">5.43.0</a>.<br>\n      You can see the <a href=\"https://github.com/codemirror/codemirror\" title=\"Github repository\">code</a>,<br>\n      read the <a href=\"doc/releases.html\">release notes</a>,<br>\n      or study the <a href=\"doc/manual.html\">user manual</a>.\n    </div>\n    <div class=actionsright>\n      Software needs maintenance,<br>\n      maintainers need to subsist.<br>\n      You can help <a href=\"https://marijnhaverbeke.nl/fund/\" title=\"Set up a monthly contribution\">per month</a> or\n      <a title=\"Donate with PayPal\" href=\"https://www.paypal.me/marijnhaverbeke\">once</a>.\n    </div>\n  </div>\n\n</section>\n\n<section id=features>\n  <h2>Features</h2>\n  <ul>\n    <li>Support for <a href=\"mode/index.html\">over 100 languages</a> out of the box\n    <li>A powerful, <a href=\"mode/htmlmixed/index.html\">composable</a> language mode <a href=\"doc/manual.html#modeapi\">system</a>\n    <li><a href=\"doc/manual.html#addon_show-hint\">Autocompletion</a> (<a href=\"demo/xmlcomplete.html\">XML</a>)\n    <li><a href=\"doc/manual.html#addon_foldcode\">Code folding</a>\n    <li><a href=\"doc/manual.html#option_extraKeys\">Configurable</a> keybindings\n    <li><a href=\"demo/vim.html\">Vim</a>, <a href=\"demo/emacs.html\">Emacs</a>, and <a href=\"demo/sublime.html\">Sublime Text</a> bindings\n    <li><a href=\"doc/manual.html#addon_search\">Search and replace</a> interface\n    <li><a href=\"doc/manual.html#addon_matchbrackets\">Bracket</a> and <a href=\"doc/manual.html#addon_matchtags\">tag</a> matching\n    <li>Support for <a href=\"demo/buffers.html\">split views</a>\n    <li><a href=\"doc/manual.html#addon_lint\">Linter integration</a>\n    <li><a href=\"demo/variableheight.html\">Mixing font sizes and styles</a>\n    <li><a href=\"demo/theme.html\">Various themes</a>\n    <li>Able to <a href=\"demo/resize.html\">resize to fit content</a>\n    <li><a href=\"doc/manual.html#mark_replacedWith\">Inline</a> and <a href=\"doc/manual.html#addLineWidget\">block</a> widgets\n    <li>Programmable <a href=\"demo/marker.html\">gutters</a>\n    <li>Making ranges of text <a href=\"doc/manual.html#markText\">styled, read-only, or atomic</a>\n    <li><a href=\"demo/bidi.html\">Bi-directional text</a> support\n    <li>Many other <a href=\"doc/manual.html#api\">methods</a> and <a href=\"doc/manual.html#addons\">addons</a>...\n  </ul>\n</section>\n\n<section id=community>\n  <h2>Community</h2>\n\n  <p>CodeMirror is an open-source project shared under\n  an <a href=\"LICENSE\">MIT license</a>. It is the editor used in the\n  dev tools for\n  <a href=\"https://hacks.mozilla.org/2013/11/firefox-developer-tools-episode-27-edit-as-html-codemirror-more/\">Firefox</a>,\n  <a href=\"https://developers.google.com/chrome-developer-tools/\">Chrome</a>,\n  and <a href=\"https://developer.apple.com/safari/tools/\">Safari</a>, in <a href=\"http://www.lighttable.com/\">Light\n  Table</a>, <a href=\"http://brackets.io/\">Adobe\n  Brackets</a>, <a href=\"http://blog.bitbucket.org/2013/05/14/edit-your-code-in-the-cloud-with-bitbucket/\">Bitbucket</a>,\n  and <a href=\"doc/realworld.html\">many other projects</a>.</p>\n\n  <p>Development and bug tracking happens\n  on <a href=\"https://github.com/codemirror/CodeMirror/\">github</a>\n  (<a href=\"http://marijnhaverbeke.nl/git/codemirror\">alternate git\n  repository</a>).\n  Please <a href=\"https://codemirror.net/doc/reporting.html\">read these\n  pointers</a> before submitting a bug. Use pull requests to submit\n  patches. All contributions must be released under the same MIT\n  license that CodeMirror uses.</p>\n\n  <p>Discussion around the project is done on\n  a <a href=\"https://discuss.codemirror.net\">discussion forum</a>.\n  Announcements related to the project, such as new versions, are\n  posted in the\n  forum's <a href=\"https://discuss.codemirror.net/c/announce\">\"announce\"</a>\n  category. If needed, you can\n  contact <a href=\"mailto:marijnh@gmail.com\">the maintainer</a>\n  directly. We aim to be an inclusive, welcoming community. To make\n  that explicit, we have\n  a <a href=\"http://contributor-covenant.org/version/1/1/0/\">code of\n  conduct</a> that applies to communication around the project.</p>\n\n  <p>A list of CodeMirror-related software that is not part of the\n  main distribution is maintained\n  on <a href=\"https://github.com/codemirror/CodeMirror/wiki/CodeMirror-addons\">our\n  wiki</a>. Feel free to add your project.</p>\n</section>\n\n<section id=browsersupport>\n  <h2>Browser support</h2>\n  <p>The <em>desktop</em> versions of the following browsers,\n  in <em>standards mode</em> (HTML5 <code>&lt;!doctype html></code>\n  recommended) are supported:</p>\n  <table style=\"margin-bottom: 1em\">\n    <tr><th>Firefox</th><td>version 4 and up</td></tr>\n    <tr><th>Chrome</th><td>any version</td></tr>\n    <tr><th>Safari</th><td>version 5.2 and up</td></tr>\n    <tr><th style=\"padding-right: 1em;\">Internet Explorer/Edge</th><td>version 8 and up</td></tr>\n    <tr><th>Opera</th><td>version 9 and up</td></tr>\n  </table>\n  <p>Support for modern mobile browsers is experimental. Recent\n  versions of the iOS browser and Chrome on Android should work\n  pretty well.</p>\n</section>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/keymap/emacs.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var Pos = CodeMirror.Pos;\n  function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }\n\n  // Kill 'ring'\n\n  var killRing = [];\n  function addToRing(str) {\n    killRing.push(str);\n    if (killRing.length > 50) killRing.shift();\n  }\n  function growRingTop(str) {\n    if (!killRing.length) return addToRing(str);\n    killRing[killRing.length - 1] += str;\n  }\n  function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || \"\"; }\n  function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }\n\n  var lastKill = null;\n\n  function kill(cm, from, to, ring, text) {\n    if (text == null) text = cm.getRange(from, to);\n\n    if (ring == \"grow\" && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen))\n      growRingTop(text);\n    else if (ring !== false)\n      addToRing(text);\n    cm.replaceRange(\"\", from, to, \"+delete\");\n\n    if (ring == \"grow\") lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()};\n    else lastKill = null;\n  }\n\n  // Boundaries of various units\n\n  function byChar(cm, pos, dir) {\n    return cm.findPosH(pos, dir, \"char\", true);\n  }\n\n  function byWord(cm, pos, dir) {\n    return cm.findPosH(pos, dir, \"word\", true);\n  }\n\n  function byLine(cm, pos, dir) {\n    return cm.findPosV(pos, dir, \"line\", cm.doc.sel.goalColumn);\n  }\n\n  function byPage(cm, pos, dir) {\n    return cm.findPosV(pos, dir, \"page\", cm.doc.sel.goalColumn);\n  }\n\n  function byParagraph(cm, pos, dir) {\n    var no = pos.line, line = cm.getLine(no);\n    var sawText = /\\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch));\n    var fst = cm.firstLine(), lst = cm.lastLine();\n    for (;;) {\n      no += dir;\n      if (no < fst || no > lst)\n        return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null));\n      line = cm.getLine(no);\n      var hasText = /\\S/.test(line);\n      if (hasText) sawText = true;\n      else if (sawText) return Pos(no, 0);\n    }\n  }\n\n  function bySentence(cm, pos, dir) {\n    var line = pos.line, ch = pos.ch;\n    var text = cm.getLine(pos.line), sawWord = false;\n    for (;;) {\n      var next = text.charAt(ch + (dir < 0 ? -1 : 0));\n      if (!next) { // End/beginning of line reached\n        if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);\n        text = cm.getLine(line + dir);\n        if (!/\\S/.test(text)) return Pos(line, ch);\n        line += dir;\n        ch = dir < 0 ? text.length : 0;\n        continue;\n      }\n      if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0));\n      if (!sawWord) sawWord = /\\w/.test(next);\n      ch += dir;\n    }\n  }\n\n  function byExpr(cm, pos, dir) {\n    var wrap;\n    if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, {strict: true}))\n        && wrap.match && (wrap.forward ? 1 : -1) == dir)\n      return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to;\n\n    for (var first = true;; first = false) {\n      var token = cm.getTokenAt(pos);\n      var after = Pos(pos.line, dir < 0 ? token.start : token.end);\n      if (first && dir > 0 && token.end == pos.ch || !/\\w/.test(token.string)) {\n        var newPos = cm.findPosH(after, dir, \"char\");\n        if (posEq(after, newPos)) return pos;\n        else pos = newPos;\n      } else {\n        return after;\n      }\n    }\n  }\n\n  // Prefixes (only crudely supported)\n\n  function getPrefix(cm, precise) {\n    var digits = cm.state.emacsPrefix;\n    if (!digits) return precise ? null : 1;\n    clearPrefix(cm);\n    return digits == \"-\" ? -1 : Number(digits);\n  }\n\n  function repeated(cmd) {\n    var f = typeof cmd == \"string\" ? function(cm) { cm.execCommand(cmd); } : cmd;\n    return function(cm) {\n      var prefix = getPrefix(cm);\n      f(cm);\n      for (var i = 1; i < prefix; ++i) f(cm);\n    };\n  }\n\n  function findEnd(cm, pos, by, dir) {\n    var prefix = getPrefix(cm);\n    if (prefix < 0) { dir = -dir; prefix = -prefix; }\n    for (var i = 0; i < prefix; ++i) {\n      var newPos = by(cm, pos, dir);\n      if (posEq(newPos, pos)) break;\n      pos = newPos;\n    }\n    return pos;\n  }\n\n  function move(by, dir) {\n    var f = function(cm) {\n      cm.extendSelection(findEnd(cm, cm.getCursor(), by, dir));\n    };\n    f.motion = true;\n    return f;\n  }\n\n  function killTo(cm, by, dir, ring) {\n    var selections = cm.listSelections(), cursor;\n    var i = selections.length;\n    while (i--) {\n      cursor = selections[i].head;\n      kill(cm, cursor, findEnd(cm, cursor, by, dir), ring);\n    }\n  }\n\n  function killRegion(cm, ring) {\n    if (cm.somethingSelected()) {\n      var selections = cm.listSelections(), selection;\n      var i = selections.length;\n      while (i--) {\n        selection = selections[i];\n        kill(cm, selection.anchor, selection.head, ring);\n      }\n      return true;\n    }\n  }\n\n  function addPrefix(cm, digit) {\n    if (cm.state.emacsPrefix) {\n      if (digit != \"-\") cm.state.emacsPrefix += digit;\n      return;\n    }\n    // Not active yet\n    cm.state.emacsPrefix = digit;\n    cm.on(\"keyHandled\", maybeClearPrefix);\n    cm.on(\"inputRead\", maybeDuplicateInput);\n  }\n\n  var prefixPreservingKeys = {\"Alt-G\": true, \"Ctrl-X\": true, \"Ctrl-Q\": true, \"Ctrl-U\": true};\n\n  function maybeClearPrefix(cm, arg) {\n    if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))\n      clearPrefix(cm);\n  }\n\n  function clearPrefix(cm) {\n    cm.state.emacsPrefix = null;\n    cm.off(\"keyHandled\", maybeClearPrefix);\n    cm.off(\"inputRead\", maybeDuplicateInput);\n  }\n\n  function maybeDuplicateInput(cm, event) {\n    var dup = getPrefix(cm);\n    if (dup > 1 && event.origin == \"+input\") {\n      var one = event.text.join(\"\\n\"), txt = \"\";\n      for (var i = 1; i < dup; ++i) txt += one;\n      cm.replaceSelection(txt);\n    }\n  }\n\n  function addPrefixMap(cm) {\n    cm.state.emacsPrefixMap = true;\n    cm.addKeyMap(prefixMap);\n    cm.on(\"keyHandled\", maybeRemovePrefixMap);\n    cm.on(\"inputRead\", maybeRemovePrefixMap);\n  }\n\n  function maybeRemovePrefixMap(cm, arg) {\n    if (typeof arg == \"string\" && (/^\\d$/.test(arg) || arg == \"Ctrl-U\")) return;\n    cm.removeKeyMap(prefixMap);\n    cm.state.emacsPrefixMap = false;\n    cm.off(\"keyHandled\", maybeRemovePrefixMap);\n    cm.off(\"inputRead\", maybeRemovePrefixMap);\n  }\n\n  // Utilities\n\n  function setMark(cm) {\n    cm.setCursor(cm.getCursor());\n    cm.setExtending(!cm.getExtending());\n    cm.on(\"change\", function() { cm.setExtending(false); });\n  }\n\n  function clearMark(cm) {\n    cm.setExtending(false);\n    cm.setCursor(cm.getCursor());\n  }\n\n  function getInput(cm, msg, f) {\n    if (cm.openDialog)\n      cm.openDialog(msg + \": <input type=\\\"text\\\" style=\\\"width: 10em\\\"/>\", f, {bottom: true});\n    else\n      f(prompt(msg, \"\"));\n  }\n\n  function operateOnWord(cm, op) {\n    var start = cm.getCursor(), end = cm.findPosH(start, 1, \"word\");\n    cm.replaceRange(op(cm.getRange(start, end)), start, end);\n    cm.setCursor(end);\n  }\n\n  function toEnclosingExpr(cm) {\n    var pos = cm.getCursor(), line = pos.line, ch = pos.ch;\n    var stack = [];\n    while (line >= cm.firstLine()) {\n      var text = cm.getLine(line);\n      for (var i = ch == null ? text.length : ch; i > 0;) {\n        var ch = text.charAt(--i);\n        if (ch == \")\")\n          stack.push(\"(\");\n        else if (ch == \"]\")\n          stack.push(\"[\");\n        else if (ch == \"}\")\n          stack.push(\"{\");\n        else if (/[\\(\\{\\[]/.test(ch) && (!stack.length || stack.pop() != ch))\n          return cm.extendSelection(Pos(line, i));\n      }\n      --line; ch = null;\n    }\n  }\n\n  function quit(cm) {\n    cm.execCommand(\"clearSearch\");\n    clearMark(cm);\n  }\n\n  CodeMirror.emacs = {kill: kill, killRegion: killRegion, repeated: repeated};\n\n  // Actual keymap\n\n  var keyMap = CodeMirror.keyMap.emacs = CodeMirror.normalizeKeyMap({\n    \"Ctrl-W\": function(cm) {kill(cm, cm.getCursor(\"start\"), cm.getCursor(\"end\"), true);},\n    \"Ctrl-K\": repeated(function(cm) {\n      var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));\n      var text = cm.getRange(start, end);\n      if (!/\\S/.test(text)) {\n        text += \"\\n\";\n        end = Pos(start.line + 1, 0);\n      }\n      kill(cm, start, end, \"grow\", text);\n    }),\n    \"Alt-W\": function(cm) {\n      addToRing(cm.getSelection());\n      clearMark(cm);\n    },\n    \"Ctrl-Y\": function(cm) {\n      var start = cm.getCursor();\n      cm.replaceRange(getFromRing(getPrefix(cm)), start, start, \"paste\");\n      cm.setSelection(start, cm.getCursor());\n    },\n    \"Alt-Y\": function(cm) {cm.replaceSelection(popFromRing(), \"around\", \"paste\");},\n\n    \"Ctrl-Space\": setMark, \"Ctrl-Shift-2\": setMark,\n\n    \"Ctrl-F\": move(byChar, 1), \"Ctrl-B\": move(byChar, -1),\n    \"Right\": move(byChar, 1), \"Left\": move(byChar, -1),\n    \"Ctrl-D\": function(cm) { killTo(cm, byChar, 1, false); },\n    \"Delete\": function(cm) { killRegion(cm, false) || killTo(cm, byChar, 1, false); },\n    \"Ctrl-H\": function(cm) { killTo(cm, byChar, -1, false); },\n    \"Backspace\": function(cm) { killRegion(cm, false) || killTo(cm, byChar, -1, false); },\n\n    \"Alt-F\": move(byWord, 1), \"Alt-B\": move(byWord, -1),\n    \"Alt-Right\": move(byWord, 1), \"Alt-Left\": move(byWord, -1),\n    \"Alt-D\": function(cm) { killTo(cm, byWord, 1, \"grow\"); },\n    \"Alt-Backspace\": function(cm) { killTo(cm, byWord, -1, \"grow\"); },\n\n    \"Ctrl-N\": move(byLine, 1), \"Ctrl-P\": move(byLine, -1),\n    \"Down\": move(byLine, 1), \"Up\": move(byLine, -1),\n    \"Ctrl-A\": \"goLineStart\", \"Ctrl-E\": \"goLineEnd\",\n    \"End\": \"goLineEnd\", \"Home\": \"goLineStart\",\n\n    \"Alt-V\": move(byPage, -1), \"Ctrl-V\": move(byPage, 1),\n    \"PageUp\": move(byPage, -1), \"PageDown\": move(byPage, 1),\n\n    \"Ctrl-Up\": move(byParagraph, -1), \"Ctrl-Down\": move(byParagraph, 1),\n\n    \"Alt-A\": move(bySentence, -1), \"Alt-E\": move(bySentence, 1),\n    \"Alt-K\": function(cm) { killTo(cm, bySentence, 1, \"grow\"); },\n\n    \"Ctrl-Alt-K\": function(cm) { killTo(cm, byExpr, 1, \"grow\"); },\n    \"Ctrl-Alt-Backspace\": function(cm) { killTo(cm, byExpr, -1, \"grow\"); },\n    \"Ctrl-Alt-F\": move(byExpr, 1), \"Ctrl-Alt-B\": move(byExpr, -1, \"grow\"),\n\n    \"Shift-Ctrl-Alt-2\": function(cm) {\n      var cursor = cm.getCursor();\n      cm.setSelection(findEnd(cm, cursor, byExpr, 1), cursor);\n    },\n    \"Ctrl-Alt-T\": function(cm) {\n      var leftStart = byExpr(cm, cm.getCursor(), -1), leftEnd = byExpr(cm, leftStart, 1);\n      var rightEnd = byExpr(cm, leftEnd, 1), rightStart = byExpr(cm, rightEnd, -1);\n      cm.replaceRange(cm.getRange(rightStart, rightEnd) + cm.getRange(leftEnd, rightStart) +\n                      cm.getRange(leftStart, leftEnd), leftStart, rightEnd);\n    },\n    \"Ctrl-Alt-U\": repeated(toEnclosingExpr),\n\n    \"Alt-Space\": function(cm) {\n      var pos = cm.getCursor(), from = pos.ch, to = pos.ch, text = cm.getLine(pos.line);\n      while (from && /\\s/.test(text.charAt(from - 1))) --from;\n      while (to < text.length && /\\s/.test(text.charAt(to))) ++to;\n      cm.replaceRange(\" \", Pos(pos.line, from), Pos(pos.line, to));\n    },\n    \"Ctrl-O\": repeated(function(cm) { cm.replaceSelection(\"\\n\", \"start\"); }),\n    \"Ctrl-T\": repeated(function(cm) {\n      cm.execCommand(\"transposeChars\");\n    }),\n\n    \"Alt-C\": repeated(function(cm) {\n      operateOnWord(cm, function(w) {\n        var letter = w.search(/\\w/);\n        if (letter == -1) return w;\n        return w.slice(0, letter) + w.charAt(letter).toUpperCase() + w.slice(letter + 1).toLowerCase();\n      });\n    }),\n    \"Alt-U\": repeated(function(cm) {\n      operateOnWord(cm, function(w) { return w.toUpperCase(); });\n    }),\n    \"Alt-L\": repeated(function(cm) {\n      operateOnWord(cm, function(w) { return w.toLowerCase(); });\n    }),\n\n    \"Alt-;\": \"toggleComment\",\n\n    \"Ctrl-/\": repeated(\"undo\"), \"Shift-Ctrl--\": repeated(\"undo\"),\n    \"Ctrl-Z\": repeated(\"undo\"), \"Cmd-Z\": repeated(\"undo\"),\n    \"Shift-Alt-,\": \"goDocStart\", \"Shift-Alt-.\": \"goDocEnd\",\n    \"Ctrl-S\": \"findPersistentNext\", \"Ctrl-R\": \"findPersistentPrev\", \"Ctrl-G\": quit, \"Shift-Alt-5\": \"replace\",\n    \"Alt-/\": \"autocomplete\",\n    \"Enter\": \"newlineAndIndent\",\n    \"Ctrl-J\": repeated(function(cm) { cm.replaceSelection(\"\\n\", \"end\"); }),\n    \"Tab\": \"indentAuto\",\n\n    \"Alt-G G\": function(cm) {\n      var prefix = getPrefix(cm, true);\n      if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);\n\n      getInput(cm, \"Goto line\", function(str) {\n        var num;\n        if (str && !isNaN(num = Number(str)) && num == (num|0) && num > 0)\n          cm.setCursor(num - 1);\n      });\n    },\n\n    \"Ctrl-X Tab\": function(cm) {\n      cm.indentSelection(getPrefix(cm, true) || cm.getOption(\"indentUnit\"));\n    },\n    \"Ctrl-X Ctrl-X\": function(cm) {\n      cm.setSelection(cm.getCursor(\"head\"), cm.getCursor(\"anchor\"));\n    },\n    \"Ctrl-X Ctrl-S\": \"save\",\n    \"Ctrl-X Ctrl-W\": \"save\",\n    \"Ctrl-X S\": \"saveAll\",\n    \"Ctrl-X F\": \"open\",\n    \"Ctrl-X U\": repeated(\"undo\"),\n    \"Ctrl-X K\": \"close\",\n    \"Ctrl-X Delete\": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), \"grow\"); },\n    \"Ctrl-X H\": \"selectAll\",\n\n    \"Ctrl-Q Tab\": repeated(\"insertTab\"),\n    \"Ctrl-U\": addPrefixMap\n  });\n\n  var prefixMap = {\"Ctrl-G\": clearPrefix};\n  function regPrefix(d) {\n    prefixMap[d] = function(cm) { addPrefix(cm, d); };\n    keyMap[\"Ctrl-\" + d] = function(cm) { addPrefix(cm, d); };\n    prefixPreservingKeys[\"Ctrl-\" + d] = true;\n  }\n  for (var i = 0; i < 10; ++i) regPrefix(String(i));\n  regPrefix(\"-\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/keymap/sublime.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// A rough approximation of Sublime Text's keybindings\n// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../lib/codemirror\"), require(\"../addon/search/searchcursor\"), require(\"../addon/edit/matchbrackets\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../lib/codemirror\", \"../addon/search/searchcursor\", \"../addon/edit/matchbrackets\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var cmds = CodeMirror.commands;\n  var Pos = CodeMirror.Pos;\n\n  // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that.\n  function findPosSubword(doc, start, dir) {\n    if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));\n    var line = doc.getLine(start.line);\n    if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));\n    var state = \"start\", type;\n    for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {\n      var next = line.charAt(dir < 0 ? pos - 1 : pos);\n      var cat = next != \"_\" && CodeMirror.isWordChar(next) ? \"w\" : \"o\";\n      if (cat == \"w\" && next.toUpperCase() == next) cat = \"W\";\n      if (state == \"start\") {\n        if (cat != \"o\") { state = \"in\"; type = cat; }\n      } else if (state == \"in\") {\n        if (type != cat) {\n          if (type == \"w\" && cat == \"W\" && dir < 0) pos--;\n          if (type == \"W\" && cat == \"w\" && dir > 0) { type = \"w\"; continue; }\n          break;\n        }\n      }\n    }\n    return Pos(start.line, pos);\n  }\n\n  function moveSubword(cm, dir) {\n    cm.extendSelectionsBy(function(range) {\n      if (cm.display.shift || cm.doc.extend || range.empty())\n        return findPosSubword(cm.doc, range.head, dir);\n      else\n        return dir < 0 ? range.from() : range.to();\n    });\n  }\n\n  cmds.goSubwordLeft = function(cm) { moveSubword(cm, -1); };\n  cmds.goSubwordRight = function(cm) { moveSubword(cm, 1); };\n\n  cmds.scrollLineUp = function(cm) {\n    var info = cm.getScrollInfo();\n    if (!cm.somethingSelected()) {\n      var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, \"local\");\n      if (cm.getCursor().line >= visibleBottomLine)\n        cm.execCommand(\"goLineUp\");\n    }\n    cm.scrollTo(null, info.top - cm.defaultTextHeight());\n  };\n  cmds.scrollLineDown = function(cm) {\n    var info = cm.getScrollInfo();\n    if (!cm.somethingSelected()) {\n      var visibleTopLine = cm.lineAtHeight(info.top, \"local\")+1;\n      if (cm.getCursor().line <= visibleTopLine)\n        cm.execCommand(\"goLineDown\");\n    }\n    cm.scrollTo(null, info.top + cm.defaultTextHeight());\n  };\n\n  cmds.splitSelectionByLine = function(cm) {\n    var ranges = cm.listSelections(), lineRanges = [];\n    for (var i = 0; i < ranges.length; i++) {\n      var from = ranges[i].from(), to = ranges[i].to();\n      for (var line = from.line; line <= to.line; ++line)\n        if (!(to.line > from.line && line == to.line && to.ch == 0))\n          lineRanges.push({anchor: line == from.line ? from : Pos(line, 0),\n                           head: line == to.line ? to : Pos(line)});\n    }\n    cm.setSelections(lineRanges, 0);\n  };\n\n  cmds.singleSelectionTop = function(cm) {\n    var range = cm.listSelections()[0];\n    cm.setSelection(range.anchor, range.head, {scroll: false});\n  };\n\n  cmds.selectLine = function(cm) {\n    var ranges = cm.listSelections(), extended = [];\n    for (var i = 0; i < ranges.length; i++) {\n      var range = ranges[i];\n      extended.push({anchor: Pos(range.from().line, 0),\n                     head: Pos(range.to().line + 1, 0)});\n    }\n    cm.setSelections(extended);\n  };\n\n  function insertLine(cm, above) {\n    if (cm.isReadOnly()) return CodeMirror.Pass\n    cm.operation(function() {\n      var len = cm.listSelections().length, newSelection = [], last = -1;\n      for (var i = 0; i < len; i++) {\n        var head = cm.listSelections()[i].head;\n        if (head.line <= last) continue;\n        var at = Pos(head.line + (above ? 0 : 1), 0);\n        cm.replaceRange(\"\\n\", at, null, \"+insertLine\");\n        cm.indentLine(at.line, null, true);\n        newSelection.push({head: at, anchor: at});\n        last = head.line + 1;\n      }\n      cm.setSelections(newSelection);\n    });\n    cm.execCommand(\"indentAuto\");\n  }\n\n  cmds.insertLineAfter = function(cm) { return insertLine(cm, false); };\n\n  cmds.insertLineBefore = function(cm) { return insertLine(cm, true); };\n\n  function wordAt(cm, pos) {\n    var start = pos.ch, end = start, line = cm.getLine(pos.line);\n    while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;\n    while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;\n    return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};\n  }\n\n  cmds.selectNextOccurrence = function(cm) {\n    var from = cm.getCursor(\"from\"), to = cm.getCursor(\"to\");\n    var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel;\n    if (CodeMirror.cmpPos(from, to) == 0) {\n      var word = wordAt(cm, from);\n      if (!word.word) return;\n      cm.setSelection(word.from, word.to);\n      fullWord = true;\n    } else {\n      var text = cm.getRange(from, to);\n      var query = fullWord ? new RegExp(\"\\\\b\" + text + \"\\\\b\") : text;\n      var cur = cm.getSearchCursor(query, to);\n      var found = cur.findNext();\n      if (!found) {\n        cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0));\n        found = cur.findNext();\n      }\n      if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to()))\n        return CodeMirror.Pass\n      cm.addSelection(cur.from(), cur.to());\n    }\n    if (fullWord)\n      cm.state.sublimeFindFullWord = cm.doc.sel;\n  };\n\n  function addCursorToSelection(cm, dir) {\n    var ranges = cm.listSelections(), newRanges = [];\n    for (var i = 0; i < ranges.length; i++) {\n      var range = ranges[i];\n      var newAnchor = cm.findPosV(\n          range.anchor, dir, \"line\", range.anchor.goalColumn);\n      var newHead = cm.findPosV(\n          range.head, dir, \"line\", range.head.goalColumn);\n      newAnchor.goalColumn = range.anchor.goalColumn != null ?\n          range.anchor.goalColumn : cm.cursorCoords(range.anchor, \"div\").left;\n      newHead.goalColumn = range.head.goalColumn != null ?\n          range.head.goalColumn : cm.cursorCoords(range.head, \"div\").left;\n      var newRange = {anchor: newAnchor, head: newHead};\n      newRanges.push(range);\n      newRanges.push(newRange);\n    }\n    cm.setSelections(newRanges);\n  }\n  cmds.addCursorToPrevLine = function(cm) { addCursorToSelection(cm, -1); };\n  cmds.addCursorToNextLine = function(cm) { addCursorToSelection(cm, 1); };\n\n  function isSelectedRange(ranges, from, to) {\n    for (var i = 0; i < ranges.length; i++)\n      if (ranges[i].from() == from && ranges[i].to() == to) return true\n    return false\n  }\n\n  var mirror = \"(){}[]\";\n  function selectBetweenBrackets(cm) {\n    var ranges = cm.listSelections(), newRanges = []\n    for (var i = 0; i < ranges.length; i++) {\n      var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1);\n      if (!opening) return false;\n      for (;;) {\n        var closing = cm.scanForBracket(pos, 1);\n        if (!closing) return false;\n        if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {\n          var startPos = Pos(opening.pos.line, opening.pos.ch + 1);\n          if (CodeMirror.cmpPos(startPos, range.from()) == 0 &&\n              CodeMirror.cmpPos(closing.pos, range.to()) == 0) {\n            opening = cm.scanForBracket(opening.pos, -1);\n            if (!opening) return false;\n          } else {\n            newRanges.push({anchor: startPos, head: closing.pos});\n            break;\n          }\n        }\n        pos = Pos(closing.pos.line, closing.pos.ch + 1);\n      }\n    }\n    cm.setSelections(newRanges);\n    return true;\n  }\n\n  cmds.selectScope = function(cm) {\n    selectBetweenBrackets(cm) || cm.execCommand(\"selectAll\");\n  };\n  cmds.selectBetweenBrackets = function(cm) {\n    if (!selectBetweenBrackets(cm)) return CodeMirror.Pass;\n  };\n\n  cmds.goToBracket = function(cm) {\n    cm.extendSelectionsBy(function(range) {\n      var next = cm.scanForBracket(range.head, 1);\n      if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos;\n      var prev = cm.scanForBracket(range.head, -1);\n      return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head;\n    });\n  };\n\n  cmds.swapLineUp = function(cm) {\n    if (cm.isReadOnly()) return CodeMirror.Pass\n    var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = [];\n    for (var i = 0; i < ranges.length; i++) {\n      var range = ranges[i], from = range.from().line - 1, to = range.to().line;\n      newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch),\n                    head: Pos(range.head.line - 1, range.head.ch)});\n      if (range.to().ch == 0 && !range.empty()) --to;\n      if (from > at) linesToMove.push(from, to);\n      else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;\n      at = to;\n    }\n    cm.operation(function() {\n      for (var i = 0; i < linesToMove.length; i += 2) {\n        var from = linesToMove[i], to = linesToMove[i + 1];\n        var line = cm.getLine(from);\n        cm.replaceRange(\"\", Pos(from, 0), Pos(from + 1, 0), \"+swapLine\");\n        if (to > cm.lastLine())\n          cm.replaceRange(\"\\n\" + line, Pos(cm.lastLine()), null, \"+swapLine\");\n        else\n          cm.replaceRange(line + \"\\n\", Pos(to, 0), null, \"+swapLine\");\n      }\n      cm.setSelections(newSels);\n      cm.scrollIntoView();\n    });\n  };\n\n  cmds.swapLineDown = function(cm) {\n    if (cm.isReadOnly()) return CodeMirror.Pass\n    var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1;\n    for (var i = ranges.length - 1; i >= 0; i--) {\n      var range = ranges[i], from = range.to().line + 1, to = range.from().line;\n      if (range.to().ch == 0 && !range.empty()) from--;\n      if (from < at) linesToMove.push(from, to);\n      else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;\n      at = to;\n    }\n    cm.operation(function() {\n      for (var i = linesToMove.length - 2; i >= 0; i -= 2) {\n        var from = linesToMove[i], to = linesToMove[i + 1];\n        var line = cm.getLine(from);\n        if (from == cm.lastLine())\n          cm.replaceRange(\"\", Pos(from - 1), Pos(from), \"+swapLine\");\n        else\n          cm.replaceRange(\"\", Pos(from, 0), Pos(from + 1, 0), \"+swapLine\");\n        cm.replaceRange(line + \"\\n\", Pos(to, 0), null, \"+swapLine\");\n      }\n      cm.scrollIntoView();\n    });\n  };\n\n  cmds.toggleCommentIndented = function(cm) {\n    cm.toggleComment({ indent: true });\n  }\n\n  cmds.joinLines = function(cm) {\n    var ranges = cm.listSelections(), joined = [];\n    for (var i = 0; i < ranges.length; i++) {\n      var range = ranges[i], from = range.from();\n      var start = from.line, end = range.to().line;\n      while (i < ranges.length - 1 && ranges[i + 1].from().line == end)\n        end = ranges[++i].to().line;\n      joined.push({start: start, end: end, anchor: !range.empty() && from});\n    }\n    cm.operation(function() {\n      var offset = 0, ranges = [];\n      for (var i = 0; i < joined.length; i++) {\n        var obj = joined[i];\n        var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head;\n        for (var line = obj.start; line <= obj.end; line++) {\n          var actual = line - offset;\n          if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1);\n          if (actual < cm.lastLine()) {\n            cm.replaceRange(\" \", Pos(actual), Pos(actual + 1, /^\\s*/.exec(cm.getLine(actual + 1))[0].length));\n            ++offset;\n          }\n        }\n        ranges.push({anchor: anchor || head, head: head});\n      }\n      cm.setSelections(ranges, 0);\n    });\n  };\n\n  cmds.duplicateLine = function(cm) {\n    cm.operation(function() {\n      var rangeCount = cm.listSelections().length;\n      for (var i = 0; i < rangeCount; i++) {\n        var range = cm.listSelections()[i];\n        if (range.empty())\n          cm.replaceRange(cm.getLine(range.head.line) + \"\\n\", Pos(range.head.line, 0));\n        else\n          cm.replaceRange(cm.getRange(range.from(), range.to()), range.from());\n      }\n      cm.scrollIntoView();\n    });\n  };\n\n\n  function sortLines(cm, caseSensitive) {\n    if (cm.isReadOnly()) return CodeMirror.Pass\n    var ranges = cm.listSelections(), toSort = [], selected;\n    for (var i = 0; i < ranges.length; i++) {\n      var range = ranges[i];\n      if (range.empty()) continue;\n      var from = range.from().line, to = range.to().line;\n      while (i < ranges.length - 1 && ranges[i + 1].from().line == to)\n        to = ranges[++i].to().line;\n      if (!ranges[i].to().ch) to--;\n      toSort.push(from, to);\n    }\n    if (toSort.length) selected = true;\n    else toSort.push(cm.firstLine(), cm.lastLine());\n\n    cm.operation(function() {\n      var ranges = [];\n      for (var i = 0; i < toSort.length; i += 2) {\n        var from = toSort[i], to = toSort[i + 1];\n        var start = Pos(from, 0), end = Pos(to);\n        var lines = cm.getRange(start, end, false);\n        if (caseSensitive)\n          lines.sort();\n        else\n          lines.sort(function(a, b) {\n            var au = a.toUpperCase(), bu = b.toUpperCase();\n            if (au != bu) { a = au; b = bu; }\n            return a < b ? -1 : a == b ? 0 : 1;\n          });\n        cm.replaceRange(lines, start, end);\n        if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)});\n      }\n      if (selected) cm.setSelections(ranges, 0);\n    });\n  }\n\n  cmds.sortLines = function(cm) { sortLines(cm, true); };\n  cmds.sortLinesInsensitive = function(cm) { sortLines(cm, false); };\n\n  cmds.nextBookmark = function(cm) {\n    var marks = cm.state.sublimeBookmarks;\n    if (marks) while (marks.length) {\n      var current = marks.shift();\n      var found = current.find();\n      if (found) {\n        marks.push(current);\n        return cm.setSelection(found.from, found.to);\n      }\n    }\n  };\n\n  cmds.prevBookmark = function(cm) {\n    var marks = cm.state.sublimeBookmarks;\n    if (marks) while (marks.length) {\n      marks.unshift(marks.pop());\n      var found = marks[marks.length - 1].find();\n      if (!found)\n        marks.pop();\n      else\n        return cm.setSelection(found.from, found.to);\n    }\n  };\n\n  cmds.toggleBookmark = function(cm) {\n    var ranges = cm.listSelections();\n    var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []);\n    for (var i = 0; i < ranges.length; i++) {\n      var from = ranges[i].from(), to = ranges[i].to();\n      var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to);\n      for (var j = 0; j < found.length; j++) {\n        if (found[j].sublimeBookmark) {\n          found[j].clear();\n          for (var k = 0; k < marks.length; k++)\n            if (marks[k] == found[j])\n              marks.splice(k--, 1);\n          break;\n        }\n      }\n      if (j == found.length)\n        marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false}));\n    }\n  };\n\n  cmds.clearBookmarks = function(cm) {\n    var marks = cm.state.sublimeBookmarks;\n    if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();\n    marks.length = 0;\n  };\n\n  cmds.selectBookmarks = function(cm) {\n    var marks = cm.state.sublimeBookmarks, ranges = [];\n    if (marks) for (var i = 0; i < marks.length; i++) {\n      var found = marks[i].find();\n      if (!found)\n        marks.splice(i--, 0);\n      else\n        ranges.push({anchor: found.from, head: found.to});\n    }\n    if (ranges.length)\n      cm.setSelections(ranges, 0);\n  };\n\n  function modifyWordOrSelection(cm, mod) {\n    cm.operation(function() {\n      var ranges = cm.listSelections(), indices = [], replacements = [];\n      for (var i = 0; i < ranges.length; i++) {\n        var range = ranges[i];\n        if (range.empty()) { indices.push(i); replacements.push(\"\"); }\n        else replacements.push(mod(cm.getRange(range.from(), range.to())));\n      }\n      cm.replaceSelections(replacements, \"around\", \"case\");\n      for (var i = indices.length - 1, at; i >= 0; i--) {\n        var range = ranges[indices[i]];\n        if (at && CodeMirror.cmpPos(range.head, at) > 0) continue;\n        var word = wordAt(cm, range.head);\n        at = word.from;\n        cm.replaceRange(mod(word.word), word.from, word.to);\n      }\n    });\n  }\n\n  cmds.smartBackspace = function(cm) {\n    if (cm.somethingSelected()) return CodeMirror.Pass;\n\n    cm.operation(function() {\n      var cursors = cm.listSelections();\n      var indentUnit = cm.getOption(\"indentUnit\");\n\n      for (var i = cursors.length - 1; i >= 0; i--) {\n        var cursor = cursors[i].head;\n        var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor);\n        var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption(\"tabSize\"));\n\n        // Delete by one character by default\n        var deletePos = cm.findPosH(cursor, -1, \"char\", false);\n\n        if (toStartOfLine && !/\\S/.test(toStartOfLine) && column % indentUnit == 0) {\n          var prevIndent = new Pos(cursor.line,\n            CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit));\n\n          // Smart delete only if we found a valid prevIndent location\n          if (prevIndent.ch != cursor.ch) deletePos = prevIndent;\n        }\n\n        cm.replaceRange(\"\", deletePos, cursor, \"+delete\");\n      }\n    });\n  };\n\n  cmds.delLineRight = function(cm) {\n    cm.operation(function() {\n      var ranges = cm.listSelections();\n      for (var i = ranges.length - 1; i >= 0; i--)\n        cm.replaceRange(\"\", ranges[i].anchor, Pos(ranges[i].to().line), \"+delete\");\n      cm.scrollIntoView();\n    });\n  };\n\n  cmds.upcaseAtCursor = function(cm) {\n    modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });\n  };\n  cmds.downcaseAtCursor = function(cm) {\n    modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });\n  };\n\n  cmds.setSublimeMark = function(cm) {\n    if (cm.state.sublimeMark) cm.state.sublimeMark.clear();\n    cm.state.sublimeMark = cm.setBookmark(cm.getCursor());\n  };\n  cmds.selectToSublimeMark = function(cm) {\n    var found = cm.state.sublimeMark && cm.state.sublimeMark.find();\n    if (found) cm.setSelection(cm.getCursor(), found);\n  };\n  cmds.deleteToSublimeMark = function(cm) {\n    var found = cm.state.sublimeMark && cm.state.sublimeMark.find();\n    if (found) {\n      var from = cm.getCursor(), to = found;\n      if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; }\n      cm.state.sublimeKilled = cm.getRange(from, to);\n      cm.replaceRange(\"\", from, to);\n    }\n  };\n  cmds.swapWithSublimeMark = function(cm) {\n    var found = cm.state.sublimeMark && cm.state.sublimeMark.find();\n    if (found) {\n      cm.state.sublimeMark.clear();\n      cm.state.sublimeMark = cm.setBookmark(cm.getCursor());\n      cm.setCursor(found);\n    }\n  };\n  cmds.sublimeYank = function(cm) {\n    if (cm.state.sublimeKilled != null)\n      cm.replaceSelection(cm.state.sublimeKilled, null, \"paste\");\n  };\n\n  cmds.showInCenter = function(cm) {\n    var pos = cm.cursorCoords(null, \"local\");\n    cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);\n  };\n\n  function getTarget(cm) {\n    var from = cm.getCursor(\"from\"), to = cm.getCursor(\"to\");\n    if (CodeMirror.cmpPos(from, to) == 0) {\n      var word = wordAt(cm, from);\n      if (!word.word) return;\n      from = word.from;\n      to = word.to;\n    }\n    return {from: from, to: to, query: cm.getRange(from, to), word: word};\n  }\n\n  function findAndGoTo(cm, forward) {\n    var target = getTarget(cm);\n    if (!target) return;\n    var query = target.query;\n    var cur = cm.getSearchCursor(query, forward ? target.to : target.from);\n\n    if (forward ? cur.findNext() : cur.findPrevious()) {\n      cm.setSelection(cur.from(), cur.to());\n    } else {\n      cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0)\n                                              : cm.clipPos(Pos(cm.lastLine())));\n      if (forward ? cur.findNext() : cur.findPrevious())\n        cm.setSelection(cur.from(), cur.to());\n      else if (target.word)\n        cm.setSelection(target.from, target.to);\n    }\n  };\n  cmds.findUnder = function(cm) { findAndGoTo(cm, true); };\n  cmds.findUnderPrevious = function(cm) { findAndGoTo(cm,false); };\n  cmds.findAllUnder = function(cm) {\n    var target = getTarget(cm);\n    if (!target) return;\n    var cur = cm.getSearchCursor(target.query);\n    var matches = [];\n    var primaryIndex = -1;\n    while (cur.findNext()) {\n      matches.push({anchor: cur.from(), head: cur.to()});\n      if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch)\n        primaryIndex++;\n    }\n    cm.setSelections(matches, primaryIndex);\n  };\n\n\n  var keyMap = CodeMirror.keyMap;\n  keyMap.macSublime = {\n    \"Cmd-Left\": \"goLineStartSmart\",\n    \"Shift-Tab\": \"indentLess\",\n    \"Shift-Ctrl-K\": \"deleteLine\",\n    \"Alt-Q\": \"wrapLines\",\n    \"Ctrl-Left\": \"goSubwordLeft\",\n    \"Ctrl-Right\": \"goSubwordRight\",\n    \"Ctrl-Alt-Up\": \"scrollLineUp\",\n    \"Ctrl-Alt-Down\": \"scrollLineDown\",\n    \"Cmd-L\": \"selectLine\",\n    \"Shift-Cmd-L\": \"splitSelectionByLine\",\n    \"Esc\": \"singleSelectionTop\",\n    \"Cmd-Enter\": \"insertLineAfter\",\n    \"Shift-Cmd-Enter\": \"insertLineBefore\",\n    \"Cmd-D\": \"selectNextOccurrence\",\n    \"Shift-Cmd-Space\": \"selectScope\",\n    \"Shift-Cmd-M\": \"selectBetweenBrackets\",\n    \"Cmd-M\": \"goToBracket\",\n    \"Cmd-Ctrl-Up\": \"swapLineUp\",\n    \"Cmd-Ctrl-Down\": \"swapLineDown\",\n    \"Cmd-/\": \"toggleCommentIndented\",\n    \"Cmd-J\": \"joinLines\",\n    \"Shift-Cmd-D\": \"duplicateLine\",\n    \"F9\": \"sortLines\",\n    \"Cmd-F9\": \"sortLinesInsensitive\",\n    \"F2\": \"nextBookmark\",\n    \"Shift-F2\": \"prevBookmark\",\n    \"Cmd-F2\": \"toggleBookmark\",\n    \"Shift-Cmd-F2\": \"clearBookmarks\",\n    \"Alt-F2\": \"selectBookmarks\",\n    \"Backspace\": \"smartBackspace\",\n    \"Cmd-K Cmd-K\": \"delLineRight\",\n    \"Cmd-K Cmd-U\": \"upcaseAtCursor\",\n    \"Cmd-K Cmd-L\": \"downcaseAtCursor\",\n    \"Cmd-K Cmd-Space\": \"setSublimeMark\",\n    \"Cmd-K Cmd-A\": \"selectToSublimeMark\",\n    \"Cmd-K Cmd-W\": \"deleteToSublimeMark\",\n    \"Cmd-K Cmd-X\": \"swapWithSublimeMark\",\n    \"Cmd-K Cmd-Y\": \"sublimeYank\",\n    \"Cmd-K Cmd-C\": \"showInCenter\",\n    \"Cmd-K Cmd-G\": \"clearBookmarks\",\n    \"Cmd-K Cmd-Backspace\": \"delLineLeft\",\n    \"Cmd-K Cmd-0\": \"unfoldAll\",\n    \"Cmd-K Cmd-J\": \"unfoldAll\",\n    \"Ctrl-Shift-Up\": \"addCursorToPrevLine\",\n    \"Ctrl-Shift-Down\": \"addCursorToNextLine\",\n    \"Cmd-F3\": \"findUnder\",\n    \"Shift-Cmd-F3\": \"findUnderPrevious\",\n    \"Alt-F3\": \"findAllUnder\",\n    \"Shift-Cmd-[\": \"fold\",\n    \"Shift-Cmd-]\": \"unfold\",\n    \"Cmd-I\": \"findIncremental\",\n    \"Shift-Cmd-I\": \"findIncrementalReverse\",\n    \"Cmd-H\": \"replace\",\n    \"F3\": \"findNext\",\n    \"Shift-F3\": \"findPrev\",\n    \"fallthrough\": \"macDefault\"\n  };\n  CodeMirror.normalizeKeyMap(keyMap.macSublime);\n\n  keyMap.pcSublime = {\n    \"Shift-Tab\": \"indentLess\",\n    \"Shift-Ctrl-K\": \"deleteLine\",\n    \"Alt-Q\": \"wrapLines\",\n    \"Ctrl-T\": \"transposeChars\",\n    \"Alt-Left\": \"goSubwordLeft\",\n    \"Alt-Right\": \"goSubwordRight\",\n    \"Ctrl-Up\": \"scrollLineUp\",\n    \"Ctrl-Down\": \"scrollLineDown\",\n    \"Ctrl-L\": \"selectLine\",\n    \"Shift-Ctrl-L\": \"splitSelectionByLine\",\n    \"Esc\": \"singleSelectionTop\",\n    \"Ctrl-Enter\": \"insertLineAfter\",\n    \"Shift-Ctrl-Enter\": \"insertLineBefore\",\n    \"Ctrl-D\": \"selectNextOccurrence\",\n    \"Shift-Ctrl-Space\": \"selectScope\",\n    \"Shift-Ctrl-M\": \"selectBetweenBrackets\",\n    \"Ctrl-M\": \"goToBracket\",\n    \"Shift-Ctrl-Up\": \"swapLineUp\",\n    \"Shift-Ctrl-Down\": \"swapLineDown\",\n    \"Ctrl-/\": \"toggleCommentIndented\",\n    \"Ctrl-J\": \"joinLines\",\n    \"Shift-Ctrl-D\": \"duplicateLine\",\n    \"F9\": \"sortLines\",\n    \"Ctrl-F9\": \"sortLinesInsensitive\",\n    \"F2\": \"nextBookmark\",\n    \"Shift-F2\": \"prevBookmark\",\n    \"Ctrl-F2\": \"toggleBookmark\",\n    \"Shift-Ctrl-F2\": \"clearBookmarks\",\n    \"Alt-F2\": \"selectBookmarks\",\n    \"Backspace\": \"smartBackspace\",\n    \"Ctrl-K Ctrl-K\": \"delLineRight\",\n    \"Ctrl-K Ctrl-U\": \"upcaseAtCursor\",\n    \"Ctrl-K Ctrl-L\": \"downcaseAtCursor\",\n    \"Ctrl-K Ctrl-Space\": \"setSublimeMark\",\n    \"Ctrl-K Ctrl-A\": \"selectToSublimeMark\",\n    \"Ctrl-K Ctrl-W\": \"deleteToSublimeMark\",\n    \"Ctrl-K Ctrl-X\": \"swapWithSublimeMark\",\n    \"Ctrl-K Ctrl-Y\": \"sublimeYank\",\n    \"Ctrl-K Ctrl-C\": \"showInCenter\",\n    \"Ctrl-K Ctrl-G\": \"clearBookmarks\",\n    \"Ctrl-K Ctrl-Backspace\": \"delLineLeft\",\n    \"Ctrl-K Ctrl-0\": \"unfoldAll\",\n    \"Ctrl-K Ctrl-J\": \"unfoldAll\",\n    \"Ctrl-Alt-Up\": \"addCursorToPrevLine\",\n    \"Ctrl-Alt-Down\": \"addCursorToNextLine\",\n    \"Ctrl-F3\": \"findUnder\",\n    \"Shift-Ctrl-F3\": \"findUnderPrevious\",\n    \"Alt-F3\": \"findAllUnder\",\n    \"Shift-Ctrl-[\": \"fold\",\n    \"Shift-Ctrl-]\": \"unfold\",\n    \"Ctrl-I\": \"findIncremental\",\n    \"Shift-Ctrl-I\": \"findIncrementalReverse\",\n    \"Ctrl-H\": \"replace\",\n    \"F3\": \"findNext\",\n    \"Shift-F3\": \"findPrev\",\n    \"fallthrough\": \"pcDefault\"\n  };\n  CodeMirror.normalizeKeyMap(keyMap.pcSublime);\n\n  var mac = keyMap.default == keyMap.macDefault;\n  keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime;\n});\n"
  },
  {
    "path": "third_party/CodeMirror/keymap/vim.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**\n * Supported keybindings:\n *   Too many to list. Refer to defaultKeymap below.\n *\n * Supported Ex commands:\n *   Refer to defaultExCommandMap below.\n *\n * Registers: unnamed, -, a-z, A-Z, 0-9\n *   (Does not respect the special case for number registers when delete\n *    operator is made with these commands: %, (, ),  , /, ?, n, N, {, } )\n *   TODO: Implement the remaining registers.\n *\n * Marks: a-z, A-Z, and 0-9\n *   TODO: Implement the remaining special marks. They have more complex\n *       behavior.\n *\n * Events:\n *  'vim-mode-change' - raised on the editor anytime the current mode changes,\n *                      Event object: {mode: \"visual\", subMode: \"linewise\"}\n *\n * Code structure:\n *  1. Default keymap\n *  2. Variable declarations and short basic helpers\n *  3. Instance (External API) implementation\n *  4. Internal state tracking objects (input state, counter) implementation\n *     and instantiation\n *  5. Key handler (the main command dispatcher) implementation\n *  6. Motion, operator, and action implementations\n *  7. Helper functions for the key handler, motions, operators, and actions\n *  8. Set up Vim to work as a keymap for CodeMirror.\n *  9. Ex command implementations.\n */\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../lib/codemirror\"), require(\"../addon/search/searchcursor\"), require(\"../addon/dialog/dialog\"), require(\"../addon/edit/matchbrackets.js\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../lib/codemirror\", \"../addon/search/searchcursor\", \"../addon/dialog/dialog\", \"../addon/edit/matchbrackets\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  'use strict';\n\n  var defaultKeymap = [\n    // Key to key mapping. This goes first to make it possible to override\n    // existing mappings.\n    { keys: '<Left>', type: 'keyToKey', toKeys: 'h' },\n    { keys: '<Right>', type: 'keyToKey', toKeys: 'l' },\n    { keys: '<Up>', type: 'keyToKey', toKeys: 'k' },\n    { keys: '<Down>', type: 'keyToKey', toKeys: 'j' },\n    { keys: '<Space>', type: 'keyToKey', toKeys: 'l' },\n    { keys: '<BS>', type: 'keyToKey', toKeys: 'h', context: 'normal'},\n    { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },\n    { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B', context: 'normal' },\n    { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },\n    { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b', context: 'normal' },\n    { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },\n    { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },\n    { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },\n    { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },\n    { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },\n    { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },\n    { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },\n    { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'},\n    { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },\n    { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' },\n    { keys: '<Home>', type: 'keyToKey', toKeys: '0' },\n    { keys: '<End>', type: 'keyToKey', toKeys: '$' },\n    { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },\n    { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },\n    { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },\n    { keys: '<Ins>', type: 'action', action: 'toggleOverwrite', context: 'insert' },\n    // Motions\n    { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},\n    { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},\n    { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},\n    { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},\n    { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},\n    { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},\n    { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},\n    { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},\n    { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},\n    { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},\n    { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},\n    { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},\n    { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},\n    { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},\n    { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},\n    { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},\n    { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},\n    { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},\n    { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},\n    { keys: '(', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: false }},\n    { keys: ')', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: true }},\n    { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},\n    { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},\n    { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},\n    { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},\n    { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},\n    { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},\n    { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },\n    { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },\n    { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},\n    { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},\n    { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},\n    { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},\n    { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},\n    { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},\n    { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},\n    { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},\n    { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},\n    { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},\n    { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},\n    { keys: '\\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},\n    { keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},\n    { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },\n    { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },\n    { keys: ']\\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },\n    { keys: '[\\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },\n    // the next two aren't motions but must come before more general motion declarations\n    { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},\n    { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},\n    { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},\n    { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},\n    { keys: '|', type: 'motion', motion: 'moveToColumn'},\n    { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},\n    { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},\n    // Operators\n    { keys: 'd', type: 'operator', operator: 'delete' },\n    { keys: 'y', type: 'operator', operator: 'yank' },\n    { keys: 'c', type: 'operator', operator: 'change' },\n    { keys: '=', type: 'operator', operator: 'indentAuto' },\n    { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},\n    { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},\n    { keys: 'g~', type: 'operator', operator: 'changeCase' },\n    { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },\n    { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },\n    { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},\n    { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},\n    // Operator-Motion dual commands\n    { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},\n    { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},\n    { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},\n    { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},\n    { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal'},\n    { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},\n    { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},\n    { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},\n    { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},\n    { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},\n    { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },\n    //ignore C-w in normal mode\n    { keys: '<C-w>', type: 'idle', context: 'normal' },\n    // Actions\n    { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},\n    { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},\n    { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},\n    { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},\n    { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },\n    { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },\n    { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },\n    { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },\n    { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },\n    { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },\n    { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },\n    { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },\n    { keys: 'v', type: 'action', action: 'toggleVisualMode' },\n    { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},\n    { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},\n    { keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},\n    { keys: 'gv', type: 'action', action: 'reselectLastSelection' },\n    { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },\n    { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},\n    { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},\n    { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },\n    { keys: '@<character>', type: 'action', action: 'replayMacro' },\n    { keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' },\n    // Handle Replace-mode as a special case of insert mode.\n    { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }},\n    { keys: 'u', type: 'action', action: 'undo', context: 'normal' },\n    { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },\n    { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },\n    { keys: '<C-r>', type: 'action', action: 'redo' },\n    { keys: 'm<character>', type: 'action', action: 'setMark' },\n    { keys: '\"<character>', type: 'action', action: 'setRegister' },\n    { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},\n    { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },\n    { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},\n    { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },\n    { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},\n    { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },\n    { keys: '.', type: 'action', action: 'repeatLastEdit' },\n    { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},\n    { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},\n    { keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },\n    { keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },\n    // Text object motions\n    { keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },\n    { keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},\n    // Search\n    { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},\n    { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},\n    { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},\n    { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},\n    { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},\n    { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},\n    // Ex command\n    { keys: ':', type: 'ex' }\n  ];\n  var defaultKeymapLength = defaultKeymap.length;\n\n  /**\n   * Ex commands\n   * Care must be taken when adding to the default Ex command map. For any\n   * pair of commands that have a shared prefix, at least one of their\n   * shortNames must not match the prefix of the other command.\n   */\n  var defaultExCommandMap = [\n    { name: 'colorscheme', shortName: 'colo' },\n    { name: 'map' },\n    { name: 'imap', shortName: 'im' },\n    { name: 'nmap', shortName: 'nm' },\n    { name: 'vmap', shortName: 'vm' },\n    { name: 'unmap' },\n    { name: 'write', shortName: 'w' },\n    { name: 'undo', shortName: 'u' },\n    { name: 'redo', shortName: 'red' },\n    { name: 'set', shortName: 'se' },\n    { name: 'set', shortName: 'se' },\n    { name: 'setlocal', shortName: 'setl' },\n    { name: 'setglobal', shortName: 'setg' },\n    { name: 'sort', shortName: 'sor' },\n    { name: 'substitute', shortName: 's', possiblyAsync: true },\n    { name: 'nohlsearch', shortName: 'noh' },\n    { name: 'yank', shortName: 'y' },\n    { name: 'delmarks', shortName: 'delm' },\n    { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },\n    { name: 'global', shortName: 'g' }\n  ];\n\n  var Pos = CodeMirror.Pos;\n\n  var Vim = function() {\n    function enterVimMode(cm) {\n      cm.setOption('disableInput', true);\n      cm.setOption('showCursorWhenSelecting', false);\n      CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"normal\"});\n      cm.on('cursorActivity', onCursorActivity);\n      maybeInitVimState(cm);\n      CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));\n    }\n\n    function leaveVimMode(cm) {\n      cm.setOption('disableInput', false);\n      cm.off('cursorActivity', onCursorActivity);\n      CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));\n      cm.state.vim = null;\n    }\n\n    function detachVimMap(cm, next) {\n      if (this == CodeMirror.keyMap.vim) {\n        CodeMirror.rmClass(cm.getWrapperElement(), \"cm-fat-cursor\");\n        if (cm.getOption(\"inputStyle\") == \"contenteditable\" && document.body.style.caretColor != null) {\n          disableFatCursorMark(cm);\n          cm.getInputField().style.caretColor = \"\";\n        }\n      }\n\n      if (!next || next.attach != attachVimMap)\n        leaveVimMode(cm);\n    }\n    function attachVimMap(cm, prev) {\n      if (this == CodeMirror.keyMap.vim) {\n        CodeMirror.addClass(cm.getWrapperElement(), \"cm-fat-cursor\");\n        if (cm.getOption(\"inputStyle\") == \"contenteditable\" && document.body.style.caretColor != null) {\n          enableFatCursorMark(cm);\n          cm.getInputField().style.caretColor = \"transparent\";\n        }\n      }\n\n      if (!prev || prev.attach != attachVimMap)\n        enterVimMode(cm);\n    }\n\n    function fatCursorMarks(cm) {\n      var ranges = cm.listSelections(), result = []\n      for (var i = 0; i < ranges.length; i++) {\n        var range = ranges[i]\n        if (range.empty()) {\n          if (range.anchor.ch < cm.getLine(range.anchor.line).length) {\n            result.push(cm.markText(range.anchor, Pos(range.anchor.line, range.anchor.ch + 1),\n                                    {className: \"cm-fat-cursor-mark\"}))\n          } else {\n            var widget = document.createElement(\"span\")\n            widget.textContent = \"\\u00a0\"\n            widget.className = \"cm-fat-cursor-mark\"\n            result.push(cm.setBookmark(range.anchor, {widget: widget}))\n          }\n        }\n      }\n      return result\n    }\n\n    function updateFatCursorMark(cm) {\n      var marks = cm.state.fatCursorMarks\n      if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear()\n      cm.state.fatCursorMarks = fatCursorMarks(cm)\n    }\n\n    function enableFatCursorMark(cm) {\n      cm.state.fatCursorMarks = fatCursorMarks(cm)\n      cm.on(\"cursorActivity\", updateFatCursorMark)\n    }\n\n    function disableFatCursorMark(cm) {\n      var marks = cm.state.fatCursorMarks\n      if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear()\n      cm.state.fatCursorMarks = null\n      cm.off(\"cursorActivity\", updateFatCursorMark)\n    }\n\n    // Deprecated, simply setting the keymap works again.\n    CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {\n      if (val && cm.getOption(\"keyMap\") != \"vim\")\n        cm.setOption(\"keyMap\", \"vim\");\n      else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption(\"keyMap\")))\n        cm.setOption(\"keyMap\", \"default\");\n    });\n\n    function cmKey(key, cm) {\n      if (!cm) { return undefined; }\n      if (this[key]) { return this[key]; }\n      var vimKey = cmKeyToVimKey(key);\n      if (!vimKey) {\n        return false;\n      }\n      var cmd = CodeMirror.Vim.findKey(cm, vimKey);\n      if (typeof cmd == 'function') {\n        CodeMirror.signal(cm, 'vim-keypress', vimKey);\n      }\n      return cmd;\n    }\n\n    var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'};\n    var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del',Insert:'Ins'};\n    function cmKeyToVimKey(key) {\n      if (key.charAt(0) == '\\'') {\n        // Keypress character binding of format \"'a'\"\n        return key.charAt(1);\n      }\n      var pieces = key.split(/-(?!$)/);\n      var lastPiece = pieces[pieces.length - 1];\n      if (pieces.length == 1 && pieces[0].length == 1) {\n        // No-modifier bindings use literal character bindings above. Skip.\n        return false;\n      } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {\n        // Ignore Shift+char bindings as they should be handled by literal character.\n        return false;\n      }\n      var hasCharacter = false;\n      for (var i = 0; i < pieces.length; i++) {\n        var piece = pieces[i];\n        if (piece in modifiers) { pieces[i] = modifiers[piece]; }\n        else { hasCharacter = true; }\n        if (piece in specialKeys) { pieces[i] = specialKeys[piece]; }\n      }\n      if (!hasCharacter) {\n        // Vim does not support modifier only keys.\n        return false;\n      }\n      // TODO: Current bindings expect the character to be lower case, but\n      // it looks like vim key notation uses upper case.\n      if (isUpperCase(lastPiece)) {\n        pieces[pieces.length - 1] = lastPiece.toLowerCase();\n      }\n      return '<' + pieces.join('-') + '>';\n    }\n\n    function getOnPasteFn(cm) {\n      var vim = cm.state.vim;\n      if (!vim.onPasteFn) {\n        vim.onPasteFn = function() {\n          if (!vim.insertMode) {\n            cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));\n            actions.enterInsertMode(cm, {}, vim);\n          }\n        };\n      }\n      return vim.onPasteFn;\n    }\n\n    var numberRegex = /[\\d]/;\n    var wordCharTest = [CodeMirror.isWordChar, function(ch) {\n      return ch && !CodeMirror.isWordChar(ch) && !/\\s/.test(ch);\n    }], bigWordCharTest = [function(ch) {\n      return /\\S/.test(ch);\n    }];\n    function makeKeyRange(start, size) {\n      var keys = [];\n      for (var i = start; i < start + size; i++) {\n        keys.push(String.fromCharCode(i));\n      }\n      return keys;\n    }\n    var upperCaseAlphabet = makeKeyRange(65, 26);\n    var lowerCaseAlphabet = makeKeyRange(97, 26);\n    var numbers = makeKeyRange(48, 10);\n    var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);\n    var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '\"', '.', ':', '/']);\n\n    function isLine(cm, line) {\n      return line >= cm.firstLine() && line <= cm.lastLine();\n    }\n    function isLowerCase(k) {\n      return (/^[a-z]$/).test(k);\n    }\n    function isMatchableSymbol(k) {\n      return '()[]{}'.indexOf(k) != -1;\n    }\n    function isNumber(k) {\n      return numberRegex.test(k);\n    }\n    function isUpperCase(k) {\n      return (/^[A-Z]$/).test(k);\n    }\n    function isWhiteSpaceString(k) {\n      return (/^\\s*$/).test(k);\n    }\n    function isEndOfSentenceSymbol(k) {\n      return '.?!'.indexOf(k) != -1;\n    }\n    function inArray(val, arr) {\n      for (var i = 0; i < arr.length; i++) {\n        if (arr[i] == val) {\n          return true;\n        }\n      }\n      return false;\n    }\n\n    var options = {};\n    function defineOption(name, defaultValue, type, aliases, callback) {\n      if (defaultValue === undefined && !callback) {\n        throw Error('defaultValue is required unless callback is provided');\n      }\n      if (!type) { type = 'string'; }\n      options[name] = {\n        type: type,\n        defaultValue: defaultValue,\n        callback: callback\n      };\n      if (aliases) {\n        for (var i = 0; i < aliases.length; i++) {\n          options[aliases[i]] = options[name];\n        }\n      }\n      if (defaultValue) {\n        setOption(name, defaultValue);\n      }\n    }\n\n    function setOption(name, value, cm, cfg) {\n      var option = options[name];\n      cfg = cfg || {};\n      var scope = cfg.scope;\n      if (!option) {\n        return new Error('Unknown option: ' + name);\n      }\n      if (option.type == 'boolean') {\n        if (value && value !== true) {\n          return new Error('Invalid argument: ' + name + '=' + value);\n        } else if (value !== false) {\n          // Boolean options are set to true if value is not defined.\n          value = true;\n        }\n      }\n      if (option.callback) {\n        if (scope !== 'local') {\n          option.callback(value, undefined);\n        }\n        if (scope !== 'global' && cm) {\n          option.callback(value, cm);\n        }\n      } else {\n        if (scope !== 'local') {\n          option.value = option.type == 'boolean' ? !!value : value;\n        }\n        if (scope !== 'global' && cm) {\n          cm.state.vim.options[name] = {value: value};\n        }\n      }\n    }\n\n    function getOption(name, cm, cfg) {\n      var option = options[name];\n      cfg = cfg || {};\n      var scope = cfg.scope;\n      if (!option) {\n        return new Error('Unknown option: ' + name);\n      }\n      if (option.callback) {\n        var local = cm && option.callback(undefined, cm);\n        if (scope !== 'global' && local !== undefined) {\n          return local;\n        }\n        if (scope !== 'local') {\n          return option.callback();\n        }\n        return;\n      } else {\n        var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);\n        return (local || (scope !== 'local') && option || {}).value;\n      }\n    }\n\n    defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {\n      // Option is local. Do nothing for global.\n      if (cm === undefined) {\n        return;\n      }\n      // The 'filetype' option proxies to the CodeMirror 'mode' option.\n      if (name === undefined) {\n        var mode = cm.getOption('mode');\n        return mode == 'null' ? '' : mode;\n      } else {\n        var mode = name == '' ? 'null' : name;\n        cm.setOption('mode', mode);\n      }\n    });\n\n    var createCircularJumpList = function() {\n      var size = 100;\n      var pointer = -1;\n      var head = 0;\n      var tail = 0;\n      var buffer = new Array(size);\n      function add(cm, oldCur, newCur) {\n        var current = pointer % size;\n        var curMark = buffer[current];\n        function useNextSlot(cursor) {\n          var next = ++pointer % size;\n          var trashMark = buffer[next];\n          if (trashMark) {\n            trashMark.clear();\n          }\n          buffer[next] = cm.setBookmark(cursor);\n        }\n        if (curMark) {\n          var markPos = curMark.find();\n          // avoid recording redundant cursor position\n          if (markPos && !cursorEqual(markPos, oldCur)) {\n            useNextSlot(oldCur);\n          }\n        } else {\n          useNextSlot(oldCur);\n        }\n        useNextSlot(newCur);\n        head = pointer;\n        tail = pointer - size + 1;\n        if (tail < 0) {\n          tail = 0;\n        }\n      }\n      function move(cm, offset) {\n        pointer += offset;\n        if (pointer > head) {\n          pointer = head;\n        } else if (pointer < tail) {\n          pointer = tail;\n        }\n        var mark = buffer[(size + pointer) % size];\n        // skip marks that are temporarily removed from text buffer\n        if (mark && !mark.find()) {\n          var inc = offset > 0 ? 1 : -1;\n          var newCur;\n          var oldCur = cm.getCursor();\n          do {\n            pointer += inc;\n            mark = buffer[(size + pointer) % size];\n            // skip marks that are the same as current position\n            if (mark &&\n                (newCur = mark.find()) &&\n                !cursorEqual(oldCur, newCur)) {\n              break;\n            }\n          } while (pointer < head && pointer > tail);\n        }\n        return mark;\n      }\n      return {\n        cachedCursor: undefined, //used for # and * jumps\n        add: add,\n        move: move\n      };\n    };\n\n    // Returns an object to track the changes associated insert mode.  It\n    // clones the object that is passed in, or creates an empty object one if\n    // none is provided.\n    var createInsertModeChanges = function(c) {\n      if (c) {\n        // Copy construction\n        return {\n          changes: c.changes,\n          expectCursorActivityForChange: c.expectCursorActivityForChange\n        };\n      }\n      return {\n        // Change list\n        changes: [],\n        // Set to true on change, false on cursorActivity.\n        expectCursorActivityForChange: false\n      };\n    };\n\n    function MacroModeState() {\n      this.latestRegister = undefined;\n      this.isPlaying = false;\n      this.isRecording = false;\n      this.replaySearchQueries = [];\n      this.onRecordingDone = undefined;\n      this.lastInsertModeChanges = createInsertModeChanges();\n    }\n    MacroModeState.prototype = {\n      exitMacroRecordMode: function() {\n        var macroModeState = vimGlobalState.macroModeState;\n        if (macroModeState.onRecordingDone) {\n          macroModeState.onRecordingDone(); // close dialog\n        }\n        macroModeState.onRecordingDone = undefined;\n        macroModeState.isRecording = false;\n      },\n      enterMacroRecordMode: function(cm, registerName) {\n        var register =\n            vimGlobalState.registerController.getRegister(registerName);\n        if (register) {\n          register.clear();\n          this.latestRegister = registerName;\n          if (cm.openDialog) {\n            this.onRecordingDone = cm.openDialog(\n                '(recording)['+registerName+']', null, {bottom:true});\n          }\n          this.isRecording = true;\n        }\n      }\n    };\n\n    function maybeInitVimState(cm) {\n      if (!cm.state.vim) {\n        // Store instance state in the CodeMirror object.\n        cm.state.vim = {\n          inputState: new InputState(),\n          // Vim's input state that triggered the last edit, used to repeat\n          // motions and operators with '.'.\n          lastEditInputState: undefined,\n          // Vim's action command before the last edit, used to repeat actions\n          // with '.' and insert mode repeat.\n          lastEditActionCommand: undefined,\n          // When using jk for navigation, if you move from a longer line to a\n          // shorter line, the cursor may clip to the end of the shorter line.\n          // If j is pressed again and cursor goes to the next line, the\n          // cursor should go back to its horizontal position on the longer\n          // line if it can. This is to keep track of the horizontal position.\n          lastHPos: -1,\n          // Doing the same with screen-position for gj/gk\n          lastHSPos: -1,\n          // The last motion command run. Cleared if a non-motion command gets\n          // executed in between.\n          lastMotion: null,\n          marks: {},\n          // Mark for rendering fake cursor for visual mode.\n          fakeCursor: null,\n          insertMode: false,\n          // Repeat count for changes made in insert mode, triggered by key\n          // sequences like 3,i. Only exists when insertMode is true.\n          insertModeRepeat: undefined,\n          visualMode: false,\n          // If we are in visual line mode. No effect if visualMode is false.\n          visualLine: false,\n          visualBlock: false,\n          lastSelection: null,\n          lastPastedText: null,\n          sel: {},\n          // Buffer-local/window-local values of vim options.\n          options: {}\n        };\n      }\n      return cm.state.vim;\n    }\n    var vimGlobalState;\n    function resetVimGlobalState() {\n      vimGlobalState = {\n        // The current search query.\n        searchQuery: null,\n        // Whether we are searching backwards.\n        searchIsReversed: false,\n        // Replace part of the last substituted pattern\n        lastSubstituteReplacePart: undefined,\n        jumpList: createCircularJumpList(),\n        macroModeState: new MacroModeState,\n        // Recording latest f, t, F or T motion command.\n        lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''},\n        registerController: new RegisterController({}),\n        // search history buffer\n        searchHistoryController: new HistoryController(),\n        // ex Command history buffer\n        exCommandHistoryController : new HistoryController()\n      };\n      for (var optionName in options) {\n        var option = options[optionName];\n        option.value = option.defaultValue;\n      }\n    }\n\n    var lastInsertModeKeyTimer;\n    var vimApi= {\n      buildKeyMap: function() {\n        // TODO: Convert keymap into dictionary format for fast lookup.\n      },\n      // Testing hook, though it might be useful to expose the register\n      // controller anyways.\n      getRegisterController: function() {\n        return vimGlobalState.registerController;\n      },\n      // Testing hook.\n      resetVimGlobalState_: resetVimGlobalState,\n\n      // Testing hook.\n      getVimGlobalState_: function() {\n        return vimGlobalState;\n      },\n\n      // Testing hook.\n      maybeInitVimState_: maybeInitVimState,\n\n      suppressErrorLogging: false,\n\n      InsertModeKey: InsertModeKey,\n      map: function(lhs, rhs, ctx) {\n        // Add user defined key bindings.\n        exCommandDispatcher.map(lhs, rhs, ctx);\n      },\n      unmap: function(lhs, ctx) {\n        exCommandDispatcher.unmap(lhs, ctx);\n      },\n      // Non-recursive map function.\n      // NOTE: This will not create mappings to key maps that aren't present\n      // in the default key map. See TODO at bottom of function.\n      noremap: function(lhs, rhs, ctx) {\n        function toCtxArray(ctx) {\n          return ctx ? [ctx] : ['normal', 'insert', 'visual'];\n        }\n        var ctxsToMap = toCtxArray(ctx);\n        // Look through all actual defaults to find a map candidate.\n        var actualLength = defaultKeymap.length, origLength = defaultKeymapLength;\n        for (var i = actualLength - origLength;\n             i < actualLength && ctxsToMap.length;\n             i++) {\n          var mapping = defaultKeymap[i];\n          // Omit mappings that operate in the wrong context(s) and those of invalid type.\n          if (mapping.keys == rhs &&\n              (!ctx || !mapping.context || mapping.context === ctx) &&\n              mapping.type.substr(0, 2) !== 'ex' &&\n              mapping.type.substr(0, 3) !== 'key') {\n            // Make a shallow copy of the original keymap entry.\n            var newMapping = {};\n            for (var key in mapping) {\n              newMapping[key] = mapping[key];\n            }\n            // Modify it point to the new mapping with the proper context.\n            newMapping.keys = lhs;\n            if (ctx && !newMapping.context) {\n              newMapping.context = ctx;\n            }\n            // Add it to the keymap with a higher priority than the original.\n            this._mapCommand(newMapping);\n            // Record the mapped contexts as complete.\n            var mappedCtxs = toCtxArray(mapping.context);\n            ctxsToMap = ctxsToMap.filter(function(el) { return mappedCtxs.indexOf(el) === -1; });\n          }\n        }\n        // TODO: Create non-recursive keyToKey mappings for the unmapped contexts once those exist.\n      },\n      // Remove all user-defined mappings for the provided context.\n      mapclear: function(ctx) {\n        // Partition the existing keymap into user-defined and true defaults.\n        var actualLength = defaultKeymap.length,\n            origLength = defaultKeymapLength;\n        var userKeymap = defaultKeymap.slice(0, actualLength - origLength);\n        defaultKeymap = defaultKeymap.slice(actualLength - origLength);\n        if (ctx) {\n          // If a specific context is being cleared, we need to keep mappings\n          // from all other contexts.\n          for (var i = userKeymap.length - 1; i >= 0; i--) {\n            var mapping = userKeymap[i];\n            if (ctx !== mapping.context) {\n              if (mapping.context) {\n                this._mapCommand(mapping);\n              } else {\n                // `mapping` applies to all contexts so create keymap copies\n                // for each context except the one being cleared.\n                var contexts = ['normal', 'insert', 'visual'];\n                for (var j in contexts) {\n                  if (contexts[j] !== ctx) {\n                    var newMapping = {};\n                    for (var key in mapping) {\n                      newMapping[key] = mapping[key];\n                    }\n                    newMapping.context = contexts[j];\n                    this._mapCommand(newMapping);\n                  }\n                }\n              }\n            }\n          }\n        }\n      },\n      // TODO: Expose setOption and getOption as instance methods. Need to decide how to namespace\n      // them, or somehow make them work with the existing CodeMirror setOption/getOption API.\n      setOption: setOption,\n      getOption: getOption,\n      defineOption: defineOption,\n      defineEx: function(name, prefix, func){\n        if (!prefix) {\n          prefix = name;\n        } else if (name.indexOf(prefix) !== 0) {\n          throw new Error('(Vim.defineEx) \"'+prefix+'\" is not a prefix of \"'+name+'\", command not registered');\n        }\n        exCommands[name]=func;\n        exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};\n      },\n      handleKey: function (cm, key, origin) {\n        var command = this.findKey(cm, key, origin);\n        if (typeof command === 'function') {\n          return command();\n        }\n      },\n      /**\n       * This is the outermost function called by CodeMirror, after keys have\n       * been mapped to their Vim equivalents.\n       *\n       * Finds a command based on the key (and cached keys if there is a\n       * multi-key sequence). Returns `undefined` if no key is matched, a noop\n       * function if a partial match is found (multi-key), and a function to\n       * execute the bound command if a a key is matched. The function always\n       * returns true.\n       */\n      findKey: function(cm, key, origin) {\n        var vim = maybeInitVimState(cm);\n        function handleMacroRecording() {\n          var macroModeState = vimGlobalState.macroModeState;\n          if (macroModeState.isRecording) {\n            if (key == 'q') {\n              macroModeState.exitMacroRecordMode();\n              clearInputState(cm);\n              return true;\n            }\n            if (origin != 'mapping') {\n              logKey(macroModeState, key);\n            }\n          }\n        }\n        function handleEsc() {\n          if (key == '<Esc>') {\n            // Clear input state and get back to normal mode.\n            clearInputState(cm);\n            if (vim.visualMode) {\n              exitVisualMode(cm);\n            } else if (vim.insertMode) {\n              exitInsertMode(cm);\n            }\n            return true;\n          }\n        }\n        function doKeyToKey(keys) {\n          // TODO: prevent infinite recursion.\n          var match;\n          while (keys) {\n            // Pull off one command key, which is either a single character\n            // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.\n            match = (/<\\w+-.+?>|<\\w+>|./).exec(keys);\n            key = match[0];\n            keys = keys.substring(match.index + key.length);\n            CodeMirror.Vim.handleKey(cm, key, 'mapping');\n          }\n        }\n\n        function handleKeyInsertMode() {\n          if (handleEsc()) { return true; }\n          var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;\n          var keysAreChars = key.length == 1;\n          var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');\n          // Need to check all key substrings in insert mode.\n          while (keys.length > 1 && match.type != 'full') {\n            var keys = vim.inputState.keyBuffer = keys.slice(1);\n            var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');\n            if (thisMatch.type != 'none') { match = thisMatch; }\n          }\n          if (match.type == 'none') { clearInputState(cm); return false; }\n          else if (match.type == 'partial') {\n            if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }\n            lastInsertModeKeyTimer = window.setTimeout(\n              function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },\n              getOption('insertModeEscKeysTimeout'));\n            return !keysAreChars;\n          }\n\n          if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }\n          if (keysAreChars) {\n            var selections = cm.listSelections();\n            for (var i = 0; i < selections.length; i++) {\n              var here = selections[i].head;\n              cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');\n            }\n            vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();\n          }\n          clearInputState(cm);\n          return match.command;\n        }\n\n        function handleKeyNonInsertMode() {\n          if (handleMacroRecording() || handleEsc()) { return true; }\n\n          var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;\n          if (/^[1-9]\\d*$/.test(keys)) { return true; }\n\n          var keysMatcher = /^(\\d*)(.*)$/.exec(keys);\n          if (!keysMatcher) { clearInputState(cm); return false; }\n          var context = vim.visualMode ? 'visual' :\n                                         'normal';\n          var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);\n          if (match.type == 'none') { clearInputState(cm); return false; }\n          else if (match.type == 'partial') { return true; }\n\n          vim.inputState.keyBuffer = '';\n          var keysMatcher = /^(\\d*)(.*)$/.exec(keys);\n          if (keysMatcher[1] && keysMatcher[1] != '0') {\n            vim.inputState.pushRepeatDigit(keysMatcher[1]);\n          }\n          return match.command;\n        }\n\n        var command;\n        if (vim.insertMode) { command = handleKeyInsertMode(); }\n        else { command = handleKeyNonInsertMode(); }\n        if (command === false) {\n          return !vim.insertMode && key.length === 1 ? function() { return true; } : undefined;\n        } else if (command === true) {\n          // TODO: Look into using CodeMirror's multi-key handling.\n          // Return no-op since we are caching the key. Counts as handled, but\n          // don't want act on it just yet.\n          return function() { return true; };\n        } else {\n          return function() {\n            return cm.operation(function() {\n              cm.curOp.isVimOp = true;\n              try {\n                if (command.type == 'keyToKey') {\n                  doKeyToKey(command.toKeys);\n                } else {\n                  commandDispatcher.processCommand(cm, vim, command);\n                }\n              } catch (e) {\n                // clear VIM state in case it's in a bad state.\n                cm.state.vim = undefined;\n                maybeInitVimState(cm);\n                if (!CodeMirror.Vim.suppressErrorLogging) {\n                  console['log'](e);\n                }\n                throw e;\n              }\n              return true;\n            });\n          };\n        }\n      },\n      handleEx: function(cm, input) {\n        exCommandDispatcher.processCommand(cm, input);\n      },\n\n      defineMotion: defineMotion,\n      defineAction: defineAction,\n      defineOperator: defineOperator,\n      mapCommand: mapCommand,\n      _mapCommand: _mapCommand,\n\n      defineRegister: defineRegister,\n\n      exitVisualMode: exitVisualMode,\n      exitInsertMode: exitInsertMode\n    };\n\n    // Represents the current input state.\n    function InputState() {\n      this.prefixRepeat = [];\n      this.motionRepeat = [];\n\n      this.operator = null;\n      this.operatorArgs = null;\n      this.motion = null;\n      this.motionArgs = null;\n      this.keyBuffer = []; // For matching multi-key commands.\n      this.registerName = null; // Defaults to the unnamed register.\n    }\n    InputState.prototype.pushRepeatDigit = function(n) {\n      if (!this.operator) {\n        this.prefixRepeat = this.prefixRepeat.concat(n);\n      } else {\n        this.motionRepeat = this.motionRepeat.concat(n);\n      }\n    };\n    InputState.prototype.getRepeat = function() {\n      var repeat = 0;\n      if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {\n        repeat = 1;\n        if (this.prefixRepeat.length > 0) {\n          repeat *= parseInt(this.prefixRepeat.join(''), 10);\n        }\n        if (this.motionRepeat.length > 0) {\n          repeat *= parseInt(this.motionRepeat.join(''), 10);\n        }\n      }\n      return repeat;\n    };\n\n    function clearInputState(cm, reason) {\n      cm.state.vim.inputState = new InputState();\n      CodeMirror.signal(cm, 'vim-command-done', reason);\n    }\n\n    /*\n     * Register stores information about copy and paste registers.  Besides\n     * text, a register must store whether it is linewise (i.e., when it is\n     * pasted, should it insert itself into a new line, or should the text be\n     * inserted at the cursor position.)\n     */\n    function Register(text, linewise, blockwise) {\n      this.clear();\n      this.keyBuffer = [text || ''];\n      this.insertModeChanges = [];\n      this.searchQueries = [];\n      this.linewise = !!linewise;\n      this.blockwise = !!blockwise;\n    }\n    Register.prototype = {\n      setText: function(text, linewise, blockwise) {\n        this.keyBuffer = [text || ''];\n        this.linewise = !!linewise;\n        this.blockwise = !!blockwise;\n      },\n      pushText: function(text, linewise) {\n        // if this register has ever been set to linewise, use linewise.\n        if (linewise) {\n          if (!this.linewise) {\n            this.keyBuffer.push('\\n');\n          }\n          this.linewise = true;\n        }\n        this.keyBuffer.push(text);\n      },\n      pushInsertModeChanges: function(changes) {\n        this.insertModeChanges.push(createInsertModeChanges(changes));\n      },\n      pushSearchQuery: function(query) {\n        this.searchQueries.push(query);\n      },\n      clear: function() {\n        this.keyBuffer = [];\n        this.insertModeChanges = [];\n        this.searchQueries = [];\n        this.linewise = false;\n      },\n      toString: function() {\n        return this.keyBuffer.join('');\n      }\n    };\n\n    /**\n     * Defines an external register.\n     *\n     * The name should be a single character that will be used to reference the register.\n     * The register should support setText, pushText, clear, and toString(). See Register\n     * for a reference implementation.\n     */\n    function defineRegister(name, register) {\n      var registers = vimGlobalState.registerController.registers;\n      if (!name || name.length != 1) {\n        throw Error('Register name must be 1 character');\n      }\n      if (registers[name]) {\n        throw Error('Register already defined ' + name);\n      }\n      registers[name] = register;\n      validRegisters.push(name);\n    }\n\n    /*\n     * vim registers allow you to keep many independent copy and paste buffers.\n     * See http://usevim.com/2012/04/13/registers/ for an introduction.\n     *\n     * RegisterController keeps the state of all the registers.  An initial\n     * state may be passed in.  The unnamed register '\"' will always be\n     * overridden.\n     */\n    function RegisterController(registers) {\n      this.registers = registers;\n      this.unnamedRegister = registers['\"'] = new Register();\n      registers['.'] = new Register();\n      registers[':'] = new Register();\n      registers['/'] = new Register();\n    }\n    RegisterController.prototype = {\n      pushText: function(registerName, operator, text, linewise, blockwise) {\n        if (linewise && text.charAt(text.length - 1) !== '\\n'){\n          text += '\\n';\n        }\n        // Lowercase and uppercase registers refer to the same register.\n        // Uppercase just means append.\n        var register = this.isValidRegister(registerName) ?\n            this.getRegister(registerName) : null;\n        // if no register/an invalid register was specified, things go to the\n        // default registers\n        if (!register) {\n          switch (operator) {\n            case 'yank':\n              // The 0 register contains the text from the most recent yank.\n              this.registers['0'] = new Register(text, linewise, blockwise);\n              break;\n            case 'delete':\n            case 'change':\n              if (text.indexOf('\\n') == -1) {\n                // Delete less than 1 line. Update the small delete register.\n                this.registers['-'] = new Register(text, linewise);\n              } else {\n                // Shift down the contents of the numbered registers and put the\n                // deleted text into register 1.\n                this.shiftNumericRegisters_();\n                this.registers['1'] = new Register(text, linewise);\n              }\n              break;\n          }\n          // Make sure the unnamed register is set to what just happened\n          this.unnamedRegister.setText(text, linewise, blockwise);\n          return;\n        }\n\n        // If we've gotten to this point, we've actually specified a register\n        var append = isUpperCase(registerName);\n        if (append) {\n          register.pushText(text, linewise);\n        } else {\n          register.setText(text, linewise, blockwise);\n        }\n        // The unnamed register always has the same value as the last used\n        // register.\n        this.unnamedRegister.setText(register.toString(), linewise);\n      },\n      // Gets the register named @name.  If one of @name doesn't already exist,\n      // create it.  If @name is invalid, return the unnamedRegister.\n      getRegister: function(name) {\n        if (!this.isValidRegister(name)) {\n          return this.unnamedRegister;\n        }\n        name = name.toLowerCase();\n        if (!this.registers[name]) {\n          this.registers[name] = new Register();\n        }\n        return this.registers[name];\n      },\n      isValidRegister: function(name) {\n        return name && inArray(name, validRegisters);\n      },\n      shiftNumericRegisters_: function() {\n        for (var i = 9; i >= 2; i--) {\n          this.registers[i] = this.getRegister('' + (i - 1));\n        }\n      }\n    };\n    function HistoryController() {\n        this.historyBuffer = [];\n        this.iterator = 0;\n        this.initialPrefix = null;\n    }\n    HistoryController.prototype = {\n      // the input argument here acts a user entered prefix for a small time\n      // until we start autocompletion in which case it is the autocompleted.\n      nextMatch: function (input, up) {\n        var historyBuffer = this.historyBuffer;\n        var dir = up ? -1 : 1;\n        if (this.initialPrefix === null) this.initialPrefix = input;\n        for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {\n          var element = historyBuffer[i];\n          for (var j = 0; j <= element.length; j++) {\n            if (this.initialPrefix == element.substring(0, j)) {\n              this.iterator = i;\n              return element;\n            }\n          }\n        }\n        // should return the user input in case we reach the end of buffer.\n        if (i >= historyBuffer.length) {\n          this.iterator = historyBuffer.length;\n          return this.initialPrefix;\n        }\n        // return the last autocompleted query or exCommand as it is.\n        if (i < 0 ) return input;\n      },\n      pushInput: function(input) {\n        var index = this.historyBuffer.indexOf(input);\n        if (index > -1) this.historyBuffer.splice(index, 1);\n        if (input.length) this.historyBuffer.push(input);\n      },\n      reset: function() {\n        this.initialPrefix = null;\n        this.iterator = this.historyBuffer.length;\n      }\n    };\n    var commandDispatcher = {\n      matchCommand: function(keys, keyMap, inputState, context) {\n        var matches = commandMatches(keys, keyMap, context, inputState);\n        if (!matches.full && !matches.partial) {\n          return {type: 'none'};\n        } else if (!matches.full && matches.partial) {\n          return {type: 'partial'};\n        }\n\n        var bestMatch;\n        for (var i = 0; i < matches.full.length; i++) {\n          var match = matches.full[i];\n          if (!bestMatch) {\n            bestMatch = match;\n          }\n        }\n        if (bestMatch.keys.slice(-11) == '<character>') {\n          var character = lastChar(keys);\n          if (!character) return {type: 'none'};\n          inputState.selectedCharacter = character;\n        }\n        return {type: 'full', command: bestMatch};\n      },\n      processCommand: function(cm, vim, command) {\n        vim.inputState.repeatOverride = command.repeatOverride;\n        switch (command.type) {\n          case 'motion':\n            this.processMotion(cm, vim, command);\n            break;\n          case 'operator':\n            this.processOperator(cm, vim, command);\n            break;\n          case 'operatorMotion':\n            this.processOperatorMotion(cm, vim, command);\n            break;\n          case 'action':\n            this.processAction(cm, vim, command);\n            break;\n          case 'search':\n            this.processSearch(cm, vim, command);\n            break;\n          case 'ex':\n          case 'keyToEx':\n            this.processEx(cm, vim, command);\n            break;\n          default:\n            break;\n        }\n      },\n      processMotion: function(cm, vim, command) {\n        vim.inputState.motion = command.motion;\n        vim.inputState.motionArgs = copyArgs(command.motionArgs);\n        this.evalInput(cm, vim);\n      },\n      processOperator: function(cm, vim, command) {\n        var inputState = vim.inputState;\n        if (inputState.operator) {\n          if (inputState.operator == command.operator) {\n            // Typing an operator twice like 'dd' makes the operator operate\n            // linewise\n            inputState.motion = 'expandToLine';\n            inputState.motionArgs = { linewise: true };\n            this.evalInput(cm, vim);\n            return;\n          } else {\n            // 2 different operators in a row doesn't make sense.\n            clearInputState(cm);\n          }\n        }\n        inputState.operator = command.operator;\n        inputState.operatorArgs = copyArgs(command.operatorArgs);\n        if (vim.visualMode) {\n          // Operating on a selection in visual mode. We don't need a motion.\n          this.evalInput(cm, vim);\n        }\n      },\n      processOperatorMotion: function(cm, vim, command) {\n        var visualMode = vim.visualMode;\n        var operatorMotionArgs = copyArgs(command.operatorMotionArgs);\n        if (operatorMotionArgs) {\n          // Operator motions may have special behavior in visual mode.\n          if (visualMode && operatorMotionArgs.visualLine) {\n            vim.visualLine = true;\n          }\n        }\n        this.processOperator(cm, vim, command);\n        if (!visualMode) {\n          this.processMotion(cm, vim, command);\n        }\n      },\n      processAction: function(cm, vim, command) {\n        var inputState = vim.inputState;\n        var repeat = inputState.getRepeat();\n        var repeatIsExplicit = !!repeat;\n        var actionArgs = copyArgs(command.actionArgs) || {};\n        if (inputState.selectedCharacter) {\n          actionArgs.selectedCharacter = inputState.selectedCharacter;\n        }\n        // Actions may or may not have motions and operators. Do these first.\n        if (command.operator) {\n          this.processOperator(cm, vim, command);\n        }\n        if (command.motion) {\n          this.processMotion(cm, vim, command);\n        }\n        if (command.motion || command.operator) {\n          this.evalInput(cm, vim);\n        }\n        actionArgs.repeat = repeat || 1;\n        actionArgs.repeatIsExplicit = repeatIsExplicit;\n        actionArgs.registerName = inputState.registerName;\n        clearInputState(cm);\n        vim.lastMotion = null;\n        if (command.isEdit) {\n          this.recordLastEdit(vim, inputState, command);\n        }\n        actions[command.action](cm, actionArgs, vim);\n      },\n      processSearch: function(cm, vim, command) {\n        if (!cm.getSearchCursor) {\n          // Search depends on SearchCursor.\n          return;\n        }\n        var forward = command.searchArgs.forward;\n        var wholeWordOnly = command.searchArgs.wholeWordOnly;\n        getSearchState(cm).setReversed(!forward);\n        var promptPrefix = (forward) ? '/' : '?';\n        var originalQuery = getSearchState(cm).getQuery();\n        var originalScrollPos = cm.getScrollInfo();\n        function handleQuery(query, ignoreCase, smartCase) {\n          vimGlobalState.searchHistoryController.pushInput(query);\n          vimGlobalState.searchHistoryController.reset();\n          try {\n            updateSearchQuery(cm, query, ignoreCase, smartCase);\n          } catch (e) {\n            showConfirm(cm, 'Invalid regex: ' + query);\n            clearInputState(cm);\n            return;\n          }\n          commandDispatcher.processMotion(cm, vim, {\n            type: 'motion',\n            motion: 'findNext',\n            motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }\n          });\n        }\n        function onPromptClose(query) {\n          cm.scrollTo(originalScrollPos.left, originalScrollPos.top);\n          handleQuery(query, true /** ignoreCase */, true /** smartCase */);\n          var macroModeState = vimGlobalState.macroModeState;\n          if (macroModeState.isRecording) {\n            logSearchQuery(macroModeState, query);\n          }\n        }\n        function onPromptKeyUp(e, query, close) {\n          var keyName = CodeMirror.keyName(e), up, offset;\n          if (keyName == 'Up' || keyName == 'Down') {\n            up = keyName == 'Up' ? true : false;\n            offset = e.target ? e.target.selectionEnd : 0;\n            query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';\n            close(query);\n            if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);\n          } else {\n            if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')\n              vimGlobalState.searchHistoryController.reset();\n          }\n          var parsedQuery;\n          try {\n            parsedQuery = updateSearchQuery(cm, query,\n                true /** ignoreCase */, true /** smartCase */);\n          } catch (e) {\n            // Swallow bad regexes for incremental search.\n          }\n          if (parsedQuery) {\n            cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);\n          } else {\n            clearSearchHighlight(cm);\n            cm.scrollTo(originalScrollPos.left, originalScrollPos.top);\n          }\n        }\n        function onPromptKeyDown(e, query, close) {\n          var keyName = CodeMirror.keyName(e);\n          if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||\n              (keyName == 'Backspace' && query == '')) {\n            vimGlobalState.searchHistoryController.pushInput(query);\n            vimGlobalState.searchHistoryController.reset();\n            updateSearchQuery(cm, originalQuery);\n            clearSearchHighlight(cm);\n            cm.scrollTo(originalScrollPos.left, originalScrollPos.top);\n            CodeMirror.e_stop(e);\n            clearInputState(cm);\n            close();\n            cm.focus();\n          } else if (keyName == 'Up' || keyName == 'Down') {\n            CodeMirror.e_stop(e);\n          } else if (keyName == 'Ctrl-U') {\n            // Ctrl-U clears input.\n            CodeMirror.e_stop(e);\n            close('');\n          }\n        }\n        switch (command.searchArgs.querySrc) {\n          case 'prompt':\n            var macroModeState = vimGlobalState.macroModeState;\n            if (macroModeState.isPlaying) {\n              var query = macroModeState.replaySearchQueries.shift();\n              handleQuery(query, true /** ignoreCase */, false /** smartCase */);\n            } else {\n              showPrompt(cm, {\n                  onClose: onPromptClose,\n                  prefix: promptPrefix,\n                  desc: searchPromptDesc,\n                  onKeyUp: onPromptKeyUp,\n                  onKeyDown: onPromptKeyDown\n              });\n            }\n            break;\n          case 'wordUnderCursor':\n            var word = expandWordUnderCursor(cm, false /** inclusive */,\n                true /** forward */, false /** bigWord */,\n                true /** noSymbol */);\n            var isKeyword = true;\n            if (!word) {\n              word = expandWordUnderCursor(cm, false /** inclusive */,\n                  true /** forward */, false /** bigWord */,\n                  false /** noSymbol */);\n              isKeyword = false;\n            }\n            if (!word) {\n              return;\n            }\n            var query = cm.getLine(word.start.line).substring(word.start.ch,\n                word.end.ch);\n            if (isKeyword && wholeWordOnly) {\n                query = '\\\\b' + query + '\\\\b';\n            } else {\n              query = escapeRegex(query);\n            }\n\n            // cachedCursor is used to save the old position of the cursor\n            // when * or # causes vim to seek for the nearest word and shift\n            // the cursor before entering the motion.\n            vimGlobalState.jumpList.cachedCursor = cm.getCursor();\n            cm.setCursor(word.start);\n\n            handleQuery(query, true /** ignoreCase */, false /** smartCase */);\n            break;\n        }\n      },\n      processEx: function(cm, vim, command) {\n        function onPromptClose(input) {\n          // Give the prompt some time to close so that if processCommand shows\n          // an error, the elements don't overlap.\n          vimGlobalState.exCommandHistoryController.pushInput(input);\n          vimGlobalState.exCommandHistoryController.reset();\n          exCommandDispatcher.processCommand(cm, input);\n        }\n        function onPromptKeyDown(e, input, close) {\n          var keyName = CodeMirror.keyName(e), up, offset;\n          if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||\n              (keyName == 'Backspace' && input == '')) {\n            vimGlobalState.exCommandHistoryController.pushInput(input);\n            vimGlobalState.exCommandHistoryController.reset();\n            CodeMirror.e_stop(e);\n            clearInputState(cm);\n            close();\n            cm.focus();\n          }\n          if (keyName == 'Up' || keyName == 'Down') {\n            CodeMirror.e_stop(e);\n            up = keyName == 'Up' ? true : false;\n            offset = e.target ? e.target.selectionEnd : 0;\n            input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';\n            close(input);\n            if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);\n          } else if (keyName == 'Ctrl-U') {\n            // Ctrl-U clears input.\n            CodeMirror.e_stop(e);\n            close('');\n          } else {\n            if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')\n              vimGlobalState.exCommandHistoryController.reset();\n          }\n        }\n        if (command.type == 'keyToEx') {\n          // Handle user defined Ex to Ex mappings\n          exCommandDispatcher.processCommand(cm, command.exArgs.input);\n        } else {\n          if (vim.visualMode) {\n            showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\\'<,\\'>',\n                onKeyDown: onPromptKeyDown, selectValueOnOpen: false});\n          } else {\n            showPrompt(cm, { onClose: onPromptClose, prefix: ':',\n                onKeyDown: onPromptKeyDown});\n          }\n        }\n      },\n      evalInput: function(cm, vim) {\n        // If the motion command is set, execute both the operator and motion.\n        // Otherwise return.\n        var inputState = vim.inputState;\n        var motion = inputState.motion;\n        var motionArgs = inputState.motionArgs || {};\n        var operator = inputState.operator;\n        var operatorArgs = inputState.operatorArgs || {};\n        var registerName = inputState.registerName;\n        var sel = vim.sel;\n        // TODO: Make sure cm and vim selections are identical outside visual mode.\n        var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));\n        var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));\n        var oldHead = copyCursor(origHead);\n        var oldAnchor = copyCursor(origAnchor);\n        var newHead, newAnchor;\n        var repeat;\n        if (operator) {\n          this.recordLastEdit(vim, inputState);\n        }\n        if (inputState.repeatOverride !== undefined) {\n          // If repeatOverride is specified, that takes precedence over the\n          // input state's repeat. Used by Ex mode and can be user defined.\n          repeat = inputState.repeatOverride;\n        } else {\n          repeat = inputState.getRepeat();\n        }\n        if (repeat > 0 && motionArgs.explicitRepeat) {\n          motionArgs.repeatIsExplicit = true;\n        } else if (motionArgs.noRepeat ||\n            (!motionArgs.explicitRepeat && repeat === 0)) {\n          repeat = 1;\n          motionArgs.repeatIsExplicit = false;\n        }\n        if (inputState.selectedCharacter) {\n          // If there is a character input, stick it in all of the arg arrays.\n          motionArgs.selectedCharacter = operatorArgs.selectedCharacter =\n              inputState.selectedCharacter;\n        }\n        motionArgs.repeat = repeat;\n        clearInputState(cm);\n        if (motion) {\n          var motionResult = motions[motion](cm, origHead, motionArgs, vim);\n          vim.lastMotion = motions[motion];\n          if (!motionResult) {\n            return;\n          }\n          if (motionArgs.toJumplist) {\n            var jumpList = vimGlobalState.jumpList;\n            // if the current motion is # or *, use cachedCursor\n            var cachedCursor = jumpList.cachedCursor;\n            if (cachedCursor) {\n              recordJumpPosition(cm, cachedCursor, motionResult);\n              delete jumpList.cachedCursor;\n            } else {\n              recordJumpPosition(cm, origHead, motionResult);\n            }\n          }\n          if (motionResult instanceof Array) {\n            newAnchor = motionResult[0];\n            newHead = motionResult[1];\n          } else {\n            newHead = motionResult;\n          }\n          // TODO: Handle null returns from motion commands better.\n          if (!newHead) {\n            newHead = copyCursor(origHead);\n          }\n          if (vim.visualMode) {\n            if (!(vim.visualBlock && newHead.ch === Infinity)) {\n              newHead = clipCursorToContent(cm, newHead, vim.visualBlock);\n            }\n            if (newAnchor) {\n              newAnchor = clipCursorToContent(cm, newAnchor, true);\n            }\n            newAnchor = newAnchor || oldAnchor;\n            sel.anchor = newAnchor;\n            sel.head = newHead;\n            updateCmSelection(cm);\n            updateMark(cm, vim, '<',\n                cursorIsBefore(newAnchor, newHead) ? newAnchor\n                    : newHead);\n            updateMark(cm, vim, '>',\n                cursorIsBefore(newAnchor, newHead) ? newHead\n                    : newAnchor);\n          } else if (!operator) {\n            newHead = clipCursorToContent(cm, newHead);\n            cm.setCursor(newHead.line, newHead.ch);\n          }\n        }\n        if (operator) {\n          if (operatorArgs.lastSel) {\n            // Replaying a visual mode operation\n            newAnchor = oldAnchor;\n            var lastSel = operatorArgs.lastSel;\n            var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);\n            var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);\n            if (lastSel.visualLine) {\n              // Linewise Visual mode: The same number of lines.\n              newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);\n            } else if (lastSel.visualBlock) {\n              // Blockwise Visual mode: The same number of lines and columns.\n              newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);\n            } else if (lastSel.head.line == lastSel.anchor.line) {\n              // Normal Visual mode within one line: The same number of characters.\n              newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);\n            } else {\n              // Normal Visual mode with several lines: The same number of lines, in the\n              // last line the same number of characters as in the last line the last time.\n              newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);\n            }\n            vim.visualMode = true;\n            vim.visualLine = lastSel.visualLine;\n            vim.visualBlock = lastSel.visualBlock;\n            sel = vim.sel = {\n              anchor: newAnchor,\n              head: newHead\n            };\n            updateCmSelection(cm);\n          } else if (vim.visualMode) {\n            operatorArgs.lastSel = {\n              anchor: copyCursor(sel.anchor),\n              head: copyCursor(sel.head),\n              visualBlock: vim.visualBlock,\n              visualLine: vim.visualLine\n            };\n          }\n          var curStart, curEnd, linewise, mode;\n          var cmSel;\n          if (vim.visualMode) {\n            // Init visual op\n            curStart = cursorMin(sel.head, sel.anchor);\n            curEnd = cursorMax(sel.head, sel.anchor);\n            linewise = vim.visualLine || operatorArgs.linewise;\n            mode = vim.visualBlock ? 'block' :\n                   linewise ? 'line' :\n                   'char';\n            cmSel = makeCmSelection(cm, {\n              anchor: curStart,\n              head: curEnd\n            }, mode);\n            if (linewise) {\n              var ranges = cmSel.ranges;\n              if (mode == 'block') {\n                // Linewise operators in visual block mode extend to end of line\n                for (var i = 0; i < ranges.length; i++) {\n                  ranges[i].head.ch = lineLength(cm, ranges[i].head.line);\n                }\n              } else if (mode == 'line') {\n                ranges[0].head = Pos(ranges[0].head.line + 1, 0);\n              }\n            }\n          } else {\n            // Init motion op\n            curStart = copyCursor(newAnchor || oldAnchor);\n            curEnd = copyCursor(newHead || oldHead);\n            if (cursorIsBefore(curEnd, curStart)) {\n              var tmp = curStart;\n              curStart = curEnd;\n              curEnd = tmp;\n            }\n            linewise = motionArgs.linewise || operatorArgs.linewise;\n            if (linewise) {\n              // Expand selection to entire line.\n              expandSelectionToLine(cm, curStart, curEnd);\n            } else if (motionArgs.forward) {\n              // Clip to trailing newlines only if the motion goes forward.\n              clipToLine(cm, curStart, curEnd);\n            }\n            mode = 'char';\n            var exclusive = !motionArgs.inclusive || linewise;\n            cmSel = makeCmSelection(cm, {\n              anchor: curStart,\n              head: curEnd\n            }, mode, exclusive);\n          }\n          cm.setSelections(cmSel.ranges, cmSel.primary);\n          vim.lastMotion = null;\n          operatorArgs.repeat = repeat; // For indent in visual mode.\n          operatorArgs.registerName = registerName;\n          // Keep track of linewise as it affects how paste and change behave.\n          operatorArgs.linewise = linewise;\n          var operatorMoveTo = operators[operator](\n            cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);\n          if (vim.visualMode) {\n            exitVisualMode(cm, operatorMoveTo != null);\n          }\n          if (operatorMoveTo) {\n            cm.setCursor(operatorMoveTo);\n          }\n        }\n      },\n      recordLastEdit: function(vim, inputState, actionCommand) {\n        var macroModeState = vimGlobalState.macroModeState;\n        if (macroModeState.isPlaying) { return; }\n        vim.lastEditInputState = inputState;\n        vim.lastEditActionCommand = actionCommand;\n        macroModeState.lastInsertModeChanges.changes = [];\n        macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;\n      }\n    };\n\n    /**\n     * typedef {Object{line:number,ch:number}} Cursor An object containing the\n     *     position of the cursor.\n     */\n    // All of the functions below return Cursor objects.\n    var motions = {\n      moveToTopLine: function(cm, _head, motionArgs) {\n        var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;\n        return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));\n      },\n      moveToMiddleLine: function(cm) {\n        var range = getUserVisibleLines(cm);\n        var line = Math.floor((range.top + range.bottom) * 0.5);\n        return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));\n      },\n      moveToBottomLine: function(cm, _head, motionArgs) {\n        var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;\n        return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));\n      },\n      expandToLine: function(_cm, head, motionArgs) {\n        // Expands forward to end of line, and then to next line if repeat is\n        // >1. Does not handle backward motion!\n        var cur = head;\n        return Pos(cur.line + motionArgs.repeat - 1, Infinity);\n      },\n      findNext: function(cm, _head, motionArgs) {\n        var state = getSearchState(cm);\n        var query = state.getQuery();\n        if (!query) {\n          return;\n        }\n        var prev = !motionArgs.forward;\n        // If search is initiated with ? instead of /, negate direction.\n        prev = (state.isReversed()) ? !prev : prev;\n        highlightSearchMatches(cm, query);\n        return findNext(cm, prev/** prev */, query, motionArgs.repeat);\n      },\n      goToMark: function(cm, _head, motionArgs, vim) {\n        var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter);\n        if (pos) {\n          return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;\n        }\n        return null;\n      },\n      moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {\n        if (vim.visualBlock && motionArgs.sameLine) {\n          var sel = vim.sel;\n          return [\n            clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),\n            clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))\n          ];\n        } else {\n          return ([vim.sel.head, vim.sel.anchor]);\n        }\n      },\n      jumpToMark: function(cm, head, motionArgs, vim) {\n        var best = head;\n        for (var i = 0; i < motionArgs.repeat; i++) {\n          var cursor = best;\n          for (var key in vim.marks) {\n            if (!isLowerCase(key)) {\n              continue;\n            }\n            var mark = vim.marks[key].find();\n            var isWrongDirection = (motionArgs.forward) ?\n              cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);\n\n            if (isWrongDirection) {\n              continue;\n            }\n            if (motionArgs.linewise && (mark.line == cursor.line)) {\n              continue;\n            }\n\n            var equal = cursorEqual(cursor, best);\n            var between = (motionArgs.forward) ?\n              cursorIsBetween(cursor, mark, best) :\n              cursorIsBetween(best, mark, cursor);\n\n            if (equal || between) {\n              best = mark;\n            }\n          }\n        }\n\n        if (motionArgs.linewise) {\n          // Vim places the cursor on the first non-whitespace character of\n          // the line if there is one, else it places the cursor at the end\n          // of the line, regardless of whether a mark was found.\n          best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));\n        }\n        return best;\n      },\n      moveByCharacters: function(_cm, head, motionArgs) {\n        var cur = head;\n        var repeat = motionArgs.repeat;\n        var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;\n        return Pos(cur.line, ch);\n      },\n      moveByLines: function(cm, head, motionArgs, vim) {\n        var cur = head;\n        var endCh = cur.ch;\n        // Depending what our last motion was, we may want to do different\n        // things. If our last motion was moving vertically, we want to\n        // preserve the HPos from our last horizontal move.  If our last motion\n        // was going to the end of a line, moving vertically we should go to\n        // the end of the line, etc.\n        switch (vim.lastMotion) {\n          case this.moveByLines:\n          case this.moveByDisplayLines:\n          case this.moveByScroll:\n          case this.moveToColumn:\n          case this.moveToEol:\n            endCh = vim.lastHPos;\n            break;\n          default:\n            vim.lastHPos = endCh;\n        }\n        var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);\n        var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;\n        var first = cm.firstLine();\n        var last = cm.lastLine();\n        // Vim go to line begin or line end when cursor at first/last line and\n        // move to previous/next line is triggered.\n        if (line < first && cur.line == first){\n          return this.moveToStartOfLine(cm, head, motionArgs, vim);\n        }else if (line > last && cur.line == last){\n            return this.moveToEol(cm, head, motionArgs, vim);\n        }\n        if (motionArgs.toFirstChar){\n          endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));\n          vim.lastHPos = endCh;\n        }\n        vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;\n        return Pos(line, endCh);\n      },\n      moveByDisplayLines: function(cm, head, motionArgs, vim) {\n        var cur = head;\n        switch (vim.lastMotion) {\n          case this.moveByDisplayLines:\n          case this.moveByScroll:\n          case this.moveByLines:\n          case this.moveToColumn:\n          case this.moveToEol:\n            break;\n          default:\n            vim.lastHSPos = cm.charCoords(cur,'div').left;\n        }\n        var repeat = motionArgs.repeat;\n        var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);\n        if (res.hitSide) {\n          if (motionArgs.forward) {\n            var lastCharCoords = cm.charCoords(res, 'div');\n            var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };\n            var res = cm.coordsChar(goalCoords, 'div');\n          } else {\n            var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');\n            resCoords.left = vim.lastHSPos;\n            res = cm.coordsChar(resCoords, 'div');\n          }\n        }\n        vim.lastHPos = res.ch;\n        return res;\n      },\n      moveByPage: function(cm, head, motionArgs) {\n        // CodeMirror only exposes functions that move the cursor page down, so\n        // doing this bad hack to move the cursor and move it back. evalInput\n        // will move the cursor to where it should be in the end.\n        var curStart = head;\n        var repeat = motionArgs.repeat;\n        return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');\n      },\n      moveByParagraph: function(cm, head, motionArgs) {\n        var dir = motionArgs.forward ? 1 : -1;\n        return findParagraph(cm, head, motionArgs.repeat, dir);\n      },\n      moveBySentence: function(cm, head, motionArgs) {\n        var dir = motionArgs.forward ? 1 : -1;\n        return findSentence(cm, head, motionArgs.repeat, dir);\n      },\n      moveByScroll: function(cm, head, motionArgs, vim) {\n        var scrollbox = cm.getScrollInfo();\n        var curEnd = null;\n        var repeat = motionArgs.repeat;\n        if (!repeat) {\n          repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());\n        }\n        var orig = cm.charCoords(head, 'local');\n        motionArgs.repeat = repeat;\n        var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);\n        if (!curEnd) {\n          return null;\n        }\n        var dest = cm.charCoords(curEnd, 'local');\n        cm.scrollTo(null, scrollbox.top + dest.top - orig.top);\n        return curEnd;\n      },\n      moveByWords: function(cm, head, motionArgs) {\n        return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,\n            !!motionArgs.wordEnd, !!motionArgs.bigWord);\n      },\n      moveTillCharacter: function(cm, _head, motionArgs) {\n        var repeat = motionArgs.repeat;\n        var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,\n            motionArgs.selectedCharacter);\n        var increment = motionArgs.forward ? -1 : 1;\n        recordLastCharacterSearch(increment, motionArgs);\n        if (!curEnd) return null;\n        curEnd.ch += increment;\n        return curEnd;\n      },\n      moveToCharacter: function(cm, head, motionArgs) {\n        var repeat = motionArgs.repeat;\n        recordLastCharacterSearch(0, motionArgs);\n        return moveToCharacter(cm, repeat, motionArgs.forward,\n            motionArgs.selectedCharacter) || head;\n      },\n      moveToSymbol: function(cm, head, motionArgs) {\n        var repeat = motionArgs.repeat;\n        return findSymbol(cm, repeat, motionArgs.forward,\n            motionArgs.selectedCharacter) || head;\n      },\n      moveToColumn: function(cm, head, motionArgs, vim) {\n        var repeat = motionArgs.repeat;\n        // repeat is equivalent to which column we want to move to!\n        vim.lastHPos = repeat - 1;\n        vim.lastHSPos = cm.charCoords(head,'div').left;\n        return moveToColumn(cm, repeat);\n      },\n      moveToEol: function(cm, head, motionArgs, vim) {\n        var cur = head;\n        vim.lastHPos = Infinity;\n        var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);\n        var end=cm.clipPos(retval);\n        end.ch--;\n        vim.lastHSPos = cm.charCoords(end,'div').left;\n        return retval;\n      },\n      moveToFirstNonWhiteSpaceCharacter: function(cm, head) {\n        // Go to the start of the line where the text begins, or the end for\n        // whitespace-only lines\n        var cursor = head;\n        return Pos(cursor.line,\n                   findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));\n      },\n      moveToMatchedSymbol: function(cm, head) {\n        var cursor = head;\n        var line = cursor.line;\n        var ch = cursor.ch;\n        var lineText = cm.getLine(line);\n        var symbol;\n        for (; ch < lineText.length; ch++) {\n          symbol = lineText.charAt(ch);\n          if (symbol && isMatchableSymbol(symbol)) {\n            var style = cm.getTokenTypeAt(Pos(line, ch + 1));\n            if (style !== \"string\" && style !== \"comment\") {\n              break;\n            }\n          }\n        }\n        if (ch < lineText.length) {\n          var matched = cm.findMatchingBracket(Pos(line, ch), {bracketRegex: /[(){}[\\]<>]/});\n          return matched.to;\n        } else {\n          return cursor;\n        }\n      },\n      moveToStartOfLine: function(_cm, head) {\n        return Pos(head.line, 0);\n      },\n      moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {\n        var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();\n        if (motionArgs.repeatIsExplicit) {\n          lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');\n        }\n        return Pos(lineNum,\n                   findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));\n      },\n      textObjectManipulation: function(cm, head, motionArgs, vim) {\n        // TODO: lots of possible exceptions that can be thrown here. Try da(\n        //     outside of a () block.\n        var mirroredPairs = {'(': ')', ')': '(',\n                             '{': '}', '}': '{',\n                             '[': ']', ']': '[',\n                             '<': '>', '>': '<'};\n        var selfPaired = {'\\'': true, '\"': true};\n\n        var character = motionArgs.selectedCharacter;\n        // 'b' refers to  '()' block.\n        // 'B' refers to  '{}' block.\n        if (character == 'b') {\n          character = '(';\n        } else if (character == 'B') {\n          character = '{';\n        }\n\n        // Inclusive is the difference between a and i\n        // TODO: Instead of using the additional text object map to perform text\n        //     object operations, merge the map into the defaultKeyMap and use\n        //     motionArgs to define behavior. Define separate entries for 'aw',\n        //     'iw', 'a[', 'i[', etc.\n        var inclusive = !motionArgs.textObjectInner;\n\n        var tmp;\n        if (mirroredPairs[character]) {\n          tmp = selectCompanionObject(cm, head, character, inclusive);\n        } else if (selfPaired[character]) {\n          tmp = findBeginningAndEnd(cm, head, character, inclusive);\n        } else if (character === 'W') {\n          tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,\n                                                     true /** bigWord */);\n        } else if (character === 'w') {\n          tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,\n                                                     false /** bigWord */);\n        } else if (character === 'p') {\n          tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);\n          motionArgs.linewise = true;\n          if (vim.visualMode) {\n            if (!vim.visualLine) { vim.visualLine = true; }\n          } else {\n            var operatorArgs = vim.inputState.operatorArgs;\n            if (operatorArgs) { operatorArgs.linewise = true; }\n            tmp.end.line--;\n          }\n        } else {\n          // No text object defined for this, don't move.\n          return null;\n        }\n\n        if (!cm.state.vim.visualMode) {\n          return [tmp.start, tmp.end];\n        } else {\n          return expandSelection(cm, tmp.start, tmp.end);\n        }\n      },\n\n      repeatLastCharacterSearch: function(cm, head, motionArgs) {\n        var lastSearch = vimGlobalState.lastCharacterSearch;\n        var repeat = motionArgs.repeat;\n        var forward = motionArgs.forward === lastSearch.forward;\n        var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);\n        cm.moveH(-increment, 'char');\n        motionArgs.inclusive = forward ? true : false;\n        var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);\n        if (!curEnd) {\n          cm.moveH(increment, 'char');\n          return head;\n        }\n        curEnd.ch += increment;\n        return curEnd;\n      }\n    };\n\n    function defineMotion(name, fn) {\n      motions[name] = fn;\n    }\n\n    function fillArray(val, times) {\n      var arr = [];\n      for (var i = 0; i < times; i++) {\n        arr.push(val);\n      }\n      return arr;\n    }\n    /**\n     * An operator acts on a text selection. It receives the list of selections\n     * as input. The corresponding CodeMirror selection is guaranteed to\n    * match the input selection.\n     */\n    var operators = {\n      change: function(cm, args, ranges) {\n        var finalHead, text;\n        var vim = cm.state.vim;\n        vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock;\n        if (!vim.visualMode) {\n          var anchor = ranges[0].anchor,\n              head = ranges[0].head;\n          text = cm.getRange(anchor, head);\n          var lastState = vim.lastEditInputState || {};\n          if (lastState.motion == \"moveByWords\" && !isWhiteSpaceString(text)) {\n            // Exclude trailing whitespace if the range is not all whitespace.\n            var match = (/\\s+$/).exec(text);\n            if (match && lastState.motionArgs && lastState.motionArgs.forward) {\n              head = offsetCursor(head, 0, - match[0].length);\n              text = text.slice(0, - match[0].length);\n            }\n          }\n          var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE);\n          var wasLastLine = cm.firstLine() == cm.lastLine();\n          if (head.line > cm.lastLine() && args.linewise && !wasLastLine) {\n            cm.replaceRange('', prevLineEnd, head);\n          } else {\n            cm.replaceRange('', anchor, head);\n          }\n          if (args.linewise) {\n            // Push the next line back down, if there is a next line.\n            if (!wasLastLine) {\n              cm.setCursor(prevLineEnd);\n              CodeMirror.commands.newlineAndIndent(cm);\n            }\n            // make sure cursor ends up at the end of the line.\n            anchor.ch = Number.MAX_VALUE;\n          }\n          finalHead = anchor;\n        } else {\n          text = cm.getSelection();\n          var replacement = fillArray('', ranges.length);\n          cm.replaceSelections(replacement);\n          finalHead = cursorMin(ranges[0].head, ranges[0].anchor);\n        }\n        vimGlobalState.registerController.pushText(\n            args.registerName, 'change', text,\n            args.linewise, ranges.length > 1);\n        actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);\n      },\n      // delete is a javascript keyword.\n      'delete': function(cm, args, ranges) {\n        var finalHead, text;\n        var vim = cm.state.vim;\n        if (!vim.visualBlock) {\n          var anchor = ranges[0].anchor,\n              head = ranges[0].head;\n          if (args.linewise &&\n              head.line != cm.firstLine() &&\n              anchor.line == cm.lastLine() &&\n              anchor.line == head.line - 1) {\n            // Special case for dd on last line (and first line).\n            if (anchor.line == cm.firstLine()) {\n              anchor.ch = 0;\n            } else {\n              anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));\n            }\n          }\n          text = cm.getRange(anchor, head);\n          cm.replaceRange('', anchor, head);\n          finalHead = anchor;\n          if (args.linewise) {\n            finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);\n          }\n        } else {\n          text = cm.getSelection();\n          var replacement = fillArray('', ranges.length);\n          cm.replaceSelections(replacement);\n          finalHead = ranges[0].anchor;\n        }\n        vimGlobalState.registerController.pushText(\n            args.registerName, 'delete', text,\n            args.linewise, vim.visualBlock);\n        var includeLineBreak = vim.insertMode\n        return clipCursorToContent(cm, finalHead, includeLineBreak);\n      },\n      indent: function(cm, args, ranges) {\n        var vim = cm.state.vim;\n        var startLine = ranges[0].anchor.line;\n        var endLine = vim.visualBlock ?\n          ranges[ranges.length - 1].anchor.line :\n          ranges[0].head.line;\n        // In visual mode, n> shifts the selection right n times, instead of\n        // shifting n lines right once.\n        var repeat = (vim.visualMode) ? args.repeat : 1;\n        if (args.linewise) {\n          // The only way to delete a newline is to delete until the start of\n          // the next line, so in linewise mode evalInput will include the next\n          // line. We don't want this in indent, so we go back a line.\n          endLine--;\n        }\n        for (var i = startLine; i <= endLine; i++) {\n          for (var j = 0; j < repeat; j++) {\n            cm.indentLine(i, args.indentRight);\n          }\n        }\n        return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);\n      },\n      indentAuto: function(cm, _args, ranges) {\n        cm.execCommand(\"indentAuto\");\n        return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);\n      },\n      changeCase: function(cm, args, ranges, oldAnchor, newHead) {\n        var selections = cm.getSelections();\n        var swapped = [];\n        var toLower = args.toLower;\n        for (var j = 0; j < selections.length; j++) {\n          var toSwap = selections[j];\n          var text = '';\n          if (toLower === true) {\n            text = toSwap.toLowerCase();\n          } else if (toLower === false) {\n            text = toSwap.toUpperCase();\n          } else {\n            for (var i = 0; i < toSwap.length; i++) {\n              var character = toSwap.charAt(i);\n              text += isUpperCase(character) ? character.toLowerCase() :\n                  character.toUpperCase();\n            }\n          }\n          swapped.push(text);\n        }\n        cm.replaceSelections(swapped);\n        if (args.shouldMoveCursor){\n          return newHead;\n        } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {\n          return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);\n        } else if (args.linewise){\n          return oldAnchor;\n        } else {\n          return cursorMin(ranges[0].anchor, ranges[0].head);\n        }\n      },\n      yank: function(cm, args, ranges, oldAnchor) {\n        var vim = cm.state.vim;\n        var text = cm.getSelection();\n        var endPos = vim.visualMode\n          ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)\n          : oldAnchor;\n        vimGlobalState.registerController.pushText(\n            args.registerName, 'yank',\n            text, args.linewise, vim.visualBlock);\n        return endPos;\n      }\n    };\n\n    function defineOperator(name, fn) {\n      operators[name] = fn;\n    }\n\n    var actions = {\n      jumpListWalk: function(cm, actionArgs, vim) {\n        if (vim.visualMode) {\n          return;\n        }\n        var repeat = actionArgs.repeat;\n        var forward = actionArgs.forward;\n        var jumpList = vimGlobalState.jumpList;\n\n        var mark = jumpList.move(cm, forward ? repeat : -repeat);\n        var markPos = mark ? mark.find() : undefined;\n        markPos = markPos ? markPos : cm.getCursor();\n        cm.setCursor(markPos);\n      },\n      scroll: function(cm, actionArgs, vim) {\n        if (vim.visualMode) {\n          return;\n        }\n        var repeat = actionArgs.repeat || 1;\n        var lineHeight = cm.defaultTextHeight();\n        var top = cm.getScrollInfo().top;\n        var delta = lineHeight * repeat;\n        var newPos = actionArgs.forward ? top + delta : top - delta;\n        var cursor = copyCursor(cm.getCursor());\n        var cursorCoords = cm.charCoords(cursor, 'local');\n        if (actionArgs.forward) {\n          if (newPos > cursorCoords.top) {\n             cursor.line += (newPos - cursorCoords.top) / lineHeight;\n             cursor.line = Math.ceil(cursor.line);\n             cm.setCursor(cursor);\n             cursorCoords = cm.charCoords(cursor, 'local');\n             cm.scrollTo(null, cursorCoords.top);\n          } else {\n             // Cursor stays within bounds.  Just reposition the scroll window.\n             cm.scrollTo(null, newPos);\n          }\n        } else {\n          var newBottom = newPos + cm.getScrollInfo().clientHeight;\n          if (newBottom < cursorCoords.bottom) {\n             cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;\n             cursor.line = Math.floor(cursor.line);\n             cm.setCursor(cursor);\n             cursorCoords = cm.charCoords(cursor, 'local');\n             cm.scrollTo(\n                 null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);\n          } else {\n             // Cursor stays within bounds.  Just reposition the scroll window.\n             cm.scrollTo(null, newPos);\n          }\n        }\n      },\n      scrollToCursor: function(cm, actionArgs) {\n        var lineNum = cm.getCursor().line;\n        var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');\n        var height = cm.getScrollInfo().clientHeight;\n        var y = charCoords.top;\n        var lineHeight = charCoords.bottom - y;\n        switch (actionArgs.position) {\n          case 'center': y = y - (height / 2) + lineHeight;\n            break;\n          case 'bottom': y = y - height + lineHeight;\n            break;\n        }\n        cm.scrollTo(null, y);\n      },\n      replayMacro: function(cm, actionArgs, vim) {\n        var registerName = actionArgs.selectedCharacter;\n        var repeat = actionArgs.repeat;\n        var macroModeState = vimGlobalState.macroModeState;\n        if (registerName == '@') {\n          registerName = macroModeState.latestRegister;\n        }\n        while(repeat--){\n          executeMacroRegister(cm, vim, macroModeState, registerName);\n        }\n      },\n      enterMacroRecordMode: function(cm, actionArgs) {\n        var macroModeState = vimGlobalState.macroModeState;\n        var registerName = actionArgs.selectedCharacter;\n        if (vimGlobalState.registerController.isValidRegister(registerName)) {\n          macroModeState.enterMacroRecordMode(cm, registerName);\n        }\n      },\n      toggleOverwrite: function(cm) {\n        if (!cm.state.overwrite) {\n          cm.toggleOverwrite(true);\n          cm.setOption('keyMap', 'vim-replace');\n          CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"replace\"});\n        } else {\n          cm.toggleOverwrite(false);\n          cm.setOption('keyMap', 'vim-insert');\n          CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"insert\"});\n        }\n      },\n      enterInsertMode: function(cm, actionArgs, vim) {\n        if (cm.getOption('readOnly')) { return; }\n        vim.insertMode = true;\n        vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;\n        var insertAt = (actionArgs) ? actionArgs.insertAt : null;\n        var sel = vim.sel;\n        var head = actionArgs.head || cm.getCursor('head');\n        var height = cm.listSelections().length;\n        if (insertAt == 'eol') {\n          head = Pos(head.line, lineLength(cm, head.line));\n        } else if (insertAt == 'charAfter') {\n          head = offsetCursor(head, 0, 1);\n        } else if (insertAt == 'firstNonBlank') {\n          head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);\n        } else if (insertAt == 'startOfSelectedArea') {\n          if (!vim.visualBlock) {\n            if (sel.head.line < sel.anchor.line) {\n              head = sel.head;\n            } else {\n              head = Pos(sel.anchor.line, 0);\n            }\n          } else {\n            head = Pos(\n                Math.min(sel.head.line, sel.anchor.line),\n                Math.min(sel.head.ch, sel.anchor.ch));\n            height = Math.abs(sel.head.line - sel.anchor.line) + 1;\n          }\n        } else if (insertAt == 'endOfSelectedArea') {\n          if (!vim.visualBlock) {\n            if (sel.head.line >= sel.anchor.line) {\n              head = offsetCursor(sel.head, 0, 1);\n            } else {\n              head = Pos(sel.anchor.line, 0);\n            }\n          } else {\n            head = Pos(\n                Math.min(sel.head.line, sel.anchor.line),\n                Math.max(sel.head.ch + 1, sel.anchor.ch));\n            height = Math.abs(sel.head.line - sel.anchor.line) + 1;\n          }\n        } else if (insertAt == 'inplace') {\n          if (vim.visualMode){\n            return;\n          }\n        }\n        cm.setOption('disableInput', false);\n        if (actionArgs && actionArgs.replace) {\n          // Handle Replace-mode as a special case of insert mode.\n          cm.toggleOverwrite(true);\n          cm.setOption('keyMap', 'vim-replace');\n          CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"replace\"});\n        } else {\n          cm.toggleOverwrite(false);\n          cm.setOption('keyMap', 'vim-insert');\n          CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"insert\"});\n        }\n        if (!vimGlobalState.macroModeState.isPlaying) {\n          // Only record if not replaying.\n          cm.on('change', onChange);\n          CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);\n        }\n        if (vim.visualMode) {\n          exitVisualMode(cm);\n        }\n        selectForInsert(cm, head, height);\n      },\n      toggleVisualMode: function(cm, actionArgs, vim) {\n        var repeat = actionArgs.repeat;\n        var anchor = cm.getCursor();\n        var head;\n        // TODO: The repeat should actually select number of characters/lines\n        //     equal to the repeat times the size of the previous visual\n        //     operation.\n        if (!vim.visualMode) {\n          // Entering visual mode\n          vim.visualMode = true;\n          vim.visualLine = !!actionArgs.linewise;\n          vim.visualBlock = !!actionArgs.blockwise;\n          head = clipCursorToContent(\n              cm, Pos(anchor.line, anchor.ch + repeat - 1),\n              true /** includeLineBreak */);\n          vim.sel = {\n            anchor: anchor,\n            head: head\n          };\n          CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"visual\", subMode: vim.visualLine ? \"linewise\" : vim.visualBlock ? \"blockwise\" : \"\"});\n          updateCmSelection(cm);\n          updateMark(cm, vim, '<', cursorMin(anchor, head));\n          updateMark(cm, vim, '>', cursorMax(anchor, head));\n        } else if (vim.visualLine ^ actionArgs.linewise ||\n            vim.visualBlock ^ actionArgs.blockwise) {\n          // Toggling between modes\n          vim.visualLine = !!actionArgs.linewise;\n          vim.visualBlock = !!actionArgs.blockwise;\n          CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"visual\", subMode: vim.visualLine ? \"linewise\" : vim.visualBlock ? \"blockwise\" : \"\"});\n          updateCmSelection(cm);\n        } else {\n          exitVisualMode(cm);\n        }\n      },\n      reselectLastSelection: function(cm, _actionArgs, vim) {\n        var lastSelection = vim.lastSelection;\n        if (vim.visualMode) {\n          updateLastSelection(cm, vim);\n        }\n        if (lastSelection) {\n          var anchor = lastSelection.anchorMark.find();\n          var head = lastSelection.headMark.find();\n          if (!anchor || !head) {\n            // If the marks have been destroyed due to edits, do nothing.\n            return;\n          }\n          vim.sel = {\n            anchor: anchor,\n            head: head\n          };\n          vim.visualMode = true;\n          vim.visualLine = lastSelection.visualLine;\n          vim.visualBlock = lastSelection.visualBlock;\n          updateCmSelection(cm);\n          updateMark(cm, vim, '<', cursorMin(anchor, head));\n          updateMark(cm, vim, '>', cursorMax(anchor, head));\n          CodeMirror.signal(cm, 'vim-mode-change', {\n            mode: 'visual',\n            subMode: vim.visualLine ? 'linewise' :\n                     vim.visualBlock ? 'blockwise' : ''});\n        }\n      },\n      joinLines: function(cm, actionArgs, vim) {\n        var curStart, curEnd;\n        if (vim.visualMode) {\n          curStart = cm.getCursor('anchor');\n          curEnd = cm.getCursor('head');\n          if (cursorIsBefore(curEnd, curStart)) {\n            var tmp = curEnd;\n            curEnd = curStart;\n            curStart = tmp;\n          }\n          curEnd.ch = lineLength(cm, curEnd.line) - 1;\n        } else {\n          // Repeat is the number of lines to join. Minimum 2 lines.\n          var repeat = Math.max(actionArgs.repeat, 2);\n          curStart = cm.getCursor();\n          curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,\n                                               Infinity));\n        }\n        var finalCh = 0;\n        for (var i = curStart.line; i < curEnd.line; i++) {\n          finalCh = lineLength(cm, curStart.line);\n          var tmp = Pos(curStart.line + 1,\n                        lineLength(cm, curStart.line + 1));\n          var text = cm.getRange(curStart, tmp);\n          text = text.replace(/\\n\\s*/g, ' ');\n          cm.replaceRange(text, curStart, tmp);\n        }\n        var curFinalPos = Pos(curStart.line, finalCh);\n        if (vim.visualMode) {\n          exitVisualMode(cm, false);\n        }\n        cm.setCursor(curFinalPos);\n      },\n      newLineAndEnterInsertMode: function(cm, actionArgs, vim) {\n        vim.insertMode = true;\n        var insertAt = copyCursor(cm.getCursor());\n        if (insertAt.line === cm.firstLine() && !actionArgs.after) {\n          // Special case for inserting newline before start of document.\n          cm.replaceRange('\\n', Pos(cm.firstLine(), 0));\n          cm.setCursor(cm.firstLine(), 0);\n        } else {\n          insertAt.line = (actionArgs.after) ? insertAt.line :\n              insertAt.line - 1;\n          insertAt.ch = lineLength(cm, insertAt.line);\n          cm.setCursor(insertAt);\n          var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||\n              CodeMirror.commands.newlineAndIndent;\n          newlineFn(cm);\n        }\n        this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);\n      },\n      paste: function(cm, actionArgs, vim) {\n        var cur = copyCursor(cm.getCursor());\n        var register = vimGlobalState.registerController.getRegister(\n            actionArgs.registerName);\n        var text = register.toString();\n        if (!text) {\n          return;\n        }\n        if (actionArgs.matchIndent) {\n          var tabSize = cm.getOption(\"tabSize\");\n          // length that considers tabs and tabSize\n          var whitespaceLength = function(str) {\n            var tabs = (str.split(\"\\t\").length - 1);\n            var spaces = (str.split(\" \").length - 1);\n            return tabs * tabSize + spaces * 1;\n          };\n          var currentLine = cm.getLine(cm.getCursor().line);\n          var indent = whitespaceLength(currentLine.match(/^\\s*/)[0]);\n          // chomp last newline b/c don't want it to match /^\\s*/gm\n          var chompedText = text.replace(/\\n$/, '');\n          var wasChomped = text !== chompedText;\n          var firstIndent = whitespaceLength(text.match(/^\\s*/)[0]);\n          var text = chompedText.replace(/^\\s*/gm, function(wspace) {\n            var newIndent = indent + (whitespaceLength(wspace) - firstIndent);\n            if (newIndent < 0) {\n              return \"\";\n            }\n            else if (cm.getOption(\"indentWithTabs\")) {\n              var quotient = Math.floor(newIndent / tabSize);\n              return Array(quotient + 1).join('\\t');\n            }\n            else {\n              return Array(newIndent + 1).join(' ');\n            }\n          });\n          text += wasChomped ? \"\\n\" : \"\";\n        }\n        if (actionArgs.repeat > 1) {\n          var text = Array(actionArgs.repeat + 1).join(text);\n        }\n        var linewise = register.linewise;\n        var blockwise = register.blockwise;\n        if (linewise) {\n          if(vim.visualMode) {\n            text = vim.visualLine ? text.slice(0, -1) : '\\n' + text.slice(0, text.length - 1) + '\\n';\n          } else if (actionArgs.after) {\n            // Move the newline at the end to the start instead, and paste just\n            // before the newline character of the line we are on right now.\n            text = '\\n' + text.slice(0, text.length - 1);\n            cur.ch = lineLength(cm, cur.line);\n          } else {\n            cur.ch = 0;\n          }\n        } else {\n          if (blockwise) {\n            text = text.split('\\n');\n            for (var i = 0; i < text.length; i++) {\n              text[i] = (text[i] == '') ? ' ' : text[i];\n            }\n          }\n          cur.ch += actionArgs.after ? 1 : 0;\n        }\n        var curPosFinal;\n        var idx;\n        if (vim.visualMode) {\n          //  save the pasted text for reselection if the need arises\n          vim.lastPastedText = text;\n          var lastSelectionCurEnd;\n          var selectedArea = getSelectedAreaRange(cm, vim);\n          var selectionStart = selectedArea[0];\n          var selectionEnd = selectedArea[1];\n          var selectedText = cm.getSelection();\n          var selections = cm.listSelections();\n          var emptyStrings = new Array(selections.length).join('1').split('1');\n          // save the curEnd marker before it get cleared due to cm.replaceRange.\n          if (vim.lastSelection) {\n            lastSelectionCurEnd = vim.lastSelection.headMark.find();\n          }\n          // push the previously selected text to unnamed register\n          vimGlobalState.registerController.unnamedRegister.setText(selectedText);\n          if (blockwise) {\n            // first delete the selected text\n            cm.replaceSelections(emptyStrings);\n            // Set new selections as per the block length of the yanked text\n            selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch);\n            cm.setCursor(selectionStart);\n            selectBlock(cm, selectionEnd);\n            cm.replaceSelections(text);\n            curPosFinal = selectionStart;\n          } else if (vim.visualBlock) {\n            cm.replaceSelections(emptyStrings);\n            cm.setCursor(selectionStart);\n            cm.replaceRange(text, selectionStart, selectionStart);\n            curPosFinal = selectionStart;\n          } else {\n            cm.replaceRange(text, selectionStart, selectionEnd);\n            curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);\n          }\n          // restore the the curEnd marker\n          if(lastSelectionCurEnd) {\n            vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);\n          }\n          if (linewise) {\n            curPosFinal.ch=0;\n          }\n        } else {\n          if (blockwise) {\n            cm.setCursor(cur);\n            for (var i = 0; i < text.length; i++) {\n              var line = cur.line+i;\n              if (line > cm.lastLine()) {\n                cm.replaceRange('\\n',  Pos(line, 0));\n              }\n              var lastCh = lineLength(cm, line);\n              if (lastCh < cur.ch) {\n                extendLineToColumn(cm, line, cur.ch);\n              }\n            }\n            cm.setCursor(cur);\n            selectBlock(cm, Pos(cur.line + text.length-1, cur.ch));\n            cm.replaceSelections(text);\n            curPosFinal = cur;\n          } else {\n            cm.replaceRange(text, cur);\n            // Now fine tune the cursor to where we want it.\n            if (linewise && actionArgs.after) {\n              curPosFinal = Pos(\n              cur.line + 1,\n              findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));\n            } else if (linewise && !actionArgs.after) {\n              curPosFinal = Pos(\n                cur.line,\n                findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));\n            } else if (!linewise && actionArgs.after) {\n              idx = cm.indexFromPos(cur);\n              curPosFinal = cm.posFromIndex(idx + text.length - 1);\n            } else {\n              idx = cm.indexFromPos(cur);\n              curPosFinal = cm.posFromIndex(idx + text.length);\n            }\n          }\n        }\n        if (vim.visualMode) {\n          exitVisualMode(cm, false);\n        }\n        cm.setCursor(curPosFinal);\n      },\n      undo: function(cm, actionArgs) {\n        cm.operation(function() {\n          repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();\n          cm.setCursor(cm.getCursor('anchor'));\n        });\n      },\n      redo: function(cm, actionArgs) {\n        repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();\n      },\n      setRegister: function(_cm, actionArgs, vim) {\n        vim.inputState.registerName = actionArgs.selectedCharacter;\n      },\n      setMark: function(cm, actionArgs, vim) {\n        var markName = actionArgs.selectedCharacter;\n        updateMark(cm, vim, markName, cm.getCursor());\n      },\n      replace: function(cm, actionArgs, vim) {\n        var replaceWith = actionArgs.selectedCharacter;\n        var curStart = cm.getCursor();\n        var replaceTo;\n        var curEnd;\n        var selections = cm.listSelections();\n        if (vim.visualMode) {\n          curStart = cm.getCursor('start');\n          curEnd = cm.getCursor('end');\n        } else {\n          var line = cm.getLine(curStart.line);\n          replaceTo = curStart.ch + actionArgs.repeat;\n          if (replaceTo > line.length) {\n            replaceTo=line.length;\n          }\n          curEnd = Pos(curStart.line, replaceTo);\n        }\n        if (replaceWith=='\\n') {\n          if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);\n          // special case, where vim help says to replace by just one line-break\n          (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);\n        } else {\n          var replaceWithStr = cm.getRange(curStart, curEnd);\n          //replace all characters in range by selected, but keep linebreaks\n          replaceWithStr = replaceWithStr.replace(/[^\\n]/g, replaceWith);\n          if (vim.visualBlock) {\n            // Tabs are split in visua block before replacing\n            var spaces = new Array(cm.getOption(\"tabSize\")+1).join(' ');\n            replaceWithStr = cm.getSelection();\n            replaceWithStr = replaceWithStr.replace(/\\t/g, spaces).replace(/[^\\n]/g, replaceWith).split('\\n');\n            cm.replaceSelections(replaceWithStr);\n          } else {\n            cm.replaceRange(replaceWithStr, curStart, curEnd);\n          }\n          if (vim.visualMode) {\n            curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?\n                         selections[0].anchor : selections[0].head;\n            cm.setCursor(curStart);\n            exitVisualMode(cm, false);\n          } else {\n            cm.setCursor(offsetCursor(curEnd, 0, -1));\n          }\n        }\n      },\n      incrementNumberToken: function(cm, actionArgs) {\n        var cur = cm.getCursor();\n        var lineStr = cm.getLine(cur.line);\n        var re = /(-?)(?:(0x)([\\da-f]+)|(0b|0|)(\\d+))/gi;\n        var match;\n        var start;\n        var end;\n        var numberStr;\n        while ((match = re.exec(lineStr)) !== null) {\n          start = match.index;\n          end = start + match[0].length;\n          if (cur.ch < end)break;\n        }\n        if (!actionArgs.backtrack && (end <= cur.ch))return;\n        if (match) {\n          var baseStr = match[2] || match[4]\n          var digits = match[3] || match[5]\n          var increment = actionArgs.increase ? 1 : -1;\n          var base = {'0b': 2, '0': 8, '': 10, '0x': 16}[baseStr.toLowerCase()];\n          var number = parseInt(match[1] + digits, base) + (increment * actionArgs.repeat);\n          numberStr = number.toString(base);\n          var zeroPadding = baseStr ? new Array(digits.length - numberStr.length + 1 + match[1].length).join('0') : ''\n          if (numberStr.charAt(0) === '-') {\n            numberStr = '-' + baseStr + zeroPadding + numberStr.substr(1);\n          } else {\n            numberStr = baseStr + zeroPadding + numberStr;\n          }\n          var from = Pos(cur.line, start);\n          var to = Pos(cur.line, end);\n          cm.replaceRange(numberStr, from, to);\n        } else {\n          return;\n        }\n        cm.setCursor(Pos(cur.line, start + numberStr.length - 1));\n      },\n      repeatLastEdit: function(cm, actionArgs, vim) {\n        var lastEditInputState = vim.lastEditInputState;\n        if (!lastEditInputState) { return; }\n        var repeat = actionArgs.repeat;\n        if (repeat && actionArgs.repeatIsExplicit) {\n          vim.lastEditInputState.repeatOverride = repeat;\n        } else {\n          repeat = vim.lastEditInputState.repeatOverride || repeat;\n        }\n        repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);\n      },\n      indent: function(cm, actionArgs) {\n        cm.indentLine(cm.getCursor().line, actionArgs.indentRight);\n      },\n      exitInsertMode: exitInsertMode\n    };\n\n    function defineAction(name, fn) {\n      actions[name] = fn;\n    }\n\n    /*\n     * Below are miscellaneous utility functions used by vim.js\n     */\n\n    /**\n     * Clips cursor to ensure that line is within the buffer's range\n     * If includeLineBreak is true, then allow cur.ch == lineLength.\n     */\n    function clipCursorToContent(cm, cur, includeLineBreak) {\n      var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );\n      var maxCh = lineLength(cm, line) - 1;\n      maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;\n      var ch = Math.min(Math.max(0, cur.ch), maxCh);\n      return Pos(line, ch);\n    }\n    function copyArgs(args) {\n      var ret = {};\n      for (var prop in args) {\n        if (args.hasOwnProperty(prop)) {\n          ret[prop] = args[prop];\n        }\n      }\n      return ret;\n    }\n    function offsetCursor(cur, offsetLine, offsetCh) {\n      if (typeof offsetLine === 'object') {\n        offsetCh = offsetLine.ch;\n        offsetLine = offsetLine.line;\n      }\n      return Pos(cur.line + offsetLine, cur.ch + offsetCh);\n    }\n    function getOffset(anchor, head) {\n      return {\n        line: head.line - anchor.line,\n        ch: head.line - anchor.line\n      };\n    }\n    function commandMatches(keys, keyMap, context, inputState) {\n      // Partial matches are not applied. They inform the key handler\n      // that the current key sequence is a subsequence of a valid key\n      // sequence, so that the key buffer is not cleared.\n      var match, partial = [], full = [];\n      for (var i = 0; i < keyMap.length; i++) {\n        var command = keyMap[i];\n        if (context == 'insert' && command.context != 'insert' ||\n            command.context && command.context != context ||\n            inputState.operator && command.type == 'action' ||\n            !(match = commandMatch(keys, command.keys))) { continue; }\n        if (match == 'partial') { partial.push(command); }\n        if (match == 'full') { full.push(command); }\n      }\n      return {\n        partial: partial.length && partial,\n        full: full.length && full\n      };\n    }\n    function commandMatch(pressed, mapped) {\n      if (mapped.slice(-11) == '<character>') {\n        // Last character matches anything.\n        var prefixLen = mapped.length - 11;\n        var pressedPrefix = pressed.slice(0, prefixLen);\n        var mappedPrefix = mapped.slice(0, prefixLen);\n        return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :\n               mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;\n      } else {\n        return pressed == mapped ? 'full' :\n               mapped.indexOf(pressed) == 0 ? 'partial' : false;\n      }\n    }\n    function lastChar(keys) {\n      var match = /^.*(<[^>]+>)$/.exec(keys);\n      var selectedCharacter = match ? match[1] : keys.slice(-1);\n      if (selectedCharacter.length > 1){\n        switch(selectedCharacter){\n          case '<CR>':\n            selectedCharacter='\\n';\n            break;\n          case '<Space>':\n            selectedCharacter=' ';\n            break;\n          default:\n            selectedCharacter='';\n            break;\n        }\n      }\n      return selectedCharacter;\n    }\n    function repeatFn(cm, fn, repeat) {\n      return function() {\n        for (var i = 0; i < repeat; i++) {\n          fn(cm);\n        }\n      };\n    }\n    function copyCursor(cur) {\n      return Pos(cur.line, cur.ch);\n    }\n    function cursorEqual(cur1, cur2) {\n      return cur1.ch == cur2.ch && cur1.line == cur2.line;\n    }\n    function cursorIsBefore(cur1, cur2) {\n      if (cur1.line < cur2.line) {\n        return true;\n      }\n      if (cur1.line == cur2.line && cur1.ch < cur2.ch) {\n        return true;\n      }\n      return false;\n    }\n    function cursorMin(cur1, cur2) {\n      if (arguments.length > 2) {\n        cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));\n      }\n      return cursorIsBefore(cur1, cur2) ? cur1 : cur2;\n    }\n    function cursorMax(cur1, cur2) {\n      if (arguments.length > 2) {\n        cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));\n      }\n      return cursorIsBefore(cur1, cur2) ? cur2 : cur1;\n    }\n    function cursorIsBetween(cur1, cur2, cur3) {\n      // returns true if cur2 is between cur1 and cur3.\n      var cur1before2 = cursorIsBefore(cur1, cur2);\n      var cur2before3 = cursorIsBefore(cur2, cur3);\n      return cur1before2 && cur2before3;\n    }\n    function lineLength(cm, lineNum) {\n      return cm.getLine(lineNum).length;\n    }\n    function trim(s) {\n      if (s.trim) {\n        return s.trim();\n      }\n      return s.replace(/^\\s+|\\s+$/g, '');\n    }\n    function escapeRegex(s) {\n      return s.replace(/([.?*+$\\[\\]\\/\\\\(){}|\\-])/g, '\\\\$1');\n    }\n    function extendLineToColumn(cm, lineNum, column) {\n      var endCh = lineLength(cm, lineNum);\n      var spaces = new Array(column-endCh+1).join(' ');\n      cm.setCursor(Pos(lineNum, endCh));\n      cm.replaceRange(spaces, cm.getCursor());\n    }\n    // This functions selects a rectangular block\n    // of text with selectionEnd as any of its corner\n    // Height of block:\n    // Difference in selectionEnd.line and first/last selection.line\n    // Width of the block:\n    // Distance between selectionEnd.ch and any(first considered here) selection.ch\n    function selectBlock(cm, selectionEnd) {\n      var selections = [], ranges = cm.listSelections();\n      var head = copyCursor(cm.clipPos(selectionEnd));\n      var isClipped = !cursorEqual(selectionEnd, head);\n      var curHead = cm.getCursor('head');\n      var primIndex = getIndex(ranges, curHead);\n      var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);\n      var max = ranges.length - 1;\n      var index = max - primIndex > primIndex ? max : 0;\n      var base = ranges[index].anchor;\n\n      var firstLine = Math.min(base.line, head.line);\n      var lastLine = Math.max(base.line, head.line);\n      var baseCh = base.ch, headCh = head.ch;\n\n      var dir = ranges[index].head.ch - baseCh;\n      var newDir = headCh - baseCh;\n      if (dir > 0 && newDir <= 0) {\n        baseCh++;\n        if (!isClipped) { headCh--; }\n      } else if (dir < 0 && newDir >= 0) {\n        baseCh--;\n        if (!wasClipped) { headCh++; }\n      } else if (dir < 0 && newDir == -1) {\n        baseCh--;\n        headCh++;\n      }\n      for (var line = firstLine; line <= lastLine; line++) {\n        var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};\n        selections.push(range);\n      }\n      cm.setSelections(selections);\n      selectionEnd.ch = headCh;\n      base.ch = baseCh;\n      return base;\n    }\n    function selectForInsert(cm, head, height) {\n      var sel = [];\n      for (var i = 0; i < height; i++) {\n        var lineHead = offsetCursor(head, i, 0);\n        sel.push({anchor: lineHead, head: lineHead});\n      }\n      cm.setSelections(sel, 0);\n    }\n    // getIndex returns the index of the cursor in the selections.\n    function getIndex(ranges, cursor, end) {\n      for (var i = 0; i < ranges.length; i++) {\n        var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);\n        var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);\n        if (atAnchor || atHead) {\n          return i;\n        }\n      }\n      return -1;\n    }\n    function getSelectedAreaRange(cm, vim) {\n      var lastSelection = vim.lastSelection;\n      var getCurrentSelectedAreaRange = function() {\n        var selections = cm.listSelections();\n        var start =  selections[0];\n        var end = selections[selections.length-1];\n        var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;\n        var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;\n        return [selectionStart, selectionEnd];\n      };\n      var getLastSelectedAreaRange = function() {\n        var selectionStart = cm.getCursor();\n        var selectionEnd = cm.getCursor();\n        var block = lastSelection.visualBlock;\n        if (block) {\n          var width = block.width;\n          var height = block.height;\n          selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width);\n          var selections = [];\n          // selectBlock creates a 'proper' rectangular block.\n          // We do not want that in all cases, so we manually set selections.\n          for (var i = selectionStart.line; i < selectionEnd.line; i++) {\n            var anchor = Pos(i, selectionStart.ch);\n            var head = Pos(i, selectionEnd.ch);\n            var range = {anchor: anchor, head: head};\n            selections.push(range);\n          }\n          cm.setSelections(selections);\n        } else {\n          var start = lastSelection.anchorMark.find();\n          var end = lastSelection.headMark.find();\n          var line = end.line - start.line;\n          var ch = end.ch - start.ch;\n          selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};\n          if (lastSelection.visualLine) {\n            selectionStart = Pos(selectionStart.line, 0);\n            selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));\n          }\n          cm.setSelection(selectionStart, selectionEnd);\n        }\n        return [selectionStart, selectionEnd];\n      };\n      if (!vim.visualMode) {\n      // In case of replaying the action.\n        return getLastSelectedAreaRange();\n      } else {\n        return getCurrentSelectedAreaRange();\n      }\n    }\n    // Updates the previous selection with the current selection's values. This\n    // should only be called in visual mode.\n    function updateLastSelection(cm, vim) {\n      var anchor = vim.sel.anchor;\n      var head = vim.sel.head;\n      // To accommodate the effect of lastPastedText in the last selection\n      if (vim.lastPastedText) {\n        head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);\n        vim.lastPastedText = null;\n      }\n      vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),\n                           'headMark': cm.setBookmark(head),\n                           'anchor': copyCursor(anchor),\n                           'head': copyCursor(head),\n                           'visualMode': vim.visualMode,\n                           'visualLine': vim.visualLine,\n                           'visualBlock': vim.visualBlock};\n    }\n    function expandSelection(cm, start, end) {\n      var sel = cm.state.vim.sel;\n      var head = sel.head;\n      var anchor = sel.anchor;\n      var tmp;\n      if (cursorIsBefore(end, start)) {\n        tmp = end;\n        end = start;\n        start = tmp;\n      }\n      if (cursorIsBefore(head, anchor)) {\n        head = cursorMin(start, head);\n        anchor = cursorMax(anchor, end);\n      } else {\n        anchor = cursorMin(start, anchor);\n        head = cursorMax(head, end);\n        head = offsetCursor(head, 0, -1);\n        if (head.ch == -1 && head.line != cm.firstLine()) {\n          head = Pos(head.line - 1, lineLength(cm, head.line - 1));\n        }\n      }\n      return [anchor, head];\n    }\n    /**\n     * Updates the CodeMirror selection to match the provided vim selection.\n     * If no arguments are given, it uses the current vim selection state.\n     */\n    function updateCmSelection(cm, sel, mode) {\n      var vim = cm.state.vim;\n      sel = sel || vim.sel;\n      var mode = mode ||\n        vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';\n      var cmSel = makeCmSelection(cm, sel, mode);\n      cm.setSelections(cmSel.ranges, cmSel.primary);\n      updateFakeCursor(cm);\n    }\n    function makeCmSelection(cm, sel, mode, exclusive) {\n      var head = copyCursor(sel.head);\n      var anchor = copyCursor(sel.anchor);\n      if (mode == 'char') {\n        var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;\n        var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;\n        head = offsetCursor(sel.head, 0, headOffset);\n        anchor = offsetCursor(sel.anchor, 0, anchorOffset);\n        return {\n          ranges: [{anchor: anchor, head: head}],\n          primary: 0\n        };\n      } else if (mode == 'line') {\n        if (!cursorIsBefore(sel.head, sel.anchor)) {\n          anchor.ch = 0;\n\n          var lastLine = cm.lastLine();\n          if (head.line > lastLine) {\n            head.line = lastLine;\n          }\n          head.ch = lineLength(cm, head.line);\n        } else {\n          head.ch = 0;\n          anchor.ch = lineLength(cm, anchor.line);\n        }\n        return {\n          ranges: [{anchor: anchor, head: head}],\n          primary: 0\n        };\n      } else if (mode == 'block') {\n        var top = Math.min(anchor.line, head.line),\n            left = Math.min(anchor.ch, head.ch),\n            bottom = Math.max(anchor.line, head.line),\n            right = Math.max(anchor.ch, head.ch) + 1;\n        var height = bottom - top + 1;\n        var primary = head.line == top ? 0 : height - 1;\n        var ranges = [];\n        for (var i = 0; i < height; i++) {\n          ranges.push({\n            anchor: Pos(top + i, left),\n            head: Pos(top + i, right)\n          });\n        }\n        return {\n          ranges: ranges,\n          primary: primary\n        };\n      }\n    }\n    function getHead(cm) {\n      var cur = cm.getCursor('head');\n      if (cm.getSelection().length == 1) {\n        // Small corner case when only 1 character is selected. The \"real\"\n        // head is the left of head and anchor.\n        cur = cursorMin(cur, cm.getCursor('anchor'));\n      }\n      return cur;\n    }\n\n    /**\n     * If moveHead is set to false, the CodeMirror selection will not be\n     * touched. The caller assumes the responsibility of putting the cursor\n    * in the right place.\n     */\n    function exitVisualMode(cm, moveHead) {\n      var vim = cm.state.vim;\n      if (moveHead !== false) {\n        cm.setCursor(clipCursorToContent(cm, vim.sel.head));\n      }\n      updateLastSelection(cm, vim);\n      vim.visualMode = false;\n      vim.visualLine = false;\n      vim.visualBlock = false;\n      CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"normal\"});\n      if (vim.fakeCursor) {\n        vim.fakeCursor.clear();\n      }\n    }\n\n    // Remove any trailing newlines from the selection. For\n    // example, with the caret at the start of the last word on the line,\n    // 'dw' should word, but not the newline, while 'w' should advance the\n    // caret to the first character of the next line.\n    function clipToLine(cm, curStart, curEnd) {\n      var selection = cm.getRange(curStart, curEnd);\n      // Only clip if the selection ends with trailing newline + whitespace\n      if (/\\n\\s*$/.test(selection)) {\n        var lines = selection.split('\\n');\n        // We know this is all whitespace.\n        lines.pop();\n\n        // Cases:\n        // 1. Last word is an empty line - do not clip the trailing '\\n'\n        // 2. Last word is not an empty line - clip the trailing '\\n'\n        var line;\n        // Find the line containing the last word, and clip all whitespace up\n        // to it.\n        for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {\n          curEnd.line--;\n          curEnd.ch = 0;\n        }\n        // If the last word is not an empty line, clip an additional newline\n        if (line) {\n          curEnd.line--;\n          curEnd.ch = lineLength(cm, curEnd.line);\n        } else {\n          curEnd.ch = 0;\n        }\n      }\n    }\n\n    // Expand the selection to line ends.\n    function expandSelectionToLine(_cm, curStart, curEnd) {\n      curStart.ch = 0;\n      curEnd.ch = 0;\n      curEnd.line++;\n    }\n\n    function findFirstNonWhiteSpaceCharacter(text) {\n      if (!text) {\n        return 0;\n      }\n      var firstNonWS = text.search(/\\S/);\n      return firstNonWS == -1 ? text.length : firstNonWS;\n    }\n\n    function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {\n      var cur = getHead(cm);\n      var line = cm.getLine(cur.line);\n      var idx = cur.ch;\n\n      // Seek to first word or non-whitespace character, depending on if\n      // noSymbol is true.\n      var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];\n      while (!test(line.charAt(idx))) {\n        idx++;\n        if (idx >= line.length) { return null; }\n      }\n\n      if (bigWord) {\n        test = bigWordCharTest[0];\n      } else {\n        test = wordCharTest[0];\n        if (!test(line.charAt(idx))) {\n          test = wordCharTest[1];\n        }\n      }\n\n      var end = idx, start = idx;\n      while (test(line.charAt(end)) && end < line.length) { end++; }\n      while (test(line.charAt(start)) && start >= 0) { start--; }\n      start++;\n\n      if (inclusive) {\n        // If present, include all whitespace after word.\n        // Otherwise, include all whitespace before word, except indentation.\n        var wordEnd = end;\n        while (/\\s/.test(line.charAt(end)) && end < line.length) { end++; }\n        if (wordEnd == end) {\n          var wordStart = start;\n          while (/\\s/.test(line.charAt(start - 1)) && start > 0) { start--; }\n          if (!start) { start = wordStart; }\n        }\n      }\n      return { start: Pos(cur.line, start), end: Pos(cur.line, end) };\n    }\n\n    function recordJumpPosition(cm, oldCur, newCur) {\n      if (!cursorEqual(oldCur, newCur)) {\n        vimGlobalState.jumpList.add(cm, oldCur, newCur);\n      }\n    }\n\n    function recordLastCharacterSearch(increment, args) {\n        vimGlobalState.lastCharacterSearch.increment = increment;\n        vimGlobalState.lastCharacterSearch.forward = args.forward;\n        vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter;\n    }\n\n    var symbolToMode = {\n        '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',\n        '[': 'section', ']': 'section',\n        '*': 'comment', '/': 'comment',\n        'm': 'method', 'M': 'method',\n        '#': 'preprocess'\n    };\n    var findSymbolModes = {\n      bracket: {\n        isComplete: function(state) {\n          if (state.nextCh === state.symb) {\n            state.depth++;\n            if (state.depth >= 1)return true;\n          } else if (state.nextCh === state.reverseSymb) {\n            state.depth--;\n          }\n          return false;\n        }\n      },\n      section: {\n        init: function(state) {\n          state.curMoveThrough = true;\n          state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';\n        },\n        isComplete: function(state) {\n          return state.index === 0 && state.nextCh === state.symb;\n        }\n      },\n      comment: {\n        isComplete: function(state) {\n          var found = state.lastCh === '*' && state.nextCh === '/';\n          state.lastCh = state.nextCh;\n          return found;\n        }\n      },\n      // TODO: The original Vim implementation only operates on level 1 and 2.\n      // The current implementation doesn't check for code block level and\n      // therefore it operates on any levels.\n      method: {\n        init: function(state) {\n          state.symb = (state.symb === 'm' ? '{' : '}');\n          state.reverseSymb = state.symb === '{' ? '}' : '{';\n        },\n        isComplete: function(state) {\n          if (state.nextCh === state.symb)return true;\n          return false;\n        }\n      },\n      preprocess: {\n        init: function(state) {\n          state.index = 0;\n        },\n        isComplete: function(state) {\n          if (state.nextCh === '#') {\n            var token = state.lineText.match(/#(\\w+)/)[1];\n            if (token === 'endif') {\n              if (state.forward && state.depth === 0) {\n                return true;\n              }\n              state.depth++;\n            } else if (token === 'if') {\n              if (!state.forward && state.depth === 0) {\n                return true;\n              }\n              state.depth--;\n            }\n            if (token === 'else' && state.depth === 0)return true;\n          }\n          return false;\n        }\n      }\n    };\n    function findSymbol(cm, repeat, forward, symb) {\n      var cur = copyCursor(cm.getCursor());\n      var increment = forward ? 1 : -1;\n      var endLine = forward ? cm.lineCount() : -1;\n      var curCh = cur.ch;\n      var line = cur.line;\n      var lineText = cm.getLine(line);\n      var state = {\n        lineText: lineText,\n        nextCh: lineText.charAt(curCh),\n        lastCh: null,\n        index: curCh,\n        symb: symb,\n        reverseSymb: (forward ?  { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],\n        forward: forward,\n        depth: 0,\n        curMoveThrough: false\n      };\n      var mode = symbolToMode[symb];\n      if (!mode)return cur;\n      var init = findSymbolModes[mode].init;\n      var isComplete = findSymbolModes[mode].isComplete;\n      if (init) { init(state); }\n      while (line !== endLine && repeat) {\n        state.index += increment;\n        state.nextCh = state.lineText.charAt(state.index);\n        if (!state.nextCh) {\n          line += increment;\n          state.lineText = cm.getLine(line) || '';\n          if (increment > 0) {\n            state.index = 0;\n          } else {\n            var lineLen = state.lineText.length;\n            state.index = (lineLen > 0) ? (lineLen-1) : 0;\n          }\n          state.nextCh = state.lineText.charAt(state.index);\n        }\n        if (isComplete(state)) {\n          cur.line = line;\n          cur.ch = state.index;\n          repeat--;\n        }\n      }\n      if (state.nextCh || state.curMoveThrough) {\n        return Pos(line, state.index);\n      }\n      return cur;\n    }\n\n    /*\n     * Returns the boundaries of the next word. If the cursor in the middle of\n     * the word, then returns the boundaries of the current word, starting at\n     * the cursor. If the cursor is at the start/end of a word, and we are going\n     * forward/backward, respectively, find the boundaries of the next word.\n     *\n     * @param {CodeMirror} cm CodeMirror object.\n     * @param {Cursor} cur The cursor position.\n     * @param {boolean} forward True to search forward. False to search\n     *     backward.\n     * @param {boolean} bigWord True if punctuation count as part of the word.\n     *     False if only [a-zA-Z0-9] characters count as part of the word.\n     * @param {boolean} emptyLineIsWord True if empty lines should be treated\n     *     as words.\n     * @return {Object{from:number, to:number, line: number}} The boundaries of\n     *     the word, or null if there are no more words.\n     */\n    function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {\n      var lineNum = cur.line;\n      var pos = cur.ch;\n      var line = cm.getLine(lineNum);\n      var dir = forward ? 1 : -1;\n      var charTests = bigWord ? bigWordCharTest: wordCharTest;\n\n      if (emptyLineIsWord && line == '') {\n        lineNum += dir;\n        line = cm.getLine(lineNum);\n        if (!isLine(cm, lineNum)) {\n          return null;\n        }\n        pos = (forward) ? 0 : line.length;\n      }\n\n      while (true) {\n        if (emptyLineIsWord && line == '') {\n          return { from: 0, to: 0, line: lineNum };\n        }\n        var stop = (dir > 0) ? line.length : -1;\n        var wordStart = stop, wordEnd = stop;\n        // Find bounds of next word.\n        while (pos != stop) {\n          var foundWord = false;\n          for (var i = 0; i < charTests.length && !foundWord; ++i) {\n            if (charTests[i](line.charAt(pos))) {\n              wordStart = pos;\n              // Advance to end of word.\n              while (pos != stop && charTests[i](line.charAt(pos))) {\n                pos += dir;\n              }\n              wordEnd = pos;\n              foundWord = wordStart != wordEnd;\n              if (wordStart == cur.ch && lineNum == cur.line &&\n                  wordEnd == wordStart + dir) {\n                // We started at the end of a word. Find the next one.\n                continue;\n              } else {\n                return {\n                  from: Math.min(wordStart, wordEnd + 1),\n                  to: Math.max(wordStart, wordEnd),\n                  line: lineNum };\n              }\n            }\n          }\n          if (!foundWord) {\n            pos += dir;\n          }\n        }\n        // Advance to next/prev line.\n        lineNum += dir;\n        if (!isLine(cm, lineNum)) {\n          return null;\n        }\n        line = cm.getLine(lineNum);\n        pos = (dir > 0) ? 0 : line.length;\n      }\n    }\n\n    /**\n     * @param {CodeMirror} cm CodeMirror object.\n     * @param {Pos} cur The position to start from.\n     * @param {int} repeat Number of words to move past.\n     * @param {boolean} forward True to search forward. False to search\n     *     backward.\n     * @param {boolean} wordEnd True to move to end of word. False to move to\n     *     beginning of word.\n     * @param {boolean} bigWord True if punctuation count as part of the word.\n     *     False if only alphabet characters count as part of the word.\n     * @return {Cursor} The position the cursor should move to.\n     */\n    function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {\n      var curStart = copyCursor(cur);\n      var words = [];\n      if (forward && !wordEnd || !forward && wordEnd) {\n        repeat++;\n      }\n      // For 'e', empty lines are not considered words, go figure.\n      var emptyLineIsWord = !(forward && wordEnd);\n      for (var i = 0; i < repeat; i++) {\n        var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);\n        if (!word) {\n          var eodCh = lineLength(cm, cm.lastLine());\n          words.push(forward\n              ? {line: cm.lastLine(), from: eodCh, to: eodCh}\n              : {line: 0, from: 0, to: 0});\n          break;\n        }\n        words.push(word);\n        cur = Pos(word.line, forward ? (word.to - 1) : word.from);\n      }\n      var shortCircuit = words.length != repeat;\n      var firstWord = words[0];\n      var lastWord = words.pop();\n      if (forward && !wordEnd) {\n        // w\n        if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {\n          // We did not start in the middle of a word. Discard the extra word at the end.\n          lastWord = words.pop();\n        }\n        return Pos(lastWord.line, lastWord.from);\n      } else if (forward && wordEnd) {\n        return Pos(lastWord.line, lastWord.to - 1);\n      } else if (!forward && wordEnd) {\n        // ge\n        if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {\n          // We did not start in the middle of a word. Discard the extra word at the end.\n          lastWord = words.pop();\n        }\n        return Pos(lastWord.line, lastWord.to);\n      } else {\n        // b\n        return Pos(lastWord.line, lastWord.from);\n      }\n    }\n\n    function moveToCharacter(cm, repeat, forward, character) {\n      var cur = cm.getCursor();\n      var start = cur.ch;\n      var idx;\n      for (var i = 0; i < repeat; i ++) {\n        var line = cm.getLine(cur.line);\n        idx = charIdxInLine(start, line, character, forward, true);\n        if (idx == -1) {\n          return null;\n        }\n        start = idx;\n      }\n      return Pos(cm.getCursor().line, idx);\n    }\n\n    function moveToColumn(cm, repeat) {\n      // repeat is always >= 1, so repeat - 1 always corresponds\n      // to the column we want to go to.\n      var line = cm.getCursor().line;\n      return clipCursorToContent(cm, Pos(line, repeat - 1));\n    }\n\n    function updateMark(cm, vim, markName, pos) {\n      if (!inArray(markName, validMarks)) {\n        return;\n      }\n      if (vim.marks[markName]) {\n        vim.marks[markName].clear();\n      }\n      vim.marks[markName] = cm.setBookmark(pos);\n    }\n\n    function charIdxInLine(start, line, character, forward, includeChar) {\n      // Search for char in line.\n      // motion_options: {forward, includeChar}\n      // If includeChar = true, include it too.\n      // If forward = true, search forward, else search backwards.\n      // If char is not found on this line, do nothing\n      var idx;\n      if (forward) {\n        idx = line.indexOf(character, start + 1);\n        if (idx != -1 && !includeChar) {\n          idx -= 1;\n        }\n      } else {\n        idx = line.lastIndexOf(character, start - 1);\n        if (idx != -1 && !includeChar) {\n          idx += 1;\n        }\n      }\n      return idx;\n    }\n\n    function findParagraph(cm, head, repeat, dir, inclusive) {\n      var line = head.line;\n      var min = cm.firstLine();\n      var max = cm.lastLine();\n      var start, end, i = line;\n      function isEmpty(i) { return !cm.getLine(i); }\n      function isBoundary(i, dir, any) {\n        if (any) { return isEmpty(i) != isEmpty(i + dir); }\n        return !isEmpty(i) && isEmpty(i + dir);\n      }\n      if (dir) {\n        while (min <= i && i <= max && repeat > 0) {\n          if (isBoundary(i, dir)) { repeat--; }\n          i += dir;\n        }\n        return new Pos(i, 0);\n      }\n\n      var vim = cm.state.vim;\n      if (vim.visualLine && isBoundary(line, 1, true)) {\n        var anchor = vim.sel.anchor;\n        if (isBoundary(anchor.line, -1, true)) {\n          if (!inclusive || anchor.line != line) {\n            line += 1;\n          }\n        }\n      }\n      var startState = isEmpty(line);\n      for (i = line; i <= max && repeat; i++) {\n        if (isBoundary(i, 1, true)) {\n          if (!inclusive || isEmpty(i) != startState) {\n            repeat--;\n          }\n        }\n      }\n      end = new Pos(i, 0);\n      // select boundary before paragraph for the last one\n      if (i > max && !startState) { startState = true; }\n      else { inclusive = false; }\n      for (i = line; i > min; i--) {\n        if (!inclusive || isEmpty(i) == startState || i == line) {\n          if (isBoundary(i, -1, true)) { break; }\n        }\n      }\n      start = new Pos(i, 0);\n      return { start: start, end: end };\n    }\n\n    function findSentence(cm, cur, repeat, dir) {\n\n      /*\n        Takes an index object\n        {\n          line: the line string,\n          ln: line number,\n          pos: index in line,\n          dir: direction of traversal (-1 or 1)\n        }\n        and modifies the line, ln, and pos members to represent the\n        next valid position or sets them to null if there are\n        no more valid positions.\n       */\n      function nextChar(cm, idx) {\n        if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) {\n          idx.ln += idx.dir;\n          if (!isLine(cm, idx.ln)) {\n            idx.line = null;\n            idx.ln = null;\n            idx.pos = null;\n            return;\n          }\n          idx.line = cm.getLine(idx.ln);\n          idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1;\n        }\n        else {\n          idx.pos += idx.dir;\n        }\n      }\n\n      /*\n        Performs one iteration of traversal in forward direction\n        Returns an index object of the new location\n       */\n      function forward(cm, ln, pos, dir) {\n        var line = cm.getLine(ln);\n        var stop = (line === \"\");\n\n        var curr = {\n          line: line,\n          ln: ln,\n          pos: pos,\n          dir: dir,\n        }\n\n        var last_valid = {\n          ln: curr.ln,\n          pos: curr.pos,\n        }\n\n        var skip_empty_lines = (curr.line === \"\");\n\n        // Move one step to skip character we start on\n        nextChar(cm, curr);\n\n        while (curr.line !== null) {\n          last_valid.ln = curr.ln;\n          last_valid.pos = curr.pos;\n\n          if (curr.line === \"\" && !skip_empty_lines) {\n            return { ln: curr.ln, pos: curr.pos, };\n          }\n          else if (stop && curr.line !== \"\" && !isWhiteSpaceString(curr.line[curr.pos])) {\n            return { ln: curr.ln, pos: curr.pos, };\n          }\n          else if (isEndOfSentenceSymbol(curr.line[curr.pos])\n            && !stop\n            && (curr.pos === curr.line.length - 1\n              || isWhiteSpaceString(curr.line[curr.pos + 1]))) {\n            stop = true;\n          }\n\n          nextChar(cm, curr);\n        }\n\n        /*\n          Set the position to the last non whitespace character on the last\n          valid line in the case that we reach the end of the document.\n        */\n        var line = cm.getLine(last_valid.ln);\n        last_valid.pos = 0;\n        for(var i = line.length - 1; i >= 0; --i) {\n          if (!isWhiteSpaceString(line[i])) {\n            last_valid.pos = i;\n            break;\n          }\n        }\n\n        return last_valid;\n\n      }\n\n      /*\n        Performs one iteration of traversal in reverse direction\n        Returns an index object of the new location\n       */\n      function reverse(cm, ln, pos, dir) {\n        var line = cm.getLine(ln);\n\n        var curr = {\n          line: line,\n          ln: ln,\n          pos: pos,\n          dir: dir,\n        }\n\n        var last_valid = {\n          ln: curr.ln,\n          pos: null,\n        };\n\n        var skip_empty_lines = (curr.line === \"\");\n\n        // Move one step to skip character we start on\n        nextChar(cm, curr);\n\n        while (curr.line !== null) {\n\n          if (curr.line === \"\" && !skip_empty_lines) {\n            if (last_valid.pos !== null) {\n              return last_valid;\n            }\n            else {\n              return { ln: curr.ln, pos: curr.pos };\n            }\n          }\n          else if (isEndOfSentenceSymbol(curr.line[curr.pos])\n              && last_valid.pos !== null\n              && !(curr.ln === last_valid.ln && curr.pos + 1 === last_valid.pos)) {\n            return last_valid;\n          }\n          else if (curr.line !== \"\" && !isWhiteSpaceString(curr.line[curr.pos])) {\n            skip_empty_lines = false;\n            last_valid = { ln: curr.ln, pos: curr.pos }\n          }\n\n          nextChar(cm, curr);\n        }\n\n        /*\n          Set the position to the first non whitespace character on the last\n          valid line in the case that we reach the beginning of the document.\n        */\n        var line = cm.getLine(last_valid.ln);\n        last_valid.pos = 0;\n        for(var i = 0; i < line.length; ++i) {\n          if (!isWhiteSpaceString(line[i])) {\n            last_valid.pos = i;\n            break;\n          }\n        }\n        return last_valid;\n      }\n\n      var curr_index = {\n        ln: cur.line,\n        pos: cur.ch,\n      };\n\n      while (repeat > 0) {\n        if (dir < 0) {\n          curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);\n        }\n        else {\n          curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);\n        }\n        repeat--;\n      }\n\n      return Pos(curr_index.ln, curr_index.pos);\n    }\n\n    // TODO: perhaps this finagling of start and end positions belonds\n    // in codemirror/replaceRange?\n    function selectCompanionObject(cm, head, symb, inclusive) {\n      var cur = head, start, end;\n\n      var bracketRegexp = ({\n        '(': /[()]/, ')': /[()]/,\n        '[': /[[\\]]/, ']': /[[\\]]/,\n        '{': /[{}]/, '}': /[{}]/,\n        '<': /[<>]/, '>': /[<>]/})[symb];\n      var openSym = ({\n        '(': '(', ')': '(',\n        '[': '[', ']': '[',\n        '{': '{', '}': '{',\n        '<': '<', '>': '<'})[symb];\n      var curChar = cm.getLine(cur.line).charAt(cur.ch);\n      // Due to the behavior of scanForBracket, we need to add an offset if the\n      // cursor is on a matching open bracket.\n      var offset = curChar === openSym ? 1 : 0;\n\n      start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, undefined, {'bracketRegex': bracketRegexp});\n      end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, undefined, {'bracketRegex': bracketRegexp});\n\n      if (!start || !end) {\n        return { start: cur, end: cur };\n      }\n\n      start = start.pos;\n      end = end.pos;\n\n      if ((start.line == end.line && start.ch > end.ch)\n          || (start.line > end.line)) {\n        var tmp = start;\n        start = end;\n        end = tmp;\n      }\n\n      if (inclusive) {\n        end.ch += 1;\n      } else {\n        start.ch += 1;\n      }\n\n      return { start: start, end: end };\n    }\n\n    // Takes in a symbol and a cursor and tries to simulate text objects that\n    // have identical opening and closing symbols\n    // TODO support across multiple lines\n    function findBeginningAndEnd(cm, head, symb, inclusive) {\n      var cur = copyCursor(head);\n      var line = cm.getLine(cur.line);\n      var chars = line.split('');\n      var start, end, i, len;\n      var firstIndex = chars.indexOf(symb);\n\n      // the decision tree is to always look backwards for the beginning first,\n      // but if the cursor is in front of the first instance of the symb,\n      // then move the cursor forward\n      if (cur.ch < firstIndex) {\n        cur.ch = firstIndex;\n        // Why is this line even here???\n        // cm.setCursor(cur.line, firstIndex+1);\n      }\n      // otherwise if the cursor is currently on the closing symbol\n      else if (firstIndex < cur.ch && chars[cur.ch] == symb) {\n        end = cur.ch; // assign end to the current cursor\n        --cur.ch; // make sure to look backwards\n      }\n\n      // if we're currently on the symbol, we've got a start\n      if (chars[cur.ch] == symb && !end) {\n        start = cur.ch + 1; // assign start to ahead of the cursor\n      } else {\n        // go backwards to find the start\n        for (i = cur.ch; i > -1 && !start; i--) {\n          if (chars[i] == symb) {\n            start = i + 1;\n          }\n        }\n      }\n\n      // look forwards for the end symbol\n      if (start && !end) {\n        for (i = start, len = chars.length; i < len && !end; i++) {\n          if (chars[i] == symb) {\n            end = i;\n          }\n        }\n      }\n\n      // nothing found\n      if (!start || !end) {\n        return { start: cur, end: cur };\n      }\n\n      // include the symbols\n      if (inclusive) {\n        --start; ++end;\n      }\n\n      return {\n        start: Pos(cur.line, start),\n        end: Pos(cur.line, end)\n      };\n    }\n\n    // Search functions\n    defineOption('pcre', true, 'boolean');\n    function SearchState() {}\n    SearchState.prototype = {\n      getQuery: function() {\n        return vimGlobalState.query;\n      },\n      setQuery: function(query) {\n        vimGlobalState.query = query;\n      },\n      getOverlay: function() {\n        return this.searchOverlay;\n      },\n      setOverlay: function(overlay) {\n        this.searchOverlay = overlay;\n      },\n      isReversed: function() {\n        return vimGlobalState.isReversed;\n      },\n      setReversed: function(reversed) {\n        vimGlobalState.isReversed = reversed;\n      },\n      getScrollbarAnnotate: function() {\n        return this.annotate;\n      },\n      setScrollbarAnnotate: function(annotate) {\n        this.annotate = annotate;\n      }\n    };\n    function getSearchState(cm) {\n      var vim = cm.state.vim;\n      return vim.searchState_ || (vim.searchState_ = new SearchState());\n    }\n    function dialog(cm, template, shortText, onClose, options) {\n      if (cm.openDialog) {\n        cm.openDialog(template, onClose, { bottom: true, value: options.value,\n            onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,\n            selectValueOnOpen: false});\n      }\n      else {\n        onClose(prompt(shortText, ''));\n      }\n    }\n    function splitBySlash(argString) {\n      return splitBySeparator(argString, '/');\n    }\n\n    function findUnescapedSlashes(argString) {\n      return findUnescapedSeparators(argString, '/');\n    }\n\n    function splitBySeparator(argString, separator) {\n      var slashes = findUnescapedSeparators(argString, separator) || [];\n      if (!slashes.length) return [];\n      var tokens = [];\n      // in case of strings like foo/bar\n      if (slashes[0] !== 0) return;\n      for (var i = 0; i < slashes.length; i++) {\n        if (typeof slashes[i] == 'number')\n          tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));\n      }\n      return tokens;\n    }\n\n    function findUnescapedSeparators(str, separator) {\n      if (!separator)\n        separator = '/';\n\n      var escapeNextChar = false;\n      var slashes = [];\n      for (var i = 0; i < str.length; i++) {\n        var c = str.charAt(i);\n        if (!escapeNextChar && c == separator) {\n          slashes.push(i);\n        }\n        escapeNextChar = !escapeNextChar && (c == '\\\\');\n      }\n      return slashes;\n    }\n\n    // Translates a search string from ex (vim) syntax into javascript form.\n    function translateRegex(str) {\n      // When these match, add a '\\' if unescaped or remove one if escaped.\n      var specials = '|(){';\n      // Remove, but never add, a '\\' for these.\n      var unescape = '}';\n      var escapeNextChar = false;\n      var out = [];\n      for (var i = -1; i < str.length; i++) {\n        var c = str.charAt(i) || '';\n        var n = str.charAt(i+1) || '';\n        var specialComesNext = (n && specials.indexOf(n) != -1);\n        if (escapeNextChar) {\n          if (c !== '\\\\' || !specialComesNext) {\n            out.push(c);\n          }\n          escapeNextChar = false;\n        } else {\n          if (c === '\\\\') {\n            escapeNextChar = true;\n            // Treat the unescape list as special for removing, but not adding '\\'.\n            if (n && unescape.indexOf(n) != -1) {\n              specialComesNext = true;\n            }\n            // Not passing this test means removing a '\\'.\n            if (!specialComesNext || n === '\\\\') {\n              out.push(c);\n            }\n          } else {\n            out.push(c);\n            if (specialComesNext && n !== '\\\\') {\n              out.push('\\\\');\n            }\n          }\n        }\n      }\n      return out.join('');\n    }\n\n    // Translates the replace part of a search and replace from ex (vim) syntax into\n    // javascript form.  Similar to translateRegex, but additionally fixes back references\n    // (translates '\\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.\n    var charUnescapes = {'\\\\n': '\\n', '\\\\r': '\\r', '\\\\t': '\\t'};\n    function translateRegexReplace(str) {\n      var escapeNextChar = false;\n      var out = [];\n      for (var i = -1; i < str.length; i++) {\n        var c = str.charAt(i) || '';\n        var n = str.charAt(i+1) || '';\n        if (charUnescapes[c + n]) {\n          out.push(charUnescapes[c+n]);\n          i++;\n        } else if (escapeNextChar) {\n          // At any point in the loop, escapeNextChar is true if the previous\n          // character was a '\\' and was not escaped.\n          out.push(c);\n          escapeNextChar = false;\n        } else {\n          if (c === '\\\\') {\n            escapeNextChar = true;\n            if ((isNumber(n) || n === '$')) {\n              out.push('$');\n            } else if (n !== '/' && n !== '\\\\') {\n              out.push('\\\\');\n            }\n          } else {\n            if (c === '$') {\n              out.push('$');\n            }\n            out.push(c);\n            if (n === '/') {\n              out.push('\\\\');\n            }\n          }\n        }\n      }\n      return out.join('');\n    }\n\n    // Unescape \\ and / in the replace part, for PCRE mode.\n    var unescapes = {'\\\\/': '/', '\\\\\\\\': '\\\\', '\\\\n': '\\n', '\\\\r': '\\r', '\\\\t': '\\t'};\n    function unescapeRegexReplace(str) {\n      var stream = new CodeMirror.StringStream(str);\n      var output = [];\n      while (!stream.eol()) {\n        // Search for \\.\n        while (stream.peek() && stream.peek() != '\\\\') {\n          output.push(stream.next());\n        }\n        var matched = false;\n        for (var matcher in unescapes) {\n          if (stream.match(matcher, true)) {\n            matched = true;\n            output.push(unescapes[matcher]);\n            break;\n          }\n        }\n        if (!matched) {\n          // Don't change anything\n          output.push(stream.next());\n        }\n      }\n      return output.join('');\n    }\n\n    /**\n     * Extract the regular expression from the query and return a Regexp object.\n     * Returns null if the query is blank.\n     * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.\n     * If smartCase is passed in, and the query contains upper case letters,\n     *   then ignoreCase is overridden, and the 'i' flag will not be set.\n     * If the query contains the /i in the flag part of the regular expression,\n     *   then both ignoreCase and smartCase are ignored, and 'i' will be passed\n     *   through to the Regex object.\n     */\n    function parseQuery(query, ignoreCase, smartCase) {\n      // First update the last search register\n      var lastSearchRegister = vimGlobalState.registerController.getRegister('/');\n      lastSearchRegister.setText(query);\n      // Check if the query is already a regex.\n      if (query instanceof RegExp) { return query; }\n      // First try to extract regex + flags from the input. If no flags found,\n      // extract just the regex. IE does not accept flags directly defined in\n      // the regex string in the form /regex/flags\n      var slashes = findUnescapedSlashes(query);\n      var regexPart;\n      var forceIgnoreCase;\n      if (!slashes.length) {\n        // Query looks like 'regexp'\n        regexPart = query;\n      } else {\n        // Query looks like 'regexp/...'\n        regexPart = query.substring(0, slashes[0]);\n        var flagsPart = query.substring(slashes[0]);\n        forceIgnoreCase = (flagsPart.indexOf('i') != -1);\n      }\n      if (!regexPart) {\n        return null;\n      }\n      if (!getOption('pcre')) {\n        regexPart = translateRegex(regexPart);\n      }\n      if (smartCase) {\n        ignoreCase = (/^[^A-Z]*$/).test(regexPart);\n      }\n      var regexp = new RegExp(regexPart,\n          (ignoreCase || forceIgnoreCase) ? 'i' : undefined);\n      return regexp;\n    }\n    function showConfirm(cm, text) {\n      if (cm.openNotification) {\n        cm.openNotification('<span style=\"color: red\">' + text + '</span>',\n                            {bottom: true, duration: 5000});\n      } else {\n        alert(text);\n      }\n    }\n    function makePrompt(prefix, desc) {\n      var raw = '<span style=\"font-family: monospace; white-space: pre\">' +\n          (prefix || \"\") + '<input type=\"text\"></span>';\n      if (desc)\n        raw += ' <span style=\"color: #888\">' + desc + '</span>';\n      return raw;\n    }\n    var searchPromptDesc = '(Javascript regexp)';\n    function showPrompt(cm, options) {\n      var shortText = (options.prefix || '') + ' ' + (options.desc || '');\n      var prompt = makePrompt(options.prefix, options.desc);\n      dialog(cm, prompt, shortText, options.onClose, options);\n    }\n    function regexEqual(r1, r2) {\n      if (r1 instanceof RegExp && r2 instanceof RegExp) {\n          var props = ['global', 'multiline', 'ignoreCase', 'source'];\n          for (var i = 0; i < props.length; i++) {\n              var prop = props[i];\n              if (r1[prop] !== r2[prop]) {\n                  return false;\n              }\n          }\n          return true;\n      }\n      return false;\n    }\n    // Returns true if the query is valid.\n    function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {\n      if (!rawQuery) {\n        return;\n      }\n      var state = getSearchState(cm);\n      var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);\n      if (!query) {\n        return;\n      }\n      highlightSearchMatches(cm, query);\n      if (regexEqual(query, state.getQuery())) {\n        return query;\n      }\n      state.setQuery(query);\n      return query;\n    }\n    function searchOverlay(query) {\n      if (query.source.charAt(0) == '^') {\n        var matchSol = true;\n      }\n      return {\n        token: function(stream) {\n          if (matchSol && !stream.sol()) {\n            stream.skipToEnd();\n            return;\n          }\n          var match = stream.match(query, false);\n          if (match) {\n            if (match[0].length == 0) {\n              // Matched empty string, skip to next.\n              stream.next();\n              return 'searching';\n            }\n            if (!stream.sol()) {\n              // Backtrack 1 to match \\b\n              stream.backUp(1);\n              if (!query.exec(stream.next() + match[0])) {\n                stream.next();\n                return null;\n              }\n            }\n            stream.match(query);\n            return 'searching';\n          }\n          while (!stream.eol()) {\n            stream.next();\n            if (stream.match(query, false)) break;\n          }\n        },\n        query: query\n      };\n    }\n    function highlightSearchMatches(cm, query) {\n      var searchState = getSearchState(cm);\n      var overlay = searchState.getOverlay();\n      if (!overlay || query != overlay.query) {\n        if (overlay) {\n          cm.removeOverlay(overlay);\n        }\n        overlay = searchOverlay(query);\n        cm.addOverlay(overlay);\n        if (cm.showMatchesOnScrollbar) {\n          if (searchState.getScrollbarAnnotate()) {\n            searchState.getScrollbarAnnotate().clear();\n          }\n          searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));\n        }\n        searchState.setOverlay(overlay);\n      }\n    }\n    function findNext(cm, prev, query, repeat) {\n      if (repeat === undefined) { repeat = 1; }\n      return cm.operation(function() {\n        var pos = cm.getCursor();\n        var cursor = cm.getSearchCursor(query, pos);\n        for (var i = 0; i < repeat; i++) {\n          var found = cursor.find(prev);\n          if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }\n          if (!found) {\n            // SearchCursor may have returned null because it hit EOF, wrap\n            // around and try again.\n            cursor = cm.getSearchCursor(query,\n                (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );\n            if (!cursor.find(prev)) {\n              return;\n            }\n          }\n        }\n        return cursor.from();\n      });\n    }\n    function clearSearchHighlight(cm) {\n      var state = getSearchState(cm);\n      cm.removeOverlay(getSearchState(cm).getOverlay());\n      state.setOverlay(null);\n      if (state.getScrollbarAnnotate()) {\n        state.getScrollbarAnnotate().clear();\n        state.setScrollbarAnnotate(null);\n      }\n    }\n    /**\n     * Check if pos is in the specified range, INCLUSIVE.\n     * Range can be specified with 1 or 2 arguments.\n     * If the first range argument is an array, treat it as an array of line\n     * numbers. Match pos against any of the lines.\n     * If the first range argument is a number,\n     *   if there is only 1 range argument, check if pos has the same line\n     *       number\n     *   if there are 2 range arguments, then check if pos is in between the two\n     *       range arguments.\n     */\n    function isInRange(pos, start, end) {\n      if (typeof pos != 'number') {\n        // Assume it is a cursor position. Get the line number.\n        pos = pos.line;\n      }\n      if (start instanceof Array) {\n        return inArray(pos, start);\n      } else {\n        if (end) {\n          return (pos >= start && pos <= end);\n        } else {\n          return pos == start;\n        }\n      }\n    }\n    function getUserVisibleLines(cm) {\n      var scrollInfo = cm.getScrollInfo();\n      var occludeToleranceTop = 6;\n      var occludeToleranceBottom = 10;\n      var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');\n      var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;\n      var to = cm.coordsChar({left:0, top: bottomY}, 'local');\n      return {top: from.line, bottom: to.line};\n    }\n\n    function getMarkPos(cm, vim, markName) {\n      if (markName == '\\'') {\n        var history = cm.doc.history.done;\n        var event = history[history.length - 2];\n        return event && event.ranges && event.ranges[0].head;\n      } else if (markName == '.') {\n        if (cm.doc.history.lastModTime == 0) {\n          return  // If no changes, bail out; don't bother to copy or reverse history array.\n        } else {\n          var changeHistory = cm.doc.history.done.filter(function(el){ if (el.changes !== undefined) { return el } });\n          changeHistory.reverse();\n          var lastEditPos = changeHistory[0].changes[0].to;\n        }\n        return lastEditPos;\n      }\n\n      var mark = vim.marks[markName];\n      return mark && mark.find();\n    }\n\n    var ExCommandDispatcher = function() {\n      this.buildCommandMap_();\n    };\n    ExCommandDispatcher.prototype = {\n      processCommand: function(cm, input, opt_params) {\n        var that = this;\n        cm.operation(function () {\n          cm.curOp.isVimOp = true;\n          that._processCommand(cm, input, opt_params);\n        });\n      },\n      _processCommand: function(cm, input, opt_params) {\n        var vim = cm.state.vim;\n        var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');\n        var previousCommand = commandHistoryRegister.toString();\n        if (vim.visualMode) {\n          exitVisualMode(cm);\n        }\n        var inputStream = new CodeMirror.StringStream(input);\n        // update \": with the latest command whether valid or invalid\n        commandHistoryRegister.setText(input);\n        var params = opt_params || {};\n        params.input = input;\n        try {\n          this.parseInput_(cm, inputStream, params);\n        } catch(e) {\n          showConfirm(cm, e);\n          throw e;\n        }\n        var command;\n        var commandName;\n        if (!params.commandName) {\n          // If only a line range is defined, move to the line.\n          if (params.line !== undefined) {\n            commandName = 'move';\n          }\n        } else {\n          command = this.matchCommand_(params.commandName);\n          if (command) {\n            commandName = command.name;\n            if (command.excludeFromCommandHistory) {\n              commandHistoryRegister.setText(previousCommand);\n            }\n            this.parseCommandArgs_(inputStream, params, command);\n            if (command.type == 'exToKey') {\n              // Handle Ex to Key mapping.\n              for (var i = 0; i < command.toKeys.length; i++) {\n                CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');\n              }\n              return;\n            } else if (command.type == 'exToEx') {\n              // Handle Ex to Ex mapping.\n              this.processCommand(cm, command.toInput);\n              return;\n            }\n          }\n        }\n        if (!commandName) {\n          showConfirm(cm, 'Not an editor command \":' + input + '\"');\n          return;\n        }\n        try {\n          exCommands[commandName](cm, params);\n          // Possibly asynchronous commands (e.g. substitute, which might have a\n          // user confirmation), are responsible for calling the callback when\n          // done. All others have it taken care of for them here.\n          if ((!command || !command.possiblyAsync) && params.callback) {\n            params.callback();\n          }\n        } catch(e) {\n          showConfirm(cm, e);\n          throw e;\n        }\n      },\n      parseInput_: function(cm, inputStream, result) {\n        inputStream.eatWhile(':');\n        // Parse range.\n        if (inputStream.eat('%')) {\n          result.line = cm.firstLine();\n          result.lineEnd = cm.lastLine();\n        } else {\n          result.line = this.parseLineSpec_(cm, inputStream);\n          if (result.line !== undefined && inputStream.eat(',')) {\n            result.lineEnd = this.parseLineSpec_(cm, inputStream);\n          }\n        }\n\n        // Parse command name.\n        var commandMatch = inputStream.match(/^(\\w+)/);\n        if (commandMatch) {\n          result.commandName = commandMatch[1];\n        } else {\n          result.commandName = inputStream.match(/.*/)[0];\n        }\n\n        return result;\n      },\n      parseLineSpec_: function(cm, inputStream) {\n        var numberMatch = inputStream.match(/^(\\d+)/);\n        if (numberMatch) {\n          // Absolute line number plus offset (N+M or N-M) is probably a typo,\n          // not something the user actually wanted. (NB: vim does allow this.)\n          return parseInt(numberMatch[1], 10) - 1;\n        }\n        switch (inputStream.next()) {\n          case '.':\n            return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);\n          case '$':\n            return this.parseLineSpecOffset_(inputStream, cm.lastLine());\n          case '\\'':\n            var markName = inputStream.next();\n            var markPos = getMarkPos(cm, cm.state.vim, markName);\n            if (!markPos) throw new Error('Mark not set');\n            return this.parseLineSpecOffset_(inputStream, markPos.line);\n          case '-':\n          case '+':\n            inputStream.backUp(1);\n            // Offset is relative to current line if not otherwise specified.\n            return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);\n          default:\n            inputStream.backUp(1);\n            return undefined;\n        }\n      },\n      parseLineSpecOffset_: function(inputStream, line) {\n        var offsetMatch = inputStream.match(/^([+-])?(\\d+)/);\n        if (offsetMatch) {\n          var offset = parseInt(offsetMatch[2], 10);\n          if (offsetMatch[1] == \"-\") {\n            line -= offset;\n          } else {\n            line += offset;\n          }\n        }\n        return line;\n      },\n      parseCommandArgs_: function(inputStream, params, command) {\n        if (inputStream.eol()) {\n          return;\n        }\n        params.argString = inputStream.match(/.*/)[0];\n        // Parse command-line arguments\n        var delim = command.argDelimiter || /\\s+/;\n        var args = trim(params.argString).split(delim);\n        if (args.length && args[0]) {\n          params.args = args;\n        }\n      },\n      matchCommand_: function(commandName) {\n        // Return the command in the command map that matches the shortest\n        // prefix of the passed in command name. The match is guaranteed to be\n        // unambiguous if the defaultExCommandMap's shortNames are set up\n        // correctly. (see @code{defaultExCommandMap}).\n        for (var i = commandName.length; i > 0; i--) {\n          var prefix = commandName.substring(0, i);\n          if (this.commandMap_[prefix]) {\n            var command = this.commandMap_[prefix];\n            if (command.name.indexOf(commandName) === 0) {\n              return command;\n            }\n          }\n        }\n        return null;\n      },\n      buildCommandMap_: function() {\n        this.commandMap_ = {};\n        for (var i = 0; i < defaultExCommandMap.length; i++) {\n          var command = defaultExCommandMap[i];\n          var key = command.shortName || command.name;\n          this.commandMap_[key] = command;\n        }\n      },\n      map: function(lhs, rhs, ctx) {\n        if (lhs != ':' && lhs.charAt(0) == ':') {\n          if (ctx) { throw Error('Mode not supported for ex mappings'); }\n          var commandName = lhs.substring(1);\n          if (rhs != ':' && rhs.charAt(0) == ':') {\n            // Ex to Ex mapping\n            this.commandMap_[commandName] = {\n              name: commandName,\n              type: 'exToEx',\n              toInput: rhs.substring(1),\n              user: true\n            };\n          } else {\n            // Ex to key mapping\n            this.commandMap_[commandName] = {\n              name: commandName,\n              type: 'exToKey',\n              toKeys: rhs,\n              user: true\n            };\n          }\n        } else {\n          if (rhs != ':' && rhs.charAt(0) == ':') {\n            // Key to Ex mapping.\n            var mapping = {\n              keys: lhs,\n              type: 'keyToEx',\n              exArgs: { input: rhs.substring(1) }\n            };\n            if (ctx) { mapping.context = ctx; }\n            defaultKeymap.unshift(mapping);\n          } else {\n            // Key to key mapping\n            var mapping = {\n              keys: lhs,\n              type: 'keyToKey',\n              toKeys: rhs\n            };\n            if (ctx) { mapping.context = ctx; }\n            defaultKeymap.unshift(mapping);\n          }\n        }\n      },\n      unmap: function(lhs, ctx) {\n        if (lhs != ':' && lhs.charAt(0) == ':') {\n          // Ex to Ex or Ex to key mapping\n          if (ctx) { throw Error('Mode not supported for ex mappings'); }\n          var commandName = lhs.substring(1);\n          if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {\n            delete this.commandMap_[commandName];\n            return;\n          }\n        } else {\n          // Key to Ex or key to key mapping\n          var keys = lhs;\n          for (var i = 0; i < defaultKeymap.length; i++) {\n            if (keys == defaultKeymap[i].keys\n                && defaultKeymap[i].context === ctx) {\n              defaultKeymap.splice(i, 1);\n              return;\n            }\n          }\n        }\n        throw Error('No such mapping.');\n      }\n    };\n\n    var exCommands = {\n      colorscheme: function(cm, params) {\n        if (!params.args || params.args.length < 1) {\n          showConfirm(cm, cm.getOption('theme'));\n          return;\n        }\n        cm.setOption('theme', params.args[0]);\n      },\n      map: function(cm, params, ctx) {\n        var mapArgs = params.args;\n        if (!mapArgs || mapArgs.length < 2) {\n          if (cm) {\n            showConfirm(cm, 'Invalid mapping: ' + params.input);\n          }\n          return;\n        }\n        exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);\n      },\n      imap: function(cm, params) { this.map(cm, params, 'insert'); },\n      nmap: function(cm, params) { this.map(cm, params, 'normal'); },\n      vmap: function(cm, params) { this.map(cm, params, 'visual'); },\n      unmap: function(cm, params, ctx) {\n        var mapArgs = params.args;\n        if (!mapArgs || mapArgs.length < 1) {\n          if (cm) {\n            showConfirm(cm, 'No such mapping: ' + params.input);\n          }\n          return;\n        }\n        exCommandDispatcher.unmap(mapArgs[0], ctx);\n      },\n      move: function(cm, params) {\n        commandDispatcher.processCommand(cm, cm.state.vim, {\n            type: 'motion',\n            motion: 'moveToLineOrEdgeOfDocument',\n            motionArgs: { forward: false, explicitRepeat: true,\n              linewise: true },\n            repeatOverride: params.line+1});\n      },\n      set: function(cm, params) {\n        var setArgs = params.args;\n        // Options passed through to the setOption/getOption calls. May be passed in by the\n        // local/global versions of the set command\n        var setCfg = params.setCfg || {};\n        if (!setArgs || setArgs.length < 1) {\n          if (cm) {\n            showConfirm(cm, 'Invalid mapping: ' + params.input);\n          }\n          return;\n        }\n        var expr = setArgs[0].split('=');\n        var optionName = expr[0];\n        var value = expr[1];\n        var forceGet = false;\n\n        if (optionName.charAt(optionName.length - 1) == '?') {\n          // If post-fixed with ?, then the set is actually a get.\n          if (value) { throw Error('Trailing characters: ' + params.argString); }\n          optionName = optionName.substring(0, optionName.length - 1);\n          forceGet = true;\n        }\n        if (value === undefined && optionName.substring(0, 2) == 'no') {\n          // To set boolean options to false, the option name is prefixed with\n          // 'no'.\n          optionName = optionName.substring(2);\n          value = false;\n        }\n\n        var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';\n        if (optionIsBoolean && value == undefined) {\n          // Calling set with a boolean option sets it to true.\n          value = true;\n        }\n        // If no value is provided, then we assume this is a get.\n        if (!optionIsBoolean && value === undefined || forceGet) {\n          var oldValue = getOption(optionName, cm, setCfg);\n          if (oldValue instanceof Error) {\n            showConfirm(cm, oldValue.message);\n          } else if (oldValue === true || oldValue === false) {\n            showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);\n          } else {\n            showConfirm(cm, '  ' + optionName + '=' + oldValue);\n          }\n        } else {\n          var setOptionReturn = setOption(optionName, value, cm, setCfg);\n          if (setOptionReturn instanceof Error) {\n            showConfirm(cm, setOptionReturn.message);\n          }\n        }\n      },\n      setlocal: function (cm, params) {\n        // setCfg is passed through to setOption\n        params.setCfg = {scope: 'local'};\n        this.set(cm, params);\n      },\n      setglobal: function (cm, params) {\n        // setCfg is passed through to setOption\n        params.setCfg = {scope: 'global'};\n        this.set(cm, params);\n      },\n      registers: function(cm, params) {\n        var regArgs = params.args;\n        var registers = vimGlobalState.registerController.registers;\n        var regInfo = '----------Registers----------<br><br>';\n        if (!regArgs) {\n          for (var registerName in registers) {\n            var text = registers[registerName].toString();\n            if (text.length) {\n              regInfo += '\"' + registerName + '    ' + text + '<br>';\n            }\n          }\n        } else {\n          var registerName;\n          regArgs = regArgs.join('');\n          for (var i = 0; i < regArgs.length; i++) {\n            registerName = regArgs.charAt(i);\n            if (!vimGlobalState.registerController.isValidRegister(registerName)) {\n              continue;\n            }\n            var register = registers[registerName] || new Register();\n            regInfo += '\"' + registerName + '    ' + register.toString() + '<br>';\n          }\n        }\n        showConfirm(cm, regInfo);\n      },\n      sort: function(cm, params) {\n        var reverse, ignoreCase, unique, number, pattern;\n        function parseArgs() {\n          if (params.argString) {\n            var args = new CodeMirror.StringStream(params.argString);\n            if (args.eat('!')) { reverse = true; }\n            if (args.eol()) { return; }\n            if (!args.eatSpace()) { return 'Invalid arguments'; }\n            var opts = args.match(/([dinuox]+)?\\s*(\\/.+\\/)?\\s*/);\n            if (!opts && !args.eol()) { return 'Invalid arguments'; }\n            if (opts[1]) {\n              ignoreCase = opts[1].indexOf('i') != -1;\n              unique = opts[1].indexOf('u') != -1;\n              var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1 && 1;\n              var hex = opts[1].indexOf('x') != -1 && 1;\n              var octal = opts[1].indexOf('o') != -1 && 1;\n              if (decimal + hex + octal > 1) { return 'Invalid arguments'; }\n              number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';\n            }\n            if (opts[2]) {\n              pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : '');\n            }\n          }\n        }\n        var err = parseArgs();\n        if (err) {\n          showConfirm(cm, err + ': ' + params.argString);\n          return;\n        }\n        var lineStart = params.line || cm.firstLine();\n        var lineEnd = params.lineEnd || params.line || cm.lastLine();\n        if (lineStart == lineEnd) { return; }\n        var curStart = Pos(lineStart, 0);\n        var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));\n        var text = cm.getRange(curStart, curEnd).split('\\n');\n        var numberRegex = pattern ? pattern :\n           (number == 'decimal') ? /(-?)([\\d]+)/ :\n           (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :\n           (number == 'octal') ? /([0-7]+)/ : null;\n        var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;\n        var numPart = [], textPart = [];\n        if (number || pattern) {\n          for (var i = 0; i < text.length; i++) {\n            var matchPart = pattern ? text[i].match(pattern) : null;\n            if (matchPart && matchPart[0] != '') {\n              numPart.push(matchPart);\n            } else if (!pattern && numberRegex.exec(text[i])) {\n              numPart.push(text[i]);\n            } else {\n              textPart.push(text[i]);\n            }\n          }\n        } else {\n          textPart = text;\n        }\n        function compareFn(a, b) {\n          if (reverse) { var tmp; tmp = a; a = b; b = tmp; }\n          if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }\n          var anum = number && numberRegex.exec(a);\n          var bnum = number && numberRegex.exec(b);\n          if (!anum) { return a < b ? -1 : 1; }\n          anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);\n          bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);\n          return anum - bnum;\n        }\n        function comparePatternFn(a, b) {\n          if (reverse) { var tmp; tmp = a; a = b; b = tmp; }\n          if (ignoreCase) { a[0] = a[0].toLowerCase(); b[0] = b[0].toLowerCase(); }\n          return (a[0] < b[0]) ? -1 : 1;\n        }\n        numPart.sort(pattern ? comparePatternFn : compareFn);\n        if (pattern) {\n          for (var i = 0; i < numPart.length; i++) {\n            numPart[i] = numPart[i].input;\n          }\n        } else if (!number) { textPart.sort(compareFn); }\n        text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);\n        if (unique) { // Remove duplicate lines\n          var textOld = text;\n          var lastLine;\n          text = [];\n          for (var i = 0; i < textOld.length; i++) {\n            if (textOld[i] != lastLine) {\n              text.push(textOld[i]);\n            }\n            lastLine = textOld[i];\n          }\n        }\n        cm.replaceRange(text.join('\\n'), curStart, curEnd);\n      },\n      global: function(cm, params) {\n        // a global command is of the form\n        // :[range]g/pattern/[cmd]\n        // argString holds the string /pattern/[cmd]\n        var argString = params.argString;\n        if (!argString) {\n          showConfirm(cm, 'Regular Expression missing from global');\n          return;\n        }\n        // range is specified here\n        var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();\n        var lineEnd = params.lineEnd || params.line || cm.lastLine();\n        // get the tokens from argString\n        var tokens = splitBySlash(argString);\n        var regexPart = argString, cmd;\n        if (tokens.length) {\n          regexPart = tokens[0];\n          cmd = tokens.slice(1, tokens.length).join('/');\n        }\n        if (regexPart) {\n          // If regex part is empty, then use the previous query. Otherwise\n          // use the regex part as the new query.\n          try {\n           updateSearchQuery(cm, regexPart, true /** ignoreCase */,\n             true /** smartCase */);\n          } catch (e) {\n           showConfirm(cm, 'Invalid regex: ' + regexPart);\n           return;\n          }\n        }\n        // now that we have the regexPart, search for regex matches in the\n        // specified range of lines\n        var query = getSearchState(cm).getQuery();\n        var matchedLines = [], content = '';\n        for (var i = lineStart; i <= lineEnd; i++) {\n          var matched = query.test(cm.getLine(i));\n          if (matched) {\n            matchedLines.push(i+1);\n            content+= cm.getLine(i) + '<br>';\n          }\n        }\n        // if there is no [cmd], just display the list of matched lines\n        if (!cmd) {\n          showConfirm(cm, content);\n          return;\n        }\n        var index = 0;\n        var nextCommand = function() {\n          if (index < matchedLines.length) {\n            var command = matchedLines[index] + cmd;\n            exCommandDispatcher.processCommand(cm, command, {\n              callback: nextCommand\n            });\n          }\n          index++;\n        };\n        nextCommand();\n      },\n      substitute: function(cm, params) {\n        if (!cm.getSearchCursor) {\n          throw new Error('Search feature not available. Requires searchcursor.js or ' +\n              'any other getSearchCursor implementation.');\n        }\n        var argString = params.argString;\n        var tokens = argString ? splitBySeparator(argString, argString[0]) : [];\n        var regexPart, replacePart = '', trailing, flagsPart, count;\n        var confirm = false; // Whether to confirm each replace.\n        var global = false; // True to replace all instances on a line, false to replace only 1.\n        if (tokens.length) {\n          regexPart = tokens[0];\n          replacePart = tokens[1];\n          if (regexPart && regexPart[regexPart.length - 1] === '$') {\n            regexPart = regexPart.slice(0, regexPart.length - 1) + '\\\\n';\n            replacePart = replacePart ? replacePart + '\\n' : '\\n';\n          }\n          if (replacePart !== undefined) {\n            if (getOption('pcre')) {\n              replacePart = unescapeRegexReplace(replacePart);\n            } else {\n              replacePart = translateRegexReplace(replacePart);\n            }\n            vimGlobalState.lastSubstituteReplacePart = replacePart;\n          }\n          trailing = tokens[2] ? tokens[2].split(' ') : [];\n        } else {\n          // either the argString is empty or its of the form ' hello/world'\n          // actually splitBySlash returns a list of tokens\n          // only if the string starts with a '/'\n          if (argString && argString.length) {\n            showConfirm(cm, 'Substitutions should be of the form ' +\n                ':s/pattern/replace/');\n            return;\n          }\n        }\n        // After the 3rd slash, we can have flags followed by a space followed\n        // by count.\n        if (trailing) {\n          flagsPart = trailing[0];\n          count = parseInt(trailing[1]);\n          if (flagsPart) {\n            if (flagsPart.indexOf('c') != -1) {\n              confirm = true;\n              flagsPart.replace('c', '');\n            }\n            if (flagsPart.indexOf('g') != -1) {\n              global = true;\n              flagsPart.replace('g', '');\n            }\n            regexPart = regexPart.replace(/\\//g, \"\\\\/\") + '/' + flagsPart;\n          }\n        }\n        if (regexPart) {\n          // If regex part is empty, then use the previous query. Otherwise use\n          // the regex part as the new query.\n          try {\n            updateSearchQuery(cm, regexPart, true /** ignoreCase */,\n              true /** smartCase */);\n          } catch (e) {\n            showConfirm(cm, 'Invalid regex: ' + regexPart);\n            return;\n          }\n        }\n        replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;\n        if (replacePart === undefined) {\n          showConfirm(cm, 'No previous substitute regular expression');\n          return;\n        }\n        var state = getSearchState(cm);\n        var query = state.getQuery();\n        var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;\n        var lineEnd = params.lineEnd || lineStart;\n        if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {\n          lineEnd = Infinity;\n        }\n        if (count) {\n          lineStart = lineEnd;\n          lineEnd = lineStart + count - 1;\n        }\n        var startPos = clipCursorToContent(cm, Pos(lineStart, 0));\n        var cursor = cm.getSearchCursor(query, startPos);\n        doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);\n      },\n      redo: CodeMirror.commands.redo,\n      undo: CodeMirror.commands.undo,\n      write: function(cm) {\n        if (CodeMirror.commands.save) {\n          // If a save command is defined, call it.\n          CodeMirror.commands.save(cm);\n        } else if (cm.save) {\n          // Saves to text area if no save command is defined and cm.save() is available.\n          cm.save();\n        }\n      },\n      nohlsearch: function(cm) {\n        clearSearchHighlight(cm);\n      },\n      yank: function (cm) {\n        var cur = copyCursor(cm.getCursor());\n        var line = cur.line;\n        var lineText = cm.getLine(line);\n        vimGlobalState.registerController.pushText(\n          '0', 'yank', lineText, true, true);\n      },\n      delmarks: function(cm, params) {\n        if (!params.argString || !trim(params.argString)) {\n          showConfirm(cm, 'Argument required');\n          return;\n        }\n\n        var state = cm.state.vim;\n        var stream = new CodeMirror.StringStream(trim(params.argString));\n        while (!stream.eol()) {\n          stream.eatSpace();\n\n          // Record the streams position at the beginning of the loop for use\n          // in error messages.\n          var count = stream.pos;\n\n          if (!stream.match(/[a-zA-Z]/, false)) {\n            showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));\n            return;\n          }\n\n          var sym = stream.next();\n          // Check if this symbol is part of a range\n          if (stream.match('-', true)) {\n            // This symbol is part of a range.\n\n            // The range must terminate at an alphabetic character.\n            if (!stream.match(/[a-zA-Z]/, false)) {\n              showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));\n              return;\n            }\n\n            var startMark = sym;\n            var finishMark = stream.next();\n            // The range must terminate at an alphabetic character which\n            // shares the same case as the start of the range.\n            if (isLowerCase(startMark) && isLowerCase(finishMark) ||\n                isUpperCase(startMark) && isUpperCase(finishMark)) {\n              var start = startMark.charCodeAt(0);\n              var finish = finishMark.charCodeAt(0);\n              if (start >= finish) {\n                showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));\n                return;\n              }\n\n              // Because marks are always ASCII values, and we have\n              // determined that they are the same case, we can use\n              // their char codes to iterate through the defined range.\n              for (var j = 0; j <= finish - start; j++) {\n                var mark = String.fromCharCode(start + j);\n                delete state.marks[mark];\n              }\n            } else {\n              showConfirm(cm, 'Invalid argument: ' + startMark + '-');\n              return;\n            }\n          } else {\n            // This symbol is a valid mark, and is not part of a range.\n            delete state.marks[sym];\n          }\n        }\n      }\n    };\n\n    var exCommandDispatcher = new ExCommandDispatcher();\n\n    /**\n    * @param {CodeMirror} cm CodeMirror instance we are in.\n    * @param {boolean} confirm Whether to confirm each replace.\n    * @param {Cursor} lineStart Line to start replacing from.\n    * @param {Cursor} lineEnd Line to stop replacing at.\n    * @param {RegExp} query Query for performing matches with.\n    * @param {string} replaceWith Text to replace matches with. May contain $1,\n    *     $2, etc for replacing captured groups using Javascript replace.\n    * @param {function()} callback A callback for when the replace is done.\n    */\n    function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,\n        replaceWith, callback) {\n      // Set up all the functions.\n      cm.state.vim.exMode = true;\n      var done = false;\n      var lastPos = searchCursor.from();\n      function replaceAll() {\n        cm.operation(function() {\n          while (!done) {\n            replace();\n            next();\n          }\n          stop();\n        });\n      }\n      function replace() {\n        var text = cm.getRange(searchCursor.from(), searchCursor.to());\n        var newText = text.replace(query, replaceWith);\n        searchCursor.replace(newText);\n      }\n      function next() {\n        // The below only loops to skip over multiple occurrences on the same\n        // line when 'global' is not true.\n        while(searchCursor.findNext() &&\n              isInRange(searchCursor.from(), lineStart, lineEnd)) {\n          if (!global && lastPos && searchCursor.from().line == lastPos.line) {\n            continue;\n          }\n          cm.scrollIntoView(searchCursor.from(), 30);\n          cm.setSelection(searchCursor.from(), searchCursor.to());\n          lastPos = searchCursor.from();\n          done = false;\n          return;\n        }\n        done = true;\n      }\n      function stop(close) {\n        if (close) { close(); }\n        cm.focus();\n        if (lastPos) {\n          cm.setCursor(lastPos);\n          var vim = cm.state.vim;\n          vim.exMode = false;\n          vim.lastHPos = vim.lastHSPos = lastPos.ch;\n        }\n        if (callback) { callback(); }\n      }\n      function onPromptKeyDown(e, _value, close) {\n        // Swallow all keys.\n        CodeMirror.e_stop(e);\n        var keyName = CodeMirror.keyName(e);\n        switch (keyName) {\n          case 'Y':\n            replace(); next(); break;\n          case 'N':\n            next(); break;\n          case 'A':\n            // replaceAll contains a call to close of its own. We don't want it\n            // to fire too early or multiple times.\n            var savedCallback = callback;\n            callback = undefined;\n            cm.operation(replaceAll);\n            callback = savedCallback;\n            break;\n          case 'L':\n            replace();\n            // fall through and exit.\n          case 'Q':\n          case 'Esc':\n          case 'Ctrl-C':\n          case 'Ctrl-[':\n            stop(close);\n            break;\n        }\n        if (done) { stop(close); }\n        return true;\n      }\n\n      // Actually do replace.\n      next();\n      if (done) {\n        showConfirm(cm, 'No matches for ' + query.source);\n        return;\n      }\n      if (!confirm) {\n        replaceAll();\n        if (callback) { callback(); }\n        return;\n      }\n      showPrompt(cm, {\n        prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',\n        onKeyDown: onPromptKeyDown\n      });\n    }\n\n    CodeMirror.keyMap.vim = {\n      attach: attachVimMap,\n      detach: detachVimMap,\n      call: cmKey\n    };\n\n    function exitInsertMode(cm) {\n      var vim = cm.state.vim;\n      var macroModeState = vimGlobalState.macroModeState;\n      var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');\n      var isPlaying = macroModeState.isPlaying;\n      var lastChange = macroModeState.lastInsertModeChanges;\n      if (!isPlaying) {\n        cm.off('change', onChange);\n        CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);\n      }\n      if (!isPlaying && vim.insertModeRepeat > 1) {\n        // Perform insert mode repeat for commands like 3,a and 3,o.\n        repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,\n            true /** repeatForInsert */);\n        vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;\n      }\n      delete vim.insertModeRepeat;\n      vim.insertMode = false;\n      cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);\n      cm.setOption('keyMap', 'vim');\n      cm.setOption('disableInput', true);\n      cm.toggleOverwrite(false); // exit replace mode if we were in it.\n      // update the \". register before exiting insert mode\n      insertModeChangeRegister.setText(lastChange.changes.join(''));\n      CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"normal\"});\n      if (macroModeState.isRecording) {\n        logInsertModeChange(macroModeState);\n      }\n    }\n\n    function _mapCommand(command) {\n      defaultKeymap.unshift(command);\n    }\n\n    function mapCommand(keys, type, name, args, extra) {\n      var command = {keys: keys, type: type};\n      command[type] = name;\n      command[type + \"Args\"] = args;\n      for (var key in extra)\n        command[key] = extra[key];\n      _mapCommand(command);\n    }\n\n    // The timeout in milliseconds for the two-character ESC keymap should be\n    // adjusted according to your typing speed to prevent false positives.\n    defineOption('insertModeEscKeysTimeout', 200, 'number');\n\n    CodeMirror.keyMap['vim-insert'] = {\n      // TODO: override navigation keys so that Esc will cancel automatic\n      // indentation from o, O, i_<CR>\n      fallthrough: ['default'],\n      attach: attachVimMap,\n      detach: detachVimMap,\n      call: cmKey\n    };\n\n    CodeMirror.keyMap['vim-replace'] = {\n      'Backspace': 'goCharLeft',\n      fallthrough: ['vim-insert'],\n      attach: attachVimMap,\n      detach: detachVimMap,\n      call: cmKey\n    };\n\n    function executeMacroRegister(cm, vim, macroModeState, registerName) {\n      var register = vimGlobalState.registerController.getRegister(registerName);\n      if (registerName == ':') {\n        // Read-only register containing last Ex command.\n        if (register.keyBuffer[0]) {\n          exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);\n        }\n        macroModeState.isPlaying = false;\n        return;\n      }\n      var keyBuffer = register.keyBuffer;\n      var imc = 0;\n      macroModeState.isPlaying = true;\n      macroModeState.replaySearchQueries = register.searchQueries.slice(0);\n      for (var i = 0; i < keyBuffer.length; i++) {\n        var text = keyBuffer[i];\n        var match, key;\n        while (text) {\n          // Pull off one command key, which is either a single character\n          // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.\n          match = (/<\\w+-.+?>|<\\w+>|./).exec(text);\n          key = match[0];\n          text = text.substring(match.index + key.length);\n          CodeMirror.Vim.handleKey(cm, key, 'macro');\n          if (vim.insertMode) {\n            var changes = register.insertModeChanges[imc++].changes;\n            vimGlobalState.macroModeState.lastInsertModeChanges.changes =\n                changes;\n            repeatInsertModeChanges(cm, changes, 1);\n            exitInsertMode(cm);\n          }\n        }\n      }\n      macroModeState.isPlaying = false;\n    }\n\n    function logKey(macroModeState, key) {\n      if (macroModeState.isPlaying) { return; }\n      var registerName = macroModeState.latestRegister;\n      var register = vimGlobalState.registerController.getRegister(registerName);\n      if (register) {\n        register.pushText(key);\n      }\n    }\n\n    function logInsertModeChange(macroModeState) {\n      if (macroModeState.isPlaying) { return; }\n      var registerName = macroModeState.latestRegister;\n      var register = vimGlobalState.registerController.getRegister(registerName);\n      if (register && register.pushInsertModeChanges) {\n        register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);\n      }\n    }\n\n    function logSearchQuery(macroModeState, query) {\n      if (macroModeState.isPlaying) { return; }\n      var registerName = macroModeState.latestRegister;\n      var register = vimGlobalState.registerController.getRegister(registerName);\n      if (register && register.pushSearchQuery) {\n        register.pushSearchQuery(query);\n      }\n    }\n\n    /**\n     * Listens for changes made in insert mode.\n     * Should only be active in insert mode.\n     */\n    function onChange(cm, changeObj) {\n      var macroModeState = vimGlobalState.macroModeState;\n      var lastChange = macroModeState.lastInsertModeChanges;\n      if (!macroModeState.isPlaying) {\n        while(changeObj) {\n          lastChange.expectCursorActivityForChange = true;\n          if (lastChange.ignoreCount > 1) {\n            lastChange.ignoreCount--;\n          } else if (changeObj.origin == '+input' || changeObj.origin == 'paste'\n              || changeObj.origin === undefined /* only in testing */) {\n            var selectionCount = cm.listSelections().length;\n            if (selectionCount > 1)\n              lastChange.ignoreCount = selectionCount;\n            var text = changeObj.text.join('\\n');\n            if (lastChange.maybeReset) {\n              lastChange.changes = [];\n              lastChange.maybeReset = false;\n            }\n            if (text) {\n              if (cm.state.overwrite && !/\\n/.test(text)) {\n                lastChange.changes.push([text]);\n              } else {\n                lastChange.changes.push(text);\n              }\n            }\n          }\n          // Change objects may be chained with next.\n          changeObj = changeObj.next;\n        }\n      }\n    }\n\n    /**\n    * Listens for any kind of cursor activity on CodeMirror.\n    */\n    function onCursorActivity(cm) {\n      var vim = cm.state.vim;\n      if (vim.insertMode) {\n        // Tracking cursor activity in insert mode (for macro support).\n        var macroModeState = vimGlobalState.macroModeState;\n        if (macroModeState.isPlaying) { return; }\n        var lastChange = macroModeState.lastInsertModeChanges;\n        if (lastChange.expectCursorActivityForChange) {\n          lastChange.expectCursorActivityForChange = false;\n        } else {\n          // Cursor moved outside the context of an edit. Reset the change.\n          lastChange.maybeReset = true;\n        }\n      } else if (!cm.curOp.isVimOp) {\n        handleExternalSelection(cm, vim);\n      }\n      if (vim.visualMode) {\n        updateFakeCursor(cm);\n      }\n    }\n    function updateFakeCursor(cm) {\n      var vim = cm.state.vim;\n      var from = clipCursorToContent(cm, copyCursor(vim.sel.head));\n      var to = offsetCursor(from, 0, 1);\n      if (vim.fakeCursor) {\n        vim.fakeCursor.clear();\n      }\n      vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});\n    }\n    function handleExternalSelection(cm, vim) {\n      var anchor = cm.getCursor('anchor');\n      var head = cm.getCursor('head');\n      // Enter or exit visual mode to match mouse selection.\n      if (vim.visualMode && !cm.somethingSelected()) {\n        exitVisualMode(cm, false);\n      } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {\n        vim.visualMode = true;\n        vim.visualLine = false;\n        CodeMirror.signal(cm, \"vim-mode-change\", {mode: \"visual\"});\n      }\n      if (vim.visualMode) {\n        // Bind CodeMirror selection model to vim selection model.\n        // Mouse selections are considered visual characterwise.\n        var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;\n        var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;\n        head = offsetCursor(head, 0, headOffset);\n        anchor = offsetCursor(anchor, 0, anchorOffset);\n        vim.sel = {\n          anchor: anchor,\n          head: head\n        };\n        updateMark(cm, vim, '<', cursorMin(head, anchor));\n        updateMark(cm, vim, '>', cursorMax(head, anchor));\n      } else if (!vim.insertMode) {\n        // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.\n        vim.lastHPos = cm.getCursor().ch;\n      }\n    }\n\n    /** Wrapper for special keys pressed in insert mode */\n    function InsertModeKey(keyName) {\n      this.keyName = keyName;\n    }\n\n    /**\n    * Handles raw key down events from the text area.\n    * - Should only be active in insert mode.\n    * - For recording deletes in insert mode.\n    */\n    function onKeyEventTargetKeyDown(e) {\n      var macroModeState = vimGlobalState.macroModeState;\n      var lastChange = macroModeState.lastInsertModeChanges;\n      var keyName = CodeMirror.keyName(e);\n      if (!keyName) { return; }\n      function onKeyFound() {\n        if (lastChange.maybeReset) {\n          lastChange.changes = [];\n          lastChange.maybeReset = false;\n        }\n        lastChange.changes.push(new InsertModeKey(keyName));\n        return true;\n      }\n      if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {\n        CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);\n      }\n    }\n\n    /**\n     * Repeats the last edit, which includes exactly 1 command and at most 1\n     * insert. Operator and motion commands are read from lastEditInputState,\n     * while action commands are read from lastEditActionCommand.\n     *\n     * If repeatForInsert is true, then the function was called by\n     * exitInsertMode to repeat the insert mode changes the user just made. The\n     * corresponding enterInsertMode call was made with a count.\n     */\n    function repeatLastEdit(cm, vim, repeat, repeatForInsert) {\n      var macroModeState = vimGlobalState.macroModeState;\n      macroModeState.isPlaying = true;\n      var isAction = !!vim.lastEditActionCommand;\n      var cachedInputState = vim.inputState;\n      function repeatCommand() {\n        if (isAction) {\n          commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);\n        } else {\n          commandDispatcher.evalInput(cm, vim);\n        }\n      }\n      function repeatInsert(repeat) {\n        if (macroModeState.lastInsertModeChanges.changes.length > 0) {\n          // For some reason, repeat cw in desktop VIM does not repeat\n          // insert mode changes. Will conform to that behavior.\n          repeat = !vim.lastEditActionCommand ? 1 : repeat;\n          var changeObject = macroModeState.lastInsertModeChanges;\n          repeatInsertModeChanges(cm, changeObject.changes, repeat);\n        }\n      }\n      vim.inputState = vim.lastEditInputState;\n      if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {\n        // o and O repeat have to be interlaced with insert repeats so that the\n        // insertions appear on separate lines instead of the last line.\n        for (var i = 0; i < repeat; i++) {\n          repeatCommand();\n          repeatInsert(1);\n        }\n      } else {\n        if (!repeatForInsert) {\n          // Hack to get the cursor to end up at the right place. If I is\n          // repeated in insert mode repeat, cursor will be 1 insert\n          // change set left of where it should be.\n          repeatCommand();\n        }\n        repeatInsert(repeat);\n      }\n      vim.inputState = cachedInputState;\n      if (vim.insertMode && !repeatForInsert) {\n        // Don't exit insert mode twice. If repeatForInsert is set, then we\n        // were called by an exitInsertMode call lower on the stack.\n        exitInsertMode(cm);\n      }\n      macroModeState.isPlaying = false;\n    }\n\n    function repeatInsertModeChanges(cm, changes, repeat) {\n      function keyHandler(binding) {\n        if (typeof binding == 'string') {\n          CodeMirror.commands[binding](cm);\n        } else {\n          binding(cm);\n        }\n        return true;\n      }\n      var head = cm.getCursor('head');\n      var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;\n      if (inVisualBlock) {\n        // Set up block selection again for repeating the changes.\n        var vim = cm.state.vim;\n        var lastSel = vim.lastSelection;\n        var offset = getOffset(lastSel.anchor, lastSel.head);\n        selectForInsert(cm, head, offset.line + 1);\n        repeat = cm.listSelections().length;\n        cm.setCursor(head);\n      }\n      for (var i = 0; i < repeat; i++) {\n        if (inVisualBlock) {\n          cm.setCursor(offsetCursor(head, i, 0));\n        }\n        for (var j = 0; j < changes.length; j++) {\n          var change = changes[j];\n          if (change instanceof InsertModeKey) {\n            CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);\n          } else if (typeof change == \"string\") {\n            var cur = cm.getCursor();\n            cm.replaceRange(change, cur, cur);\n          } else {\n            var start = cm.getCursor();\n            var end = offsetCursor(start, 0, change[0].length);\n            cm.replaceRange(change[0], start, end);\n          }\n        }\n      }\n      if (inVisualBlock) {\n        cm.setCursor(offsetCursor(head, 0, 1));\n      }\n    }\n\n    resetVimGlobalState();\n    return vimApi;\n  };\n  // Initialize Vim and make it available as an API.\n  CodeMirror.Vim = Vim();\n});\n"
  },
  {
    "path": "third_party/CodeMirror/lib/codemirror.css",
    "content": "/* BASICS */\n\n.CodeMirror {\n  /* Set height, width, borders, and global font properties here */\n  font-family: monospace;\n  height: 300px;\n  color: black;\n  direction: ltr;\n}\n\n/* PADDING */\n\n.CodeMirror-lines {\n  padding: 4px 0; /* Vertical padding around content */\n}\n.CodeMirror pre {\n  padding: 0 4px; /* Horizontal padding of content */\n}\n\n.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n  background-color: white; /* The little square between H and V scrollbars */\n}\n\n/* GUTTER */\n\n.CodeMirror-gutters {\n  border-right: 1px solid #ddd;\n  background-color: #f7f7f7;\n  white-space: nowrap;\n}\n.CodeMirror-linenumbers {}\n.CodeMirror-linenumber {\n  padding: 0 3px 0 5px;\n  min-width: 20px;\n  text-align: right;\n  color: #999;\n  white-space: nowrap;\n}\n\n.CodeMirror-guttermarker { color: black; }\n.CodeMirror-guttermarker-subtle { color: #999; }\n\n/* CURSOR */\n\n.CodeMirror-cursor {\n  border-left: 1px solid black;\n  border-right: none;\n  width: 0;\n}\n/* Shown when moving in bi-directional text */\n.CodeMirror div.CodeMirror-secondarycursor {\n  border-left: 1px solid silver;\n}\n.cm-fat-cursor .CodeMirror-cursor {\n  width: auto;\n  border: 0 !important;\n  background: #7e7;\n}\n.cm-fat-cursor div.CodeMirror-cursors {\n  z-index: 1;\n}\n.cm-fat-cursor-mark {\n  background-color: rgba(20, 255, 20, 0.5);\n  -webkit-animation: blink 1.06s steps(1) infinite;\n  -moz-animation: blink 1.06s steps(1) infinite;\n  animation: blink 1.06s steps(1) infinite;\n}\n.cm-animate-fat-cursor {\n  width: auto;\n  border: 0;\n  -webkit-animation: blink 1.06s steps(1) infinite;\n  -moz-animation: blink 1.06s steps(1) infinite;\n  animation: blink 1.06s steps(1) infinite;\n  background-color: #7e7;\n}\n@-moz-keyframes blink {\n  0% {}\n  50% { background-color: transparent; }\n  100% {}\n}\n@-webkit-keyframes blink {\n  0% {}\n  50% { background-color: transparent; }\n  100% {}\n}\n@keyframes blink {\n  0% {}\n  50% { background-color: transparent; }\n  100% {}\n}\n\n/* Can style cursor different in overwrite (non-insert) mode */\n.CodeMirror-overwrite .CodeMirror-cursor {}\n\n.cm-tab { display: inline-block; text-decoration: inherit; }\n\n.CodeMirror-rulers {\n  position: absolute;\n  left: 0; right: 0; top: -50px; bottom: -20px;\n  overflow: hidden;\n}\n.CodeMirror-ruler {\n  border-left: 1px solid #ccc;\n  top: 0; bottom: 0;\n  position: absolute;\n}\n\n/* DEFAULT THEME */\n\n.cm-s-default .cm-header {color: blue;}\n.cm-s-default .cm-quote {color: #090;}\n.cm-negative {color: #d44;}\n.cm-positive {color: #292;}\n.cm-header, .cm-strong {font-weight: bold;}\n.cm-em {font-style: italic;}\n.cm-link {text-decoration: underline;}\n.cm-strikethrough {text-decoration: line-through;}\n\n.cm-s-default .cm-keyword {color: #708;}\n.cm-s-default .cm-atom {color: #219;}\n.cm-s-default .cm-number {color: #164;}\n.cm-s-default .cm-def {color: #00f;}\n.cm-s-default .cm-variable,\n.cm-s-default .cm-punctuation,\n.cm-s-default .cm-property,\n.cm-s-default .cm-operator {}\n.cm-s-default .cm-variable-2 {color: #05a;}\n.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}\n.cm-s-default .cm-comment {color: #a50;}\n.cm-s-default .cm-string {color: #a11;}\n.cm-s-default .cm-string-2 {color: #f50;}\n.cm-s-default .cm-meta {color: #555;}\n.cm-s-default .cm-qualifier {color: #555;}\n.cm-s-default .cm-builtin {color: #30a;}\n.cm-s-default .cm-bracket {color: #997;}\n.cm-s-default .cm-tag {color: #170;}\n.cm-s-default .cm-attribute {color: #00c;}\n.cm-s-default .cm-hr {color: #999;}\n.cm-s-default .cm-link {color: #00c;}\n\n.cm-s-default .cm-error {color: #f00;}\n.cm-invalidchar {color: #f00;}\n\n.CodeMirror-composing { border-bottom: 2px solid; }\n\n/* Default styles for common addons */\n\ndiv.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}\n.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }\n.CodeMirror-activeline-background {background: #e8f2ff;}\n\n/* STOP */\n\n/* The rest of this file contains styles related to the mechanics of\n   the editor. You probably shouldn't touch them. */\n\n.CodeMirror {\n  position: relative;\n  overflow: hidden;\n  background: white;\n}\n\n.CodeMirror-scroll {\n  overflow: scroll !important; /* Things will break if this is overridden */\n  /* 30px is the magic margin used to hide the element's real scrollbars */\n  /* See overflow: hidden in .CodeMirror */\n  margin-bottom: -30px; margin-right: -30px;\n  padding-bottom: 30px;\n  height: 100%;\n  outline: none; /* Prevent dragging from highlighting the element */\n  position: relative;\n}\n.CodeMirror-sizer {\n  position: relative;\n  border-right: 30px solid transparent;\n}\n\n/* The fake, visible scrollbars. Used to force redraw during scrolling\n   before actual scrolling happens, thus preventing shaking and\n   flickering artifacts. */\n.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n  position: absolute;\n  z-index: 6;\n  display: none;\n}\n.CodeMirror-vscrollbar {\n  right: 0; top: 0;\n  overflow-x: hidden;\n  overflow-y: scroll;\n}\n.CodeMirror-hscrollbar {\n  bottom: 0; left: 0;\n  overflow-y: hidden;\n  overflow-x: scroll;\n}\n.CodeMirror-scrollbar-filler {\n  right: 0; bottom: 0;\n}\n.CodeMirror-gutter-filler {\n  left: 0; bottom: 0;\n}\n\n.CodeMirror-gutters {\n  position: absolute; left: 0; top: 0;\n  min-height: 100%;\n  z-index: 3;\n}\n.CodeMirror-gutter {\n  white-space: normal;\n  height: 100%;\n  display: inline-block;\n  vertical-align: top;\n  margin-bottom: -30px;\n}\n.CodeMirror-gutter-wrapper {\n  position: absolute;\n  z-index: 4;\n  background: none !important;\n  border: none !important;\n}\n.CodeMirror-gutter-background {\n  position: absolute;\n  top: 0; bottom: 0;\n  z-index: 4;\n}\n.CodeMirror-gutter-elt {\n  position: absolute;\n  cursor: default;\n  z-index: 4;\n}\n.CodeMirror-gutter-wrapper ::selection { background-color: transparent }\n.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }\n\n.CodeMirror-lines {\n  cursor: text;\n  min-height: 1px; /* prevents collapsing before first draw */\n}\n.CodeMirror pre {\n  /* Reset some styles that the rest of the page might have set */\n  -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;\n  border-width: 0;\n  background: transparent;\n  font-family: inherit;\n  font-size: inherit;\n  margin: 0;\n  white-space: pre;\n  word-wrap: normal;\n  line-height: inherit;\n  color: inherit;\n  z-index: 2;\n  position: relative;\n  overflow: visible;\n  -webkit-tap-highlight-color: transparent;\n  -webkit-font-variant-ligatures: contextual;\n  font-variant-ligatures: contextual;\n}\n.CodeMirror-wrap pre {\n  word-wrap: break-word;\n  white-space: pre-wrap;\n  word-break: normal;\n}\n\n.CodeMirror-linebackground {\n  position: absolute;\n  left: 0; right: 0; top: 0; bottom: 0;\n  z-index: 0;\n}\n\n.CodeMirror-linewidget {\n  position: relative;\n  z-index: 2;\n  padding: 0.1px; /* Force widget margins to stay inside of the container */\n}\n\n.CodeMirror-widget {}\n\n.CodeMirror-rtl pre { direction: rtl; }\n\n.CodeMirror-code {\n  outline: none;\n}\n\n/* Force content-box sizing for the elements where we expect it */\n.CodeMirror-scroll,\n.CodeMirror-sizer,\n.CodeMirror-gutter,\n.CodeMirror-gutters,\n.CodeMirror-linenumber {\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n}\n\n.CodeMirror-measure {\n  position: absolute;\n  width: 100%;\n  height: 0;\n  overflow: hidden;\n  visibility: hidden;\n}\n\n.CodeMirror-cursor {\n  position: absolute;\n  pointer-events: none;\n}\n.CodeMirror-measure pre { position: static; }\n\ndiv.CodeMirror-cursors {\n  visibility: hidden;\n  position: relative;\n  z-index: 3;\n}\ndiv.CodeMirror-dragcursors {\n  visibility: visible;\n}\n\n.CodeMirror-focused div.CodeMirror-cursors {\n  visibility: visible;\n}\n\n.CodeMirror-selected { background: #d9d9d9; }\n.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }\n.CodeMirror-crosshair { cursor: crosshair; }\n.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }\n.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }\n\n.cm-searching {\n  background-color: #ffa;\n  background-color: rgba(255, 255, 0, .4);\n}\n\n/* Used to force a border model for a node */\n.cm-force-border { padding-right: .1px; }\n\n@media print {\n  /* Hide the cursor when printing */\n  .CodeMirror div.CodeMirror-cursors {\n    visibility: hidden;\n  }\n}\n\n/* See issue #2901 */\n.cm-tab-wrap-hack:after { content: ''; }\n\n/* Help users use markselection to safely style text background */\nspan.CodeMirror-selectedtext { background: none; }\n"
  },
  {
    "path": "third_party/CodeMirror/lib/codemirror.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// This is CodeMirror (https://codemirror.net), a code editor\n// implemented in JavaScript on top of the browser's DOM.\n//\n// You can find some technical background for some of the code below\n// at http://marijnhaverbeke.nl/blog/#cm-internals .\n\n(function (global, factory) {\n  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n  typeof define === 'function' && define.amd ? define(factory) :\n  (global.CodeMirror = factory());\n}(this, (function () { 'use strict';\n\n  // Kludges for bugs and behavior differences that can't be feature\n  // detected are enabled based on userAgent etc sniffing.\n  var userAgent = navigator.userAgent;\n  var platform = navigator.platform;\n\n  var gecko = /gecko\\/\\d/i.test(userAgent);\n  var ie_upto10 = /MSIE \\d/.test(userAgent);\n  var ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(userAgent);\n  var edge = /Edge\\/(\\d+)/.exec(userAgent);\n  var ie = ie_upto10 || ie_11up || edge;\n  var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);\n  var webkit = !edge && /WebKit\\//.test(userAgent);\n  var qtwebkit = webkit && /Qt\\/\\d+\\.\\d+/.test(userAgent);\n  var chrome = !edge && /Chrome\\//.test(userAgent);\n  var presto = /Opera\\//.test(userAgent);\n  var safari = /Apple Computer/.test(navigator.vendor);\n  var mac_geMountainLion = /Mac OS X 1\\d\\D([8-9]|\\d\\d)\\D/.test(userAgent);\n  var phantom = /PhantomJS/.test(userAgent);\n\n  var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\\/\\w+/.test(userAgent);\n  var android = /Android/.test(userAgent);\n  // This is woefully incomplete. Suggestions for alternative methods welcome.\n  var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);\n  var mac = ios || /Mac/.test(platform);\n  var chromeOS = /\\bCrOS\\b/.test(userAgent);\n  var windows = /win/i.test(platform);\n\n  var presto_version = presto && userAgent.match(/Version\\/(\\d*\\.\\d*)/);\n  if (presto_version) { presto_version = Number(presto_version[1]); }\n  if (presto_version && presto_version >= 15) { presto = false; webkit = true; }\n  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X\n  var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));\n  var captureRightClick = gecko || (ie && ie_version >= 9);\n\n  function classTest(cls) { return new RegExp(\"(^|\\\\s)\" + cls + \"(?:$|\\\\s)\\\\s*\") }\n\n  var rmClass = function(node, cls) {\n    var current = node.className;\n    var match = classTest(cls).exec(current);\n    if (match) {\n      var after = current.slice(match.index + match[0].length);\n      node.className = current.slice(0, match.index) + (after ? match[1] + after : \"\");\n    }\n  };\n\n  function removeChildren(e) {\n    for (var count = e.childNodes.length; count > 0; --count)\n      { e.removeChild(e.firstChild); }\n    return e\n  }\n\n  function removeChildrenAndAdd(parent, e) {\n    return removeChildren(parent).appendChild(e)\n  }\n\n  function elt(tag, content, className, style) {\n    var e = document.createElement(tag);\n    if (className) { e.className = className; }\n    if (style) { e.style.cssText = style; }\n    if (typeof content == \"string\") { e.appendChild(document.createTextNode(content)); }\n    else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }\n    return e\n  }\n  // wrapper for elt, which removes the elt from the accessibility tree\n  function eltP(tag, content, className, style) {\n    var e = elt(tag, content, className, style);\n    e.setAttribute(\"role\", \"presentation\");\n    return e\n  }\n\n  var range;\n  if (document.createRange) { range = function(node, start, end, endNode) {\n    var r = document.createRange();\n    r.setEnd(endNode || node, end);\n    r.setStart(node, start);\n    return r\n  }; }\n  else { range = function(node, start, end) {\n    var r = document.body.createTextRange();\n    try { r.moveToElementText(node.parentNode); }\n    catch(e) { return r }\n    r.collapse(true);\n    r.moveEnd(\"character\", end);\n    r.moveStart(\"character\", start);\n    return r\n  }; }\n\n  function contains(parent, child) {\n    if (child.nodeType == 3) // Android browser always returns false when child is a textnode\n      { child = child.parentNode; }\n    if (parent.contains)\n      { return parent.contains(child) }\n    do {\n      if (child.nodeType == 11) { child = child.host; }\n      if (child == parent) { return true }\n    } while (child = child.parentNode)\n  }\n\n  function activeElt() {\n    // IE and Edge may throw an \"Unspecified Error\" when accessing document.activeElement.\n    // IE < 10 will throw when accessed while the page is loading or in an iframe.\n    // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.\n    var activeElement;\n    try {\n      activeElement = document.activeElement;\n    } catch(e) {\n      activeElement = document.body || null;\n    }\n    while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)\n      { activeElement = activeElement.shadowRoot.activeElement; }\n    return activeElement\n  }\n\n  function addClass(node, cls) {\n    var current = node.className;\n    if (!classTest(cls).test(current)) { node.className += (current ? \" \" : \"\") + cls; }\n  }\n  function joinClasses(a, b) {\n    var as = a.split(\" \");\n    for (var i = 0; i < as.length; i++)\n      { if (as[i] && !classTest(as[i]).test(b)) { b += \" \" + as[i]; } }\n    return b\n  }\n\n  var selectInput = function(node) { node.select(); };\n  if (ios) // Mobile Safari apparently has a bug where select() is broken.\n    { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }\n  else if (ie) // Suppress mysterious IE10 errors\n    { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }\n\n  function bind(f) {\n    var args = Array.prototype.slice.call(arguments, 1);\n    return function(){return f.apply(null, args)}\n  }\n\n  function copyObj(obj, target, overwrite) {\n    if (!target) { target = {}; }\n    for (var prop in obj)\n      { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))\n        { target[prop] = obj[prop]; } }\n    return target\n  }\n\n  // Counts the column offset in a string, taking tabs into account.\n  // Used mostly to find indentation.\n  function countColumn(string, end, tabSize, startIndex, startValue) {\n    if (end == null) {\n      end = string.search(/[^\\s\\u00a0]/);\n      if (end == -1) { end = string.length; }\n    }\n    for (var i = startIndex || 0, n = startValue || 0;;) {\n      var nextTab = string.indexOf(\"\\t\", i);\n      if (nextTab < 0 || nextTab >= end)\n        { return n + (end - i) }\n      n += nextTab - i;\n      n += tabSize - (n % tabSize);\n      i = nextTab + 1;\n    }\n  }\n\n  var Delayed = function() {this.id = null;};\n  Delayed.prototype.set = function (ms, f) {\n    clearTimeout(this.id);\n    this.id = setTimeout(f, ms);\n  };\n\n  function indexOf(array, elt) {\n    for (var i = 0; i < array.length; ++i)\n      { if (array[i] == elt) { return i } }\n    return -1\n  }\n\n  // Number of pixels added to scroller and sizer to hide scrollbar\n  var scrollerGap = 30;\n\n  // Returned or thrown by various protocols to signal 'I'm not\n  // handling this'.\n  var Pass = {toString: function(){return \"CodeMirror.Pass\"}};\n\n  // Reused option objects for setSelection & friends\n  var sel_dontScroll = {scroll: false}, sel_mouse = {origin: \"*mouse\"}, sel_move = {origin: \"+move\"};\n\n  // The inverse of countColumn -- find the offset that corresponds to\n  // a particular column.\n  function findColumn(string, goal, tabSize) {\n    for (var pos = 0, col = 0;;) {\n      var nextTab = string.indexOf(\"\\t\", pos);\n      if (nextTab == -1) { nextTab = string.length; }\n      var skipped = nextTab - pos;\n      if (nextTab == string.length || col + skipped >= goal)\n        { return pos + Math.min(skipped, goal - col) }\n      col += nextTab - pos;\n      col += tabSize - (col % tabSize);\n      pos = nextTab + 1;\n      if (col >= goal) { return pos }\n    }\n  }\n\n  var spaceStrs = [\"\"];\n  function spaceStr(n) {\n    while (spaceStrs.length <= n)\n      { spaceStrs.push(lst(spaceStrs) + \" \"); }\n    return spaceStrs[n]\n  }\n\n  function lst(arr) { return arr[arr.length-1] }\n\n  function map(array, f) {\n    var out = [];\n    for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }\n    return out\n  }\n\n  function insertSorted(array, value, score) {\n    var pos = 0, priority = score(value);\n    while (pos < array.length && score(array[pos]) <= priority) { pos++; }\n    array.splice(pos, 0, value);\n  }\n\n  function nothing() {}\n\n  function createObj(base, props) {\n    var inst;\n    if (Object.create) {\n      inst = Object.create(base);\n    } else {\n      nothing.prototype = base;\n      inst = new nothing();\n    }\n    if (props) { copyObj(props, inst); }\n    return inst\n  }\n\n  var nonASCIISingleCaseWordChar = /[\\u00df\\u0587\\u0590-\\u05f4\\u0600-\\u06ff\\u3040-\\u309f\\u30a0-\\u30ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\uac00-\\ud7af]/;\n  function isWordCharBasic(ch) {\n    return /\\w/.test(ch) || ch > \"\\x80\" &&\n      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))\n  }\n  function isWordChar(ch, helper) {\n    if (!helper) { return isWordCharBasic(ch) }\n    if (helper.source.indexOf(\"\\\\w\") > -1 && isWordCharBasic(ch)) { return true }\n    return helper.test(ch)\n  }\n\n  function isEmpty(obj) {\n    for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }\n    return true\n  }\n\n  // Extending unicode characters. A series of a non-extending char +\n  // any number of extending chars is treated as a single unit as far\n  // as editing and measuring is concerned. This is not fully correct,\n  // since some scripts/fonts/browsers also treat other configurations\n  // of code points as a group.\n  var extendingChars = /[\\u0300-\\u036f\\u0483-\\u0489\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u065e\\u0670\\u06d6-\\u06dc\\u06de-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07eb-\\u07f3\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0900-\\u0902\\u093c\\u0941-\\u0948\\u094d\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09bc\\u09be\\u09c1-\\u09c4\\u09cd\\u09d7\\u09e2\\u09e3\\u0a01\\u0a02\\u0a3c\\u0a41\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a70\\u0a71\\u0a75\\u0a81\\u0a82\\u0abc\\u0ac1-\\u0ac5\\u0ac7\\u0ac8\\u0acd\\u0ae2\\u0ae3\\u0b01\\u0b3c\\u0b3e\\u0b3f\\u0b41-\\u0b44\\u0b4d\\u0b56\\u0b57\\u0b62\\u0b63\\u0b82\\u0bbe\\u0bc0\\u0bcd\\u0bd7\\u0c3e-\\u0c40\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0cbc\\u0cbf\\u0cc2\\u0cc6\\u0ccc\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0d3e\\u0d41-\\u0d44\\u0d4d\\u0d57\\u0d62\\u0d63\\u0dca\\u0dcf\\u0dd2-\\u0dd4\\u0dd6\\u0ddf\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0eb1\\u0eb4-\\u0eb9\\u0ebb\\u0ebc\\u0ec8-\\u0ecd\\u0f18\\u0f19\\u0f35\\u0f37\\u0f39\\u0f71-\\u0f7e\\u0f80-\\u0f84\\u0f86\\u0f87\\u0f90-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102d-\\u1030\\u1032-\\u1037\\u1039\\u103a\\u103d\\u103e\\u1058\\u1059\\u105e-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108d\\u109d\\u135f\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b7-\\u17bd\\u17c6\\u17c9-\\u17d3\\u17dd\\u180b-\\u180d\\u18a9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193b\\u1a17\\u1a18\\u1a56\\u1a58-\\u1a5e\\u1a60\\u1a62\\u1a65-\\u1a6c\\u1a73-\\u1a7c\\u1a7f\\u1b00-\\u1b03\\u1b34\\u1b36-\\u1b3a\\u1b3c\\u1b42\\u1b6b-\\u1b73\\u1b80\\u1b81\\u1ba2-\\u1ba5\\u1ba8\\u1ba9\\u1c2c-\\u1c33\\u1c36\\u1c37\\u1cd0-\\u1cd2\\u1cd4-\\u1ce0\\u1ce2-\\u1ce8\\u1ced\\u1dc0-\\u1de6\\u1dfd-\\u1dff\\u200c\\u200d\\u20d0-\\u20f0\\u2cef-\\u2cf1\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua66f-\\ua672\\ua67c\\ua67d\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua825\\ua826\\ua8c4\\ua8e0-\\ua8f1\\ua926-\\ua92d\\ua947-\\ua951\\ua980-\\ua982\\ua9b3\\ua9b6-\\ua9b9\\ua9bc\\uaa29-\\uaa2e\\uaa31\\uaa32\\uaa35\\uaa36\\uaa43\\uaa4c\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uabe5\\uabe8\\uabed\\udc00-\\udfff\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe26\\uff9e\\uff9f]/;\n  function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }\n\n  // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.\n  function skipExtendingChars(str, pos, dir) {\n    while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }\n    return pos\n  }\n\n  // Returns the value from the range [`from`; `to`] that satisfies\n  // `pred` and is closest to `from`. Assumes that at least `to`\n  // satisfies `pred`. Supports `from` being greater than `to`.\n  function findFirst(pred, from, to) {\n    // At any point we are certain `to` satisfies `pred`, don't know\n    // whether `from` does.\n    var dir = from > to ? -1 : 1;\n    for (;;) {\n      if (from == to) { return from }\n      var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);\n      if (mid == from) { return pred(mid) ? from : to }\n      if (pred(mid)) { to = mid; }\n      else { from = mid + dir; }\n    }\n  }\n\n  // The display handles the DOM integration, both for input reading\n  // and content drawing. It holds references to DOM nodes and\n  // display-related state.\n\n  function Display(place, doc, input) {\n    var d = this;\n    this.input = input;\n\n    // Covers bottom-right square when both scrollbars are present.\n    d.scrollbarFiller = elt(\"div\", null, \"CodeMirror-scrollbar-filler\");\n    d.scrollbarFiller.setAttribute(\"cm-not-content\", \"true\");\n    // Covers bottom of gutter when coverGutterNextToScrollbar is on\n    // and h scrollbar is present.\n    d.gutterFiller = elt(\"div\", null, \"CodeMirror-gutter-filler\");\n    d.gutterFiller.setAttribute(\"cm-not-content\", \"true\");\n    // Will contain the actual code, positioned to cover the viewport.\n    d.lineDiv = eltP(\"div\", null, \"CodeMirror-code\");\n    // Elements are added to these to represent selection and cursors.\n    d.selectionDiv = elt(\"div\", null, null, \"position: relative; z-index: 1\");\n    d.cursorDiv = elt(\"div\", null, \"CodeMirror-cursors\");\n    // A visibility: hidden element used to find the size of things.\n    d.measure = elt(\"div\", null, \"CodeMirror-measure\");\n    // When lines outside of the viewport are measured, they are drawn in this.\n    d.lineMeasure = elt(\"div\", null, \"CodeMirror-measure\");\n    // Wraps everything that needs to exist inside the vertically-padded coordinate system\n    d.lineSpace = eltP(\"div\", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],\n                      null, \"position: relative; outline: none\");\n    var lines = eltP(\"div\", [d.lineSpace], \"CodeMirror-lines\");\n    // Moved around its parent to cover visible view.\n    d.mover = elt(\"div\", [lines], null, \"position: relative\");\n    // Set to the height of the document, allowing scrolling.\n    d.sizer = elt(\"div\", [d.mover], \"CodeMirror-sizer\");\n    d.sizerWidth = null;\n    // Behavior of elts with overflow: auto and padding is\n    // inconsistent across browsers. This is used to ensure the\n    // scrollable area is big enough.\n    d.heightForcer = elt(\"div\", null, null, \"position: absolute; height: \" + scrollerGap + \"px; width: 1px;\");\n    // Will contain the gutters, if any.\n    d.gutters = elt(\"div\", null, \"CodeMirror-gutters\");\n    d.lineGutter = null;\n    // Actual scrollable element.\n    d.scroller = elt(\"div\", [d.sizer, d.heightForcer, d.gutters], \"CodeMirror-scroll\");\n    d.scroller.setAttribute(\"tabIndex\", \"-1\");\n    // The element in which the editor lives.\n    d.wrapper = elt(\"div\", [d.scrollbarFiller, d.gutterFiller, d.scroller], \"CodeMirror\");\n\n    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)\n    if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }\n    if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }\n\n    if (place) {\n      if (place.appendChild) { place.appendChild(d.wrapper); }\n      else { place(d.wrapper); }\n    }\n\n    // Current rendered range (may be bigger than the view window).\n    d.viewFrom = d.viewTo = doc.first;\n    d.reportedViewFrom = d.reportedViewTo = doc.first;\n    // Information about the rendered lines.\n    d.view = [];\n    d.renderedView = null;\n    // Holds info about a single rendered line when it was rendered\n    // for measurement, while not in view.\n    d.externalMeasured = null;\n    // Empty space (in pixels) above the view\n    d.viewOffset = 0;\n    d.lastWrapHeight = d.lastWrapWidth = 0;\n    d.updateLineNumbers = null;\n\n    d.nativeBarWidth = d.barHeight = d.barWidth = 0;\n    d.scrollbarsClipped = false;\n\n    // Used to only resize the line number gutter when necessary (when\n    // the amount of lines crosses a boundary that makes its width change)\n    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;\n    // Set to true when a non-horizontal-scrolling line widget is\n    // added. As an optimization, line widget aligning is skipped when\n    // this is false.\n    d.alignWidgets = false;\n\n    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n\n    // Tracks the maximum line length so that the horizontal scrollbar\n    // can be kept static when scrolling.\n    d.maxLine = null;\n    d.maxLineLength = 0;\n    d.maxLineChanged = false;\n\n    // Used for measuring wheel scrolling granularity\n    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;\n\n    // True when shift is held down.\n    d.shift = false;\n\n    // Used to track whether anything happened since the context menu\n    // was opened.\n    d.selForContextMenu = null;\n\n    d.activeTouch = null;\n\n    input.init(d);\n  }\n\n  // Find the line object corresponding to the given line number.\n  function getLine(doc, n) {\n    n -= doc.first;\n    if (n < 0 || n >= doc.size) { throw new Error(\"There is no line \" + (n + doc.first) + \" in the document.\") }\n    var chunk = doc;\n    while (!chunk.lines) {\n      for (var i = 0;; ++i) {\n        var child = chunk.children[i], sz = child.chunkSize();\n        if (n < sz) { chunk = child; break }\n        n -= sz;\n      }\n    }\n    return chunk.lines[n]\n  }\n\n  // Get the part of a document between two positions, as an array of\n  // strings.\n  function getBetween(doc, start, end) {\n    var out = [], n = start.line;\n    doc.iter(start.line, end.line + 1, function (line) {\n      var text = line.text;\n      if (n == end.line) { text = text.slice(0, end.ch); }\n      if (n == start.line) { text = text.slice(start.ch); }\n      out.push(text);\n      ++n;\n    });\n    return out\n  }\n  // Get the lines between from and to, as array of strings.\n  function getLines(doc, from, to) {\n    var out = [];\n    doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value\n    return out\n  }\n\n  // Update the height of a line, propagating the height change\n  // upwards to parent nodes.\n  function updateLineHeight(line, height) {\n    var diff = height - line.height;\n    if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }\n  }\n\n  // Given a line object, find its line number by walking up through\n  // its parent links.\n  function lineNo(line) {\n    if (line.parent == null) { return null }\n    var cur = line.parent, no = indexOf(cur.lines, line);\n    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {\n      for (var i = 0;; ++i) {\n        if (chunk.children[i] == cur) { break }\n        no += chunk.children[i].chunkSize();\n      }\n    }\n    return no + cur.first\n  }\n\n  // Find the line at the given vertical position, using the height\n  // information in the document tree.\n  function lineAtHeight(chunk, h) {\n    var n = chunk.first;\n    outer: do {\n      for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {\n        var child = chunk.children[i$1], ch = child.height;\n        if (h < ch) { chunk = child; continue outer }\n        h -= ch;\n        n += child.chunkSize();\n      }\n      return n\n    } while (!chunk.lines)\n    var i = 0;\n    for (; i < chunk.lines.length; ++i) {\n      var line = chunk.lines[i], lh = line.height;\n      if (h < lh) { break }\n      h -= lh;\n    }\n    return n + i\n  }\n\n  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}\n\n  function lineNumberFor(options, i) {\n    return String(options.lineNumberFormatter(i + options.firstLineNumber))\n  }\n\n  // A Pos instance represents a position within the text.\n  function Pos(line, ch, sticky) {\n    if ( sticky === void 0 ) sticky = null;\n\n    if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }\n    this.line = line;\n    this.ch = ch;\n    this.sticky = sticky;\n  }\n\n  // Compare two positions, return 0 if they are the same, a negative\n  // number when a is less, and a positive number otherwise.\n  function cmp(a, b) { return a.line - b.line || a.ch - b.ch }\n\n  function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }\n\n  function copyPos(x) {return Pos(x.line, x.ch)}\n  function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }\n  function minPos(a, b) { return cmp(a, b) < 0 ? a : b }\n\n  // Most of the external API clips given positions to make sure they\n  // actually exist within the document.\n  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}\n  function clipPos(doc, pos) {\n    if (pos.line < doc.first) { return Pos(doc.first, 0) }\n    var last = doc.first + doc.size - 1;\n    if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }\n    return clipToLen(pos, getLine(doc, pos.line).text.length)\n  }\n  function clipToLen(pos, linelen) {\n    var ch = pos.ch;\n    if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }\n    else if (ch < 0) { return Pos(pos.line, 0) }\n    else { return pos }\n  }\n  function clipPosArray(doc, array) {\n    var out = [];\n    for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }\n    return out\n  }\n\n  // Optimize some code when these features are not used.\n  var sawReadOnlySpans = false, sawCollapsedSpans = false;\n\n  function seeReadOnlySpans() {\n    sawReadOnlySpans = true;\n  }\n\n  function seeCollapsedSpans() {\n    sawCollapsedSpans = true;\n  }\n\n  // TEXTMARKER SPANS\n\n  function MarkedSpan(marker, from, to) {\n    this.marker = marker;\n    this.from = from; this.to = to;\n  }\n\n  // Search an array of spans for a span matching the given marker.\n  function getMarkedSpanFor(spans, marker) {\n    if (spans) { for (var i = 0; i < spans.length; ++i) {\n      var span = spans[i];\n      if (span.marker == marker) { return span }\n    } }\n  }\n  // Remove a span from an array, returning undefined if no spans are\n  // left (we don't store arrays for lines without spans).\n  function removeMarkedSpan(spans, span) {\n    var r;\n    for (var i = 0; i < spans.length; ++i)\n      { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }\n    return r\n  }\n  // Add a span to a line.\n  function addMarkedSpan(line, span) {\n    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];\n    span.marker.attachLine(line);\n  }\n\n  // Used for the algorithm that adjusts markers for a change in the\n  // document. These functions cut an array of spans at a given\n  // character position, returning an array of remaining chunks (or\n  // undefined if nothing remains).\n  function markedSpansBefore(old, startCh, isInsert) {\n    var nw;\n    if (old) { for (var i = 0; i < old.length; ++i) {\n      var span = old[i], marker = span.marker;\n      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);\n      if (startsBefore || span.from == startCh && marker.type == \"bookmark\" && (!isInsert || !span.marker.insertLeft)) {\n        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)\n        ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));\n      }\n    } }\n    return nw\n  }\n  function markedSpansAfter(old, endCh, isInsert) {\n    var nw;\n    if (old) { for (var i = 0; i < old.length; ++i) {\n      var span = old[i], marker = span.marker;\n      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);\n      if (endsAfter || span.from == endCh && marker.type == \"bookmark\" && (!isInsert || span.marker.insertLeft)) {\n        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)\n        ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,\n                                              span.to == null ? null : span.to - endCh));\n      }\n    } }\n    return nw\n  }\n\n  // Given a change object, compute the new set of marker spans that\n  // cover the line in which the change took place. Removes spans\n  // entirely within the change, reconnects spans belonging to the\n  // same marker that appear on both sides of the change, and cuts off\n  // spans partially within the change. Returns an array of span\n  // arrays with one element for each line in (after) the change.\n  function stretchSpansOverChange(doc, change) {\n    if (change.full) { return null }\n    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;\n    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;\n    if (!oldFirst && !oldLast) { return null }\n\n    var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;\n    // Get the spans that 'stick out' on both sides\n    var first = markedSpansBefore(oldFirst, startCh, isInsert);\n    var last = markedSpansAfter(oldLast, endCh, isInsert);\n\n    // Next, merge those two ends\n    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);\n    if (first) {\n      // Fix up .to properties of first\n      for (var i = 0; i < first.length; ++i) {\n        var span = first[i];\n        if (span.to == null) {\n          var found = getMarkedSpanFor(last, span.marker);\n          if (!found) { span.to = startCh; }\n          else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }\n        }\n      }\n    }\n    if (last) {\n      // Fix up .from in last (or move them into first in case of sameLine)\n      for (var i$1 = 0; i$1 < last.length; ++i$1) {\n        var span$1 = last[i$1];\n        if (span$1.to != null) { span$1.to += offset; }\n        if (span$1.from == null) {\n          var found$1 = getMarkedSpanFor(first, span$1.marker);\n          if (!found$1) {\n            span$1.from = offset;\n            if (sameLine) { (first || (first = [])).push(span$1); }\n          }\n        } else {\n          span$1.from += offset;\n          if (sameLine) { (first || (first = [])).push(span$1); }\n        }\n      }\n    }\n    // Make sure we didn't create any zero-length spans\n    if (first) { first = clearEmptySpans(first); }\n    if (last && last != first) { last = clearEmptySpans(last); }\n\n    var newMarkers = [first];\n    if (!sameLine) {\n      // Fill gap with whole-line-spans\n      var gap = change.text.length - 2, gapMarkers;\n      if (gap > 0 && first)\n        { for (var i$2 = 0; i$2 < first.length; ++i$2)\n          { if (first[i$2].to == null)\n            { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }\n      for (var i$3 = 0; i$3 < gap; ++i$3)\n        { newMarkers.push(gapMarkers); }\n      newMarkers.push(last);\n    }\n    return newMarkers\n  }\n\n  // Remove spans that are empty and don't have a clearWhenEmpty\n  // option of false.\n  function clearEmptySpans(spans) {\n    for (var i = 0; i < spans.length; ++i) {\n      var span = spans[i];\n      if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)\n        { spans.splice(i--, 1); }\n    }\n    if (!spans.length) { return null }\n    return spans\n  }\n\n  // Used to 'clip' out readOnly ranges when making a change.\n  function removeReadOnlyRanges(doc, from, to) {\n    var markers = null;\n    doc.iter(from.line, to.line + 1, function (line) {\n      if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {\n        var mark = line.markedSpans[i].marker;\n        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))\n          { (markers || (markers = [])).push(mark); }\n      } }\n    });\n    if (!markers) { return null }\n    var parts = [{from: from, to: to}];\n    for (var i = 0; i < markers.length; ++i) {\n      var mk = markers[i], m = mk.find(0);\n      for (var j = 0; j < parts.length; ++j) {\n        var p = parts[j];\n        if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }\n        var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);\n        if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)\n          { newParts.push({from: p.from, to: m.from}); }\n        if (dto > 0 || !mk.inclusiveRight && !dto)\n          { newParts.push({from: m.to, to: p.to}); }\n        parts.splice.apply(parts, newParts);\n        j += newParts.length - 3;\n      }\n    }\n    return parts\n  }\n\n  // Connect or disconnect spans from a line.\n  function detachMarkedSpans(line) {\n    var spans = line.markedSpans;\n    if (!spans) { return }\n    for (var i = 0; i < spans.length; ++i)\n      { spans[i].marker.detachLine(line); }\n    line.markedSpans = null;\n  }\n  function attachMarkedSpans(line, spans) {\n    if (!spans) { return }\n    for (var i = 0; i < spans.length; ++i)\n      { spans[i].marker.attachLine(line); }\n    line.markedSpans = spans;\n  }\n\n  // Helpers used when computing which overlapping collapsed span\n  // counts as the larger one.\n  function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }\n  function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }\n\n  // Returns a number indicating which of two overlapping collapsed\n  // spans is larger (and thus includes the other). Falls back to\n  // comparing ids when the spans cover exactly the same range.\n  function compareCollapsedMarkers(a, b) {\n    var lenDiff = a.lines.length - b.lines.length;\n    if (lenDiff != 0) { return lenDiff }\n    var aPos = a.find(), bPos = b.find();\n    var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);\n    if (fromCmp) { return -fromCmp }\n    var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);\n    if (toCmp) { return toCmp }\n    return b.id - a.id\n  }\n\n  // Find out whether a line ends or starts in a collapsed span. If\n  // so, return the marker for that span.\n  function collapsedSpanAtSide(line, start) {\n    var sps = sawCollapsedSpans && line.markedSpans, found;\n    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {\n      sp = sps[i];\n      if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&\n          (!found || compareCollapsedMarkers(found, sp.marker) < 0))\n        { found = sp.marker; }\n    } }\n    return found\n  }\n  function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }\n  function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }\n\n  function collapsedSpanAround(line, ch) {\n    var sps = sawCollapsedSpans && line.markedSpans, found;\n    if (sps) { for (var i = 0; i < sps.length; ++i) {\n      var sp = sps[i];\n      if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&\n          (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }\n    } }\n    return found\n  }\n\n  // Test whether there exists a collapsed span that partially\n  // overlaps (covers the start or end, but not both) of a new span.\n  // Such overlap is not allowed.\n  function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {\n    var line = getLine(doc, lineNo$$1);\n    var sps = sawCollapsedSpans && line.markedSpans;\n    if (sps) { for (var i = 0; i < sps.length; ++i) {\n      var sp = sps[i];\n      if (!sp.marker.collapsed) { continue }\n      var found = sp.marker.find(0);\n      var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);\n      var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);\n      if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }\n      if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||\n          fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))\n        { return true }\n    } }\n  }\n\n  // A visual line is a line as drawn on the screen. Folding, for\n  // example, can cause multiple logical lines to appear on the same\n  // visual line. This finds the start of the visual line that the\n  // given line is part of (usually that is the line itself).\n  function visualLine(line) {\n    var merged;\n    while (merged = collapsedSpanAtStart(line))\n      { line = merged.find(-1, true).line; }\n    return line\n  }\n\n  function visualLineEnd(line) {\n    var merged;\n    while (merged = collapsedSpanAtEnd(line))\n      { line = merged.find(1, true).line; }\n    return line\n  }\n\n  // Returns an array of logical lines that continue the visual line\n  // started by the argument, or undefined if there are no such lines.\n  function visualLineContinued(line) {\n    var merged, lines;\n    while (merged = collapsedSpanAtEnd(line)) {\n      line = merged.find(1, true).line\n      ;(lines || (lines = [])).push(line);\n    }\n    return lines\n  }\n\n  // Get the line number of the start of the visual line that the\n  // given line number is part of.\n  function visualLineNo(doc, lineN) {\n    var line = getLine(doc, lineN), vis = visualLine(line);\n    if (line == vis) { return lineN }\n    return lineNo(vis)\n  }\n\n  // Get the line number of the start of the next visual line after\n  // the given line.\n  function visualLineEndNo(doc, lineN) {\n    if (lineN > doc.lastLine()) { return lineN }\n    var line = getLine(doc, lineN), merged;\n    if (!lineIsHidden(doc, line)) { return lineN }\n    while (merged = collapsedSpanAtEnd(line))\n      { line = merged.find(1, true).line; }\n    return lineNo(line) + 1\n  }\n\n  // Compute whether a line is hidden. Lines count as hidden when they\n  // are part of a visual line that starts with another line, or when\n  // they are entirely covered by collapsed, non-widget span.\n  function lineIsHidden(doc, line) {\n    var sps = sawCollapsedSpans && line.markedSpans;\n    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {\n      sp = sps[i];\n      if (!sp.marker.collapsed) { continue }\n      if (sp.from == null) { return true }\n      if (sp.marker.widgetNode) { continue }\n      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))\n        { return true }\n    } }\n  }\n  function lineIsHiddenInner(doc, line, span) {\n    if (span.to == null) {\n      var end = span.marker.find(1, true);\n      return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))\n    }\n    if (span.marker.inclusiveRight && span.to == line.text.length)\n      { return true }\n    for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {\n      sp = line.markedSpans[i];\n      if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&\n          (sp.to == null || sp.to != span.from) &&\n          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&\n          lineIsHiddenInner(doc, line, sp)) { return true }\n    }\n  }\n\n  // Find the height above the given line.\n  function heightAtLine(lineObj) {\n    lineObj = visualLine(lineObj);\n\n    var h = 0, chunk = lineObj.parent;\n    for (var i = 0; i < chunk.lines.length; ++i) {\n      var line = chunk.lines[i];\n      if (line == lineObj) { break }\n      else { h += line.height; }\n    }\n    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n      for (var i$1 = 0; i$1 < p.children.length; ++i$1) {\n        var cur = p.children[i$1];\n        if (cur == chunk) { break }\n        else { h += cur.height; }\n      }\n    }\n    return h\n  }\n\n  // Compute the character length of a line, taking into account\n  // collapsed ranges (see markText) that might hide parts, and join\n  // other lines onto it.\n  function lineLength(line) {\n    if (line.height == 0) { return 0 }\n    var len = line.text.length, merged, cur = line;\n    while (merged = collapsedSpanAtStart(cur)) {\n      var found = merged.find(0, true);\n      cur = found.from.line;\n      len += found.from.ch - found.to.ch;\n    }\n    cur = line;\n    while (merged = collapsedSpanAtEnd(cur)) {\n      var found$1 = merged.find(0, true);\n      len -= cur.text.length - found$1.from.ch;\n      cur = found$1.to.line;\n      len += cur.text.length - found$1.to.ch;\n    }\n    return len\n  }\n\n  // Find the longest line in the document.\n  function findMaxLine(cm) {\n    var d = cm.display, doc = cm.doc;\n    d.maxLine = getLine(doc, doc.first);\n    d.maxLineLength = lineLength(d.maxLine);\n    d.maxLineChanged = true;\n    doc.iter(function (line) {\n      var len = lineLength(line);\n      if (len > d.maxLineLength) {\n        d.maxLineLength = len;\n        d.maxLine = line;\n      }\n    });\n  }\n\n  // BIDI HELPERS\n\n  function iterateBidiSections(order, from, to, f) {\n    if (!order) { return f(from, to, \"ltr\", 0) }\n    var found = false;\n    for (var i = 0; i < order.length; ++i) {\n      var part = order[i];\n      if (part.from < to && part.to > from || from == to && part.to == from) {\n        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? \"rtl\" : \"ltr\", i);\n        found = true;\n      }\n    }\n    if (!found) { f(from, to, \"ltr\"); }\n  }\n\n  var bidiOther = null;\n  function getBidiPartAt(order, ch, sticky) {\n    var found;\n    bidiOther = null;\n    for (var i = 0; i < order.length; ++i) {\n      var cur = order[i];\n      if (cur.from < ch && cur.to > ch) { return i }\n      if (cur.to == ch) {\n        if (cur.from != cur.to && sticky == \"before\") { found = i; }\n        else { bidiOther = i; }\n      }\n      if (cur.from == ch) {\n        if (cur.from != cur.to && sticky != \"before\") { found = i; }\n        else { bidiOther = i; }\n      }\n    }\n    return found != null ? found : bidiOther\n  }\n\n  // Bidirectional ordering algorithm\n  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm\n  // that this (partially) implements.\n\n  // One-char codes used for character types:\n  // L (L):   Left-to-Right\n  // R (R):   Right-to-Left\n  // r (AL):  Right-to-Left Arabic\n  // 1 (EN):  European Number\n  // + (ES):  European Number Separator\n  // % (ET):  European Number Terminator\n  // n (AN):  Arabic Number\n  // , (CS):  Common Number Separator\n  // m (NSM): Non-Spacing Mark\n  // b (BN):  Boundary Neutral\n  // s (B):   Paragraph Separator\n  // t (S):   Segment Separator\n  // w (WS):  Whitespace\n  // N (ON):  Other Neutrals\n\n  // Returns null if characters are ordered as they appear\n  // (left-to-right), or an array of sections ({from, to, level}\n  // objects) in the order in which they occur visually.\n  var bidiOrdering = (function() {\n    // Character types for codepoints 0 to 0xff\n    var lowTypes = \"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN\";\n    // Character types for codepoints 0x600 to 0x6f9\n    var arabicTypes = \"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111\";\n    function charType(code) {\n      if (code <= 0xf7) { return lowTypes.charAt(code) }\n      else if (0x590 <= code && code <= 0x5f4) { return \"R\" }\n      else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }\n      else if (0x6ee <= code && code <= 0x8ac) { return \"r\" }\n      else if (0x2000 <= code && code <= 0x200b) { return \"w\" }\n      else if (code == 0x200c) { return \"b\" }\n      else { return \"L\" }\n    }\n\n    var bidiRE = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;\n\n    function BidiSpan(level, from, to) {\n      this.level = level;\n      this.from = from; this.to = to;\n    }\n\n    return function(str, direction) {\n      var outerType = direction == \"ltr\" ? \"L\" : \"R\";\n\n      if (str.length == 0 || direction == \"ltr\" && !bidiRE.test(str)) { return false }\n      var len = str.length, types = [];\n      for (var i = 0; i < len; ++i)\n        { types.push(charType(str.charCodeAt(i))); }\n\n      // W1. Examine each non-spacing mark (NSM) in the level run, and\n      // change the type of the NSM to the type of the previous\n      // character. If the NSM is at the start of the level run, it will\n      // get the type of sor.\n      for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {\n        var type = types[i$1];\n        if (type == \"m\") { types[i$1] = prev; }\n        else { prev = type; }\n      }\n\n      // W2. Search backwards from each instance of a European number\n      // until the first strong type (R, L, AL, or sor) is found. If an\n      // AL is found, change the type of the European number to Arabic\n      // number.\n      // W3. Change all ALs to R.\n      for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {\n        var type$1 = types[i$2];\n        if (type$1 == \"1\" && cur == \"r\") { types[i$2] = \"n\"; }\n        else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == \"r\") { types[i$2] = \"R\"; } }\n      }\n\n      // W4. A single European separator between two European numbers\n      // changes to a European number. A single common separator between\n      // two numbers of the same type changes to that type.\n      for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {\n        var type$2 = types[i$3];\n        if (type$2 == \"+\" && prev$1 == \"1\" && types[i$3+1] == \"1\") { types[i$3] = \"1\"; }\n        else if (type$2 == \",\" && prev$1 == types[i$3+1] &&\n                 (prev$1 == \"1\" || prev$1 == \"n\")) { types[i$3] = prev$1; }\n        prev$1 = type$2;\n      }\n\n      // W5. A sequence of European terminators adjacent to European\n      // numbers changes to all European numbers.\n      // W6. Otherwise, separators and terminators change to Other\n      // Neutral.\n      for (var i$4 = 0; i$4 < len; ++i$4) {\n        var type$3 = types[i$4];\n        if (type$3 == \",\") { types[i$4] = \"N\"; }\n        else if (type$3 == \"%\") {\n          var end = (void 0);\n          for (end = i$4 + 1; end < len && types[end] == \"%\"; ++end) {}\n          var replace = (i$4 && types[i$4-1] == \"!\") || (end < len && types[end] == \"1\") ? \"1\" : \"N\";\n          for (var j = i$4; j < end; ++j) { types[j] = replace; }\n          i$4 = end - 1;\n        }\n      }\n\n      // W7. Search backwards from each instance of a European number\n      // until the first strong type (R, L, or sor) is found. If an L is\n      // found, then change the type of the European number to L.\n      for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {\n        var type$4 = types[i$5];\n        if (cur$1 == \"L\" && type$4 == \"1\") { types[i$5] = \"L\"; }\n        else if (isStrong.test(type$4)) { cur$1 = type$4; }\n      }\n\n      // N1. A sequence of neutrals takes the direction of the\n      // surrounding strong text if the text on both sides has the same\n      // direction. European and Arabic numbers act as if they were R in\n      // terms of their influence on neutrals. Start-of-level-run (sor)\n      // and end-of-level-run (eor) are used at level run boundaries.\n      // N2. Any remaining neutrals take the embedding direction.\n      for (var i$6 = 0; i$6 < len; ++i$6) {\n        if (isNeutral.test(types[i$6])) {\n          var end$1 = (void 0);\n          for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}\n          var before = (i$6 ? types[i$6-1] : outerType) == \"L\";\n          var after = (end$1 < len ? types[end$1] : outerType) == \"L\";\n          var replace$1 = before == after ? (before ? \"L\" : \"R\") : outerType;\n          for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }\n          i$6 = end$1 - 1;\n        }\n      }\n\n      // Here we depart from the documented algorithm, in order to avoid\n      // building up an actual levels array. Since there are only three\n      // levels (0, 1, 2) in an implementation that doesn't take\n      // explicit embedding into account, we can build up the order on\n      // the fly, without following the level-based algorithm.\n      var order = [], m;\n      for (var i$7 = 0; i$7 < len;) {\n        if (countsAsLeft.test(types[i$7])) {\n          var start = i$7;\n          for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}\n          order.push(new BidiSpan(0, start, i$7));\n        } else {\n          var pos = i$7, at = order.length;\n          for (++i$7; i$7 < len && types[i$7] != \"L\"; ++i$7) {}\n          for (var j$2 = pos; j$2 < i$7;) {\n            if (countsAsNum.test(types[j$2])) {\n              if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }\n              var nstart = j$2;\n              for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}\n              order.splice(at, 0, new BidiSpan(2, nstart, j$2));\n              pos = j$2;\n            } else { ++j$2; }\n          }\n          if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }\n        }\n      }\n      if (direction == \"ltr\") {\n        if (order[0].level == 1 && (m = str.match(/^\\s+/))) {\n          order[0].from = m[0].length;\n          order.unshift(new BidiSpan(0, 0, m[0].length));\n        }\n        if (lst(order).level == 1 && (m = str.match(/\\s+$/))) {\n          lst(order).to -= m[0].length;\n          order.push(new BidiSpan(0, len - m[0].length, len));\n        }\n      }\n\n      return direction == \"rtl\" ? order.reverse() : order\n    }\n  })();\n\n  // Get the bidi ordering for the given line (and cache it). Returns\n  // false for lines that are fully left-to-right, and an array of\n  // BidiSpan objects otherwise.\n  function getOrder(line, direction) {\n    var order = line.order;\n    if (order == null) { order = line.order = bidiOrdering(line.text, direction); }\n    return order\n  }\n\n  // EVENT HANDLING\n\n  // Lightweight event framework. on/off also work on DOM nodes,\n  // registering native DOM handlers.\n\n  var noHandlers = [];\n\n  var on = function(emitter, type, f) {\n    if (emitter.addEventListener) {\n      emitter.addEventListener(type, f, false);\n    } else if (emitter.attachEvent) {\n      emitter.attachEvent(\"on\" + type, f);\n    } else {\n      var map$$1 = emitter._handlers || (emitter._handlers = {});\n      map$$1[type] = (map$$1[type] || noHandlers).concat(f);\n    }\n  };\n\n  function getHandlers(emitter, type) {\n    return emitter._handlers && emitter._handlers[type] || noHandlers\n  }\n\n  function off(emitter, type, f) {\n    if (emitter.removeEventListener) {\n      emitter.removeEventListener(type, f, false);\n    } else if (emitter.detachEvent) {\n      emitter.detachEvent(\"on\" + type, f);\n    } else {\n      var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];\n      if (arr) {\n        var index = indexOf(arr, f);\n        if (index > -1)\n          { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }\n      }\n    }\n  }\n\n  function signal(emitter, type /*, values...*/) {\n    var handlers = getHandlers(emitter, type);\n    if (!handlers.length) { return }\n    var args = Array.prototype.slice.call(arguments, 2);\n    for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }\n  }\n\n  // The DOM events that CodeMirror handles can be overridden by\n  // registering a (non-DOM) handler on the editor for the event name,\n  // and preventDefault-ing the event in that handler.\n  function signalDOMEvent(cm, e, override) {\n    if (typeof e == \"string\")\n      { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }\n    signal(cm, override || e.type, cm, e);\n    return e_defaultPrevented(e) || e.codemirrorIgnore\n  }\n\n  function signalCursorActivity(cm) {\n    var arr = cm._handlers && cm._handlers.cursorActivity;\n    if (!arr) { return }\n    var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);\n    for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)\n      { set.push(arr[i]); } }\n  }\n\n  function hasHandler(emitter, type) {\n    return getHandlers(emitter, type).length > 0\n  }\n\n  // Add on and off methods to a constructor's prototype, to make\n  // registering events on such objects more convenient.\n  function eventMixin(ctor) {\n    ctor.prototype.on = function(type, f) {on(this, type, f);};\n    ctor.prototype.off = function(type, f) {off(this, type, f);};\n  }\n\n  // Due to the fact that we still support jurassic IE versions, some\n  // compatibility wrappers are needed.\n\n  function e_preventDefault(e) {\n    if (e.preventDefault) { e.preventDefault(); }\n    else { e.returnValue = false; }\n  }\n  function e_stopPropagation(e) {\n    if (e.stopPropagation) { e.stopPropagation(); }\n    else { e.cancelBubble = true; }\n  }\n  function e_defaultPrevented(e) {\n    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false\n  }\n  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}\n\n  function e_target(e) {return e.target || e.srcElement}\n  function e_button(e) {\n    var b = e.which;\n    if (b == null) {\n      if (e.button & 1) { b = 1; }\n      else if (e.button & 2) { b = 3; }\n      else if (e.button & 4) { b = 2; }\n    }\n    if (mac && e.ctrlKey && b == 1) { b = 3; }\n    return b\n  }\n\n  // Detect drag-and-drop\n  var dragAndDrop = function() {\n    // There is *some* kind of drag-and-drop support in IE6-8, but I\n    // couldn't get it to work yet.\n    if (ie && ie_version < 9) { return false }\n    var div = elt('div');\n    return \"draggable\" in div || \"dragDrop\" in div\n  }();\n\n  var zwspSupported;\n  function zeroWidthElement(measure) {\n    if (zwspSupported == null) {\n      var test = elt(\"span\", \"\\u200b\");\n      removeChildrenAndAdd(measure, elt(\"span\", [test, document.createTextNode(\"x\")]));\n      if (measure.firstChild.offsetHeight != 0)\n        { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }\n    }\n    var node = zwspSupported ? elt(\"span\", \"\\u200b\") :\n      elt(\"span\", \"\\u00a0\", null, \"display: inline-block; width: 1px; margin-right: -1px\");\n    node.setAttribute(\"cm-text\", \"\");\n    return node\n  }\n\n  // Feature-detect IE's crummy client rect reporting for bidi text\n  var badBidiRects;\n  function hasBadBidiRects(measure) {\n    if (badBidiRects != null) { return badBidiRects }\n    var txt = removeChildrenAndAdd(measure, document.createTextNode(\"A\\u062eA\"));\n    var r0 = range(txt, 0, 1).getBoundingClientRect();\n    var r1 = range(txt, 1, 2).getBoundingClientRect();\n    removeChildren(measure);\n    if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)\n    return badBidiRects = (r1.right - r0.right < 3)\n  }\n\n  // See if \"\".split is the broken IE version, if so, provide an\n  // alternative way to split lines.\n  var splitLinesAuto = \"\\n\\nb\".split(/\\n/).length != 3 ? function (string) {\n    var pos = 0, result = [], l = string.length;\n    while (pos <= l) {\n      var nl = string.indexOf(\"\\n\", pos);\n      if (nl == -1) { nl = string.length; }\n      var line = string.slice(pos, string.charAt(nl - 1) == \"\\r\" ? nl - 1 : nl);\n      var rt = line.indexOf(\"\\r\");\n      if (rt != -1) {\n        result.push(line.slice(0, rt));\n        pos += rt + 1;\n      } else {\n        result.push(line);\n        pos = nl + 1;\n      }\n    }\n    return result\n  } : function (string) { return string.split(/\\r\\n?|\\n/); };\n\n  var hasSelection = window.getSelection ? function (te) {\n    try { return te.selectionStart != te.selectionEnd }\n    catch(e) { return false }\n  } : function (te) {\n    var range$$1;\n    try {range$$1 = te.ownerDocument.selection.createRange();}\n    catch(e) {}\n    if (!range$$1 || range$$1.parentElement() != te) { return false }\n    return range$$1.compareEndPoints(\"StartToEnd\", range$$1) != 0\n  };\n\n  var hasCopyEvent = (function () {\n    var e = elt(\"div\");\n    if (\"oncopy\" in e) { return true }\n    e.setAttribute(\"oncopy\", \"return;\");\n    return typeof e.oncopy == \"function\"\n  })();\n\n  var badZoomedRects = null;\n  function hasBadZoomedRects(measure) {\n    if (badZoomedRects != null) { return badZoomedRects }\n    var node = removeChildrenAndAdd(measure, elt(\"span\", \"x\"));\n    var normal = node.getBoundingClientRect();\n    var fromRange = range(node, 0, 1).getBoundingClientRect();\n    return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1\n  }\n\n  // Known modes, by name and by MIME\n  var modes = {}, mimeModes = {};\n\n  // Extra arguments are stored as the mode's dependencies, which is\n  // used by (legacy) mechanisms like loadmode.js to automatically\n  // load a mode. (Preferred mechanism is the require/define calls.)\n  function defineMode(name, mode) {\n    if (arguments.length > 2)\n      { mode.dependencies = Array.prototype.slice.call(arguments, 2); }\n    modes[name] = mode;\n  }\n\n  function defineMIME(mime, spec) {\n    mimeModes[mime] = spec;\n  }\n\n  // Given a MIME type, a {name, ...options} config object, or a name\n  // string, return a mode config object.\n  function resolveMode(spec) {\n    if (typeof spec == \"string\" && mimeModes.hasOwnProperty(spec)) {\n      spec = mimeModes[spec];\n    } else if (spec && typeof spec.name == \"string\" && mimeModes.hasOwnProperty(spec.name)) {\n      var found = mimeModes[spec.name];\n      if (typeof found == \"string\") { found = {name: found}; }\n      spec = createObj(found, spec);\n      spec.name = found.name;\n    } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+xml$/.test(spec)) {\n      return resolveMode(\"application/xml\")\n    } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+json$/.test(spec)) {\n      return resolveMode(\"application/json\")\n    }\n    if (typeof spec == \"string\") { return {name: spec} }\n    else { return spec || {name: \"null\"} }\n  }\n\n  // Given a mode spec (anything that resolveMode accepts), find and\n  // initialize an actual mode object.\n  function getMode(options, spec) {\n    spec = resolveMode(spec);\n    var mfactory = modes[spec.name];\n    if (!mfactory) { return getMode(options, \"text/plain\") }\n    var modeObj = mfactory(options, spec);\n    if (modeExtensions.hasOwnProperty(spec.name)) {\n      var exts = modeExtensions[spec.name];\n      for (var prop in exts) {\n        if (!exts.hasOwnProperty(prop)) { continue }\n        if (modeObj.hasOwnProperty(prop)) { modeObj[\"_\" + prop] = modeObj[prop]; }\n        modeObj[prop] = exts[prop];\n      }\n    }\n    modeObj.name = spec.name;\n    if (spec.helperType) { modeObj.helperType = spec.helperType; }\n    if (spec.modeProps) { for (var prop$1 in spec.modeProps)\n      { modeObj[prop$1] = spec.modeProps[prop$1]; } }\n\n    return modeObj\n  }\n\n  // This can be used to attach properties to mode objects from\n  // outside the actual mode definition.\n  var modeExtensions = {};\n  function extendMode(mode, properties) {\n    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});\n    copyObj(properties, exts);\n  }\n\n  function copyState(mode, state) {\n    if (state === true) { return state }\n    if (mode.copyState) { return mode.copyState(state) }\n    var nstate = {};\n    for (var n in state) {\n      var val = state[n];\n      if (val instanceof Array) { val = val.concat([]); }\n      nstate[n] = val;\n    }\n    return nstate\n  }\n\n  // Given a mode and a state (for that mode), find the inner mode and\n  // state at the position that the state refers to.\n  function innerMode(mode, state) {\n    var info;\n    while (mode.innerMode) {\n      info = mode.innerMode(state);\n      if (!info || info.mode == mode) { break }\n      state = info.state;\n      mode = info.mode;\n    }\n    return info || {mode: mode, state: state}\n  }\n\n  function startState(mode, a1, a2) {\n    return mode.startState ? mode.startState(a1, a2) : true\n  }\n\n  // STRING STREAM\n\n  // Fed to the mode parsers, provides helper functions to make\n  // parsers more succinct.\n\n  var StringStream = function(string, tabSize, lineOracle) {\n    this.pos = this.start = 0;\n    this.string = string;\n    this.tabSize = tabSize || 8;\n    this.lastColumnPos = this.lastColumnValue = 0;\n    this.lineStart = 0;\n    this.lineOracle = lineOracle;\n  };\n\n  StringStream.prototype.eol = function () {return this.pos >= this.string.length};\n  StringStream.prototype.sol = function () {return this.pos == this.lineStart};\n  StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};\n  StringStream.prototype.next = function () {\n    if (this.pos < this.string.length)\n      { return this.string.charAt(this.pos++) }\n  };\n  StringStream.prototype.eat = function (match) {\n    var ch = this.string.charAt(this.pos);\n    var ok;\n    if (typeof match == \"string\") { ok = ch == match; }\n    else { ok = ch && (match.test ? match.test(ch) : match(ch)); }\n    if (ok) {++this.pos; return ch}\n  };\n  StringStream.prototype.eatWhile = function (match) {\n    var start = this.pos;\n    while (this.eat(match)){}\n    return this.pos > start\n  };\n  StringStream.prototype.eatSpace = function () {\n      var this$1 = this;\n\n    var start = this.pos;\n    while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }\n    return this.pos > start\n  };\n  StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};\n  StringStream.prototype.skipTo = function (ch) {\n    var found = this.string.indexOf(ch, this.pos);\n    if (found > -1) {this.pos = found; return true}\n  };\n  StringStream.prototype.backUp = function (n) {this.pos -= n;};\n  StringStream.prototype.column = function () {\n    if (this.lastColumnPos < this.start) {\n      this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);\n      this.lastColumnPos = this.start;\n    }\n    return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n  };\n  StringStream.prototype.indentation = function () {\n    return countColumn(this.string, null, this.tabSize) -\n      (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n  };\n  StringStream.prototype.match = function (pattern, consume, caseInsensitive) {\n    if (typeof pattern == \"string\") {\n      var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };\n      var substr = this.string.substr(this.pos, pattern.length);\n      if (cased(substr) == cased(pattern)) {\n        if (consume !== false) { this.pos += pattern.length; }\n        return true\n      }\n    } else {\n      var match = this.string.slice(this.pos).match(pattern);\n      if (match && match.index > 0) { return null }\n      if (match && consume !== false) { this.pos += match[0].length; }\n      return match\n    }\n  };\n  StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};\n  StringStream.prototype.hideFirstChars = function (n, inner) {\n    this.lineStart += n;\n    try { return inner() }\n    finally { this.lineStart -= n; }\n  };\n  StringStream.prototype.lookAhead = function (n) {\n    var oracle = this.lineOracle;\n    return oracle && oracle.lookAhead(n)\n  };\n  StringStream.prototype.baseToken = function () {\n    var oracle = this.lineOracle;\n    return oracle && oracle.baseToken(this.pos)\n  };\n\n  var SavedContext = function(state, lookAhead) {\n    this.state = state;\n    this.lookAhead = lookAhead;\n  };\n\n  var Context = function(doc, state, line, lookAhead) {\n    this.state = state;\n    this.doc = doc;\n    this.line = line;\n    this.maxLookAhead = lookAhead || 0;\n    this.baseTokens = null;\n    this.baseTokenPos = 1;\n  };\n\n  Context.prototype.lookAhead = function (n) {\n    var line = this.doc.getLine(this.line + n);\n    if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }\n    return line\n  };\n\n  Context.prototype.baseToken = function (n) {\n      var this$1 = this;\n\n    if (!this.baseTokens) { return null }\n    while (this.baseTokens[this.baseTokenPos] <= n)\n      { this$1.baseTokenPos += 2; }\n    var type = this.baseTokens[this.baseTokenPos + 1];\n    return {type: type && type.replace(/( |^)overlay .*/, \"\"),\n            size: this.baseTokens[this.baseTokenPos] - n}\n  };\n\n  Context.prototype.nextLine = function () {\n    this.line++;\n    if (this.maxLookAhead > 0) { this.maxLookAhead--; }\n  };\n\n  Context.fromSaved = function (doc, saved, line) {\n    if (saved instanceof SavedContext)\n      { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }\n    else\n      { return new Context(doc, copyState(doc.mode, saved), line) }\n  };\n\n  Context.prototype.save = function (copy) {\n    var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;\n    return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state\n  };\n\n\n  // Compute a style array (an array starting with a mode generation\n  // -- for invalidation -- followed by pairs of end positions and\n  // style strings), which is used to highlight the tokens on the\n  // line.\n  function highlightLine(cm, line, context, forceToEnd) {\n    // A styles array always starts with a number identifying the\n    // mode/overlays that it is based on (for easy invalidation).\n    var st = [cm.state.modeGen], lineClasses = {};\n    // Compute the base array of styles\n    runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },\n            lineClasses, forceToEnd);\n    var state = context.state;\n\n    // Run overlays, adjust style array.\n    var loop = function ( o ) {\n      context.baseTokens = st;\n      var overlay = cm.state.overlays[o], i = 1, at = 0;\n      context.state = true;\n      runMode(cm, line.text, overlay.mode, context, function (end, style) {\n        var start = i;\n        // Ensure there's a token end at the current position, and that i points at it\n        while (at < end) {\n          var i_end = st[i];\n          if (i_end > end)\n            { st.splice(i, 1, end, st[i+1], i_end); }\n          i += 2;\n          at = Math.min(end, i_end);\n        }\n        if (!style) { return }\n        if (overlay.opaque) {\n          st.splice(start, i - start, end, \"overlay \" + style);\n          i = start + 2;\n        } else {\n          for (; start < i; start += 2) {\n            var cur = st[start+1];\n            st[start+1] = (cur ? cur + \" \" : \"\") + \"overlay \" + style;\n          }\n        }\n      }, lineClasses);\n      context.state = state;\n      context.baseTokens = null;\n      context.baseTokenPos = 1;\n    };\n\n    for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );\n\n    return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}\n  }\n\n  function getLineStyles(cm, line, updateFrontier) {\n    if (!line.styles || line.styles[0] != cm.state.modeGen) {\n      var context = getContextBefore(cm, lineNo(line));\n      var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);\n      var result = highlightLine(cm, line, context);\n      if (resetState) { context.state = resetState; }\n      line.stateAfter = context.save(!resetState);\n      line.styles = result.styles;\n      if (result.classes) { line.styleClasses = result.classes; }\n      else if (line.styleClasses) { line.styleClasses = null; }\n      if (updateFrontier === cm.doc.highlightFrontier)\n        { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }\n    }\n    return line.styles\n  }\n\n  function getContextBefore(cm, n, precise) {\n    var doc = cm.doc, display = cm.display;\n    if (!doc.mode.startState) { return new Context(doc, true, n) }\n    var start = findStartLine(cm, n, precise);\n    var saved = start > doc.first && getLine(doc, start - 1).stateAfter;\n    var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);\n\n    doc.iter(start, n, function (line) {\n      processLine(cm, line.text, context);\n      var pos = context.line;\n      line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;\n      context.nextLine();\n    });\n    if (precise) { doc.modeFrontier = context.line; }\n    return context\n  }\n\n  // Lightweight form of highlight -- proceed over this line and\n  // update state, but don't save a style array. Used for lines that\n  // aren't currently visible.\n  function processLine(cm, text, context, startAt) {\n    var mode = cm.doc.mode;\n    var stream = new StringStream(text, cm.options.tabSize, context);\n    stream.start = stream.pos = startAt || 0;\n    if (text == \"\") { callBlankLine(mode, context.state); }\n    while (!stream.eol()) {\n      readToken(mode, stream, context.state);\n      stream.start = stream.pos;\n    }\n  }\n\n  function callBlankLine(mode, state) {\n    if (mode.blankLine) { return mode.blankLine(state) }\n    if (!mode.innerMode) { return }\n    var inner = innerMode(mode, state);\n    if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }\n  }\n\n  function readToken(mode, stream, state, inner) {\n    for (var i = 0; i < 10; i++) {\n      if (inner) { inner[0] = innerMode(mode, state).mode; }\n      var style = mode.token(stream, state);\n      if (stream.pos > stream.start) { return style }\n    }\n    throw new Error(\"Mode \" + mode.name + \" failed to advance stream.\")\n  }\n\n  var Token = function(stream, type, state) {\n    this.start = stream.start; this.end = stream.pos;\n    this.string = stream.current();\n    this.type = type || null;\n    this.state = state;\n  };\n\n  // Utility for getTokenAt and getLineTokens\n  function takeToken(cm, pos, precise, asArray) {\n    var doc = cm.doc, mode = doc.mode, style;\n    pos = clipPos(doc, pos);\n    var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);\n    var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;\n    if (asArray) { tokens = []; }\n    while ((asArray || stream.pos < pos.ch) && !stream.eol()) {\n      stream.start = stream.pos;\n      style = readToken(mode, stream, context.state);\n      if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }\n    }\n    return asArray ? tokens : new Token(stream, style, context.state)\n  }\n\n  function extractLineClasses(type, output) {\n    if (type) { for (;;) {\n      var lineClass = type.match(/(?:^|\\s+)line-(background-)?(\\S+)/);\n      if (!lineClass) { break }\n      type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);\n      var prop = lineClass[1] ? \"bgClass\" : \"textClass\";\n      if (output[prop] == null)\n        { output[prop] = lineClass[2]; }\n      else if (!(new RegExp(\"(?:^|\\s)\" + lineClass[2] + \"(?:$|\\s)\")).test(output[prop]))\n        { output[prop] += \" \" + lineClass[2]; }\n    } }\n    return type\n  }\n\n  // Run the given mode's parser over a line, calling f for each token.\n  function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {\n    var flattenSpans = mode.flattenSpans;\n    if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }\n    var curStart = 0, curStyle = null;\n    var stream = new StringStream(text, cm.options.tabSize, context), style;\n    var inner = cm.options.addModeClass && [null];\n    if (text == \"\") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }\n    while (!stream.eol()) {\n      if (stream.pos > cm.options.maxHighlightLength) {\n        flattenSpans = false;\n        if (forceToEnd) { processLine(cm, text, context, stream.pos); }\n        stream.pos = text.length;\n        style = null;\n      } else {\n        style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);\n      }\n      if (inner) {\n        var mName = inner[0].name;\n        if (mName) { style = \"m-\" + (style ? mName + \" \" + style : mName); }\n      }\n      if (!flattenSpans || curStyle != style) {\n        while (curStart < stream.start) {\n          curStart = Math.min(stream.start, curStart + 5000);\n          f(curStart, curStyle);\n        }\n        curStyle = style;\n      }\n      stream.start = stream.pos;\n    }\n    while (curStart < stream.pos) {\n      // Webkit seems to refuse to render text nodes longer than 57444\n      // characters, and returns inaccurate measurements in nodes\n      // starting around 5000 chars.\n      var pos = Math.min(stream.pos, curStart + 5000);\n      f(pos, curStyle);\n      curStart = pos;\n    }\n  }\n\n  // Finds the line to start with when starting a parse. Tries to\n  // find a line with a stateAfter, so that it can start with a\n  // valid state. If that fails, it returns the line with the\n  // smallest indentation, which tends to need the least context to\n  // parse correctly.\n  function findStartLine(cm, n, precise) {\n    var minindent, minline, doc = cm.doc;\n    var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);\n    for (var search = n; search > lim; --search) {\n      if (search <= doc.first) { return doc.first }\n      var line = getLine(doc, search - 1), after = line.stateAfter;\n      if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))\n        { return search }\n      var indented = countColumn(line.text, null, cm.options.tabSize);\n      if (minline == null || minindent > indented) {\n        minline = search - 1;\n        minindent = indented;\n      }\n    }\n    return minline\n  }\n\n  function retreatFrontier(doc, n) {\n    doc.modeFrontier = Math.min(doc.modeFrontier, n);\n    if (doc.highlightFrontier < n - 10) { return }\n    var start = doc.first;\n    for (var line = n - 1; line > start; line--) {\n      var saved = getLine(doc, line).stateAfter;\n      // change is on 3\n      // state on line 1 looked ahead 2 -- so saw 3\n      // test 1 + 2 < 3 should cover this\n      if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {\n        start = line + 1;\n        break\n      }\n    }\n    doc.highlightFrontier = Math.min(doc.highlightFrontier, start);\n  }\n\n  // LINE DATA STRUCTURE\n\n  // Line objects. These hold state related to a line, including\n  // highlighting info (the styles array).\n  var Line = function(text, markedSpans, estimateHeight) {\n    this.text = text;\n    attachMarkedSpans(this, markedSpans);\n    this.height = estimateHeight ? estimateHeight(this) : 1;\n  };\n\n  Line.prototype.lineNo = function () { return lineNo(this) };\n  eventMixin(Line);\n\n  // Change the content (text, markers) of a line. Automatically\n  // invalidates cached information and tries to re-estimate the\n  // line's height.\n  function updateLine(line, text, markedSpans, estimateHeight) {\n    line.text = text;\n    if (line.stateAfter) { line.stateAfter = null; }\n    if (line.styles) { line.styles = null; }\n    if (line.order != null) { line.order = null; }\n    detachMarkedSpans(line);\n    attachMarkedSpans(line, markedSpans);\n    var estHeight = estimateHeight ? estimateHeight(line) : 1;\n    if (estHeight != line.height) { updateLineHeight(line, estHeight); }\n  }\n\n  // Detach a line from the document tree and its markers.\n  function cleanUpLine(line) {\n    line.parent = null;\n    detachMarkedSpans(line);\n  }\n\n  // Convert a style as returned by a mode (either null, or a string\n  // containing one or more styles) to a CSS style. This is cached,\n  // and also looks for line-wide styles.\n  var styleToClassCache = {}, styleToClassCacheWithMode = {};\n  function interpretTokenStyle(style, options) {\n    if (!style || /^\\s*$/.test(style)) { return null }\n    var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;\n    return cache[style] ||\n      (cache[style] = style.replace(/\\S+/g, \"cm-$&\"))\n  }\n\n  // Render the DOM representation of the text of a line. Also builds\n  // up a 'line map', which points at the DOM nodes that represent\n  // specific stretches of text, and is used by the measuring code.\n  // The returned object contains the DOM node, this map, and\n  // information about line-wide styles that were set by the mode.\n  function buildLineContent(cm, lineView) {\n    // The padding-right forces the element to have a 'border', which\n    // is needed on Webkit to be able to get line-level bounding\n    // rectangles for it (in measureChar).\n    var content = eltP(\"span\", null, null, webkit ? \"padding-right: .1px\" : null);\n    var builder = {pre: eltP(\"pre\", [content], \"CodeMirror-line\"), content: content,\n                   col: 0, pos: 0, cm: cm,\n                   trailingSpace: false,\n                   splitSpaces: cm.getOption(\"lineWrapping\")};\n    lineView.measure = {};\n\n    // Iterate over the logical lines that make up this visual line.\n    for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {\n      var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);\n      builder.pos = 0;\n      builder.addToken = buildToken;\n      // Optionally wire in some hacks into the token-rendering\n      // algorithm, to deal with browser quirks.\n      if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))\n        { builder.addToken = buildTokenBadBidi(builder.addToken, order); }\n      builder.map = [];\n      var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);\n      insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));\n      if (line.styleClasses) {\n        if (line.styleClasses.bgClass)\n          { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || \"\"); }\n        if (line.styleClasses.textClass)\n          { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || \"\"); }\n      }\n\n      // Ensure at least a single node is present, for measuring.\n      if (builder.map.length == 0)\n        { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }\n\n      // Store the map and a cache object for the current logical line\n      if (i == 0) {\n        lineView.measure.map = builder.map;\n        lineView.measure.cache = {};\n      } else {\n  (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)\n        ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});\n      }\n    }\n\n    // See issue #2901\n    if (webkit) {\n      var last = builder.content.lastChild;\n      if (/\\bcm-tab\\b/.test(last.className) || (last.querySelector && last.querySelector(\".cm-tab\")))\n        { builder.content.className = \"cm-tab-wrap-hack\"; }\n    }\n\n    signal(cm, \"renderLine\", cm, lineView.line, builder.pre);\n    if (builder.pre.className)\n      { builder.textClass = joinClasses(builder.pre.className, builder.textClass || \"\"); }\n\n    return builder\n  }\n\n  function defaultSpecialCharPlaceholder(ch) {\n    var token = elt(\"span\", \"\\u2022\", \"cm-invalidchar\");\n    token.title = \"\\\\u\" + ch.charCodeAt(0).toString(16);\n    token.setAttribute(\"aria-label\", token.title);\n    return token\n  }\n\n  // Build up the DOM representation for a single token, and add it to\n  // the line map. Takes care to render special characters separately.\n  function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {\n    if (!text) { return }\n    var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;\n    var special = builder.cm.state.specialChars, mustWrap = false;\n    var content;\n    if (!special.test(text)) {\n      builder.col += text.length;\n      content = document.createTextNode(displayText);\n      builder.map.push(builder.pos, builder.pos + text.length, content);\n      if (ie && ie_version < 9) { mustWrap = true; }\n      builder.pos += text.length;\n    } else {\n      content = document.createDocumentFragment();\n      var pos = 0;\n      while (true) {\n        special.lastIndex = pos;\n        var m = special.exec(text);\n        var skipped = m ? m.index - pos : text.length - pos;\n        if (skipped) {\n          var txt = document.createTextNode(displayText.slice(pos, pos + skipped));\n          if (ie && ie_version < 9) { content.appendChild(elt(\"span\", [txt])); }\n          else { content.appendChild(txt); }\n          builder.map.push(builder.pos, builder.pos + skipped, txt);\n          builder.col += skipped;\n          builder.pos += skipped;\n        }\n        if (!m) { break }\n        pos += skipped + 1;\n        var txt$1 = (void 0);\n        if (m[0] == \"\\t\") {\n          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;\n          txt$1 = content.appendChild(elt(\"span\", spaceStr(tabWidth), \"cm-tab\"));\n          txt$1.setAttribute(\"role\", \"presentation\");\n          txt$1.setAttribute(\"cm-text\", \"\\t\");\n          builder.col += tabWidth;\n        } else if (m[0] == \"\\r\" || m[0] == \"\\n\") {\n          txt$1 = content.appendChild(elt(\"span\", m[0] == \"\\r\" ? \"\\u240d\" : \"\\u2424\", \"cm-invalidchar\"));\n          txt$1.setAttribute(\"cm-text\", m[0]);\n          builder.col += 1;\n        } else {\n          txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);\n          txt$1.setAttribute(\"cm-text\", m[0]);\n          if (ie && ie_version < 9) { content.appendChild(elt(\"span\", [txt$1])); }\n          else { content.appendChild(txt$1); }\n          builder.col += 1;\n        }\n        builder.map.push(builder.pos, builder.pos + 1, txt$1);\n        builder.pos++;\n      }\n    }\n    builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;\n    if (style || startStyle || endStyle || mustWrap || css) {\n      var fullStyle = style || \"\";\n      if (startStyle) { fullStyle += startStyle; }\n      if (endStyle) { fullStyle += endStyle; }\n      var token = elt(\"span\", [content], fullStyle, css);\n      if (attributes) {\n        for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != \"style\" && attr != \"class\")\n          { token.setAttribute(attr, attributes[attr]); } }\n      }\n      return builder.content.appendChild(token)\n    }\n    builder.content.appendChild(content);\n  }\n\n  // Change some spaces to NBSP to prevent the browser from collapsing\n  // trailing spaces at the end of a line when rendering text (issue #1362).\n  function splitSpaces(text, trailingBefore) {\n    if (text.length > 1 && !/  /.test(text)) { return text }\n    var spaceBefore = trailingBefore, result = \"\";\n    for (var i = 0; i < text.length; i++) {\n      var ch = text.charAt(i);\n      if (ch == \" \" && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))\n        { ch = \"\\u00a0\"; }\n      result += ch;\n      spaceBefore = ch == \" \";\n    }\n    return result\n  }\n\n  // Work around nonsense dimensions being reported for stretches of\n  // right-to-left text.\n  function buildTokenBadBidi(inner, order) {\n    return function (builder, text, style, startStyle, endStyle, css, attributes) {\n      style = style ? style + \" cm-force-border\" : \"cm-force-border\";\n      var start = builder.pos, end = start + text.length;\n      for (;;) {\n        // Find the part that overlaps with the start of this text\n        var part = (void 0);\n        for (var i = 0; i < order.length; i++) {\n          part = order[i];\n          if (part.to > start && part.from <= start) { break }\n        }\n        if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }\n        inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);\n        startStyle = null;\n        text = text.slice(part.to - start);\n        start = part.to;\n      }\n    }\n  }\n\n  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {\n    var widget = !ignoreWidget && marker.widgetNode;\n    if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }\n    if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {\n      if (!widget)\n        { widget = builder.content.appendChild(document.createElement(\"span\")); }\n      widget.setAttribute(\"cm-marker\", marker.id);\n    }\n    if (widget) {\n      builder.cm.display.input.setUneditable(widget);\n      builder.content.appendChild(widget);\n    }\n    builder.pos += size;\n    builder.trailingSpace = false;\n  }\n\n  // Outputs a number of spans to make up a line, taking highlighting\n  // and marked text into account.\n  function insertLineContent(line, builder, styles) {\n    var spans = line.markedSpans, allText = line.text, at = 0;\n    if (!spans) {\n      for (var i$1 = 1; i$1 < styles.length; i$1+=2)\n        { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }\n      return\n    }\n\n    var len = allText.length, pos = 0, i = 1, text = \"\", style, css;\n    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;\n    for (;;) {\n      if (nextChange == pos) { // Update current marker set\n        spanStyle = spanEndStyle = spanStartStyle = css = \"\";\n        attributes = null;\n        collapsed = null; nextChange = Infinity;\n        var foundBookmarks = [], endStyles = (void 0);\n        for (var j = 0; j < spans.length; ++j) {\n          var sp = spans[j], m = sp.marker;\n          if (m.type == \"bookmark\" && sp.from == pos && m.widgetNode) {\n            foundBookmarks.push(m);\n          } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {\n            if (sp.to != null && sp.to != pos && nextChange > sp.to) {\n              nextChange = sp.to;\n              spanEndStyle = \"\";\n            }\n            if (m.className) { spanStyle += \" \" + m.className; }\n            if (m.css) { css = (css ? css + \";\" : \"\") + m.css; }\n            if (m.startStyle && sp.from == pos) { spanStartStyle += \" \" + m.startStyle; }\n            if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }\n            // support for the old title property\n            // https://github.com/codemirror/CodeMirror/pull/5673\n            if (m.title) { (attributes || (attributes = {})).title = m.title; }\n            if (m.attributes) {\n              for (var attr in m.attributes)\n                { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }\n            }\n            if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))\n              { collapsed = sp; }\n          } else if (sp.from > pos && nextChange > sp.from) {\n            nextChange = sp.from;\n          }\n        }\n        if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)\n          { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += \" \" + endStyles[j$1]; } } }\n\n        if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)\n          { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }\n        if (collapsed && (collapsed.from || 0) == pos) {\n          buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,\n                             collapsed.marker, collapsed.from == null);\n          if (collapsed.to == null) { return }\n          if (collapsed.to == pos) { collapsed = false; }\n        }\n      }\n      if (pos >= len) { break }\n\n      var upto = Math.min(len, nextChange);\n      while (true) {\n        if (text) {\n          var end = pos + text.length;\n          if (!collapsed) {\n            var tokenText = end > upto ? text.slice(0, upto - pos) : text;\n            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,\n                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : \"\", css, attributes);\n          }\n          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}\n          pos = end;\n          spanStartStyle = \"\";\n        }\n        text = allText.slice(at, at = styles[i++]);\n        style = interpretTokenStyle(styles[i++], builder.cm.options);\n      }\n    }\n  }\n\n\n  // These objects are used to represent the visible (currently drawn)\n  // part of the document. A LineView may correspond to multiple\n  // logical lines, if those are connected by collapsed ranges.\n  function LineView(doc, line, lineN) {\n    // The starting line\n    this.line = line;\n    // Continuing lines, if any\n    this.rest = visualLineContinued(line);\n    // Number of logical lines in this visual line\n    this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;\n    this.node = this.text = null;\n    this.hidden = lineIsHidden(doc, line);\n  }\n\n  // Create a range of LineView objects for the given lines.\n  function buildViewArray(cm, from, to) {\n    var array = [], nextPos;\n    for (var pos = from; pos < to; pos = nextPos) {\n      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);\n      nextPos = pos + view.size;\n      array.push(view);\n    }\n    return array\n  }\n\n  var operationGroup = null;\n\n  function pushOperation(op) {\n    if (operationGroup) {\n      operationGroup.ops.push(op);\n    } else {\n      op.ownsGroup = operationGroup = {\n        ops: [op],\n        delayedCallbacks: []\n      };\n    }\n  }\n\n  function fireCallbacksForOps(group) {\n    // Calls delayed callbacks and cursorActivity handlers until no\n    // new ones appear\n    var callbacks = group.delayedCallbacks, i = 0;\n    do {\n      for (; i < callbacks.length; i++)\n        { callbacks[i].call(null); }\n      for (var j = 0; j < group.ops.length; j++) {\n        var op = group.ops[j];\n        if (op.cursorActivityHandlers)\n          { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)\n            { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }\n      }\n    } while (i < callbacks.length)\n  }\n\n  function finishOperation(op, endCb) {\n    var group = op.ownsGroup;\n    if (!group) { return }\n\n    try { fireCallbacksForOps(group); }\n    finally {\n      operationGroup = null;\n      endCb(group);\n    }\n  }\n\n  var orphanDelayedCallbacks = null;\n\n  // Often, we want to signal events at a point where we are in the\n  // middle of some work, but don't want the handler to start calling\n  // other methods on the editor, which might be in an inconsistent\n  // state or simply not expect any other events to happen.\n  // signalLater looks whether there are any handlers, and schedules\n  // them to be executed when the last operation ends, or, if no\n  // operation is active, when a timeout fires.\n  function signalLater(emitter, type /*, values...*/) {\n    var arr = getHandlers(emitter, type);\n    if (!arr.length) { return }\n    var args = Array.prototype.slice.call(arguments, 2), list;\n    if (operationGroup) {\n      list = operationGroup.delayedCallbacks;\n    } else if (orphanDelayedCallbacks) {\n      list = orphanDelayedCallbacks;\n    } else {\n      list = orphanDelayedCallbacks = [];\n      setTimeout(fireOrphanDelayed, 0);\n    }\n    var loop = function ( i ) {\n      list.push(function () { return arr[i].apply(null, args); });\n    };\n\n    for (var i = 0; i < arr.length; ++i)\n      loop( i );\n  }\n\n  function fireOrphanDelayed() {\n    var delayed = orphanDelayedCallbacks;\n    orphanDelayedCallbacks = null;\n    for (var i = 0; i < delayed.length; ++i) { delayed[i](); }\n  }\n\n  // When an aspect of a line changes, a string is added to\n  // lineView.changes. This updates the relevant part of the line's\n  // DOM structure.\n  function updateLineForChanges(cm, lineView, lineN, dims) {\n    for (var j = 0; j < lineView.changes.length; j++) {\n      var type = lineView.changes[j];\n      if (type == \"text\") { updateLineText(cm, lineView); }\n      else if (type == \"gutter\") { updateLineGutter(cm, lineView, lineN, dims); }\n      else if (type == \"class\") { updateLineClasses(cm, lineView); }\n      else if (type == \"widget\") { updateLineWidgets(cm, lineView, dims); }\n    }\n    lineView.changes = null;\n  }\n\n  // Lines with gutter elements, widgets or a background class need to\n  // be wrapped, and have the extra elements added to the wrapper div\n  function ensureLineWrapped(lineView) {\n    if (lineView.node == lineView.text) {\n      lineView.node = elt(\"div\", null, null, \"position: relative\");\n      if (lineView.text.parentNode)\n        { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }\n      lineView.node.appendChild(lineView.text);\n      if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }\n    }\n    return lineView.node\n  }\n\n  function updateLineBackground(cm, lineView) {\n    var cls = lineView.bgClass ? lineView.bgClass + \" \" + (lineView.line.bgClass || \"\") : lineView.line.bgClass;\n    if (cls) { cls += \" CodeMirror-linebackground\"; }\n    if (lineView.background) {\n      if (cls) { lineView.background.className = cls; }\n      else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }\n    } else if (cls) {\n      var wrap = ensureLineWrapped(lineView);\n      lineView.background = wrap.insertBefore(elt(\"div\", null, cls), wrap.firstChild);\n      cm.display.input.setUneditable(lineView.background);\n    }\n  }\n\n  // Wrapper around buildLineContent which will reuse the structure\n  // in display.externalMeasured when possible.\n  function getLineContent(cm, lineView) {\n    var ext = cm.display.externalMeasured;\n    if (ext && ext.line == lineView.line) {\n      cm.display.externalMeasured = null;\n      lineView.measure = ext.measure;\n      return ext.built\n    }\n    return buildLineContent(cm, lineView)\n  }\n\n  // Redraw the line's text. Interacts with the background and text\n  // classes because the mode may output tokens that influence these\n  // classes.\n  function updateLineText(cm, lineView) {\n    var cls = lineView.text.className;\n    var built = getLineContent(cm, lineView);\n    if (lineView.text == lineView.node) { lineView.node = built.pre; }\n    lineView.text.parentNode.replaceChild(built.pre, lineView.text);\n    lineView.text = built.pre;\n    if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {\n      lineView.bgClass = built.bgClass;\n      lineView.textClass = built.textClass;\n      updateLineClasses(cm, lineView);\n    } else if (cls) {\n      lineView.text.className = cls;\n    }\n  }\n\n  function updateLineClasses(cm, lineView) {\n    updateLineBackground(cm, lineView);\n    if (lineView.line.wrapClass)\n      { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }\n    else if (lineView.node != lineView.text)\n      { lineView.node.className = \"\"; }\n    var textClass = lineView.textClass ? lineView.textClass + \" \" + (lineView.line.textClass || \"\") : lineView.line.textClass;\n    lineView.text.className = textClass || \"\";\n  }\n\n  function updateLineGutter(cm, lineView, lineN, dims) {\n    if (lineView.gutter) {\n      lineView.node.removeChild(lineView.gutter);\n      lineView.gutter = null;\n    }\n    if (lineView.gutterBackground) {\n      lineView.node.removeChild(lineView.gutterBackground);\n      lineView.gutterBackground = null;\n    }\n    if (lineView.line.gutterClass) {\n      var wrap = ensureLineWrapped(lineView);\n      lineView.gutterBackground = elt(\"div\", null, \"CodeMirror-gutter-background \" + lineView.line.gutterClass,\n                                      (\"left: \" + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + \"px; width: \" + (dims.gutterTotalWidth) + \"px\"));\n      cm.display.input.setUneditable(lineView.gutterBackground);\n      wrap.insertBefore(lineView.gutterBackground, lineView.text);\n    }\n    var markers = lineView.line.gutterMarkers;\n    if (cm.options.lineNumbers || markers) {\n      var wrap$1 = ensureLineWrapped(lineView);\n      var gutterWrap = lineView.gutter = elt(\"div\", null, \"CodeMirror-gutter-wrapper\", (\"left: \" + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + \"px\"));\n      cm.display.input.setUneditable(gutterWrap);\n      wrap$1.insertBefore(gutterWrap, lineView.text);\n      if (lineView.line.gutterClass)\n        { gutterWrap.className += \" \" + lineView.line.gutterClass; }\n      if (cm.options.lineNumbers && (!markers || !markers[\"CodeMirror-linenumbers\"]))\n        { lineView.lineNumber = gutterWrap.appendChild(\n          elt(\"div\", lineNumberFor(cm.options, lineN),\n              \"CodeMirror-linenumber CodeMirror-gutter-elt\",\n              (\"left: \" + (dims.gutterLeft[\"CodeMirror-linenumbers\"]) + \"px; width: \" + (cm.display.lineNumInnerWidth) + \"px\"))); }\n      if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {\n        var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];\n        if (found)\n          { gutterWrap.appendChild(elt(\"div\", [found], \"CodeMirror-gutter-elt\",\n                                     (\"left: \" + (dims.gutterLeft[id]) + \"px; width: \" + (dims.gutterWidth[id]) + \"px\"))); }\n      } }\n    }\n  }\n\n  function updateLineWidgets(cm, lineView, dims) {\n    if (lineView.alignable) { lineView.alignable = null; }\n    for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {\n      next = node.nextSibling;\n      if (node.className == \"CodeMirror-linewidget\")\n        { lineView.node.removeChild(node); }\n    }\n    insertLineWidgets(cm, lineView, dims);\n  }\n\n  // Build a line's DOM representation from scratch\n  function buildLineElement(cm, lineView, lineN, dims) {\n    var built = getLineContent(cm, lineView);\n    lineView.text = lineView.node = built.pre;\n    if (built.bgClass) { lineView.bgClass = built.bgClass; }\n    if (built.textClass) { lineView.textClass = built.textClass; }\n\n    updateLineClasses(cm, lineView);\n    updateLineGutter(cm, lineView, lineN, dims);\n    insertLineWidgets(cm, lineView, dims);\n    return lineView.node\n  }\n\n  // A lineView may contain multiple logical lines (when merged by\n  // collapsed spans). The widgets for all of them need to be drawn.\n  function insertLineWidgets(cm, lineView, dims) {\n    insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);\n    if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)\n      { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }\n  }\n\n  function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {\n    if (!line.widgets) { return }\n    var wrap = ensureLineWrapped(lineView);\n    for (var i = 0, ws = line.widgets; i < ws.length; ++i) {\n      var widget = ws[i], node = elt(\"div\", [widget.node], \"CodeMirror-linewidget\");\n      if (!widget.handleMouseEvents) { node.setAttribute(\"cm-ignore-events\", \"true\"); }\n      positionLineWidget(widget, node, lineView, dims);\n      cm.display.input.setUneditable(node);\n      if (allowAbove && widget.above)\n        { wrap.insertBefore(node, lineView.gutter || lineView.text); }\n      else\n        { wrap.appendChild(node); }\n      signalLater(widget, \"redraw\");\n    }\n  }\n\n  function positionLineWidget(widget, node, lineView, dims) {\n    if (widget.noHScroll) {\n  (lineView.alignable || (lineView.alignable = [])).push(node);\n      var width = dims.wrapperWidth;\n      node.style.left = dims.fixedPos + \"px\";\n      if (!widget.coverGutter) {\n        width -= dims.gutterTotalWidth;\n        node.style.paddingLeft = dims.gutterTotalWidth + \"px\";\n      }\n      node.style.width = width + \"px\";\n    }\n    if (widget.coverGutter) {\n      node.style.zIndex = 5;\n      node.style.position = \"relative\";\n      if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + \"px\"; }\n    }\n  }\n\n  function widgetHeight(widget) {\n    if (widget.height != null) { return widget.height }\n    var cm = widget.doc.cm;\n    if (!cm) { return 0 }\n    if (!contains(document.body, widget.node)) {\n      var parentStyle = \"position: relative;\";\n      if (widget.coverGutter)\n        { parentStyle += \"margin-left: -\" + cm.display.gutters.offsetWidth + \"px;\"; }\n      if (widget.noHScroll)\n        { parentStyle += \"width: \" + cm.display.wrapper.clientWidth + \"px;\"; }\n      removeChildrenAndAdd(cm.display.measure, elt(\"div\", [widget.node], null, parentStyle));\n    }\n    return widget.height = widget.node.parentNode.offsetHeight\n  }\n\n  // Return true when the given mouse event happened in a widget\n  function eventInWidget(display, e) {\n    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {\n      if (!n || (n.nodeType == 1 && n.getAttribute(\"cm-ignore-events\") == \"true\") ||\n          (n.parentNode == display.sizer && n != display.mover))\n        { return true }\n    }\n  }\n\n  // POSITION MEASUREMENT\n\n  function paddingTop(display) {return display.lineSpace.offsetTop}\n  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}\n  function paddingH(display) {\n    if (display.cachedPaddingH) { return display.cachedPaddingH }\n    var e = removeChildrenAndAdd(display.measure, elt(\"pre\", \"x\"));\n    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;\n    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};\n    if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }\n    return data\n  }\n\n  function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }\n  function displayWidth(cm) {\n    return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth\n  }\n  function displayHeight(cm) {\n    return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight\n  }\n\n  // Ensure the lineView.wrapping.heights array is populated. This is\n  // an array of bottom offsets for the lines that make up a drawn\n  // line. When lineWrapping is on, there might be more than one\n  // height.\n  function ensureLineHeights(cm, lineView, rect) {\n    var wrapping = cm.options.lineWrapping;\n    var curWidth = wrapping && displayWidth(cm);\n    if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {\n      var heights = lineView.measure.heights = [];\n      if (wrapping) {\n        lineView.measure.width = curWidth;\n        var rects = lineView.text.firstChild.getClientRects();\n        for (var i = 0; i < rects.length - 1; i++) {\n          var cur = rects[i], next = rects[i + 1];\n          if (Math.abs(cur.bottom - next.bottom) > 2)\n            { heights.push((cur.bottom + next.top) / 2 - rect.top); }\n        }\n      }\n      heights.push(rect.bottom - rect.top);\n    }\n  }\n\n  // Find a line map (mapping character offsets to text nodes) and a\n  // measurement cache for the given line number. (A line view might\n  // contain multiple lines when collapsed ranges are present.)\n  function mapFromLineView(lineView, line, lineN) {\n    if (lineView.line == line)\n      { return {map: lineView.measure.map, cache: lineView.measure.cache} }\n    for (var i = 0; i < lineView.rest.length; i++)\n      { if (lineView.rest[i] == line)\n        { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }\n    for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)\n      { if (lineNo(lineView.rest[i$1]) > lineN)\n        { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }\n  }\n\n  // Render a line into the hidden node display.externalMeasured. Used\n  // when measurement is needed for a line that's not in the viewport.\n  function updateExternalMeasurement(cm, line) {\n    line = visualLine(line);\n    var lineN = lineNo(line);\n    var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);\n    view.lineN = lineN;\n    var built = view.built = buildLineContent(cm, view);\n    view.text = built.pre;\n    removeChildrenAndAdd(cm.display.lineMeasure, built.pre);\n    return view\n  }\n\n  // Get a {top, bottom, left, right} box (in line-local coordinates)\n  // for a given character.\n  function measureChar(cm, line, ch, bias) {\n    return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)\n  }\n\n  // Find a line view that corresponds to the given line number.\n  function findViewForLine(cm, lineN) {\n    if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)\n      { return cm.display.view[findViewIndex(cm, lineN)] }\n    var ext = cm.display.externalMeasured;\n    if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)\n      { return ext }\n  }\n\n  // Measurement can be split in two steps, the set-up work that\n  // applies to the whole line, and the measurement of the actual\n  // character. Functions like coordsChar, that need to do a lot of\n  // measurements in a row, can thus ensure that the set-up work is\n  // only done once.\n  function prepareMeasureForLine(cm, line) {\n    var lineN = lineNo(line);\n    var view = findViewForLine(cm, lineN);\n    if (view && !view.text) {\n      view = null;\n    } else if (view && view.changes) {\n      updateLineForChanges(cm, view, lineN, getDimensions(cm));\n      cm.curOp.forceUpdate = true;\n    }\n    if (!view)\n      { view = updateExternalMeasurement(cm, line); }\n\n    var info = mapFromLineView(view, line, lineN);\n    return {\n      line: line, view: view, rect: null,\n      map: info.map, cache: info.cache, before: info.before,\n      hasHeights: false\n    }\n  }\n\n  // Given a prepared measurement object, measures the position of an\n  // actual character (or fetches it from the cache).\n  function measureCharPrepared(cm, prepared, ch, bias, varHeight) {\n    if (prepared.before) { ch = -1; }\n    var key = ch + (bias || \"\"), found;\n    if (prepared.cache.hasOwnProperty(key)) {\n      found = prepared.cache[key];\n    } else {\n      if (!prepared.rect)\n        { prepared.rect = prepared.view.text.getBoundingClientRect(); }\n      if (!prepared.hasHeights) {\n        ensureLineHeights(cm, prepared.view, prepared.rect);\n        prepared.hasHeights = true;\n      }\n      found = measureCharInner(cm, prepared, ch, bias);\n      if (!found.bogus) { prepared.cache[key] = found; }\n    }\n    return {left: found.left, right: found.right,\n            top: varHeight ? found.rtop : found.top,\n            bottom: varHeight ? found.rbottom : found.bottom}\n  }\n\n  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};\n\n  function nodeAndOffsetInLineMap(map$$1, ch, bias) {\n    var node, start, end, collapse, mStart, mEnd;\n    // First, search the line map for the text node corresponding to,\n    // or closest to, the target character.\n    for (var i = 0; i < map$$1.length; i += 3) {\n      mStart = map$$1[i];\n      mEnd = map$$1[i + 1];\n      if (ch < mStart) {\n        start = 0; end = 1;\n        collapse = \"left\";\n      } else if (ch < mEnd) {\n        start = ch - mStart;\n        end = start + 1;\n      } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {\n        end = mEnd - mStart;\n        start = end - 1;\n        if (ch >= mEnd) { collapse = \"right\"; }\n      }\n      if (start != null) {\n        node = map$$1[i + 2];\n        if (mStart == mEnd && bias == (node.insertLeft ? \"left\" : \"right\"))\n          { collapse = bias; }\n        if (bias == \"left\" && start == 0)\n          { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {\n            node = map$$1[(i -= 3) + 2];\n            collapse = \"left\";\n          } }\n        if (bias == \"right\" && start == mEnd - mStart)\n          { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {\n            node = map$$1[(i += 3) + 2];\n            collapse = \"right\";\n          } }\n        break\n      }\n    }\n    return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}\n  }\n\n  function getUsefulRect(rects, bias) {\n    var rect = nullRect;\n    if (bias == \"left\") { for (var i = 0; i < rects.length; i++) {\n      if ((rect = rects[i]).left != rect.right) { break }\n    } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {\n      if ((rect = rects[i$1]).left != rect.right) { break }\n    } }\n    return rect\n  }\n\n  function measureCharInner(cm, prepared, ch, bias) {\n    var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);\n    var node = place.node, start = place.start, end = place.end, collapse = place.collapse;\n\n    var rect;\n    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.\n      for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned\n        while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }\n        while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }\n        if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)\n          { rect = node.parentNode.getBoundingClientRect(); }\n        else\n          { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }\n        if (rect.left || rect.right || start == 0) { break }\n        end = start;\n        start = start - 1;\n        collapse = \"right\";\n      }\n      if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }\n    } else { // If it is a widget, simply get the box for the whole widget.\n      if (start > 0) { collapse = bias = \"right\"; }\n      var rects;\n      if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)\n        { rect = rects[bias == \"right\" ? rects.length - 1 : 0]; }\n      else\n        { rect = node.getBoundingClientRect(); }\n    }\n    if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {\n      var rSpan = node.parentNode.getClientRects()[0];\n      if (rSpan)\n        { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }\n      else\n        { rect = nullRect; }\n    }\n\n    var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;\n    var mid = (rtop + rbot) / 2;\n    var heights = prepared.view.measure.heights;\n    var i = 0;\n    for (; i < heights.length - 1; i++)\n      { if (mid < heights[i]) { break } }\n    var top = i ? heights[i - 1] : 0, bot = heights[i];\n    var result = {left: (collapse == \"right\" ? rect.right : rect.left) - prepared.rect.left,\n                  right: (collapse == \"left\" ? rect.left : rect.right) - prepared.rect.left,\n                  top: top, bottom: bot};\n    if (!rect.left && !rect.right) { result.bogus = true; }\n    if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }\n\n    return result\n  }\n\n  // Work around problem with bounding client rects on ranges being\n  // returned incorrectly when zoomed on IE10 and below.\n  function maybeUpdateRectForZooming(measure, rect) {\n    if (!window.screen || screen.logicalXDPI == null ||\n        screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))\n      { return rect }\n    var scaleX = screen.logicalXDPI / screen.deviceXDPI;\n    var scaleY = screen.logicalYDPI / screen.deviceYDPI;\n    return {left: rect.left * scaleX, right: rect.right * scaleX,\n            top: rect.top * scaleY, bottom: rect.bottom * scaleY}\n  }\n\n  function clearLineMeasurementCacheFor(lineView) {\n    if (lineView.measure) {\n      lineView.measure.cache = {};\n      lineView.measure.heights = null;\n      if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)\n        { lineView.measure.caches[i] = {}; } }\n    }\n  }\n\n  function clearLineMeasurementCache(cm) {\n    cm.display.externalMeasure = null;\n    removeChildren(cm.display.lineMeasure);\n    for (var i = 0; i < cm.display.view.length; i++)\n      { clearLineMeasurementCacheFor(cm.display.view[i]); }\n  }\n\n  function clearCaches(cm) {\n    clearLineMeasurementCache(cm);\n    cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;\n    if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }\n    cm.display.lineNumChars = null;\n  }\n\n  function pageScrollX() {\n    // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206\n    // which causes page_Offset and bounding client rects to use\n    // different reference viewports and invalidate our calculations.\n    if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }\n    return window.pageXOffset || (document.documentElement || document.body).scrollLeft\n  }\n  function pageScrollY() {\n    if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }\n    return window.pageYOffset || (document.documentElement || document.body).scrollTop\n  }\n\n  function widgetTopHeight(lineObj) {\n    var height = 0;\n    if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)\n      { height += widgetHeight(lineObj.widgets[i]); } } }\n    return height\n  }\n\n  // Converts a {top, bottom, left, right} box from line-local\n  // coordinates into another coordinate system. Context may be one of\n  // \"line\", \"div\" (display.lineDiv), \"local\"./null (editor), \"window\",\n  // or \"page\".\n  function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {\n    if (!includeWidgets) {\n      var height = widgetTopHeight(lineObj);\n      rect.top += height; rect.bottom += height;\n    }\n    if (context == \"line\") { return rect }\n    if (!context) { context = \"local\"; }\n    var yOff = heightAtLine(lineObj);\n    if (context == \"local\") { yOff += paddingTop(cm.display); }\n    else { yOff -= cm.display.viewOffset; }\n    if (context == \"page\" || context == \"window\") {\n      var lOff = cm.display.lineSpace.getBoundingClientRect();\n      yOff += lOff.top + (context == \"window\" ? 0 : pageScrollY());\n      var xOff = lOff.left + (context == \"window\" ? 0 : pageScrollX());\n      rect.left += xOff; rect.right += xOff;\n    }\n    rect.top += yOff; rect.bottom += yOff;\n    return rect\n  }\n\n  // Coverts a box from \"div\" coords to another coordinate system.\n  // Context may be \"window\", \"page\", \"div\", or \"local\"./null.\n  function fromCoordSystem(cm, coords, context) {\n    if (context == \"div\") { return coords }\n    var left = coords.left, top = coords.top;\n    // First move into \"page\" coordinate system\n    if (context == \"page\") {\n      left -= pageScrollX();\n      top -= pageScrollY();\n    } else if (context == \"local\" || !context) {\n      var localBox = cm.display.sizer.getBoundingClientRect();\n      left += localBox.left;\n      top += localBox.top;\n    }\n\n    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();\n    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}\n  }\n\n  function charCoords(cm, pos, context, lineObj, bias) {\n    if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }\n    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)\n  }\n\n  // Returns a box for a given cursor position, which may have an\n  // 'other' property containing the position of the secondary cursor\n  // on a bidi boundary.\n  // A cursor Pos(line, char, \"before\") is on the same visual line as `char - 1`\n  // and after `char - 1` in writing order of `char - 1`\n  // A cursor Pos(line, char, \"after\") is on the same visual line as `char`\n  // and before `char` in writing order of `char`\n  // Examples (upper-case letters are RTL, lower-case are LTR):\n  //     Pos(0, 1, ...)\n  //     before   after\n  // ab     a|b     a|b\n  // aB     a|B     aB|\n  // Ab     |Ab     A|b\n  // AB     B|A     B|A\n  // Every position after the last character on a line is considered to stick\n  // to the last character on the line.\n  function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {\n    lineObj = lineObj || getLine(cm.doc, pos.line);\n    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }\n    function get(ch, right) {\n      var m = measureCharPrepared(cm, preparedMeasure, ch, right ? \"right\" : \"left\", varHeight);\n      if (right) { m.left = m.right; } else { m.right = m.left; }\n      return intoCoordSystem(cm, lineObj, m, context)\n    }\n    var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;\n    if (ch >= lineObj.text.length) {\n      ch = lineObj.text.length;\n      sticky = \"before\";\n    } else if (ch <= 0) {\n      ch = 0;\n      sticky = \"after\";\n    }\n    if (!order) { return get(sticky == \"before\" ? ch - 1 : ch, sticky == \"before\") }\n\n    function getBidi(ch, partPos, invert) {\n      var part = order[partPos], right = part.level == 1;\n      return get(invert ? ch - 1 : ch, right != invert)\n    }\n    var partPos = getBidiPartAt(order, ch, sticky);\n    var other = bidiOther;\n    var val = getBidi(ch, partPos, sticky == \"before\");\n    if (other != null) { val.other = getBidi(ch, other, sticky != \"before\"); }\n    return val\n  }\n\n  // Used to cheaply estimate the coordinates for a position. Used for\n  // intermediate scroll updates.\n  function estimateCoords(cm, pos) {\n    var left = 0;\n    pos = clipPos(cm.doc, pos);\n    if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }\n    var lineObj = getLine(cm.doc, pos.line);\n    var top = heightAtLine(lineObj) + paddingTop(cm.display);\n    return {left: left, right: left, top: top, bottom: top + lineObj.height}\n  }\n\n  // Positions returned by coordsChar contain some extra information.\n  // xRel is the relative x position of the input coordinates compared\n  // to the found position (so xRel > 0 means the coordinates are to\n  // the right of the character position, for example). When outside\n  // is true, that means the coordinates lie outside the line's\n  // vertical range.\n  function PosWithInfo(line, ch, sticky, outside, xRel) {\n    var pos = Pos(line, ch, sticky);\n    pos.xRel = xRel;\n    if (outside) { pos.outside = true; }\n    return pos\n  }\n\n  // Compute the character position closest to the given coordinates.\n  // Input must be lineSpace-local (\"div\" coordinate system).\n  function coordsChar(cm, x, y) {\n    var doc = cm.doc;\n    y += cm.display.viewOffset;\n    if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n    if (lineN > last)\n      { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n    if (x < 0) { x = 0; }\n\n    var lineObj = getLine(doc, lineN);\n    for (;;) {\n      var found = coordsCharInner(cm, lineObj, lineN, x, y);\n      var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n      if (!collapsed) { return found }\n      var rangeEnd = collapsed.find(1);\n      if (rangeEnd.line == lineN) { return rangeEnd }\n      lineObj = getLine(doc, lineN = rangeEnd.line);\n    }\n  }\n\n  function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {\n    y -= widgetTopHeight(lineObj);\n    var end = lineObj.text.length;\n    var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);\n    end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);\n    return {begin: begin, end: end}\n  }\n\n  function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {\n    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }\n    var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), \"line\").top;\n    return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)\n  }\n\n  // Returns true if the given side of a box is after the given\n  // coordinates, in top-to-bottom, left-to-right order.\n  function boxIsAfter(box, x, y, left) {\n    return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x\n  }\n\n  function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {\n    // Move y into line-local coordinate space\n    y -= heightAtLine(lineObj);\n    var preparedMeasure = prepareMeasureForLine(cm, lineObj);\n    // When directly calling `measureCharPrepared`, we have to adjust\n    // for the widgets at this line.\n    var widgetHeight$$1 = widgetTopHeight(lineObj);\n    var begin = 0, end = lineObj.text.length, ltr = true;\n\n    var order = getOrder(lineObj, cm.doc.direction);\n    // If the line isn't plain left-to-right text, first figure out\n    // which bidi section the coordinates fall into.\n    if (order) {\n      var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)\n                   (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);\n      ltr = part.level != 1;\n      // The awkward -1 offsets are needed because findFirst (called\n      // on these below) will treat its first bound as inclusive,\n      // second as exclusive, but we want to actually address the\n      // characters in the part's range\n      begin = ltr ? part.from : part.to - 1;\n      end = ltr ? part.to : part.from - 1;\n    }\n\n    // A binary search to find the first character whose bounding box\n    // starts after the coordinates. If we run across any whose box wrap\n    // the coordinates, store that.\n    var chAround = null, boxAround = null;\n    var ch = findFirst(function (ch) {\n      var box = measureCharPrepared(cm, preparedMeasure, ch);\n      box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;\n      if (!boxIsAfter(box, x, y, false)) { return false }\n      if (box.top <= y && box.left <= x) {\n        chAround = ch;\n        boxAround = box;\n      }\n      return true\n    }, begin, end);\n\n    var baseX, sticky, outside = false;\n    // If a box around the coordinates was found, use that\n    if (boxAround) {\n      // Distinguish coordinates nearer to the left or right side of the box\n      var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;\n      ch = chAround + (atStart ? 0 : 1);\n      sticky = atStart ? \"after\" : \"before\";\n      baseX = atLeft ? boxAround.left : boxAround.right;\n    } else {\n      // (Adjust for extended bound, if necessary.)\n      if (!ltr && (ch == end || ch == begin)) { ch++; }\n      // To determine which side to associate with, get the box to the\n      // left of the character and compare it's vertical position to the\n      // coordinates\n      sticky = ch == 0 ? \"after\" : ch == lineObj.text.length ? \"before\" :\n        (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?\n        \"after\" : \"before\";\n      // Now get accurate coordinates for this place, in order to get a\n      // base X position\n      var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), \"line\", lineObj, preparedMeasure);\n      baseX = coords.left;\n      outside = y < coords.top || y >= coords.bottom;\n    }\n\n    ch = skipExtendingChars(lineObj.text, ch, 1);\n    return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)\n  }\n\n  function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {\n    // Bidi parts are sorted left-to-right, and in a non-line-wrapping\n    // situation, we can take this ordering to correspond to the visual\n    // ordering. This finds the first part whose end is after the given\n    // coordinates.\n    var index = findFirst(function (i) {\n      var part = order[i], ltr = part.level != 1;\n      return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? \"before\" : \"after\"),\n                                     \"line\", lineObj, preparedMeasure), x, y, true)\n    }, 0, order.length - 1);\n    var part = order[index];\n    // If this isn't the first part, the part's start is also after\n    // the coordinates, and the coordinates aren't on the same line as\n    // that start, move one part back.\n    if (index > 0) {\n      var ltr = part.level != 1;\n      var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? \"after\" : \"before\"),\n                               \"line\", lineObj, preparedMeasure);\n      if (boxIsAfter(start, x, y, true) && start.top > y)\n        { part = order[index - 1]; }\n    }\n    return part\n  }\n\n  function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {\n    // In a wrapped line, rtl text on wrapping boundaries can do things\n    // that don't correspond to the ordering in our `order` array at\n    // all, so a binary search doesn't work, and we want to return a\n    // part that only spans one line so that the binary search in\n    // coordsCharInner is safe. As such, we first find the extent of the\n    // wrapped line, and then do a flat search in which we discard any\n    // spans that aren't on the line.\n    var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);\n    var begin = ref.begin;\n    var end = ref.end;\n    if (/\\s/.test(lineObj.text.charAt(end - 1))) { end--; }\n    var part = null, closestDist = null;\n    for (var i = 0; i < order.length; i++) {\n      var p = order[i];\n      if (p.from >= end || p.to <= begin) { continue }\n      var ltr = p.level != 1;\n      var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;\n      // Weigh against spans ending before this, so that they are only\n      // picked if nothing ends after\n      var dist = endX < x ? x - endX + 1e9 : endX - x;\n      if (!part || closestDist > dist) {\n        part = p;\n        closestDist = dist;\n      }\n    }\n    if (!part) { part = order[order.length - 1]; }\n    // Clip the part to the wrapped line.\n    if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }\n    if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }\n    return part\n  }\n\n  var measureText;\n  // Compute the default text height.\n  function textHeight(display) {\n    if (display.cachedTextHeight != null) { return display.cachedTextHeight }\n    if (measureText == null) {\n      measureText = elt(\"pre\");\n      // Measure a bunch of lines, for browsers that compute\n      // fractional heights.\n      for (var i = 0; i < 49; ++i) {\n        measureText.appendChild(document.createTextNode(\"x\"));\n        measureText.appendChild(elt(\"br\"));\n      }\n      measureText.appendChild(document.createTextNode(\"x\"));\n    }\n    removeChildrenAndAdd(display.measure, measureText);\n    var height = measureText.offsetHeight / 50;\n    if (height > 3) { display.cachedTextHeight = height; }\n    removeChildren(display.measure);\n    return height || 1\n  }\n\n  // Compute the default character width.\n  function charWidth(display) {\n    if (display.cachedCharWidth != null) { return display.cachedCharWidth }\n    var anchor = elt(\"span\", \"xxxxxxxxxx\");\n    var pre = elt(\"pre\", [anchor]);\n    removeChildrenAndAdd(display.measure, pre);\n    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;\n    if (width > 2) { display.cachedCharWidth = width; }\n    return width || 10\n  }\n\n  // Do a bulk-read of the DOM positions and sizes needed to draw the\n  // view, so that we don't interleave reading and writing to the DOM.\n  function getDimensions(cm) {\n    var d = cm.display, left = {}, width = {};\n    var gutterLeft = d.gutters.clientLeft;\n    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {\n      left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;\n      width[cm.options.gutters[i]] = n.clientWidth;\n    }\n    return {fixedPos: compensateForHScroll(d),\n            gutterTotalWidth: d.gutters.offsetWidth,\n            gutterLeft: left,\n            gutterWidth: width,\n            wrapperWidth: d.wrapper.clientWidth}\n  }\n\n  // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,\n  // but using getBoundingClientRect to get a sub-pixel-accurate\n  // result.\n  function compensateForHScroll(display) {\n    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left\n  }\n\n  // Returns a function that estimates the height of a line, to use as\n  // first approximation until the line becomes visible (and is thus\n  // properly measurable).\n  function estimateHeight(cm) {\n    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;\n    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);\n    return function (line) {\n      if (lineIsHidden(cm.doc, line)) { return 0 }\n\n      var widgetsHeight = 0;\n      if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {\n        if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }\n      } }\n\n      if (wrapping)\n        { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }\n      else\n        { return widgetsHeight + th }\n    }\n  }\n\n  function estimateLineHeights(cm) {\n    var doc = cm.doc, est = estimateHeight(cm);\n    doc.iter(function (line) {\n      var estHeight = est(line);\n      if (estHeight != line.height) { updateLineHeight(line, estHeight); }\n    });\n  }\n\n  // Given a mouse event, find the corresponding position. If liberal\n  // is false, it checks whether a gutter or scrollbar was clicked,\n  // and returns null if it was. forRect is used by rectangular\n  // selections, and tries to estimate a character position even for\n  // coordinates beyond the right of the text.\n  function posFromMouse(cm, e, liberal, forRect) {\n    var display = cm.display;\n    if (!liberal && e_target(e).getAttribute(\"cm-not-content\") == \"true\") { return null }\n\n    var x, y, space = display.lineSpace.getBoundingClientRect();\n    // Fails unpredictably on IE[67] when mouse is dragged around quickly.\n    try { x = e.clientX - space.left; y = e.clientY - space.top; }\n    catch (e) { return null }\n    var coords = coordsChar(cm, x, y), line;\n    if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {\n      var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;\n      coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));\n    }\n    return coords\n  }\n\n  // Find the view element corresponding to a given line. Return null\n  // when the line isn't visible.\n  function findViewIndex(cm, n) {\n    if (n >= cm.display.viewTo) { return null }\n    n -= cm.display.viewFrom;\n    if (n < 0) { return null }\n    var view = cm.display.view;\n    for (var i = 0; i < view.length; i++) {\n      n -= view[i].size;\n      if (n < 0) { return i }\n    }\n  }\n\n  function updateSelection(cm) {\n    cm.display.input.showSelection(cm.display.input.prepareSelection());\n  }\n\n  function prepareSelection(cm, primary) {\n    if ( primary === void 0 ) primary = true;\n\n    var doc = cm.doc, result = {};\n    var curFragment = result.cursors = document.createDocumentFragment();\n    var selFragment = result.selection = document.createDocumentFragment();\n\n    for (var i = 0; i < doc.sel.ranges.length; i++) {\n      if (!primary && i == doc.sel.primIndex) { continue }\n      var range$$1 = doc.sel.ranges[i];\n      if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }\n      var collapsed = range$$1.empty();\n      if (collapsed || cm.options.showCursorWhenSelecting)\n        { drawSelectionCursor(cm, range$$1.head, curFragment); }\n      if (!collapsed)\n        { drawSelectionRange(cm, range$$1, selFragment); }\n    }\n    return result\n  }\n\n  // Draws a cursor for the given range\n  function drawSelectionCursor(cm, head, output) {\n    var pos = cursorCoords(cm, head, \"div\", null, null, !cm.options.singleCursorHeightPerLine);\n\n    var cursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor\"));\n    cursor.style.left = pos.left + \"px\";\n    cursor.style.top = pos.top + \"px\";\n    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + \"px\";\n\n    if (pos.other) {\n      // Secondary cursor, shown when on a 'jump' in bi-directional text\n      var otherCursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor CodeMirror-secondarycursor\"));\n      otherCursor.style.display = \"\";\n      otherCursor.style.left = pos.other.left + \"px\";\n      otherCursor.style.top = pos.other.top + \"px\";\n      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + \"px\";\n    }\n  }\n\n  function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }\n\n  // Draws the given range as a highlighted selection\n  function drawSelectionRange(cm, range$$1, output) {\n    var display = cm.display, doc = cm.doc;\n    var fragment = document.createDocumentFragment();\n    var padding = paddingH(cm.display), leftSide = padding.left;\n    var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n    var docLTR = doc.direction == \"ltr\";\n\n    function add(left, top, width, bottom) {\n      if (top < 0) { top = 0; }\n      top = Math.round(top);\n      bottom = Math.round(bottom);\n      fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n                             top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n                             height: \" + (bottom - top) + \"px\")));\n    }\n\n    function drawForLine(line, fromArg, toArg) {\n      var lineObj = getLine(doc, line);\n      var lineLen = lineObj.text.length;\n      var start, end;\n      function coords(ch, bias) {\n        return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n      }\n\n      function wrapX(pos, dir, side) {\n        var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n        var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n        var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n        return coords(ch, prop)[prop]\n      }\n\n      var order = getOrder(lineObj, doc.direction);\n      iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n        var ltr = dir == \"ltr\";\n        var fromPos = coords(from, ltr ? \"left\" : \"right\");\n        var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n        var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n        var first = i == 0, last = !order || i == order.length - 1;\n        if (toPos.top - fromPos.top <= 3) { // Single line\n          var openLeft = (docLTR ? openStart : openEnd) && first;\n          var openRight = (docLTR ? openEnd : openStart) && last;\n          var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n          var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n          add(left, fromPos.top, right - left, fromPos.bottom);\n        } else { // Multiple lines\n          var topLeft, topRight, botLeft, botRight;\n          if (ltr) {\n            topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n            topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n            botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n            botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n          } else {\n            topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n            topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n            botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n            botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n          }\n          add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n          if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n          add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n        }\n\n        if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n        if (cmpCoords(toPos, start) < 0) { start = toPos; }\n        if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n        if (cmpCoords(toPos, end) < 0) { end = toPos; }\n      });\n      return {start: start, end: end}\n    }\n\n    var sFrom = range$$1.from(), sTo = range$$1.to();\n    if (sFrom.line == sTo.line) {\n      drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n    } else {\n      var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n      var singleVLine = visualLine(fromLine) == visualLine(toLine);\n      var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n      var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n      if (singleVLine) {\n        if (leftEnd.top < rightStart.top - 2) {\n          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n          add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n        } else {\n          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n        }\n      }\n      if (leftEnd.bottom < rightStart.top)\n        { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n    }\n\n    output.appendChild(fragment);\n  }\n\n  // Cursor-blinking\n  function restartBlink(cm) {\n    if (!cm.state.focused) { return }\n    var display = cm.display;\n    clearInterval(display.blinker);\n    var on = true;\n    display.cursorDiv.style.visibility = \"\";\n    if (cm.options.cursorBlinkRate > 0)\n      { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? \"\" : \"hidden\"; },\n        cm.options.cursorBlinkRate); }\n    else if (cm.options.cursorBlinkRate < 0)\n      { display.cursorDiv.style.visibility = \"hidden\"; }\n  }\n\n  function ensureFocus(cm) {\n    if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }\n  }\n\n  function delayBlurEvent(cm) {\n    cm.state.delayingBlurEvent = true;\n    setTimeout(function () { if (cm.state.delayingBlurEvent) {\n      cm.state.delayingBlurEvent = false;\n      onBlur(cm);\n    } }, 100);\n  }\n\n  function onFocus(cm, e) {\n    if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }\n\n    if (cm.options.readOnly == \"nocursor\") { return }\n    if (!cm.state.focused) {\n      signal(cm, \"focus\", cm, e);\n      cm.state.focused = true;\n      addClass(cm.display.wrapper, \"CodeMirror-focused\");\n      // This test prevents this from firing when a context\n      // menu is closed (since the input reset would kill the\n      // select-all detection hack)\n      if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {\n        cm.display.input.reset();\n        if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730\n      }\n      cm.display.input.receivedFocus();\n    }\n    restartBlink(cm);\n  }\n  function onBlur(cm, e) {\n    if (cm.state.delayingBlurEvent) { return }\n\n    if (cm.state.focused) {\n      signal(cm, \"blur\", cm, e);\n      cm.state.focused = false;\n      rmClass(cm.display.wrapper, \"CodeMirror-focused\");\n    }\n    clearInterval(cm.display.blinker);\n    setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);\n  }\n\n  // Read the actual heights of the rendered lines, and update their\n  // stored heights to match.\n  function updateHeightsInViewport(cm) {\n    var display = cm.display;\n    var prevBottom = display.lineDiv.offsetTop;\n    for (var i = 0; i < display.view.length; i++) {\n      var cur = display.view[i], wrapping = cm.options.lineWrapping;\n      var height = (void 0), width = 0;\n      if (cur.hidden) { continue }\n      if (ie && ie_version < 8) {\n        var bot = cur.node.offsetTop + cur.node.offsetHeight;\n        height = bot - prevBottom;\n        prevBottom = bot;\n      } else {\n        var box = cur.node.getBoundingClientRect();\n        height = box.bottom - box.top;\n        // Check that lines don't extend past the right of the current\n        // editor width\n        if (!wrapping && cur.text.firstChild)\n          { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }\n      }\n      var diff = cur.line.height - height;\n      if (height < 2) { height = textHeight(display); }\n      if (diff > .005 || diff < -.005) {\n        updateLineHeight(cur.line, height);\n        updateWidgetHeight(cur.line);\n        if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)\n          { updateWidgetHeight(cur.rest[j]); } }\n      }\n      if (width > cm.display.sizerWidth) {\n        var chWidth = Math.ceil(width / charWidth(cm.display));\n        if (chWidth > cm.display.maxLineLength) {\n          cm.display.maxLineLength = chWidth;\n          cm.display.maxLine = cur.line;\n          cm.display.maxLineChanged = true;\n        }\n      }\n    }\n  }\n\n  // Read and store the height of line widgets associated with the\n  // given line.\n  function updateWidgetHeight(line) {\n    if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {\n      var w = line.widgets[i], parent = w.node.parentNode;\n      if (parent) { w.height = parent.offsetHeight; }\n    } }\n  }\n\n  // Compute the lines that are visible in a given viewport (defaults\n  // the the current scroll position). viewport may contain top,\n  // height, and ensure (see op.scrollToPos) properties.\n  function visibleLines(display, doc, viewport) {\n    var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;\n    top = Math.floor(top - paddingTop(display));\n    var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;\n\n    var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);\n    // Ensure is a {from: {line, ch}, to: {line, ch}} object, and\n    // forces those lines into the viewport (if possible).\n    if (viewport && viewport.ensure) {\n      var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;\n      if (ensureFrom < from) {\n        from = ensureFrom;\n        to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);\n      } else if (Math.min(ensureTo, doc.lastLine()) >= to) {\n        from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);\n        to = ensureTo;\n      }\n    }\n    return {from: from, to: Math.max(to, from + 1)}\n  }\n\n  // Re-align line numbers and gutter marks to compensate for\n  // horizontal scrolling.\n  function alignHorizontally(cm) {\n    var display = cm.display, view = display.view;\n    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }\n    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;\n    var gutterW = display.gutters.offsetWidth, left = comp + \"px\";\n    for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {\n      if (cm.options.fixedGutter) {\n        if (view[i].gutter)\n          { view[i].gutter.style.left = left; }\n        if (view[i].gutterBackground)\n          { view[i].gutterBackground.style.left = left; }\n      }\n      var align = view[i].alignable;\n      if (align) { for (var j = 0; j < align.length; j++)\n        { align[j].style.left = left; } }\n    } }\n    if (cm.options.fixedGutter)\n      { display.gutters.style.left = (comp + gutterW) + \"px\"; }\n  }\n\n  // Used to ensure that the line number gutter is still the right\n  // size for the current document size. Returns true when an update\n  // is needed.\n  function maybeUpdateLineNumberWidth(cm) {\n    if (!cm.options.lineNumbers) { return false }\n    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;\n    if (last.length != display.lineNumChars) {\n      var test = display.measure.appendChild(elt(\"div\", [elt(\"div\", last)],\n                                                 \"CodeMirror-linenumber CodeMirror-gutter-elt\"));\n      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;\n      display.lineGutter.style.width = \"\";\n      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;\n      display.lineNumWidth = display.lineNumInnerWidth + padding;\n      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;\n      display.lineGutter.style.width = display.lineNumWidth + \"px\";\n      updateGutterSpace(cm);\n      return true\n    }\n    return false\n  }\n\n  // SCROLLING THINGS INTO VIEW\n\n  // If an editor sits on the top or bottom of the window, partially\n  // scrolled out of view, this ensures that the cursor is visible.\n  function maybeScrollWindow(cm, rect) {\n    if (signalDOMEvent(cm, \"scrollCursorIntoView\")) { return }\n\n    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;\n    if (rect.top + box.top < 0) { doScroll = true; }\n    else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }\n    if (doScroll != null && !phantom) {\n      var scrollNode = elt(\"div\", \"\\u200b\", null, (\"position: absolute;\\n                         top: \" + (rect.top - display.viewOffset - paddingTop(cm.display)) + \"px;\\n                         height: \" + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + \"px;\\n                         left: \" + (rect.left) + \"px; width: \" + (Math.max(2, rect.right - rect.left)) + \"px;\"));\n      cm.display.lineSpace.appendChild(scrollNode);\n      scrollNode.scrollIntoView(doScroll);\n      cm.display.lineSpace.removeChild(scrollNode);\n    }\n  }\n\n  // Scroll a given position into view (immediately), verifying that\n  // it actually became visible (as line heights are accurately\n  // measured, the position of something may 'drift' during drawing).\n  function scrollPosIntoView(cm, pos, end, margin) {\n    if (margin == null) { margin = 0; }\n    var rect;\n    if (!cm.options.lineWrapping && pos == end) {\n      // Set pos and end to the cursor positions around the character pos sticks to\n      // If pos.sticky == \"before\", that is around pos.ch - 1, otherwise around pos.ch\n      // If pos == Pos(_, 0, \"before\"), pos and end are unchanged\n      pos = pos.ch ? Pos(pos.line, pos.sticky == \"before\" ? pos.ch - 1 : pos.ch, \"after\") : pos;\n      end = pos.sticky == \"before\" ? Pos(pos.line, pos.ch + 1, \"before\") : pos;\n    }\n    for (var limit = 0; limit < 5; limit++) {\n      var changed = false;\n      var coords = cursorCoords(cm, pos);\n      var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);\n      rect = {left: Math.min(coords.left, endCoords.left),\n              top: Math.min(coords.top, endCoords.top) - margin,\n              right: Math.max(coords.left, endCoords.left),\n              bottom: Math.max(coords.bottom, endCoords.bottom) + margin};\n      var scrollPos = calculateScrollPos(cm, rect);\n      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;\n      if (scrollPos.scrollTop != null) {\n        updateScrollTop(cm, scrollPos.scrollTop);\n        if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }\n      }\n      if (scrollPos.scrollLeft != null) {\n        setScrollLeft(cm, scrollPos.scrollLeft);\n        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }\n      }\n      if (!changed) { break }\n    }\n    return rect\n  }\n\n  // Scroll a given set of coordinates into view (immediately).\n  function scrollIntoView(cm, rect) {\n    var scrollPos = calculateScrollPos(cm, rect);\n    if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }\n    if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }\n  }\n\n  // Calculate a new scroll position needed to scroll the given\n  // rectangle into view. Returns an object with scrollTop and\n  // scrollLeft properties. When these are undefined, the\n  // vertical/horizontal position does not need to be adjusted.\n  function calculateScrollPos(cm, rect) {\n    var display = cm.display, snapMargin = textHeight(cm.display);\n    if (rect.top < 0) { rect.top = 0; }\n    var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;\n    var screen = displayHeight(cm), result = {};\n    if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }\n    var docBottom = cm.doc.height + paddingVert(display);\n    var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;\n    if (rect.top < screentop) {\n      result.scrollTop = atTop ? 0 : rect.top;\n    } else if (rect.bottom > screentop + screen) {\n      var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);\n      if (newTop != screentop) { result.scrollTop = newTop; }\n    }\n\n    var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;\n    var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);\n    var tooWide = rect.right - rect.left > screenw;\n    if (tooWide) { rect.right = rect.left + screenw; }\n    if (rect.left < 10)\n      { result.scrollLeft = 0; }\n    else if (rect.left < screenleft)\n      { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }\n    else if (rect.right > screenw + screenleft - 3)\n      { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }\n    return result\n  }\n\n  // Store a relative adjustment to the scroll position in the current\n  // operation (to be applied when the operation finishes).\n  function addToScrollTop(cm, top) {\n    if (top == null) { return }\n    resolveScrollToPos(cm);\n    cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;\n  }\n\n  // Make sure that at the end of the operation the current cursor is\n  // shown.\n  function ensureCursorVisible(cm) {\n    resolveScrollToPos(cm);\n    var cur = cm.getCursor();\n    cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};\n  }\n\n  function scrollToCoords(cm, x, y) {\n    if (x != null || y != null) { resolveScrollToPos(cm); }\n    if (x != null) { cm.curOp.scrollLeft = x; }\n    if (y != null) { cm.curOp.scrollTop = y; }\n  }\n\n  function scrollToRange(cm, range$$1) {\n    resolveScrollToPos(cm);\n    cm.curOp.scrollToPos = range$$1;\n  }\n\n  // When an operation has its scrollToPos property set, and another\n  // scroll action is applied before the end of the operation, this\n  // 'simulates' scrolling that position into view in a cheap way, so\n  // that the effect of intermediate scroll commands is not ignored.\n  function resolveScrollToPos(cm) {\n    var range$$1 = cm.curOp.scrollToPos;\n    if (range$$1) {\n      cm.curOp.scrollToPos = null;\n      var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);\n      scrollToCoordsRange(cm, from, to, range$$1.margin);\n    }\n  }\n\n  function scrollToCoordsRange(cm, from, to, margin) {\n    var sPos = calculateScrollPos(cm, {\n      left: Math.min(from.left, to.left),\n      top: Math.min(from.top, to.top) - margin,\n      right: Math.max(from.right, to.right),\n      bottom: Math.max(from.bottom, to.bottom) + margin\n    });\n    scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);\n  }\n\n  // Sync the scrollable area and scrollbars, ensure the viewport\n  // covers the visible area.\n  function updateScrollTop(cm, val) {\n    if (Math.abs(cm.doc.scrollTop - val) < 2) { return }\n    if (!gecko) { updateDisplaySimple(cm, {top: val}); }\n    setScrollTop(cm, val, true);\n    if (gecko) { updateDisplaySimple(cm); }\n    startWorker(cm, 100);\n  }\n\n  function setScrollTop(cm, val, forceScroll) {\n    val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);\n    if (cm.display.scroller.scrollTop == val && !forceScroll) { return }\n    cm.doc.scrollTop = val;\n    cm.display.scrollbars.setScrollTop(val);\n    if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }\n  }\n\n  // Sync scroller and scrollbar, ensure the gutter elements are\n  // aligned.\n  function setScrollLeft(cm, val, isScroller, forceScroll) {\n    val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);\n    if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }\n    cm.doc.scrollLeft = val;\n    alignHorizontally(cm);\n    if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }\n    cm.display.scrollbars.setScrollLeft(val);\n  }\n\n  // SCROLLBARS\n\n  // Prepare DOM reads needed to update the scrollbars. Done in one\n  // shot to minimize update/measure roundtrips.\n  function measureForScrollbars(cm) {\n    var d = cm.display, gutterW = d.gutters.offsetWidth;\n    var docH = Math.round(cm.doc.height + paddingVert(cm.display));\n    return {\n      clientHeight: d.scroller.clientHeight,\n      viewHeight: d.wrapper.clientHeight,\n      scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,\n      viewWidth: d.wrapper.clientWidth,\n      barLeft: cm.options.fixedGutter ? gutterW : 0,\n      docHeight: docH,\n      scrollHeight: docH + scrollGap(cm) + d.barHeight,\n      nativeBarWidth: d.nativeBarWidth,\n      gutterWidth: gutterW\n    }\n  }\n\n  var NativeScrollbars = function(place, scroll, cm) {\n    this.cm = cm;\n    var vert = this.vert = elt(\"div\", [elt(\"div\", null, null, \"min-width: 1px\")], \"CodeMirror-vscrollbar\");\n    var horiz = this.horiz = elt(\"div\", [elt(\"div\", null, null, \"height: 100%; min-height: 1px\")], \"CodeMirror-hscrollbar\");\n    vert.tabIndex = horiz.tabIndex = -1;\n    place(vert); place(horiz);\n\n    on(vert, \"scroll\", function () {\n      if (vert.clientHeight) { scroll(vert.scrollTop, \"vertical\"); }\n    });\n    on(horiz, \"scroll\", function () {\n      if (horiz.clientWidth) { scroll(horiz.scrollLeft, \"horizontal\"); }\n    });\n\n    this.checkedZeroWidth = false;\n    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).\n    if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = \"18px\"; }\n  };\n\n  NativeScrollbars.prototype.update = function (measure) {\n    var needsH = measure.scrollWidth > measure.clientWidth + 1;\n    var needsV = measure.scrollHeight > measure.clientHeight + 1;\n    var sWidth = measure.nativeBarWidth;\n\n    if (needsV) {\n      this.vert.style.display = \"block\";\n      this.vert.style.bottom = needsH ? sWidth + \"px\" : \"0\";\n      var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);\n      // A bug in IE8 can cause this value to be negative, so guard it.\n      this.vert.firstChild.style.height =\n        Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + \"px\";\n    } else {\n      this.vert.style.display = \"\";\n      this.vert.firstChild.style.height = \"0\";\n    }\n\n    if (needsH) {\n      this.horiz.style.display = \"block\";\n      this.horiz.style.right = needsV ? sWidth + \"px\" : \"0\";\n      this.horiz.style.left = measure.barLeft + \"px\";\n      var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);\n      this.horiz.firstChild.style.width =\n        Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + \"px\";\n    } else {\n      this.horiz.style.display = \"\";\n      this.horiz.firstChild.style.width = \"0\";\n    }\n\n    if (!this.checkedZeroWidth && measure.clientHeight > 0) {\n      if (sWidth == 0) { this.zeroWidthHack(); }\n      this.checkedZeroWidth = true;\n    }\n\n    return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}\n  };\n\n  NativeScrollbars.prototype.setScrollLeft = function (pos) {\n    if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }\n    if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, \"horiz\"); }\n  };\n\n  NativeScrollbars.prototype.setScrollTop = function (pos) {\n    if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }\n    if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, \"vert\"); }\n  };\n\n  NativeScrollbars.prototype.zeroWidthHack = function () {\n    var w = mac && !mac_geMountainLion ? \"12px\" : \"18px\";\n    this.horiz.style.height = this.vert.style.width = w;\n    this.horiz.style.pointerEvents = this.vert.style.pointerEvents = \"none\";\n    this.disableHoriz = new Delayed;\n    this.disableVert = new Delayed;\n  };\n\n  NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {\n    bar.style.pointerEvents = \"auto\";\n    function maybeDisable() {\n      // To find out whether the scrollbar is still visible, we\n      // check whether the element under the pixel in the bottom\n      // right corner of the scrollbar box is the scrollbar box\n      // itself (when the bar is still visible) or its filler child\n      // (when the bar is hidden). If it is still visible, we keep\n      // it enabled, if it's hidden, we disable pointer events.\n      var box = bar.getBoundingClientRect();\n      var elt$$1 = type == \"vert\" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)\n          : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);\n      if (elt$$1 != bar) { bar.style.pointerEvents = \"none\"; }\n      else { delay.set(1000, maybeDisable); }\n    }\n    delay.set(1000, maybeDisable);\n  };\n\n  NativeScrollbars.prototype.clear = function () {\n    var parent = this.horiz.parentNode;\n    parent.removeChild(this.horiz);\n    parent.removeChild(this.vert);\n  };\n\n  var NullScrollbars = function () {};\n\n  NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };\n  NullScrollbars.prototype.setScrollLeft = function () {};\n  NullScrollbars.prototype.setScrollTop = function () {};\n  NullScrollbars.prototype.clear = function () {};\n\n  function updateScrollbars(cm, measure) {\n    if (!measure) { measure = measureForScrollbars(cm); }\n    var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;\n    updateScrollbarsInner(cm, measure);\n    for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {\n      if (startWidth != cm.display.barWidth && cm.options.lineWrapping)\n        { updateHeightsInViewport(cm); }\n      updateScrollbarsInner(cm, measureForScrollbars(cm));\n      startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;\n    }\n  }\n\n  // Re-synchronize the fake scrollbars with the actual size of the\n  // content.\n  function updateScrollbarsInner(cm, measure) {\n    var d = cm.display;\n    var sizes = d.scrollbars.update(measure);\n\n    d.sizer.style.paddingRight = (d.barWidth = sizes.right) + \"px\";\n    d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + \"px\";\n    d.heightForcer.style.borderBottom = sizes.bottom + \"px solid transparent\";\n\n    if (sizes.right && sizes.bottom) {\n      d.scrollbarFiller.style.display = \"block\";\n      d.scrollbarFiller.style.height = sizes.bottom + \"px\";\n      d.scrollbarFiller.style.width = sizes.right + \"px\";\n    } else { d.scrollbarFiller.style.display = \"\"; }\n    if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {\n      d.gutterFiller.style.display = \"block\";\n      d.gutterFiller.style.height = sizes.bottom + \"px\";\n      d.gutterFiller.style.width = measure.gutterWidth + \"px\";\n    } else { d.gutterFiller.style.display = \"\"; }\n  }\n\n  var scrollbarModel = {\"native\": NativeScrollbars, \"null\": NullScrollbars};\n\n  function initScrollbars(cm) {\n    if (cm.display.scrollbars) {\n      cm.display.scrollbars.clear();\n      if (cm.display.scrollbars.addClass)\n        { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }\n    }\n\n    cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {\n      cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);\n      // Prevent clicks in the scrollbars from killing focus\n      on(node, \"mousedown\", function () {\n        if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }\n      });\n      node.setAttribute(\"cm-not-content\", \"true\");\n    }, function (pos, axis) {\n      if (axis == \"horizontal\") { setScrollLeft(cm, pos); }\n      else { updateScrollTop(cm, pos); }\n    }, cm);\n    if (cm.display.scrollbars.addClass)\n      { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }\n  }\n\n  // Operations are used to wrap a series of changes to the editor\n  // state in such a way that each change won't have to update the\n  // cursor and display (which would be awkward, slow, and\n  // error-prone). Instead, display updates are batched and then all\n  // combined and executed at once.\n\n  var nextOpId = 0;\n  // Start a new operation.\n  function startOperation(cm) {\n    cm.curOp = {\n      cm: cm,\n      viewChanged: false,      // Flag that indicates that lines might need to be redrawn\n      startHeight: cm.doc.height, // Used to detect need to update scrollbar\n      forceUpdate: false,      // Used to force a redraw\n      updateInput: 0,       // Whether to reset the input textarea\n      typing: false,           // Whether this reset should be careful to leave existing text (for compositing)\n      changeObjs: null,        // Accumulated changes, for firing change events\n      cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on\n      cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already\n      selectionChanged: false, // Whether the selection needs to be redrawn\n      updateMaxLine: false,    // Set when the widest line needs to be determined anew\n      scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet\n      scrollToPos: null,       // Used to scroll to a specific position\n      focus: false,\n      id: ++nextOpId           // Unique ID\n    };\n    pushOperation(cm.curOp);\n  }\n\n  // Finish an operation, updating the display and signalling delayed events\n  function endOperation(cm) {\n    var op = cm.curOp;\n    if (op) { finishOperation(op, function (group) {\n      for (var i = 0; i < group.ops.length; i++)\n        { group.ops[i].cm.curOp = null; }\n      endOperations(group);\n    }); }\n  }\n\n  // The DOM updates done when an operation finishes are batched so\n  // that the minimum number of relayouts are required.\n  function endOperations(group) {\n    var ops = group.ops;\n    for (var i = 0; i < ops.length; i++) // Read DOM\n      { endOperation_R1(ops[i]); }\n    for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)\n      { endOperation_W1(ops[i$1]); }\n    for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM\n      { endOperation_R2(ops[i$2]); }\n    for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)\n      { endOperation_W2(ops[i$3]); }\n    for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM\n      { endOperation_finish(ops[i$4]); }\n  }\n\n  function endOperation_R1(op) {\n    var cm = op.cm, display = cm.display;\n    maybeClipScrollbars(cm);\n    if (op.updateMaxLine) { findMaxLine(cm); }\n\n    op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||\n      op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||\n                         op.scrollToPos.to.line >= display.viewTo) ||\n      display.maxLineChanged && cm.options.lineWrapping;\n    op.update = op.mustUpdate &&\n      new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);\n  }\n\n  function endOperation_W1(op) {\n    op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);\n  }\n\n  function endOperation_R2(op) {\n    var cm = op.cm, display = cm.display;\n    if (op.updatedDisplay) { updateHeightsInViewport(cm); }\n\n    op.barMeasure = measureForScrollbars(cm);\n\n    // If the max line changed since it was last measured, measure it,\n    // and ensure the document's width matches it.\n    // updateDisplay_W2 will use these properties to do the actual resizing\n    if (display.maxLineChanged && !cm.options.lineWrapping) {\n      op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;\n      cm.display.sizerWidth = op.adjustWidthTo;\n      op.barMeasure.scrollWidth =\n        Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);\n      op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));\n    }\n\n    if (op.updatedDisplay || op.selectionChanged)\n      { op.preparedSelection = display.input.prepareSelection(); }\n  }\n\n  function endOperation_W2(op) {\n    var cm = op.cm;\n\n    if (op.adjustWidthTo != null) {\n      cm.display.sizer.style.minWidth = op.adjustWidthTo + \"px\";\n      if (op.maxScrollLeft < cm.doc.scrollLeft)\n        { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }\n      cm.display.maxLineChanged = false;\n    }\n\n    var takeFocus = op.focus && op.focus == activeElt();\n    if (op.preparedSelection)\n      { cm.display.input.showSelection(op.preparedSelection, takeFocus); }\n    if (op.updatedDisplay || op.startHeight != cm.doc.height)\n      { updateScrollbars(cm, op.barMeasure); }\n    if (op.updatedDisplay)\n      { setDocumentHeight(cm, op.barMeasure); }\n\n    if (op.selectionChanged) { restartBlink(cm); }\n\n    if (cm.state.focused && op.updateInput)\n      { cm.display.input.reset(op.typing); }\n    if (takeFocus) { ensureFocus(op.cm); }\n  }\n\n  function endOperation_finish(op) {\n    var cm = op.cm, display = cm.display, doc = cm.doc;\n\n    if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }\n\n    // Abort mouse wheel delta measurement, when scrolling explicitly\n    if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))\n      { display.wheelStartX = display.wheelStartY = null; }\n\n    // Propagate the scroll position to the actual DOM scroller\n    if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }\n\n    if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }\n    // If we need to scroll a specific position into view, do so.\n    if (op.scrollToPos) {\n      var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),\n                                   clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);\n      maybeScrollWindow(cm, rect);\n    }\n\n    // Fire events for markers that are hidden/unidden by editing or\n    // undoing\n    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;\n    if (hidden) { for (var i = 0; i < hidden.length; ++i)\n      { if (!hidden[i].lines.length) { signal(hidden[i], \"hide\"); } } }\n    if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)\n      { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], \"unhide\"); } } }\n\n    if (display.wrapper.offsetHeight)\n      { doc.scrollTop = cm.display.scroller.scrollTop; }\n\n    // Fire change events, and delayed event handlers\n    if (op.changeObjs)\n      { signal(cm, \"changes\", cm, op.changeObjs); }\n    if (op.update)\n      { op.update.finish(); }\n  }\n\n  // Run the given function in an operation\n  function runInOp(cm, f) {\n    if (cm.curOp) { return f() }\n    startOperation(cm);\n    try { return f() }\n    finally { endOperation(cm); }\n  }\n  // Wraps a function in an operation. Returns the wrapped function.\n  function operation(cm, f) {\n    return function() {\n      if (cm.curOp) { return f.apply(cm, arguments) }\n      startOperation(cm);\n      try { return f.apply(cm, arguments) }\n      finally { endOperation(cm); }\n    }\n  }\n  // Used to add methods to editor and doc instances, wrapping them in\n  // operations.\n  function methodOp(f) {\n    return function() {\n      if (this.curOp) { return f.apply(this, arguments) }\n      startOperation(this);\n      try { return f.apply(this, arguments) }\n      finally { endOperation(this); }\n    }\n  }\n  function docMethodOp(f) {\n    return function() {\n      var cm = this.cm;\n      if (!cm || cm.curOp) { return f.apply(this, arguments) }\n      startOperation(cm);\n      try { return f.apply(this, arguments) }\n      finally { endOperation(cm); }\n    }\n  }\n\n  // Updates the display.view data structure for a given change to the\n  // document. From and to are in pre-change coordinates. Lendiff is\n  // the amount of lines added or subtracted by the change. This is\n  // used for changes that span multiple lines, or change the way\n  // lines are divided into visual lines. regLineChange (below)\n  // registers single-line changes.\n  function regChange(cm, from, to, lendiff) {\n    if (from == null) { from = cm.doc.first; }\n    if (to == null) { to = cm.doc.first + cm.doc.size; }\n    if (!lendiff) { lendiff = 0; }\n\n    var display = cm.display;\n    if (lendiff && to < display.viewTo &&\n        (display.updateLineNumbers == null || display.updateLineNumbers > from))\n      { display.updateLineNumbers = from; }\n\n    cm.curOp.viewChanged = true;\n\n    if (from >= display.viewTo) { // Change after\n      if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)\n        { resetView(cm); }\n    } else if (to <= display.viewFrom) { // Change before\n      if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {\n        resetView(cm);\n      } else {\n        display.viewFrom += lendiff;\n        display.viewTo += lendiff;\n      }\n    } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap\n      resetView(cm);\n    } else if (from <= display.viewFrom) { // Top overlap\n      var cut = viewCuttingPoint(cm, to, to + lendiff, 1);\n      if (cut) {\n        display.view = display.view.slice(cut.index);\n        display.viewFrom = cut.lineN;\n        display.viewTo += lendiff;\n      } else {\n        resetView(cm);\n      }\n    } else if (to >= display.viewTo) { // Bottom overlap\n      var cut$1 = viewCuttingPoint(cm, from, from, -1);\n      if (cut$1) {\n        display.view = display.view.slice(0, cut$1.index);\n        display.viewTo = cut$1.lineN;\n      } else {\n        resetView(cm);\n      }\n    } else { // Gap in the middle\n      var cutTop = viewCuttingPoint(cm, from, from, -1);\n      var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);\n      if (cutTop && cutBot) {\n        display.view = display.view.slice(0, cutTop.index)\n          .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))\n          .concat(display.view.slice(cutBot.index));\n        display.viewTo += lendiff;\n      } else {\n        resetView(cm);\n      }\n    }\n\n    var ext = display.externalMeasured;\n    if (ext) {\n      if (to < ext.lineN)\n        { ext.lineN += lendiff; }\n      else if (from < ext.lineN + ext.size)\n        { display.externalMeasured = null; }\n    }\n  }\n\n  // Register a change to a single line. Type must be one of \"text\",\n  // \"gutter\", \"class\", \"widget\"\n  function regLineChange(cm, line, type) {\n    cm.curOp.viewChanged = true;\n    var display = cm.display, ext = cm.display.externalMeasured;\n    if (ext && line >= ext.lineN && line < ext.lineN + ext.size)\n      { display.externalMeasured = null; }\n\n    if (line < display.viewFrom || line >= display.viewTo) { return }\n    var lineView = display.view[findViewIndex(cm, line)];\n    if (lineView.node == null) { return }\n    var arr = lineView.changes || (lineView.changes = []);\n    if (indexOf(arr, type) == -1) { arr.push(type); }\n  }\n\n  // Clear the view.\n  function resetView(cm) {\n    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;\n    cm.display.view = [];\n    cm.display.viewOffset = 0;\n  }\n\n  function viewCuttingPoint(cm, oldN, newN, dir) {\n    var index = findViewIndex(cm, oldN), diff, view = cm.display.view;\n    if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)\n      { return {index: index, lineN: newN} }\n    var n = cm.display.viewFrom;\n    for (var i = 0; i < index; i++)\n      { n += view[i].size; }\n    if (n != oldN) {\n      if (dir > 0) {\n        if (index == view.length - 1) { return null }\n        diff = (n + view[index].size) - oldN;\n        index++;\n      } else {\n        diff = n - oldN;\n      }\n      oldN += diff; newN += diff;\n    }\n    while (visualLineNo(cm.doc, newN) != newN) {\n      if (index == (dir < 0 ? 0 : view.length - 1)) { return null }\n      newN += dir * view[index - (dir < 0 ? 1 : 0)].size;\n      index += dir;\n    }\n    return {index: index, lineN: newN}\n  }\n\n  // Force the view to cover a given range, adding empty view element\n  // or clipping off existing ones as needed.\n  function adjustView(cm, from, to) {\n    var display = cm.display, view = display.view;\n    if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {\n      display.view = buildViewArray(cm, from, to);\n      display.viewFrom = from;\n    } else {\n      if (display.viewFrom > from)\n        { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }\n      else if (display.viewFrom < from)\n        { display.view = display.view.slice(findViewIndex(cm, from)); }\n      display.viewFrom = from;\n      if (display.viewTo < to)\n        { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }\n      else if (display.viewTo > to)\n        { display.view = display.view.slice(0, findViewIndex(cm, to)); }\n    }\n    display.viewTo = to;\n  }\n\n  // Count the number of lines in the view whose DOM representation is\n  // out of date (or nonexistent).\n  function countDirtyView(cm) {\n    var view = cm.display.view, dirty = 0;\n    for (var i = 0; i < view.length; i++) {\n      var lineView = view[i];\n      if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }\n    }\n    return dirty\n  }\n\n  // HIGHLIGHT WORKER\n\n  function startWorker(cm, time) {\n    if (cm.doc.highlightFrontier < cm.display.viewTo)\n      { cm.state.highlight.set(time, bind(highlightWorker, cm)); }\n  }\n\n  function highlightWorker(cm) {\n    var doc = cm.doc;\n    if (doc.highlightFrontier >= cm.display.viewTo) { return }\n    var end = +new Date + cm.options.workTime;\n    var context = getContextBefore(cm, doc.highlightFrontier);\n    var changedLines = [];\n\n    doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {\n      if (context.line >= cm.display.viewFrom) { // Visible\n        var oldStyles = line.styles;\n        var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;\n        var highlighted = highlightLine(cm, line, context, true);\n        if (resetState) { context.state = resetState; }\n        line.styles = highlighted.styles;\n        var oldCls = line.styleClasses, newCls = highlighted.classes;\n        if (newCls) { line.styleClasses = newCls; }\n        else if (oldCls) { line.styleClasses = null; }\n        var ischange = !oldStyles || oldStyles.length != line.styles.length ||\n          oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);\n        for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }\n        if (ischange) { changedLines.push(context.line); }\n        line.stateAfter = context.save();\n        context.nextLine();\n      } else {\n        if (line.text.length <= cm.options.maxHighlightLength)\n          { processLine(cm, line.text, context); }\n        line.stateAfter = context.line % 5 == 0 ? context.save() : null;\n        context.nextLine();\n      }\n      if (+new Date > end) {\n        startWorker(cm, cm.options.workDelay);\n        return true\n      }\n    });\n    doc.highlightFrontier = context.line;\n    doc.modeFrontier = Math.max(doc.modeFrontier, context.line);\n    if (changedLines.length) { runInOp(cm, function () {\n      for (var i = 0; i < changedLines.length; i++)\n        { regLineChange(cm, changedLines[i], \"text\"); }\n    }); }\n  }\n\n  // DISPLAY DRAWING\n\n  var DisplayUpdate = function(cm, viewport, force) {\n    var display = cm.display;\n\n    this.viewport = viewport;\n    // Store some values that we'll need later (but don't want to force a relayout for)\n    this.visible = visibleLines(display, cm.doc, viewport);\n    this.editorIsHidden = !display.wrapper.offsetWidth;\n    this.wrapperHeight = display.wrapper.clientHeight;\n    this.wrapperWidth = display.wrapper.clientWidth;\n    this.oldDisplayWidth = displayWidth(cm);\n    this.force = force;\n    this.dims = getDimensions(cm);\n    this.events = [];\n  };\n\n  DisplayUpdate.prototype.signal = function (emitter, type) {\n    if (hasHandler(emitter, type))\n      { this.events.push(arguments); }\n  };\n  DisplayUpdate.prototype.finish = function () {\n      var this$1 = this;\n\n    for (var i = 0; i < this.events.length; i++)\n      { signal.apply(null, this$1.events[i]); }\n  };\n\n  function maybeClipScrollbars(cm) {\n    var display = cm.display;\n    if (!display.scrollbarsClipped && display.scroller.offsetWidth) {\n      display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;\n      display.heightForcer.style.height = scrollGap(cm) + \"px\";\n      display.sizer.style.marginBottom = -display.nativeBarWidth + \"px\";\n      display.sizer.style.borderRightWidth = scrollGap(cm) + \"px\";\n      display.scrollbarsClipped = true;\n    }\n  }\n\n  function selectionSnapshot(cm) {\n    if (cm.hasFocus()) { return null }\n    var active = activeElt();\n    if (!active || !contains(cm.display.lineDiv, active)) { return null }\n    var result = {activeElt: active};\n    if (window.getSelection) {\n      var sel = window.getSelection();\n      if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {\n        result.anchorNode = sel.anchorNode;\n        result.anchorOffset = sel.anchorOffset;\n        result.focusNode = sel.focusNode;\n        result.focusOffset = sel.focusOffset;\n      }\n    }\n    return result\n  }\n\n  function restoreSelection(snapshot) {\n    if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }\n    snapshot.activeElt.focus();\n    if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {\n      var sel = window.getSelection(), range$$1 = document.createRange();\n      range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);\n      range$$1.collapse(false);\n      sel.removeAllRanges();\n      sel.addRange(range$$1);\n      sel.extend(snapshot.focusNode, snapshot.focusOffset);\n    }\n  }\n\n  // Does the actual updating of the line display. Bails out\n  // (returning false) when there is nothing to be done and forced is\n  // false.\n  function updateDisplayIfNeeded(cm, update) {\n    var display = cm.display, doc = cm.doc;\n\n    if (update.editorIsHidden) {\n      resetView(cm);\n      return false\n    }\n\n    // Bail out if the visible area is already rendered and nothing changed.\n    if (!update.force &&\n        update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&\n        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&\n        display.renderedView == display.view && countDirtyView(cm) == 0)\n      { return false }\n\n    if (maybeUpdateLineNumberWidth(cm)) {\n      resetView(cm);\n      update.dims = getDimensions(cm);\n    }\n\n    // Compute a suitable new viewport (from & to)\n    var end = doc.first + doc.size;\n    var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);\n    var to = Math.min(end, update.visible.to + cm.options.viewportMargin);\n    if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }\n    if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }\n    if (sawCollapsedSpans) {\n      from = visualLineNo(cm.doc, from);\n      to = visualLineEndNo(cm.doc, to);\n    }\n\n    var different = from != display.viewFrom || to != display.viewTo ||\n      display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;\n    adjustView(cm, from, to);\n\n    display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));\n    // Position the mover div to align with the current scroll position\n    cm.display.mover.style.top = display.viewOffset + \"px\";\n\n    var toUpdate = countDirtyView(cm);\n    if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&\n        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))\n      { return false }\n\n    // For big changes, we hide the enclosing element during the\n    // update, since that speeds up the operations on most browsers.\n    var selSnapshot = selectionSnapshot(cm);\n    if (toUpdate > 4) { display.lineDiv.style.display = \"none\"; }\n    patchDisplay(cm, display.updateLineNumbers, update.dims);\n    if (toUpdate > 4) { display.lineDiv.style.display = \"\"; }\n    display.renderedView = display.view;\n    // There might have been a widget with a focused element that got\n    // hidden or updated, if so re-focus it.\n    restoreSelection(selSnapshot);\n\n    // Prevent selection and cursors from interfering with the scroll\n    // width and height.\n    removeChildren(display.cursorDiv);\n    removeChildren(display.selectionDiv);\n    display.gutters.style.height = display.sizer.style.minHeight = 0;\n\n    if (different) {\n      display.lastWrapHeight = update.wrapperHeight;\n      display.lastWrapWidth = update.wrapperWidth;\n      startWorker(cm, 400);\n    }\n\n    display.updateLineNumbers = null;\n\n    return true\n  }\n\n  function postUpdateDisplay(cm, update) {\n    var viewport = update.viewport;\n\n    for (var first = true;; first = false) {\n      if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {\n        // Clip forced viewport to actual scrollable area.\n        if (viewport && viewport.top != null)\n          { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }\n        // Updated line heights might result in the drawn area not\n        // actually covering the viewport. Keep looping until it does.\n        update.visible = visibleLines(cm.display, cm.doc, viewport);\n        if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)\n          { break }\n      }\n      if (!updateDisplayIfNeeded(cm, update)) { break }\n      updateHeightsInViewport(cm);\n      var barMeasure = measureForScrollbars(cm);\n      updateSelection(cm);\n      updateScrollbars(cm, barMeasure);\n      setDocumentHeight(cm, barMeasure);\n      update.force = false;\n    }\n\n    update.signal(cm, \"update\", cm);\n    if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {\n      update.signal(cm, \"viewportChange\", cm, cm.display.viewFrom, cm.display.viewTo);\n      cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;\n    }\n  }\n\n  function updateDisplaySimple(cm, viewport) {\n    var update = new DisplayUpdate(cm, viewport);\n    if (updateDisplayIfNeeded(cm, update)) {\n      updateHeightsInViewport(cm);\n      postUpdateDisplay(cm, update);\n      var barMeasure = measureForScrollbars(cm);\n      updateSelection(cm);\n      updateScrollbars(cm, barMeasure);\n      setDocumentHeight(cm, barMeasure);\n      update.finish();\n    }\n  }\n\n  // Sync the actual display DOM structure with display.view, removing\n  // nodes for lines that are no longer in view, and creating the ones\n  // that are not there yet, and updating the ones that are out of\n  // date.\n  function patchDisplay(cm, updateNumbersFrom, dims) {\n    var display = cm.display, lineNumbers = cm.options.lineNumbers;\n    var container = display.lineDiv, cur = container.firstChild;\n\n    function rm(node) {\n      var next = node.nextSibling;\n      // Works around a throw-scroll bug in OS X Webkit\n      if (webkit && mac && cm.display.currentWheelTarget == node)\n        { node.style.display = \"none\"; }\n      else\n        { node.parentNode.removeChild(node); }\n      return next\n    }\n\n    var view = display.view, lineN = display.viewFrom;\n    // Loop over the elements in the view, syncing cur (the DOM nodes\n    // in display.lineDiv) with the view as we go.\n    for (var i = 0; i < view.length; i++) {\n      var lineView = view[i];\n      if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet\n        var node = buildLineElement(cm, lineView, lineN, dims);\n        container.insertBefore(node, cur);\n      } else { // Already drawn\n        while (cur != lineView.node) { cur = rm(cur); }\n        var updateNumber = lineNumbers && updateNumbersFrom != null &&\n          updateNumbersFrom <= lineN && lineView.lineNumber;\n        if (lineView.changes) {\n          if (indexOf(lineView.changes, \"gutter\") > -1) { updateNumber = false; }\n          updateLineForChanges(cm, lineView, lineN, dims);\n        }\n        if (updateNumber) {\n          removeChildren(lineView.lineNumber);\n          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));\n        }\n        cur = lineView.node.nextSibling;\n      }\n      lineN += lineView.size;\n    }\n    while (cur) { cur = rm(cur); }\n  }\n\n  function updateGutterSpace(cm) {\n    var width = cm.display.gutters.offsetWidth;\n    cm.display.sizer.style.marginLeft = width + \"px\";\n  }\n\n  function setDocumentHeight(cm, measure) {\n    cm.display.sizer.style.minHeight = measure.docHeight + \"px\";\n    cm.display.heightForcer.style.top = measure.docHeight + \"px\";\n    cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + \"px\";\n  }\n\n  // Rebuild the gutter elements, ensure the margin to the left of the\n  // code matches their width.\n  function updateGutters(cm) {\n    var gutters = cm.display.gutters, specs = cm.options.gutters;\n    removeChildren(gutters);\n    var i = 0;\n    for (; i < specs.length; ++i) {\n      var gutterClass = specs[i];\n      var gElt = gutters.appendChild(elt(\"div\", null, \"CodeMirror-gutter \" + gutterClass));\n      if (gutterClass == \"CodeMirror-linenumbers\") {\n        cm.display.lineGutter = gElt;\n        gElt.style.width = (cm.display.lineNumWidth || 1) + \"px\";\n      }\n    }\n    gutters.style.display = i ? \"\" : \"none\";\n    updateGutterSpace(cm);\n  }\n\n  // Make sure the gutters options contains the element\n  // \"CodeMirror-linenumbers\" when the lineNumbers option is true.\n  function setGuttersForLineNumbers(options) {\n    var found = indexOf(options.gutters, \"CodeMirror-linenumbers\");\n    if (found == -1 && options.lineNumbers) {\n      options.gutters = options.gutters.concat([\"CodeMirror-linenumbers\"]);\n    } else if (found > -1 && !options.lineNumbers) {\n      options.gutters = options.gutters.slice(0);\n      options.gutters.splice(found, 1);\n    }\n  }\n\n  // Since the delta values reported on mouse wheel events are\n  // unstandardized between browsers and even browser versions, and\n  // generally horribly unpredictable, this code starts by measuring\n  // the scroll effect that the first few mouse wheel events have,\n  // and, from that, detects the way it can convert deltas to pixel\n  // offsets afterwards.\n  //\n  // The reason we want to know the amount a wheel event will scroll\n  // is that it gives us a chance to update the display before the\n  // actual scrolling happens, reducing flickering.\n\n  var wheelSamples = 0, wheelPixelsPerUnit = null;\n  // Fill in a browser-detected starting value on browsers where we\n  // know one. These don't have to be accurate -- the result of them\n  // being wrong would just be a slight flicker on the first wheel\n  // scroll (if it is large enough).\n  if (ie) { wheelPixelsPerUnit = -.53; }\n  else if (gecko) { wheelPixelsPerUnit = 15; }\n  else if (chrome) { wheelPixelsPerUnit = -.7; }\n  else if (safari) { wheelPixelsPerUnit = -1/3; }\n\n  function wheelEventDelta(e) {\n    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;\n    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }\n    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }\n    else if (dy == null) { dy = e.wheelDelta; }\n    return {x: dx, y: dy}\n  }\n  function wheelEventPixels(e) {\n    var delta = wheelEventDelta(e);\n    delta.x *= wheelPixelsPerUnit;\n    delta.y *= wheelPixelsPerUnit;\n    return delta\n  }\n\n  function onScrollWheel(cm, e) {\n    var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;\n\n    var display = cm.display, scroll = display.scroller;\n    // Quit if there's nothing to scroll here\n    var canScrollX = scroll.scrollWidth > scroll.clientWidth;\n    var canScrollY = scroll.scrollHeight > scroll.clientHeight;\n    if (!(dx && canScrollX || dy && canScrollY)) { return }\n\n    // Webkit browsers on OS X abort momentum scrolls when the target\n    // of the scroll event is removed from the scrollable element.\n    // This hack (see related code in patchDisplay) makes sure the\n    // element is kept around.\n    if (dy && mac && webkit) {\n      outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {\n        for (var i = 0; i < view.length; i++) {\n          if (view[i].node == cur) {\n            cm.display.currentWheelTarget = cur;\n            break outer\n          }\n        }\n      }\n    }\n\n    // On some browsers, horizontal scrolling will cause redraws to\n    // happen before the gutter has been realigned, causing it to\n    // wriggle around in a most unseemly way. When we have an\n    // estimated pixels/delta value, we just handle horizontal\n    // scrolling entirely here. It'll be slightly off from native, but\n    // better than glitching out.\n    if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {\n      if (dy && canScrollY)\n        { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }\n      setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));\n      // Only prevent default scrolling if vertical scrolling is\n      // actually possible. Otherwise, it causes vertical scroll\n      // jitter on OSX trackpads when deltaX is small and deltaY\n      // is large (issue #3579)\n      if (!dy || (dy && canScrollY))\n        { e_preventDefault(e); }\n      display.wheelStartX = null; // Abort measurement, if in progress\n      return\n    }\n\n    // 'Project' the visible viewport to cover the area that is being\n    // scrolled into view (if we know enough to estimate it).\n    if (dy && wheelPixelsPerUnit != null) {\n      var pixels = dy * wheelPixelsPerUnit;\n      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;\n      if (pixels < 0) { top = Math.max(0, top + pixels - 50); }\n      else { bot = Math.min(cm.doc.height, bot + pixels + 50); }\n      updateDisplaySimple(cm, {top: top, bottom: bot});\n    }\n\n    if (wheelSamples < 20) {\n      if (display.wheelStartX == null) {\n        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;\n        display.wheelDX = dx; display.wheelDY = dy;\n        setTimeout(function () {\n          if (display.wheelStartX == null) { return }\n          var movedX = scroll.scrollLeft - display.wheelStartX;\n          var movedY = scroll.scrollTop - display.wheelStartY;\n          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||\n            (movedX && display.wheelDX && movedX / display.wheelDX);\n          display.wheelStartX = display.wheelStartY = null;\n          if (!sample) { return }\n          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);\n          ++wheelSamples;\n        }, 200);\n      } else {\n        display.wheelDX += dx; display.wheelDY += dy;\n      }\n    }\n  }\n\n  // Selection objects are immutable. A new one is created every time\n  // the selection changes. A selection is one or more non-overlapping\n  // (and non-touching) ranges, sorted, and an integer that indicates\n  // which one is the primary selection (the one that's scrolled into\n  // view, that getCursor returns, etc).\n  var Selection = function(ranges, primIndex) {\n    this.ranges = ranges;\n    this.primIndex = primIndex;\n  };\n\n  Selection.prototype.primary = function () { return this.ranges[this.primIndex] };\n\n  Selection.prototype.equals = function (other) {\n      var this$1 = this;\n\n    if (other == this) { return true }\n    if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }\n    for (var i = 0; i < this.ranges.length; i++) {\n      var here = this$1.ranges[i], there = other.ranges[i];\n      if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }\n    }\n    return true\n  };\n\n  Selection.prototype.deepCopy = function () {\n      var this$1 = this;\n\n    var out = [];\n    for (var i = 0; i < this.ranges.length; i++)\n      { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }\n    return new Selection(out, this.primIndex)\n  };\n\n  Selection.prototype.somethingSelected = function () {\n      var this$1 = this;\n\n    for (var i = 0; i < this.ranges.length; i++)\n      { if (!this$1.ranges[i].empty()) { return true } }\n    return false\n  };\n\n  Selection.prototype.contains = function (pos, end) {\n      var this$1 = this;\n\n    if (!end) { end = pos; }\n    for (var i = 0; i < this.ranges.length; i++) {\n      var range = this$1.ranges[i];\n      if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)\n        { return i }\n    }\n    return -1\n  };\n\n  var Range = function(anchor, head) {\n    this.anchor = anchor; this.head = head;\n  };\n\n  Range.prototype.from = function () { return minPos(this.anchor, this.head) };\n  Range.prototype.to = function () { return maxPos(this.anchor, this.head) };\n  Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };\n\n  // Take an unsorted, potentially overlapping set of ranges, and\n  // build a selection out of it. 'Consumes' ranges array (modifying\n  // it).\n  function normalizeSelection(cm, ranges, primIndex) {\n    var mayTouch = cm && cm.options.selectionsMayTouch;\n    var prim = ranges[primIndex];\n    ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });\n    primIndex = indexOf(ranges, prim);\n    for (var i = 1; i < ranges.length; i++) {\n      var cur = ranges[i], prev = ranges[i - 1];\n      var diff = cmp(prev.to(), cur.from());\n      if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {\n        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());\n        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;\n        if (i <= primIndex) { --primIndex; }\n        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));\n      }\n    }\n    return new Selection(ranges, primIndex)\n  }\n\n  function simpleSelection(anchor, head) {\n    return new Selection([new Range(anchor, head || anchor)], 0)\n  }\n\n  // Compute the position of the end of a change (its 'to' property\n  // refers to the pre-change end).\n  function changeEnd(change) {\n    if (!change.text) { return change.to }\n    return Pos(change.from.line + change.text.length - 1,\n               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))\n  }\n\n  // Adjust a position to refer to the post-change position of the\n  // same text, or the end of the change if the change covers it.\n  function adjustForChange(pos, change) {\n    if (cmp(pos, change.from) < 0) { return pos }\n    if (cmp(pos, change.to) <= 0) { return changeEnd(change) }\n\n    var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;\n    if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }\n    return Pos(line, ch)\n  }\n\n  function computeSelAfterChange(doc, change) {\n    var out = [];\n    for (var i = 0; i < doc.sel.ranges.length; i++) {\n      var range = doc.sel.ranges[i];\n      out.push(new Range(adjustForChange(range.anchor, change),\n                         adjustForChange(range.head, change)));\n    }\n    return normalizeSelection(doc.cm, out, doc.sel.primIndex)\n  }\n\n  function offsetPos(pos, old, nw) {\n    if (pos.line == old.line)\n      { return Pos(nw.line, pos.ch - old.ch + nw.ch) }\n    else\n      { return Pos(nw.line + (pos.line - old.line), pos.ch) }\n  }\n\n  // Used by replaceSelections to allow moving the selection to the\n  // start or around the replaced test. Hint may be \"start\" or \"around\".\n  function computeReplacedSel(doc, changes, hint) {\n    var out = [];\n    var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;\n    for (var i = 0; i < changes.length; i++) {\n      var change = changes[i];\n      var from = offsetPos(change.from, oldPrev, newPrev);\n      var to = offsetPos(changeEnd(change), oldPrev, newPrev);\n      oldPrev = change.to;\n      newPrev = to;\n      if (hint == \"around\") {\n        var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;\n        out[i] = new Range(inv ? to : from, inv ? from : to);\n      } else {\n        out[i] = new Range(from, from);\n      }\n    }\n    return new Selection(out, doc.sel.primIndex)\n  }\n\n  // Used to get the editor into a consistent state again when options change.\n\n  function loadMode(cm) {\n    cm.doc.mode = getMode(cm.options, cm.doc.modeOption);\n    resetModeState(cm);\n  }\n\n  function resetModeState(cm) {\n    cm.doc.iter(function (line) {\n      if (line.stateAfter) { line.stateAfter = null; }\n      if (line.styles) { line.styles = null; }\n    });\n    cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;\n    startWorker(cm, 100);\n    cm.state.modeGen++;\n    if (cm.curOp) { regChange(cm); }\n  }\n\n  // DOCUMENT DATA STRUCTURE\n\n  // By default, updates that start and end at the beginning of a line\n  // are treated specially, in order to make the association of line\n  // widgets and marker elements with the text behave more intuitive.\n  function isWholeLineUpdate(doc, change) {\n    return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == \"\" &&\n      (!doc.cm || doc.cm.options.wholeLineUpdateBefore)\n  }\n\n  // Perform a change on the document data structure.\n  function updateDoc(doc, change, markedSpans, estimateHeight$$1) {\n    function spansFor(n) {return markedSpans ? markedSpans[n] : null}\n    function update(line, text, spans) {\n      updateLine(line, text, spans, estimateHeight$$1);\n      signalLater(line, \"change\", line, change);\n    }\n    function linesFor(start, end) {\n      var result = [];\n      for (var i = start; i < end; ++i)\n        { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }\n      return result\n    }\n\n    var from = change.from, to = change.to, text = change.text;\n    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);\n    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;\n\n    // Adjust the line structure\n    if (change.full) {\n      doc.insert(0, linesFor(0, text.length));\n      doc.remove(text.length, doc.size - text.length);\n    } else if (isWholeLineUpdate(doc, change)) {\n      // This is a whole-line replace. Treated specially to make\n      // sure line objects move the way they are supposed to.\n      var added = linesFor(0, text.length - 1);\n      update(lastLine, lastLine.text, lastSpans);\n      if (nlines) { doc.remove(from.line, nlines); }\n      if (added.length) { doc.insert(from.line, added); }\n    } else if (firstLine == lastLine) {\n      if (text.length == 1) {\n        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);\n      } else {\n        var added$1 = linesFor(1, text.length - 1);\n        added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));\n        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n        doc.insert(from.line + 1, added$1);\n      }\n    } else if (text.length == 1) {\n      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));\n      doc.remove(from.line + 1, nlines);\n    } else {\n      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);\n      var added$2 = linesFor(1, text.length - 1);\n      if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }\n      doc.insert(from.line + 1, added$2);\n    }\n\n    signalLater(doc, \"change\", doc, change);\n  }\n\n  // Call f for all linked documents.\n  function linkedDocs(doc, f, sharedHistOnly) {\n    function propagate(doc, skip, sharedHist) {\n      if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {\n        var rel = doc.linked[i];\n        if (rel.doc == skip) { continue }\n        var shared = sharedHist && rel.sharedHist;\n        if (sharedHistOnly && !shared) { continue }\n        f(rel.doc, shared);\n        propagate(rel.doc, doc, shared);\n      } }\n    }\n    propagate(doc, null, true);\n  }\n\n  // Attach a document to an editor.\n  function attachDoc(cm, doc) {\n    if (doc.cm) { throw new Error(\"This document is already in use.\") }\n    cm.doc = doc;\n    doc.cm = cm;\n    estimateLineHeights(cm);\n    loadMode(cm);\n    setDirectionClass(cm);\n    if (!cm.options.lineWrapping) { findMaxLine(cm); }\n    cm.options.mode = doc.modeOption;\n    regChange(cm);\n  }\n\n  function setDirectionClass(cm) {\n  (cm.doc.direction == \"rtl\" ? addClass : rmClass)(cm.display.lineDiv, \"CodeMirror-rtl\");\n  }\n\n  function directionChanged(cm) {\n    runInOp(cm, function () {\n      setDirectionClass(cm);\n      regChange(cm);\n    });\n  }\n\n  function History(startGen) {\n    // Arrays of change events and selections. Doing something adds an\n    // event to done and clears undo. Undoing moves events from done\n    // to undone, redoing moves them in the other direction.\n    this.done = []; this.undone = [];\n    this.undoDepth = Infinity;\n    // Used to track when changes can be merged into a single undo\n    // event\n    this.lastModTime = this.lastSelTime = 0;\n    this.lastOp = this.lastSelOp = null;\n    this.lastOrigin = this.lastSelOrigin = null;\n    // Used by the isClean() method\n    this.generation = this.maxGeneration = startGen || 1;\n  }\n\n  // Create a history change event from an updateDoc-style change\n  // object.\n  function historyChangeFromChange(doc, change) {\n    var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};\n    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);\n    linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);\n    return histChange\n  }\n\n  // Pop all selection events off the end of a history array. Stop at\n  // a change event.\n  function clearSelectionEvents(array) {\n    while (array.length) {\n      var last = lst(array);\n      if (last.ranges) { array.pop(); }\n      else { break }\n    }\n  }\n\n  // Find the top change event in the history. Pop off selection\n  // events that are in the way.\n  function lastChangeEvent(hist, force) {\n    if (force) {\n      clearSelectionEvents(hist.done);\n      return lst(hist.done)\n    } else if (hist.done.length && !lst(hist.done).ranges) {\n      return lst(hist.done)\n    } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {\n      hist.done.pop();\n      return lst(hist.done)\n    }\n  }\n\n  // Register a change in the history. Merges changes that are within\n  // a single operation, or are close together with an origin that\n  // allows merging (starting with \"+\") into a single event.\n  function addChangeToHistory(doc, change, selAfter, opId) {\n    var hist = doc.history;\n    hist.undone.length = 0;\n    var time = +new Date, cur;\n    var last;\n\n    if ((hist.lastOp == opId ||\n         hist.lastOrigin == change.origin && change.origin &&\n         ((change.origin.charAt(0) == \"+\" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||\n          change.origin.charAt(0) == \"*\")) &&\n        (cur = lastChangeEvent(hist, hist.lastOp == opId))) {\n      // Merge this change into the last event\n      last = lst(cur.changes);\n      if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {\n        // Optimized case for simple insertion -- don't want to add\n        // new changesets for every character typed\n        last.to = changeEnd(change);\n      } else {\n        // Add new sub-event\n        cur.changes.push(historyChangeFromChange(doc, change));\n      }\n    } else {\n      // Can not be merged, start a new event.\n      var before = lst(hist.done);\n      if (!before || !before.ranges)\n        { pushSelectionToHistory(doc.sel, hist.done); }\n      cur = {changes: [historyChangeFromChange(doc, change)],\n             generation: hist.generation};\n      hist.done.push(cur);\n      while (hist.done.length > hist.undoDepth) {\n        hist.done.shift();\n        if (!hist.done[0].ranges) { hist.done.shift(); }\n      }\n    }\n    hist.done.push(selAfter);\n    hist.generation = ++hist.maxGeneration;\n    hist.lastModTime = hist.lastSelTime = time;\n    hist.lastOp = hist.lastSelOp = opId;\n    hist.lastOrigin = hist.lastSelOrigin = change.origin;\n\n    if (!last) { signal(doc, \"historyAdded\"); }\n  }\n\n  function selectionEventCanBeMerged(doc, origin, prev, sel) {\n    var ch = origin.charAt(0);\n    return ch == \"*\" ||\n      ch == \"+\" &&\n      prev.ranges.length == sel.ranges.length &&\n      prev.somethingSelected() == sel.somethingSelected() &&\n      new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)\n  }\n\n  // Called whenever the selection changes, sets the new selection as\n  // the pending selection in the history, and pushes the old pending\n  // selection into the 'done' array when it was significantly\n  // different (in number of selected ranges, emptiness, or time).\n  function addSelectionToHistory(doc, sel, opId, options) {\n    var hist = doc.history, origin = options && options.origin;\n\n    // A new event is started when the previous origin does not match\n    // the current, or the origins don't allow matching. Origins\n    // starting with * are always merged, those starting with + are\n    // merged when similar and close together in time.\n    if (opId == hist.lastSelOp ||\n        (origin && hist.lastSelOrigin == origin &&\n         (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||\n          selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))\n      { hist.done[hist.done.length - 1] = sel; }\n    else\n      { pushSelectionToHistory(sel, hist.done); }\n\n    hist.lastSelTime = +new Date;\n    hist.lastSelOrigin = origin;\n    hist.lastSelOp = opId;\n    if (options && options.clearRedo !== false)\n      { clearSelectionEvents(hist.undone); }\n  }\n\n  function pushSelectionToHistory(sel, dest) {\n    var top = lst(dest);\n    if (!(top && top.ranges && top.equals(sel)))\n      { dest.push(sel); }\n  }\n\n  // Used to store marked span information in the history.\n  function attachLocalSpans(doc, change, from, to) {\n    var existing = change[\"spans_\" + doc.id], n = 0;\n    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n      if (line.markedSpans)\n        { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n      ++n;\n    });\n  }\n\n  // When un/re-doing restores text containing marked spans, those\n  // that have been explicitly cleared should not be restored.\n  function removeClearedSpans(spans) {\n    if (!spans) { return null }\n    var out;\n    for (var i = 0; i < spans.length; ++i) {\n      if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }\n      else if (out) { out.push(spans[i]); }\n    }\n    return !out ? spans : out.length ? out : null\n  }\n\n  // Retrieve and filter the old marked spans stored in a change event.\n  function getOldSpans(doc, change) {\n    var found = change[\"spans_\" + doc.id];\n    if (!found) { return null }\n    var nw = [];\n    for (var i = 0; i < change.text.length; ++i)\n      { nw.push(removeClearedSpans(found[i])); }\n    return nw\n  }\n\n  // Used for un/re-doing changes from the history. Combines the\n  // result of computing the existing spans with the set of spans that\n  // existed in the history (so that deleting around a span and then\n  // undoing brings back the span).\n  function mergeOldSpans(doc, change) {\n    var old = getOldSpans(doc, change);\n    var stretched = stretchSpansOverChange(doc, change);\n    if (!old) { return stretched }\n    if (!stretched) { return old }\n\n    for (var i = 0; i < old.length; ++i) {\n      var oldCur = old[i], stretchCur = stretched[i];\n      if (oldCur && stretchCur) {\n        spans: for (var j = 0; j < stretchCur.length; ++j) {\n          var span = stretchCur[j];\n          for (var k = 0; k < oldCur.length; ++k)\n            { if (oldCur[k].marker == span.marker) { continue spans } }\n          oldCur.push(span);\n        }\n      } else if (stretchCur) {\n        old[i] = stretchCur;\n      }\n    }\n    return old\n  }\n\n  // Used both to provide a JSON-safe object in .getHistory, and, when\n  // detaching a document, to split the history in two\n  function copyHistoryArray(events, newGroup, instantiateSel) {\n    var copy = [];\n    for (var i = 0; i < events.length; ++i) {\n      var event = events[i];\n      if (event.ranges) {\n        copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);\n        continue\n      }\n      var changes = event.changes, newChanges = [];\n      copy.push({changes: newChanges});\n      for (var j = 0; j < changes.length; ++j) {\n        var change = changes[j], m = (void 0);\n        newChanges.push({from: change.from, to: change.to, text: change.text});\n        if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\\d+)$/)) {\n          if (indexOf(newGroup, Number(m[1])) > -1) {\n            lst(newChanges)[prop] = change[prop];\n            delete change[prop];\n          }\n        } } }\n      }\n    }\n    return copy\n  }\n\n  // The 'scroll' parameter given to many of these indicated whether\n  // the new cursor position should be scrolled into view after\n  // modifying the selection.\n\n  // If shift is held or the extend flag is set, extends a range to\n  // include a given position (and optionally a second position).\n  // Otherwise, simply returns the range between the given positions.\n  // Used for cursor motion and such.\n  function extendRange(range, head, other, extend) {\n    if (extend) {\n      var anchor = range.anchor;\n      if (other) {\n        var posBefore = cmp(head, anchor) < 0;\n        if (posBefore != (cmp(other, anchor) < 0)) {\n          anchor = head;\n          head = other;\n        } else if (posBefore != (cmp(head, other) < 0)) {\n          head = other;\n        }\n      }\n      return new Range(anchor, head)\n    } else {\n      return new Range(other || head, head)\n    }\n  }\n\n  // Extend the primary selection range, discard the rest.\n  function extendSelection(doc, head, other, options, extend) {\n    if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }\n    setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);\n  }\n\n  // Extend all selections (pos is an array of selections with length\n  // equal the number of selections)\n  function extendSelections(doc, heads, options) {\n    var out = [];\n    var extend = doc.cm && (doc.cm.display.shift || doc.extend);\n    for (var i = 0; i < doc.sel.ranges.length; i++)\n      { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }\n    var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);\n    setSelection(doc, newSel, options);\n  }\n\n  // Updates a single range in the selection.\n  function replaceOneSelection(doc, i, range, options) {\n    var ranges = doc.sel.ranges.slice(0);\n    ranges[i] = range;\n    setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);\n  }\n\n  // Reset the selection to a single range.\n  function setSimpleSelection(doc, anchor, head, options) {\n    setSelection(doc, simpleSelection(anchor, head), options);\n  }\n\n  // Give beforeSelectionChange handlers a change to influence a\n  // selection update.\n  function filterSelectionChange(doc, sel, options) {\n    var obj = {\n      ranges: sel.ranges,\n      update: function(ranges) {\n        var this$1 = this;\n\n        this.ranges = [];\n        for (var i = 0; i < ranges.length; i++)\n          { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),\n                                     clipPos(doc, ranges[i].head)); }\n      },\n      origin: options && options.origin\n    };\n    signal(doc, \"beforeSelectionChange\", doc, obj);\n    if (doc.cm) { signal(doc.cm, \"beforeSelectionChange\", doc.cm, obj); }\n    if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }\n    else { return sel }\n  }\n\n  function setSelectionReplaceHistory(doc, sel, options) {\n    var done = doc.history.done, last = lst(done);\n    if (last && last.ranges) {\n      done[done.length - 1] = sel;\n      setSelectionNoUndo(doc, sel, options);\n    } else {\n      setSelection(doc, sel, options);\n    }\n  }\n\n  // Set a new selection.\n  function setSelection(doc, sel, options) {\n    setSelectionNoUndo(doc, sel, options);\n    addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);\n  }\n\n  function setSelectionNoUndo(doc, sel, options) {\n    if (hasHandler(doc, \"beforeSelectionChange\") || doc.cm && hasHandler(doc.cm, \"beforeSelectionChange\"))\n      { sel = filterSelectionChange(doc, sel, options); }\n\n    var bias = options && options.bias ||\n      (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);\n    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));\n\n    if (!(options && options.scroll === false) && doc.cm)\n      { ensureCursorVisible(doc.cm); }\n  }\n\n  function setSelectionInner(doc, sel) {\n    if (sel.equals(doc.sel)) { return }\n\n    doc.sel = sel;\n\n    if (doc.cm) {\n      doc.cm.curOp.updateInput = 1;\n      doc.cm.curOp.selectionChanged = true;\n      signalCursorActivity(doc.cm);\n    }\n    signalLater(doc, \"cursorActivity\", doc);\n  }\n\n  // Verify that the selection does not partially select any atomic\n  // marked ranges.\n  function reCheckSelection(doc) {\n    setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));\n  }\n\n  // Return a selection that does not partially select any atomic\n  // ranges.\n  function skipAtomicInSelection(doc, sel, bias, mayClear) {\n    var out;\n    for (var i = 0; i < sel.ranges.length; i++) {\n      var range = sel.ranges[i];\n      var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];\n      var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);\n      var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);\n      if (out || newAnchor != range.anchor || newHead != range.head) {\n        if (!out) { out = sel.ranges.slice(0, i); }\n        out[i] = new Range(newAnchor, newHead);\n      }\n    }\n    return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel\n  }\n\n  function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {\n    var line = getLine(doc, pos.line);\n    if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {\n      var sp = line.markedSpans[i], m = sp.marker;\n      if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&\n          (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {\n        if (mayClear) {\n          signal(m, \"beforeCursorEnter\");\n          if (m.explicitlyCleared) {\n            if (!line.markedSpans) { break }\n            else {--i; continue}\n          }\n        }\n        if (!m.atomic) { continue }\n\n        if (oldPos) {\n          var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);\n          if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)\n            { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }\n          if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))\n            { return skipAtomicInner(doc, near, pos, dir, mayClear) }\n        }\n\n        var far = m.find(dir < 0 ? -1 : 1);\n        if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)\n          { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }\n        return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null\n      }\n    } }\n    return pos\n  }\n\n  // Ensure a given position is not inside an atomic range.\n  function skipAtomic(doc, pos, oldPos, bias, mayClear) {\n    var dir = bias || 1;\n    var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||\n        (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||\n        skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||\n        (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));\n    if (!found) {\n      doc.cantEdit = true;\n      return Pos(doc.first, 0)\n    }\n    return found\n  }\n\n  function movePos(doc, pos, dir, line) {\n    if (dir < 0 && pos.ch == 0) {\n      if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }\n      else { return null }\n    } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {\n      if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }\n      else { return null }\n    } else {\n      return new Pos(pos.line, pos.ch + dir)\n    }\n  }\n\n  function selectAll(cm) {\n    cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);\n  }\n\n  // UPDATING\n\n  // Allow \"beforeChange\" event handlers to influence a change\n  function filterChange(doc, change, update) {\n    var obj = {\n      canceled: false,\n      from: change.from,\n      to: change.to,\n      text: change.text,\n      origin: change.origin,\n      cancel: function () { return obj.canceled = true; }\n    };\n    if (update) { obj.update = function (from, to, text, origin) {\n      if (from) { obj.from = clipPos(doc, from); }\n      if (to) { obj.to = clipPos(doc, to); }\n      if (text) { obj.text = text; }\n      if (origin !== undefined) { obj.origin = origin; }\n    }; }\n    signal(doc, \"beforeChange\", doc, obj);\n    if (doc.cm) { signal(doc.cm, \"beforeChange\", doc.cm, obj); }\n\n    if (obj.canceled) {\n      if (doc.cm) { doc.cm.curOp.updateInput = 2; }\n      return null\n    }\n    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}\n  }\n\n  // Apply a change to a document, and add it to the document's\n  // history, and propagating it to all linked documents.\n  function makeChange(doc, change, ignoreReadOnly) {\n    if (doc.cm) {\n      if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }\n      if (doc.cm.state.suppressEdits) { return }\n    }\n\n    if (hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\")) {\n      change = filterChange(doc, change, true);\n      if (!change) { return }\n    }\n\n    // Possibly split or suppress the update based on the presence\n    // of read-only spans in its range.\n    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);\n    if (split) {\n      for (var i = split.length - 1; i >= 0; --i)\n        { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [\"\"] : change.text, origin: change.origin}); }\n    } else {\n      makeChangeInner(doc, change);\n    }\n  }\n\n  function makeChangeInner(doc, change) {\n    if (change.text.length == 1 && change.text[0] == \"\" && cmp(change.from, change.to) == 0) { return }\n    var selAfter = computeSelAfterChange(doc, change);\n    addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);\n\n    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));\n    var rebased = [];\n\n    linkedDocs(doc, function (doc, sharedHist) {\n      if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n        rebaseHist(doc.history, change);\n        rebased.push(doc.history);\n      }\n      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));\n    });\n  }\n\n  // Revert a change stored in a document's history.\n  function makeChangeFromHistory(doc, type, allowSelectionOnly) {\n    var suppress = doc.cm && doc.cm.state.suppressEdits;\n    if (suppress && !allowSelectionOnly) { return }\n\n    var hist = doc.history, event, selAfter = doc.sel;\n    var source = type == \"undo\" ? hist.done : hist.undone, dest = type == \"undo\" ? hist.undone : hist.done;\n\n    // Verify that there is a useable event (so that ctrl-z won't\n    // needlessly clear selection events)\n    var i = 0;\n    for (; i < source.length; i++) {\n      event = source[i];\n      if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)\n        { break }\n    }\n    if (i == source.length) { return }\n    hist.lastOrigin = hist.lastSelOrigin = null;\n\n    for (;;) {\n      event = source.pop();\n      if (event.ranges) {\n        pushSelectionToHistory(event, dest);\n        if (allowSelectionOnly && !event.equals(doc.sel)) {\n          setSelection(doc, event, {clearRedo: false});\n          return\n        }\n        selAfter = event;\n      } else if (suppress) {\n        source.push(event);\n        return\n      } else { break }\n    }\n\n    // Build up a reverse change object to add to the opposite history\n    // stack (redo when undoing, and vice versa).\n    var antiChanges = [];\n    pushSelectionToHistory(selAfter, dest);\n    dest.push({changes: antiChanges, generation: hist.generation});\n    hist.generation = event.generation || ++hist.maxGeneration;\n\n    var filter = hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\");\n\n    var loop = function ( i ) {\n      var change = event.changes[i];\n      change.origin = type;\n      if (filter && !filterChange(doc, change, false)) {\n        source.length = 0;\n        return {}\n      }\n\n      antiChanges.push(historyChangeFromChange(doc, change));\n\n      var after = i ? computeSelAfterChange(doc, change) : lst(source);\n      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));\n      if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }\n      var rebased = [];\n\n      // Propagate to the linked documents\n      linkedDocs(doc, function (doc, sharedHist) {\n        if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n          rebaseHist(doc.history, change);\n          rebased.push(doc.history);\n        }\n        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));\n      });\n    };\n\n    for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {\n      var returned = loop( i$1 );\n\n      if ( returned ) return returned.v;\n    }\n  }\n\n  // Sub-views need their line numbers shifted when text is added\n  // above or below them in the parent document.\n  function shiftDoc(doc, distance) {\n    if (distance == 0) { return }\n    doc.first += distance;\n    doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(\n      Pos(range.anchor.line + distance, range.anchor.ch),\n      Pos(range.head.line + distance, range.head.ch)\n    ); }), doc.sel.primIndex);\n    if (doc.cm) {\n      regChange(doc.cm, doc.first, doc.first - distance, distance);\n      for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)\n        { regLineChange(doc.cm, l, \"gutter\"); }\n    }\n  }\n\n  // More lower-level change function, handling only a single document\n  // (not linked ones).\n  function makeChangeSingleDoc(doc, change, selAfter, spans) {\n    if (doc.cm && !doc.cm.curOp)\n      { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }\n\n    if (change.to.line < doc.first) {\n      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));\n      return\n    }\n    if (change.from.line > doc.lastLine()) { return }\n\n    // Clip the change to the size of this doc\n    if (change.from.line < doc.first) {\n      var shift = change.text.length - 1 - (doc.first - change.from.line);\n      shiftDoc(doc, shift);\n      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),\n                text: [lst(change.text)], origin: change.origin};\n    }\n    var last = doc.lastLine();\n    if (change.to.line > last) {\n      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),\n                text: [change.text[0]], origin: change.origin};\n    }\n\n    change.removed = getBetween(doc, change.from, change.to);\n\n    if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }\n    if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }\n    else { updateDoc(doc, change, spans); }\n    setSelectionNoUndo(doc, selAfter, sel_dontScroll);\n  }\n\n  // Handle the interaction of a change to a document with the editor\n  // that this document is part of.\n  function makeChangeSingleDocInEditor(cm, change, spans) {\n    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;\n\n    var recomputeMaxLength = false, checkWidthStart = from.line;\n    if (!cm.options.lineWrapping) {\n      checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));\n      doc.iter(checkWidthStart, to.line + 1, function (line) {\n        if (line == display.maxLine) {\n          recomputeMaxLength = true;\n          return true\n        }\n      });\n    }\n\n    if (doc.sel.contains(change.from, change.to) > -1)\n      { signalCursorActivity(cm); }\n\n    updateDoc(doc, change, spans, estimateHeight(cm));\n\n    if (!cm.options.lineWrapping) {\n      doc.iter(checkWidthStart, from.line + change.text.length, function (line) {\n        var len = lineLength(line);\n        if (len > display.maxLineLength) {\n          display.maxLine = line;\n          display.maxLineLength = len;\n          display.maxLineChanged = true;\n          recomputeMaxLength = false;\n        }\n      });\n      if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }\n    }\n\n    retreatFrontier(doc, from.line);\n    startWorker(cm, 400);\n\n    var lendiff = change.text.length - (to.line - from.line) - 1;\n    // Remember that these lines changed, for updating the display\n    if (change.full)\n      { regChange(cm); }\n    else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))\n      { regLineChange(cm, from.line, \"text\"); }\n    else\n      { regChange(cm, from.line, to.line + 1, lendiff); }\n\n    var changesHandler = hasHandler(cm, \"changes\"), changeHandler = hasHandler(cm, \"change\");\n    if (changeHandler || changesHandler) {\n      var obj = {\n        from: from, to: to,\n        text: change.text,\n        removed: change.removed,\n        origin: change.origin\n      };\n      if (changeHandler) { signalLater(cm, \"change\", cm, obj); }\n      if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }\n    }\n    cm.display.selForContextMenu = null;\n  }\n\n  function replaceRange(doc, code, from, to, origin) {\n    var assign;\n\n    if (!to) { to = from; }\n    if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }\n    if (typeof code == \"string\") { code = doc.splitLines(code); }\n    makeChange(doc, {from: from, to: to, text: code, origin: origin});\n  }\n\n  // Rebasing/resetting history to deal with externally-sourced changes\n\n  function rebaseHistSelSingle(pos, from, to, diff) {\n    if (to < pos.line) {\n      pos.line += diff;\n    } else if (from < pos.line) {\n      pos.line = from;\n      pos.ch = 0;\n    }\n  }\n\n  // Tries to rebase an array of history events given a change in the\n  // document. If the change touches the same lines as the event, the\n  // event, and everything 'behind' it, is discarded. If the change is\n  // before the event, the event's positions are updated. Uses a\n  // copy-on-write scheme for the positions, to avoid having to\n  // reallocate them all on every rebase, but also avoid problems with\n  // shared position objects being unsafely updated.\n  function rebaseHistArray(array, from, to, diff) {\n    for (var i = 0; i < array.length; ++i) {\n      var sub = array[i], ok = true;\n      if (sub.ranges) {\n        if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }\n        for (var j = 0; j < sub.ranges.length; j++) {\n          rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);\n          rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);\n        }\n        continue\n      }\n      for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {\n        var cur = sub.changes[j$1];\n        if (to < cur.from.line) {\n          cur.from = Pos(cur.from.line + diff, cur.from.ch);\n          cur.to = Pos(cur.to.line + diff, cur.to.ch);\n        } else if (from <= cur.to.line) {\n          ok = false;\n          break\n        }\n      }\n      if (!ok) {\n        array.splice(0, i + 1);\n        i = 0;\n      }\n    }\n  }\n\n  function rebaseHist(hist, change) {\n    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;\n    rebaseHistArray(hist.done, from, to, diff);\n    rebaseHistArray(hist.undone, from, to, diff);\n  }\n\n  // Utility for applying a change to a line by handle or number,\n  // returning the number and optionally registering the line as\n  // changed.\n  function changeLine(doc, handle, changeType, op) {\n    var no = handle, line = handle;\n    if (typeof handle == \"number\") { line = getLine(doc, clipLine(doc, handle)); }\n    else { no = lineNo(handle); }\n    if (no == null) { return null }\n    if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }\n    return line\n  }\n\n  // The document is represented as a BTree consisting of leaves, with\n  // chunk of lines in them, and branches, with up to ten leaves or\n  // other branch nodes below them. The top node is always a branch\n  // node, and is the document object itself (meaning it has\n  // additional methods and properties).\n  //\n  // All nodes have parent links. The tree is used both to go from\n  // line numbers to line objects, and to go from objects to numbers.\n  // It also indexes by height, and is used to convert between height\n  // and line object, and to find the total height of the document.\n  //\n  // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html\n\n  function LeafChunk(lines) {\n    var this$1 = this;\n\n    this.lines = lines;\n    this.parent = null;\n    var height = 0;\n    for (var i = 0; i < lines.length; ++i) {\n      lines[i].parent = this$1;\n      height += lines[i].height;\n    }\n    this.height = height;\n  }\n\n  LeafChunk.prototype = {\n    chunkSize: function() { return this.lines.length },\n\n    // Remove the n lines at offset 'at'.\n    removeInner: function(at, n) {\n      var this$1 = this;\n\n      for (var i = at, e = at + n; i < e; ++i) {\n        var line = this$1.lines[i];\n        this$1.height -= line.height;\n        cleanUpLine(line);\n        signalLater(line, \"delete\");\n      }\n      this.lines.splice(at, n);\n    },\n\n    // Helper used to collapse a small branch into a single leaf.\n    collapse: function(lines) {\n      lines.push.apply(lines, this.lines);\n    },\n\n    // Insert the given array of lines at offset 'at', count them as\n    // having the given height.\n    insertInner: function(at, lines, height) {\n      var this$1 = this;\n\n      this.height += height;\n      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));\n      for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }\n    },\n\n    // Used to iterate over a part of the tree.\n    iterN: function(at, n, op) {\n      var this$1 = this;\n\n      for (var e = at + n; at < e; ++at)\n        { if (op(this$1.lines[at])) { return true } }\n    }\n  };\n\n  function BranchChunk(children) {\n    var this$1 = this;\n\n    this.children = children;\n    var size = 0, height = 0;\n    for (var i = 0; i < children.length; ++i) {\n      var ch = children[i];\n      size += ch.chunkSize(); height += ch.height;\n      ch.parent = this$1;\n    }\n    this.size = size;\n    this.height = height;\n    this.parent = null;\n  }\n\n  BranchChunk.prototype = {\n    chunkSize: function() { return this.size },\n\n    removeInner: function(at, n) {\n      var this$1 = this;\n\n      this.size -= n;\n      for (var i = 0; i < this.children.length; ++i) {\n        var child = this$1.children[i], sz = child.chunkSize();\n        if (at < sz) {\n          var rm = Math.min(n, sz - at), oldHeight = child.height;\n          child.removeInner(at, rm);\n          this$1.height -= oldHeight - child.height;\n          if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }\n          if ((n -= rm) == 0) { break }\n          at = 0;\n        } else { at -= sz; }\n      }\n      // If the result is smaller than 25 lines, ensure that it is a\n      // single leaf node.\n      if (this.size - n < 25 &&\n          (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {\n        var lines = [];\n        this.collapse(lines);\n        this.children = [new LeafChunk(lines)];\n        this.children[0].parent = this;\n      }\n    },\n\n    collapse: function(lines) {\n      var this$1 = this;\n\n      for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }\n    },\n\n    insertInner: function(at, lines, height) {\n      var this$1 = this;\n\n      this.size += lines.length;\n      this.height += height;\n      for (var i = 0; i < this.children.length; ++i) {\n        var child = this$1.children[i], sz = child.chunkSize();\n        if (at <= sz) {\n          child.insertInner(at, lines, height);\n          if (child.lines && child.lines.length > 50) {\n            // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.\n            // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.\n            var remaining = child.lines.length % 25 + 25;\n            for (var pos = remaining; pos < child.lines.length;) {\n              var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));\n              child.height -= leaf.height;\n              this$1.children.splice(++i, 0, leaf);\n              leaf.parent = this$1;\n            }\n            child.lines = child.lines.slice(0, remaining);\n            this$1.maybeSpill();\n          }\n          break\n        }\n        at -= sz;\n      }\n    },\n\n    // When a node has grown, check whether it should be split.\n    maybeSpill: function() {\n      if (this.children.length <= 10) { return }\n      var me = this;\n      do {\n        var spilled = me.children.splice(me.children.length - 5, 5);\n        var sibling = new BranchChunk(spilled);\n        if (!me.parent) { // Become the parent node\n          var copy = new BranchChunk(me.children);\n          copy.parent = me;\n          me.children = [copy, sibling];\n          me = copy;\n       } else {\n          me.size -= sibling.size;\n          me.height -= sibling.height;\n          var myIndex = indexOf(me.parent.children, me);\n          me.parent.children.splice(myIndex + 1, 0, sibling);\n        }\n        sibling.parent = me.parent;\n      } while (me.children.length > 10)\n      me.parent.maybeSpill();\n    },\n\n    iterN: function(at, n, op) {\n      var this$1 = this;\n\n      for (var i = 0; i < this.children.length; ++i) {\n        var child = this$1.children[i], sz = child.chunkSize();\n        if (at < sz) {\n          var used = Math.min(n, sz - at);\n          if (child.iterN(at, used, op)) { return true }\n          if ((n -= used) == 0) { break }\n          at = 0;\n        } else { at -= sz; }\n      }\n    }\n  };\n\n  // Line widgets are block elements displayed above or below a line.\n\n  var LineWidget = function(doc, node, options) {\n    var this$1 = this;\n\n    if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))\n      { this$1[opt] = options[opt]; } } }\n    this.doc = doc;\n    this.node = node;\n  };\n\n  LineWidget.prototype.clear = function () {\n      var this$1 = this;\n\n    var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);\n    if (no == null || !ws) { return }\n    for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }\n    if (!ws.length) { line.widgets = null; }\n    var height = widgetHeight(this);\n    updateLineHeight(line, Math.max(0, line.height - height));\n    if (cm) {\n      runInOp(cm, function () {\n        adjustScrollWhenAboveVisible(cm, line, -height);\n        regLineChange(cm, no, \"widget\");\n      });\n      signalLater(cm, \"lineWidgetCleared\", cm, this, no);\n    }\n  };\n\n  LineWidget.prototype.changed = function () {\n      var this$1 = this;\n\n    var oldH = this.height, cm = this.doc.cm, line = this.line;\n    this.height = null;\n    var diff = widgetHeight(this) - oldH;\n    if (!diff) { return }\n    if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }\n    if (cm) {\n      runInOp(cm, function () {\n        cm.curOp.forceUpdate = true;\n        adjustScrollWhenAboveVisible(cm, line, diff);\n        signalLater(cm, \"lineWidgetChanged\", cm, this$1, lineNo(line));\n      });\n    }\n  };\n  eventMixin(LineWidget);\n\n  function adjustScrollWhenAboveVisible(cm, line, diff) {\n    if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))\n      { addToScrollTop(cm, diff); }\n  }\n\n  function addLineWidget(doc, handle, node, options) {\n    var widget = new LineWidget(doc, node, options);\n    var cm = doc.cm;\n    if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }\n    changeLine(doc, handle, \"widget\", function (line) {\n      var widgets = line.widgets || (line.widgets = []);\n      if (widget.insertAt == null) { widgets.push(widget); }\n      else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }\n      widget.line = line;\n      if (cm && !lineIsHidden(doc, line)) {\n        var aboveVisible = heightAtLine(line) < doc.scrollTop;\n        updateLineHeight(line, line.height + widgetHeight(widget));\n        if (aboveVisible) { addToScrollTop(cm, widget.height); }\n        cm.curOp.forceUpdate = true;\n      }\n      return true\n    });\n    if (cm) { signalLater(cm, \"lineWidgetAdded\", cm, widget, typeof handle == \"number\" ? handle : lineNo(handle)); }\n    return widget\n  }\n\n  // TEXTMARKERS\n\n  // Created with markText and setBookmark methods. A TextMarker is a\n  // handle that can be used to clear or find a marked position in the\n  // document. Line objects hold arrays (markedSpans) containing\n  // {from, to, marker} object pointing to such marker objects, and\n  // indicating that such a marker is present on that line. Multiple\n  // lines may point to the same marker when it spans across lines.\n  // The spans will have null for their from/to properties when the\n  // marker continues beyond the start/end of the line. Markers have\n  // links back to the lines they currently touch.\n\n  // Collapsed markers have unique ids, in order to be able to order\n  // them, which is needed for uniquely determining an outer marker\n  // when they overlap (they may nest, but not partially overlap).\n  var nextMarkerId = 0;\n\n  var TextMarker = function(doc, type) {\n    this.lines = [];\n    this.type = type;\n    this.doc = doc;\n    this.id = ++nextMarkerId;\n  };\n\n  // Clear the marker.\n  TextMarker.prototype.clear = function () {\n      var this$1 = this;\n\n    if (this.explicitlyCleared) { return }\n    var cm = this.doc.cm, withOp = cm && !cm.curOp;\n    if (withOp) { startOperation(cm); }\n    if (hasHandler(this, \"clear\")) {\n      var found = this.find();\n      if (found) { signalLater(this, \"clear\", found.from, found.to); }\n    }\n    var min = null, max = null;\n    for (var i = 0; i < this.lines.length; ++i) {\n      var line = this$1.lines[i];\n      var span = getMarkedSpanFor(line.markedSpans, this$1);\n      if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), \"text\"); }\n      else if (cm) {\n        if (span.to != null) { max = lineNo(line); }\n        if (span.from != null) { min = lineNo(line); }\n      }\n      line.markedSpans = removeMarkedSpan(line.markedSpans, span);\n      if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)\n        { updateLineHeight(line, textHeight(cm.display)); }\n    }\n    if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {\n      var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);\n      if (len > cm.display.maxLineLength) {\n        cm.display.maxLine = visual;\n        cm.display.maxLineLength = len;\n        cm.display.maxLineChanged = true;\n      }\n    } }\n\n    if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }\n    this.lines.length = 0;\n    this.explicitlyCleared = true;\n    if (this.atomic && this.doc.cantEdit) {\n      this.doc.cantEdit = false;\n      if (cm) { reCheckSelection(cm.doc); }\n    }\n    if (cm) { signalLater(cm, \"markerCleared\", cm, this, min, max); }\n    if (withOp) { endOperation(cm); }\n    if (this.parent) { this.parent.clear(); }\n  };\n\n  // Find the position of the marker in the document. Returns a {from,\n  // to} object by default. Side can be passed to get a specific side\n  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the\n  // Pos objects returned contain a line object, rather than a line\n  // number (used to prevent looking up the same line twice).\n  TextMarker.prototype.find = function (side, lineObj) {\n      var this$1 = this;\n\n    if (side == null && this.type == \"bookmark\") { side = 1; }\n    var from, to;\n    for (var i = 0; i < this.lines.length; ++i) {\n      var line = this$1.lines[i];\n      var span = getMarkedSpanFor(line.markedSpans, this$1);\n      if (span.from != null) {\n        from = Pos(lineObj ? line : lineNo(line), span.from);\n        if (side == -1) { return from }\n      }\n      if (span.to != null) {\n        to = Pos(lineObj ? line : lineNo(line), span.to);\n        if (side == 1) { return to }\n      }\n    }\n    return from && {from: from, to: to}\n  };\n\n  // Signals that the marker's widget changed, and surrounding layout\n  // should be recomputed.\n  TextMarker.prototype.changed = function () {\n      var this$1 = this;\n\n    var pos = this.find(-1, true), widget = this, cm = this.doc.cm;\n    if (!pos || !cm) { return }\n    runInOp(cm, function () {\n      var line = pos.line, lineN = lineNo(pos.line);\n      var view = findViewForLine(cm, lineN);\n      if (view) {\n        clearLineMeasurementCacheFor(view);\n        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;\n      }\n      cm.curOp.updateMaxLine = true;\n      if (!lineIsHidden(widget.doc, line) && widget.height != null) {\n        var oldHeight = widget.height;\n        widget.height = null;\n        var dHeight = widgetHeight(widget) - oldHeight;\n        if (dHeight)\n          { updateLineHeight(line, line.height + dHeight); }\n      }\n      signalLater(cm, \"markerChanged\", cm, this$1);\n    });\n  };\n\n  TextMarker.prototype.attachLine = function (line) {\n    if (!this.lines.length && this.doc.cm) {\n      var op = this.doc.cm.curOp;\n      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)\n        { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }\n    }\n    this.lines.push(line);\n  };\n\n  TextMarker.prototype.detachLine = function (line) {\n    this.lines.splice(indexOf(this.lines, line), 1);\n    if (!this.lines.length && this.doc.cm) {\n      var op = this.doc.cm.curOp\n      ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);\n    }\n  };\n  eventMixin(TextMarker);\n\n  // Create a marker, wire it up to the right lines, and\n  function markText(doc, from, to, options, type) {\n    // Shared markers (across linked documents) are handled separately\n    // (markTextShared will call out to this again, once per\n    // document).\n    if (options && options.shared) { return markTextShared(doc, from, to, options, type) }\n    // Ensure we are in an operation.\n    if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }\n\n    var marker = new TextMarker(doc, type), diff = cmp(from, to);\n    if (options) { copyObj(options, marker, false); }\n    // Don't connect empty markers unless clearWhenEmpty is false\n    if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)\n      { return marker }\n    if (marker.replacedWith) {\n      // Showing up as a widget implies collapsed (widget replaces text)\n      marker.collapsed = true;\n      marker.widgetNode = eltP(\"span\", [marker.replacedWith], \"CodeMirror-widget\");\n      if (!options.handleMouseEvents) { marker.widgetNode.setAttribute(\"cm-ignore-events\", \"true\"); }\n      if (options.insertLeft) { marker.widgetNode.insertLeft = true; }\n    }\n    if (marker.collapsed) {\n      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||\n          from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))\n        { throw new Error(\"Inserting collapsed marker partially overlapping an existing one\") }\n      seeCollapsedSpans();\n    }\n\n    if (marker.addToHistory)\n      { addChangeToHistory(doc, {from: from, to: to, origin: \"markText\"}, doc.sel, NaN); }\n\n    var curLine = from.line, cm = doc.cm, updateMaxLine;\n    doc.iter(curLine, to.line + 1, function (line) {\n      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)\n        { updateMaxLine = true; }\n      if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }\n      addMarkedSpan(line, new MarkedSpan(marker,\n                                         curLine == from.line ? from.ch : null,\n                                         curLine == to.line ? to.ch : null));\n      ++curLine;\n    });\n    // lineIsHidden depends on the presence of the spans, so needs a second pass\n    if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {\n      if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }\n    }); }\n\n    if (marker.clearOnEnter) { on(marker, \"beforeCursorEnter\", function () { return marker.clear(); }); }\n\n    if (marker.readOnly) {\n      seeReadOnlySpans();\n      if (doc.history.done.length || doc.history.undone.length)\n        { doc.clearHistory(); }\n    }\n    if (marker.collapsed) {\n      marker.id = ++nextMarkerId;\n      marker.atomic = true;\n    }\n    if (cm) {\n      // Sync editor state\n      if (updateMaxLine) { cm.curOp.updateMaxLine = true; }\n      if (marker.collapsed)\n        { regChange(cm, from.line, to.line + 1); }\n      else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||\n               marker.attributes || marker.title)\n        { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, \"text\"); } }\n      if (marker.atomic) { reCheckSelection(cm.doc); }\n      signalLater(cm, \"markerAdded\", cm, marker);\n    }\n    return marker\n  }\n\n  // SHARED TEXTMARKERS\n\n  // A shared marker spans multiple linked documents. It is\n  // implemented as a meta-marker-object controlling multiple normal\n  // markers.\n  var SharedTextMarker = function(markers, primary) {\n    var this$1 = this;\n\n    this.markers = markers;\n    this.primary = primary;\n    for (var i = 0; i < markers.length; ++i)\n      { markers[i].parent = this$1; }\n  };\n\n  SharedTextMarker.prototype.clear = function () {\n      var this$1 = this;\n\n    if (this.explicitlyCleared) { return }\n    this.explicitlyCleared = true;\n    for (var i = 0; i < this.markers.length; ++i)\n      { this$1.markers[i].clear(); }\n    signalLater(this, \"clear\");\n  };\n\n  SharedTextMarker.prototype.find = function (side, lineObj) {\n    return this.primary.find(side, lineObj)\n  };\n  eventMixin(SharedTextMarker);\n\n  function markTextShared(doc, from, to, options, type) {\n    options = copyObj(options);\n    options.shared = false;\n    var markers = [markText(doc, from, to, options, type)], primary = markers[0];\n    var widget = options.widgetNode;\n    linkedDocs(doc, function (doc) {\n      if (widget) { options.widgetNode = widget.cloneNode(true); }\n      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));\n      for (var i = 0; i < doc.linked.length; ++i)\n        { if (doc.linked[i].isParent) { return } }\n      primary = lst(markers);\n    });\n    return new SharedTextMarker(markers, primary)\n  }\n\n  function findSharedMarkers(doc) {\n    return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })\n  }\n\n  function copySharedMarkers(doc, markers) {\n    for (var i = 0; i < markers.length; i++) {\n      var marker = markers[i], pos = marker.find();\n      var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);\n      if (cmp(mFrom, mTo)) {\n        var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);\n        marker.markers.push(subMark);\n        subMark.parent = marker;\n      }\n    }\n  }\n\n  function detachSharedMarkers(markers) {\n    var loop = function ( i ) {\n      var marker = markers[i], linked = [marker.primary.doc];\n      linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });\n      for (var j = 0; j < marker.markers.length; j++) {\n        var subMarker = marker.markers[j];\n        if (indexOf(linked, subMarker.doc) == -1) {\n          subMarker.parent = null;\n          marker.markers.splice(j--, 1);\n        }\n      }\n    };\n\n    for (var i = 0; i < markers.length; i++) loop( i );\n  }\n\n  var nextDocId = 0;\n  var Doc = function(text, mode, firstLine, lineSep, direction) {\n    if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }\n    if (firstLine == null) { firstLine = 0; }\n\n    BranchChunk.call(this, [new LeafChunk([new Line(\"\", null)])]);\n    this.first = firstLine;\n    this.scrollTop = this.scrollLeft = 0;\n    this.cantEdit = false;\n    this.cleanGeneration = 1;\n    this.modeFrontier = this.highlightFrontier = firstLine;\n    var start = Pos(firstLine, 0);\n    this.sel = simpleSelection(start);\n    this.history = new History(null);\n    this.id = ++nextDocId;\n    this.modeOption = mode;\n    this.lineSep = lineSep;\n    this.direction = (direction == \"rtl\") ? \"rtl\" : \"ltr\";\n    this.extend = false;\n\n    if (typeof text == \"string\") { text = this.splitLines(text); }\n    updateDoc(this, {from: start, to: start, text: text});\n    setSelection(this, simpleSelection(start), sel_dontScroll);\n  };\n\n  Doc.prototype = createObj(BranchChunk.prototype, {\n    constructor: Doc,\n    // Iterate over the document. Supports two forms -- with only one\n    // argument, it calls that for each line in the document. With\n    // three, it iterates over the range given by the first two (with\n    // the second being non-inclusive).\n    iter: function(from, to, op) {\n      if (op) { this.iterN(from - this.first, to - from, op); }\n      else { this.iterN(this.first, this.first + this.size, from); }\n    },\n\n    // Non-public interface for adding and removing lines.\n    insert: function(at, lines) {\n      var height = 0;\n      for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }\n      this.insertInner(at - this.first, lines, height);\n    },\n    remove: function(at, n) { this.removeInner(at - this.first, n); },\n\n    // From here, the methods are part of the public interface. Most\n    // are also available from CodeMirror (editor) instances.\n\n    getValue: function(lineSep) {\n      var lines = getLines(this, this.first, this.first + this.size);\n      if (lineSep === false) { return lines }\n      return lines.join(lineSep || this.lineSeparator())\n    },\n    setValue: docMethodOp(function(code) {\n      var top = Pos(this.first, 0), last = this.first + this.size - 1;\n      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),\n                        text: this.splitLines(code), origin: \"setValue\", full: true}, true);\n      if (this.cm) { scrollToCoords(this.cm, 0, 0); }\n      setSelection(this, simpleSelection(top), sel_dontScroll);\n    }),\n    replaceRange: function(code, from, to, origin) {\n      from = clipPos(this, from);\n      to = to ? clipPos(this, to) : from;\n      replaceRange(this, code, from, to, origin);\n    },\n    getRange: function(from, to, lineSep) {\n      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));\n      if (lineSep === false) { return lines }\n      return lines.join(lineSep || this.lineSeparator())\n    },\n\n    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},\n\n    getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},\n    getLineNumber: function(line) {return lineNo(line)},\n\n    getLineHandleVisualStart: function(line) {\n      if (typeof line == \"number\") { line = getLine(this, line); }\n      return visualLine(line)\n    },\n\n    lineCount: function() {return this.size},\n    firstLine: function() {return this.first},\n    lastLine: function() {return this.first + this.size - 1},\n\n    clipPos: function(pos) {return clipPos(this, pos)},\n\n    getCursor: function(start) {\n      var range$$1 = this.sel.primary(), pos;\n      if (start == null || start == \"head\") { pos = range$$1.head; }\n      else if (start == \"anchor\") { pos = range$$1.anchor; }\n      else if (start == \"end\" || start == \"to\" || start === false) { pos = range$$1.to(); }\n      else { pos = range$$1.from(); }\n      return pos\n    },\n    listSelections: function() { return this.sel.ranges },\n    somethingSelected: function() {return this.sel.somethingSelected()},\n\n    setCursor: docMethodOp(function(line, ch, options) {\n      setSimpleSelection(this, clipPos(this, typeof line == \"number\" ? Pos(line, ch || 0) : line), null, options);\n    }),\n    setSelection: docMethodOp(function(anchor, head, options) {\n      setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);\n    }),\n    extendSelection: docMethodOp(function(head, other, options) {\n      extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);\n    }),\n    extendSelections: docMethodOp(function(heads, options) {\n      extendSelections(this, clipPosArray(this, heads), options);\n    }),\n    extendSelectionsBy: docMethodOp(function(f, options) {\n      var heads = map(this.sel.ranges, f);\n      extendSelections(this, clipPosArray(this, heads), options);\n    }),\n    setSelections: docMethodOp(function(ranges, primary, options) {\n      var this$1 = this;\n\n      if (!ranges.length) { return }\n      var out = [];\n      for (var i = 0; i < ranges.length; i++)\n        { out[i] = new Range(clipPos(this$1, ranges[i].anchor),\n                           clipPos(this$1, ranges[i].head)); }\n      if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }\n      setSelection(this, normalizeSelection(this.cm, out, primary), options);\n    }),\n    addSelection: docMethodOp(function(anchor, head, options) {\n      var ranges = this.sel.ranges.slice(0);\n      ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));\n      setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);\n    }),\n\n    getSelection: function(lineSep) {\n      var this$1 = this;\n\n      var ranges = this.sel.ranges, lines;\n      for (var i = 0; i < ranges.length; i++) {\n        var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());\n        lines = lines ? lines.concat(sel) : sel;\n      }\n      if (lineSep === false) { return lines }\n      else { return lines.join(lineSep || this.lineSeparator()) }\n    },\n    getSelections: function(lineSep) {\n      var this$1 = this;\n\n      var parts = [], ranges = this.sel.ranges;\n      for (var i = 0; i < ranges.length; i++) {\n        var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());\n        if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }\n        parts[i] = sel;\n      }\n      return parts\n    },\n    replaceSelection: function(code, collapse, origin) {\n      var dup = [];\n      for (var i = 0; i < this.sel.ranges.length; i++)\n        { dup[i] = code; }\n      this.replaceSelections(dup, collapse, origin || \"+input\");\n    },\n    replaceSelections: docMethodOp(function(code, collapse, origin) {\n      var this$1 = this;\n\n      var changes = [], sel = this.sel;\n      for (var i = 0; i < sel.ranges.length; i++) {\n        var range$$1 = sel.ranges[i];\n        changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};\n      }\n      var newSel = collapse && collapse != \"end\" && computeReplacedSel(this, changes, collapse);\n      for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)\n        { makeChange(this$1, changes[i$1]); }\n      if (newSel) { setSelectionReplaceHistory(this, newSel); }\n      else if (this.cm) { ensureCursorVisible(this.cm); }\n    }),\n    undo: docMethodOp(function() {makeChangeFromHistory(this, \"undo\");}),\n    redo: docMethodOp(function() {makeChangeFromHistory(this, \"redo\");}),\n    undoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"undo\", true);}),\n    redoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"redo\", true);}),\n\n    setExtending: function(val) {this.extend = val;},\n    getExtending: function() {return this.extend},\n\n    historySize: function() {\n      var hist = this.history, done = 0, undone = 0;\n      for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }\n      for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }\n      return {undo: done, redo: undone}\n    },\n    clearHistory: function() {this.history = new History(this.history.maxGeneration);},\n\n    markClean: function() {\n      this.cleanGeneration = this.changeGeneration(true);\n    },\n    changeGeneration: function(forceSplit) {\n      if (forceSplit)\n        { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }\n      return this.history.generation\n    },\n    isClean: function (gen) {\n      return this.history.generation == (gen || this.cleanGeneration)\n    },\n\n    getHistory: function() {\n      return {done: copyHistoryArray(this.history.done),\n              undone: copyHistoryArray(this.history.undone)}\n    },\n    setHistory: function(histData) {\n      var hist = this.history = new History(this.history.maxGeneration);\n      hist.done = copyHistoryArray(histData.done.slice(0), null, true);\n      hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);\n    },\n\n    setGutterMarker: docMethodOp(function(line, gutterID, value) {\n      return changeLine(this, line, \"gutter\", function (line) {\n        var markers = line.gutterMarkers || (line.gutterMarkers = {});\n        markers[gutterID] = value;\n        if (!value && isEmpty(markers)) { line.gutterMarkers = null; }\n        return true\n      })\n    }),\n\n    clearGutter: docMethodOp(function(gutterID) {\n      var this$1 = this;\n\n      this.iter(function (line) {\n        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {\n          changeLine(this$1, line, \"gutter\", function () {\n            line.gutterMarkers[gutterID] = null;\n            if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }\n            return true\n          });\n        }\n      });\n    }),\n\n    lineInfo: function(line) {\n      var n;\n      if (typeof line == \"number\") {\n        if (!isLine(this, line)) { return null }\n        n = line;\n        line = getLine(this, line);\n        if (!line) { return null }\n      } else {\n        n = lineNo(line);\n        if (n == null) { return null }\n      }\n      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,\n              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,\n              widgets: line.widgets}\n    },\n\n    addLineClass: docMethodOp(function(handle, where, cls) {\n      return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", function (line) {\n        var prop = where == \"text\" ? \"textClass\"\n                 : where == \"background\" ? \"bgClass\"\n                 : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\";\n        if (!line[prop]) { line[prop] = cls; }\n        else if (classTest(cls).test(line[prop])) { return false }\n        else { line[prop] += \" \" + cls; }\n        return true\n      })\n    }),\n    removeLineClass: docMethodOp(function(handle, where, cls) {\n      return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", function (line) {\n        var prop = where == \"text\" ? \"textClass\"\n                 : where == \"background\" ? \"bgClass\"\n                 : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\";\n        var cur = line[prop];\n        if (!cur) { return false }\n        else if (cls == null) { line[prop] = null; }\n        else {\n          var found = cur.match(classTest(cls));\n          if (!found) { return false }\n          var end = found.index + found[0].length;\n          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? \"\" : \" \") + cur.slice(end) || null;\n        }\n        return true\n      })\n    }),\n\n    addLineWidget: docMethodOp(function(handle, node, options) {\n      return addLineWidget(this, handle, node, options)\n    }),\n    removeLineWidget: function(widget) { widget.clear(); },\n\n    markText: function(from, to, options) {\n      return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || \"range\")\n    },\n    setBookmark: function(pos, options) {\n      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),\n                      insertLeft: options && options.insertLeft,\n                      clearWhenEmpty: false, shared: options && options.shared,\n                      handleMouseEvents: options && options.handleMouseEvents};\n      pos = clipPos(this, pos);\n      return markText(this, pos, pos, realOpts, \"bookmark\")\n    },\n    findMarksAt: function(pos) {\n      pos = clipPos(this, pos);\n      var markers = [], spans = getLine(this, pos.line).markedSpans;\n      if (spans) { for (var i = 0; i < spans.length; ++i) {\n        var span = spans[i];\n        if ((span.from == null || span.from <= pos.ch) &&\n            (span.to == null || span.to >= pos.ch))\n          { markers.push(span.marker.parent || span.marker); }\n      } }\n      return markers\n    },\n    findMarks: function(from, to, filter) {\n      from = clipPos(this, from); to = clipPos(this, to);\n      var found = [], lineNo$$1 = from.line;\n      this.iter(from.line, to.line + 1, function (line) {\n        var spans = line.markedSpans;\n        if (spans) { for (var i = 0; i < spans.length; i++) {\n          var span = spans[i];\n          if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||\n                span.from == null && lineNo$$1 != from.line ||\n                span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&\n              (!filter || filter(span.marker)))\n            { found.push(span.marker.parent || span.marker); }\n        } }\n        ++lineNo$$1;\n      });\n      return found\n    },\n    getAllMarks: function() {\n      var markers = [];\n      this.iter(function (line) {\n        var sps = line.markedSpans;\n        if (sps) { for (var i = 0; i < sps.length; ++i)\n          { if (sps[i].from != null) { markers.push(sps[i].marker); } } }\n      });\n      return markers\n    },\n\n    posFromIndex: function(off) {\n      var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;\n      this.iter(function (line) {\n        var sz = line.text.length + sepSize;\n        if (sz > off) { ch = off; return true }\n        off -= sz;\n        ++lineNo$$1;\n      });\n      return clipPos(this, Pos(lineNo$$1, ch))\n    },\n    indexFromPos: function (coords) {\n      coords = clipPos(this, coords);\n      var index = coords.ch;\n      if (coords.line < this.first || coords.ch < 0) { return 0 }\n      var sepSize = this.lineSeparator().length;\n      this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value\n        index += line.text.length + sepSize;\n      });\n      return index\n    },\n\n    copy: function(copyHistory) {\n      var doc = new Doc(getLines(this, this.first, this.first + this.size),\n                        this.modeOption, this.first, this.lineSep, this.direction);\n      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;\n      doc.sel = this.sel;\n      doc.extend = false;\n      if (copyHistory) {\n        doc.history.undoDepth = this.history.undoDepth;\n        doc.setHistory(this.getHistory());\n      }\n      return doc\n    },\n\n    linkedDoc: function(options) {\n      if (!options) { options = {}; }\n      var from = this.first, to = this.first + this.size;\n      if (options.from != null && options.from > from) { from = options.from; }\n      if (options.to != null && options.to < to) { to = options.to; }\n      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);\n      if (options.sharedHist) { copy.history = this.history\n      ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});\n      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];\n      copySharedMarkers(copy, findSharedMarkers(this));\n      return copy\n    },\n    unlinkDoc: function(other) {\n      var this$1 = this;\n\n      if (other instanceof CodeMirror) { other = other.doc; }\n      if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {\n        var link = this$1.linked[i];\n        if (link.doc != other) { continue }\n        this$1.linked.splice(i, 1);\n        other.unlinkDoc(this$1);\n        detachSharedMarkers(findSharedMarkers(this$1));\n        break\n      } }\n      // If the histories were shared, split them again\n      if (other.history == this.history) {\n        var splitIds = [other.id];\n        linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);\n        other.history = new History(null);\n        other.history.done = copyHistoryArray(this.history.done, splitIds);\n        other.history.undone = copyHistoryArray(this.history.undone, splitIds);\n      }\n    },\n    iterLinkedDocs: function(f) {linkedDocs(this, f);},\n\n    getMode: function() {return this.mode},\n    getEditor: function() {return this.cm},\n\n    splitLines: function(str) {\n      if (this.lineSep) { return str.split(this.lineSep) }\n      return splitLinesAuto(str)\n    },\n    lineSeparator: function() { return this.lineSep || \"\\n\" },\n\n    setDirection: docMethodOp(function (dir) {\n      if (dir != \"rtl\") { dir = \"ltr\"; }\n      if (dir == this.direction) { return }\n      this.direction = dir;\n      this.iter(function (line) { return line.order = null; });\n      if (this.cm) { directionChanged(this.cm); }\n    })\n  });\n\n  // Public alias.\n  Doc.prototype.eachLine = Doc.prototype.iter;\n\n  // Kludge to work around strange IE behavior where it'll sometimes\n  // re-fire a series of drag-related events right after the drop (#1551)\n  var lastDrop = 0;\n\n  function onDrop(e) {\n    var cm = this;\n    clearDragCursor(cm);\n    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))\n      { return }\n    e_preventDefault(e);\n    if (ie) { lastDrop = +new Date; }\n    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;\n    if (!pos || cm.isReadOnly()) { return }\n    // Might be a file drop, in which case we simply extract the text\n    // and insert it.\n    if (files && files.length && window.FileReader && window.File) {\n      var n = files.length, text = Array(n), read = 0;\n      var loadFile = function (file, i) {\n        if (cm.options.allowDropFileTypes &&\n            indexOf(cm.options.allowDropFileTypes, file.type) == -1)\n          { return }\n\n        var reader = new FileReader;\n        reader.onload = operation(cm, function () {\n          var content = reader.result;\n          if (/[\\x00-\\x08\\x0e-\\x1f]{2}/.test(content)) { content = \"\"; }\n          text[i] = content;\n          if (++read == n) {\n            pos = clipPos(cm.doc, pos);\n            var change = {from: pos, to: pos,\n                          text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),\n                          origin: \"paste\"};\n            makeChange(cm.doc, change);\n            setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));\n          }\n        });\n        reader.readAsText(file);\n      };\n      for (var i = 0; i < n; ++i) { loadFile(files[i], i); }\n    } else { // Normal drop\n      // Don't do a replace if the drop happened inside of the selected text.\n      if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {\n        cm.state.draggingText(e);\n        // Ensure the editor is re-focused\n        setTimeout(function () { return cm.display.input.focus(); }, 20);\n        return\n      }\n      try {\n        var text$1 = e.dataTransfer.getData(\"Text\");\n        if (text$1) {\n          var selected;\n          if (cm.state.draggingText && !cm.state.draggingText.copy)\n            { selected = cm.listSelections(); }\n          setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));\n          if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)\n            { replaceRange(cm.doc, \"\", selected[i$1].anchor, selected[i$1].head, \"drag\"); } }\n          cm.replaceSelection(text$1, \"around\", \"paste\");\n          cm.display.input.focus();\n        }\n      }\n      catch(e){}\n    }\n  }\n\n  function onDragStart(cm, e) {\n    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }\n    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }\n\n    e.dataTransfer.setData(\"Text\", cm.getSelection());\n    e.dataTransfer.effectAllowed = \"copyMove\";\n\n    // Use dummy image instead of default browsers image.\n    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.\n    if (e.dataTransfer.setDragImage && !safari) {\n      var img = elt(\"img\", null, null, \"position: fixed; left: 0; top: 0;\");\n      img.src = \"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\";\n      if (presto) {\n        img.width = img.height = 1;\n        cm.display.wrapper.appendChild(img);\n        // Force a relayout, or Opera won't use our image for some obscure reason\n        img._top = img.offsetTop;\n      }\n      e.dataTransfer.setDragImage(img, 0, 0);\n      if (presto) { img.parentNode.removeChild(img); }\n    }\n  }\n\n  function onDragOver(cm, e) {\n    var pos = posFromMouse(cm, e);\n    if (!pos) { return }\n    var frag = document.createDocumentFragment();\n    drawSelectionCursor(cm, pos, frag);\n    if (!cm.display.dragCursor) {\n      cm.display.dragCursor = elt(\"div\", null, \"CodeMirror-cursors CodeMirror-dragcursors\");\n      cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);\n    }\n    removeChildrenAndAdd(cm.display.dragCursor, frag);\n  }\n\n  function clearDragCursor(cm) {\n    if (cm.display.dragCursor) {\n      cm.display.lineSpace.removeChild(cm.display.dragCursor);\n      cm.display.dragCursor = null;\n    }\n  }\n\n  // These must be handled carefully, because naively registering a\n  // handler for each editor will cause the editors to never be\n  // garbage collected.\n\n  function forEachCodeMirror(f) {\n    if (!document.getElementsByClassName) { return }\n    var byClass = document.getElementsByClassName(\"CodeMirror\"), editors = [];\n    for (var i = 0; i < byClass.length; i++) {\n      var cm = byClass[i].CodeMirror;\n      if (cm) { editors.push(cm); }\n    }\n    if (editors.length) { editors[0].operation(function () {\n      for (var i = 0; i < editors.length; i++) { f(editors[i]); }\n    }); }\n  }\n\n  var globalsRegistered = false;\n  function ensureGlobalHandlers() {\n    if (globalsRegistered) { return }\n    registerGlobalHandlers();\n    globalsRegistered = true;\n  }\n  function registerGlobalHandlers() {\n    // When the window resizes, we need to refresh active editors.\n    var resizeTimer;\n    on(window, \"resize\", function () {\n      if (resizeTimer == null) { resizeTimer = setTimeout(function () {\n        resizeTimer = null;\n        forEachCodeMirror(onResize);\n      }, 100); }\n    });\n    // When the window loses focus, we want to show the editor as blurred\n    on(window, \"blur\", function () { return forEachCodeMirror(onBlur); });\n  }\n  // Called when the window resizes\n  function onResize(cm) {\n    var d = cm.display;\n    // Might be a text scaling operation, clear size caches.\n    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n    d.scrollbarsClipped = false;\n    cm.setSize();\n  }\n\n  var keyNames = {\n    3: \"Pause\", 8: \"Backspace\", 9: \"Tab\", 13: \"Enter\", 16: \"Shift\", 17: \"Ctrl\", 18: \"Alt\",\n    19: \"Pause\", 20: \"CapsLock\", 27: \"Esc\", 32: \"Space\", 33: \"PageUp\", 34: \"PageDown\", 35: \"End\",\n    36: \"Home\", 37: \"Left\", 38: \"Up\", 39: \"Right\", 40: \"Down\", 44: \"PrintScrn\", 45: \"Insert\",\n    46: \"Delete\", 59: \";\", 61: \"=\", 91: \"Mod\", 92: \"Mod\", 93: \"Mod\",\n    106: \"*\", 107: \"=\", 109: \"-\", 110: \".\", 111: \"/\", 127: \"Delete\", 145: \"ScrollLock\",\n    173: \"-\", 186: \";\", 187: \"=\", 188: \",\", 189: \"-\", 190: \".\", 191: \"/\", 192: \"`\", 219: \"[\", 220: \"\\\\\",\n    221: \"]\", 222: \"'\", 63232: \"Up\", 63233: \"Down\", 63234: \"Left\", 63235: \"Right\", 63272: \"Delete\",\n    63273: \"Home\", 63275: \"End\", 63276: \"PageUp\", 63277: \"PageDown\", 63302: \"Insert\"\n  };\n\n  // Number keys\n  for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }\n  // Alphabetic keys\n  for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }\n  // Function keys\n  for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = \"F\" + i$2; }\n\n  var keyMap = {};\n\n  keyMap.basic = {\n    \"Left\": \"goCharLeft\", \"Right\": \"goCharRight\", \"Up\": \"goLineUp\", \"Down\": \"goLineDown\",\n    \"End\": \"goLineEnd\", \"Home\": \"goLineStartSmart\", \"PageUp\": \"goPageUp\", \"PageDown\": \"goPageDown\",\n    \"Delete\": \"delCharAfter\", \"Backspace\": \"delCharBefore\", \"Shift-Backspace\": \"delCharBefore\",\n    \"Tab\": \"defaultTab\", \"Shift-Tab\": \"indentAuto\",\n    \"Enter\": \"newlineAndIndent\", \"Insert\": \"toggleOverwrite\",\n    \"Esc\": \"singleSelection\"\n  };\n  // Note that the save and find-related commands aren't defined by\n  // default. User code or addons can define them. Unknown commands\n  // are simply ignored.\n  keyMap.pcDefault = {\n    \"Ctrl-A\": \"selectAll\", \"Ctrl-D\": \"deleteLine\", \"Ctrl-Z\": \"undo\", \"Shift-Ctrl-Z\": \"redo\", \"Ctrl-Y\": \"redo\",\n    \"Ctrl-Home\": \"goDocStart\", \"Ctrl-End\": \"goDocEnd\", \"Ctrl-Up\": \"goLineUp\", \"Ctrl-Down\": \"goLineDown\",\n    \"Ctrl-Left\": \"goGroupLeft\", \"Ctrl-Right\": \"goGroupRight\", \"Alt-Left\": \"goLineStart\", \"Alt-Right\": \"goLineEnd\",\n    \"Ctrl-Backspace\": \"delGroupBefore\", \"Ctrl-Delete\": \"delGroupAfter\", \"Ctrl-S\": \"save\", \"Ctrl-F\": \"find\",\n    \"Ctrl-G\": \"findNext\", \"Shift-Ctrl-G\": \"findPrev\", \"Shift-Ctrl-F\": \"replace\", \"Shift-Ctrl-R\": \"replaceAll\",\n    \"Ctrl-[\": \"indentLess\", \"Ctrl-]\": \"indentMore\",\n    \"Ctrl-U\": \"undoSelection\", \"Shift-Ctrl-U\": \"redoSelection\", \"Alt-U\": \"redoSelection\",\n    \"fallthrough\": \"basic\"\n  };\n  // Very basic readline/emacs-style bindings, which are standard on Mac.\n  keyMap.emacsy = {\n    \"Ctrl-F\": \"goCharRight\", \"Ctrl-B\": \"goCharLeft\", \"Ctrl-P\": \"goLineUp\", \"Ctrl-N\": \"goLineDown\",\n    \"Alt-F\": \"goWordRight\", \"Alt-B\": \"goWordLeft\", \"Ctrl-A\": \"goLineStart\", \"Ctrl-E\": \"goLineEnd\",\n    \"Ctrl-V\": \"goPageDown\", \"Shift-Ctrl-V\": \"goPageUp\", \"Ctrl-D\": \"delCharAfter\", \"Ctrl-H\": \"delCharBefore\",\n    \"Alt-D\": \"delWordAfter\", \"Alt-Backspace\": \"delWordBefore\", \"Ctrl-K\": \"killLine\", \"Ctrl-T\": \"transposeChars\",\n    \"Ctrl-O\": \"openLine\"\n  };\n  keyMap.macDefault = {\n    \"Cmd-A\": \"selectAll\", \"Cmd-D\": \"deleteLine\", \"Cmd-Z\": \"undo\", \"Shift-Cmd-Z\": \"redo\", \"Cmd-Y\": \"redo\",\n    \"Cmd-Home\": \"goDocStart\", \"Cmd-Up\": \"goDocStart\", \"Cmd-End\": \"goDocEnd\", \"Cmd-Down\": \"goDocEnd\", \"Alt-Left\": \"goGroupLeft\",\n    \"Alt-Right\": \"goGroupRight\", \"Cmd-Left\": \"goLineLeft\", \"Cmd-Right\": \"goLineRight\", \"Alt-Backspace\": \"delGroupBefore\",\n    \"Ctrl-Alt-Backspace\": \"delGroupAfter\", \"Alt-Delete\": \"delGroupAfter\", \"Cmd-S\": \"save\", \"Cmd-F\": \"find\",\n    \"Cmd-G\": \"findNext\", \"Shift-Cmd-G\": \"findPrev\", \"Cmd-Alt-F\": \"replace\", \"Shift-Cmd-Alt-F\": \"replaceAll\",\n    \"Cmd-[\": \"indentLess\", \"Cmd-]\": \"indentMore\", \"Cmd-Backspace\": \"delWrappedLineLeft\", \"Cmd-Delete\": \"delWrappedLineRight\",\n    \"Cmd-U\": \"undoSelection\", \"Shift-Cmd-U\": \"redoSelection\", \"Ctrl-Up\": \"goDocStart\", \"Ctrl-Down\": \"goDocEnd\",\n    \"fallthrough\": [\"basic\", \"emacsy\"]\n  };\n  keyMap[\"default\"] = mac ? keyMap.macDefault : keyMap.pcDefault;\n\n  // KEYMAP DISPATCH\n\n  function normalizeKeyName(name) {\n    var parts = name.split(/-(?!$)/);\n    name = parts[parts.length - 1];\n    var alt, ctrl, shift, cmd;\n    for (var i = 0; i < parts.length - 1; i++) {\n      var mod = parts[i];\n      if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }\n      else if (/^a(lt)?$/i.test(mod)) { alt = true; }\n      else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }\n      else if (/^s(hift)?$/i.test(mod)) { shift = true; }\n      else { throw new Error(\"Unrecognized modifier name: \" + mod) }\n    }\n    if (alt) { name = \"Alt-\" + name; }\n    if (ctrl) { name = \"Ctrl-\" + name; }\n    if (cmd) { name = \"Cmd-\" + name; }\n    if (shift) { name = \"Shift-\" + name; }\n    return name\n  }\n\n  // This is a kludge to keep keymaps mostly working as raw objects\n  // (backwards compatibility) while at the same time support features\n  // like normalization and multi-stroke key bindings. It compiles a\n  // new normalized keymap, and then updates the old object to reflect\n  // this.\n  function normalizeKeyMap(keymap) {\n    var copy = {};\n    for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {\n      var value = keymap[keyname];\n      if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }\n      if (value == \"...\") { delete keymap[keyname]; continue }\n\n      var keys = map(keyname.split(\" \"), normalizeKeyName);\n      for (var i = 0; i < keys.length; i++) {\n        var val = (void 0), name = (void 0);\n        if (i == keys.length - 1) {\n          name = keys.join(\" \");\n          val = value;\n        } else {\n          name = keys.slice(0, i + 1).join(\" \");\n          val = \"...\";\n        }\n        var prev = copy[name];\n        if (!prev) { copy[name] = val; }\n        else if (prev != val) { throw new Error(\"Inconsistent bindings for \" + name) }\n      }\n      delete keymap[keyname];\n    } }\n    for (var prop in copy) { keymap[prop] = copy[prop]; }\n    return keymap\n  }\n\n  function lookupKey(key, map$$1, handle, context) {\n    map$$1 = getKeyMap(map$$1);\n    var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];\n    if (found === false) { return \"nothing\" }\n    if (found === \"...\") { return \"multi\" }\n    if (found != null && handle(found)) { return \"handled\" }\n\n    if (map$$1.fallthrough) {\n      if (Object.prototype.toString.call(map$$1.fallthrough) != \"[object Array]\")\n        { return lookupKey(key, map$$1.fallthrough, handle, context) }\n      for (var i = 0; i < map$$1.fallthrough.length; i++) {\n        var result = lookupKey(key, map$$1.fallthrough[i], handle, context);\n        if (result) { return result }\n      }\n    }\n  }\n\n  // Modifier key presses don't count as 'real' key presses for the\n  // purpose of keymap fallthrough.\n  function isModifierKey(value) {\n    var name = typeof value == \"string\" ? value : keyNames[value.keyCode];\n    return name == \"Ctrl\" || name == \"Alt\" || name == \"Shift\" || name == \"Mod\"\n  }\n\n  function addModifierNames(name, event, noShift) {\n    var base = name;\n    if (event.altKey && base != \"Alt\") { name = \"Alt-\" + name; }\n    if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != \"Ctrl\") { name = \"Ctrl-\" + name; }\n    if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != \"Cmd\") { name = \"Cmd-\" + name; }\n    if (!noShift && event.shiftKey && base != \"Shift\") { name = \"Shift-\" + name; }\n    return name\n  }\n\n  // Look up the name of a key as indicated by an event object.\n  function keyName(event, noShift) {\n    if (presto && event.keyCode == 34 && event[\"char\"]) { return false }\n    var name = keyNames[event.keyCode];\n    if (name == null || event.altGraphKey) { return false }\n    // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,\n    // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)\n    if (event.keyCode == 3 && event.code) { name = event.code; }\n    return addModifierNames(name, event, noShift)\n  }\n\n  function getKeyMap(val) {\n    return typeof val == \"string\" ? keyMap[val] : val\n  }\n\n  // Helper for deleting text near the selection(s), used to implement\n  // backspace, delete, and similar functionality.\n  function deleteNearSelection(cm, compute) {\n    var ranges = cm.doc.sel.ranges, kill = [];\n    // Build up a set of ranges to kill first, merging overlapping\n    // ranges.\n    for (var i = 0; i < ranges.length; i++) {\n      var toKill = compute(ranges[i]);\n      while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {\n        var replaced = kill.pop();\n        if (cmp(replaced.from, toKill.from) < 0) {\n          toKill.from = replaced.from;\n          break\n        }\n      }\n      kill.push(toKill);\n    }\n    // Next, remove those actual ranges.\n    runInOp(cm, function () {\n      for (var i = kill.length - 1; i >= 0; i--)\n        { replaceRange(cm.doc, \"\", kill[i].from, kill[i].to, \"+delete\"); }\n      ensureCursorVisible(cm);\n    });\n  }\n\n  function moveCharLogically(line, ch, dir) {\n    var target = skipExtendingChars(line.text, ch + dir, dir);\n    return target < 0 || target > line.text.length ? null : target\n  }\n\n  function moveLogically(line, start, dir) {\n    var ch = moveCharLogically(line, start.ch, dir);\n    return ch == null ? null : new Pos(start.line, ch, dir < 0 ? \"after\" : \"before\")\n  }\n\n  function endOfLine(visually, cm, lineObj, lineNo, dir) {\n    if (visually) {\n      var order = getOrder(lineObj, cm.doc.direction);\n      if (order) {\n        var part = dir < 0 ? lst(order) : order[0];\n        var moveInStorageOrder = (dir < 0) == (part.level == 1);\n        var sticky = moveInStorageOrder ? \"after\" : \"before\";\n        var ch;\n        // With a wrapped rtl chunk (possibly spanning multiple bidi parts),\n        // it could be that the last bidi part is not on the last visual line,\n        // since visual lines contain content order-consecutive chunks.\n        // Thus, in rtl, we are looking for the first (content-order) character\n        // in the rtl chunk that is on the last line (that is, the same line\n        // as the last (content-order) character).\n        if (part.level > 0 || cm.doc.direction == \"rtl\") {\n          var prep = prepareMeasureForLine(cm, lineObj);\n          ch = dir < 0 ? lineObj.text.length - 1 : 0;\n          var targetTop = measureCharPrepared(cm, prep, ch).top;\n          ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);\n          if (sticky == \"before\") { ch = moveCharLogically(lineObj, ch, 1); }\n        } else { ch = dir < 0 ? part.to : part.from; }\n        return new Pos(lineNo, ch, sticky)\n      }\n    }\n    return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? \"before\" : \"after\")\n  }\n\n  function moveVisually(cm, line, start, dir) {\n    var bidi = getOrder(line, cm.doc.direction);\n    if (!bidi) { return moveLogically(line, start, dir) }\n    if (start.ch >= line.text.length) {\n      start.ch = line.text.length;\n      start.sticky = \"before\";\n    } else if (start.ch <= 0) {\n      start.ch = 0;\n      start.sticky = \"after\";\n    }\n    var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];\n    if (cm.doc.direction == \"ltr\" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {\n      // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,\n      // nothing interesting happens.\n      return moveLogically(line, start, dir)\n    }\n\n    var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };\n    var prep;\n    var getWrappedLineExtent = function (ch) {\n      if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }\n      prep = prep || prepareMeasureForLine(cm, line);\n      return wrappedLineExtentChar(cm, line, prep, ch)\n    };\n    var wrappedLineExtent = getWrappedLineExtent(start.sticky == \"before\" ? mv(start, -1) : start.ch);\n\n    if (cm.doc.direction == \"rtl\" || part.level == 1) {\n      var moveInStorageOrder = (part.level == 1) == (dir < 0);\n      var ch = mv(start, moveInStorageOrder ? 1 : -1);\n      if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {\n        // Case 2: We move within an rtl part or in an rtl editor on the same visual line\n        var sticky = moveInStorageOrder ? \"before\" : \"after\";\n        return new Pos(start.line, ch, sticky)\n      }\n    }\n\n    // Case 3: Could not move within this bidi part in this visual line, so leave\n    // the current bidi part\n\n    var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {\n      var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder\n        ? new Pos(start.line, mv(ch, 1), \"before\")\n        : new Pos(start.line, ch, \"after\"); };\n\n      for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {\n        var part = bidi[partPos];\n        var moveInStorageOrder = (dir > 0) == (part.level != 1);\n        var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);\n        if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }\n        ch = moveInStorageOrder ? part.from : mv(part.to, -1);\n        if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }\n      }\n    };\n\n    // Case 3a: Look for other bidi parts on the same visual line\n    var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);\n    if (res) { return res }\n\n    // Case 3b: Look for other bidi parts on the next visual line\n    var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);\n    if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {\n      res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));\n      if (res) { return res }\n    }\n\n    // Case 4: Nowhere to move\n    return null\n  }\n\n  // Commands are parameter-less actions that can be performed on an\n  // editor, mostly used for keybindings.\n  var commands = {\n    selectAll: selectAll,\n    singleSelection: function (cm) { return cm.setSelection(cm.getCursor(\"anchor\"), cm.getCursor(\"head\"), sel_dontScroll); },\n    killLine: function (cm) { return deleteNearSelection(cm, function (range) {\n      if (range.empty()) {\n        var len = getLine(cm.doc, range.head.line).text.length;\n        if (range.head.ch == len && range.head.line < cm.lastLine())\n          { return {from: range.head, to: Pos(range.head.line + 1, 0)} }\n        else\n          { return {from: range.head, to: Pos(range.head.line, len)} }\n      } else {\n        return {from: range.from(), to: range.to()}\n      }\n    }); },\n    deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({\n      from: Pos(range.from().line, 0),\n      to: clipPos(cm.doc, Pos(range.to().line + 1, 0))\n    }); }); },\n    delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({\n      from: Pos(range.from().line, 0), to: range.from()\n    }); }); },\n    delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {\n      var top = cm.charCoords(range.head, \"div\").top + 5;\n      var leftPos = cm.coordsChar({left: 0, top: top}, \"div\");\n      return {from: leftPos, to: range.from()}\n    }); },\n    delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {\n      var top = cm.charCoords(range.head, \"div\").top + 5;\n      var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\");\n      return {from: range.from(), to: rightPos }\n    }); },\n    undo: function (cm) { return cm.undo(); },\n    redo: function (cm) { return cm.redo(); },\n    undoSelection: function (cm) { return cm.undoSelection(); },\n    redoSelection: function (cm) { return cm.redoSelection(); },\n    goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },\n    goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },\n    goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },\n      {origin: \"+move\", bias: 1}\n    ); },\n    goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },\n      {origin: \"+move\", bias: 1}\n    ); },\n    goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },\n      {origin: \"+move\", bias: -1}\n    ); },\n    goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {\n      var top = cm.cursorCoords(range.head, \"div\").top + 5;\n      return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\")\n    }, sel_move); },\n    goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {\n      var top = cm.cursorCoords(range.head, \"div\").top + 5;\n      return cm.coordsChar({left: 0, top: top}, \"div\")\n    }, sel_move); },\n    goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {\n      var top = cm.cursorCoords(range.head, \"div\").top + 5;\n      var pos = cm.coordsChar({left: 0, top: top}, \"div\");\n      if (pos.ch < cm.getLine(pos.line).search(/\\S/)) { return lineStartSmart(cm, range.head) }\n      return pos\n    }, sel_move); },\n    goLineUp: function (cm) { return cm.moveV(-1, \"line\"); },\n    goLineDown: function (cm) { return cm.moveV(1, \"line\"); },\n    goPageUp: function (cm) { return cm.moveV(-1, \"page\"); },\n    goPageDown: function (cm) { return cm.moveV(1, \"page\"); },\n    goCharLeft: function (cm) { return cm.moveH(-1, \"char\"); },\n    goCharRight: function (cm) { return cm.moveH(1, \"char\"); },\n    goColumnLeft: function (cm) { return cm.moveH(-1, \"column\"); },\n    goColumnRight: function (cm) { return cm.moveH(1, \"column\"); },\n    goWordLeft: function (cm) { return cm.moveH(-1, \"word\"); },\n    goGroupRight: function (cm) { return cm.moveH(1, \"group\"); },\n    goGroupLeft: function (cm) { return cm.moveH(-1, \"group\"); },\n    goWordRight: function (cm) { return cm.moveH(1, \"word\"); },\n    delCharBefore: function (cm) { return cm.deleteH(-1, \"char\"); },\n    delCharAfter: function (cm) { return cm.deleteH(1, \"char\"); },\n    delWordBefore: function (cm) { return cm.deleteH(-1, \"word\"); },\n    delWordAfter: function (cm) { return cm.deleteH(1, \"word\"); },\n    delGroupBefore: function (cm) { return cm.deleteH(-1, \"group\"); },\n    delGroupAfter: function (cm) { return cm.deleteH(1, \"group\"); },\n    indentAuto: function (cm) { return cm.indentSelection(\"smart\"); },\n    indentMore: function (cm) { return cm.indentSelection(\"add\"); },\n    indentLess: function (cm) { return cm.indentSelection(\"subtract\"); },\n    insertTab: function (cm) { return cm.replaceSelection(\"\\t\"); },\n    insertSoftTab: function (cm) {\n      var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;\n      for (var i = 0; i < ranges.length; i++) {\n        var pos = ranges[i].from();\n        var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);\n        spaces.push(spaceStr(tabSize - col % tabSize));\n      }\n      cm.replaceSelections(spaces);\n    },\n    defaultTab: function (cm) {\n      if (cm.somethingSelected()) { cm.indentSelection(\"add\"); }\n      else { cm.execCommand(\"insertTab\"); }\n    },\n    // Swap the two chars left and right of each selection's head.\n    // Move cursor behind the two swapped characters afterwards.\n    //\n    // Doesn't consider line feeds a character.\n    // Doesn't scan more than one line above to find a character.\n    // Doesn't do anything on an empty line.\n    // Doesn't do anything with non-empty selections.\n    transposeChars: function (cm) { return runInOp(cm, function () {\n      var ranges = cm.listSelections(), newSel = [];\n      for (var i = 0; i < ranges.length; i++) {\n        if (!ranges[i].empty()) { continue }\n        var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;\n        if (line) {\n          if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }\n          if (cur.ch > 0) {\n            cur = new Pos(cur.line, cur.ch + 1);\n            cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),\n                            Pos(cur.line, cur.ch - 2), cur, \"+transpose\");\n          } else if (cur.line > cm.doc.first) {\n            var prev = getLine(cm.doc, cur.line - 1).text;\n            if (prev) {\n              cur = new Pos(cur.line, 1);\n              cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +\n                              prev.charAt(prev.length - 1),\n                              Pos(cur.line - 1, prev.length - 1), cur, \"+transpose\");\n            }\n          }\n        }\n        newSel.push(new Range(cur, cur));\n      }\n      cm.setSelections(newSel);\n    }); },\n    newlineAndIndent: function (cm) { return runInOp(cm, function () {\n      var sels = cm.listSelections();\n      for (var i = sels.length - 1; i >= 0; i--)\n        { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, \"+input\"); }\n      sels = cm.listSelections();\n      for (var i$1 = 0; i$1 < sels.length; i$1++)\n        { cm.indentLine(sels[i$1].from().line, null, true); }\n      ensureCursorVisible(cm);\n    }); },\n    openLine: function (cm) { return cm.replaceSelection(\"\\n\", \"start\"); },\n    toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }\n  };\n\n\n  function lineStart(cm, lineN) {\n    var line = getLine(cm.doc, lineN);\n    var visual = visualLine(line);\n    if (visual != line) { lineN = lineNo(visual); }\n    return endOfLine(true, cm, visual, lineN, 1)\n  }\n  function lineEnd(cm, lineN) {\n    var line = getLine(cm.doc, lineN);\n    var visual = visualLineEnd(line);\n    if (visual != line) { lineN = lineNo(visual); }\n    return endOfLine(true, cm, line, lineN, -1)\n  }\n  function lineStartSmart(cm, pos) {\n    var start = lineStart(cm, pos.line);\n    var line = getLine(cm.doc, start.line);\n    var order = getOrder(line, cm.doc.direction);\n    if (!order || order[0].level == 0) {\n      var firstNonWS = Math.max(0, line.text.search(/\\S/));\n      var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;\n      return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)\n    }\n    return start\n  }\n\n  // Run a handler that was bound to a key.\n  function doHandleBinding(cm, bound, dropShift) {\n    if (typeof bound == \"string\") {\n      bound = commands[bound];\n      if (!bound) { return false }\n    }\n    // Ensure previous input has been read, so that the handler sees a\n    // consistent view of the document\n    cm.display.input.ensurePolled();\n    var prevShift = cm.display.shift, done = false;\n    try {\n      if (cm.isReadOnly()) { cm.state.suppressEdits = true; }\n      if (dropShift) { cm.display.shift = false; }\n      done = bound(cm) != Pass;\n    } finally {\n      cm.display.shift = prevShift;\n      cm.state.suppressEdits = false;\n    }\n    return done\n  }\n\n  function lookupKeyForEditor(cm, name, handle) {\n    for (var i = 0; i < cm.state.keyMaps.length; i++) {\n      var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);\n      if (result) { return result }\n    }\n    return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))\n      || lookupKey(name, cm.options.keyMap, handle, cm)\n  }\n\n  // Note that, despite the name, this function is also used to check\n  // for bound mouse clicks.\n\n  var stopSeq = new Delayed;\n\n  function dispatchKey(cm, name, e, handle) {\n    var seq = cm.state.keySeq;\n    if (seq) {\n      if (isModifierKey(name)) { return \"handled\" }\n      if (/\\'$/.test(name))\n        { cm.state.keySeq = null; }\n      else\n        { stopSeq.set(50, function () {\n          if (cm.state.keySeq == seq) {\n            cm.state.keySeq = null;\n            cm.display.input.reset();\n          }\n        }); }\n      if (dispatchKeyInner(cm, seq + \" \" + name, e, handle)) { return true }\n    }\n    return dispatchKeyInner(cm, name, e, handle)\n  }\n\n  function dispatchKeyInner(cm, name, e, handle) {\n    var result = lookupKeyForEditor(cm, name, handle);\n\n    if (result == \"multi\")\n      { cm.state.keySeq = name; }\n    if (result == \"handled\")\n      { signalLater(cm, \"keyHandled\", cm, name, e); }\n\n    if (result == \"handled\" || result == \"multi\") {\n      e_preventDefault(e);\n      restartBlink(cm);\n    }\n\n    return !!result\n  }\n\n  // Handle a key from the keydown event.\n  function handleKeyBinding(cm, e) {\n    var name = keyName(e, true);\n    if (!name) { return false }\n\n    if (e.shiftKey && !cm.state.keySeq) {\n      // First try to resolve full name (including 'Shift-'). Failing\n      // that, see if there is a cursor-motion command (starting with\n      // 'go') bound to the keyname without 'Shift-'.\n      return dispatchKey(cm, \"Shift-\" + name, e, function (b) { return doHandleBinding(cm, b, true); })\n          || dispatchKey(cm, name, e, function (b) {\n               if (typeof b == \"string\" ? /^go[A-Z]/.test(b) : b.motion)\n                 { return doHandleBinding(cm, b) }\n             })\n    } else {\n      return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })\n    }\n  }\n\n  // Handle a key from the keypress event\n  function handleCharBinding(cm, e, ch) {\n    return dispatchKey(cm, \"'\" + ch + \"'\", e, function (b) { return doHandleBinding(cm, b, true); })\n  }\n\n  var lastStoppedKey = null;\n  function onKeyDown(e) {\n    var cm = this;\n    cm.curOp.focus = activeElt();\n    if (signalDOMEvent(cm, e)) { return }\n    // IE does strange things with escape.\n    if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }\n    var code = e.keyCode;\n    cm.display.shift = code == 16 || e.shiftKey;\n    var handled = handleKeyBinding(cm, e);\n    if (presto) {\n      lastStoppedKey = handled ? code : null;\n      // Opera has no cut event... we try to at least catch the key combo\n      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))\n        { cm.replaceSelection(\"\", null, \"cut\"); }\n    }\n\n    // Turn mouse into crosshair when Alt is held on Mac.\n    if (code == 18 && !/\\bCodeMirror-crosshair\\b/.test(cm.display.lineDiv.className))\n      { showCrossHair(cm); }\n  }\n\n  function showCrossHair(cm) {\n    var lineDiv = cm.display.lineDiv;\n    addClass(lineDiv, \"CodeMirror-crosshair\");\n\n    function up(e) {\n      if (e.keyCode == 18 || !e.altKey) {\n        rmClass(lineDiv, \"CodeMirror-crosshair\");\n        off(document, \"keyup\", up);\n        off(document, \"mouseover\", up);\n      }\n    }\n    on(document, \"keyup\", up);\n    on(document, \"mouseover\", up);\n  }\n\n  function onKeyUp(e) {\n    if (e.keyCode == 16) { this.doc.sel.shift = false; }\n    signalDOMEvent(this, e);\n  }\n\n  function onKeyPress(e) {\n    var cm = this;\n    if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }\n    var keyCode = e.keyCode, charCode = e.charCode;\n    if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}\n    if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }\n    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);\n    // Some browsers fire keypress events for backspace\n    if (ch == \"\\x08\") { return }\n    if (handleCharBinding(cm, e, ch)) { return }\n    cm.display.input.onKeyPress(e);\n  }\n\n  var DOUBLECLICK_DELAY = 400;\n\n  var PastClick = function(time, pos, button) {\n    this.time = time;\n    this.pos = pos;\n    this.button = button;\n  };\n\n  PastClick.prototype.compare = function (time, pos, button) {\n    return this.time + DOUBLECLICK_DELAY > time &&\n      cmp(pos, this.pos) == 0 && button == this.button\n  };\n\n  var lastClick, lastDoubleClick;\n  function clickRepeat(pos, button) {\n    var now = +new Date;\n    if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {\n      lastClick = lastDoubleClick = null;\n      return \"triple\"\n    } else if (lastClick && lastClick.compare(now, pos, button)) {\n      lastDoubleClick = new PastClick(now, pos, button);\n      lastClick = null;\n      return \"double\"\n    } else {\n      lastClick = new PastClick(now, pos, button);\n      lastDoubleClick = null;\n      return \"single\"\n    }\n  }\n\n  // A mouse down can be a single click, double click, triple click,\n  // start of selection drag, start of text drag, new cursor\n  // (ctrl-click), rectangle drag (alt-drag), or xwin\n  // middle-click-paste. Or it might be a click on something we should\n  // not interfere with, such as a scrollbar or widget.\n  function onMouseDown(e) {\n    var cm = this, display = cm.display;\n    if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }\n    display.input.ensurePolled();\n    display.shift = e.shiftKey;\n\n    if (eventInWidget(display, e)) {\n      if (!webkit) {\n        // Briefly turn off draggability, to allow widgets to do\n        // normal dragging things.\n        display.scroller.draggable = false;\n        setTimeout(function () { return display.scroller.draggable = true; }, 100);\n      }\n      return\n    }\n    if (clickInGutter(cm, e)) { return }\n    var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : \"single\";\n    window.focus();\n\n    // #3261: make sure, that we're not starting a second selection\n    if (button == 1 && cm.state.selectingText)\n      { cm.state.selectingText(e); }\n\n    if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }\n\n    if (button == 1) {\n      if (pos) { leftButtonDown(cm, pos, repeat, e); }\n      else if (e_target(e) == display.scroller) { e_preventDefault(e); }\n    } else if (button == 2) {\n      if (pos) { extendSelection(cm.doc, pos); }\n      setTimeout(function () { return display.input.focus(); }, 20);\n    } else if (button == 3) {\n      if (captureRightClick) { cm.display.input.onContextMenu(e); }\n      else { delayBlurEvent(cm); }\n    }\n  }\n\n  function handleMappedButton(cm, button, pos, repeat, event) {\n    var name = \"Click\";\n    if (repeat == \"double\") { name = \"Double\" + name; }\n    else if (repeat == \"triple\") { name = \"Triple\" + name; }\n    name = (button == 1 ? \"Left\" : button == 2 ? \"Middle\" : \"Right\") + name;\n\n    return dispatchKey(cm,  addModifierNames(name, event), event, function (bound) {\n      if (typeof bound == \"string\") { bound = commands[bound]; }\n      if (!bound) { return false }\n      var done = false;\n      try {\n        if (cm.isReadOnly()) { cm.state.suppressEdits = true; }\n        done = bound(cm, pos) != Pass;\n      } finally {\n        cm.state.suppressEdits = false;\n      }\n      return done\n    })\n  }\n\n  function configureMouse(cm, repeat, event) {\n    var option = cm.getOption(\"configureMouse\");\n    var value = option ? option(cm, repeat, event) : {};\n    if (value.unit == null) {\n      var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;\n      value.unit = rect ? \"rectangle\" : repeat == \"single\" ? \"char\" : repeat == \"double\" ? \"word\" : \"line\";\n    }\n    if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }\n    if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }\n    if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }\n    return value\n  }\n\n  function leftButtonDown(cm, pos, repeat, event) {\n    if (ie) { setTimeout(bind(ensureFocus, cm), 0); }\n    else { cm.curOp.focus = activeElt(); }\n\n    var behavior = configureMouse(cm, repeat, event);\n\n    var sel = cm.doc.sel, contained;\n    if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&\n        repeat == \"single\" && (contained = sel.contains(pos)) > -1 &&\n        (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&\n        (cmp(contained.to(), pos) > 0 || pos.xRel < 0))\n      { leftButtonStartDrag(cm, event, pos, behavior); }\n    else\n      { leftButtonSelect(cm, event, pos, behavior); }\n  }\n\n  // Start a text drag. When it ends, see if any dragging actually\n  // happen, and treat as a click if it didn't.\n  function leftButtonStartDrag(cm, event, pos, behavior) {\n    var display = cm.display, moved = false;\n    var dragEnd = operation(cm, function (e) {\n      if (webkit) { display.scroller.draggable = false; }\n      cm.state.draggingText = false;\n      off(display.wrapper.ownerDocument, \"mouseup\", dragEnd);\n      off(display.wrapper.ownerDocument, \"mousemove\", mouseMove);\n      off(display.scroller, \"dragstart\", dragStart);\n      off(display.scroller, \"drop\", dragEnd);\n      if (!moved) {\n        e_preventDefault(e);\n        if (!behavior.addNew)\n          { extendSelection(cm.doc, pos, null, null, behavior.extend); }\n        // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)\n        if (webkit || ie && ie_version == 9)\n          { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }\n        else\n          { display.input.focus(); }\n      }\n    });\n    var mouseMove = function(e2) {\n      moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;\n    };\n    var dragStart = function () { return moved = true; };\n    // Let the drag handler handle this.\n    if (webkit) { display.scroller.draggable = true; }\n    cm.state.draggingText = dragEnd;\n    dragEnd.copy = !behavior.moveOnDrag;\n    // IE's approach to draggable\n    if (display.scroller.dragDrop) { display.scroller.dragDrop(); }\n    on(display.wrapper.ownerDocument, \"mouseup\", dragEnd);\n    on(display.wrapper.ownerDocument, \"mousemove\", mouseMove);\n    on(display.scroller, \"dragstart\", dragStart);\n    on(display.scroller, \"drop\", dragEnd);\n\n    delayBlurEvent(cm);\n    setTimeout(function () { return display.input.focus(); }, 20);\n  }\n\n  function rangeForUnit(cm, pos, unit) {\n    if (unit == \"char\") { return new Range(pos, pos) }\n    if (unit == \"word\") { return cm.findWordAt(pos) }\n    if (unit == \"line\") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }\n    var result = unit(cm, pos);\n    return new Range(result.from, result.to)\n  }\n\n  // Normal selection, as opposed to text dragging.\n  function leftButtonSelect(cm, event, start, behavior) {\n    var display = cm.display, doc = cm.doc;\n    e_preventDefault(event);\n\n    var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;\n    if (behavior.addNew && !behavior.extend) {\n      ourIndex = doc.sel.contains(start);\n      if (ourIndex > -1)\n        { ourRange = ranges[ourIndex]; }\n      else\n        { ourRange = new Range(start, start); }\n    } else {\n      ourRange = doc.sel.primary();\n      ourIndex = doc.sel.primIndex;\n    }\n\n    if (behavior.unit == \"rectangle\") {\n      if (!behavior.addNew) { ourRange = new Range(start, start); }\n      start = posFromMouse(cm, event, true, true);\n      ourIndex = -1;\n    } else {\n      var range$$1 = rangeForUnit(cm, start, behavior.unit);\n      if (behavior.extend)\n        { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }\n      else\n        { ourRange = range$$1; }\n    }\n\n    if (!behavior.addNew) {\n      ourIndex = 0;\n      setSelection(doc, new Selection([ourRange], 0), sel_mouse);\n      startSel = doc.sel;\n    } else if (ourIndex == -1) {\n      ourIndex = ranges.length;\n      setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),\n                   {scroll: false, origin: \"*mouse\"});\n    } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == \"char\" && !behavior.extend) {\n      setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),\n                   {scroll: false, origin: \"*mouse\"});\n      startSel = doc.sel;\n    } else {\n      replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);\n    }\n\n    var lastPos = start;\n    function extendTo(pos) {\n      if (cmp(lastPos, pos) == 0) { return }\n      lastPos = pos;\n\n      if (behavior.unit == \"rectangle\") {\n        var ranges = [], tabSize = cm.options.tabSize;\n        var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);\n        var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);\n        var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);\n        for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));\n             line <= end; line++) {\n          var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);\n          if (left == right)\n            { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }\n          else if (text.length > leftPos)\n            { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }\n        }\n        if (!ranges.length) { ranges.push(new Range(start, start)); }\n        setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),\n                     {origin: \"*mouse\", scroll: false});\n        cm.scrollIntoView(pos);\n      } else {\n        var oldRange = ourRange;\n        var range$$1 = rangeForUnit(cm, pos, behavior.unit);\n        var anchor = oldRange.anchor, head;\n        if (cmp(range$$1.anchor, anchor) > 0) {\n          head = range$$1.head;\n          anchor = minPos(oldRange.from(), range$$1.anchor);\n        } else {\n          head = range$$1.anchor;\n          anchor = maxPos(oldRange.to(), range$$1.head);\n        }\n        var ranges$1 = startSel.ranges.slice(0);\n        ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));\n        setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);\n      }\n    }\n\n    var editorSize = display.wrapper.getBoundingClientRect();\n    // Used to ensure timeout re-tries don't fire when another extend\n    // happened in the meantime (clearTimeout isn't reliable -- at\n    // least on Chrome, the timeouts still happen even when cleared,\n    // if the clear happens after their scheduled firing time).\n    var counter = 0;\n\n    function extend(e) {\n      var curCount = ++counter;\n      var cur = posFromMouse(cm, e, true, behavior.unit == \"rectangle\");\n      if (!cur) { return }\n      if (cmp(cur, lastPos) != 0) {\n        cm.curOp.focus = activeElt();\n        extendTo(cur);\n        var visible = visibleLines(display, doc);\n        if (cur.line >= visible.to || cur.line < visible.from)\n          { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }\n      } else {\n        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;\n        if (outside) { setTimeout(operation(cm, function () {\n          if (counter != curCount) { return }\n          display.scroller.scrollTop += outside;\n          extend(e);\n        }), 50); }\n      }\n    }\n\n    function done(e) {\n      cm.state.selectingText = false;\n      counter = Infinity;\n      e_preventDefault(e);\n      display.input.focus();\n      off(display.wrapper.ownerDocument, \"mousemove\", move);\n      off(display.wrapper.ownerDocument, \"mouseup\", up);\n      doc.history.lastSelOrigin = null;\n    }\n\n    var move = operation(cm, function (e) {\n      if (e.buttons === 0 || !e_button(e)) { done(e); }\n      else { extend(e); }\n    });\n    var up = operation(cm, done);\n    cm.state.selectingText = up;\n    on(display.wrapper.ownerDocument, \"mousemove\", move);\n    on(display.wrapper.ownerDocument, \"mouseup\", up);\n  }\n\n  // Used when mouse-selecting to adjust the anchor to the proper side\n  // of a bidi jump depending on the visual position of the head.\n  function bidiSimplify(cm, range$$1) {\n    var anchor = range$$1.anchor;\n    var head = range$$1.head;\n    var anchorLine = getLine(cm.doc, anchor.line);\n    if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }\n    var order = getOrder(anchorLine);\n    if (!order) { return range$$1 }\n    var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];\n    if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }\n    var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);\n    if (boundary == 0 || boundary == order.length) { return range$$1 }\n\n    // Compute the relative visual position of the head compared to the\n    // anchor (<0 is to the left, >0 to the right)\n    var leftSide;\n    if (head.line != anchor.line) {\n      leftSide = (head.line - anchor.line) * (cm.doc.direction == \"ltr\" ? 1 : -1) > 0;\n    } else {\n      var headIndex = getBidiPartAt(order, head.ch, head.sticky);\n      var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);\n      if (headIndex == boundary - 1 || headIndex == boundary)\n        { leftSide = dir < 0; }\n      else\n        { leftSide = dir > 0; }\n    }\n\n    var usePart = order[boundary + (leftSide ? -1 : 0)];\n    var from = leftSide == (usePart.level == 1);\n    var ch = from ? usePart.from : usePart.to, sticky = from ? \"after\" : \"before\";\n    return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)\n  }\n\n\n  // Determines whether an event happened in the gutter, and fires the\n  // handlers for the corresponding event.\n  function gutterEvent(cm, e, type, prevent) {\n    var mX, mY;\n    if (e.touches) {\n      mX = e.touches[0].clientX;\n      mY = e.touches[0].clientY;\n    } else {\n      try { mX = e.clientX; mY = e.clientY; }\n      catch(e) { return false }\n    }\n    if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }\n    if (prevent) { e_preventDefault(e); }\n\n    var display = cm.display;\n    var lineBox = display.lineDiv.getBoundingClientRect();\n\n    if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }\n    mY -= lineBox.top - display.viewOffset;\n\n    for (var i = 0; i < cm.options.gutters.length; ++i) {\n      var g = display.gutters.childNodes[i];\n      if (g && g.getBoundingClientRect().right >= mX) {\n        var line = lineAtHeight(cm.doc, mY);\n        var gutter = cm.options.gutters[i];\n        signal(cm, type, cm, line, gutter, e);\n        return e_defaultPrevented(e)\n      }\n    }\n  }\n\n  function clickInGutter(cm, e) {\n    return gutterEvent(cm, e, \"gutterClick\", true)\n  }\n\n  // CONTEXT MENU HANDLING\n\n  // To make the context menu work, we need to briefly unhide the\n  // textarea (making it as unobtrusive as possible) to let the\n  // right-click take effect on it.\n  function onContextMenu(cm, e) {\n    if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }\n    if (signalDOMEvent(cm, e, \"contextmenu\")) { return }\n    if (!captureRightClick) { cm.display.input.onContextMenu(e); }\n  }\n\n  function contextMenuInGutter(cm, e) {\n    if (!hasHandler(cm, \"gutterContextMenu\")) { return false }\n    return gutterEvent(cm, e, \"gutterContextMenu\", false)\n  }\n\n  function themeChanged(cm) {\n    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\\s*cm-s-\\S+/g, \"\") +\n      cm.options.theme.replace(/(^|\\s)\\s*/g, \" cm-s-\");\n    clearCaches(cm);\n  }\n\n  var Init = {toString: function(){return \"CodeMirror.Init\"}};\n\n  var defaults = {};\n  var optionHandlers = {};\n\n  function defineOptions(CodeMirror) {\n    var optionHandlers = CodeMirror.optionHandlers;\n\n    function option(name, deflt, handle, notOnInit) {\n      CodeMirror.defaults[name] = deflt;\n      if (handle) { optionHandlers[name] =\n        notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }\n    }\n\n    CodeMirror.defineOption = option;\n\n    // Passed to option handlers when there is no old value.\n    CodeMirror.Init = Init;\n\n    // These two are, on init, called from the constructor because they\n    // have to be initialized before the editor can start at all.\n    option(\"value\", \"\", function (cm, val) { return cm.setValue(val); }, true);\n    option(\"mode\", null, function (cm, val) {\n      cm.doc.modeOption = val;\n      loadMode(cm);\n    }, true);\n\n    option(\"indentUnit\", 2, loadMode, true);\n    option(\"indentWithTabs\", false);\n    option(\"smartIndent\", true);\n    option(\"tabSize\", 4, function (cm) {\n      resetModeState(cm);\n      clearCaches(cm);\n      regChange(cm);\n    }, true);\n\n    option(\"lineSeparator\", null, function (cm, val) {\n      cm.doc.lineSep = val;\n      if (!val) { return }\n      var newBreaks = [], lineNo = cm.doc.first;\n      cm.doc.iter(function (line) {\n        for (var pos = 0;;) {\n          var found = line.text.indexOf(val, pos);\n          if (found == -1) { break }\n          pos = found + val.length;\n          newBreaks.push(Pos(lineNo, found));\n        }\n        lineNo++;\n      });\n      for (var i = newBreaks.length - 1; i >= 0; i--)\n        { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }\n    });\n    option(\"specialChars\", /[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u061c\\u200b-\\u200f\\u2028\\u2029\\ufeff]/g, function (cm, val, old) {\n      cm.state.specialChars = new RegExp(val.source + (val.test(\"\\t\") ? \"\" : \"|\\t\"), \"g\");\n      if (old != Init) { cm.refresh(); }\n    });\n    option(\"specialCharPlaceholder\", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);\n    option(\"electricChars\", true);\n    option(\"inputStyle\", mobile ? \"contenteditable\" : \"textarea\", function () {\n      throw new Error(\"inputStyle can not (yet) be changed in a running editor\") // FIXME\n    }, true);\n    option(\"spellcheck\", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);\n    option(\"autocorrect\", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);\n    option(\"autocapitalize\", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);\n    option(\"rtlMoveVisually\", !windows);\n    option(\"wholeLineUpdateBefore\", true);\n\n    option(\"theme\", \"default\", function (cm) {\n      themeChanged(cm);\n      guttersChanged(cm);\n    }, true);\n    option(\"keyMap\", \"default\", function (cm, val, old) {\n      var next = getKeyMap(val);\n      var prev = old != Init && getKeyMap(old);\n      if (prev && prev.detach) { prev.detach(cm, next); }\n      if (next.attach) { next.attach(cm, prev || null); }\n    });\n    option(\"extraKeys\", null);\n    option(\"configureMouse\", null);\n\n    option(\"lineWrapping\", false, wrappingChanged, true);\n    option(\"gutters\", [], function (cm) {\n      setGuttersForLineNumbers(cm.options);\n      guttersChanged(cm);\n    }, true);\n    option(\"fixedGutter\", true, function (cm, val) {\n      cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + \"px\" : \"0\";\n      cm.refresh();\n    }, true);\n    option(\"coverGutterNextToScrollbar\", false, function (cm) { return updateScrollbars(cm); }, true);\n    option(\"scrollbarStyle\", \"native\", function (cm) {\n      initScrollbars(cm);\n      updateScrollbars(cm);\n      cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);\n      cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);\n    }, true);\n    option(\"lineNumbers\", false, function (cm) {\n      setGuttersForLineNumbers(cm.options);\n      guttersChanged(cm);\n    }, true);\n    option(\"firstLineNumber\", 1, guttersChanged, true);\n    option(\"lineNumberFormatter\", function (integer) { return integer; }, guttersChanged, true);\n    option(\"showCursorWhenSelecting\", false, updateSelection, true);\n\n    option(\"resetSelectionOnContextMenu\", true);\n    option(\"lineWiseCopyCut\", true);\n    option(\"pasteLinesPerSelection\", true);\n    option(\"selectionsMayTouch\", false);\n\n    option(\"readOnly\", false, function (cm, val) {\n      if (val == \"nocursor\") {\n        onBlur(cm);\n        cm.display.input.blur();\n      }\n      cm.display.input.readOnlyChanged(val);\n    });\n    option(\"disableInput\", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);\n    option(\"dragDrop\", true, dragDropChanged);\n    option(\"allowDropFileTypes\", null);\n\n    option(\"cursorBlinkRate\", 530);\n    option(\"cursorScrollMargin\", 0);\n    option(\"cursorHeight\", 1, updateSelection, true);\n    option(\"singleCursorHeightPerLine\", true, updateSelection, true);\n    option(\"workTime\", 100);\n    option(\"workDelay\", 100);\n    option(\"flattenSpans\", true, resetModeState, true);\n    option(\"addModeClass\", false, resetModeState, true);\n    option(\"pollInterval\", 100);\n    option(\"undoDepth\", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });\n    option(\"historyEventDelay\", 1250);\n    option(\"viewportMargin\", 10, function (cm) { return cm.refresh(); }, true);\n    option(\"maxHighlightLength\", 10000, resetModeState, true);\n    option(\"moveInputWithCursor\", true, function (cm, val) {\n      if (!val) { cm.display.input.resetPosition(); }\n    });\n\n    option(\"tabindex\", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || \"\"; });\n    option(\"autofocus\", null);\n    option(\"direction\", \"ltr\", function (cm, val) { return cm.doc.setDirection(val); }, true);\n    option(\"phrases\", null);\n  }\n\n  function guttersChanged(cm) {\n    updateGutters(cm);\n    regChange(cm);\n    alignHorizontally(cm);\n  }\n\n  function dragDropChanged(cm, value, old) {\n    var wasOn = old && old != Init;\n    if (!value != !wasOn) {\n      var funcs = cm.display.dragFunctions;\n      var toggle = value ? on : off;\n      toggle(cm.display.scroller, \"dragstart\", funcs.start);\n      toggle(cm.display.scroller, \"dragenter\", funcs.enter);\n      toggle(cm.display.scroller, \"dragover\", funcs.over);\n      toggle(cm.display.scroller, \"dragleave\", funcs.leave);\n      toggle(cm.display.scroller, \"drop\", funcs.drop);\n    }\n  }\n\n  function wrappingChanged(cm) {\n    if (cm.options.lineWrapping) {\n      addClass(cm.display.wrapper, \"CodeMirror-wrap\");\n      cm.display.sizer.style.minWidth = \"\";\n      cm.display.sizerWidth = null;\n    } else {\n      rmClass(cm.display.wrapper, \"CodeMirror-wrap\");\n      findMaxLine(cm);\n    }\n    estimateLineHeights(cm);\n    regChange(cm);\n    clearCaches(cm);\n    setTimeout(function () { return updateScrollbars(cm); }, 100);\n  }\n\n  // A CodeMirror instance represents an editor. This is the object\n  // that user code is usually dealing with.\n\n  function CodeMirror(place, options) {\n    var this$1 = this;\n\n    if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }\n\n    this.options = options = options ? copyObj(options) : {};\n    // Determine effective options based on given values and defaults.\n    copyObj(defaults, options, false);\n    setGuttersForLineNumbers(options);\n\n    var doc = options.value;\n    if (typeof doc == \"string\") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }\n    else if (options.mode) { doc.modeOption = options.mode; }\n    this.doc = doc;\n\n    var input = new CodeMirror.inputStyles[options.inputStyle](this);\n    var display = this.display = new Display(place, doc, input);\n    display.wrapper.CodeMirror = this;\n    updateGutters(this);\n    themeChanged(this);\n    if (options.lineWrapping)\n      { this.display.wrapper.className += \" CodeMirror-wrap\"; }\n    initScrollbars(this);\n\n    this.state = {\n      keyMaps: [],  // stores maps added by addKeyMap\n      overlays: [], // highlighting overlays, as added by addOverlay\n      modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info\n      overwrite: false,\n      delayingBlurEvent: false,\n      focused: false,\n      suppressEdits: false, // used to disable editing during key handlers when in readOnly mode\n      pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll\n      selectingText: false,\n      draggingText: false,\n      highlight: new Delayed(), // stores highlight worker timeout\n      keySeq: null,  // Unfinished key sequence\n      specialChars: null\n    };\n\n    if (options.autofocus && !mobile) { display.input.focus(); }\n\n    // Override magic textarea content restore that IE sometimes does\n    // on our hidden textarea on reload\n    if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }\n\n    registerEventHandlers(this);\n    ensureGlobalHandlers();\n\n    startOperation(this);\n    this.curOp.forceUpdate = true;\n    attachDoc(this, doc);\n\n    if ((options.autofocus && !mobile) || this.hasFocus())\n      { setTimeout(bind(onFocus, this), 20); }\n    else\n      { onBlur(this); }\n\n    for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))\n      { optionHandlers[opt](this$1, options[opt], Init); } }\n    maybeUpdateLineNumberWidth(this);\n    if (options.finishInit) { options.finishInit(this); }\n    for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }\n    endOperation(this);\n    // Suppress optimizelegibility in Webkit, since it breaks text\n    // measuring on line wrapping boundaries.\n    if (webkit && options.lineWrapping &&\n        getComputedStyle(display.lineDiv).textRendering == \"optimizelegibility\")\n      { display.lineDiv.style.textRendering = \"auto\"; }\n  }\n\n  // The default configuration options.\n  CodeMirror.defaults = defaults;\n  // Functions to run when options are changed.\n  CodeMirror.optionHandlers = optionHandlers;\n\n  // Attach the necessary event handlers when initializing the editor\n  function registerEventHandlers(cm) {\n    var d = cm.display;\n    on(d.scroller, \"mousedown\", operation(cm, onMouseDown));\n    // Older IE's will not fire a second mousedown for a double click\n    if (ie && ie_version < 11)\n      { on(d.scroller, \"dblclick\", operation(cm, function (e) {\n        if (signalDOMEvent(cm, e)) { return }\n        var pos = posFromMouse(cm, e);\n        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }\n        e_preventDefault(e);\n        var word = cm.findWordAt(pos);\n        extendSelection(cm.doc, word.anchor, word.head);\n      })); }\n    else\n      { on(d.scroller, \"dblclick\", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }\n    // Some browsers fire contextmenu *after* opening the menu, at\n    // which point we can't mess with it anymore. Context menu is\n    // handled in onMouseDown for these browsers.\n    on(d.scroller, \"contextmenu\", function (e) { return onContextMenu(cm, e); });\n\n    // Used to suppress mouse event handling when a touch happens\n    var touchFinished, prevTouch = {end: 0};\n    function finishTouch() {\n      if (d.activeTouch) {\n        touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);\n        prevTouch = d.activeTouch;\n        prevTouch.end = +new Date;\n      }\n    }\n    function isMouseLikeTouchEvent(e) {\n      if (e.touches.length != 1) { return false }\n      var touch = e.touches[0];\n      return touch.radiusX <= 1 && touch.radiusY <= 1\n    }\n    function farAway(touch, other) {\n      if (other.left == null) { return true }\n      var dx = other.left - touch.left, dy = other.top - touch.top;\n      return dx * dx + dy * dy > 20 * 20\n    }\n    on(d.scroller, \"touchstart\", function (e) {\n      if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {\n        d.input.ensurePolled();\n        clearTimeout(touchFinished);\n        var now = +new Date;\n        d.activeTouch = {start: now, moved: false,\n                         prev: now - prevTouch.end <= 300 ? prevTouch : null};\n        if (e.touches.length == 1) {\n          d.activeTouch.left = e.touches[0].pageX;\n          d.activeTouch.top = e.touches[0].pageY;\n        }\n      }\n    });\n    on(d.scroller, \"touchmove\", function () {\n      if (d.activeTouch) { d.activeTouch.moved = true; }\n    });\n    on(d.scroller, \"touchend\", function (e) {\n      var touch = d.activeTouch;\n      if (touch && !eventInWidget(d, e) && touch.left != null &&\n          !touch.moved && new Date - touch.start < 300) {\n        var pos = cm.coordsChar(d.activeTouch, \"page\"), range;\n        if (!touch.prev || farAway(touch, touch.prev)) // Single tap\n          { range = new Range(pos, pos); }\n        else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap\n          { range = cm.findWordAt(pos); }\n        else // Triple tap\n          { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }\n        cm.setSelection(range.anchor, range.head);\n        cm.focus();\n        e_preventDefault(e);\n      }\n      finishTouch();\n    });\n    on(d.scroller, \"touchcancel\", finishTouch);\n\n    // Sync scrolling between fake scrollbars and real scrollable\n    // area, ensure viewport is updated when scrolling.\n    on(d.scroller, \"scroll\", function () {\n      if (d.scroller.clientHeight) {\n        updateScrollTop(cm, d.scroller.scrollTop);\n        setScrollLeft(cm, d.scroller.scrollLeft, true);\n        signal(cm, \"scroll\", cm);\n      }\n    });\n\n    // Listen to wheel events in order to try and update the viewport on time.\n    on(d.scroller, \"mousewheel\", function (e) { return onScrollWheel(cm, e); });\n    on(d.scroller, \"DOMMouseScroll\", function (e) { return onScrollWheel(cm, e); });\n\n    // Prevent wrapper from ever scrolling\n    on(d.wrapper, \"scroll\", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });\n\n    d.dragFunctions = {\n      enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},\n      over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},\n      start: function (e) { return onDragStart(cm, e); },\n      drop: operation(cm, onDrop),\n      leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}\n    };\n\n    var inp = d.input.getField();\n    on(inp, \"keyup\", function (e) { return onKeyUp.call(cm, e); });\n    on(inp, \"keydown\", operation(cm, onKeyDown));\n    on(inp, \"keypress\", operation(cm, onKeyPress));\n    on(inp, \"focus\", function (e) { return onFocus(cm, e); });\n    on(inp, \"blur\", function (e) { return onBlur(cm, e); });\n  }\n\n  var initHooks = [];\n  CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };\n\n  // Indent the given line. The how parameter can be \"smart\",\n  // \"add\"/null, \"subtract\", or \"prev\". When aggressive is false\n  // (typically set to true for forced single-line indents), empty\n  // lines are not indented, and places where the mode returns Pass\n  // are left alone.\n  function indentLine(cm, n, how, aggressive) {\n    var doc = cm.doc, state;\n    if (how == null) { how = \"add\"; }\n    if (how == \"smart\") {\n      // Fall back to \"prev\" when the mode doesn't have an indentation\n      // method.\n      if (!doc.mode.indent) { how = \"prev\"; }\n      else { state = getContextBefore(cm, n).state; }\n    }\n\n    var tabSize = cm.options.tabSize;\n    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);\n    if (line.stateAfter) { line.stateAfter = null; }\n    var curSpaceString = line.text.match(/^\\s*/)[0], indentation;\n    if (!aggressive && !/\\S/.test(line.text)) {\n      indentation = 0;\n      how = \"not\";\n    } else if (how == \"smart\") {\n      indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);\n      if (indentation == Pass || indentation > 150) {\n        if (!aggressive) { return }\n        how = \"prev\";\n      }\n    }\n    if (how == \"prev\") {\n      if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }\n      else { indentation = 0; }\n    } else if (how == \"add\") {\n      indentation = curSpace + cm.options.indentUnit;\n    } else if (how == \"subtract\") {\n      indentation = curSpace - cm.options.indentUnit;\n    } else if (typeof how == \"number\") {\n      indentation = curSpace + how;\n    }\n    indentation = Math.max(0, indentation);\n\n    var indentString = \"\", pos = 0;\n    if (cm.options.indentWithTabs)\n      { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += \"\\t\";} }\n    if (pos < indentation) { indentString += spaceStr(indentation - pos); }\n\n    if (indentString != curSpaceString) {\n      replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), \"+input\");\n      line.stateAfter = null;\n      return true\n    } else {\n      // Ensure that, if the cursor was in the whitespace at the start\n      // of the line, it is moved to the end of that space.\n      for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {\n        var range = doc.sel.ranges[i$1];\n        if (range.head.line == n && range.head.ch < curSpaceString.length) {\n          var pos$1 = Pos(n, curSpaceString.length);\n          replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));\n          break\n        }\n      }\n    }\n  }\n\n  // This will be set to a {lineWise: bool, text: [string]} object, so\n  // that, when pasting, we know what kind of selections the copied\n  // text was made out of.\n  var lastCopied = null;\n\n  function setLastCopied(newLastCopied) {\n    lastCopied = newLastCopied;\n  }\n\n  function applyTextInput(cm, inserted, deleted, sel, origin) {\n    var doc = cm.doc;\n    cm.display.shift = false;\n    if (!sel) { sel = doc.sel; }\n\n    var paste = cm.state.pasteIncoming || origin == \"paste\";\n    var textLines = splitLinesAuto(inserted), multiPaste = null;\n    // When pasting N lines into N selections, insert one line per selection\n    if (paste && sel.ranges.length > 1) {\n      if (lastCopied && lastCopied.text.join(\"\\n\") == inserted) {\n        if (sel.ranges.length % lastCopied.text.length == 0) {\n          multiPaste = [];\n          for (var i = 0; i < lastCopied.text.length; i++)\n            { multiPaste.push(doc.splitLines(lastCopied.text[i])); }\n        }\n      } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {\n        multiPaste = map(textLines, function (l) { return [l]; });\n      }\n    }\n\n    var updateInput = cm.curOp.updateInput;\n    // Normal behavior is to insert the new text into every selection\n    for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {\n      var range$$1 = sel.ranges[i$1];\n      var from = range$$1.from(), to = range$$1.to();\n      if (range$$1.empty()) {\n        if (deleted && deleted > 0) // Handle deletion\n          { from = Pos(from.line, from.ch - deleted); }\n        else if (cm.state.overwrite && !paste) // Handle overwrite\n          { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }\n        else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join(\"\\n\") == inserted)\n          { from = to = Pos(from.line, 0); }\n      }\n      var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,\n                         origin: origin || (paste ? \"paste\" : cm.state.cutIncoming ? \"cut\" : \"+input\")};\n      makeChange(cm.doc, changeEvent);\n      signalLater(cm, \"inputRead\", cm, changeEvent);\n    }\n    if (inserted && !paste)\n      { triggerElectric(cm, inserted); }\n\n    ensureCursorVisible(cm);\n    if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }\n    cm.curOp.typing = true;\n    cm.state.pasteIncoming = cm.state.cutIncoming = false;\n  }\n\n  function handlePaste(e, cm) {\n    var pasted = e.clipboardData && e.clipboardData.getData(\"Text\");\n    if (pasted) {\n      e.preventDefault();\n      if (!cm.isReadOnly() && !cm.options.disableInput)\n        { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, \"paste\"); }); }\n      return true\n    }\n  }\n\n  function triggerElectric(cm, inserted) {\n    // When an 'electric' character is inserted, immediately trigger a reindent\n    if (!cm.options.electricChars || !cm.options.smartIndent) { return }\n    var sel = cm.doc.sel;\n\n    for (var i = sel.ranges.length - 1; i >= 0; i--) {\n      var range$$1 = sel.ranges[i];\n      if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }\n      var mode = cm.getModeAt(range$$1.head);\n      var indented = false;\n      if (mode.electricChars) {\n        for (var j = 0; j < mode.electricChars.length; j++)\n          { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {\n            indented = indentLine(cm, range$$1.head.line, \"smart\");\n            break\n          } }\n      } else if (mode.electricInput) {\n        if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))\n          { indented = indentLine(cm, range$$1.head.line, \"smart\"); }\n      }\n      if (indented) { signalLater(cm, \"electricInput\", cm, range$$1.head.line); }\n    }\n  }\n\n  function copyableRanges(cm) {\n    var text = [], ranges = [];\n    for (var i = 0; i < cm.doc.sel.ranges.length; i++) {\n      var line = cm.doc.sel.ranges[i].head.line;\n      var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};\n      ranges.push(lineRange);\n      text.push(cm.getRange(lineRange.anchor, lineRange.head));\n    }\n    return {text: text, ranges: ranges}\n  }\n\n  function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {\n    field.setAttribute(\"autocorrect\", !!autocorrect);\n    field.setAttribute(\"autocapitalize\", !!autocapitalize);\n    field.setAttribute(\"spellcheck\", !!spellcheck);\n  }\n\n  function hiddenTextarea() {\n    var te = elt(\"textarea\", null, null, \"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none\");\n    var div = elt(\"div\", [te], null, \"overflow: hidden; position: relative; width: 3px; height: 0px;\");\n    // The textarea is kept positioned near the cursor to prevent the\n    // fact that it'll be scrolled into view on input from scrolling\n    // our fake cursor out of view. On webkit, when wrap=off, paste is\n    // very slow. So make the area wide instead.\n    if (webkit) { te.style.width = \"1000px\"; }\n    else { te.setAttribute(\"wrap\", \"off\"); }\n    // If border: 0; -- iOS fails to open keyboard (issue #1287)\n    if (ios) { te.style.border = \"1px solid black\"; }\n    disableBrowserMagic(te);\n    return div\n  }\n\n  // The publicly visible API. Note that methodOp(f) means\n  // 'wrap f in an operation, performed on its `this` parameter'.\n\n  // This is not the complete set of editor methods. Most of the\n  // methods defined on the Doc type are also injected into\n  // CodeMirror.prototype, for backwards compatibility and\n  // convenience.\n\n  function addEditorMethods(CodeMirror) {\n    var optionHandlers = CodeMirror.optionHandlers;\n\n    var helpers = CodeMirror.helpers = {};\n\n    CodeMirror.prototype = {\n      constructor: CodeMirror,\n      focus: function(){window.focus(); this.display.input.focus();},\n\n      setOption: function(option, value) {\n        var options = this.options, old = options[option];\n        if (options[option] == value && option != \"mode\") { return }\n        options[option] = value;\n        if (optionHandlers.hasOwnProperty(option))\n          { operation(this, optionHandlers[option])(this, value, old); }\n        signal(this, \"optionChange\", this, option);\n      },\n\n      getOption: function(option) {return this.options[option]},\n      getDoc: function() {return this.doc},\n\n      addKeyMap: function(map$$1, bottom) {\n        this.state.keyMaps[bottom ? \"push\" : \"unshift\"](getKeyMap(map$$1));\n      },\n      removeKeyMap: function(map$$1) {\n        var maps = this.state.keyMaps;\n        for (var i = 0; i < maps.length; ++i)\n          { if (maps[i] == map$$1 || maps[i].name == map$$1) {\n            maps.splice(i, 1);\n            return true\n          } }\n      },\n\n      addOverlay: methodOp(function(spec, options) {\n        var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);\n        if (mode.startState) { throw new Error(\"Overlays may not be stateful.\") }\n        insertSorted(this.state.overlays,\n                     {mode: mode, modeSpec: spec, opaque: options && options.opaque,\n                      priority: (options && options.priority) || 0},\n                     function (overlay) { return overlay.priority; });\n        this.state.modeGen++;\n        regChange(this);\n      }),\n      removeOverlay: methodOp(function(spec) {\n        var this$1 = this;\n\n        var overlays = this.state.overlays;\n        for (var i = 0; i < overlays.length; ++i) {\n          var cur = overlays[i].modeSpec;\n          if (cur == spec || typeof spec == \"string\" && cur.name == spec) {\n            overlays.splice(i, 1);\n            this$1.state.modeGen++;\n            regChange(this$1);\n            return\n          }\n        }\n      }),\n\n      indentLine: methodOp(function(n, dir, aggressive) {\n        if (typeof dir != \"string\" && typeof dir != \"number\") {\n          if (dir == null) { dir = this.options.smartIndent ? \"smart\" : \"prev\"; }\n          else { dir = dir ? \"add\" : \"subtract\"; }\n        }\n        if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }\n      }),\n      indentSelection: methodOp(function(how) {\n        var this$1 = this;\n\n        var ranges = this.doc.sel.ranges, end = -1;\n        for (var i = 0; i < ranges.length; i++) {\n          var range$$1 = ranges[i];\n          if (!range$$1.empty()) {\n            var from = range$$1.from(), to = range$$1.to();\n            var start = Math.max(end, from.line);\n            end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;\n            for (var j = start; j < end; ++j)\n              { indentLine(this$1, j, how); }\n            var newRanges = this$1.doc.sel.ranges;\n            if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)\n              { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }\n          } else if (range$$1.head.line > end) {\n            indentLine(this$1, range$$1.head.line, how, true);\n            end = range$$1.head.line;\n            if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }\n          }\n        }\n      }),\n\n      // Fetch the parser token for a given character. Useful for hacks\n      // that want to inspect the mode state (say, for completion).\n      getTokenAt: function(pos, precise) {\n        return takeToken(this, pos, precise)\n      },\n\n      getLineTokens: function(line, precise) {\n        return takeToken(this, Pos(line), precise, true)\n      },\n\n      getTokenTypeAt: function(pos) {\n        pos = clipPos(this.doc, pos);\n        var styles = getLineStyles(this, getLine(this.doc, pos.line));\n        var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;\n        var type;\n        if (ch == 0) { type = styles[2]; }\n        else { for (;;) {\n          var mid = (before + after) >> 1;\n          if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }\n          else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }\n          else { type = styles[mid * 2 + 2]; break }\n        } }\n        var cut = type ? type.indexOf(\"overlay \") : -1;\n        return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)\n      },\n\n      getModeAt: function(pos) {\n        var mode = this.doc.mode;\n        if (!mode.innerMode) { return mode }\n        return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode\n      },\n\n      getHelper: function(pos, type) {\n        return this.getHelpers(pos, type)[0]\n      },\n\n      getHelpers: function(pos, type) {\n        var this$1 = this;\n\n        var found = [];\n        if (!helpers.hasOwnProperty(type)) { return found }\n        var help = helpers[type], mode = this.getModeAt(pos);\n        if (typeof mode[type] == \"string\") {\n          if (help[mode[type]]) { found.push(help[mode[type]]); }\n        } else if (mode[type]) {\n          for (var i = 0; i < mode[type].length; i++) {\n            var val = help[mode[type][i]];\n            if (val) { found.push(val); }\n          }\n        } else if (mode.helperType && help[mode.helperType]) {\n          found.push(help[mode.helperType]);\n        } else if (help[mode.name]) {\n          found.push(help[mode.name]);\n        }\n        for (var i$1 = 0; i$1 < help._global.length; i$1++) {\n          var cur = help._global[i$1];\n          if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)\n            { found.push(cur.val); }\n        }\n        return found\n      },\n\n      getStateAfter: function(line, precise) {\n        var doc = this.doc;\n        line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);\n        return getContextBefore(this, line + 1, precise).state\n      },\n\n      cursorCoords: function(start, mode) {\n        var pos, range$$1 = this.doc.sel.primary();\n        if (start == null) { pos = range$$1.head; }\n        else if (typeof start == \"object\") { pos = clipPos(this.doc, start); }\n        else { pos = start ? range$$1.from() : range$$1.to(); }\n        return cursorCoords(this, pos, mode || \"page\")\n      },\n\n      charCoords: function(pos, mode) {\n        return charCoords(this, clipPos(this.doc, pos), mode || \"page\")\n      },\n\n      coordsChar: function(coords, mode) {\n        coords = fromCoordSystem(this, coords, mode || \"page\");\n        return coordsChar(this, coords.left, coords.top)\n      },\n\n      lineAtHeight: function(height, mode) {\n        height = fromCoordSystem(this, {top: height, left: 0}, mode || \"page\").top;\n        return lineAtHeight(this.doc, height + this.display.viewOffset)\n      },\n      heightAtLine: function(line, mode, includeWidgets) {\n        var end = false, lineObj;\n        if (typeof line == \"number\") {\n          var last = this.doc.first + this.doc.size - 1;\n          if (line < this.doc.first) { line = this.doc.first; }\n          else if (line > last) { line = last; end = true; }\n          lineObj = getLine(this.doc, line);\n        } else {\n          lineObj = line;\n        }\n        return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || \"page\", includeWidgets || end).top +\n          (end ? this.doc.height - heightAtLine(lineObj) : 0)\n      },\n\n      defaultTextHeight: function() { return textHeight(this.display) },\n      defaultCharWidth: function() { return charWidth(this.display) },\n\n      getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},\n\n      addWidget: function(pos, node, scroll, vert, horiz) {\n        var display = this.display;\n        pos = cursorCoords(this, clipPos(this.doc, pos));\n        var top = pos.bottom, left = pos.left;\n        node.style.position = \"absolute\";\n        node.setAttribute(\"cm-ignore-events\", \"true\");\n        this.display.input.setUneditable(node);\n        display.sizer.appendChild(node);\n        if (vert == \"over\") {\n          top = pos.top;\n        } else if (vert == \"above\" || vert == \"near\") {\n          var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),\n          hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);\n          // Default to positioning above (if specified and possible); otherwise default to positioning below\n          if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)\n            { top = pos.top - node.offsetHeight; }\n          else if (pos.bottom + node.offsetHeight <= vspace)\n            { top = pos.bottom; }\n          if (left + node.offsetWidth > hspace)\n            { left = hspace - node.offsetWidth; }\n        }\n        node.style.top = top + \"px\";\n        node.style.left = node.style.right = \"\";\n        if (horiz == \"right\") {\n          left = display.sizer.clientWidth - node.offsetWidth;\n          node.style.right = \"0px\";\n        } else {\n          if (horiz == \"left\") { left = 0; }\n          else if (horiz == \"middle\") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }\n          node.style.left = left + \"px\";\n        }\n        if (scroll)\n          { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }\n      },\n\n      triggerOnKeyDown: methodOp(onKeyDown),\n      triggerOnKeyPress: methodOp(onKeyPress),\n      triggerOnKeyUp: onKeyUp,\n      triggerOnMouseDown: methodOp(onMouseDown),\n\n      execCommand: function(cmd) {\n        if (commands.hasOwnProperty(cmd))\n          { return commands[cmd].call(null, this) }\n      },\n\n      triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),\n\n      findPosH: function(from, amount, unit, visually) {\n        var this$1 = this;\n\n        var dir = 1;\n        if (amount < 0) { dir = -1; amount = -amount; }\n        var cur = clipPos(this.doc, from);\n        for (var i = 0; i < amount; ++i) {\n          cur = findPosH(this$1.doc, cur, dir, unit, visually);\n          if (cur.hitSide) { break }\n        }\n        return cur\n      },\n\n      moveH: methodOp(function(dir, unit) {\n        var this$1 = this;\n\n        this.extendSelectionsBy(function (range$$1) {\n          if (this$1.display.shift || this$1.doc.extend || range$$1.empty())\n            { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }\n          else\n            { return dir < 0 ? range$$1.from() : range$$1.to() }\n        }, sel_move);\n      }),\n\n      deleteH: methodOp(function(dir, unit) {\n        var sel = this.doc.sel, doc = this.doc;\n        if (sel.somethingSelected())\n          { doc.replaceSelection(\"\", null, \"+delete\"); }\n        else\n          { deleteNearSelection(this, function (range$$1) {\n            var other = findPosH(doc, range$$1.head, dir, unit, false);\n            return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}\n          }); }\n      }),\n\n      findPosV: function(from, amount, unit, goalColumn) {\n        var this$1 = this;\n\n        var dir = 1, x = goalColumn;\n        if (amount < 0) { dir = -1; amount = -amount; }\n        var cur = clipPos(this.doc, from);\n        for (var i = 0; i < amount; ++i) {\n          var coords = cursorCoords(this$1, cur, \"div\");\n          if (x == null) { x = coords.left; }\n          else { coords.left = x; }\n          cur = findPosV(this$1, coords, dir, unit);\n          if (cur.hitSide) { break }\n        }\n        return cur\n      },\n\n      moveV: methodOp(function(dir, unit) {\n        var this$1 = this;\n\n        var doc = this.doc, goals = [];\n        var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();\n        doc.extendSelectionsBy(function (range$$1) {\n          if (collapse)\n            { return dir < 0 ? range$$1.from() : range$$1.to() }\n          var headPos = cursorCoords(this$1, range$$1.head, \"div\");\n          if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }\n          goals.push(headPos.left);\n          var pos = findPosV(this$1, headPos, dir, unit);\n          if (unit == \"page\" && range$$1 == doc.sel.primary())\n            { addToScrollTop(this$1, charCoords(this$1, pos, \"div\").top - headPos.top); }\n          return pos\n        }, sel_move);\n        if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)\n          { doc.sel.ranges[i].goalColumn = goals[i]; } }\n      }),\n\n      // Find the word at the given position (as returned by coordsChar).\n      findWordAt: function(pos) {\n        var doc = this.doc, line = getLine(doc, pos.line).text;\n        var start = pos.ch, end = pos.ch;\n        if (line) {\n          var helper = this.getHelper(pos, \"wordChars\");\n          if ((pos.sticky == \"before\" || end == line.length) && start) { --start; } else { ++end; }\n          var startChar = line.charAt(start);\n          var check = isWordChar(startChar, helper)\n            ? function (ch) { return isWordChar(ch, helper); }\n            : /\\s/.test(startChar) ? function (ch) { return /\\s/.test(ch); }\n            : function (ch) { return (!/\\s/.test(ch) && !isWordChar(ch)); };\n          while (start > 0 && check(line.charAt(start - 1))) { --start; }\n          while (end < line.length && check(line.charAt(end))) { ++end; }\n        }\n        return new Range(Pos(pos.line, start), Pos(pos.line, end))\n      },\n\n      toggleOverwrite: function(value) {\n        if (value != null && value == this.state.overwrite) { return }\n        if (this.state.overwrite = !this.state.overwrite)\n          { addClass(this.display.cursorDiv, \"CodeMirror-overwrite\"); }\n        else\n          { rmClass(this.display.cursorDiv, \"CodeMirror-overwrite\"); }\n\n        signal(this, \"overwriteToggle\", this, this.state.overwrite);\n      },\n      hasFocus: function() { return this.display.input.getField() == activeElt() },\n      isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },\n\n      scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),\n      getScrollInfo: function() {\n        var scroller = this.display.scroller;\n        return {left: scroller.scrollLeft, top: scroller.scrollTop,\n                height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,\n                width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,\n                clientHeight: displayHeight(this), clientWidth: displayWidth(this)}\n      },\n\n      scrollIntoView: methodOp(function(range$$1, margin) {\n        if (range$$1 == null) {\n          range$$1 = {from: this.doc.sel.primary().head, to: null};\n          if (margin == null) { margin = this.options.cursorScrollMargin; }\n        } else if (typeof range$$1 == \"number\") {\n          range$$1 = {from: Pos(range$$1, 0), to: null};\n        } else if (range$$1.from == null) {\n          range$$1 = {from: range$$1, to: null};\n        }\n        if (!range$$1.to) { range$$1.to = range$$1.from; }\n        range$$1.margin = margin || 0;\n\n        if (range$$1.from.line != null) {\n          scrollToRange(this, range$$1);\n        } else {\n          scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);\n        }\n      }),\n\n      setSize: methodOp(function(width, height) {\n        var this$1 = this;\n\n        var interpret = function (val) { return typeof val == \"number\" || /^\\d+$/.test(String(val)) ? val + \"px\" : val; };\n        if (width != null) { this.display.wrapper.style.width = interpret(width); }\n        if (height != null) { this.display.wrapper.style.height = interpret(height); }\n        if (this.options.lineWrapping) { clearLineMeasurementCache(this); }\n        var lineNo$$1 = this.display.viewFrom;\n        this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {\n          if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)\n            { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, \"widget\"); break } } }\n          ++lineNo$$1;\n        });\n        this.curOp.forceUpdate = true;\n        signal(this, \"refresh\", this);\n      }),\n\n      operation: function(f){return runInOp(this, f)},\n      startOperation: function(){return startOperation(this)},\n      endOperation: function(){return endOperation(this)},\n\n      refresh: methodOp(function() {\n        var oldHeight = this.display.cachedTextHeight;\n        regChange(this);\n        this.curOp.forceUpdate = true;\n        clearCaches(this);\n        scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);\n        updateGutterSpace(this);\n        if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)\n          { estimateLineHeights(this); }\n        signal(this, \"refresh\", this);\n      }),\n\n      swapDoc: methodOp(function(doc) {\n        var old = this.doc;\n        old.cm = null;\n        attachDoc(this, doc);\n        clearCaches(this);\n        this.display.input.reset();\n        scrollToCoords(this, doc.scrollLeft, doc.scrollTop);\n        this.curOp.forceScroll = true;\n        signalLater(this, \"swapDoc\", this, old);\n        return old\n      }),\n\n      phrase: function(phraseText) {\n        var phrases = this.options.phrases;\n        return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText\n      },\n\n      getInputField: function(){return this.display.input.getField()},\n      getWrapperElement: function(){return this.display.wrapper},\n      getScrollerElement: function(){return this.display.scroller},\n      getGutterElement: function(){return this.display.gutters}\n    };\n    eventMixin(CodeMirror);\n\n    CodeMirror.registerHelper = function(type, name, value) {\n      if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }\n      helpers[type][name] = value;\n    };\n    CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {\n      CodeMirror.registerHelper(type, name, value);\n      helpers[type]._global.push({pred: predicate, val: value});\n    };\n  }\n\n  // Used for horizontal relative motion. Dir is -1 or 1 (left or\n  // right), unit can be \"char\", \"column\" (like char, but doesn't\n  // cross line boundaries), \"word\" (across next word), or \"group\" (to\n  // the start of next group of word or non-word-non-whitespace\n  // chars). The visually param controls whether, in right-to-left\n  // text, direction 1 means to move towards the next index in the\n  // string, or towards the character to the right of the current\n  // position. The resulting position will have a hitSide=true\n  // property if it reached the end of the document.\n  function findPosH(doc, pos, dir, unit, visually) {\n    var oldPos = pos;\n    var origDir = dir;\n    var lineObj = getLine(doc, pos.line);\n    function findNextLine() {\n      var l = pos.line + dir;\n      if (l < doc.first || l >= doc.first + doc.size) { return false }\n      pos = new Pos(l, pos.ch, pos.sticky);\n      return lineObj = getLine(doc, l)\n    }\n    function moveOnce(boundToLine) {\n      var next;\n      if (visually) {\n        next = moveVisually(doc.cm, lineObj, pos, dir);\n      } else {\n        next = moveLogically(lineObj, pos, dir);\n      }\n      if (next == null) {\n        if (!boundToLine && findNextLine())\n          { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }\n        else\n          { return false }\n      } else {\n        pos = next;\n      }\n      return true\n    }\n\n    if (unit == \"char\") {\n      moveOnce();\n    } else if (unit == \"column\") {\n      moveOnce(true);\n    } else if (unit == \"word\" || unit == \"group\") {\n      var sawType = null, group = unit == \"group\";\n      var helper = doc.cm && doc.cm.getHelper(pos, \"wordChars\");\n      for (var first = true;; first = false) {\n        if (dir < 0 && !moveOnce(!first)) { break }\n        var cur = lineObj.text.charAt(pos.ch) || \"\\n\";\n        var type = isWordChar(cur, helper) ? \"w\"\n          : group && cur == \"\\n\" ? \"n\"\n          : !group || /\\s/.test(cur) ? null\n          : \"p\";\n        if (group && !first && !type) { type = \"s\"; }\n        if (sawType && sawType != type) {\n          if (dir < 0) {dir = 1; moveOnce(); pos.sticky = \"after\";}\n          break\n        }\n\n        if (type) { sawType = type; }\n        if (dir > 0 && !moveOnce(!first)) { break }\n      }\n    }\n    var result = skipAtomic(doc, pos, oldPos, origDir, true);\n    if (equalCursorPos(oldPos, result)) { result.hitSide = true; }\n    return result\n  }\n\n  // For relative vertical movement. Dir may be -1 or 1. Unit can be\n  // \"page\" or \"line\". The resulting position will have a hitSide=true\n  // property if it reached the end of the document.\n  function findPosV(cm, pos, dir, unit) {\n    var doc = cm.doc, x = pos.left, y;\n    if (unit == \"page\") {\n      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);\n      var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);\n      y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;\n\n    } else if (unit == \"line\") {\n      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;\n    }\n    var target;\n    for (;;) {\n      target = coordsChar(cm, x, y);\n      if (!target.outside) { break }\n      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }\n      y += dir * 5;\n    }\n    return target\n  }\n\n  // CONTENTEDITABLE INPUT STYLE\n\n  var ContentEditableInput = function(cm) {\n    this.cm = cm;\n    this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;\n    this.polling = new Delayed();\n    this.composing = null;\n    this.gracePeriod = false;\n    this.readDOMTimeout = null;\n  };\n\n  ContentEditableInput.prototype.init = function (display) {\n      var this$1 = this;\n\n    var input = this, cm = input.cm;\n    var div = input.div = display.lineDiv;\n    disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);\n\n    on(div, \"paste\", function (e) {\n      if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }\n      // IE doesn't fire input events, so we schedule a read for the pasted content in this way\n      if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }\n    });\n\n    on(div, \"compositionstart\", function (e) {\n      this$1.composing = {data: e.data, done: false};\n    });\n    on(div, \"compositionupdate\", function (e) {\n      if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }\n    });\n    on(div, \"compositionend\", function (e) {\n      if (this$1.composing) {\n        if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }\n        this$1.composing.done = true;\n      }\n    });\n\n    on(div, \"touchstart\", function () { return input.forceCompositionEnd(); });\n\n    on(div, \"input\", function () {\n      if (!this$1.composing) { this$1.readFromDOMSoon(); }\n    });\n\n    function onCopyCut(e) {\n      if (signalDOMEvent(cm, e)) { return }\n      if (cm.somethingSelected()) {\n        setLastCopied({lineWise: false, text: cm.getSelections()});\n        if (e.type == \"cut\") { cm.replaceSelection(\"\", null, \"cut\"); }\n      } else if (!cm.options.lineWiseCopyCut) {\n        return\n      } else {\n        var ranges = copyableRanges(cm);\n        setLastCopied({lineWise: true, text: ranges.text});\n        if (e.type == \"cut\") {\n          cm.operation(function () {\n            cm.setSelections(ranges.ranges, 0, sel_dontScroll);\n            cm.replaceSelection(\"\", null, \"cut\");\n          });\n        }\n      }\n      if (e.clipboardData) {\n        e.clipboardData.clearData();\n        var content = lastCopied.text.join(\"\\n\");\n        // iOS exposes the clipboard API, but seems to discard content inserted into it\n        e.clipboardData.setData(\"Text\", content);\n        if (e.clipboardData.getData(\"Text\") == content) {\n          e.preventDefault();\n          return\n        }\n      }\n      // Old-fashioned briefly-focus-a-textarea hack\n      var kludge = hiddenTextarea(), te = kludge.firstChild;\n      cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);\n      te.value = lastCopied.text.join(\"\\n\");\n      var hadFocus = document.activeElement;\n      selectInput(te);\n      setTimeout(function () {\n        cm.display.lineSpace.removeChild(kludge);\n        hadFocus.focus();\n        if (hadFocus == div) { input.showPrimarySelection(); }\n      }, 50);\n    }\n    on(div, \"copy\", onCopyCut);\n    on(div, \"cut\", onCopyCut);\n  };\n\n  ContentEditableInput.prototype.prepareSelection = function () {\n    var result = prepareSelection(this.cm, false);\n    result.focus = this.cm.state.focused;\n    return result\n  };\n\n  ContentEditableInput.prototype.showSelection = function (info, takeFocus) {\n    if (!info || !this.cm.display.view.length) { return }\n    if (info.focus || takeFocus) { this.showPrimarySelection(); }\n    this.showMultipleSelections(info);\n  };\n\n  ContentEditableInput.prototype.getSelection = function () {\n    return this.cm.display.wrapper.ownerDocument.getSelection()\n  };\n\n  ContentEditableInput.prototype.showPrimarySelection = function () {\n    var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();\n    var from = prim.from(), to = prim.to();\n\n    if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {\n      sel.removeAllRanges();\n      return\n    }\n\n    var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);\n    var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);\n    if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&\n        cmp(minPos(curAnchor, curFocus), from) == 0 &&\n        cmp(maxPos(curAnchor, curFocus), to) == 0)\n      { return }\n\n    var view = cm.display.view;\n    var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||\n        {node: view[0].measure.map[2], offset: 0};\n    var end = to.line < cm.display.viewTo && posToDOM(cm, to);\n    if (!end) {\n      var measure = view[view.length - 1].measure;\n      var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;\n      end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};\n    }\n\n    if (!start || !end) {\n      sel.removeAllRanges();\n      return\n    }\n\n    var old = sel.rangeCount && sel.getRangeAt(0), rng;\n    try { rng = range(start.node, start.offset, end.offset, end.node); }\n    catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible\n    if (rng) {\n      if (!gecko && cm.state.focused) {\n        sel.collapse(start.node, start.offset);\n        if (!rng.collapsed) {\n          sel.removeAllRanges();\n          sel.addRange(rng);\n        }\n      } else {\n        sel.removeAllRanges();\n        sel.addRange(rng);\n      }\n      if (old && sel.anchorNode == null) { sel.addRange(old); }\n      else if (gecko) { this.startGracePeriod(); }\n    }\n    this.rememberSelection();\n  };\n\n  ContentEditableInput.prototype.startGracePeriod = function () {\n      var this$1 = this;\n\n    clearTimeout(this.gracePeriod);\n    this.gracePeriod = setTimeout(function () {\n      this$1.gracePeriod = false;\n      if (this$1.selectionChanged())\n        { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }\n    }, 20);\n  };\n\n  ContentEditableInput.prototype.showMultipleSelections = function (info) {\n    removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);\n    removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);\n  };\n\n  ContentEditableInput.prototype.rememberSelection = function () {\n    var sel = this.getSelection();\n    this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;\n    this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;\n  };\n\n  ContentEditableInput.prototype.selectionInEditor = function () {\n    var sel = this.getSelection();\n    if (!sel.rangeCount) { return false }\n    var node = sel.getRangeAt(0).commonAncestorContainer;\n    return contains(this.div, node)\n  };\n\n  ContentEditableInput.prototype.focus = function () {\n    if (this.cm.options.readOnly != \"nocursor\") {\n      if (!this.selectionInEditor())\n        { this.showSelection(this.prepareSelection(), true); }\n      this.div.focus();\n    }\n  };\n  ContentEditableInput.prototype.blur = function () { this.div.blur(); };\n  ContentEditableInput.prototype.getField = function () { return this.div };\n\n  ContentEditableInput.prototype.supportsTouch = function () { return true };\n\n  ContentEditableInput.prototype.receivedFocus = function () {\n    var input = this;\n    if (this.selectionInEditor())\n      { this.pollSelection(); }\n    else\n      { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }\n\n    function poll() {\n      if (input.cm.state.focused) {\n        input.pollSelection();\n        input.polling.set(input.cm.options.pollInterval, poll);\n      }\n    }\n    this.polling.set(this.cm.options.pollInterval, poll);\n  };\n\n  ContentEditableInput.prototype.selectionChanged = function () {\n    var sel = this.getSelection();\n    return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||\n      sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset\n  };\n\n  ContentEditableInput.prototype.pollSelection = function () {\n    if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }\n    var sel = this.getSelection(), cm = this.cm;\n    // On Android Chrome (version 56, at least), backspacing into an\n    // uneditable block element will put the cursor in that element,\n    // and then, because it's not editable, hide the virtual keyboard.\n    // Because Android doesn't allow us to actually detect backspace\n    // presses in a sane way, this code checks for when that happens\n    // and simulates a backspace press in this case.\n    if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {\n      this.cm.triggerOnKeyDown({type: \"keydown\", keyCode: 8, preventDefault: Math.abs});\n      this.blur();\n      this.focus();\n      return\n    }\n    if (this.composing) { return }\n    this.rememberSelection();\n    var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);\n    var head = domToPos(cm, sel.focusNode, sel.focusOffset);\n    if (anchor && head) { runInOp(cm, function () {\n      setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);\n      if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }\n    }); }\n  };\n\n  ContentEditableInput.prototype.pollContent = function () {\n    if (this.readDOMTimeout != null) {\n      clearTimeout(this.readDOMTimeout);\n      this.readDOMTimeout = null;\n    }\n\n    var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();\n    var from = sel.from(), to = sel.to();\n    if (from.ch == 0 && from.line > cm.firstLine())\n      { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }\n    if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())\n      { to = Pos(to.line + 1, 0); }\n    if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }\n\n    var fromIndex, fromLine, fromNode;\n    if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {\n      fromLine = lineNo(display.view[0].line);\n      fromNode = display.view[0].node;\n    } else {\n      fromLine = lineNo(display.view[fromIndex].line);\n      fromNode = display.view[fromIndex - 1].node.nextSibling;\n    }\n    var toIndex = findViewIndex(cm, to.line);\n    var toLine, toNode;\n    if (toIndex == display.view.length - 1) {\n      toLine = display.viewTo - 1;\n      toNode = display.lineDiv.lastChild;\n    } else {\n      toLine = lineNo(display.view[toIndex + 1].line) - 1;\n      toNode = display.view[toIndex + 1].node.previousSibling;\n    }\n\n    if (!fromNode) { return false }\n    var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));\n    var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));\n    while (newText.length > 1 && oldText.length > 1) {\n      if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }\n      else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }\n      else { break }\n    }\n\n    var cutFront = 0, cutEnd = 0;\n    var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);\n    while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))\n      { ++cutFront; }\n    var newBot = lst(newText), oldBot = lst(oldText);\n    var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),\n                             oldBot.length - (oldText.length == 1 ? cutFront : 0));\n    while (cutEnd < maxCutEnd &&\n           newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))\n      { ++cutEnd; }\n    // Try to move start of change to start of selection if ambiguous\n    if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {\n      while (cutFront && cutFront > from.ch &&\n             newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {\n        cutFront--;\n        cutEnd++;\n      }\n    }\n\n    newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\\u200b+/, \"\");\n    newText[0] = newText[0].slice(cutFront).replace(/\\u200b+$/, \"\");\n\n    var chFrom = Pos(fromLine, cutFront);\n    var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);\n    if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {\n      replaceRange(cm.doc, newText, chFrom, chTo, \"+input\");\n      return true\n    }\n  };\n\n  ContentEditableInput.prototype.ensurePolled = function () {\n    this.forceCompositionEnd();\n  };\n  ContentEditableInput.prototype.reset = function () {\n    this.forceCompositionEnd();\n  };\n  ContentEditableInput.prototype.forceCompositionEnd = function () {\n    if (!this.composing) { return }\n    clearTimeout(this.readDOMTimeout);\n    this.composing = null;\n    this.updateFromDOM();\n    this.div.blur();\n    this.div.focus();\n  };\n  ContentEditableInput.prototype.readFromDOMSoon = function () {\n      var this$1 = this;\n\n    if (this.readDOMTimeout != null) { return }\n    this.readDOMTimeout = setTimeout(function () {\n      this$1.readDOMTimeout = null;\n      if (this$1.composing) {\n        if (this$1.composing.done) { this$1.composing = null; }\n        else { return }\n      }\n      this$1.updateFromDOM();\n    }, 80);\n  };\n\n  ContentEditableInput.prototype.updateFromDOM = function () {\n      var this$1 = this;\n\n    if (this.cm.isReadOnly() || !this.pollContent())\n      { runInOp(this.cm, function () { return regChange(this$1.cm); }); }\n  };\n\n  ContentEditableInput.prototype.setUneditable = function (node) {\n    node.contentEditable = \"false\";\n  };\n\n  ContentEditableInput.prototype.onKeyPress = function (e) {\n    if (e.charCode == 0 || this.composing) { return }\n    e.preventDefault();\n    if (!this.cm.isReadOnly())\n      { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }\n  };\n\n  ContentEditableInput.prototype.readOnlyChanged = function (val) {\n    this.div.contentEditable = String(val != \"nocursor\");\n  };\n\n  ContentEditableInput.prototype.onContextMenu = function () {};\n  ContentEditableInput.prototype.resetPosition = function () {};\n\n  ContentEditableInput.prototype.needsContentAttribute = true;\n\n  function posToDOM(cm, pos) {\n    var view = findViewForLine(cm, pos.line);\n    if (!view || view.hidden) { return null }\n    var line = getLine(cm.doc, pos.line);\n    var info = mapFromLineView(view, line, pos.line);\n\n    var order = getOrder(line, cm.doc.direction), side = \"left\";\n    if (order) {\n      var partPos = getBidiPartAt(order, pos.ch);\n      side = partPos % 2 ? \"right\" : \"left\";\n    }\n    var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);\n    result.offset = result.collapse == \"right\" ? result.end : result.start;\n    return result\n  }\n\n  function isInGutter(node) {\n    for (var scan = node; scan; scan = scan.parentNode)\n      { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }\n    return false\n  }\n\n  function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }\n\n  function domTextBetween(cm, from, to, fromLine, toLine) {\n    var text = \"\", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;\n    function recognizeMarker(id) { return function (marker) { return marker.id == id; } }\n    function close() {\n      if (closing) {\n        text += lineSep;\n        if (extraLinebreak) { text += lineSep; }\n        closing = extraLinebreak = false;\n      }\n    }\n    function addText(str) {\n      if (str) {\n        close();\n        text += str;\n      }\n    }\n    function walk(node) {\n      if (node.nodeType == 1) {\n        var cmText = node.getAttribute(\"cm-text\");\n        if (cmText) {\n          addText(cmText);\n          return\n        }\n        var markerID = node.getAttribute(\"cm-marker\"), range$$1;\n        if (markerID) {\n          var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));\n          if (found.length && (range$$1 = found[0].find(0)))\n            { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }\n          return\n        }\n        if (node.getAttribute(\"contenteditable\") == \"false\") { return }\n        var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);\n        if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }\n\n        if (isBlock) { close(); }\n        for (var i = 0; i < node.childNodes.length; i++)\n          { walk(node.childNodes[i]); }\n\n        if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }\n        if (isBlock) { closing = true; }\n      } else if (node.nodeType == 3) {\n        addText(node.nodeValue.replace(/\\u200b/g, \"\").replace(/\\u00a0/g, \" \"));\n      }\n    }\n    for (;;) {\n      walk(from);\n      if (from == to) { break }\n      from = from.nextSibling;\n      extraLinebreak = false;\n    }\n    return text\n  }\n\n  function domToPos(cm, node, offset) {\n    var lineNode;\n    if (node == cm.display.lineDiv) {\n      lineNode = cm.display.lineDiv.childNodes[offset];\n      if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }\n      node = null; offset = 0;\n    } else {\n      for (lineNode = node;; lineNode = lineNode.parentNode) {\n        if (!lineNode || lineNode == cm.display.lineDiv) { return null }\n        if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }\n      }\n    }\n    for (var i = 0; i < cm.display.view.length; i++) {\n      var lineView = cm.display.view[i];\n      if (lineView.node == lineNode)\n        { return locateNodeInLineView(lineView, node, offset) }\n    }\n  }\n\n  function locateNodeInLineView(lineView, node, offset) {\n    var wrapper = lineView.text.firstChild, bad = false;\n    if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }\n    if (node == wrapper) {\n      bad = true;\n      node = wrapper.childNodes[offset];\n      offset = 0;\n      if (!node) {\n        var line = lineView.rest ? lst(lineView.rest) : lineView.line;\n        return badPos(Pos(lineNo(line), line.text.length), bad)\n      }\n    }\n\n    var textNode = node.nodeType == 3 ? node : null, topNode = node;\n    if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {\n      textNode = node.firstChild;\n      if (offset) { offset = textNode.nodeValue.length; }\n    }\n    while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }\n    var measure = lineView.measure, maps = measure.maps;\n\n    function find(textNode, topNode, offset) {\n      for (var i = -1; i < (maps ? maps.length : 0); i++) {\n        var map$$1 = i < 0 ? measure.map : maps[i];\n        for (var j = 0; j < map$$1.length; j += 3) {\n          var curNode = map$$1[j + 2];\n          if (curNode == textNode || curNode == topNode) {\n            var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);\n            var ch = map$$1[j] + offset;\n            if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }\n            return Pos(line, ch)\n          }\n        }\n      }\n    }\n    var found = find(textNode, topNode, offset);\n    if (found) { return badPos(found, bad) }\n\n    // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems\n    for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {\n      found = find(after, after.firstChild, 0);\n      if (found)\n        { return badPos(Pos(found.line, found.ch - dist), bad) }\n      else\n        { dist += after.textContent.length; }\n    }\n    for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {\n      found = find(before, before.firstChild, -1);\n      if (found)\n        { return badPos(Pos(found.line, found.ch + dist$1), bad) }\n      else\n        { dist$1 += before.textContent.length; }\n    }\n  }\n\n  // TEXTAREA INPUT STYLE\n\n  var TextareaInput = function(cm) {\n    this.cm = cm;\n    // See input.poll and input.reset\n    this.prevInput = \"\";\n\n    // Flag that indicates whether we expect input to appear real soon\n    // now (after some event like 'keypress' or 'input') and are\n    // polling intensively.\n    this.pollingFast = false;\n    // Self-resetting timeout for the poller\n    this.polling = new Delayed();\n    // Used to work around IE issue with selection being forgotten when focus moves away from textarea\n    this.hasSelection = false;\n    this.composing = null;\n  };\n\n  TextareaInput.prototype.init = function (display) {\n      var this$1 = this;\n\n    var input = this, cm = this.cm;\n    this.createField(display);\n    var te = this.textarea;\n\n    display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);\n\n    // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)\n    if (ios) { te.style.width = \"0px\"; }\n\n    on(te, \"input\", function () {\n      if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }\n      input.poll();\n    });\n\n    on(te, \"paste\", function (e) {\n      if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }\n\n      cm.state.pasteIncoming = true;\n      input.fastPoll();\n    });\n\n    function prepareCopyCut(e) {\n      if (signalDOMEvent(cm, e)) { return }\n      if (cm.somethingSelected()) {\n        setLastCopied({lineWise: false, text: cm.getSelections()});\n      } else if (!cm.options.lineWiseCopyCut) {\n        return\n      } else {\n        var ranges = copyableRanges(cm);\n        setLastCopied({lineWise: true, text: ranges.text});\n        if (e.type == \"cut\") {\n          cm.setSelections(ranges.ranges, null, sel_dontScroll);\n        } else {\n          input.prevInput = \"\";\n          te.value = ranges.text.join(\"\\n\");\n          selectInput(te);\n        }\n      }\n      if (e.type == \"cut\") { cm.state.cutIncoming = true; }\n    }\n    on(te, \"cut\", prepareCopyCut);\n    on(te, \"copy\", prepareCopyCut);\n\n    on(display.scroller, \"paste\", function (e) {\n      if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }\n      cm.state.pasteIncoming = true;\n      input.focus();\n    });\n\n    // Prevent normal selection in the editor (we handle our own)\n    on(display.lineSpace, \"selectstart\", function (e) {\n      if (!eventInWidget(display, e)) { e_preventDefault(e); }\n    });\n\n    on(te, \"compositionstart\", function () {\n      var start = cm.getCursor(\"from\");\n      if (input.composing) { input.composing.range.clear(); }\n      input.composing = {\n        start: start,\n        range: cm.markText(start, cm.getCursor(\"to\"), {className: \"CodeMirror-composing\"})\n      };\n    });\n    on(te, \"compositionend\", function () {\n      if (input.composing) {\n        input.poll();\n        input.composing.range.clear();\n        input.composing = null;\n      }\n    });\n  };\n\n  TextareaInput.prototype.createField = function (_display) {\n    // Wraps and hides input textarea\n    this.wrapper = hiddenTextarea();\n    // The semihidden textarea that is focused when the editor is\n    // focused, and receives input.\n    this.textarea = this.wrapper.firstChild;\n  };\n\n  TextareaInput.prototype.prepareSelection = function () {\n    // Redraw the selection and/or cursor\n    var cm = this.cm, display = cm.display, doc = cm.doc;\n    var result = prepareSelection(cm);\n\n    // Move the hidden textarea near the cursor to prevent scrolling artifacts\n    if (cm.options.moveInputWithCursor) {\n      var headPos = cursorCoords(cm, doc.sel.primary().head, \"div\");\n      var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();\n      result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,\n                                          headPos.top + lineOff.top - wrapOff.top));\n      result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,\n                                           headPos.left + lineOff.left - wrapOff.left));\n    }\n\n    return result\n  };\n\n  TextareaInput.prototype.showSelection = function (drawn) {\n    var cm = this.cm, display = cm.display;\n    removeChildrenAndAdd(display.cursorDiv, drawn.cursors);\n    removeChildrenAndAdd(display.selectionDiv, drawn.selection);\n    if (drawn.teTop != null) {\n      this.wrapper.style.top = drawn.teTop + \"px\";\n      this.wrapper.style.left = drawn.teLeft + \"px\";\n    }\n  };\n\n  // Reset the input to correspond to the selection (or to be empty,\n  // when not typing and nothing is selected)\n  TextareaInput.prototype.reset = function (typing) {\n    if (this.contextMenuPending || this.composing) { return }\n    var cm = this.cm;\n    if (cm.somethingSelected()) {\n      this.prevInput = \"\";\n      var content = cm.getSelection();\n      this.textarea.value = content;\n      if (cm.state.focused) { selectInput(this.textarea); }\n      if (ie && ie_version >= 9) { this.hasSelection = content; }\n    } else if (!typing) {\n      this.prevInput = this.textarea.value = \"\";\n      if (ie && ie_version >= 9) { this.hasSelection = null; }\n    }\n  };\n\n  TextareaInput.prototype.getField = function () { return this.textarea };\n\n  TextareaInput.prototype.supportsTouch = function () { return false };\n\n  TextareaInput.prototype.focus = function () {\n    if (this.cm.options.readOnly != \"nocursor\" && (!mobile || activeElt() != this.textarea)) {\n      try { this.textarea.focus(); }\n      catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM\n    }\n  };\n\n  TextareaInput.prototype.blur = function () { this.textarea.blur(); };\n\n  TextareaInput.prototype.resetPosition = function () {\n    this.wrapper.style.top = this.wrapper.style.left = 0;\n  };\n\n  TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };\n\n  // Poll for input changes, using the normal rate of polling. This\n  // runs as long as the editor is focused.\n  TextareaInput.prototype.slowPoll = function () {\n      var this$1 = this;\n\n    if (this.pollingFast) { return }\n    this.polling.set(this.cm.options.pollInterval, function () {\n      this$1.poll();\n      if (this$1.cm.state.focused) { this$1.slowPoll(); }\n    });\n  };\n\n  // When an event has just come in that is likely to add or change\n  // something in the input textarea, we poll faster, to ensure that\n  // the change appears on the screen quickly.\n  TextareaInput.prototype.fastPoll = function () {\n    var missed = false, input = this;\n    input.pollingFast = true;\n    function p() {\n      var changed = input.poll();\n      if (!changed && !missed) {missed = true; input.polling.set(60, p);}\n      else {input.pollingFast = false; input.slowPoll();}\n    }\n    input.polling.set(20, p);\n  };\n\n  // Read input from the textarea, and update the document to match.\n  // When something is selected, it is present in the textarea, and\n  // selected (unless it is huge, in which case a placeholder is\n  // used). When nothing is selected, the cursor sits after previously\n  // seen text (can be empty), which is stored in prevInput (we must\n  // not reset the textarea when typing, because that breaks IME).\n  TextareaInput.prototype.poll = function () {\n      var this$1 = this;\n\n    var cm = this.cm, input = this.textarea, prevInput = this.prevInput;\n    // Since this is called a *lot*, try to bail out as cheaply as\n    // possible when it is clear that nothing happened. hasSelection\n    // will be the case when there is a lot of text in the textarea,\n    // in which case reading its value would be expensive.\n    if (this.contextMenuPending || !cm.state.focused ||\n        (hasSelection(input) && !prevInput && !this.composing) ||\n        cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)\n      { return false }\n\n    var text = input.value;\n    // If nothing changed, bail.\n    if (text == prevInput && !cm.somethingSelected()) { return false }\n    // Work around nonsensical selection resetting in IE9/10, and\n    // inexplicable appearance of private area unicode characters on\n    // some key combos in Mac (#2689).\n    if (ie && ie_version >= 9 && this.hasSelection === text ||\n        mac && /[\\uf700-\\uf7ff]/.test(text)) {\n      cm.display.input.reset();\n      return false\n    }\n\n    if (cm.doc.sel == cm.display.selForContextMenu) {\n      var first = text.charCodeAt(0);\n      if (first == 0x200b && !prevInput) { prevInput = \"\\u200b\"; }\n      if (first == 0x21da) { this.reset(); return this.cm.execCommand(\"undo\") }\n    }\n    // Find the part of the input that is actually new\n    var same = 0, l = Math.min(prevInput.length, text.length);\n    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }\n\n    runInOp(cm, function () {\n      applyTextInput(cm, text.slice(same), prevInput.length - same,\n                     null, this$1.composing ? \"*compose\" : null);\n\n      // Don't leave long text in the textarea, since it makes further polling slow\n      if (text.length > 1000 || text.indexOf(\"\\n\") > -1) { input.value = this$1.prevInput = \"\"; }\n      else { this$1.prevInput = text; }\n\n      if (this$1.composing) {\n        this$1.composing.range.clear();\n        this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor(\"to\"),\n                                           {className: \"CodeMirror-composing\"});\n      }\n    });\n    return true\n  };\n\n  TextareaInput.prototype.ensurePolled = function () {\n    if (this.pollingFast && this.poll()) { this.pollingFast = false; }\n  };\n\n  TextareaInput.prototype.onKeyPress = function () {\n    if (ie && ie_version >= 9) { this.hasSelection = null; }\n    this.fastPoll();\n  };\n\n  TextareaInput.prototype.onContextMenu = function (e) {\n    var input = this, cm = input.cm, display = cm.display, te = input.textarea;\n    if (input.contextMenuPending) { input.contextMenuPending(); }\n    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;\n    if (!pos || presto) { return } // Opera is difficult.\n\n    // Reset the current text selection only if the click is done outside of the selection\n    // and 'resetSelectionOnContextMenu' option is true.\n    var reset = cm.options.resetSelectionOnContextMenu;\n    if (reset && cm.doc.sel.contains(pos) == -1)\n      { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }\n\n    var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;\n    var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();\n    input.wrapper.style.cssText = \"position: static\";\n    te.style.cssText = \"position: absolute; width: 30px; height: 30px;\\n      top: \" + (e.clientY - wrapperBox.top - 5) + \"px; left: \" + (e.clientX - wrapperBox.left - 5) + \"px;\\n      z-index: 1000; background: \" + (ie ? \"rgba(255, 255, 255, .05)\" : \"transparent\") + \";\\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);\";\n    var oldScrollY;\n    if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)\n    display.input.focus();\n    if (webkit) { window.scrollTo(null, oldScrollY); }\n    display.input.reset();\n    // Adds \"Select all\" to context menu in FF\n    if (!cm.somethingSelected()) { te.value = input.prevInput = \" \"; }\n    input.contextMenuPending = rehide;\n    display.selForContextMenu = cm.doc.sel;\n    clearTimeout(display.detectingSelectAll);\n\n    // Select-all will be greyed out if there's nothing to select, so\n    // this adds a zero-width space so that we can later check whether\n    // it got selected.\n    function prepareSelectAllHack() {\n      if (te.selectionStart != null) {\n        var selected = cm.somethingSelected();\n        var extval = \"\\u200b\" + (selected ? te.value : \"\");\n        te.value = \"\\u21da\"; // Used to catch context-menu undo\n        te.value = extval;\n        input.prevInput = selected ? \"\" : \"\\u200b\";\n        te.selectionStart = 1; te.selectionEnd = extval.length;\n        // Re-set this, in case some other handler touched the\n        // selection in the meantime.\n        display.selForContextMenu = cm.doc.sel;\n      }\n    }\n    function rehide() {\n      if (input.contextMenuPending != rehide) { return }\n      input.contextMenuPending = false;\n      input.wrapper.style.cssText = oldWrapperCSS;\n      te.style.cssText = oldCSS;\n      if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }\n\n      // Try to detect the user choosing select-all\n      if (te.selectionStart != null) {\n        if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }\n        var i = 0, poll = function () {\n          if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&\n              te.selectionEnd > 0 && input.prevInput == \"\\u200b\") {\n            operation(cm, selectAll)(cm);\n          } else if (i++ < 10) {\n            display.detectingSelectAll = setTimeout(poll, 500);\n          } else {\n            display.selForContextMenu = null;\n            display.input.reset();\n          }\n        };\n        display.detectingSelectAll = setTimeout(poll, 200);\n      }\n    }\n\n    if (ie && ie_version >= 9) { prepareSelectAllHack(); }\n    if (captureRightClick) {\n      e_stop(e);\n      var mouseup = function () {\n        off(window, \"mouseup\", mouseup);\n        setTimeout(rehide, 20);\n      };\n      on(window, \"mouseup\", mouseup);\n    } else {\n      setTimeout(rehide, 50);\n    }\n  };\n\n  TextareaInput.prototype.readOnlyChanged = function (val) {\n    if (!val) { this.reset(); }\n    this.textarea.disabled = val == \"nocursor\";\n  };\n\n  TextareaInput.prototype.setUneditable = function () {};\n\n  TextareaInput.prototype.needsContentAttribute = false;\n\n  function fromTextArea(textarea, options) {\n    options = options ? copyObj(options) : {};\n    options.value = textarea.value;\n    if (!options.tabindex && textarea.tabIndex)\n      { options.tabindex = textarea.tabIndex; }\n    if (!options.placeholder && textarea.placeholder)\n      { options.placeholder = textarea.placeholder; }\n    // Set autofocus to true if this textarea is focused, or if it has\n    // autofocus and no other element is focused.\n    if (options.autofocus == null) {\n      var hasFocus = activeElt();\n      options.autofocus = hasFocus == textarea ||\n        textarea.getAttribute(\"autofocus\") != null && hasFocus == document.body;\n    }\n\n    function save() {textarea.value = cm.getValue();}\n\n    var realSubmit;\n    if (textarea.form) {\n      on(textarea.form, \"submit\", save);\n      // Deplorable hack to make the submit method do the right thing.\n      if (!options.leaveSubmitMethodAlone) {\n        var form = textarea.form;\n        realSubmit = form.submit;\n        try {\n          var wrappedSubmit = form.submit = function () {\n            save();\n            form.submit = realSubmit;\n            form.submit();\n            form.submit = wrappedSubmit;\n          };\n        } catch(e) {}\n      }\n    }\n\n    options.finishInit = function (cm) {\n      cm.save = save;\n      cm.getTextArea = function () { return textarea; };\n      cm.toTextArea = function () {\n        cm.toTextArea = isNaN; // Prevent this from being ran twice\n        save();\n        textarea.parentNode.removeChild(cm.getWrapperElement());\n        textarea.style.display = \"\";\n        if (textarea.form) {\n          off(textarea.form, \"submit\", save);\n          if (typeof textarea.form.submit == \"function\")\n            { textarea.form.submit = realSubmit; }\n        }\n      };\n    };\n\n    textarea.style.display = \"none\";\n    var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },\n      options);\n    return cm\n  }\n\n  function addLegacyProps(CodeMirror) {\n    CodeMirror.off = off;\n    CodeMirror.on = on;\n    CodeMirror.wheelEventPixels = wheelEventPixels;\n    CodeMirror.Doc = Doc;\n    CodeMirror.splitLines = splitLinesAuto;\n    CodeMirror.countColumn = countColumn;\n    CodeMirror.findColumn = findColumn;\n    CodeMirror.isWordChar = isWordCharBasic;\n    CodeMirror.Pass = Pass;\n    CodeMirror.signal = signal;\n    CodeMirror.Line = Line;\n    CodeMirror.changeEnd = changeEnd;\n    CodeMirror.scrollbarModel = scrollbarModel;\n    CodeMirror.Pos = Pos;\n    CodeMirror.cmpPos = cmp;\n    CodeMirror.modes = modes;\n    CodeMirror.mimeModes = mimeModes;\n    CodeMirror.resolveMode = resolveMode;\n    CodeMirror.getMode = getMode;\n    CodeMirror.modeExtensions = modeExtensions;\n    CodeMirror.extendMode = extendMode;\n    CodeMirror.copyState = copyState;\n    CodeMirror.startState = startState;\n    CodeMirror.innerMode = innerMode;\n    CodeMirror.commands = commands;\n    CodeMirror.keyMap = keyMap;\n    CodeMirror.keyName = keyName;\n    CodeMirror.isModifierKey = isModifierKey;\n    CodeMirror.lookupKey = lookupKey;\n    CodeMirror.normalizeKeyMap = normalizeKeyMap;\n    CodeMirror.StringStream = StringStream;\n    CodeMirror.SharedTextMarker = SharedTextMarker;\n    CodeMirror.TextMarker = TextMarker;\n    CodeMirror.LineWidget = LineWidget;\n    CodeMirror.e_preventDefault = e_preventDefault;\n    CodeMirror.e_stopPropagation = e_stopPropagation;\n    CodeMirror.e_stop = e_stop;\n    CodeMirror.addClass = addClass;\n    CodeMirror.contains = contains;\n    CodeMirror.rmClass = rmClass;\n    CodeMirror.keyNames = keyNames;\n  }\n\n  // EDITOR CONSTRUCTOR\n\n  defineOptions(CodeMirror);\n\n  addEditorMethods(CodeMirror);\n\n  // Set up methods on CodeMirror's prototype to redirect to the editor's document.\n  var dontDelegate = \"iter insert remove copy getEditor constructor\".split(\" \");\n  for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)\n    { CodeMirror.prototype[prop] = (function(method) {\n      return function() {return method.apply(this.doc, arguments)}\n    })(Doc.prototype[prop]); } }\n\n  eventMixin(Doc);\n  CodeMirror.inputStyles = {\"textarea\": TextareaInput, \"contenteditable\": ContentEditableInput};\n\n  // Extra arguments are stored as the mode's dependencies, which is\n  // used by (legacy) mechanisms like loadmode.js to automatically\n  // load a mode. (Preferred mechanism is the require/define calls.)\n  CodeMirror.defineMode = function(name/*, mode, …*/) {\n    if (!CodeMirror.defaults.mode && name != \"null\") { CodeMirror.defaults.mode = name; }\n    defineMode.apply(this, arguments);\n  };\n\n  CodeMirror.defineMIME = defineMIME;\n\n  // Minimal default mode.\n  CodeMirror.defineMode(\"null\", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });\n  CodeMirror.defineMIME(\"text/plain\", \"null\");\n\n  // EXTENSIONS\n\n  CodeMirror.defineExtension = function (name, func) {\n    CodeMirror.prototype[name] = func;\n  };\n  CodeMirror.defineDocExtension = function (name, func) {\n    Doc.prototype[name] = func;\n  };\n\n  CodeMirror.fromTextArea = fromTextArea;\n\n  addLegacyProps(CodeMirror);\n\n  CodeMirror.version = \"5.43.0\";\n\n  return CodeMirror;\n\n})));\n"
  },
  {
    "path": "third_party/CodeMirror/mode/apl/apl.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"apl\", function() {\n  var builtInOps = {\n    \".\": \"innerProduct\",\n    \"\\\\\": \"scan\",\n    \"/\": \"reduce\",\n    \"⌿\": \"reduce1Axis\",\n    \"⍀\": \"scan1Axis\",\n    \"¨\": \"each\",\n    \"⍣\": \"power\"\n  };\n  var builtInFuncs = {\n    \"+\": [\"conjugate\", \"add\"],\n    \"−\": [\"negate\", \"subtract\"],\n    \"×\": [\"signOf\", \"multiply\"],\n    \"÷\": [\"reciprocal\", \"divide\"],\n    \"⌈\": [\"ceiling\", \"greaterOf\"],\n    \"⌊\": [\"floor\", \"lesserOf\"],\n    \"∣\": [\"absolute\", \"residue\"],\n    \"⍳\": [\"indexGenerate\", \"indexOf\"],\n    \"?\": [\"roll\", \"deal\"],\n    \"⋆\": [\"exponentiate\", \"toThePowerOf\"],\n    \"⍟\": [\"naturalLog\", \"logToTheBase\"],\n    \"○\": [\"piTimes\", \"circularFuncs\"],\n    \"!\": [\"factorial\", \"binomial\"],\n    \"⌹\": [\"matrixInverse\", \"matrixDivide\"],\n    \"<\": [null, \"lessThan\"],\n    \"≤\": [null, \"lessThanOrEqual\"],\n    \"=\": [null, \"equals\"],\n    \">\": [null, \"greaterThan\"],\n    \"≥\": [null, \"greaterThanOrEqual\"],\n    \"≠\": [null, \"notEqual\"],\n    \"≡\": [\"depth\", \"match\"],\n    \"≢\": [null, \"notMatch\"],\n    \"∈\": [\"enlist\", \"membership\"],\n    \"⍷\": [null, \"find\"],\n    \"∪\": [\"unique\", \"union\"],\n    \"∩\": [null, \"intersection\"],\n    \"∼\": [\"not\", \"without\"],\n    \"∨\": [null, \"or\"],\n    \"∧\": [null, \"and\"],\n    \"⍱\": [null, \"nor\"],\n    \"⍲\": [null, \"nand\"],\n    \"⍴\": [\"shapeOf\", \"reshape\"],\n    \",\": [\"ravel\", \"catenate\"],\n    \"⍪\": [null, \"firstAxisCatenate\"],\n    \"⌽\": [\"reverse\", \"rotate\"],\n    \"⊖\": [\"axis1Reverse\", \"axis1Rotate\"],\n    \"⍉\": [\"transpose\", null],\n    \"↑\": [\"first\", \"take\"],\n    \"↓\": [null, \"drop\"],\n    \"⊂\": [\"enclose\", \"partitionWithAxis\"],\n    \"⊃\": [\"diclose\", \"pick\"],\n    \"⌷\": [null, \"index\"],\n    \"⍋\": [\"gradeUp\", null],\n    \"⍒\": [\"gradeDown\", null],\n    \"⊤\": [\"encode\", null],\n    \"⊥\": [\"decode\", null],\n    \"⍕\": [\"format\", \"formatByExample\"],\n    \"⍎\": [\"execute\", null],\n    \"⊣\": [\"stop\", \"left\"],\n    \"⊢\": [\"pass\", \"right\"]\n  };\n\n  var isOperator = /[\\.\\/⌿⍀¨⍣]/;\n  var isNiladic = /⍬/;\n  var isFunction = /[\\+−×÷⌈⌊∣⍳\\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/;\n  var isArrow = /←/;\n  var isComment = /[⍝#].*$/;\n\n  var stringEater = function(type) {\n    var prev;\n    prev = false;\n    return function(c) {\n      prev = c;\n      if (c === type) {\n        return prev === \"\\\\\";\n      }\n      return true;\n    };\n  };\n  return {\n    startState: function() {\n      return {\n        prev: false,\n        func: false,\n        op: false,\n        string: false,\n        escape: false\n      };\n    },\n    token: function(stream, state) {\n      var ch, funcName;\n      if (stream.eatSpace()) {\n        return null;\n      }\n      ch = stream.next();\n      if (ch === '\"' || ch === \"'\") {\n        stream.eatWhile(stringEater(ch));\n        stream.next();\n        state.prev = true;\n        return \"string\";\n      }\n      if (/[\\[{\\(]/.test(ch)) {\n        state.prev = false;\n        return null;\n      }\n      if (/[\\]}\\)]/.test(ch)) {\n        state.prev = true;\n        return null;\n      }\n      if (isNiladic.test(ch)) {\n        state.prev = false;\n        return \"niladic\";\n      }\n      if (/[¯\\d]/.test(ch)) {\n        if (state.func) {\n          state.func = false;\n          state.prev = false;\n        } else {\n          state.prev = true;\n        }\n        stream.eatWhile(/[\\w\\.]/);\n        return \"number\";\n      }\n      if (isOperator.test(ch)) {\n        return \"operator apl-\" + builtInOps[ch];\n      }\n      if (isArrow.test(ch)) {\n        return \"apl-arrow\";\n      }\n      if (isFunction.test(ch)) {\n        funcName = \"apl-\";\n        if (builtInFuncs[ch] != null) {\n          if (state.prev) {\n            funcName += builtInFuncs[ch][1];\n          } else {\n            funcName += builtInFuncs[ch][0];\n          }\n        }\n        state.func = true;\n        state.prev = false;\n        return \"function \" + funcName;\n      }\n      if (isComment.test(ch)) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n      if (ch === \"∘\" && stream.peek() === \".\") {\n        stream.next();\n        return \"function jot-dot\";\n      }\n      stream.eatWhile(/[\\w\\$_]/);\n      state.prev = true;\n      return \"keyword\";\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/apl\", \"apl\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/apl/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: APL mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"./apl.js\"></script>\n<style>\n\t.CodeMirror { border: 2px inset #dee; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">APL</a>\n  </ul>\n</div>\n\n<article>\n<h2>APL mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n⍝ Conway's game of life\n\n⍝ This example was inspired by the impressive demo at\n⍝ http://www.youtube.com/watch?v=a9xAKttWgP4\n\n⍝ Create a matrix:\n⍝     0 1 1\n⍝     1 1 0\n⍝     0 1 0\ncreature ← (3 3 ⍴ ⍳ 9) ∈ 1 2 3 4 7   ⍝ Original creature from demo\ncreature ← (3 3 ⍴ ⍳ 9) ∈ 1 3 6 7 8   ⍝ Glider\n\n⍝ Place the creature on a larger board, near the centre\nboard ← ¯1 ⊖ ¯2 ⌽ 5 7 ↑ creature\n\n⍝ A function to move from one generation to the next\nlife ← {∨/ 1 ⍵ ∧ 3 4 = ⊂+/ +⌿ 1 0 ¯1 ∘.⊖ 1 0 ¯1 ⌽¨ ⊂⍵}\n\n⍝ Compute n-th generation and format it as a\n⍝ character matrix\ngen ← {' #'[(life ⍣ ⍵) board]}\n\n⍝ Show first three generations\n(gen 1) (gen 2) (gen 3)\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/apl\"\n      });\n    </script>\n\n    <p>Simple mode that tries to handle APL as well as it can.</p>\n    <p>It attempts to label functions/operators based upon\n    monadic/dyadic usage (but this is far from fully fleshed out).\n    This means there are meaningful classnames so hover states can\n    have popups etc.</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/apl</code> (APL code)</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/asciiarmor/asciiarmor.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function errorIfNotEmpty(stream) {\n    var nonWS = stream.match(/^\\s*\\S/);\n    stream.skipToEnd();\n    return nonWS ? \"error\" : null;\n  }\n\n  CodeMirror.defineMode(\"asciiarmor\", function() {\n    return {\n      token: function(stream, state) {\n        var m;\n        if (state.state == \"top\") {\n          if (stream.sol() && (m = stream.match(/^-----BEGIN (.*)?-----\\s*$/))) {\n            state.state = \"headers\";\n            state.type = m[1];\n            return \"tag\";\n          }\n          return errorIfNotEmpty(stream);\n        } else if (state.state == \"headers\") {\n          if (stream.sol() && stream.match(/^\\w+:/)) {\n            state.state = \"header\";\n            return \"atom\";\n          } else {\n            var result = errorIfNotEmpty(stream);\n            if (result) state.state = \"body\";\n            return result;\n          }\n        } else if (state.state == \"header\") {\n          stream.skipToEnd();\n          state.state = \"headers\";\n          return \"string\";\n        } else if (state.state == \"body\") {\n          if (stream.sol() && (m = stream.match(/^-----END (.*)?-----\\s*$/))) {\n            if (m[1] != state.type) return \"error\";\n            state.state = \"end\";\n            return \"tag\";\n          } else {\n            if (stream.eatWhile(/[A-Za-z0-9+\\/=]/)) {\n              return null;\n            } else {\n              stream.next();\n              return \"error\";\n            }\n          }\n        } else if (state.state == \"end\") {\n          return errorIfNotEmpty(stream);\n        }\n      },\n      blankLine: function(state) {\n        if (state.state == \"headers\") state.state = \"body\";\n      },\n      startState: function() {\n        return {state: \"top\", type: null};\n      }\n    };\n  });\n\n  CodeMirror.defineMIME(\"application/pgp\", \"asciiarmor\");\n  CodeMirror.defineMIME(\"application/pgp-encrypted\", \"asciiarmor\");\n  CodeMirror.defineMIME(\"application/pgp-keys\", \"asciiarmor\");\n  CodeMirror.defineMIME(\"application/pgp-signature\", \"asciiarmor\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/asciiarmor/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: ASCII Armor (PGP) mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"asciiarmor.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">ASCII Armor</a>\n  </ul>\n</div>\n\n<article>\n<h2>ASCII Armor (PGP) mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n-----BEGIN PGP MESSAGE-----\nVersion: OpenPrivacy 0.99\n\nyDgBO22WxBHv7O8X7O/jygAEzol56iUKiXmV+XmpCtmpqQUKiQrFqclFqUDBovzS\nvBSFjNSiVHsuAA==\n=njUN\n-----END PGP MESSAGE-----\n</textarea></form>\n\n<script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true\n});\n</script>\n\n<p><strong>MIME types\ndefined:</strong> <code>application/pgp</code>, <code>application/pgp-encrypted</code>, <code>application/pgp-keys</code>, <code>application/pgp-signature</code></p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/asn.1/asn.1.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"asn.1\", function(config, parserConfig) {\n    var indentUnit = config.indentUnit,\n        keywords = parserConfig.keywords || {},\n        cmipVerbs = parserConfig.cmipVerbs || {},\n        compareTypes = parserConfig.compareTypes || {},\n        status = parserConfig.status || {},\n        tags = parserConfig.tags || {},\n        storage = parserConfig.storage || {},\n        modifier = parserConfig.modifier || {},\n        accessTypes = parserConfig.accessTypes|| {},\n        multiLineStrings = parserConfig.multiLineStrings,\n        indentStatements = parserConfig.indentStatements !== false;\n    var isOperatorChar = /[\\|\\^]/;\n    var curPunc;\n\n    function tokenBase(stream, state) {\n      var ch = stream.next();\n      if (ch == '\"' || ch == \"'\") {\n        state.tokenize = tokenString(ch);\n        return state.tokenize(stream, state);\n      }\n      if (/[\\[\\]\\(\\){}:=,;]/.test(ch)) {\n        curPunc = ch;\n        return \"punctuation\";\n      }\n      if (ch == \"-\"){\n        if (stream.eat(\"-\")) {\n          stream.skipToEnd();\n          return \"comment\";\n        }\n      }\n      if (/\\d/.test(ch)) {\n        stream.eatWhile(/[\\w\\.]/);\n        return \"number\";\n      }\n      if (isOperatorChar.test(ch)) {\n        stream.eatWhile(isOperatorChar);\n        return \"operator\";\n      }\n\n      stream.eatWhile(/[\\w\\-]/);\n      var cur = stream.current();\n      if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n      if (cmipVerbs.propertyIsEnumerable(cur)) return \"variable cmipVerbs\";\n      if (compareTypes.propertyIsEnumerable(cur)) return \"atom compareTypes\";\n      if (status.propertyIsEnumerable(cur)) return \"comment status\";\n      if (tags.propertyIsEnumerable(cur)) return \"variable-3 tags\";\n      if (storage.propertyIsEnumerable(cur)) return \"builtin storage\";\n      if (modifier.propertyIsEnumerable(cur)) return \"string-2 modifier\";\n      if (accessTypes.propertyIsEnumerable(cur)) return \"atom accessTypes\";\n\n      return \"variable\";\n    }\n\n    function tokenString(quote) {\n      return function(stream, state) {\n        var escaped = false, next, end = false;\n        while ((next = stream.next()) != null) {\n          if (next == quote && !escaped){\n            var afterNext = stream.peek();\n            //look if the character if the quote is like the B in '10100010'B\n            if (afterNext){\n              afterNext = afterNext.toLowerCase();\n              if(afterNext == \"b\" || afterNext == \"h\" || afterNext == \"o\")\n                stream.next();\n            }\n            end = true; break;\n          }\n          escaped = !escaped && next == \"\\\\\";\n        }\n        if (end || !(escaped || multiLineStrings))\n          state.tokenize = null;\n        return \"string\";\n      };\n    }\n\n    function Context(indented, column, type, align, prev) {\n      this.indented = indented;\n      this.column = column;\n      this.type = type;\n      this.align = align;\n      this.prev = prev;\n    }\n    function pushContext(state, col, type) {\n      var indent = state.indented;\n      if (state.context && state.context.type == \"statement\")\n        indent = state.context.indented;\n      return state.context = new Context(indent, col, type, null, state.context);\n    }\n    function popContext(state) {\n      var t = state.context.type;\n      if (t == \")\" || t == \"]\" || t == \"}\")\n        state.indented = state.context.indented;\n      return state.context = state.context.prev;\n    }\n\n    //Interface\n    return {\n      startState: function(basecolumn) {\n        return {\n          tokenize: null,\n          context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", false),\n          indented: 0,\n          startOfLine: true\n        };\n      },\n\n      token: function(stream, state) {\n        var ctx = state.context;\n        if (stream.sol()) {\n          if (ctx.align == null) ctx.align = false;\n          state.indented = stream.indentation();\n          state.startOfLine = true;\n        }\n        if (stream.eatSpace()) return null;\n        curPunc = null;\n        var style = (state.tokenize || tokenBase)(stream, state);\n        if (style == \"comment\") return style;\n        if (ctx.align == null) ctx.align = true;\n\n        if ((curPunc == \";\" || curPunc == \":\" || curPunc == \",\")\n            && ctx.type == \"statement\"){\n          popContext(state);\n        }\n        else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n        else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n        else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n        else if (curPunc == \"}\") {\n          while (ctx.type == \"statement\") ctx = popContext(state);\n          if (ctx.type == \"}\") ctx = popContext(state);\n          while (ctx.type == \"statement\") ctx = popContext(state);\n        }\n        else if (curPunc == ctx.type) popContext(state);\n        else if (indentStatements && (((ctx.type == \"}\" || ctx.type == \"top\")\n            && curPunc != ';') || (ctx.type == \"statement\"\n            && curPunc == \"newstatement\")))\n          pushContext(state, stream.column(), \"statement\");\n\n        state.startOfLine = false;\n        return style;\n      },\n\n      electricChars: \"{}\",\n      lineComment: \"--\",\n      fold: \"brace\"\n    };\n  });\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  CodeMirror.defineMIME(\"text/x-ttcn-asn\", {\n    name: \"asn.1\",\n    keywords: words(\"DEFINITIONS OBJECTS IF DERIVED INFORMATION ACTION\" +\n    \" REPLY ANY NAMED CHARACTERIZED BEHAVIOUR REGISTERED\" +\n    \" WITH AS IDENTIFIED CONSTRAINED BY PRESENT BEGIN\" +\n    \" IMPORTS FROM UNITS SYNTAX MIN-ACCESS MAX-ACCESS\" +\n    \" MINACCESS MAXACCESS REVISION STATUS DESCRIPTION\" +\n    \" SEQUENCE SET COMPONENTS OF CHOICE DistinguishedName\" +\n    \" ENUMERATED SIZE MODULE END INDEX AUGMENTS EXTENSIBILITY\" +\n    \" IMPLIED EXPORTS\"),\n    cmipVerbs: words(\"ACTIONS ADD GET NOTIFICATIONS REPLACE REMOVE\"),\n    compareTypes: words(\"OPTIONAL DEFAULT MANAGED MODULE-TYPE MODULE_IDENTITY\" +\n    \" MODULE-COMPLIANCE OBJECT-TYPE OBJECT-IDENTITY\" +\n    \" OBJECT-COMPLIANCE MODE CONFIRMED CONDITIONAL\" +\n    \" SUBORDINATE SUPERIOR CLASS TRUE FALSE NULL\" +\n    \" TEXTUAL-CONVENTION\"),\n    status: words(\"current deprecated mandatory obsolete\"),\n    tags: words(\"APPLICATION AUTOMATIC EXPLICIT IMPLICIT PRIVATE TAGS\" +\n    \" UNIVERSAL\"),\n    storage: words(\"BOOLEAN INTEGER OBJECT IDENTIFIER BIT OCTET STRING\" +\n    \" UTCTime InterfaceIndex IANAifType CMIP-Attribute\" +\n    \" REAL PACKAGE PACKAGES IpAddress PhysAddress\" +\n    \" NetworkAddress BITS BMPString TimeStamp TimeTicks\" +\n    \" TruthValue RowStatus DisplayString GeneralString\" +\n    \" GraphicString IA5String NumericString\" +\n    \" PrintableString SnmpAdminAtring TeletexString\" +\n    \" UTF8String VideotexString VisibleString StringStore\" +\n    \" ISO646String T61String UniversalString Unsigned32\" +\n    \" Integer32 Gauge Gauge32 Counter Counter32 Counter64\"),\n    modifier: words(\"ATTRIBUTE ATTRIBUTES MANDATORY-GROUP MANDATORY-GROUPS\" +\n    \" GROUP GROUPS ELEMENTS EQUALITY ORDERING SUBSTRINGS\" +\n    \" DEFINED\"),\n    accessTypes: words(\"not-accessible accessible-for-notify read-only\" +\n    \" read-create read-write\"),\n    multiLineStrings: true\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/asn.1/index.html",
    "content": "﻿<!doctype html>\n\n<title>CodeMirror: ASN.1 mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"asn.1.js\"></script>\n<style>\n    .CodeMirror {\n        border-top: 1px solid black;\n        border-bottom: 1px solid black;\n    }\n</style>\n<div id=nav>\n    <a href=\"https://codemirror.net\"><h1>CodeMirror</h1>\n        <img id=logo src=\"../../doc/logo.png\">\n    </a>\n\n    <ul>\n        <li><a href=\"../../index.html\">Home</a>\n        <li><a href=\"../../doc/manual.html\">Manual</a>\n        <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n    </ul>\n    <ul>\n        <li><a href=\"../index.html\">Language modes</a>\n        <li><a class=active href=\"http://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One\">ASN.1</a>\n    </ul>\n</div>\n<article>\n    <h2>ASN.1 example</h2>\n    <div>\n        <textarea id=\"ttcn-asn-code\">\n --\n -- Sample ASN.1 Code\n --\n MyModule DEFINITIONS ::=\n BEGIN\n\n MyTypes ::= SEQUENCE {\n     myObjectId   OBJECT IDENTIFIER,\n     mySeqOf      SEQUENCE OF MyInt,\n     myBitString  BIT STRING {\n                         muxToken(0),\n                         modemToken(1)\n                  }\n }\n\n MyInt ::= INTEGER (0..65535)\n\n END\n        </textarea>\n    </div>\n\n    <script>\n        var ttcnEditor = CodeMirror.fromTextArea(document.getElementById(\"ttcn-asn-code\"), {\n            lineNumbers: true,\n            matchBrackets: true,\n            mode: \"text/x-ttcn-asn\"\n        });\n        ttcnEditor.setSize(400, 400);\n        var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault;\n        CodeMirror.keyMap.default[(mac ? \"Cmd\" : \"Ctrl\") + \"-Space\"] = \"autocomplete\";\n    </script>\n    <br/>\n    <p><strong>Language:</strong> Abstract Syntax Notation One\n        (<a href=\"http://www.itu.int/en/ITU-T/asn1/Pages/introduction.aspx\">ASN.1</a>)\n    </p>\n    <p><strong>MIME types defined:</strong> <code>text/x-ttcn-asn</code></p>\n\n    <br/>\n    <p>The development of this mode has been sponsored by <a href=\"http://www.ericsson.com/\">Ericsson\n    </a>.</p>\n    <p>Coded by Asmelash Tsegay Gebretsadkan </p>\n</article>\n\n"
  },
  {
    "path": "third_party/CodeMirror/mode/asterisk/asterisk.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/*\n * =====================================================================================\n *\n *       Filename:  mode/asterisk/asterisk.js\n *\n *    Description:  CodeMirror mode for Asterisk dialplan\n *\n *        Created:  05/17/2012 09:20:25 PM\n *       Revision:  none\n *\n *         Author:  Stas Kobzar (stas@modulis.ca),\n *        Company:  Modulis.ca Inc.\n *\n * =====================================================================================\n */\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"asterisk\", function() {\n  var atoms    = [\"exten\", \"same\", \"include\",\"ignorepat\",\"switch\"],\n      dpcmd    = [\"#include\",\"#exec\"],\n      apps     = [\n                  \"addqueuemember\",\"adsiprog\",\"aelsub\",\"agentlogin\",\"agentmonitoroutgoing\",\"agi\",\n                  \"alarmreceiver\",\"amd\",\"answer\",\"authenticate\",\"background\",\"backgrounddetect\",\n                  \"bridge\",\"busy\",\"callcompletioncancel\",\"callcompletionrequest\",\"celgenuserevent\",\n                  \"changemonitor\",\"chanisavail\",\"channelredirect\",\"chanspy\",\"clearhash\",\"confbridge\",\n                  \"congestion\",\"continuewhile\",\"controlplayback\",\"dahdiacceptr2call\",\"dahdibarge\",\n                  \"dahdiras\",\"dahdiscan\",\"dahdisendcallreroutingfacility\",\"dahdisendkeypadfacility\",\n                  \"datetime\",\"dbdel\",\"dbdeltree\",\"deadagi\",\"dial\",\"dictate\",\"directory\",\"disa\",\n                  \"dumpchan\",\"eagi\",\"echo\",\"endwhile\",\"exec\",\"execif\",\"execiftime\",\"exitwhile\",\"extenspy\",\n                  \"externalivr\",\"festival\",\"flash\",\"followme\",\"forkcdr\",\"getcpeid\",\"gosub\",\"gosubif\",\n                  \"goto\",\"gotoif\",\"gotoiftime\",\"hangup\",\"iax2provision\",\"ices\",\"importvar\",\"incomplete\",\n                  \"ivrdemo\",\"jabberjoin\",\"jabberleave\",\"jabbersend\",\"jabbersendgroup\",\"jabberstatus\",\n                  \"jack\",\"log\",\"macro\",\"macroexclusive\",\"macroexit\",\"macroif\",\"mailboxexists\",\"meetme\",\n                  \"meetmeadmin\",\"meetmechanneladmin\",\"meetmecount\",\"milliwatt\",\"minivmaccmess\",\"minivmdelete\",\n                  \"minivmgreet\",\"minivmmwi\",\"minivmnotify\",\"minivmrecord\",\"mixmonitor\",\"monitor\",\"morsecode\",\n                  \"mp3player\",\"mset\",\"musiconhold\",\"nbscat\",\"nocdr\",\"noop\",\"odbc\",\"odbc\",\"odbcfinish\",\n                  \"originate\",\"ospauth\",\"ospfinish\",\"osplookup\",\"ospnext\",\"page\",\"park\",\"parkandannounce\",\n                  \"parkedcall\",\"pausemonitor\",\"pausequeuemember\",\"pickup\",\"pickupchan\",\"playback\",\"playtones\",\n                  \"privacymanager\",\"proceeding\",\"progress\",\"queue\",\"queuelog\",\"raiseexception\",\"read\",\"readexten\",\n                  \"readfile\",\"receivefax\",\"receivefax\",\"receivefax\",\"record\",\"removequeuemember\",\n                  \"resetcdr\",\"retrydial\",\"return\",\"ringing\",\"sayalpha\",\"saycountedadj\",\"saycountednoun\",\n                  \"saycountpl\",\"saydigits\",\"saynumber\",\"sayphonetic\",\"sayunixtime\",\"senddtmf\",\"sendfax\",\n                  \"sendfax\",\"sendfax\",\"sendimage\",\"sendtext\",\"sendurl\",\"set\",\"setamaflags\",\n                  \"setcallerpres\",\"setmusiconhold\",\"sipaddheader\",\"sipdtmfmode\",\"sipremoveheader\",\"skel\",\n                  \"slastation\",\"slatrunk\",\"sms\",\"softhangup\",\"speechactivategrammar\",\"speechbackground\",\n                  \"speechcreate\",\"speechdeactivategrammar\",\"speechdestroy\",\"speechloadgrammar\",\"speechprocessingsound\",\n                  \"speechstart\",\"speechunloadgrammar\",\"stackpop\",\"startmusiconhold\",\"stopmixmonitor\",\"stopmonitor\",\n                  \"stopmusiconhold\",\"stopplaytones\",\"system\",\"testclient\",\"testserver\",\"transfer\",\"tryexec\",\n                  \"trysystem\",\"unpausemonitor\",\"unpausequeuemember\",\"userevent\",\"verbose\",\"vmauthenticate\",\n                  \"vmsayname\",\"voicemail\",\"voicemailmain\",\"wait\",\"waitexten\",\"waitfornoise\",\"waitforring\",\n                  \"waitforsilence\",\"waitmusiconhold\",\"waituntil\",\"while\",\"zapateller\"\n                 ];\n\n  function basicToken(stream,state){\n    var cur = '';\n    var ch = stream.next();\n    // comment\n    if(ch == \";\") {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n    // context\n    if(ch == '[') {\n      stream.skipTo(']');\n      stream.eat(']');\n      return \"header\";\n    }\n    // string\n    if(ch == '\"') {\n      stream.skipTo('\"');\n      return \"string\";\n    }\n    if(ch == \"'\") {\n      stream.skipTo(\"'\");\n      return \"string-2\";\n    }\n    // dialplan commands\n    if(ch == '#') {\n      stream.eatWhile(/\\w/);\n      cur = stream.current();\n      if(dpcmd.indexOf(cur) !== -1) {\n        stream.skipToEnd();\n        return \"strong\";\n      }\n    }\n    // application args\n    if(ch == '$'){\n      var ch1 = stream.peek();\n      if(ch1 == '{'){\n        stream.skipTo('}');\n        stream.eat('}');\n        return \"variable-3\";\n      }\n    }\n    // extension\n    stream.eatWhile(/\\w/);\n    cur = stream.current();\n    if(atoms.indexOf(cur) !== -1) {\n      state.extenStart = true;\n      switch(cur) {\n        case 'same': state.extenSame = true; break;\n        case 'include':\n        case 'switch':\n        case 'ignorepat':\n          state.extenInclude = true;break;\n        default:break;\n      }\n      return \"atom\";\n    }\n  }\n\n  return {\n    startState: function() {\n      return {\n        extenStart: false,\n        extenSame:  false,\n        extenInclude: false,\n        extenExten: false,\n        extenPriority: false,\n        extenApplication: false\n      };\n    },\n    token: function(stream, state) {\n\n      var cur = '';\n      if(stream.eatSpace()) return null;\n      // extension started\n      if(state.extenStart){\n        stream.eatWhile(/[^\\s]/);\n        cur = stream.current();\n        if(/^=>?$/.test(cur)){\n          state.extenExten = true;\n          state.extenStart = false;\n          return \"strong\";\n        } else {\n          state.extenStart = false;\n          stream.skipToEnd();\n          return \"error\";\n        }\n      } else if(state.extenExten) {\n        // set exten and priority\n        state.extenExten = false;\n        state.extenPriority = true;\n        stream.eatWhile(/[^,]/);\n        if(state.extenInclude) {\n          stream.skipToEnd();\n          state.extenPriority = false;\n          state.extenInclude = false;\n        }\n        if(state.extenSame) {\n          state.extenPriority = false;\n          state.extenSame = false;\n          state.extenApplication = true;\n        }\n        return \"tag\";\n      } else if(state.extenPriority) {\n        state.extenPriority = false;\n        state.extenApplication = true;\n        stream.next(); // get comma\n        if(state.extenSame) return null;\n        stream.eatWhile(/[^,]/);\n        return \"number\";\n      } else if(state.extenApplication) {\n        stream.eatWhile(/,/);\n        cur = stream.current();\n        if(cur === ',') return null;\n        stream.eatWhile(/\\w/);\n        cur = stream.current().toLowerCase();\n        state.extenApplication = false;\n        if(apps.indexOf(cur) !== -1){\n          return \"def strong\";\n        }\n      } else{\n        return basicToken(stream,state);\n      }\n\n      return null;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-asterisk\", \"asterisk\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/asterisk/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Asterisk dialplan mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"asterisk.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid #999;}\n      .cm-s-default span.cm-arrow { color: red; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Asterisk dialplan</a>\n  </ul>\n</div>\n\n<article>\n<h2>Asterisk dialplan mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n; extensions.conf - the Asterisk dial plan\n;\n\n[general]\n;\n; If static is set to no, or omitted, then the pbx_config will rewrite\n; this file when extensions are modified.  Remember that all comments\n; made in the file will be lost when that happens.\nstatic=yes\n\n#include \"/etc/asterisk/additional_general.conf\n\n[iaxprovider]\nswitch => IAX2/user:[key]@myserver/mycontext\n\n[dynamic]\n#exec /usr/bin/dynamic-peers.pl\n\n[trunkint]\n;\n; International long distance through trunk\n;\nexten => _9011.,1,Macro(dundi-e164,${EXTEN:4})\nexten => _9011.,n,Dial(${GLOBAL(TRUNK)}/${FILTER(0-9,${EXTEN:${GLOBAL(TRUNKMSD)}})})\n\n[local]\n;\n; Master context for local, toll-free, and iaxtel calls only\n;\nignorepat => 9\ninclude => default\n\n[demo]\ninclude => stdexten\n;\n; We start with what to do when a call first comes in.\n;\nexten => s,1,Wait(1)\t\t\t; Wait a second, just for fun\nsame  => n,Answer\t\t\t; Answer the line\nsame  => n,Set(TIMEOUT(digit)=5)\t; Set Digit Timeout to 5 seconds\nsame  => n,Set(TIMEOUT(response)=10)\t; Set Response Timeout to 10 seconds\nsame  => n(restart),BackGround(demo-congrats)\t; Play a congratulatory message\nsame  => n(instruct),BackGround(demo-instruct)\t; Play some instructions\nsame  => n,WaitExten\t\t\t; Wait for an extension to be dialed.\n\nexten => 2,1,BackGround(demo-moreinfo)\t; Give some more information.\nexten => 2,n,Goto(s,instruct)\n\nexten => 3,1,Set(LANGUAGE()=fr)\t\t; Set language to french\nexten => 3,n,Goto(s,restart)\t\t; Start with the congratulations\n\nexten => 1000,1,Goto(default,s,1)\n;\n; We also create an example user, 1234, who is on the console and has\n; voicemail, etc.\n;\nexten => 1234,1,Playback(transfer,skip)\t\t; \"Please hold while...\"\n\t\t\t\t\t; (but skip if channel is not up)\nexten => 1234,n,Gosub(${EXTEN},stdexten(${GLOBAL(CONSOLE)}))\nexten => 1234,n,Goto(default,s,1)\t\t; exited Voicemail\n\nexten => 1235,1,Voicemail(1234,u)\t\t; Right to voicemail\n\nexten => 1236,1,Dial(Console/dsp)\t\t; Ring forever\nexten => 1236,n,Voicemail(1234,b)\t\t; Unless busy\n\n;\n; # for when they're done with the demo\n;\nexten => #,1,Playback(demo-thanks)\t; \"Thanks for trying the demo\"\nexten => #,n,Hangup\t\t\t; Hang them up.\n\n;\n; A timeout and \"invalid extension rule\"\n;\nexten => t,1,Goto(#,1)\t\t\t; If they take too long, give up\nexten => i,1,Playback(invalid)\t\t; \"That's not valid, try again\"\n\n;\n; Create an extension, 500, for dialing the\n; Asterisk demo.\n;\nexten => 500,1,Playback(demo-abouttotry); Let them know what's going on\nexten => 500,n,Dial(IAX2/guest@pbx.digium.com/s@default)\t; Call the Asterisk demo\nexten => 500,n,Playback(demo-nogo)\t; Couldn't connect to the demo site\nexten => 500,n,Goto(s,6)\t\t; Return to the start over message.\n\n;\n; Create an extension, 600, for evaluating echo latency.\n;\nexten => 600,1,Playback(demo-echotest)\t; Let them know what's going on\nexten => 600,n,Echo\t\t\t; Do the echo test\nexten => 600,n,Playback(demo-echodone)\t; Let them know it's over\nexten => 600,n,Goto(s,6)\t\t; Start over\n\n;\n;\tYou can use the Macro Page to intercom a individual user\nexten => 76245,1,Macro(page,SIP/Grandstream1)\n; or if your peernames are the same as extensions\nexten => _7XXX,1,Macro(page,SIP/${EXTEN})\n;\n;\n; System Wide Page at extension 7999\n;\nexten => 7999,1,Set(TIMEOUT(absolute)=60)\nexten => 7999,2,Page(Local/Grandstream1@page&Local/Xlite1@page&Local/1234@page/n,d)\n\n; Give voicemail at extension 8500\n;\nexten => 8500,1,VoicemailMain\nexten => 8500,n,Goto(s,6)\n\n    </textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"text/x-asterisk\",\n        matchBrackets: true,\n        lineNumbers: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-asterisk</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/brainfuck/brainfuck.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Brainfuck mode created by Michael Kaminsky https://github.com/mkaminsky11\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\")\n    mod(require(\"../../lib/codemirror\"))\n  else if (typeof define == \"function\" && define.amd)\n    define([\"../../lib/codemirror\"], mod)\n  else\n    mod(CodeMirror)\n})(function(CodeMirror) {\n  \"use strict\"\n  var reserve = \"><+-.,[]\".split(\"\");\n  /*\n  comments can be either:\n  placed behind lines\n\n        +++    this is a comment\n\n  where reserved characters cannot be used\n  or in a loop\n  [\n    this is ok to use [ ] and stuff\n  ]\n  or preceded by #\n  */\n  CodeMirror.defineMode(\"brainfuck\", function() {\n    return {\n      startState: function() {\n        return {\n          commentLine: false,\n          left: 0,\n          right: 0,\n          commentLoop: false\n        }\n      },\n      token: function(stream, state) {\n        if (stream.eatSpace()) return null\n        if(stream.sol()){\n          state.commentLine = false;\n        }\n        var ch = stream.next().toString();\n        if(reserve.indexOf(ch) !== -1){\n          if(state.commentLine === true){\n            if(stream.eol()){\n              state.commentLine = false;\n            }\n            return \"comment\";\n          }\n          if(ch === \"]\" || ch === \"[\"){\n            if(ch === \"[\"){\n              state.left++;\n            }\n            else{\n              state.right++;\n            }\n            return \"bracket\";\n          }\n          else if(ch === \"+\" || ch === \"-\"){\n            return \"keyword\";\n          }\n          else if(ch === \"<\" || ch === \">\"){\n            return \"atom\";\n          }\n          else if(ch === \".\" || ch === \",\"){\n            return \"def\";\n          }\n        }\n        else{\n          state.commentLine = true;\n          if(stream.eol()){\n            state.commentLine = false;\n          }\n          return \"comment\";\n        }\n        if(stream.eol()){\n          state.commentLine = false;\n        }\n      }\n    };\n  });\nCodeMirror.defineMIME(\"text/x-brainfuck\",\"brainfuck\")\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/brainfuck/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Brainfuck mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"./brainfuck.js\"></script>\n<style>\n\t.CodeMirror { border: 2px inset #dee; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\"></a>\n  </ul>\n</div>\n\n<article>\n<h2>Brainfuck mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n[ This program prints \"Hello World!\" and a newline to the screen, its\n  length is 106 active command characters [it is not the shortest.]\n\n  This loop is a \"comment loop\", it's a simple way of adding a comment\n  to a BF program such that you don't have to worry about any command\n  characters. Any \".\", \",\", \"+\", \"-\", \"&lt;\" and \"&gt;\" characters are simply\n  ignored, the \"[\" and \"]\" characters just have to be balanced.\n]\n+++++ +++               Set Cell #0 to 8\n[\n    &gt;++++               Add 4 to Cell #1; this will always set Cell #1 to 4\n    [                   as the cell will be cleared by the loop\n        &gt;++             Add 2 to Cell #2\n        &gt;+++            Add 3 to Cell #3\n        &gt;+++            Add 3 to Cell #4\n        &gt;+              Add 1 to Cell #5\n        &lt;&lt;&lt;&lt;-           Decrement the loop counter in Cell #1\n    ]                   Loop till Cell #1 is zero; number of iterations is 4\n    &gt;+                  Add 1 to Cell #2\n    &gt;+                  Add 1 to Cell #3\n    &gt;-                  Subtract 1 from Cell #4\n    &gt;&gt;+                 Add 1 to Cell #6\n    [&lt;]                 Move back to the first zero cell you find; this will\n                        be Cell #1 which was cleared by the previous loop\n    &lt;-                  Decrement the loop Counter in Cell #0\n]                       Loop till Cell #0 is zero; number of iterations is 8\n\nThe result of this is:\nCell No :   0   1   2   3   4   5   6\nContents:   0   0  72 104  88  32   8\nPointer :   ^\n\n&gt;&gt;.                     Cell #2 has value 72 which is 'H'\n&gt;---.                   Subtract 3 from Cell #3 to get 101 which is 'e'\n+++++++..+++.           Likewise for 'llo' from Cell #3\n&gt;&gt;.                     Cell #5 is 32 for the space\n&lt;-.                     Subtract 1 from Cell #4 for 87 to give a 'W'\n&lt;.                      Cell #3 was set to 'o' from the end of 'Hello'\n+++.------.--------.    Cell #3 for 'rl' and 'd'\n&gt;&gt;+.                    Add 1 to Cell #5 gives us an exclamation point\n&gt;++.                    And finally a newline from Cell #6\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-brainfuck\"\n      });\n    </script>\n\n    <p>A mode for Brainfuck</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-brainfuck</code></p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/clike/clike.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nfunction Context(indented, column, type, info, align, prev) {\n  this.indented = indented;\n  this.column = column;\n  this.type = type;\n  this.info = info;\n  this.align = align;\n  this.prev = prev;\n}\nfunction pushContext(state, col, type, info) {\n  var indent = state.indented;\n  if (state.context && state.context.type == \"statement\" && type != \"statement\")\n    indent = state.context.indented;\n  return state.context = new Context(indent, col, type, info, null, state.context);\n}\nfunction popContext(state) {\n  var t = state.context.type;\n  if (t == \")\" || t == \"]\" || t == \"}\")\n    state.indented = state.context.indented;\n  return state.context = state.context.prev;\n}\n\nfunction typeBefore(stream, state, pos) {\n  if (state.prevToken == \"variable\" || state.prevToken == \"type\") return true;\n  if (/\\S(?:[^- ]>|[*\\]])\\s*$|\\*$/.test(stream.string.slice(0, pos))) return true;\n  if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true;\n}\n\nfunction isTopScope(context) {\n  for (;;) {\n    if (!context || context.type == \"top\") return true;\n    if (context.type == \"}\" && context.prev.info != \"namespace\") return false;\n    context = context.prev;\n  }\n}\n\nCodeMirror.defineMode(\"clike\", function(config, parserConfig) {\n  var indentUnit = config.indentUnit,\n      statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,\n      dontAlignCalls = parserConfig.dontAlignCalls,\n      keywords = parserConfig.keywords || {},\n      types = parserConfig.types || {},\n      builtin = parserConfig.builtin || {},\n      blockKeywords = parserConfig.blockKeywords || {},\n      defKeywords = parserConfig.defKeywords || {},\n      atoms = parserConfig.atoms || {},\n      hooks = parserConfig.hooks || {},\n      multiLineStrings = parserConfig.multiLineStrings,\n      indentStatements = parserConfig.indentStatements !== false,\n      indentSwitch = parserConfig.indentSwitch !== false,\n      namespaceSeparator = parserConfig.namespaceSeparator,\n      isPunctuationChar = parserConfig.isPunctuationChar || /[\\[\\]{}\\(\\),;\\:\\.]/,\n      numberStart = parserConfig.numberStart || /[\\d\\.]/,\n      number = parserConfig.number || /^(?:0x[a-f\\d]+|0b[01]+|(?:\\d+\\.?\\d*|\\.\\d+)(?:e[-+]?\\d+)?)(u|ll?|l|f)?/i,\n      isOperatorChar = parserConfig.isOperatorChar || /[+\\-*&%=<>!?|\\/]/,\n      isIdentifierChar = parserConfig.isIdentifierChar || /[\\w\\$_\\xa1-\\uffff]/,\n      // An optional function that takes a {string} token and returns true if it\n      // should be treated as a builtin.\n      isReservedIdentifier = parserConfig.isReservedIdentifier || false;\n\n  var curPunc, isDefKeyword;\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (hooks[ch]) {\n      var result = hooks[ch](stream, state);\n      if (result !== false) return result;\n    }\n    if (ch == '\"' || ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n    if (isPunctuationChar.test(ch)) {\n      curPunc = ch;\n      return null;\n    }\n    if (numberStart.test(ch)) {\n      stream.backUp(1)\n      if (stream.match(number)) return \"number\"\n      stream.next()\n    }\n    if (ch == \"/\") {\n      if (stream.eat(\"*\")) {\n        state.tokenize = tokenComment;\n        return tokenComment(stream, state);\n      }\n      if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n    }\n    if (isOperatorChar.test(ch)) {\n      while (!stream.match(/^\\/[\\/*]/, false) && stream.eat(isOperatorChar)) {}\n      return \"operator\";\n    }\n    stream.eatWhile(isIdentifierChar);\n    if (namespaceSeparator) while (stream.match(namespaceSeparator))\n      stream.eatWhile(isIdentifierChar);\n\n    var cur = stream.current();\n    if (contains(keywords, cur)) {\n      if (contains(blockKeywords, cur)) curPunc = \"newstatement\";\n      if (contains(defKeywords, cur)) isDefKeyword = true;\n      return \"keyword\";\n    }\n    if (contains(types, cur)) return \"type\";\n    if (contains(builtin, cur)\n        || (isReservedIdentifier && isReservedIdentifier(cur))) {\n      if (contains(blockKeywords, cur)) curPunc = \"newstatement\";\n      return \"builtin\";\n    }\n    if (contains(atoms, cur)) return \"atom\";\n    return \"variable\";\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {end = true; break;}\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end || !(escaped || multiLineStrings))\n        state.tokenize = null;\n      return \"string\";\n    };\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = null;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function maybeEOL(stream, state) {\n    if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context))\n      state.typeAtEndOfLine = typeBefore(stream, state, stream.pos)\n  }\n\n  // Interface\n\n  return {\n    startState: function(basecolumn) {\n      return {\n        tokenize: null,\n        context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", null, false),\n        indented: 0,\n        startOfLine: true,\n        prevToken: null\n      };\n    },\n\n    token: function(stream, state) {\n      var ctx = state.context;\n      if (stream.sol()) {\n        if (ctx.align == null) ctx.align = false;\n        state.indented = stream.indentation();\n        state.startOfLine = true;\n      }\n      if (stream.eatSpace()) { maybeEOL(stream, state); return null; }\n      curPunc = isDefKeyword = null;\n      var style = (state.tokenize || tokenBase)(stream, state);\n      if (style == \"comment\" || style == \"meta\") return style;\n      if (ctx.align == null) ctx.align = true;\n\n      if (curPunc == \";\" || curPunc == \":\" || (curPunc == \",\" && stream.match(/^\\s*(?:\\/\\/.*)?$/, false)))\n        while (state.context.type == \"statement\") popContext(state);\n      else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n      else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n      else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n      else if (curPunc == \"}\") {\n        while (ctx.type == \"statement\") ctx = popContext(state);\n        if (ctx.type == \"}\") ctx = popContext(state);\n        while (ctx.type == \"statement\") ctx = popContext(state);\n      }\n      else if (curPunc == ctx.type) popContext(state);\n      else if (indentStatements &&\n               (((ctx.type == \"}\" || ctx.type == \"top\") && curPunc != \";\") ||\n                (ctx.type == \"statement\" && curPunc == \"newstatement\"))) {\n        pushContext(state, stream.column(), \"statement\", stream.current());\n      }\n\n      if (style == \"variable\" &&\n          ((state.prevToken == \"def\" ||\n            (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) &&\n             isTopScope(state.context) && stream.match(/^\\s*\\(/, false)))))\n        style = \"def\";\n\n      if (hooks.token) {\n        var result = hooks.token(stream, state, style);\n        if (result !== undefined) style = result;\n      }\n\n      if (style == \"def\" && parserConfig.styleDefs === false) style = \"variable\";\n\n      state.startOfLine = false;\n      state.prevToken = isDefKeyword ? \"def\" : style || curPunc;\n      maybeEOL(stream, state);\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass;\n      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);\n      var closing = firstChar == ctx.type;\n      if (ctx.type == \"statement\" && firstChar == \"}\") ctx = ctx.prev;\n      if (parserConfig.dontIndentStatements)\n        while (ctx.type == \"statement\" && parserConfig.dontIndentStatements.test(ctx.info))\n          ctx = ctx.prev\n      if (hooks.indent) {\n        var hook = hooks.indent(state, ctx, textAfter, indentUnit);\n        if (typeof hook == \"number\") return hook\n      }\n      var switchBlock = ctx.prev && ctx.prev.info == \"switch\";\n      if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) {\n        while (ctx.type != \"top\" && ctx.type != \"}\") ctx = ctx.prev\n        return ctx.indented\n      }\n      if (ctx.type == \"statement\")\n        return ctx.indented + (firstChar == \"{\" ? 0 : statementIndentUnit);\n      if (ctx.align && (!dontAlignCalls || ctx.type != \")\"))\n        return ctx.column + (closing ? 0 : 1);\n      if (ctx.type == \")\" && !closing)\n        return ctx.indented + statementIndentUnit;\n\n      return ctx.indented + (closing ? 0 : indentUnit) +\n        (!closing && switchBlock && !/^(?:case|default)\\b/.test(textAfter) ? indentUnit : 0);\n    },\n\n    electricInput: indentSwitch ? /^\\s*(?:case .*?:|default:|\\{\\}?|\\})$/ : /^\\s*[{}]$/,\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    blockCommentContinue: \" * \",\n    lineComment: \"//\",\n    fold: \"brace\"\n  };\n});\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n  function contains(words, word) {\n    if (typeof words === \"function\") {\n      return words(word);\n    } else {\n      return words.propertyIsEnumerable(word);\n    }\n  }\n  var cKeywords = \"auto if break case register continue return default do sizeof \" +\n    \"static else struct switch extern typedef union for goto while enum const \" +\n    \"volatile inline restrict asm fortran\";\n\n  // Do not use this. Use the cTypes function below. This is global just to avoid\n  // excessive calls when cTypes is being called multiple times during a parse.\n  var basicCTypes = words(\"int long char short double float unsigned signed \" +\n    \"void bool\");\n\n  // Do not use this. Use the objCTypes function below. This is global just to avoid\n  // excessive calls when objCTypes is being called multiple times during a parse.\n  var basicObjCTypes = words(\"SEL instancetype id Class Protocol BOOL\");\n\n  // Returns true if identifier is a \"C\" type.\n  // C type is defined as those that are reserved by the compiler (basicTypes),\n  // and those that end in _t (Reserved by POSIX for types)\n  // http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html\n  function cTypes(identifier) {\n    return contains(basicCTypes, identifier) || /.+_t/.test(identifier);\n  }\n\n  // Returns true if identifier is a \"Objective C\" type.\n  function objCTypes(identifier) {\n    return cTypes(identifier) || contains(basicObjCTypes, identifier);\n  }\n\n  var cBlockKeywords = \"case do else for if switch while struct enum union\";\n  var cDefKeywords = \"struct enum union\";\n\n  function cppHook(stream, state) {\n    if (!state.startOfLine) return false\n    for (var ch, next = null; ch = stream.peek();) {\n      if (ch == \"\\\\\" && stream.match(/^.$/)) {\n        next = cppHook\n        break\n      } else if (ch == \"/\" && stream.match(/^\\/[\\/\\*]/, false)) {\n        break\n      }\n      stream.next()\n    }\n    state.tokenize = next\n    return \"meta\"\n  }\n\n  function pointerHook(_stream, state) {\n    if (state.prevToken == \"type\") return \"type\";\n    return false;\n  }\n\n  // For C and C++ (and ObjC): identifiers starting with __\n  // or _ followed by a capital letter are reserved for the compiler.\n  function cIsReservedIdentifier(token) {\n    if (!token || token.length < 2) return false;\n    if (token[0] != '_') return false;\n    return (token[1] == '_') || (token[1] !== token[1].toLowerCase());\n  }\n\n  function cpp14Literal(stream) {\n    stream.eatWhile(/[\\w\\.']/);\n    return \"number\";\n  }\n\n  function cpp11StringHook(stream, state) {\n    stream.backUp(1);\n    // Raw strings.\n    if (stream.match(/(R|u8R|uR|UR|LR)/)) {\n      var match = stream.match(/\"([^\\s\\\\()]{0,16})\\(/);\n      if (!match) {\n        return false;\n      }\n      state.cpp11RawStringDelim = match[1];\n      state.tokenize = tokenRawString;\n      return tokenRawString(stream, state);\n    }\n    // Unicode strings/chars.\n    if (stream.match(/(u8|u|U|L)/)) {\n      if (stream.match(/[\"']/, /* eat */ false)) {\n        return \"string\";\n      }\n      return false;\n    }\n    // Ignore this hook.\n    stream.next();\n    return false;\n  }\n\n  function cppLooksLikeConstructor(word) {\n    var lastTwo = /(\\w+)::~?(\\w+)$/.exec(word);\n    return lastTwo && lastTwo[1] == lastTwo[2];\n  }\n\n  // C#-style strings where \"\" escapes a quote.\n  function tokenAtString(stream, state) {\n    var next;\n    while ((next = stream.next()) != null) {\n      if (next == '\"' && !stream.eat('\"')) {\n        state.tokenize = null;\n        break;\n      }\n    }\n    return \"string\";\n  }\n\n  // C++11 raw string literal is <prefix>\"<delim>( anything )<delim>\", where\n  // <delim> can be a string up to 16 characters long.\n  function tokenRawString(stream, state) {\n    // Escape characters that have special regex meanings.\n    var delim = state.cpp11RawStringDelim.replace(/[^\\w\\s]/g, '\\\\$&');\n    var match = stream.match(new RegExp(\".*?\\\\)\" + delim + '\"'));\n    if (match)\n      state.tokenize = null;\n    else\n      stream.skipToEnd();\n    return \"string\";\n  }\n\n  function def(mimes, mode) {\n    if (typeof mimes == \"string\") mimes = [mimes];\n    var words = [];\n    function add(obj) {\n      if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))\n        words.push(prop);\n    }\n    add(mode.keywords);\n    add(mode.types);\n    add(mode.builtin);\n    add(mode.atoms);\n    if (words.length) {\n      mode.helperType = mimes[0];\n      CodeMirror.registerHelper(\"hintWords\", mimes[0], words);\n    }\n\n    for (var i = 0; i < mimes.length; ++i)\n      CodeMirror.defineMIME(mimes[i], mode);\n  }\n\n  def([\"text/x-csrc\", \"text/x-c\", \"text/x-chdr\"], {\n    name: \"clike\",\n    keywords: words(cKeywords),\n    types: cTypes,\n    blockKeywords: words(cBlockKeywords),\n    defKeywords: words(cDefKeywords),\n    typeFirstDefinitions: true,\n    atoms: words(\"NULL true false\"),\n    isReservedIdentifier: cIsReservedIdentifier,\n    hooks: {\n      \"#\": cppHook,\n      \"*\": pointerHook,\n    },\n    modeProps: {fold: [\"brace\", \"include\"]}\n  });\n\n  def([\"text/x-c++src\", \"text/x-c++hdr\"], {\n    name: \"clike\",\n    // Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20.\n    keywords: words(cKeywords + \"alignas alignof and and_eq audit axiom bitand bitor catch \" +\n                    \"class compl concept constexpr const_cast decltype delete dynamic_cast \" +\n                    \"explicit export final friend import module mutable namespace new noexcept \" +\n                    \"not not_eq operator or or_eq override private protected public \" +\n                    \"reinterpret_cast requires static_assert static_cast template this \" +\n                    \"thread_local throw try typeid typename using virtual xor xor_eq\"),\n    types: cTypes,\n    blockKeywords: words(cBlockKeywords + \" class try catch\"),\n    defKeywords: words(cDefKeywords + \" class namespace\"),\n    typeFirstDefinitions: true,\n    atoms: words(\"true false NULL nullptr\"),\n    dontIndentStatements: /^template$/,\n    isIdentifierChar: /[\\w\\$_~\\xa1-\\uffff]/,\n    isReservedIdentifier: cIsReservedIdentifier,\n    hooks: {\n      \"#\": cppHook,\n      \"*\": pointerHook,\n      \"u\": cpp11StringHook,\n      \"U\": cpp11StringHook,\n      \"L\": cpp11StringHook,\n      \"R\": cpp11StringHook,\n      \"0\": cpp14Literal,\n      \"1\": cpp14Literal,\n      \"2\": cpp14Literal,\n      \"3\": cpp14Literal,\n      \"4\": cpp14Literal,\n      \"5\": cpp14Literal,\n      \"6\": cpp14Literal,\n      \"7\": cpp14Literal,\n      \"8\": cpp14Literal,\n      \"9\": cpp14Literal,\n      token: function(stream, state, style) {\n        if (style == \"variable\" && stream.peek() == \"(\" &&\n            (state.prevToken == \";\" || state.prevToken == null ||\n             state.prevToken == \"}\") &&\n            cppLooksLikeConstructor(stream.current()))\n          return \"def\";\n      }\n    },\n    namespaceSeparator: \"::\",\n    modeProps: {fold: [\"brace\", \"include\"]}\n  });\n\n  def(\"text/x-java\", {\n    name: \"clike\",\n    keywords: words(\"abstract assert break case catch class const continue default \" +\n                    \"do else enum extends final finally float for goto if implements import \" +\n                    \"instanceof interface native new package private protected public \" +\n                    \"return static strictfp super switch synchronized this throw throws transient \" +\n                    \"try volatile while @interface\"),\n    types: words(\"byte short int long float double boolean char void Boolean Byte Character Double Float \" +\n                 \"Integer Long Number Object Short String StringBuffer StringBuilder Void\"),\n    blockKeywords: words(\"catch class do else finally for if switch try while\"),\n    defKeywords: words(\"class interface enum @interface\"),\n    typeFirstDefinitions: true,\n    atoms: words(\"true false null\"),\n    number: /^(?:0x[a-f\\d_]+|0b[01_]+|(?:[\\d_]+\\.?\\d*|\\.\\d+)(?:e[-+]?[\\d_]+)?)(u|ll?|l|f)?/i,\n    hooks: {\n      \"@\": function(stream) {\n        // Don't match the @interface keyword.\n        if (stream.match('interface', false)) return false;\n\n        stream.eatWhile(/[\\w\\$_]/);\n        return \"meta\";\n      }\n    },\n    modeProps: {fold: [\"brace\", \"import\"]}\n  });\n\n  def(\"text/x-csharp\", {\n    name: \"clike\",\n    keywords: words(\"abstract as async await base break case catch checked class const continue\" +\n                    \" default delegate do else enum event explicit extern finally fixed for\" +\n                    \" foreach goto if implicit in interface internal is lock namespace new\" +\n                    \" operator out override params private protected public readonly ref return sealed\" +\n                    \" sizeof stackalloc static struct switch this throw try typeof unchecked\" +\n                    \" unsafe using virtual void volatile while add alias ascending descending dynamic from get\" +\n                    \" global group into join let orderby partial remove select set value var yield\"),\n    types: words(\"Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func\" +\n                 \" Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32\" +\n                 \" UInt64 bool byte char decimal double short int long object\"  +\n                 \" sbyte float string ushort uint ulong\"),\n    blockKeywords: words(\"catch class do else finally for foreach if struct switch try while\"),\n    defKeywords: words(\"class interface namespace struct var\"),\n    typeFirstDefinitions: true,\n    atoms: words(\"true false null\"),\n    hooks: {\n      \"@\": function(stream, state) {\n        if (stream.eat('\"')) {\n          state.tokenize = tokenAtString;\n          return tokenAtString(stream, state);\n        }\n        stream.eatWhile(/[\\w\\$_]/);\n        return \"meta\";\n      }\n    }\n  });\n\n  function tokenTripleString(stream, state) {\n    var escaped = false;\n    while (!stream.eol()) {\n      if (!escaped && stream.match('\"\"\"')) {\n        state.tokenize = null;\n        break;\n      }\n      escaped = stream.next() == \"\\\\\" && !escaped;\n    }\n    return \"string\";\n  }\n\n  function tokenNestedComment(depth) {\n    return function (stream, state) {\n      var ch\n      while (ch = stream.next()) {\n        if (ch == \"*\" && stream.eat(\"/\")) {\n          if (depth == 1) {\n            state.tokenize = null\n            break\n          } else {\n            state.tokenize = tokenNestedComment(depth - 1)\n            return state.tokenize(stream, state)\n          }\n        } else if (ch == \"/\" && stream.eat(\"*\")) {\n          state.tokenize = tokenNestedComment(depth + 1)\n          return state.tokenize(stream, state)\n        }\n      }\n      return \"comment\"\n    }\n  }\n\n  def(\"text/x-scala\", {\n    name: \"clike\",\n    keywords: words(\n      /* scala */\n      \"abstract case catch class def do else extends final finally for forSome if \" +\n      \"implicit import lazy match new null object override package private protected return \" +\n      \"sealed super this throw trait try type val var while with yield _ \" +\n\n      /* package scala */\n      \"assert assume require print println printf readLine readBoolean readByte readShort \" +\n      \"readChar readInt readLong readFloat readDouble\"\n    ),\n    types: words(\n      \"AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either \" +\n      \"Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable \" +\n      \"Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering \" +\n      \"Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder \" +\n      \"StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector \" +\n\n      /* package java.lang */\n      \"Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable \" +\n      \"Compiler Double Exception Float Integer Long Math Number Object Package Pair Process \" +\n      \"Runtime Runnable SecurityManager Short StackTraceElement StrictMath String \" +\n      \"StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void\"\n    ),\n    multiLineStrings: true,\n    blockKeywords: words(\"catch class enum do else finally for forSome if match switch try while\"),\n    defKeywords: words(\"class enum def object package trait type val var\"),\n    atoms: words(\"true false null\"),\n    indentStatements: false,\n    indentSwitch: false,\n    isOperatorChar: /[+\\-*&%=<>!?|\\/#:@]/,\n    hooks: {\n      \"@\": function(stream) {\n        stream.eatWhile(/[\\w\\$_]/);\n        return \"meta\";\n      },\n      '\"': function(stream, state) {\n        if (!stream.match('\"\"')) return false;\n        state.tokenize = tokenTripleString;\n        return state.tokenize(stream, state);\n      },\n      \"'\": function(stream) {\n        stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n        return \"atom\";\n      },\n      \"=\": function(stream, state) {\n        var cx = state.context\n        if (cx.type == \"}\" && cx.align && stream.eat(\">\")) {\n          state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev)\n          return \"operator\"\n        } else {\n          return false\n        }\n      },\n\n      \"/\": function(stream, state) {\n        if (!stream.eat(\"*\")) return false\n        state.tokenize = tokenNestedComment(1)\n        return state.tokenize(stream, state)\n      }\n    },\n    modeProps: {closeBrackets: {pairs: '()[]{}\"\"', triples: '\"'}}\n  });\n\n  function tokenKotlinString(tripleString){\n    return function (stream, state) {\n      var escaped = false, next, end = false;\n      while (!stream.eol()) {\n        if (!tripleString && !escaped && stream.match('\"') ) {end = true; break;}\n        if (tripleString && stream.match('\"\"\"')) {end = true; break;}\n        next = stream.next();\n        if(!escaped && next == \"$\" && stream.match('{'))\n          stream.skipTo(\"}\");\n        escaped = !escaped && next == \"\\\\\" && !tripleString;\n      }\n      if (end || !tripleString)\n        state.tokenize = null;\n      return \"string\";\n    }\n  }\n\n  def(\"text/x-kotlin\", {\n    name: \"clike\",\n    keywords: words(\n      /*keywords*/\n      \"package as typealias class interface this super val operator \" +\n      \"var fun for is in This throw return annotation \" +\n      \"break continue object if else while do try when !in !is as? \" +\n\n      /*soft keywords*/\n      \"file import where by get set abstract enum open inner override private public internal \" +\n      \"protected catch finally out final vararg reified dynamic companion constructor init \" +\n      \"sealed field property receiver param sparam lateinit data inline noinline tailrec \" +\n      \"external annotation crossinline const operator infix suspend actual expect setparam\"\n    ),\n    types: words(\n      /* package java.lang */\n      \"Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable \" +\n      \"Compiler Double Exception Float Integer Long Math Number Object Package Pair Process \" +\n      \"Runtime Runnable SecurityManager Short StackTraceElement StrictMath String \" +\n      \"StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray \" +\n      \"ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy \" +\n      \"LazyThreadSafetyMode LongArray Nothing ShortArray Unit\"\n    ),\n    intendSwitch: false,\n    indentStatements: false,\n    multiLineStrings: true,\n    number: /^(?:0x[a-f\\d_]+|0b[01_]+|(?:[\\d_]+(\\.\\d+)?|\\.\\d+)(?:e[-+]?[\\d_]+)?)(u|ll?|l|f)?/i,\n    blockKeywords: words(\"catch class do else finally for if where try while enum\"),\n    defKeywords: words(\"class val var object interface fun\"),\n    atoms: words(\"true false null this\"),\n    hooks: {\n      \"@\": function(stream) {\n        stream.eatWhile(/[\\w\\$_]/);\n        return \"meta\";\n      },\n      '*': function(_stream, state) {\n        return state.prevToken == '.' ? 'variable' : 'operator';\n      },\n      '\"': function(stream, state) {\n        state.tokenize = tokenKotlinString(stream.match('\"\"'));\n        return state.tokenize(stream, state);\n      },\n      indent: function(state, ctx, textAfter, indentUnit) {\n        var firstChar = textAfter && textAfter.charAt(0);\n        if ((state.prevToken == \"}\" || state.prevToken == \")\") && textAfter == \"\")\n          return state.indented;\n        if (state.prevToken == \"operator\" && textAfter != \"}\" ||\n          state.prevToken == \"variable\" && firstChar == \".\" ||\n          (state.prevToken == \"}\" || state.prevToken == \")\") && firstChar == \".\")\n          return indentUnit * 2 + ctx.indented;\n        if (ctx.align && ctx.type == \"}\")\n          return ctx.indented + (state.context.type == (textAfter || \"\").charAt(0) ? 0 : indentUnit);\n      }\n    },\n    modeProps: {closeBrackets: {triples: '\"'}}\n  });\n\n  def([\"x-shader/x-vertex\", \"x-shader/x-fragment\"], {\n    name: \"clike\",\n    keywords: words(\"sampler1D sampler2D sampler3D samplerCube \" +\n                    \"sampler1DShadow sampler2DShadow \" +\n                    \"const attribute uniform varying \" +\n                    \"break continue discard return \" +\n                    \"for while do if else struct \" +\n                    \"in out inout\"),\n    types: words(\"float int bool void \" +\n                 \"vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 \" +\n                 \"mat2 mat3 mat4\"),\n    blockKeywords: words(\"for while do if else struct\"),\n    builtin: words(\"radians degrees sin cos tan asin acos atan \" +\n                    \"pow exp log exp2 sqrt inversesqrt \" +\n                    \"abs sign floor ceil fract mod min max clamp mix step smoothstep \" +\n                    \"length distance dot cross normalize ftransform faceforward \" +\n                    \"reflect refract matrixCompMult \" +\n                    \"lessThan lessThanEqual greaterThan greaterThanEqual \" +\n                    \"equal notEqual any all not \" +\n                    \"texture1D texture1DProj texture1DLod texture1DProjLod \" +\n                    \"texture2D texture2DProj texture2DLod texture2DProjLod \" +\n                    \"texture3D texture3DProj texture3DLod texture3DProjLod \" +\n                    \"textureCube textureCubeLod \" +\n                    \"shadow1D shadow2D shadow1DProj shadow2DProj \" +\n                    \"shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod \" +\n                    \"dFdx dFdy fwidth \" +\n                    \"noise1 noise2 noise3 noise4\"),\n    atoms: words(\"true false \" +\n                \"gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex \" +\n                \"gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 \" +\n                \"gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 \" +\n                \"gl_FogCoord gl_PointCoord \" +\n                \"gl_Position gl_PointSize gl_ClipVertex \" +\n                \"gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor \" +\n                \"gl_TexCoord gl_FogFragCoord \" +\n                \"gl_FragCoord gl_FrontFacing \" +\n                \"gl_FragData gl_FragDepth \" +\n                \"gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix \" +\n                \"gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse \" +\n                \"gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse \" +\n                \"gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose \" +\n                \"gl_ProjectionMatrixInverseTranspose \" +\n                \"gl_ModelViewProjectionMatrixInverseTranspose \" +\n                \"gl_TextureMatrixInverseTranspose \" +\n                \"gl_NormalScale gl_DepthRange gl_ClipPlane \" +\n                \"gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel \" +\n                \"gl_FrontLightModelProduct gl_BackLightModelProduct \" +\n                \"gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ \" +\n                \"gl_FogParameters \" +\n                \"gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords \" +\n                \"gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats \" +\n                \"gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits \" +\n                \"gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits \" +\n                \"gl_MaxDrawBuffers\"),\n    indentSwitch: false,\n    hooks: {\"#\": cppHook},\n    modeProps: {fold: [\"brace\", \"include\"]}\n  });\n\n  def(\"text/x-nesc\", {\n    name: \"clike\",\n    keywords: words(cKeywords + \" as atomic async call command component components configuration event generic \" +\n                    \"implementation includes interface module new norace nx_struct nx_union post provides \" +\n                    \"signal task uses abstract extends\"),\n    types: cTypes,\n    blockKeywords: words(cBlockKeywords),\n    atoms: words(\"null true false\"),\n    hooks: {\"#\": cppHook},\n    modeProps: {fold: [\"brace\", \"include\"]}\n  });\n\n  def(\"text/x-objectivec\", {\n    name: \"clike\",\n    keywords: words(cKeywords + \" bycopy byref in inout oneway out self super atomic nonatomic retain copy \" +\n                    \"readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd \" +\n                    \"@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class \" +\n                    \"@public @package @private @protected @required @optional @try @catch @finally @import \" +\n                    \"@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available\"),\n    types: objCTypes,\n    builtin: words(\"FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION NS_RETURNS_RETAINED \" +\n                   \"NS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER NS_DESIGNATED_INITIALIZER \" +\n                   \"NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION NS_ASSUME_NONNULL_BEGIN \" +\n                   \"NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT\"),\n    blockKeywords: words(cBlockKeywords + \" @synthesize @try @catch @finally @autoreleasepool @synchronized\"),\n    defKeywords: words(cDefKeywords + \" @interface @implementation @protocol @class\"),\n    dontIndentStatements: /^@.*$/,\n    typeFirstDefinitions: true,\n    atoms: words(\"YES NO NULL Nil nil true false nullptr\"),\n    isReservedIdentifier: cIsReservedIdentifier,\n    hooks: {\n      \"#\": cppHook,\n      \"*\": pointerHook,\n    },\n    modeProps: {fold: [\"brace\", \"include\"]}\n  });\n\n  def(\"text/x-squirrel\", {\n    name: \"clike\",\n    keywords: words(\"base break clone continue const default delete enum extends function in class\" +\n                    \" foreach local resume return this throw typeof yield constructor instanceof static\"),\n    types: cTypes,\n    blockKeywords: words(\"case catch class else for foreach if switch try while\"),\n    defKeywords: words(\"function local class\"),\n    typeFirstDefinitions: true,\n    atoms: words(\"true false null\"),\n    hooks: {\"#\": cppHook},\n    modeProps: {fold: [\"brace\", \"include\"]}\n  });\n\n  // Ceylon Strings need to deal with interpolation\n  var stringTokenizer = null;\n  function tokenCeylonString(type) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while (!stream.eol()) {\n        if (!escaped && stream.match('\"') &&\n              (type == \"single\" || stream.match('\"\"'))) {\n          end = true;\n          break;\n        }\n        if (!escaped && stream.match('``')) {\n          stringTokenizer = tokenCeylonString(type);\n          end = true;\n          break;\n        }\n        next = stream.next();\n        escaped = type == \"single\" && !escaped && next == \"\\\\\";\n      }\n      if (end)\n          state.tokenize = null;\n      return \"string\";\n    }\n  }\n\n  def(\"text/x-ceylon\", {\n    name: \"clike\",\n    keywords: words(\"abstracts alias assembly assert assign break case catch class continue dynamic else\" +\n                    \" exists extends finally for function given if import in interface is let module new\" +\n                    \" nonempty object of out outer package return satisfies super switch then this throw\" +\n                    \" try value void while\"),\n    types: function(word) {\n        // In Ceylon all identifiers that start with an uppercase are types\n        var first = word.charAt(0);\n        return (first === first.toUpperCase() && first !== first.toLowerCase());\n    },\n    blockKeywords: words(\"case catch class dynamic else finally for function if interface module new object switch try while\"),\n    defKeywords: words(\"class dynamic function interface module object package value\"),\n    builtin: words(\"abstract actual aliased annotation by default deprecated doc final formal late license\" +\n                   \" native optional sealed see serializable shared suppressWarnings tagged throws variable\"),\n    isPunctuationChar: /[\\[\\]{}\\(\\),;\\:\\.`]/,\n    isOperatorChar: /[+\\-*&%=<>!?|^~:\\/]/,\n    numberStart: /[\\d#$]/,\n    number: /^(?:#[\\da-fA-F_]+|\\$[01_]+|[\\d_]+[kMGTPmunpf]?|[\\d_]+\\.[\\d_]+(?:[eE][-+]?\\d+|[kMGTPmunpf]|)|)/i,\n    multiLineStrings: true,\n    typeFirstDefinitions: true,\n    atoms: words(\"true false null larger smaller equal empty finished\"),\n    indentSwitch: false,\n    styleDefs: false,\n    hooks: {\n      \"@\": function(stream) {\n        stream.eatWhile(/[\\w\\$_]/);\n        return \"meta\";\n      },\n      '\"': function(stream, state) {\n          state.tokenize = tokenCeylonString(stream.match('\"\"') ? \"triple\" : \"single\");\n          return state.tokenize(stream, state);\n        },\n      '`': function(stream, state) {\n          if (!stringTokenizer || !stream.match('`')) return false;\n          state.tokenize = stringTokenizer;\n          stringTokenizer = null;\n          return state.tokenize(stream, state);\n        },\n      \"'\": function(stream) {\n        stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n        return \"atom\";\n      },\n      token: function(_stream, state, style) {\n          if ((style == \"variable\" || style == \"type\") &&\n              state.prevToken == \".\") {\n            return \"variable-2\";\n          }\n        }\n    },\n    modeProps: {\n        fold: [\"brace\", \"import\"],\n        closeBrackets: {triples: '\"'}\n    }\n  });\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/clike/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: C-like mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<link rel=\"stylesheet\" href=\"../../addon/hint/show-hint.css\">\n<script src=\"../../addon/hint/show-hint.js\"></script>\n<script src=\"clike.js\"></script>\n<style>.CodeMirror {border: 2px inset #dee;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">C-like</a>\n  </ul>\n</div>\n\n<article>\n<h2>C-like mode</h2>\n\n<div><textarea id=\"c-code\">\n/* C demo code */\n\n#include <zmq.h>\n#include <pthread.h>\n#include <semaphore.h>\n#include <time.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <malloc.h>\n\ntypedef struct {\n  void* arg_socket;\n  zmq_msg_t* arg_msg;\n  char* arg_string;\n  unsigned long arg_len;\n  int arg_int, arg_command;\n\n  int signal_fd;\n  int pad;\n  void* context;\n  sem_t sem;\n} acl_zmq_context;\n\n#define p(X) (context->arg_##X)\n\nvoid* zmq_thread(void* context_pointer) {\n  acl_zmq_context* context = (acl_zmq_context*)context_pointer;\n  char ok = 'K', err = 'X';\n  int res;\n\n  while (1) {\n    while ((res = sem_wait(&amp;context->sem)) == EINTR);\n    if (res) {write(context->signal_fd, &amp;err, 1); goto cleanup;}\n    switch(p(command)) {\n    case 0: goto cleanup;\n    case 1: p(socket) = zmq_socket(context->context, p(int)); break;\n    case 2: p(int) = zmq_close(p(socket)); break;\n    case 3: p(int) = zmq_bind(p(socket), p(string)); break;\n    case 4: p(int) = zmq_connect(p(socket), p(string)); break;\n    case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &amp;p(len)); break;\n    case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;\n    case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;\n    case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;\n    case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;\n    }\n    p(command) = errno;\n    write(context->signal_fd, &amp;ok, 1);\n  }\n cleanup:\n  close(context->signal_fd);\n  free(context_pointer);\n  return 0;\n}\n\nvoid* zmq_thread_init(void* zmq_context, int signal_fd) {\n  acl_zmq_context* context = malloc(sizeof(acl_zmq_context));\n  pthread_t thread;\n\n  context->context = zmq_context;\n  context->signal_fd = signal_fd;\n  sem_init(&amp;context->sem, 1, 0);\n  pthread_create(&amp;thread, 0, &amp;zmq_thread, context);\n  pthread_detach(thread);\n  return context;\n}\n</textarea></div>\n\n<h2>C++ example</h2>\n\n<div><textarea id=\"cpp-code\">\n#include <iostream>\n#include \"mystuff/util.h\"\n\nnamespace {\nenum Enum {\n  VAL1, VAL2, VAL3\n};\n\nchar32_t unicode_string = U\"\\U0010FFFF\";\nstring raw_string = R\"delim(anything\nyou\nwant)delim\";\n\nint Helper(const MyType& param) {\n  return 0;\n}\n} // namespace\n\nclass ForwardDec;\n\ntemplate <class T, class V>\nclass Class : public BaseClass {\n  const MyType<T, V> member_;\n\n public:\n  const MyType<T, V>& Method() const {\n    return member_;\n  }\n\n  void Method2(MyType<T, V>* value);\n}\n\ntemplate <class T, class V>\nvoid Class::Method2(MyType<T, V>* value) {\n  std::out << 1 >> method();\n  value->Method3(member_);\n  member_ = value;\n}\n</textarea></div>\n\n<h2>Objective-C example</h2>\n\n<div><textarea id=\"objectivec-code\">\n/*\nThis is a longer comment\nThat spans two lines\n*/\n\n#import \"MyClass.h\"\n#import <AFramework/AFrameork.h>\n@import BFrameworkModule;\n\nNS_ENUM(SomeValues) {\n  aValue = 1;\n};\n\n// A Class Extension with some properties\n@interface MyClass ()<AProtocol>\n@property(atomic, readwrite, assign) NSInteger anInt;\n@property(nonatomic, strong, nullable) NSString *aString;\n@end\n\n@implementation YourAppDelegate\n\n- (instancetype)initWithString:(NSString *)aStringVar {\n  if ((self = [super init])) {\n    aString = aStringVar;\n  }\n  return self;\n}\n\n- (BOOL)doSomething:(float)progress {\n  NSString *myString = @\"This is a ObjC string %f \";\n  myString = [[NSString stringWithFormat:myString, progress] stringByAppendingString:self.aString];\n  return myString.length > 100 ? NO : YES;\n}\n\n@end\n</textarea></div>\n\n<h2>Java example</h2>\n\n<div><textarea id=\"java-code\">\nimport com.demo.util.MyType;\nimport com.demo.util.MyInterface;\n\npublic enum Enum {\n  VAL1, VAL2, VAL3\n}\n\npublic class Class<T, V> implements MyInterface {\n  public static final MyType<T, V> member;\n  \n  private class InnerClass {\n    public int zero() {\n      return 0;\n    }\n  }\n\n  @Override\n  public MyType method() {\n    return member;\n  }\n\n  public void method2(MyType<T, V> value) {\n    method();\n    value.method3();\n    member = value;\n  }\n}\n</textarea></div>\n\n<h2>Scala example</h2>\n\n<div><textarea id=\"scala-code\">\nobject FilterTest extends App {\n  def filter(xs: List[Int], threshold: Int) = {\n    def process(ys: List[Int]): List[Int] =\n      if (ys.isEmpty) ys\n      else if (ys.head < threshold) ys.head :: process(ys.tail)\n      else process(ys.tail)\n    process(xs)\n  }\n  println(filter(List(1, 9, 2, 8, 3, 7, 4), 5))\n}\n</textarea></div>\n\n<h2>Kotlin mode</h2>\n\n<div><textarea id=\"kotlin-code\">\npackage org.wasabi.http\n\nimport java.util.concurrent.Executors\nimport java.net.InetSocketAddress\nimport org.wasabi.app.AppConfiguration\nimport io.netty.bootstrap.ServerBootstrap\nimport io.netty.channel.nio.NioEventLoopGroup\nimport io.netty.channel.socket.nio.NioServerSocketChannel\nimport org.wasabi.app.AppServer\n\npublic class HttpServer(private val appServer: AppServer) {\n\n    val bootstrap: ServerBootstrap\n    val primaryGroup: NioEventLoopGroup\n    val workerGroup:  NioEventLoopGroup\n\n    init {\n        // Define worker groups\n        primaryGroup = NioEventLoopGroup()\n        workerGroup = NioEventLoopGroup()\n\n        // Initialize bootstrap of server\n        bootstrap = ServerBootstrap()\n\n        bootstrap.group(primaryGroup, workerGroup)\n        bootstrap.channel(javaClass<NioServerSocketChannel>())\n        bootstrap.childHandler(NettyPipelineInitializer(appServer))\n    }\n\n    public fun start(wait: Boolean = true) {\n        val channel = bootstrap.bind(appServer.configuration.port)?.sync()?.channel()\n\n        if (wait) {\n            channel?.closeFuture()?.sync()\n        }\n    }\n\n    public fun stop() {\n        // Shutdown all event loops\n        primaryGroup.shutdownGracefully()\n        workerGroup.shutdownGracefully()\n\n        // Wait till all threads are terminated\n        primaryGroup.terminationFuture().sync()\n        workerGroup.terminationFuture().sync()\n    }\n}\n</textarea></div>\n\n<h2>Ceylon mode</h2>\n\n<div><textarea id=\"ceylon-code\">\n\"Produces the [[stream|Iterable]] that results from repeated\n application of the given [[function|next]] to the given\n [[first]] element of the stream, until the function first\n returns [[finished]]. If the given function never returns \n `finished`, the resulting stream is infinite.\n\n For example:\n\n     loop(0)(2.plus).takeWhile(10.largerThan)\n\n produces the stream `{ 0, 2, 4, 6, 8 }`.\"\ntagged(\"Streams\")\nshared {Element+} loop&lt;Element&gt;(\n        \"The first element of the resulting stream.\"\n        Element first)(\n        \"The function that produces the next element of the\n         stream, given the current element. The function may\n         return [[finished]] to indicate the end of the \n         stream.\"\n        Element|Finished next(Element element))\n    =&gt; let (start = first)\n    object satisfies {Element+} {\n        first =&gt; start;\n        empty =&gt; false;\n        function nextElement(Element element)\n                =&gt; next(element);\n        iterator()\n                =&gt; object satisfies Iterator&lt;Element&gt; {\n            variable Element|Finished current = start;\n            shared actual Element|Finished next() {\n                if (!is Finished result = current) {\n                    current = nextElement(result);\n                    return result;\n                }\n                else {\n                    return finished;\n                }\n            }\n        };\n    };\n</textarea></div>\n\n    <script>\n      var cEditor = CodeMirror.fromTextArea(document.getElementById(\"c-code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-csrc\"\n      });\n      var cppEditor = CodeMirror.fromTextArea(document.getElementById(\"cpp-code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-c++src\"\n      });\n      var javaEditor = CodeMirror.fromTextArea(document.getElementById(\"java-code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-java\"\n      });\n      var objectivecEditor = CodeMirror.fromTextArea(document.getElementById(\"objectivec-code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-objectivec\"\n      });\n      var scalaEditor = CodeMirror.fromTextArea(document.getElementById(\"scala-code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-scala\"\n      });\n      var kotlinEditor = CodeMirror.fromTextArea(document.getElementById(\"kotlin-code\"), {\n          lineNumbers: true,\n          matchBrackets: true,\n          mode: \"text/x-kotlin\"\n      });\n      var ceylonEditor = CodeMirror.fromTextArea(document.getElementById(\"ceylon-code\"), {\n          lineNumbers: true,\n          matchBrackets: true,\n          mode: \"text/x-ceylon\"\n      });\n      var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault;\n      CodeMirror.keyMap.default[(mac ? \"Cmd\" : \"Ctrl\") + \"-Space\"] = \"autocomplete\";\n    </script>\n\n    <p>Simple mode that tries to handle C-like languages as well as it\n    can. Takes two configuration parameters: <code>keywords</code>, an\n    object whose property names are the keywords in the language,\n    and <code>useCPP</code>, which determines whether C preprocessor\n    directives are recognized.</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-csrc</code>\n    (C), <code>text/x-c++src</code> (C++), <code>text/x-java</code>\n    (Java), <code>text/x-csharp</code> (C#),\n    <code>text/x-objectivec</code> (Objective-C),\n    <code>text/x-scala</code> (Scala), <code>text/x-vertex</code>\n    <code>x-shader/x-fragment</code> (shader programs),\n    <code>text/x-squirrel</code> (Squirrel) and\n    <code>text/x-ceylon</code> (Ceylon)</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/clike/scala.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Scala mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/ambiance.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"clike.js\"></script>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Scala</a>\n  </ul>\n</div>\n\n<article>\n<h2>Scala mode</h2>\n<form>\n<textarea id=\"code\" name=\"code\">\n\n  /*                     __                                               *\\\n  **     ________ ___   / /  ___     Scala API                            **\n  **    / __/ __// _ | / /  / _ |    (c) 2003-2011, LAMP/EPFL             **\n  **  __\\ \\/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **\n  ** /____/\\___/_/ |_/____/_/ | |                                         **\n  **                          |/                                          **\n  \\*                                                                      */\n\n  package scala.collection\n\n  import generic._\n  import mutable.{ Builder, ListBuffer }\n  import annotation.{tailrec, migration, bridge}\n  import annotation.unchecked.{ uncheckedVariance => uV }\n  import parallel.ParIterable\n\n  /** A template trait for traversable collections of type `Traversable[A]`.\n   *  \n   *  $traversableInfo\n   *  @define mutability\n   *  @define traversableInfo\n   *  This is a base trait of all kinds of $mutability Scala collections. It\n   *  implements the behavior common to all collections, in terms of a method\n   *  `foreach` with signature:\n   * {{{\n   *     def foreach[U](f: Elem => U): Unit\n   * }}}\n   *  Collection classes mixing in this trait provide a concrete \n   *  `foreach` method which traverses all the\n   *  elements contained in the collection, applying a given function to each.\n   *  They also need to provide a method `newBuilder`\n   *  which creates a builder for collections of the same kind.\n   *  \n   *  A traversable class might or might not have two properties: strictness\n   *  and orderedness. Neither is represented as a type.\n   *  \n   *  The instances of a strict collection class have all their elements\n   *  computed before they can be used as values. By contrast, instances of\n   *  a non-strict collection class may defer computation of some of their\n   *  elements until after the instance is available as a value.\n   *  A typical example of a non-strict collection class is a\n   *  <a href=\"../immutable/Stream.html\" target=\"ContentFrame\">\n   *  `scala.collection.immutable.Stream`</a>.\n   *  A more general class of examples are `TraversableViews`.\n   *  \n   *  If a collection is an instance of an ordered collection class, traversing\n   *  its elements with `foreach` will always visit elements in the\n   *  same order, even for different runs of the program. If the class is not\n   *  ordered, `foreach` can visit elements in different orders for\n   *  different runs (but it will keep the same order in the same run).'\n   * \n   *  A typical example of a collection class which is not ordered is a\n   *  `HashMap` of objects. The traversal order for hash maps will\n   *  depend on the hash codes of its elements, and these hash codes might\n   *  differ from one run to the next. By contrast, a `LinkedHashMap`\n   *  is ordered because it's `foreach` method visits elements in the\n   *  order they were inserted into the `HashMap`.\n   *\n   *  @author Martin Odersky\n   *  @version 2.8\n   *  @since   2.8\n   *  @tparam A    the element type of the collection\n   *  @tparam Repr the type of the actual collection containing the elements.\n   *\n   *  @define Coll Traversable\n   *  @define coll traversable collection\n   */\n  trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] \n                                      with FilterMonadic[A, Repr]\n                                      with TraversableOnce[A]\n                                      with GenTraversableLike[A, Repr]\n                                      with Parallelizable[A, ParIterable[A]]\n  {\n    self =>\n\n    import Traversable.breaks._\n\n    /** The type implementing this traversable */\n    protected type Self = Repr\n\n    /** The collection of type $coll underlying this `TraversableLike` object.\n     *  By default this is implemented as the `TraversableLike` object itself,\n     *  but this can be overridden.\n     */\n    def repr: Repr = this.asInstanceOf[Repr]\n\n    /** The underlying collection seen as an instance of `$Coll`.\n     *  By default this is implemented as the current collection object itself,\n     *  but this can be overridden.\n     */\n    protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]]\n\n    /** A conversion from collections of type `Repr` to `$Coll` objects.\n     *  By default this is implemented as just a cast, but this can be overridden.\n     */\n    protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]]\n\n    /** Creates a new builder for this collection type.\n     */\n    protected[this] def newBuilder: Builder[A, Repr]\n\n    protected[this] def parCombiner = ParIterable.newCombiner[A]\n\n    /** Applies a function `f` to all elements of this $coll.\n     *  \n     *    Note: this method underlies the implementation of most other bulk operations.\n     *    It's important to implement this method in an efficient way.\n     *  \n     *\n     *  @param  f   the function that is applied for its side-effect to every element.\n     *              The result of function `f` is discarded.\n     *              \n     *  @tparam  U  the type parameter describing the result of function `f`. \n     *              This result will always be ignored. Typically `U` is `Unit`,\n     *              but this is not necessary.\n     *\n     *  @usecase def foreach(f: A => Unit): Unit\n     */\n    def foreach[U](f: A => U): Unit\n\n    /** Tests whether this $coll is empty.\n     *\n     *  @return    `true` if the $coll contain no elements, `false` otherwise.\n     */\n    def isEmpty: Boolean = {\n      var result = true\n      breakable {\n        for (x <- this) {\n          result = false\n          break\n        }\n      }\n      result\n    }\n\n    /** Tests whether this $coll is known to have a finite size.\n     *  All strict collections are known to have finite size. For a non-strict collection\n     *  such as `Stream`, the predicate returns `true` if all elements have been computed.\n     *  It returns `false` if the stream is not yet evaluated to the end.\n     *\n     *  Note: many collection methods will not work on collections of infinite sizes. \n     *\n     *  @return  `true` if this collection is known to have finite size, `false` otherwise.\n     */\n    def hasDefiniteSize = true\n\n    def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n      val b = bf(repr)\n      if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size)\n      b ++= thisCollection\n      b ++= that.seq\n      b.result\n    }\n\n    @bridge\n    def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =\n      ++(that: GenTraversableOnce[B])(bf)\n\n    /** Concatenates this $coll with the elements of a traversable collection.\n     *  It differs from ++ in that the right operand determines the type of the\n     *  resulting collection rather than the left one.\n     * \n     *  @param that   the traversable to append.\n     *  @tparam B     the element type of the returned collection. \n     *  @tparam That  $thatinfo\n     *  @param bf     $bfinfo\n     *  @return       a new collection of type `That` which contains all elements\n     *                of this $coll followed by all elements of `that`.\n     * \n     *  @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B]\n     *  \n     *  @return       a new $coll which contains all elements of this $coll\n     *                followed by all elements of `that`.\n     */\n    def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n      val b = bf(repr)\n      if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)\n      b ++= that\n      b ++= thisCollection\n      b.result\n    }\n\n    /** This overload exists because: for the implementation of ++: we should reuse\n     *  that of ++ because many collections override it with more efficient versions.\n     *  Since TraversableOnce has no '++' method, we have to implement that directly,\n     *  but Traversable and down can use the overload.\n     */\n    def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =\n      (that ++ seq)(breakOut)\n\n    def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n      val b = bf(repr)\n      b.sizeHint(this) \n      for (x <- this) b += f(x)\n      b.result\n    }\n\n    def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n      val b = bf(repr)\n      for (x <- this) b ++= f(x).seq\n      b.result\n    }\n\n    /** Selects all elements of this $coll which satisfy a predicate.\n     *\n     *  @param p     the predicate used to test elements.\n     *  @return      a new $coll consisting of all elements of this $coll that satisfy the given\n     *               predicate `p`. The order of the elements is preserved.\n     */\n    def filter(p: A => Boolean): Repr = {\n      val b = newBuilder\n      for (x <- this) \n        if (p(x)) b += x\n      b.result\n    }\n\n    /** Selects all elements of this $coll which do not satisfy a predicate.\n     *\n     *  @param p     the predicate used to test elements.\n     *  @return      a new $coll consisting of all elements of this $coll that do not satisfy the given\n     *               predicate `p`. The order of the elements is preserved.\n     */\n    def filterNot(p: A => Boolean): Repr = filter(!p(_))\n\n    def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n      val b = bf(repr)\n      for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)\n      b.result\n    }\n\n    /** Builds a new collection by applying an option-valued function to all\n     *  elements of this $coll on which the function is defined.\n     *\n     *  @param f      the option-valued function which filters and maps the $coll.\n     *  @tparam B     the element type of the returned collection.\n     *  @tparam That  $thatinfo\n     *  @param bf     $bfinfo\n     *  @return       a new collection of type `That` resulting from applying the option-valued function\n     *                `f` to each element and collecting all defined results.\n     *                The order of the elements is preserved.\n     *\n     *  @usecase def filterMap[B](f: A => Option[B]): $Coll[B]\n     *  \n     *  @param pf     the partial function which filters and maps the $coll.\n     *  @return       a new $coll resulting from applying the given option-valued function\n     *                `f` to each element and collecting all defined results.\n     *                The order of the elements is preserved.\n    def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n      val b = bf(repr)\n      for (x <- this) \n        f(x) match {\n          case Some(y) => b += y\n          case _ =>\n        }\n      b.result\n    }\n     */\n\n    /** Partitions this $coll in two ${coll}s according to a predicate.\n     *\n     *  @param p the predicate on which to partition.\n     *  @return  a pair of ${coll}s: the first $coll consists of all elements that \n     *           satisfy the predicate `p` and the second $coll consists of all elements\n     *           that don't. The relative order of the elements in the resulting ${coll}s\n     *           is the same as in the original $coll.\n     */\n    def partition(p: A => Boolean): (Repr, Repr) = {\n      val l, r = newBuilder\n      for (x <- this) (if (p(x)) l else r) += x\n      (l.result, r.result)\n    }\n\n    def groupBy[K](f: A => K): immutable.Map[K, Repr] = {\n      val m = mutable.Map.empty[K, Builder[A, Repr]]\n      for (elem <- this) {\n        val key = f(elem)\n        val bldr = m.getOrElseUpdate(key, newBuilder)\n        bldr += elem\n      }\n      val b = immutable.Map.newBuilder[K, Repr]\n      for ((k, v) <- m)\n        b += ((k, v.result))\n\n      b.result\n    }\n\n    /** Tests whether a predicate holds for all elements of this $coll.\n     *\n     *  $mayNotTerminateInf\n     *\n     *  @param   p     the predicate used to test elements.\n     *  @return        `true` if the given predicate `p` holds for all elements\n     *                 of this $coll, otherwise `false`.\n     */\n    def forall(p: A => Boolean): Boolean = {\n      var result = true\n      breakable {\n        for (x <- this)\n          if (!p(x)) { result = false; break }\n      }\n      result\n    }\n\n    /** Tests whether a predicate holds for some of the elements of this $coll.\n     *\n     *  $mayNotTerminateInf\n     *\n     *  @param   p     the predicate used to test elements.\n     *  @return        `true` if the given predicate `p` holds for some of the\n     *                 elements of this $coll, otherwise `false`.\n     */\n    def exists(p: A => Boolean): Boolean = {\n      var result = false\n      breakable {\n        for (x <- this)\n          if (p(x)) { result = true; break }\n      }\n      result\n    }\n\n    /** Finds the first element of the $coll satisfying a predicate, if any.\n     * \n     *  $mayNotTerminateInf\n     *  $orderDependent\n     *\n     *  @param p    the predicate used to test elements.\n     *  @return     an option value containing the first element in the $coll\n     *              that satisfies `p`, or `None` if none exists.\n     */\n    def find(p: A => Boolean): Option[A] = {\n      var result: Option[A] = None\n      breakable {\n        for (x <- this)\n          if (p(x)) { result = Some(x); break }\n      }\n      result\n    }\n\n    def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op)\n\n    def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n      val b = bf(repr)\n      b.sizeHint(this, 1)\n      var acc = z\n      b += acc\n      for (x <- this) { acc = op(acc, x); b += acc }\n      b.result\n    }\n\n    @migration(2, 9,\n      \"This scanRight definition has changed in 2.9.\\n\" +\n      \"The previous behavior can be reproduced with scanRight.reverse.\"\n    )\n    def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n      var scanned = List(z)\n      var acc = z\n      for (x <- reversed) {\n        acc = op(x, acc)\n        scanned ::= acc\n      }\n      val b = bf(repr)\n      for (elem <- scanned) b += elem\n      b.result\n    }\n\n    /** Selects the first element of this $coll.\n     *  $orderDependent\n     *  @return  the first element of this $coll.\n     *  @throws `NoSuchElementException` if the $coll is empty.\n     */\n    def head: A = {\n      var result: () => A = () => throw new NoSuchElementException\n      breakable {\n        for (x <- this) {\n          result = () => x\n          break\n        }\n      }\n      result()\n    }\n\n    /** Optionally selects the first element.\n     *  $orderDependent\n     *  @return  the first element of this $coll if it is nonempty, `None` if it is empty.\n     */\n    def headOption: Option[A] = if (isEmpty) None else Some(head)\n\n    /** Selects all elements except the first.\n     *  $orderDependent\n     *  @return  a $coll consisting of all elements of this $coll\n     *           except the first one.\n     *  @throws `UnsupportedOperationException` if the $coll is empty.\n     */ \n    override def tail: Repr = {\n      if (isEmpty) throw new UnsupportedOperationException(\"empty.tail\")\n      drop(1)\n    }\n\n    /** Selects the last element.\n      * $orderDependent\n      * @return The last element of this $coll.\n      * @throws NoSuchElementException If the $coll is empty.\n      */\n    def last: A = {\n      var lst = head\n      for (x <- this)\n        lst = x\n      lst\n    }\n\n    /** Optionally selects the last element.\n     *  $orderDependent\n     *  @return  the last element of this $coll$ if it is nonempty, `None` if it is empty.\n     */\n    def lastOption: Option[A] = if (isEmpty) None else Some(last)\n\n    /** Selects all elements except the last.\n     *  $orderDependent\n     *  @return  a $coll consisting of all elements of this $coll\n     *           except the last one.\n     *  @throws `UnsupportedOperationException` if the $coll is empty.\n     */\n    def init: Repr = {\n      if (isEmpty) throw new UnsupportedOperationException(\"empty.init\")\n      var lst = head\n      var follow = false\n      val b = newBuilder\n      b.sizeHint(this, -1)\n      for (x <- this.seq) {\n        if (follow) b += lst\n        else follow = true\n        lst = x\n      }\n      b.result\n    }\n\n    def take(n: Int): Repr = slice(0, n)\n\n    def drop(n: Int): Repr = \n      if (n <= 0) {\n        val b = newBuilder\n        b.sizeHint(this)\n        b ++= thisCollection result\n      }\n      else sliceWithKnownDelta(n, Int.MaxValue, -n)\n\n    def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until)\n\n    // Precondition: from >= 0, until > 0, builder already configured for building.\n    private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = {\n      var i = 0\n      breakable {\n        for (x <- this.seq) {\n          if (i >= from) b += x\n          i += 1\n          if (i >= until) break\n        }\n      }\n      b.result\n    }\n    // Precondition: from >= 0\n    private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = {\n      val b = newBuilder\n      if (until <= from) b.result\n      else {\n        b.sizeHint(this, delta)\n        sliceInternal(from, until, b)\n      }\n    }\n    // Precondition: from >= 0\n    private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = {\n      val b = newBuilder\n      if (until <= from) b.result\n      else {\n        b.sizeHintBounded(until - from, this)      \n        sliceInternal(from, until, b)\n      }\n    }\n\n    def takeWhile(p: A => Boolean): Repr = {\n      val b = newBuilder\n      breakable {\n        for (x <- this) {\n          if (!p(x)) break\n          b += x\n        }\n      }\n      b.result\n    }\n\n    def dropWhile(p: A => Boolean): Repr = {\n      val b = newBuilder\n      var go = false\n      for (x <- this) {\n        if (!p(x)) go = true\n        if (go) b += x\n      }\n      b.result\n    }\n\n    def span(p: A => Boolean): (Repr, Repr) = {\n      val l, r = newBuilder\n      var toLeft = true\n      for (x <- this) {\n        toLeft = toLeft && p(x)\n        (if (toLeft) l else r) += x\n      }\n      (l.result, r.result)\n    }\n\n    def splitAt(n: Int): (Repr, Repr) = {\n      val l, r = newBuilder\n      l.sizeHintBounded(n, this)\n      if (n >= 0) r.sizeHint(this, -n)\n      var i = 0\n      for (x <- this) {\n        (if (i < n) l else r) += x\n        i += 1\n      }\n      (l.result, r.result)\n    }\n\n    /** Iterates over the tails of this $coll. The first value will be this\n     *  $coll and the final one will be an empty $coll, with the intervening\n     *  values the results of successive applications of `tail`.\n     *\n     *  @return   an iterator over all the tails of this $coll\n     *  @example  `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)`\n     */  \n    def tails: Iterator[Repr] = iterateUntilEmpty(_.tail)\n\n    /** Iterates over the inits of this $coll. The first value will be this\n     *  $coll and the final one will be an empty $coll, with the intervening\n     *  values the results of successive applications of `init`.\n     *\n     *  @return  an iterator over all the inits of this $coll\n     *  @example  `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)`\n     */\n    def inits: Iterator[Repr] = iterateUntilEmpty(_.init)\n\n    /** Copies elements of this $coll to an array.\n     *  Fills the given array `xs` with at most `len` elements of\n     *  this $coll, starting at position `start`.\n     *  Copying will stop once either the end of the current $coll is reached,\n     *  or the end of the array is reached, or `len` elements have been copied.\n     *\n     *  $willNotTerminateInf\n     * \n     *  @param  xs     the array to fill.\n     *  @param  start  the starting index.\n     *  @param  len    the maximal number of elements to copy.\n     *  @tparam B      the type of the elements of the array. \n     * \n     *\n     *  @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit\n     */\n    def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {\n      var i = start\n      val end = (start + len) min xs.length\n      breakable {\n        for (x <- this) {\n          if (i >= end) break\n          xs(i) = x\n          i += 1\n        }\n      }\n    }\n\n    def toTraversable: Traversable[A] = thisCollection\n    def toIterator: Iterator[A] = toStream.iterator\n    def toStream: Stream[A] = toBuffer.toStream\n\n    /** Converts this $coll to a string.\n     *\n     *  @return   a string representation of this collection. By default this\n     *            string consists of the `stringPrefix` of this $coll,\n     *            followed by all elements separated by commas and enclosed in parentheses.\n     */\n    override def toString = mkString(stringPrefix + \"(\", \", \", \")\")\n\n    /** Defines the prefix of this object's `toString` representation.\n     *\n     *  @return  a string representation which starts the result of `toString`\n     *           applied to this $coll. By default the string prefix is the\n     *           simple name of the collection class $coll.\n     */\n    def stringPrefix : String = {\n      var string = repr.asInstanceOf[AnyRef].getClass.getName\n      val idx1 = string.lastIndexOf('.' : Int)\n      if (idx1 != -1) string = string.substring(idx1 + 1)\n      val idx2 = string.indexOf('$')\n      if (idx2 != -1) string = string.substring(0, idx2)\n      string\n    }\n\n    /** Creates a non-strict view of this $coll.\n     * \n     *  @return a non-strict view of this $coll.\n     */\n    def view = new TraversableView[A, Repr] {\n      protected lazy val underlying = self.repr\n      override def foreach[U](f: A => U) = self foreach f\n    }\n\n    /** Creates a non-strict view of a slice of this $coll.\n     *\n     *  Note: the difference between `view` and `slice` is that `view` produces\n     *        a view of the current $coll, whereas `slice` produces a new $coll.\n     * \n     *  Note: `view(from, to)` is equivalent to `view.slice(from, to)`\n     *  $orderDependent\n     * \n     *  @param from   the index of the first element of the view\n     *  @param until  the index of the element following the view\n     *  @return a non-strict view of a slice of this $coll, starting at index `from`\n     *  and extending up to (but not including) index `until`.\n     */\n    def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until)\n\n    /** Creates a non-strict filter of this $coll.\n     *\n     *  Note: the difference between `c filter p` and `c withFilter p` is that\n     *        the former creates a new collection, whereas the latter only\n     *        restricts the domain of subsequent `map`, `flatMap`, `foreach`,\n     *        and `withFilter` operations.\n     *  $orderDependent\n     * \n     *  @param p   the predicate used to test elements.\n     *  @return    an object of class `WithFilter`, which supports\n     *             `map`, `flatMap`, `foreach`, and `withFilter` operations.\n     *             All these operations apply to those elements of this $coll which\n     *             satisfy the predicate `p`.\n     */\n    def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p)\n\n    /** A class supporting filtered operations. Instances of this class are\n     *  returned by method `withFilter`.\n     */\n    class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] {\n\n      /** Builds a new collection by applying a function to all elements of the\n       *  outer $coll containing this `WithFilter` instance that satisfy predicate `p`.\n       *\n       *  @param f      the function to apply to each element.\n       *  @tparam B     the element type of the returned collection.\n       *  @tparam That  $thatinfo\n       *  @param bf     $bfinfo\n       *  @return       a new collection of type `That` resulting from applying\n       *                the given function `f` to each element of the outer $coll\n       *                that satisfies predicate `p` and collecting the results.\n       *\n       *  @usecase def map[B](f: A => B): $Coll[B] \n       *  \n       *  @return       a new $coll resulting from applying the given function\n       *                `f` to each element of the outer $coll that satisfies\n       *                predicate `p` and collecting the results.\n       */\n      def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n        val b = bf(repr)\n        for (x <- self) \n          if (p(x)) b += f(x)\n        b.result\n      }\n\n      /** Builds a new collection by applying a function to all elements of the\n       *  outer $coll containing this `WithFilter` instance that satisfy\n       *  predicate `p` and concatenating the results. \n       *\n       *  @param f      the function to apply to each element.\n       *  @tparam B     the element type of the returned collection.\n       *  @tparam That  $thatinfo\n       *  @param bf     $bfinfo\n       *  @return       a new collection of type `That` resulting from applying\n       *                the given collection-valued function `f` to each element\n       *                of the outer $coll that satisfies predicate `p` and\n       *                concatenating the results.\n       *\n       *  @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B]\n       * \n       *  @return       a new $coll resulting from applying the given collection-valued function\n       *                `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.\n       */\n      def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {\n        val b = bf(repr)\n        for (x <- self) \n          if (p(x)) b ++= f(x).seq\n        b.result\n      }\n\n      /** Applies a function `f` to all elements of the outer $coll containing\n       *  this `WithFilter` instance that satisfy predicate `p`.\n       *\n       *  @param  f   the function that is applied for its side-effect to every element.\n       *              The result of function `f` is discarded.\n       *              \n       *  @tparam  U  the type parameter describing the result of function `f`. \n       *              This result will always be ignored. Typically `U` is `Unit`,\n       *              but this is not necessary.\n       *\n       *  @usecase def foreach(f: A => Unit): Unit\n       */   \n      def foreach[U](f: A => U): Unit = \n        for (x <- self) \n          if (p(x)) f(x)\n\n      /** Further refines the filter for this $coll.\n       *\n       *  @param q   the predicate used to test elements.\n       *  @return    an object of class `WithFilter`, which supports\n       *             `map`, `flatMap`, `foreach`, and `withFilter` operations.\n       *             All these operations apply to those elements of this $coll which\n       *             satisfy the predicate `q` in addition to the predicate `p`.\n       */\n      def withFilter(q: A => Boolean): WithFilter = \n        new WithFilter(x => p(x) && q(x))\n    }\n\n    // A helper for tails and inits.\n    private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = {\n      val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty)\n      it ++ Iterator(Nil) map (newBuilder ++= _ result)\n    }\n  }\n\n\n</textarea>\n</form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        theme: \"ambiance\",\n        mode: \"text/x-scala\"\n      });\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/clike/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"text/x-c\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"indent\",\n     \"[type void] [def foo]([type void*] [variable a], [type int] [variable b]) {\",\n     \"  [type int] [variable c] [operator =] [variable b] [operator +]\",\n     \"    [number 1];\",\n     \"  [keyword return] [operator *][variable a];\",\n     \"}\");\n\n  MT(\"indent_switch\",\n     \"[keyword switch] ([variable x]) {\",\n     \"  [keyword case] [number 10]:\",\n     \"    [keyword return] [number 20];\",\n     \"  [keyword default]:\",\n     \"    [variable printf]([string \\\"foo %c\\\"], [variable x]);\",\n     \"}\");\n\n  MT(\"def\",\n     \"[type void] [def foo]() {}\",\n     \"[keyword struct] [def bar]{}\",\n     \"[keyword enum] [def zot]{}\",\n     \"[keyword union] [def ugh]{}\",\n     \"[type int] [type *][def baz]() {}\");\n\n  MT(\"def_new_line\",\n     \"::[variable std]::[variable SomeTerribleType][operator <][variable T][operator >]\",\n     \"[def SomeLongMethodNameThatDoesntFitIntoOneLine]([keyword const] [variable MyType][operator &] [variable param]) {}\")\n\n  MT(\"double_block\",\n     \"[keyword for] (;;)\",\n     \"  [keyword for] (;;)\",\n     \"    [variable x][operator ++];\",\n     \"[keyword return];\");\n\n  MT(\"preprocessor\",\n     \"[meta #define FOO 3]\",\n     \"[type int] [variable foo];\",\n     \"[meta #define BAR\\\\]\",\n     \"[meta 4]\",\n     \"[type unsigned] [type int] [variable bar] [operator =] [number 8];\",\n     \"[meta #include <baz> ][comment // comment]\")\n\n  MT(\"c_underscores\",\n     \"[builtin __FOO];\",\n     \"[builtin _Complex];\",\n     \"[builtin __aName];\",\n     \"[variable _aName];\");\n\n  MT(\"c_types\",\n    \"[type int];\",\n    \"[type long];\",\n    \"[type char];\",\n    \"[type short];\",\n    \"[type double];\",\n    \"[type float];\",\n    \"[type unsigned];\",\n    \"[type signed];\",\n    \"[type void];\",\n    \"[type bool];\",\n    \"[type foo_t];\",\n    \"[variable foo_T];\",\n    \"[variable _t];\");\n\n  var mode_cpp = CodeMirror.getMode({indentUnit: 2}, \"text/x-c++src\");\n  function MTCPP(name) { test.mode(name, mode_cpp, Array.prototype.slice.call(arguments, 1)); }\n\n  MTCPP(\"cpp14_literal\",\n    \"[number 10'000];\",\n    \"[number 0b10'000];\",\n    \"[number 0x10'000];\",\n    \"[string '100000'];\");\n\n  MTCPP(\"ctor_dtor\",\n     \"[def Foo::Foo]() {}\",\n     \"[def Foo::~Foo]() {}\");\n\n  MTCPP(\"cpp_underscores\",\n        \"[builtin __FOO];\",\n        \"[builtin _Complex];\",\n        \"[builtin __aName];\",\n        \"[variable _aName];\");\n\n  var mode_objc = CodeMirror.getMode({indentUnit: 2}, \"text/x-objectivec\");\n  function MTOBJC(name) { test.mode(name, mode_objc, Array.prototype.slice.call(arguments, 1)); }\n\n  MTOBJC(\"objc_underscores\",\n         \"[builtin __FOO];\",\n         \"[builtin _Complex];\",\n         \"[builtin __aName];\",\n         \"[variable _aName];\");\n\n  MTOBJC(\"objc_interface\",\n         \"[keyword @interface] [def foo] {\",\n         \"  [type int] [variable bar];\",\n         \"}\",\n         \"[keyword @property] ([keyword atomic], [keyword nullable]) [variable NSString][operator *] [variable a];\",\n         \"[keyword @property] ([keyword nonatomic], [keyword assign]) [type int] [variable b];\",\n         \"[operator -]([type instancetype])[variable initWithFoo]:([type int])[variable a] \" +\n           \"[builtin NS_DESIGNATED_INITIALIZER];\",\n         \"[keyword @end]\");\n\n  MTOBJC(\"objc_implementation\",\n         \"[keyword @implementation] [def foo] {\",\n         \"  [type int] [variable bar];\",\n         \"}\",\n         \"[keyword @property] ([keyword readwrite]) [type SEL] [variable a];\",\n         \"[operator -]([type instancetype])[variable initWithFoo]:([type int])[variable a] {\",\n         \"  [keyword if](([keyword self] [operator =] [[[keyword super] [variable init] ]])) {}\",\n         \"  [keyword return] [keyword self];\",\n         \"}\",\n         \"[keyword @end]\");\n\n  MTOBJC(\"objc_types\",\n         \"[type int];\",\n         \"[type foo_t];\",\n         \"[variable foo_T];\",\n         \"[type id];\",\n         \"[type SEL];\",\n         \"[type instancetype];\",\n         \"[type Class];\",\n         \"[type Protocol];\",\n         \"[type BOOL];\"\n         );\n\n  var mode_scala = CodeMirror.getMode({indentUnit: 2}, \"text/x-scala\");\n  function MTSCALA(name) { test.mode(\"scala_\" + name, mode_scala, Array.prototype.slice.call(arguments, 1)); }\n  MTSCALA(\"nested_comments\",\n     \"[comment /*]\",\n     \"[comment But wait /* this is a nested comment */ for real]\",\n     \"[comment /**** let * me * show * you ****/]\",\n     \"[comment ///// let / me / show / you /////]\",\n     \"[comment */]\");\n\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/clojure/clojure.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports === \"object\" && typeof module === \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define === \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"clojure\", function (options) {\n  var atoms = [\"false\", \"nil\", \"true\"];\n  var specialForms = [\".\", \"catch\", \"def\", \"do\", \"if\", \"monitor-enter\",\n      \"monitor-exit\", \"new\", \"quote\", \"recur\", \"set!\", \"throw\", \"try\", \"var\"];\n  var coreSymbols = [\"*\", \"*'\", \"*1\", \"*2\", \"*3\", \"*agent*\",\n      \"*allow-unresolved-vars*\", \"*assert*\", \"*clojure-version*\",\n      \"*command-line-args*\", \"*compile-files*\", \"*compile-path*\",\n      \"*compiler-options*\", \"*data-readers*\", \"*default-data-reader-fn*\", \"*e\",\n      \"*err*\", \"*file*\", \"*flush-on-newline*\", \"*fn-loader*\", \"*in*\",\n      \"*math-context*\", \"*ns*\", \"*out*\", \"*print-dup*\", \"*print-length*\",\n      \"*print-level*\", \"*print-meta*\", \"*print-namespace-maps*\",\n      \"*print-readably*\", \"*read-eval*\", \"*reader-resolver*\", \"*source-path*\",\n      \"*suppress-read*\", \"*unchecked-math*\", \"*use-context-classloader*\",\n      \"*verbose-defrecords*\", \"*warn-on-reflection*\", \"+\", \"+'\", \"-\", \"-'\",\n      \"->\", \"->>\", \"->ArrayChunk\", \"->Eduction\", \"->Vec\", \"->VecNode\",\n      \"->VecSeq\", \"-cache-protocol-fn\", \"-reset-methods\", \"..\", \"/\", \"<\", \"<=\",\n      \"=\", \"==\", \">\", \">=\", \"EMPTY-NODE\", \"Inst\", \"StackTraceElement->vec\",\n      \"Throwable->map\", \"accessor\", \"aclone\", \"add-classpath\", \"add-watch\",\n      \"agent\", \"agent-error\", \"agent-errors\", \"aget\", \"alength\", \"alias\",\n      \"all-ns\", \"alter\", \"alter-meta!\", \"alter-var-root\", \"amap\", \"ancestors\",\n      \"and\", \"any?\", \"apply\", \"areduce\", \"array-map\", \"as->\", \"aset\",\n      \"aset-boolean\", \"aset-byte\", \"aset-char\", \"aset-double\", \"aset-float\",\n      \"aset-int\", \"aset-long\", \"aset-short\", \"assert\", \"assoc\", \"assoc!\",\n      \"assoc-in\", \"associative?\", \"atom\", \"await\", \"await-for\", \"await1\",\n      \"bases\", \"bean\", \"bigdec\", \"bigint\", \"biginteger\", \"binding\", \"bit-and\",\n      \"bit-and-not\", \"bit-clear\", \"bit-flip\", \"bit-not\", \"bit-or\", \"bit-set\",\n      \"bit-shift-left\", \"bit-shift-right\", \"bit-test\", \"bit-xor\", \"boolean\",\n      \"boolean-array\", \"boolean?\", \"booleans\", \"bound-fn\", \"bound-fn*\",\n      \"bound?\", \"bounded-count\", \"butlast\", \"byte\", \"byte-array\", \"bytes\",\n      \"bytes?\", \"case\", \"cast\", \"cat\", \"char\", \"char-array\",\n      \"char-escape-string\", \"char-name-string\", \"char?\", \"chars\", \"chunk\",\n      \"chunk-append\", \"chunk-buffer\", \"chunk-cons\", \"chunk-first\", \"chunk-next\",\n      \"chunk-rest\", \"chunked-seq?\", \"class\", \"class?\", \"clear-agent-errors\",\n      \"clojure-version\", \"coll?\", \"comment\", \"commute\", \"comp\", \"comparator\",\n      \"compare\", \"compare-and-set!\", \"compile\", \"complement\", \"completing\",\n      \"concat\", \"cond\", \"cond->\", \"cond->>\", \"condp\", \"conj\", \"conj!\", \"cons\",\n      \"constantly\", \"construct-proxy\", \"contains?\", \"count\", \"counted?\",\n      \"create-ns\", \"create-struct\", \"cycle\", \"dec\", \"dec'\", \"decimal?\",\n      \"declare\", \"dedupe\", \"default-data-readers\", \"definline\", \"definterface\",\n      \"defmacro\", \"defmethod\", \"defmulti\", \"defn\", \"defn-\", \"defonce\",\n      \"defprotocol\", \"defrecord\", \"defstruct\", \"deftype\", \"delay\", \"delay?\",\n      \"deliver\", \"denominator\", \"deref\", \"derive\", \"descendants\", \"destructure\",\n      \"disj\", \"disj!\", \"dissoc\", \"dissoc!\", \"distinct\", \"distinct?\", \"doall\",\n      \"dorun\", \"doseq\", \"dosync\", \"dotimes\", \"doto\", \"double\", \"double-array\",\n      \"double?\", \"doubles\", \"drop\", \"drop-last\", \"drop-while\", \"eduction\",\n      \"empty\", \"empty?\", \"ensure\", \"ensure-reduced\", \"enumeration-seq\",\n      \"error-handler\", \"error-mode\", \"eval\", \"even?\", \"every-pred\", \"every?\",\n      \"ex-data\", \"ex-info\", \"extend\", \"extend-protocol\", \"extend-type\",\n      \"extenders\", \"extends?\", \"false?\", \"ffirst\", \"file-seq\", \"filter\",\n      \"filterv\", \"find\", \"find-keyword\", \"find-ns\", \"find-protocol-impl\",\n      \"find-protocol-method\", \"find-var\", \"first\", \"flatten\", \"float\",\n      \"float-array\", \"float?\", \"floats\", \"flush\", \"fn\", \"fn?\", \"fnext\", \"fnil\",\n      \"for\", \"force\", \"format\", \"frequencies\", \"future\", \"future-call\",\n      \"future-cancel\", \"future-cancelled?\", \"future-done?\", \"future?\",\n      \"gen-class\", \"gen-interface\", \"gensym\", \"get\", \"get-in\", \"get-method\",\n      \"get-proxy-class\", \"get-thread-bindings\", \"get-validator\", \"group-by\",\n      \"halt-when\", \"hash\", \"hash-combine\", \"hash-map\", \"hash-ordered-coll\",\n      \"hash-set\", \"hash-unordered-coll\", \"ident?\", \"identical?\", \"identity\",\n      \"if-let\", \"if-not\", \"if-some\", \"ifn?\", \"import\", \"in-ns\", \"inc\", \"inc'\",\n      \"indexed?\", \"init-proxy\", \"inst-ms\", \"inst-ms*\", \"inst?\", \"instance?\",\n      \"int\", \"int-array\", \"int?\", \"integer?\", \"interleave\", \"intern\",\n      \"interpose\", \"into\", \"into-array\", \"ints\", \"io!\", \"isa?\", \"iterate\",\n      \"iterator-seq\", \"juxt\", \"keep\", \"keep-indexed\", \"key\", \"keys\", \"keyword\",\n      \"keyword?\", \"last\", \"lazy-cat\", \"lazy-seq\", \"let\", \"letfn\", \"line-seq\",\n      \"list\", \"list*\", \"list?\", \"load\", \"load-file\", \"load-reader\",\n      \"load-string\", \"loaded-libs\", \"locking\", \"long\", \"long-array\", \"longs\",\n      \"loop\", \"macroexpand\", \"macroexpand-1\", \"make-array\", \"make-hierarchy\",\n      \"map\", \"map-entry?\", \"map-indexed\", \"map?\", \"mapcat\", \"mapv\", \"max\",\n      \"max-key\", \"memfn\", \"memoize\", \"merge\", \"merge-with\", \"meta\",\n      \"method-sig\", \"methods\", \"min\", \"min-key\", \"mix-collection-hash\", \"mod\",\n      \"munge\", \"name\", \"namespace\", \"namespace-munge\", \"nat-int?\", \"neg-int?\",\n      \"neg?\", \"newline\", \"next\", \"nfirst\", \"nil?\", \"nnext\", \"not\", \"not-any?\",\n      \"not-empty\", \"not-every?\", \"not=\", \"ns\", \"ns-aliases\", \"ns-imports\",\n      \"ns-interns\", \"ns-map\", \"ns-name\", \"ns-publics\", \"ns-refers\",\n      \"ns-resolve\", \"ns-unalias\", \"ns-unmap\", \"nth\", \"nthnext\", \"nthrest\",\n      \"num\", \"number?\", \"numerator\", \"object-array\", \"odd?\", \"or\", \"parents\",\n      \"partial\", \"partition\", \"partition-all\", \"partition-by\", \"pcalls\", \"peek\",\n      \"persistent!\", \"pmap\", \"pop\", \"pop!\", \"pop-thread-bindings\", \"pos-int?\",\n      \"pos?\", \"pr\", \"pr-str\", \"prefer-method\", \"prefers\",\n      \"primitives-classnames\", \"print\", \"print-ctor\", \"print-dup\",\n      \"print-method\", \"print-simple\", \"print-str\", \"printf\", \"println\",\n      \"println-str\", \"prn\", \"prn-str\", \"promise\", \"proxy\",\n      \"proxy-call-with-super\", \"proxy-mappings\", \"proxy-name\", \"proxy-super\",\n      \"push-thread-bindings\", \"pvalues\", \"qualified-ident?\",\n      \"qualified-keyword?\", \"qualified-symbol?\", \"quot\", \"rand\", \"rand-int\",\n      \"rand-nth\", \"random-sample\", \"range\", \"ratio?\", \"rational?\",\n      \"rationalize\", \"re-find\", \"re-groups\", \"re-matcher\", \"re-matches\",\n      \"re-pattern\", \"re-seq\", \"read\", \"read-line\", \"read-string\",\n      \"reader-conditional\", \"reader-conditional?\", \"realized?\", \"record?\",\n      \"reduce\", \"reduce-kv\", \"reduced\", \"reduced?\", \"reductions\", \"ref\",\n      \"ref-history-count\", \"ref-max-history\", \"ref-min-history\", \"ref-set\",\n      \"refer\", \"refer-clojure\", \"reify\", \"release-pending-sends\", \"rem\",\n      \"remove\", \"remove-all-methods\", \"remove-method\", \"remove-ns\",\n      \"remove-watch\", \"repeat\", \"repeatedly\", \"replace\", \"replicate\", \"require\",\n      \"reset!\", \"reset-meta!\", \"reset-vals!\", \"resolve\", \"rest\",\n      \"restart-agent\", \"resultset-seq\", \"reverse\", \"reversible?\", \"rseq\",\n      \"rsubseq\", \"run!\", \"satisfies?\", \"second\", \"select-keys\", \"send\",\n      \"send-off\", \"send-via\", \"seq\", \"seq?\", \"seqable?\", \"seque\", \"sequence\",\n      \"sequential?\", \"set\", \"set-agent-send-executor!\",\n      \"set-agent-send-off-executor!\", \"set-error-handler!\", \"set-error-mode!\",\n      \"set-validator!\", \"set?\", \"short\", \"short-array\", \"shorts\", \"shuffle\",\n      \"shutdown-agents\", \"simple-ident?\", \"simple-keyword?\", \"simple-symbol?\",\n      \"slurp\", \"some\", \"some->\", \"some->>\", \"some-fn\", \"some?\", \"sort\",\n      \"sort-by\", \"sorted-map\", \"sorted-map-by\", \"sorted-set\", \"sorted-set-by\",\n      \"sorted?\", \"special-symbol?\", \"spit\", \"split-at\", \"split-with\", \"str\",\n      \"string?\", \"struct\", \"struct-map\", \"subs\", \"subseq\", \"subvec\", \"supers\",\n      \"swap!\", \"swap-vals!\", \"symbol\", \"symbol?\", \"sync\", \"tagged-literal\",\n      \"tagged-literal?\", \"take\", \"take-last\", \"take-nth\", \"take-while\", \"test\",\n      \"the-ns\", \"thread-bound?\", \"time\", \"to-array\", \"to-array-2d\",\n      \"trampoline\", \"transduce\", \"transient\", \"tree-seq\", \"true?\", \"type\",\n      \"unchecked-add\", \"unchecked-add-int\", \"unchecked-byte\", \"unchecked-char\",\n      \"unchecked-dec\", \"unchecked-dec-int\", \"unchecked-divide-int\",\n      \"unchecked-double\", \"unchecked-float\", \"unchecked-inc\",\n      \"unchecked-inc-int\", \"unchecked-int\", \"unchecked-long\",\n      \"unchecked-multiply\", \"unchecked-multiply-int\", \"unchecked-negate\",\n      \"unchecked-negate-int\", \"unchecked-remainder-int\", \"unchecked-short\",\n      \"unchecked-subtract\", \"unchecked-subtract-int\", \"underive\", \"unquote\",\n      \"unquote-splicing\", \"unreduced\", \"unsigned-bit-shift-right\", \"update\",\n      \"update-in\", \"update-proxy\", \"uri?\", \"use\", \"uuid?\", \"val\", \"vals\",\n      \"var-get\", \"var-set\", \"var?\", \"vary-meta\", \"vec\", \"vector\", \"vector-of\",\n      \"vector?\", \"volatile!\", \"volatile?\", \"vreset!\", \"vswap!\", \"when\",\n      \"when-first\", \"when-let\", \"when-not\", \"when-some\", \"while\",\n      \"with-bindings\", \"with-bindings*\", \"with-in-str\", \"with-loading-context\",\n      \"with-local-vars\", \"with-meta\", \"with-open\", \"with-out-str\",\n      \"with-precision\", \"with-redefs\", \"with-redefs-fn\", \"xml-seq\", \"zero?\",\n      \"zipmap\"];\n  var haveBodyParameter = [\n      \"->\", \"->>\", \"as->\", \"binding\", \"bound-fn\", \"case\", \"catch\", \"comment\",\n      \"cond\", \"cond->\", \"cond->>\", \"condp\", \"def\", \"definterface\", \"defmethod\",\n      \"defn\", \"defmacro\", \"defprotocol\", \"defrecord\", \"defstruct\", \"deftype\",\n      \"do\", \"doseq\", \"dotimes\", \"doto\", \"extend\", \"extend-protocol\",\n      \"extend-type\", \"fn\", \"for\", \"future\", \"if\", \"if-let\", \"if-not\", \"if-some\",\n      \"let\", \"letfn\", \"locking\", \"loop\", \"ns\", \"proxy\", \"reify\", \"struct-map\",\n      \"some->\", \"some->>\", \"try\", \"when\", \"when-first\", \"when-let\", \"when-not\",\n      \"when-some\", \"while\", \"with-bindings\", \"with-bindings*\", \"with-in-str\",\n      \"with-loading-context\", \"with-local-vars\", \"with-meta\", \"with-open\",\n      \"with-out-str\", \"with-precision\", \"with-redefs\", \"with-redefs-fn\"];\n\n  CodeMirror.registerHelper(\"hintWords\", \"clojure\",\n    [].concat(atoms, specialForms, coreSymbols));\n\n  var atom = createLookupMap(atoms);\n  var specialForm = createLookupMap(specialForms);\n  var coreSymbol = createLookupMap(coreSymbols);\n  var hasBodyParameter = createLookupMap(haveBodyParameter);\n  var delimiter = /^(?:[\\\\\\[\\]\\s\"(),;@^`{}~]|$)/;\n  var numberLiteral = /^(?:[+\\-]?\\d+(?:(?:N|(?:[eE][+\\-]?\\d+))|(?:\\.?\\d*(?:M|(?:[eE][+\\-]?\\d+))?)|\\/\\d+|[xX][0-9a-fA-F]+|r[0-9a-zA-Z]+)?(?=[\\\\\\[\\]\\s\"#'(),;@^`{}~]|$))/;\n  var characterLiteral = /^(?:\\\\(?:backspace|formfeed|newline|return|space|tab|o[0-7]{3}|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{4}|.)?(?=[\\\\\\[\\]\\s\"(),;@^`{}~]|$))/;\n\n  // simple-namespace := /^[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~][^\\\\\\[\\]\\s\"(),;@^`{}~]*/\n  // simple-symbol    := /^(?:\\/|[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~][^\\\\\\[\\]\\s\"(),;@^`{}~]*)/\n  // qualified-symbol := (<simple-namespace>(<.><simple-namespace>)*</>)?<simple-symbol>\n  var qualifiedSymbol = /^(?:(?:[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~][^\\\\\\[\\]\\s\"(),;@^`{}~]*(?:\\.[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~][^\\\\\\[\\]\\s\"(),;@^`{}~]*)*\\/)?(?:\\/|[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~][^\\\\\\[\\]\\s\"(),;@^`{}~]*)*(?=[\\\\\\[\\]\\s\"(),;@^`{}~]|$))/;\n\n  function base(stream, state) {\n    if (stream.eatSpace()) return [\"space\", null];\n    if (stream.match(numberLiteral)) return [null, \"number\"];\n    if (stream.match(characterLiteral)) return [null, \"string-2\"];\n    if (stream.eat(/^\"/)) return (state.tokenize = inString)(stream, state);\n    if (stream.eat(/^[(\\[{]/)) return [\"open\", \"bracket\"];\n    if (stream.eat(/^[)\\]}]/)) return [\"close\", \"bracket\"];\n    if (stream.eat(/^;/)) {stream.skipToEnd(); return [\"space\", \"comment\"];}\n    if (stream.eat(/^[#'@^`~]/)) return [null, \"meta\"];\n\n    var matches = stream.match(qualifiedSymbol);\n    var symbol = matches && matches[0];\n\n    if (!symbol) {\n      // advance stream by at least one character so we don't get stuck.\n      stream.next();\n      stream.eatWhile(function (c) {return !is(c, delimiter);});\n      return [null, \"error\"];\n    }\n\n    if (symbol === \"comment\" && state.lastToken === \"(\")\n      return (state.tokenize = inComment)(stream, state);\n    if (is(symbol, atom) || symbol.charAt(0) === \":\") return [\"symbol\", \"atom\"];\n    if (is(symbol, specialForm) || is(symbol, coreSymbol)) return [\"symbol\", \"keyword\"];\n    if (state.lastToken === \"(\") return [\"symbol\", \"builtin\"]; // other operator\n\n    return [\"symbol\", \"variable\"];\n  }\n\n  function inString(stream, state) {\n    var escaped = false, next;\n\n    while (next = stream.next()) {\n      if (next === \"\\\"\" && !escaped) {state.tokenize = base; break;}\n      escaped = !escaped && next === \"\\\\\";\n    }\n\n    return [null, \"string\"];\n  }\n\n  function inComment(stream, state) {\n    var parenthesisCount = 1;\n    var next;\n\n    while (next = stream.next()) {\n      if (next === \")\") parenthesisCount--;\n      if (next === \"(\") parenthesisCount++;\n      if (parenthesisCount === 0) {\n        stream.backUp(1);\n        state.tokenize = base;\n        break;\n      }\n    }\n\n    return [\"space\", \"comment\"];\n  }\n\n  function createLookupMap(words) {\n    var obj = {};\n\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n\n    return obj;\n  }\n\n  function is(value, test) {\n    if (test instanceof RegExp) return test.test(value);\n    if (test instanceof Object) return test.propertyIsEnumerable(value);\n  }\n\n  return {\n    startState: function () {\n      return {\n        ctx: {prev: null, start: 0, indentTo: 0},\n        lastToken: null,\n        tokenize: base\n      };\n    },\n\n    token: function (stream, state) {\n      if (stream.sol() && (typeof state.ctx.indentTo !== \"number\"))\n        state.ctx.indentTo = state.ctx.start + 1;\n\n      var typeStylePair = state.tokenize(stream, state);\n      var type = typeStylePair[0];\n      var style = typeStylePair[1];\n      var current = stream.current();\n\n      if (type !== \"space\") {\n        if (state.lastToken === \"(\" && state.ctx.indentTo === null) {\n          if (type === \"symbol\" && is(current, hasBodyParameter))\n            state.ctx.indentTo = state.ctx.start + options.indentUnit;\n          else state.ctx.indentTo = \"next\";\n        } else if (state.ctx.indentTo === \"next\") {\n          state.ctx.indentTo = stream.column();\n        }\n\n        state.lastToken = current;\n      }\n\n      if (type === \"open\")\n        state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};\n      else if (type === \"close\") state.ctx = state.ctx.prev || state.ctx;\n\n      return style;\n    },\n\n    indent: function (state) {\n      var i = state.ctx.indentTo;\n\n      return (typeof i === \"number\") ?\n        i :\n        state.ctx.start + 1;\n    },\n\n    closeBrackets: {pairs: \"()[]{}\\\"\\\"\"},\n    lineComment: \";;\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-clojure\", \"clojure\");\nCodeMirror.defineMIME(\"text/x-clojurescript\", \"clojure\");\nCodeMirror.defineMIME(\"application/edn\", \"clojure\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/clojure/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Clojure mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/closebrackets.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"clojure.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Clojure</a>\n  </ul>\n</div>\n\n<article>\n<h2>Clojure mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n(ns game-of-life\n  \"Conway's Game of Life, based on the work of\n  Christophe Grand (http://clj-me.cgrand.net/2011/08/19/conways-game-of-life)\n  and Laurent Petit (https://gist.github.com/1200343).\")\n\n;;; Core game of life's algorithm functions\n\n(defn neighbors\n  \"Given a cell's coordinates `[x y]`, returns the coordinates of its\n  neighbors.\"\n  [[x y]]\n  (for [dx [-1 0 1]\n        dy (if (zero? dx)\n             [-1 1]\n             [-1 0 1])]\n    [(+ dx x) (+ dy y)]))\n\n(defn step\n  \"Given a set of living `cells`, computes the new set of living cells.\"\n  [cells]\n  (set (for [[cell n] (frequencies (mapcat neighbors cells))\n             :when (or (= n 3)\n                       (and (= n 2)\n                            (cells cell)))]\n         cell)))\n\n;;; Utility methods for displaying game on a text terminal\n\n(defn print-grid\n  \"Prints a `grid` of `w` columns and `h` rows, on *out*, representing a\n  step in the game.\"\n  [grid w h]\n  (doseq [x (range (inc w))\n          y (range (inc h))]\n    (when (= y 0) (println))\n    (print (if (grid [x y])\n             \"[X]\"\n             \" . \"))))\n\n(defn print-grids\n  \"Prints a sequence of `grids` of `w` columns and `h` rows on *out*,\n  representing several steps.\"\n  [grids w h]\n  (doseq [grid grids]\n    (print-grid grid w h)\n    (println)))\n\n;;; Launches an example grid\n\n(def grid\n  \"`grid` represents the initial set of living cells\"\n  #{[2 1] [2 2] [2 3]})\n\n(print-grids (take 3 (iterate step grid)) 5 5)</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n          autoCloseBrackets: true,\n          lineNumbers: true,\n          matchBrackets: true,\n          mode: 'text/x-clojure'\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-clojure</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/clojure/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function () {\n    var mode = CodeMirror.getMode({indentUnit: 2}, \"clojure\");\n\n    function MT(name) {\n        test.mode(name, mode, Array.prototype.slice.call(arguments, 1));\n    }\n\n    MT(\"atoms\",\n        \"[atom false]\",\n        \"[atom nil]\",\n        \"[atom true]\"\n    );\n\n    MT(\"keywords\",\n        \"[atom :foo]\",\n        \"[atom ::bar]\",\n        \"[atom :foo/bar]\",\n        \"[atom :foo.bar/baz]\"\n    );\n\n    MT(\"numbers\",\n        \"[number 42] [number +42] [number -421]\",\n        \"[number 42N] [number +42N] [number -42N]\",\n        \"[number 0.42] [number +0.42] [number -0.42]\",\n        \"[number 42M] [number +42M] [number -42M]\",\n        \"[number 42.42M] [number +42.42M] [number -42.42M]\",\n        \"[number 1/42] [number +1/42] [number -1/42]\",\n        \"[number 0x42af] [number +0x42af] [number -0x42af]\",\n        \"[number 0x42AF] [number +0x42AF] [number -0x42AF]\",\n        \"[number 1e2] [number 1e+2] [number 1e-2]\",\n        \"[number +1e2] [number +1e+2] [number +1e-2]\",\n        \"[number -1e2] [number -1e+2] [number -1e-2]\",\n        \"[number -1.0e2] [number -0.1e+2] [number -1.01e-2]\",\n        \"[number 1E2] [number 1E+2] [number 1E-2]\",\n        \"[number +1E2] [number +1E+2] [number +1E-2]\",\n        \"[number -1E2] [number -1E+2] [number -1E-2]\",\n        \"[number -1.0E2] [number -0.1E+2] [number -1.01E-2]\",\n        \"[number 2r101010] [number +2r101010] [number -2r101010]\",\n        \"[number 2r101010] [number +2r101010] [number -2r101010]\",\n        \"[number 8r52] [number +8r52] [number -8r52]\",\n        \"[number 36rhello] [number +36rhello] [number -36rhello]\",\n        \"[number 36rz] [number +36rz] [number -36rz]\",\n        \"[number 36rZ] [number +36rZ] [number -36rZ]\",\n\n        // invalid numbers\n        \"[error 42foo]\",\n        \"[error 42Nfoo]\",\n        \"[error 42Mfoo]\",\n        \"[error 42.42Mfoo]\",\n        \"[error 42.42M!]\",\n        \"[error 42!]\",\n        \"[error 0x42afm]\"\n    );\n\n    MT(\"characters\",\n        \"[string-2 \\\\1]\",\n        \"[string-2 \\\\a]\",\n        \"[string-2 \\\\a\\\\b\\\\c]\",\n        \"[string-2 \\\\#]\",\n        \"[string-2 \\\\\\\\]\",\n        \"[string-2 \\\\\\\"]\",\n        \"[string-2 \\\\(]\",\n        \"[string-2 \\\\A]\",\n        \"[string-2 \\\\backspace]\",\n        \"[string-2 \\\\formfeed]\",\n        \"[string-2 \\\\newline]\",\n        \"[string-2 \\\\space]\",\n        \"[string-2 \\\\return]\",\n        \"[string-2 \\\\tab]\",\n        \"[string-2 \\\\u1000]\",\n        \"[string-2 \\\\uAaAa]\",\n        \"[string-2 \\\\u9F9F]\",\n        \"[string-2 \\\\o123]\",\n        \"[string-2 \\\\符]\",\n        \"[string-2 \\\\シ]\",\n        \"[string-2 \\\\ۇ]\",\n        // FIXME\n        // \"[string-2 \\\\🙂]\",\n\n        // invalid character literals\n        \"[error \\\\abc]\",\n        \"[error \\\\a123]\",\n        \"[error \\\\a!]\",\n        \"[error \\\\newlines]\",\n        \"[error \\\\NEWLINE]\",\n        \"[error \\\\u9F9FF]\",\n        \"[error \\\\o1234]\"\n    );\n\n    MT(\"strings\",\n        \"[string \\\"I'm a teapot.\\\"]\",\n        \"[string \\\"I'm a \\\\\\\"teapot\\\\\\\".\\\"]\",\n        \"[string \\\"I'm]\",       // this is\n        \"[string a]\",           // a multi-line\n        \"[string teapot.\\\"]\"    // string\n\n        // TODO unterminated (multi-line) strings?\n    );\n\n    MT(\"comments\",\n        \"[comment ; this is an in-line comment.]\",\n        \"[comment ;; this is a line comment.]\",\n        \"[keyword comment]\",\n        \"[bracket (][comment comment (foo 1 2 3)][bracket )]\"\n    );\n\n    MT(\"reader macro characters\",\n        \"[meta #][variable _]\",\n        \"[meta #][variable -Inf]\",\n        \"[meta ##][variable Inf]\",\n        \"[meta ##][variable NaN]\",\n        \"[meta @][variable x]\",\n        \"[meta ^][bracket {][atom :tag] [variable String][bracket }]\",\n        \"[meta `][bracket (][builtin f] [variable x][bracket )]\",\n        \"[meta ~][variable foo#]\",\n        \"[meta '][number 1]\",\n        \"[meta '][atom :foo]\",\n        \"[meta '][string \\\"foo\\\"]\",\n        \"[meta '][variable x]\",\n        \"[meta '][bracket (][builtin a] [variable b] [variable c][bracket )]\",\n        \"[meta '][bracket [[][variable a] [variable b] [variable c][bracket ]]]\",\n        \"[meta '][bracket {][variable a] [number 1] [atom :foo] [number 2] [variable c] [number 3][bracket }]\",\n        \"[meta '#][bracket {][variable a] [number 1] [atom :foo][bracket }]\"\n    );\n\n    MT(\"symbols\",\n      \"[variable foo!]\",\n      \"[variable foo#]\",\n      \"[variable foo$]\",\n      \"[variable foo&]\",\n      \"[variable foo']\",\n      \"[variable foo*]\",\n      \"[variable foo+]\",\n      \"[variable foo-]\",\n      \"[variable foo.]\",\n      \"[variable foo/bar]\",\n      \"[variable foo:bar]\",\n      \"[variable foo<]\",\n      \"[variable foo=]\",\n      \"[variable foo>]\",\n      \"[variable foo?]\",\n      \"[variable foo_]\",\n      \"[variable foo|]\",\n      \"[variable foobarBaz]\",\n      \"[variable foo¡]\",\n      \"[variable 符号]\",\n      \"[variable シンボル]\",\n      \"[variable ئۇيغۇر]\",\n      \"[variable 🙂❤🇺🇸]\",\n\n      // invalid symbols\n      \"[error 3foo]\",\n      \"[error 3+]\",\n      \"[error 3|]\",\n      \"[error 3_]\"\n    );\n\n    MT(\"numbers and other forms\",\n      \"[number 42][bracket (][builtin foo][bracket )]\",\n      \"[number 42][bracket [[][variable foo][bracket ]]]\",\n      \"[number 42][meta #][bracket {][variable foo][bracket }]\",\n      \"[number 42][bracket {][atom :foo] [variable bar][bracket }]\",\n      \"[number 42][meta `][variable foo]\",\n      \"[number 42][meta ~][variable foo]\",\n      \"[number 42][meta #][variable foo]\"\n    );\n\n    var specialForms = [\".\", \"catch\", \"def\", \"do\", \"if\", \"monitor-enter\",\n        \"monitor-exit\", \"new\", \"quote\", \"recur\", \"set!\", \"throw\", \"try\", \"var\"];\n\n    MT(\"should highlight special forms as keywords\",\n        typeTokenPairs(\"keyword\", specialForms)\n    );\n\n    var coreSymbols1 = [\n        \"*\", \"*'\", \"*1\", \"*2\", \"*3\", \"*agent*\", \"*allow-unresolved-vars*\", \"*assert*\",\n        \"*clojure-version*\", \"*command-line-args*\", \"*compile-files*\", \"*compile-path*\", \"*compiler-options*\",\n        \"*data-readers*\", \"*default-data-reader-fn*\", \"*e\", \"*err*\", \"*file*\", \"*flush-on-newline*\", \"*fn-loader*\",\n        \"*in*\", \"*math-context*\", \"*ns*\", \"*out*\", \"*print-dup*\", \"*print-length*\", \"*print-level*\", \"*print-meta*\",\n        \"*print-namespace-maps*\", \"*print-readably*\", \"*read-eval*\", \"*reader-resolver*\", \"*source-path*\",\n        \"*suppress-read*\", \"*unchecked-math*\", \"*use-context-classloader*\", \"*verbose-defrecords*\",\n        \"*warn-on-reflection*\", \"+\", \"+'\", \"-\", \"-'\", \"->\", \"->>\", \"->ArrayChunk\", \"->Eduction\", \"->Vec\", \"->VecNode\",\n        \"->VecSeq\", \"-cache-protocol-fn\", \"-reset-methods\", \"..\", \"/\", \"<\", \"<=\", \"=\", \"==\", \">\", \">=\",\n        \"EMPTY-NODE\", \"Inst\", \"StackTraceElement->vec\", \"Throwable->map\", \"accessor\", \"aclone\", \"add-classpath\",\n        \"add-watch\", \"agent\", \"agent-error\", \"agent-errors\", \"aget\", \"alength\", \"alias\", \"all-ns\", \"alter\",\n        \"alter-meta!\", \"alter-var-root\", \"amap\", \"ancestors\", \"and\", \"any?\", \"apply\", \"areduce\", \"array-map\",\n        \"as->\", \"aset\", \"aset-boolean\", \"aset-byte\", \"aset-char\", \"aset-double\", \"aset-float\", \"aset-int\",\n        \"aset-long\", \"aset-short\", \"assert\", \"assoc\", \"assoc!\", \"assoc-in\", \"associative?\", \"atom\", \"await\",\n        \"await-for\", \"await1\", \"bases\", \"bean\", \"bigdec\", \"bigint\", \"biginteger\", \"binding\", \"bit-and\", \"bit-and-not\",\n        \"bit-clear\", \"bit-flip\", \"bit-not\", \"bit-or\", \"bit-set\", \"bit-shift-left\", \"bit-shift-right\", \"bit-test\",\n        \"bit-xor\", \"boolean\", \"boolean-array\", \"boolean?\", \"booleans\", \"bound-fn\", \"bound-fn*\", \"bound?\",\n        \"bounded-count\", \"butlast\", \"byte\", \"byte-array\", \"bytes\", \"bytes?\", \"case\", \"cast\", \"cat\", \"char\",\n        \"char-array\", \"char-escape-string\", \"char-name-string\", \"char?\", \"chars\", \"chunk\", \"chunk-append\",\n        \"chunk-buffer\", \"chunk-cons\", \"chunk-first\", \"chunk-next\", \"chunk-rest\", \"chunked-seq?\", \"class\", \"class?\",\n        \"clear-agent-errors\", \"clojure-version\", \"coll?\", \"comment\", \"commute\", \"comp\", \"comparator\", \"compare\",\n        \"compare-and-set!\", \"compile\", \"complement\", \"completing\", \"concat\", \"cond\", \"cond->\", \"cond->>\", \"condp\",\n        \"conj\", \"conj!\", \"cons\", \"constantly\", \"construct-proxy\", \"contains?\", \"count\", \"counted?\", \"create-ns\",\n        \"create-struct\", \"cycle\", \"dec\", \"dec'\", \"decimal?\", \"declare\", \"dedupe\", \"default-data-readers\", \"definline\",\n        \"definterface\", \"defmacro\", \"defmethod\", \"defmulti\", \"defn\", \"defn-\", \"defonce\", \"defprotocol\", \"defrecord\",\n        \"defstruct\", \"deftype\", \"delay\", \"delay?\", \"deliver\", \"denominator\", \"deref\", \"derive\", \"descendants\",\n        \"destructure\", \"disj\", \"disj!\", \"dissoc\", \"dissoc!\", \"distinct\", \"distinct?\", \"doall\", \"dorun\", \"doseq\",\n        \"dosync\", \"dotimes\", \"doto\", \"double\", \"double-array\", \"double?\", \"doubles\", \"drop\", \"drop-last\", \"drop-while\",\n        \"eduction\", \"empty\", \"empty?\", \"ensure\", \"ensure-reduced\", \"enumeration-seq\", \"error-handler\", \"error-mode\",\n        \"eval\", \"even?\", \"every-pred\", \"every?\", \"ex-data\", \"ex-info\", \"extend\", \"extend-protocol\", \"extend-type\",\n        \"extenders\", \"extends?\", \"false?\", \"ffirst\", \"file-seq\", \"filter\", \"filterv\", \"find\", \"find-keyword\", \"find-ns\",\n        \"find-protocol-impl\", \"find-protocol-method\", \"find-var\", \"first\", \"flatten\", \"float\", \"float-array\", \"float?\",\n        \"floats\", \"flush\", \"fn\", \"fn?\", \"fnext\", \"fnil\", \"for\", \"force\", \"format\", \"frequencies\", \"future\", \"future-call\",\n        \"future-cancel\", \"future-cancelled?\", \"future-done?\", \"future?\", \"gen-class\", \"gen-interface\", \"gensym\", \"get\",\n        \"get-in\", \"get-method\", \"get-proxy-class\", \"get-thread-bindings\", \"get-validator\", \"group-by\", \"halt-when\", \"hash\",\n        \"hash-combine\", \"hash-map\", \"hash-ordered-coll\", \"hash-set\", \"hash-unordered-coll\", \"ident?\", \"identical?\",\n        \"identity\", \"if-let\", \"if-not\", \"if-some\", \"ifn?\", \"import\", \"in-ns\", \"inc\", \"inc'\", \"indexed?\", \"init-proxy\",\n        \"inst-ms\", \"inst-ms*\", \"inst?\", \"instance?\", \"int\", \"int-array\", \"int?\", \"integer?\", \"interleave\", \"intern\",\n        \"interpose\", \"into\", \"into-array\", \"ints\", \"io!\", \"isa?\", \"iterate\", \"iterator-seq\", \"juxt\", \"keep\", \"keep-indexed\",\n        \"key\", \"keys\", \"keyword\", \"keyword?\", \"last\", \"lazy-cat\", \"lazy-seq\", \"let\", \"letfn\", \"line-seq\", \"list\", \"list*\",\n        \"list?\", \"load\", \"load-file\", \"load-reader\", \"load-string\", \"loaded-libs\", \"locking\", \"long\", \"long-array\", \"longs\",\n        \"loop\", \"macroexpand\", \"macroexpand-1\", \"make-array\", \"make-hierarchy\", \"map\", \"map-entry?\", \"map-indexed\", \"map?\",\n        \"mapcat\", \"mapv\", \"max\", \"max-key\", \"memfn\", \"memoize\", \"merge\", \"merge-with\", \"meta\", \"method-sig\", \"methods\"];\n\n    var coreSymbols2 = [\n        \"min\", \"min-key\", \"mix-collection-hash\", \"mod\", \"munge\", \"name\", \"namespace\", \"namespace-munge\", \"nat-int?\",\n        \"neg-int?\", \"neg?\", \"newline\", \"next\", \"nfirst\", \"nil?\", \"nnext\", \"not\", \"not-any?\", \"not-empty\", \"not-every?\",\n        \"not=\", \"ns\", \"ns-aliases\", \"ns-imports\", \"ns-interns\", \"ns-map\", \"ns-name\", \"ns-publics\", \"ns-refers\", \"ns-resolve\",\n        \"ns-unalias\", \"ns-unmap\", \"nth\", \"nthnext\", \"nthrest\", \"num\", \"number?\", \"numerator\", \"object-array\", \"odd?\", \"or\",\n        \"parents\", \"partial\", \"partition\", \"partition-all\", \"partition-by\", \"pcalls\", \"peek\", \"persistent!\", \"pmap\", \"pop\",\n        \"pop!\", \"pop-thread-bindings\", \"pos-int?\", \"pos?\", \"pr\", \"pr-str\", \"prefer-method\", \"prefers\",\n        \"primitives-classnames\", \"print\", \"print-ctor\", \"print-dup\", \"print-method\", \"print-simple\", \"print-str\", \"printf\",\n        \"println\", \"println-str\", \"prn\", \"prn-str\", \"promise\", \"proxy\", \"proxy-call-with-super\", \"proxy-mappings\",\n        \"proxy-name\", \"proxy-super\", \"push-thread-bindings\", \"pvalues\", \"qualified-ident?\", \"qualified-keyword?\",\n        \"qualified-symbol?\", \"quot\", \"rand\", \"rand-int\", \"rand-nth\", \"random-sample\", \"range\", \"ratio?\", \"rational?\",\n        \"rationalize\", \"re-find\", \"re-groups\", \"re-matcher\", \"re-matches\", \"re-pattern\", \"re-seq\", \"read\", \"read-line\",\n        \"read-string\", \"reader-conditional\", \"reader-conditional?\", \"realized?\", \"record?\", \"reduce\", \"reduce-kv\", \"reduced\",\n        \"reduced?\", \"reductions\", \"ref\", \"ref-history-count\", \"ref-max-history\", \"ref-min-history\", \"ref-set\", \"refer\",\n        \"refer-clojure\", \"reify\", \"release-pending-sends\", \"rem\", \"remove\", \"remove-all-methods\", \"remove-method\", \"remove-ns\",\n        \"remove-watch\", \"repeat\", \"repeatedly\", \"replace\", \"replicate\", \"require\", \"reset!\", \"reset-meta!\", \"reset-vals!\",\n        \"resolve\", \"rest\", \"restart-agent\", \"resultset-seq\", \"reverse\", \"reversible?\", \"rseq\", \"rsubseq\", \"run!\", \"satisfies?\",\n        \"second\", \"select-keys\", \"send\", \"send-off\", \"send-via\", \"seq\", \"seq?\", \"seqable?\", \"seque\", \"sequence\", \"sequential?\",\n        \"set\", \"set-agent-send-executor!\", \"set-agent-send-off-executor!\", \"set-error-handler!\", \"set-error-mode!\",\n        \"set-validator!\", \"set?\", \"short\", \"short-array\", \"shorts\", \"shuffle\", \"shutdown-agents\", \"simple-ident?\",\n        \"simple-keyword?\", \"simple-symbol?\", \"slurp\", \"some\", \"some->\", \"some->>\", \"some-fn\", \"some?\", \"sort\", \"sort-by\",\n        \"sorted-map\", \"sorted-map-by\", \"sorted-set\", \"sorted-set-by\", \"sorted?\", \"special-symbol?\", \"spit\", \"split-at\",\n        \"split-with\", \"str\", \"string?\", \"struct\", \"struct-map\", \"subs\", \"subseq\", \"subvec\", \"supers\", \"swap!\", \"swap-vals!\",\n        \"symbol\", \"symbol?\", \"sync\", \"tagged-literal\", \"tagged-literal?\", \"take\", \"take-last\", \"take-nth\", \"take-while\", \"test\",\n        \"the-ns\", \"thread-bound?\", \"time\", \"to-array\", \"to-array-2d\", \"trampoline\", \"transduce\", \"transient\", \"tree-seq\",\n        \"true?\", \"type\", \"unchecked-add\", \"unchecked-add-int\", \"unchecked-byte\", \"unchecked-char\", \"unchecked-dec\",\n        \"unchecked-dec-int\", \"unchecked-divide-int\", \"unchecked-double\", \"unchecked-float\", \"unchecked-inc\", \"unchecked-inc-int\",\n        \"unchecked-int\", \"unchecked-long\", \"unchecked-multiply\", \"unchecked-multiply-int\", \"unchecked-negate\",\n        \"unchecked-negate-int\", \"unchecked-remainder-int\", \"unchecked-short\", \"unchecked-subtract\", \"unchecked-subtract-int\",\n        \"underive\", \"unquote\", \"unquote-splicing\", \"unreduced\", \"unsigned-bit-shift-right\", \"update\", \"update-in\",\n        \"update-proxy\", \"uri?\", \"use\", \"uuid?\", \"val\", \"vals\", \"var-get\", \"var-set\", \"var?\", \"vary-meta\", \"vec\", \"vector\",\n        \"vector-of\", \"vector?\", \"volatile!\", \"volatile?\", \"vreset!\", \"vswap!\", \"when\", \"when-first\", \"when-let\", \"when-not\",\n        \"when-some\", \"while\", \"with-bindings\", \"with-bindings*\", \"with-in-str\", \"with-loading-context\", \"with-local-vars\",\n        \"with-meta\", \"with-open\", \"with-out-str\", \"with-precision\", \"with-redefs\", \"with-redefs-fn\", \"xml-seq\", \"zero?\",\n        \"zipmap\"\n    ];\n\n    MT(\"should highlight core symbols as keywords (part 1/2)\",\n        typeTokenPairs(\"keyword\", coreSymbols1)\n    );\n\n    MT(\"should highlight core symbols as keywords (part 2/2)\",\n        typeTokenPairs(\"keyword\", coreSymbols2)\n    );\n\n    MT(\"should properly indent forms in list literals\",\n        \"[bracket (][builtin foo] [atom :a] [number 1] [atom true] [atom nil][bracket )]\",\n        \"\",\n        \"[bracket (][builtin foo] [atom :a]\",\n        \"     [number 1]\",\n        \"     [atom true]\",\n        \"     [atom nil][bracket )]\",\n        \"\",\n        \"[bracket (][builtin foo] [atom :a] [number 1]\",\n        \"     [atom true]\",\n        \"     [atom nil][bracket )]\",\n        \"\",\n        \"[bracket (]\",\n        \" [builtin foo]\",\n        \" [atom :a]\",\n        \" [number 1]\",\n        \" [atom true]\",\n        \" [atom nil][bracket )]\",\n        \"\",\n        \"[bracket (][builtin foo] [bracket [[][atom :a][bracket ]]]\",\n        \"     [number 1]\",\n        \"     [atom true]\",\n        \"     [atom nil][bracket )]\"\n    );\n\n    MT(\"should properly indent forms in vector literals\",\n        \"[bracket [[][atom :a] [number 1] [atom true] [atom nil][bracket ]]]\",\n        \"\",\n        \"[bracket [[][atom :a]\",\n        \" [number 1]\",\n        \" [atom true]\",\n        \" [atom nil][bracket ]]]\",\n        \"\",\n        \"[bracket [[][atom :a] [number 1]\",\n        \" [atom true]\",\n        \" [atom nil][bracket ]]]\",\n        \"\",\n        \"[bracket [[]\",\n        \" [variable foo]\",\n        \" [atom :a]\",\n        \" [number 1]\",\n        \" [atom true]\",\n        \" [atom nil][bracket ]]]\"\n    );\n\n    MT(\"should properly indent forms in map literals\",\n        \"[bracket {][atom :a] [atom :a] [atom :b] [number 1] [atom :c] [atom true] [atom :d] [atom nil] [bracket }]\",\n        \"\",\n        \"[bracket {][atom :a] [atom :a]\",\n        \" [atom :b] [number 1]\",\n        \" [atom :c] [atom true]\",\n        \" [atom :d] [atom nil][bracket }]\",\n        \"\",\n        \"[bracket {][atom :a]\",\n        \" [atom :a]\",\n        \" [atom :b]\",\n        \" [number 1]\",\n        \" [atom :c]\",\n        \" [atom true]\",\n        \" [atom :d]\",\n        \" [atom nil][bracket }]\",\n        \"\",\n        \"[bracket {]\",\n        \" [atom :a] [atom :a]\",\n        \" [atom :b] [number 1]\",\n        \" [atom :c] [atom true]\",\n        \" [atom :d] [atom nil][bracket }]\"\n    );\n\n    MT(\"should properly indent forms in set literals\",\n        \"[meta #][bracket {][atom :a] [number 1] [atom true] [atom nil] [bracket }]\",\n        \"\",\n        \"[meta #][bracket {][atom :a]\",\n        \"  [number 1]\",\n        \"  [atom true]\",\n        \"  [atom nil][bracket }]\",\n        \"\",\n        \"[meta #][bracket {]\",\n        \"  [atom :a]\",\n        \"  [number 1]\",\n        \"  [atom true]\",\n        \"  [atom nil][bracket }]\"\n    );\n\n    var haveBodyParameter = [\n        \"->\", \"->>\", \"as->\", \"binding\", \"bound-fn\", \"case\", \"catch\", \"cond\",\n        \"cond->\", \"cond->>\", \"condp\", \"def\", \"definterface\", \"defmethod\", \"defn\",\n        \"defmacro\", \"defprotocol\", \"defrecord\", \"defstruct\", \"deftype\", \"do\",\n        \"doseq\", \"dotimes\", \"doto\", \"extend\", \"extend-protocol\", \"extend-type\",\n        \"fn\", \"for\", \"future\", \"if\", \"if-let\", \"if-not\", \"if-some\", \"let\",\n        \"letfn\", \"locking\", \"loop\", \"ns\", \"proxy\", \"reify\", \"some->\", \"some->>\",\n        \"struct-map\", \"try\", \"when\", \"when-first\", \"when-let\", \"when-not\",\n        \"when-some\", \"while\", \"with-bindings\", \"with-bindings*\", \"with-in-str\",\n        \"with-loading-context\", \"with-local-vars\", \"with-meta\", \"with-open\",\n        \"with-out-str\", \"with-precision\", \"with-redefs\", \"with-redefs-fn\"];\n\n    function testFormsThatHaveBodyParameter(forms) {\n        for (var i = 0; i < forms.length; i++) {\n            MT(\"should indent body argument of `\" + forms[i] + \"` by `options.indentUnit` spaces\",\n                \"[bracket (][keyword \" + forms[i] + \"] [variable foo] [variable bar]\",\n                \"  [variable baz]\",\n                \"  [variable qux][bracket )]\"\n            );\n        }\n    }\n\n    testFormsThatHaveBodyParameter(haveBodyParameter);\n\n    MT(\"should indent body argument of `comment` by `options.indentUnit` spaces\",\n        \"[bracket (][comment comment foo bar]\",\n        \"[comment  baz]\",\n        \"[comment  qux][bracket )]\"\n    );\n\n    function typeTokenPairs(type, tokens) {\n        return \"[\" + type + \" \" + tokens.join(\"] [\" + type + \" \") + \"]\";\n    }\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/cmake/cmake.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\")\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd)\n    define([\"../../lib/codemirror\"], mod);\n  else\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"cmake\", function () {\n  var variable_regex = /({)?[a-zA-Z0-9_]+(})?/;\n\n  function tokenString(stream, state) {\n    var current, prev, found_var = false;\n    while (!stream.eol() && (current = stream.next()) != state.pending) {\n      if (current === '$' && prev != '\\\\' && state.pending == '\"') {\n        found_var = true;\n        break;\n      }\n      prev = current;\n    }\n    if (found_var) {\n      stream.backUp(1);\n    }\n    if (current == state.pending) {\n      state.continueString = false;\n    } else {\n      state.continueString = true;\n    }\n    return \"string\";\n  }\n\n  function tokenize(stream, state) {\n    var ch = stream.next();\n\n    // Have we found a variable?\n    if (ch === '$') {\n      if (stream.match(variable_regex)) {\n        return 'variable-2';\n      }\n      return 'variable';\n    }\n    // Should we still be looking for the end of a string?\n    if (state.continueString) {\n      // If so, go through the loop again\n      stream.backUp(1);\n      return tokenString(stream, state);\n    }\n    // Do we just have a function on our hands?\n    // In 'cmake_minimum_required (VERSION 2.8.8)', 'cmake_minimum_required' is matched\n    if (stream.match(/(\\s+)?\\w+\\(/) || stream.match(/(\\s+)?\\w+\\ \\(/)) {\n      stream.backUp(1);\n      return 'def';\n    }\n    if (ch == \"#\") {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n    // Have we found a string?\n    if (ch == \"'\" || ch == '\"') {\n      // Store the type (single or double)\n      state.pending = ch;\n      // Perform the looping function to find the end\n      return tokenString(stream, state);\n    }\n    if (ch == '(' || ch == ')') {\n      return 'bracket';\n    }\n    if (ch.match(/[0-9]/)) {\n      return 'number';\n    }\n    stream.eatWhile(/[\\w-]/);\n    return null;\n  }\n  return {\n    startState: function () {\n      var state = {};\n      state.inDefinition = false;\n      state.inInclude = false;\n      state.continueString = false;\n      state.pending = false;\n      return state;\n    },\n    token: function (stream, state) {\n      if (stream.eatSpace()) return null;\n      return tokenize(stream, state);\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-cmake\", \"cmake\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/cmake/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: CMake mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"cmake.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      .cm-s-default span.cm-arrow { color: red; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">CMake</a>\n  </ul>\n</div>\n\n<article>\n<h2>CMake mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n# vim: syntax=cmake\nif(NOT CMAKE_BUILD_TYPE)\n    # default to Release build for GCC builds\n    set(CMAKE_BUILD_TYPE Release CACHE STRING\n        \"Choose the type of build, options are: None(CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.\"\n        FORCE)\nendif()\nmessage(STATUS \"cmake version ${CMAKE_VERSION}\")\nif(POLICY CMP0025)\n    cmake_policy(SET CMP0025 OLD) # report Apple's Clang as just Clang\nendif()\nif(POLICY CMP0042)\n    cmake_policy(SET CMP0042 NEW) # MACOSX_RPATH\nendif()\n\nproject (x265)\ncmake_minimum_required (VERSION 2.8.8) # OBJECT libraries require 2.8.8\ninclude(CheckIncludeFiles)\ninclude(CheckFunctionExists)\ninclude(CheckSymbolExists)\ninclude(CheckCXXCompilerFlag)\n\n# X265_BUILD must be incremented each time the public API is changed\nset(X265_BUILD 48)\nconfigure_file(\"${PROJECT_SOURCE_DIR}/x265.def.in\"\n               \"${PROJECT_BINARY_DIR}/x265.def\")\nconfigure_file(\"${PROJECT_SOURCE_DIR}/x265_config.h.in\"\n               \"${PROJECT_BINARY_DIR}/x265_config.h\")\n\nSET(CMAKE_MODULE_PATH \"${PROJECT_SOURCE_DIR}/cmake\" \"${CMAKE_MODULE_PATH}\")\n\n# System architecture detection\nstring(TOLOWER \"${CMAKE_SYSTEM_PROCESSOR}\" SYSPROC)\nset(X86_ALIASES x86 i386 i686 x86_64 amd64)\nlist(FIND X86_ALIASES \"${SYSPROC}\" X86MATCH)\nif(\"${SYSPROC}\" STREQUAL \"\" OR X86MATCH GREATER \"-1\")\n    message(STATUS \"Detected x86 target processor\")\n    set(X86 1)\n    add_definitions(-DX265_ARCH_X86=1)\n    if(\"${CMAKE_SIZEOF_VOID_P}\" MATCHES 8)\n        set(X64 1)\n        add_definitions(-DX86_64=1)\n    endif()\nelseif(${SYSPROC} STREQUAL \"armv6l\")\n    message(STATUS \"Detected ARM target processor\")\n    set(ARM 1)\n    add_definitions(-DX265_ARCH_ARM=1 -DHAVE_ARMV6=1)\nelse()\n    message(STATUS \"CMAKE_SYSTEM_PROCESSOR value `${CMAKE_SYSTEM_PROCESSOR}` is unknown\")\n    message(STATUS \"Please add this value near ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE}\")\nendif()\n\nif(UNIX)\n    list(APPEND PLATFORM_LIBS pthread)\n    find_library(LIBRT rt)\n    if(LIBRT)\n        list(APPEND PLATFORM_LIBS rt)\n    endif()\n    find_package(Numa)\n    if(NUMA_FOUND)\n        list(APPEND CMAKE_REQUIRED_LIBRARIES ${NUMA_LIBRARY})\n        check_symbol_exists(numa_node_of_cpu numa.h NUMA_V2)\n        if(NUMA_V2)\n            add_definitions(-DHAVE_LIBNUMA)\n            message(STATUS \"libnuma found, building with support for NUMA nodes\")\n            list(APPEND PLATFORM_LIBS ${NUMA_LIBRARY})\n            link_directories(${NUMA_LIBRARY_DIR})\n            include_directories(${NUMA_INCLUDE_DIR})\n        endif()\n    endif()\n    mark_as_advanced(LIBRT NUMA_FOUND)\nendif(UNIX)\n\nif(X64 AND NOT WIN32)\n    option(ENABLE_PIC \"Enable Position Independent Code\" ON)\nelse()\n    option(ENABLE_PIC \"Enable Position Independent Code\" OFF)\nendif(X64 AND NOT WIN32)\n\n# Compiler detection\nif(CMAKE_GENERATOR STREQUAL \"Xcode\")\n  set(XCODE 1)\nendif()\nif (APPLE)\n  add_definitions(-DMACOS)\nendif()\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"text/x-cmake\",\n        matchBrackets: true,\n        indentUnit: 4\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-cmake</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/cobol/cobol.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**\n * Author: Gautam Mehta\n * Branched from CodeMirror's Scheme mode\n */\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"cobol\", function () {\n  var BUILTIN = \"builtin\", COMMENT = \"comment\", STRING = \"string\",\n      ATOM = \"atom\", NUMBER = \"number\", KEYWORD = \"keyword\", MODTAG = \"header\",\n      COBOLLINENUM = \"def\", PERIOD = \"link\";\n  function makeKeywords(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n  var atoms = makeKeywords(\"TRUE FALSE ZEROES ZEROS ZERO SPACES SPACE LOW-VALUE LOW-VALUES \");\n  var keywords = makeKeywords(\n      \"ACCEPT ACCESS ACQUIRE ADD ADDRESS \" +\n      \"ADVANCING AFTER ALIAS ALL ALPHABET \" +\n      \"ALPHABETIC ALPHABETIC-LOWER ALPHABETIC-UPPER ALPHANUMERIC ALPHANUMERIC-EDITED \" +\n      \"ALSO ALTER ALTERNATE AND ANY \" +\n      \"ARE AREA AREAS ARITHMETIC ASCENDING \" +\n      \"ASSIGN AT ATTRIBUTE AUTHOR AUTO \" +\n      \"AUTO-SKIP AUTOMATIC B-AND B-EXOR B-LESS \" +\n      \"B-NOT B-OR BACKGROUND-COLOR BACKGROUND-COLOUR BEEP \" +\n      \"BEFORE BELL BINARY BIT BITS \" +\n      \"BLANK BLINK BLOCK BOOLEAN BOTTOM \" +\n      \"BY CALL CANCEL CD CF \" +\n      \"CH CHARACTER CHARACTERS CLASS CLOCK-UNITS \" +\n      \"CLOSE COBOL CODE CODE-SET COL \" +\n      \"COLLATING COLUMN COMMA COMMIT COMMITMENT \" +\n      \"COMMON COMMUNICATION COMP COMP-0 COMP-1 \" +\n      \"COMP-2 COMP-3 COMP-4 COMP-5 COMP-6 \" +\n      \"COMP-7 COMP-8 COMP-9 COMPUTATIONAL COMPUTATIONAL-0 \" +\n      \"COMPUTATIONAL-1 COMPUTATIONAL-2 COMPUTATIONAL-3 COMPUTATIONAL-4 COMPUTATIONAL-5 \" +\n      \"COMPUTATIONAL-6 COMPUTATIONAL-7 COMPUTATIONAL-8 COMPUTATIONAL-9 COMPUTE \" +\n      \"CONFIGURATION CONNECT CONSOLE CONTAINED CONTAINS \" +\n      \"CONTENT CONTINUE CONTROL CONTROL-AREA CONTROLS \" +\n      \"CONVERTING COPY CORR CORRESPONDING COUNT \" +\n      \"CRT CRT-UNDER CURRENCY CURRENT CURSOR \" +\n      \"DATA DATE DATE-COMPILED DATE-WRITTEN DAY \" +\n      \"DAY-OF-WEEK DB DB-ACCESS-CONTROL-KEY DB-DATA-NAME DB-EXCEPTION \" +\n      \"DB-FORMAT-NAME DB-RECORD-NAME DB-SET-NAME DB-STATUS DBCS \" +\n      \"DBCS-EDITED DE DEBUG-CONTENTS DEBUG-ITEM DEBUG-LINE \" +\n      \"DEBUG-NAME DEBUG-SUB-1 DEBUG-SUB-2 DEBUG-SUB-3 DEBUGGING \" +\n      \"DECIMAL-POINT DECLARATIVES DEFAULT DELETE DELIMITED \" +\n      \"DELIMITER DEPENDING DESCENDING DESCRIBED DESTINATION \" +\n      \"DETAIL DISABLE DISCONNECT DISPLAY DISPLAY-1 \" +\n      \"DISPLAY-2 DISPLAY-3 DISPLAY-4 DISPLAY-5 DISPLAY-6 \" +\n      \"DISPLAY-7 DISPLAY-8 DISPLAY-9 DIVIDE DIVISION \" +\n      \"DOWN DROP DUPLICATE DUPLICATES DYNAMIC \" +\n      \"EBCDIC EGI EJECT ELSE EMI \" +\n      \"EMPTY EMPTY-CHECK ENABLE END END. END-ACCEPT END-ACCEPT. \" +\n      \"END-ADD END-CALL END-COMPUTE END-DELETE END-DISPLAY \" +\n      \"END-DIVIDE END-EVALUATE END-IF END-INVOKE END-MULTIPLY \" +\n      \"END-OF-PAGE END-PERFORM END-READ END-RECEIVE END-RETURN \" +\n      \"END-REWRITE END-SEARCH END-START END-STRING END-SUBTRACT \" +\n      \"END-UNSTRING END-WRITE END-XML ENTER ENTRY \" +\n      \"ENVIRONMENT EOP EQUAL EQUALS ERASE \" +\n      \"ERROR ESI EVALUATE EVERY EXCEEDS \" +\n      \"EXCEPTION EXCLUSIVE EXIT EXTEND EXTERNAL \" +\n      \"EXTERNALLY-DESCRIBED-KEY FD FETCH FILE FILE-CONTROL \" +\n      \"FILE-STREAM FILES FILLER FINAL FIND \" +\n      \"FINISH FIRST FOOTING FOR FOREGROUND-COLOR \" +\n      \"FOREGROUND-COLOUR FORMAT FREE FROM FULL \" +\n      \"FUNCTION GENERATE GET GIVING GLOBAL \" +\n      \"GO GOBACK GREATER GROUP HEADING \" +\n      \"HIGH-VALUE HIGH-VALUES HIGHLIGHT I-O I-O-CONTROL \" +\n      \"ID IDENTIFICATION IF IN INDEX \" +\n      \"INDEX-1 INDEX-2 INDEX-3 INDEX-4 INDEX-5 \" +\n      \"INDEX-6 INDEX-7 INDEX-8 INDEX-9 INDEXED \" +\n      \"INDIC INDICATE INDICATOR INDICATORS INITIAL \" +\n      \"INITIALIZE INITIATE INPUT INPUT-OUTPUT INSPECT \" +\n      \"INSTALLATION INTO INVALID INVOKE IS \" +\n      \"JUST JUSTIFIED KANJI KEEP KEY \" +\n      \"LABEL LAST LD LEADING LEFT \" +\n      \"LEFT-JUSTIFY LENGTH LENGTH-CHECK LESS LIBRARY \" +\n      \"LIKE LIMIT LIMITS LINAGE LINAGE-COUNTER \" +\n      \"LINE LINE-COUNTER LINES LINKAGE LOCAL-STORAGE \" +\n      \"LOCALE LOCALLY LOCK \" +\n      \"MEMBER MEMORY MERGE MESSAGE METACLASS \" +\n      \"MODE MODIFIED MODIFY MODULES MOVE \" +\n      \"MULTIPLE MULTIPLY NATIONAL NATIVE NEGATIVE \" +\n      \"NEXT NO NO-ECHO NONE NOT \" +\n      \"NULL NULL-KEY-MAP NULL-MAP NULLS NUMBER \" +\n      \"NUMERIC NUMERIC-EDITED OBJECT OBJECT-COMPUTER OCCURS \" +\n      \"OF OFF OMITTED ON ONLY \" +\n      \"OPEN OPTIONAL OR ORDER ORGANIZATION \" +\n      \"OTHER OUTPUT OVERFLOW OWNER PACKED-DECIMAL \" +\n      \"PADDING PAGE PAGE-COUNTER PARSE PERFORM \" +\n      \"PF PH PIC PICTURE PLUS \" +\n      \"POINTER POSITION POSITIVE PREFIX PRESENT \" +\n      \"PRINTING PRIOR PROCEDURE PROCEDURE-POINTER PROCEDURES \" +\n      \"PROCEED PROCESS PROCESSING PROGRAM PROGRAM-ID \" +\n      \"PROMPT PROTECTED PURGE QUEUE QUOTE \" +\n      \"QUOTES RANDOM RD READ READY \" +\n      \"REALM RECEIVE RECONNECT RECORD RECORD-NAME \" +\n      \"RECORDS RECURSIVE REDEFINES REEL REFERENCE \" +\n      \"REFERENCE-MONITOR REFERENCES RELATION RELATIVE RELEASE \" +\n      \"REMAINDER REMOVAL RENAMES REPEATED REPLACE \" +\n      \"REPLACING REPORT REPORTING REPORTS REPOSITORY \" +\n      \"REQUIRED RERUN RESERVE RESET RETAINING \" +\n      \"RETRIEVAL RETURN RETURN-CODE RETURNING REVERSE-VIDEO \" +\n      \"REVERSED REWIND REWRITE RF RH \" +\n      \"RIGHT RIGHT-JUSTIFY ROLLBACK ROLLING ROUNDED \" +\n      \"RUN SAME SCREEN SD SEARCH \" +\n      \"SECTION SECURE SECURITY SEGMENT SEGMENT-LIMIT \" +\n      \"SELECT SEND SENTENCE SEPARATE SEQUENCE \" +\n      \"SEQUENTIAL SET SHARED SIGN SIZE \" +\n      \"SKIP1 SKIP2 SKIP3 SORT SORT-MERGE \" +\n      \"SORT-RETURN SOURCE SOURCE-COMPUTER SPACE-FILL \" +\n      \"SPECIAL-NAMES STANDARD STANDARD-1 STANDARD-2 \" +\n      \"START STARTING STATUS STOP STORE \" +\n      \"STRING SUB-QUEUE-1 SUB-QUEUE-2 SUB-QUEUE-3 SUB-SCHEMA \" +\n      \"SUBFILE SUBSTITUTE SUBTRACT SUM SUPPRESS \" +\n      \"SYMBOLIC SYNC SYNCHRONIZED SYSIN SYSOUT \" +\n      \"TABLE TALLYING TAPE TENANT TERMINAL \" +\n      \"TERMINATE TEST TEXT THAN THEN \" +\n      \"THROUGH THRU TIME TIMES TITLE \" +\n      \"TO TOP TRAILING TRAILING-SIGN TRANSACTION \" +\n      \"TYPE TYPEDEF UNDERLINE UNEQUAL UNIT \" +\n      \"UNSTRING UNTIL UP UPDATE UPON \" +\n      \"USAGE USAGE-MODE USE USING VALID \" +\n      \"VALIDATE VALUE VALUES VARYING VLR \" +\n      \"WAIT WHEN WHEN-COMPILED WITH WITHIN \" +\n      \"WORDS WORKING-STORAGE WRITE XML XML-CODE \" +\n      \"XML-EVENT XML-NTEXT XML-TEXT ZERO ZERO-FILL \" );\n\n  var builtins = makeKeywords(\"- * ** / + < <= = > >= \");\n  var tests = {\n    digit: /\\d/,\n    digit_or_colon: /[\\d:]/,\n    hex: /[0-9a-f]/i,\n    sign: /[+-]/,\n    exponent: /e/i,\n    keyword_char: /[^\\s\\(\\[\\;\\)\\]]/,\n    symbol: /[\\w*+\\-]/\n  };\n  function isNumber(ch, stream){\n    // hex\n    if ( ch === '0' && stream.eat(/x/i) ) {\n      stream.eatWhile(tests.hex);\n      return true;\n    }\n    // leading sign\n    if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {\n      stream.eat(tests.sign);\n      ch = stream.next();\n    }\n    if ( tests.digit.test(ch) ) {\n      stream.eat(ch);\n      stream.eatWhile(tests.digit);\n      if ( '.' == stream.peek()) {\n        stream.eat('.');\n        stream.eatWhile(tests.digit);\n      }\n      if ( stream.eat(tests.exponent) ) {\n        stream.eat(tests.sign);\n        stream.eatWhile(tests.digit);\n      }\n      return true;\n    }\n    return false;\n  }\n  return {\n    startState: function () {\n      return {\n        indentStack: null,\n        indentation: 0,\n        mode: false\n      };\n    },\n    token: function (stream, state) {\n      if (state.indentStack == null && stream.sol()) {\n        // update indentation, but only if indentStack is empty\n        state.indentation = 6 ; //stream.indentation();\n      }\n      // skip spaces\n      if (stream.eatSpace()) {\n        return null;\n      }\n      var returnType = null;\n      switch(state.mode){\n      case \"string\": // multi-line string parsing mode\n        var next = false;\n        while ((next = stream.next()) != null) {\n          if (next == \"\\\"\" || next == \"\\'\") {\n            state.mode = false;\n            break;\n          }\n        }\n        returnType = STRING; // continue on in string mode\n        break;\n      default: // default parsing mode\n        var ch = stream.next();\n        var col = stream.column();\n        if (col >= 0 && col <= 5) {\n          returnType = COBOLLINENUM;\n        } else if (col >= 72 && col <= 79) {\n          stream.skipToEnd();\n          returnType = MODTAG;\n        } else if (ch == \"*\" && col == 6) { // comment\n          stream.skipToEnd(); // rest of the line is a comment\n          returnType = COMMENT;\n        } else if (ch == \"\\\"\" || ch == \"\\'\") {\n          state.mode = \"string\";\n          returnType = STRING;\n        } else if (ch == \"'\" && !( tests.digit_or_colon.test(stream.peek()) )) {\n          returnType = ATOM;\n        } else if (ch == \".\") {\n          returnType = PERIOD;\n        } else if (isNumber(ch,stream)){\n          returnType = NUMBER;\n        } else {\n          if (stream.current().match(tests.symbol)) {\n            while (col < 71) {\n              if (stream.eat(tests.symbol) === undefined) {\n                break;\n              } else {\n                col++;\n              }\n            }\n          }\n          if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {\n            returnType = KEYWORD;\n          } else if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) {\n            returnType = BUILTIN;\n          } else if (atoms && atoms.propertyIsEnumerable(stream.current().toUpperCase())) {\n            returnType = ATOM;\n          } else returnType = null;\n        }\n      }\n      return returnType;\n    },\n    indent: function (state) {\n      if (state.indentStack == null) return state.indentation;\n      return state.indentStack.indent;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-cobol\", \"cobol\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/cobol/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: COBOL mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/neat.css\">\n<link rel=\"stylesheet\" href=\"../../theme/elegant.css\">\n<link rel=\"stylesheet\" href=\"../../theme/erlang-dark.css\">\n<link rel=\"stylesheet\" href=\"../../theme/night.css\">\n<link rel=\"stylesheet\" href=\"../../theme/monokai.css\">\n<link rel=\"stylesheet\" href=\"../../theme/cobalt.css\">\n<link rel=\"stylesheet\" href=\"../../theme/eclipse.css\">\n<link rel=\"stylesheet\" href=\"../../theme/rubyblue.css\">\n<link rel=\"stylesheet\" href=\"../../theme/lesser-dark.css\">\n<link rel=\"stylesheet\" href=\"../../theme/xq-dark.css\">\n<link rel=\"stylesheet\" href=\"../../theme/xq-light.css\">\n<link rel=\"stylesheet\" href=\"../../theme/ambiance.css\">\n<link rel=\"stylesheet\" href=\"../../theme/blackboard.css\">\n<link rel=\"stylesheet\" href=\"../../theme/vibrant-ink.css\">\n<link rel=\"stylesheet\" href=\"../../theme/solarized.css\">\n<link rel=\"stylesheet\" href=\"../../theme/twilight.css\">\n<link rel=\"stylesheet\" href=\"../../theme/midnight.css\">\n<link rel=\"stylesheet\" href=\"../../addon/dialog/dialog.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"cobol.js\"></script>\n<script src=\"../../addon/selection/active-line.js\"></script>\n<script src=\"../../addon/search/search.js\"></script>\n<script src=\"../../addon/dialog/dialog.js\"></script>\n<script src=\"../../addon/search/searchcursor.js\"></script>\n<style>\n        .CodeMirror {\n          border: 1px solid #eee;\n          font-size : 20px;\n          height : auto !important;\n        }\n        .CodeMirror-activeline-background {background: #555555 !important;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">COBOL</a>\n  </ul>\n</div>\n\n<article>\n<h2>COBOL mode</h2>\n\n    <p> Select Theme <select onchange=\"selectTheme()\" id=\"selectTheme\">\n        <option>default</option>\n        <option>ambiance</option>\n        <option>blackboard</option>\n        <option>cobalt</option>\n        <option>eclipse</option>\n        <option>elegant</option>\n        <option>erlang-dark</option>\n        <option>lesser-dark</option>\n        <option>midnight</option>\n        <option>monokai</option>\n        <option>neat</option>\n        <option>night</option>\n        <option>rubyblue</option>\n        <option>solarized dark</option>\n        <option>solarized light</option>\n        <option selected>twilight</option>\n        <option>vibrant-ink</option>\n        <option>xq-dark</option>\n        <option>xq-light</option>\n    </select>    Select Font Size <select onchange=\"selectFontsize()\" id=\"selectFontSize\">\n          <option value=\"13px\">13px</option>\n          <option value=\"14px\">14px</option>\n          <option value=\"16px\">16px</option>\n          <option value=\"18px\">18px</option>\n          <option value=\"20px\" selected=\"selected\">20px</option>\n          <option value=\"24px\">24px</option>\n          <option value=\"26px\">26px</option>\n          <option value=\"28px\">28px</option>\n          <option value=\"30px\">30px</option>\n          <option value=\"32px\">32px</option>\n          <option value=\"34px\">34px</option>\n          <option value=\"36px\">36px</option>\n        </select>\n<label for=\"checkBoxReadOnly\">Read-only</label>\n<input type=\"checkbox\" id=\"checkBoxReadOnly\" onchange=\"selectReadOnly()\">\n<label for=\"id_tabToIndentSpace\">Insert Spaces on Tab</label>\n<input type=\"checkbox\" id=\"id_tabToIndentSpace\" onchange=\"tabToIndentSpace()\">\n</p>\n<textarea id=\"code\" name=\"code\">\n---------1---------2---------3---------4---------5---------6---------7---------8\n12345678911234567892123456789312345678941234567895123456789612345678971234567898\n000010 IDENTIFICATION DIVISION.                                        MODTGHERE\n000020 PROGRAM-ID.       SAMPLE.\n000030 AUTHOR.           TEST SAM. \n000040 DATE-WRITTEN.     5 February 2013\n000041\n000042* A sample program just to show the form.\n000043* The program copies its input to the output,\n000044* and counts the number of records.\n000045* At the end this number is printed.\n000046\n000050 ENVIRONMENT DIVISION.\n000060 INPUT-OUTPUT SECTION.\n000070 FILE-CONTROL.\n000080     SELECT STUDENT-FILE     ASSIGN TO SYSIN\n000090         ORGANIZATION IS LINE SEQUENTIAL.\n000100     SELECT PRINT-FILE       ASSIGN TO SYSOUT\n000110         ORGANIZATION IS LINE SEQUENTIAL.\n000120\n000130 DATA DIVISION.\n000140 FILE SECTION.\n000150 FD  STUDENT-FILE\n000160     RECORD CONTAINS 43 CHARACTERS\n000170     DATA RECORD IS STUDENT-IN.\n000180 01  STUDENT-IN              PIC X(43).\n000190\n000200 FD  PRINT-FILE\n000210     RECORD CONTAINS 80 CHARACTERS\n000220     DATA RECORD IS PRINT-LINE.\n000230 01  PRINT-LINE              PIC X(80).\n000240\n000250 WORKING-STORAGE SECTION.\n000260 01  DATA-REMAINS-SWITCH     PIC X(2)      VALUE SPACES.\n000261 01  RECORDS-WRITTEN         PIC 99.\n000270\n000280 01  DETAIL-LINE.\n000290     05  FILLER              PIC X(7)      VALUE SPACES.\n000300     05  RECORD-IMAGE        PIC X(43).\n000310     05  FILLER              PIC X(30)     VALUE SPACES.\n000311 \n000312 01  SUMMARY-LINE.\n000313     05  FILLER              PIC X(7)      VALUE SPACES.\n000314     05  TOTAL-READ          PIC 99.\n000315     05  FILLER              PIC X         VALUE SPACE.\n000316     05  FILLER              PIC X(17)     \n000317                 VALUE  'Records were read'.\n000318     05  FILLER              PIC X(53)     VALUE SPACES.\n000319\n000320 PROCEDURE DIVISION.\n000321\n000330 PREPARE-SENIOR-REPORT.\n000340     OPEN INPUT  STUDENT-FILE\n000350          OUTPUT PRINT-FILE.\n000351     MOVE ZERO TO RECORDS-WRITTEN.\n000360     READ STUDENT-FILE\n000370         AT END MOVE 'NO' TO DATA-REMAINS-SWITCH\n000380     END-READ.\n000390     PERFORM PROCESS-RECORDS\n000410         UNTIL DATA-REMAINS-SWITCH = 'NO'.\n000411     PERFORM PRINT-SUMMARY.\n000420     CLOSE STUDENT-FILE\n000430           PRINT-FILE.\n000440     STOP RUN.\n000450\n000460 PROCESS-RECORDS.\n000470     MOVE STUDENT-IN TO RECORD-IMAGE.\n000480     MOVE DETAIL-LINE TO PRINT-LINE.\n000490     WRITE PRINT-LINE.\n000500     ADD 1 TO RECORDS-WRITTEN.\n000510     READ STUDENT-FILE\n000520         AT END MOVE 'NO' TO DATA-REMAINS-SWITCH\n000530     END-READ. \n000540\n000550 PRINT-SUMMARY.\n000560     MOVE RECORDS-WRITTEN TO TOTAL-READ.\n000570     MOVE SUMMARY-LINE TO PRINT-LINE.\n000571     WRITE PRINT-LINE. \n000572\n000580\n</textarea>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-cobol\",\n        theme : \"twilight\",\n        styleActiveLine: true,\n        showCursorWhenSelecting : true,  \n      });\n      function selectTheme() {\n        var themeInput = document.getElementById(\"selectTheme\");\n        var theme = themeInput.options[themeInput.selectedIndex].innerHTML;\n        editor.setOption(\"theme\", theme);\n      }\n      function selectFontsize() {\n        var fontSizeInput = document.getElementById(\"selectFontSize\");\n        var fontSize = fontSizeInput.options[fontSizeInput.selectedIndex].innerHTML;\n        editor.getWrapperElement().style.fontSize = fontSize;\n        editor.refresh();\n      }\n      function selectReadOnly() {\n        editor.setOption(\"readOnly\", document.getElementById(\"checkBoxReadOnly\").checked);\n      }\n      function tabToIndentSpace() {\n        if (document.getElementById(\"id_tabToIndentSpace\").checked) {\n            editor.setOption(\"extraKeys\", {Tab: function(cm) { cm.replaceSelection(\"    \", \"end\"); }});\n        } else {\n            editor.setOption(\"extraKeys\", {Tab: function(cm) { cm.replaceSelection(\"    \", \"end\"); }});\n        }\n      }\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/coffeescript/coffeescript.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**\n * Link to the project's GitHub page:\n * https://github.com/pickhardt/coffeescript-codemirror-mode\n */\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"coffeescript\", function(conf, parserConf) {\n  var ERRORCLASS = \"error\";\n\n  function wordRegexp(words) {\n    return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n  }\n\n  var operators = /^(?:->|=>|\\+[+=]?|-[\\-=]?|\\*[\\*=]?|\\/[\\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\\|=?|\\^=?|\\~|!|\\?|(or|and|\\|\\||&&|\\?)=)/;\n  var delimiters = /^(?:[()\\[\\]{},:`=;]|\\.\\.?\\.?)/;\n  var identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/;\n  var atProp = /^@[_A-Za-z$][_A-Za-z$0-9]*/;\n\n  var wordOperators = wordRegexp([\"and\", \"or\", \"not\",\n                                  \"is\", \"isnt\", \"in\",\n                                  \"instanceof\", \"typeof\"]);\n  var indentKeywords = [\"for\", \"while\", \"loop\", \"if\", \"unless\", \"else\",\n                        \"switch\", \"try\", \"catch\", \"finally\", \"class\"];\n  var commonKeywords = [\"break\", \"by\", \"continue\", \"debugger\", \"delete\",\n                        \"do\", \"in\", \"of\", \"new\", \"return\", \"then\",\n                        \"this\", \"@\", \"throw\", \"when\", \"until\", \"extends\"];\n\n  var keywords = wordRegexp(indentKeywords.concat(commonKeywords));\n\n  indentKeywords = wordRegexp(indentKeywords);\n\n\n  var stringPrefixes = /^('{3}|\\\"{3}|['\\\"])/;\n  var regexPrefixes = /^(\\/{3}|\\/)/;\n  var commonConstants = [\"Infinity\", \"NaN\", \"undefined\", \"null\", \"true\", \"false\", \"on\", \"off\", \"yes\", \"no\"];\n  var constants = wordRegexp(commonConstants);\n\n  // Tokenizers\n  function tokenBase(stream, state) {\n    // Handle scope changes\n    if (stream.sol()) {\n      if (state.scope.align === null) state.scope.align = false;\n      var scopeOffset = state.scope.offset;\n      if (stream.eatSpace()) {\n        var lineOffset = stream.indentation();\n        if (lineOffset > scopeOffset && state.scope.type == \"coffee\") {\n          return \"indent\";\n        } else if (lineOffset < scopeOffset) {\n          return \"dedent\";\n        }\n        return null;\n      } else {\n        if (scopeOffset > 0) {\n          dedent(stream, state);\n        }\n      }\n    }\n    if (stream.eatSpace()) {\n      return null;\n    }\n\n    var ch = stream.peek();\n\n    // Handle docco title comment (single line)\n    if (stream.match(\"####\")) {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n\n    // Handle multi line comments\n    if (stream.match(\"###\")) {\n      state.tokenize = longComment;\n      return state.tokenize(stream, state);\n    }\n\n    // Single line comment\n    if (ch === \"#\") {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n\n    // Handle number literals\n    if (stream.match(/^-?[0-9\\.]/, false)) {\n      var floatLiteral = false;\n      // Floats\n      if (stream.match(/^-?\\d*\\.\\d+(e[\\+\\-]?\\d+)?/i)) {\n        floatLiteral = true;\n      }\n      if (stream.match(/^-?\\d+\\.\\d*/)) {\n        floatLiteral = true;\n      }\n      if (stream.match(/^-?\\.\\d+/)) {\n        floatLiteral = true;\n      }\n\n      if (floatLiteral) {\n        // prevent from getting extra . on 1..\n        if (stream.peek() == \".\"){\n          stream.backUp(1);\n        }\n        return \"number\";\n      }\n      // Integers\n      var intLiteral = false;\n      // Hex\n      if (stream.match(/^-?0x[0-9a-f]+/i)) {\n        intLiteral = true;\n      }\n      // Decimal\n      if (stream.match(/^-?[1-9]\\d*(e[\\+\\-]?\\d+)?/)) {\n        intLiteral = true;\n      }\n      // Zero by itself with no other piece of number.\n      if (stream.match(/^-?0(?![\\dx])/i)) {\n        intLiteral = true;\n      }\n      if (intLiteral) {\n        return \"number\";\n      }\n    }\n\n    // Handle strings\n    if (stream.match(stringPrefixes)) {\n      state.tokenize = tokenFactory(stream.current(), false, \"string\");\n      return state.tokenize(stream, state);\n    }\n    // Handle regex literals\n    if (stream.match(regexPrefixes)) {\n      if (stream.current() != \"/\" || stream.match(/^.*\\//, false)) { // prevent highlight of division\n        state.tokenize = tokenFactory(stream.current(), true, \"string-2\");\n        return state.tokenize(stream, state);\n      } else {\n        stream.backUp(1);\n      }\n    }\n\n\n\n    // Handle operators and delimiters\n    if (stream.match(operators) || stream.match(wordOperators)) {\n      return \"operator\";\n    }\n    if (stream.match(delimiters)) {\n      return \"punctuation\";\n    }\n\n    if (stream.match(constants)) {\n      return \"atom\";\n    }\n\n    if (stream.match(atProp) || state.prop && stream.match(identifiers)) {\n      return \"property\";\n    }\n\n    if (stream.match(keywords)) {\n      return \"keyword\";\n    }\n\n    if (stream.match(identifiers)) {\n      return \"variable\";\n    }\n\n    // Handle non-detected items\n    stream.next();\n    return ERRORCLASS;\n  }\n\n  function tokenFactory(delimiter, singleline, outclass) {\n    return function(stream, state) {\n      while (!stream.eol()) {\n        stream.eatWhile(/[^'\"\\/\\\\]/);\n        if (stream.eat(\"\\\\\")) {\n          stream.next();\n          if (singleline && stream.eol()) {\n            return outclass;\n          }\n        } else if (stream.match(delimiter)) {\n          state.tokenize = tokenBase;\n          return outclass;\n        } else {\n          stream.eat(/['\"\\/]/);\n        }\n      }\n      if (singleline) {\n        if (parserConf.singleLineStringErrors) {\n          outclass = ERRORCLASS;\n        } else {\n          state.tokenize = tokenBase;\n        }\n      }\n      return outclass;\n    };\n  }\n\n  function longComment(stream, state) {\n    while (!stream.eol()) {\n      stream.eatWhile(/[^#]/);\n      if (stream.match(\"###\")) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      stream.eatWhile(\"#\");\n    }\n    return \"comment\";\n  }\n\n  function indent(stream, state, type) {\n    type = type || \"coffee\";\n    var offset = 0, align = false, alignOffset = null;\n    for (var scope = state.scope; scope; scope = scope.prev) {\n      if (scope.type === \"coffee\" || scope.type == \"}\") {\n        offset = scope.offset + conf.indentUnit;\n        break;\n      }\n    }\n    if (type !== \"coffee\") {\n      align = null;\n      alignOffset = stream.column() + stream.current().length;\n    } else if (state.scope.align) {\n      state.scope.align = false;\n    }\n    state.scope = {\n      offset: offset,\n      type: type,\n      prev: state.scope,\n      align: align,\n      alignOffset: alignOffset\n    };\n  }\n\n  function dedent(stream, state) {\n    if (!state.scope.prev) return;\n    if (state.scope.type === \"coffee\") {\n      var _indent = stream.indentation();\n      var matched = false;\n      for (var scope = state.scope; scope; scope = scope.prev) {\n        if (_indent === scope.offset) {\n          matched = true;\n          break;\n        }\n      }\n      if (!matched) {\n        return true;\n      }\n      while (state.scope.prev && state.scope.offset !== _indent) {\n        state.scope = state.scope.prev;\n      }\n      return false;\n    } else {\n      state.scope = state.scope.prev;\n      return false;\n    }\n  }\n\n  function tokenLexer(stream, state) {\n    var style = state.tokenize(stream, state);\n    var current = stream.current();\n\n    // Handle scope changes.\n    if (current === \"return\") {\n      state.dedent = true;\n    }\n    if (((current === \"->\" || current === \"=>\") && stream.eol())\n        || style === \"indent\") {\n      indent(stream, state);\n    }\n    var delimiter_index = \"[({\".indexOf(current);\n    if (delimiter_index !== -1) {\n      indent(stream, state, \"])}\".slice(delimiter_index, delimiter_index+1));\n    }\n    if (indentKeywords.exec(current)){\n      indent(stream, state);\n    }\n    if (current == \"then\"){\n      dedent(stream, state);\n    }\n\n\n    if (style === \"dedent\") {\n      if (dedent(stream, state)) {\n        return ERRORCLASS;\n      }\n    }\n    delimiter_index = \"])}\".indexOf(current);\n    if (delimiter_index !== -1) {\n      while (state.scope.type == \"coffee\" && state.scope.prev)\n        state.scope = state.scope.prev;\n      if (state.scope.type == current)\n        state.scope = state.scope.prev;\n    }\n    if (state.dedent && stream.eol()) {\n      if (state.scope.type == \"coffee\" && state.scope.prev)\n        state.scope = state.scope.prev;\n      state.dedent = false;\n    }\n\n    return style;\n  }\n\n  var external = {\n    startState: function(basecolumn) {\n      return {\n        tokenize: tokenBase,\n        scope: {offset:basecolumn || 0, type:\"coffee\", prev: null, align: false},\n        prop: false,\n        dedent: 0\n      };\n    },\n\n    token: function(stream, state) {\n      var fillAlign = state.scope.align === null && state.scope;\n      if (fillAlign && stream.sol()) fillAlign.align = false;\n\n      var style = tokenLexer(stream, state);\n      if (style && style != \"comment\") {\n        if (fillAlign) fillAlign.align = true;\n        state.prop = style == \"punctuation\" && stream.current() == \".\"\n      }\n\n      return style;\n    },\n\n    indent: function(state, text) {\n      if (state.tokenize != tokenBase) return 0;\n      var scope = state.scope;\n      var closer = text && \"])}\".indexOf(text.charAt(0)) > -1;\n      if (closer) while (scope.type == \"coffee\" && scope.prev) scope = scope.prev;\n      var closes = closer && scope.type === text.charAt(0);\n      if (scope.align)\n        return scope.alignOffset - (closes ? 1 : 0);\n      else\n        return (closes ? scope.prev : scope).offset;\n    },\n\n    lineComment: \"#\",\n    fold: \"indent\"\n  };\n  return external;\n});\n\n// IANA registered media type\n// https://www.iana.org/assignments/media-types/\nCodeMirror.defineMIME(\"application/vnd.coffeescript\", \"coffeescript\");\n\nCodeMirror.defineMIME(\"text/x-coffeescript\", \"coffeescript\");\nCodeMirror.defineMIME(\"text/coffeescript\", \"coffeescript\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/coffeescript/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: CoffeeScript mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"coffeescript.js\"></script>\n<style>.CodeMirror {border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">CoffeeScript</a>\n  </ul>\n</div>\n\n<article>\n<h2>CoffeeScript mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n# CoffeeScript mode for CodeMirror\n# Copyright (c) 2011 Jeff Pickhardt, released under\n# the MIT License.\n#\n# Modified from the Python CodeMirror mode, which also is \n# under the MIT License Copyright (c) 2010 Timothy Farrell.\n#\n# The following script, Underscore.coffee, is used to \n# demonstrate CoffeeScript mode for CodeMirror.\n#\n# To download CoffeeScript mode for CodeMirror, go to:\n# https://github.com/pickhardt/coffeescript-codemirror-mode\n\n# **Underscore.coffee\n# (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**\n# Underscore is freely distributable under the terms of the\n# [MIT license](http://en.wikipedia.org/wiki/MIT_License).\n# Portions of Underscore are inspired by or borrowed from\n# [Prototype.js](http://prototypejs.org/api), Oliver Steele's\n# [Functional](http://osteele.com), and John Resig's\n# [Micro-Templating](http://ejohn.org).\n# For all details and documentation:\n# http://documentcloud.github.com/underscore/\n\n\n# Baseline setup\n# --------------\n\n# Establish the root object, `window` in the browser, or `global` on the server.\nroot = this\n\n\n# Save the previous value of the `_` variable.\npreviousUnderscore = root._\n\n### Multiline\n    comment\n###\n\n# Establish the object that gets thrown to break out of a loop iteration.\n# `StopIteration` is SOP on Mozilla.\nbreaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration\n\n\n#### Docco style single line comment (title)\n\n\n# Helper function to escape **RegExp** contents, because JS doesn't have one.\nescapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\\]\\/\\\\])/g, '\\\\$1')\n\n\n# Save bytes in the minified (but not gzipped) version:\nArrayProto = Array.prototype\nObjProto = Object.prototype\n\n\n# Create quick reference variables for speed access to core prototypes.\nslice = ArrayProto.slice\nunshift = ArrayProto.unshift\ntoString = ObjProto.toString\nhasOwnProperty = ObjProto.hasOwnProperty\npropertyIsEnumerable = ObjProto.propertyIsEnumerable\n\n\n# All **ECMA5** native implementations we hope to use are declared here.\nnativeForEach = ArrayProto.forEach\nnativeMap = ArrayProto.map\nnativeReduce = ArrayProto.reduce\nnativeReduceRight = ArrayProto.reduceRight\nnativeFilter = ArrayProto.filter\nnativeEvery = ArrayProto.every\nnativeSome = ArrayProto.some\nnativeIndexOf = ArrayProto.indexOf\nnativeLastIndexOf = ArrayProto.lastIndexOf\nnativeIsArray = Array.isArray\nnativeKeys = Object.keys\n\n\n# Create a safe reference to the Underscore object for use below.\n_ = (obj) -> new wrapper(obj)\n\n\n# Export the Underscore object for **CommonJS**.\nif typeof(exports) != 'undefined' then exports._ = _\n\n\n# Export Underscore to global scope.\nroot._ = _\n\n\n# Current version.\n_.VERSION = '1.1.0'\n\n\n# Collection Functions\n# --------------------\n\n# The cornerstone, an **each** implementation.\n# Handles objects implementing **forEach**, arrays, and raw objects.\n_.each = (obj, iterator, context) ->\n  try\n    if nativeForEach and obj.forEach is nativeForEach\n      obj.forEach iterator, context\n    else if _.isNumber obj.length\n      iterator.call context, obj[i], i, obj for i in [0...obj.length]\n    else\n      iterator.call context, val, key, obj for own key, val of obj\n  catch e\n    throw e if e isnt breaker\n  obj\n\n\n# Return the results of applying the iterator to each element. Use JavaScript\n# 1.6's version of **map**, if possible.\n_.map = (obj, iterator, context) ->\n  return obj.map(iterator, context) if nativeMap and obj.map is nativeMap\n  results = []\n  _.each obj, (value, index, list) ->\n    results.push iterator.call context, value, index, list\n  results\n\n\n# **Reduce** builds up a single result from a list of values. Also known as\n# **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.\n_.reduce = (obj, iterator, memo, context) ->\n  if nativeReduce and obj.reduce is nativeReduce\n    iterator = _.bind iterator, context if context\n    return obj.reduce iterator, memo\n  _.each obj, (value, index, list) ->\n    memo = iterator.call context, memo, value, index, list\n  memo\n\n\n# The right-associative version of **reduce**, also known as **foldr**. Uses\n# JavaScript 1.8's version of **reduceRight**, if available.\n_.reduceRight = (obj, iterator, memo, context) ->\n  if nativeReduceRight and obj.reduceRight is nativeReduceRight\n    iterator = _.bind iterator, context if context\n    return obj.reduceRight iterator, memo\n  reversed = _.clone(_.toArray(obj)).reverse()\n  _.reduce reversed, iterator, memo, context\n\n\n# Return the first value which passes a truth test.\n_.detect = (obj, iterator, context) ->\n  result = null\n  _.each obj, (value, index, list) ->\n    if iterator.call context, value, index, list\n      result = value\n      _.breakLoop()\n  result\n\n\n# Return all the elements that pass a truth test. Use JavaScript 1.6's\n# **filter**, if it exists.\n_.filter = (obj, iterator, context) ->\n  return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter\n  results = []\n  _.each obj, (value, index, list) ->\n    results.push value if iterator.call context, value, index, list\n  results\n\n\n# Return all the elements for which a truth test fails.\n_.reject = (obj, iterator, context) ->\n  results = []\n  _.each obj, (value, index, list) ->\n    results.push value if not iterator.call context, value, index, list\n  results\n\n\n# Determine whether all of the elements match a truth test. Delegate to\n# JavaScript 1.6's **every**, if it is present.\n_.every = (obj, iterator, context) ->\n  iterator ||= _.identity\n  return obj.every iterator, context if nativeEvery and obj.every is nativeEvery\n  result = true\n  _.each obj, (value, index, list) ->\n    _.breakLoop() unless (result = result and iterator.call(context, value, index, list))\n  result\n\n\n# Determine if at least one element in the object matches a truth test. Use\n# JavaScript 1.6's **some**, if it exists.\n_.some = (obj, iterator, context) ->\n  iterator ||= _.identity\n  return obj.some iterator, context if nativeSome and obj.some is nativeSome\n  result = false\n  _.each obj, (value, index, list) ->\n    _.breakLoop() if (result = iterator.call(context, value, index, list))\n  result\n\n\n# Determine if a given value is included in the array or object,\n# based on `===`.\n_.include = (obj, target) ->\n  return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf\n  return true for own key, val of obj when val is target\n  false\n\n\n# Invoke a method with arguments on every item in a collection.\n_.invoke = (obj, method) ->\n  args = _.rest arguments, 2\n  (if method then val[method] else val).apply(val, args) for val in obj\n\n\n# Convenience version of a common use case of **map**: fetching a property.\n_.pluck = (obj, key) ->\n  _.map(obj, (val) -> val[key])\n\n\n# Return the maximum item or (item-based computation).\n_.max = (obj, iterator, context) ->\n  return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)\n  result = computed: -Infinity\n  _.each obj, (value, index, list) ->\n    computed = if iterator then iterator.call(context, value, index, list) else value\n    computed >= result.computed and (result = {value: value, computed: computed})\n  result.value\n\n\n# Return the minimum element (or element-based computation).\n_.min = (obj, iterator, context) ->\n  return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)\n  result = computed: Infinity\n  _.each obj, (value, index, list) ->\n    computed = if iterator then iterator.call(context, value, index, list) else value\n    computed < result.computed and (result = {value: value, computed: computed})\n  result.value\n\n\n# Sort the object's values by a criterion produced by an iterator.\n_.sortBy = (obj, iterator, context) ->\n  _.pluck(((_.map obj, (value, index, list) ->\n    {value: value, criteria: iterator.call(context, value, index, list)}\n  ).sort((left, right) ->\n    a = left.criteria; b = right.criteria\n    if a < b then -1 else if a > b then 1 else 0\n  )), 'value')\n\n\n# Use a comparator function to figure out at what index an object should\n# be inserted so as to maintain order. Uses binary search.\n_.sortedIndex = (array, obj, iterator) ->\n  iterator ||= _.identity\n  low = 0\n  high = array.length\n  while low < high\n    mid = (low + high) >> 1\n    if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid\n  low\n\n\n# Convert anything iterable into a real, live array.\n_.toArray = (iterable) ->\n  return [] if (!iterable)\n  return iterable.toArray() if (iterable.toArray)\n  return iterable if (_.isArray(iterable))\n  return slice.call(iterable) if (_.isArguments(iterable))\n  _.values(iterable)\n\n\n# Return the number of elements in an object.\n_.size = (obj) -> _.toArray(obj).length\n\n\n# Array Functions\n# ---------------\n\n# Get the first element of an array. Passing `n` will return the first N\n# values in the array. Aliased as **head**. The `guard` check allows it to work\n# with **map**.\n_.first = (array, n, guard) ->\n  if n and not guard then slice.call(array, 0, n) else array[0]\n\n\n# Returns everything but the first entry of the array. Aliased as **tail**.\n# Especially useful on the arguments object. Passing an `index` will return\n# the rest of the values in the array from that index onward. The `guard`\n# check allows it to work with **map**.\n_.rest = (array, index, guard) ->\n  slice.call(array, if _.isUndefined(index) or guard then 1 else index)\n\n\n# Get the last element of an array.\n_.last = (array) -> array[array.length - 1]\n\n\n# Trim out all falsy values from an array.\n_.compact = (array) -> item for item in array when item\n\n\n# Return a completely flattened version of an array.\n_.flatten = (array) ->\n  _.reduce array, (memo, value) ->\n    return memo.concat(_.flatten(value)) if _.isArray value\n    memo.push value\n    memo\n  , []\n\n\n# Return a version of the array that does not contain the specified value(s).\n_.without = (array) ->\n  values = _.rest arguments\n  val for val in _.toArray(array) when not _.include values, val\n\n\n# Produce a duplicate-free version of the array. If the array has already\n# been sorted, you have the option of using a faster algorithm.\n_.uniq = (array, isSorted) ->\n  memo = []\n  for el, i in _.toArray array\n    memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))\n  memo\n\n\n# Produce an array that contains every item shared between all the\n# passed-in arrays.\n_.intersect = (array) ->\n  rest = _.rest arguments\n  _.select _.uniq(array), (item) ->\n    _.all rest, (other) ->\n      _.indexOf(other, item) >= 0\n\n\n# Zip together multiple lists into a single array -- elements that share\n# an index go together.\n_.zip = ->\n  length = _.max _.pluck arguments, 'length'\n  results = new Array length\n  for i in [0...length]\n    results[i] = _.pluck arguments, String i\n  results\n\n\n# If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),\n# we need this function. Return the position of the first occurrence of an\n# item in an array, or -1 if the item is not included in the array.\n_.indexOf = (array, item) ->\n  return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf\n  i = 0; l = array.length\n  while l - i\n    if array[i] is item then return i else i++\n  -1\n\n\n# Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,\n# if possible.\n_.lastIndexOf = (array, item) ->\n  return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf\n  i = array.length\n  while i\n    if array[i] is item then return i else i--\n  -1\n\n\n# Generate an integer Array containing an arithmetic progression. A port of\n# [the native Python **range** function](http://docs.python.org/library/functions.html#range).\n_.range = (start, stop, step) ->\n  a = arguments\n  solo = a.length <= 1\n  i = start = if solo then 0 else a[0]\n  stop = if solo then a[0] else a[1]\n  step = a[2] or 1\n  len = Math.ceil((stop - start) / step)\n  return [] if len <= 0\n  range = new Array len\n  idx = 0\n  loop\n    return range if (if step > 0 then i - stop else stop - i) >= 0\n    range[idx] = i\n    idx++\n    i+= step\n\n\n# Function Functions\n# ------------------\n\n# Create a function bound to a given object (assigning `this`, and arguments,\n# optionally). Binding with arguments is also known as **curry**.\n_.bind = (func, obj) ->\n  args = _.rest arguments, 2\n  -> func.apply obj or root, args.concat arguments\n\n\n# Bind all of an object's methods to that object. Useful for ensuring that\n# all callbacks defined on an object belong to it.\n_.bindAll = (obj) ->\n  funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)\n  _.each funcs, (f) -> obj[f] = _.bind obj[f], obj\n  obj\n\n\n# Delays a function for the given number of milliseconds, and then calls\n# it with the arguments supplied.\n_.delay = (func, wait) ->\n  args = _.rest arguments, 2\n  setTimeout((-> func.apply(func, args)), wait)\n\n\n# Memoize an expensive function by storing its results.\n_.memoize = (func, hasher) ->\n  memo = {}\n  hasher or= _.identity\n  ->\n    key = hasher.apply this, arguments\n    return memo[key] if key of memo\n    memo[key] = func.apply this, arguments\n\n\n# Defers a function, scheduling it to run after the current call stack has\n# cleared.\n_.defer = (func) ->\n  _.delay.apply _, [func, 1].concat _.rest arguments\n\n\n# Returns the first function passed as an argument to the second,\n# allowing you to adjust arguments, run code before and after, and\n# conditionally execute the original function.\n_.wrap = (func, wrapper) ->\n  -> wrapper.apply wrapper, [func].concat arguments\n\n\n# Returns a function that is the composition of a list of functions, each\n# consuming the return value of the function that follows.\n_.compose = ->\n  funcs = arguments\n  ->\n    args = arguments\n    for i in [funcs.length - 1..0] by -1\n      args = [funcs[i].apply(this, args)]\n    args[0]\n\n\n# Object Functions\n# ----------------\n\n# Retrieve the names of an object's properties.\n_.keys = nativeKeys or (obj) ->\n  return _.range 0, obj.length if _.isArray(obj)\n  key for key, val of obj\n\n\n# Retrieve the values of an object's properties.\n_.values = (obj) ->\n  _.map obj, _.identity\n\n\n# Return a sorted list of the function names available in Underscore.\n_.functions = (obj) ->\n  _.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()\n\n\n# Extend a given object with all of the properties in a source object.\n_.extend = (obj) ->\n  for source in _.rest(arguments)\n    obj[key] = val for key, val of source\n  obj\n\n\n# Create a (shallow-cloned) duplicate of an object.\n_.clone = (obj) ->\n  return obj.slice 0 if _.isArray obj\n  _.extend {}, obj\n\n\n# Invokes interceptor with the obj, and then returns obj.\n# The primary purpose of this method is to \"tap into\" a method chain,\n# in order to perform operations on intermediate results within\n the chain.\n_.tap = (obj, interceptor) ->\n  interceptor obj\n  obj\n\n\n# Perform a deep comparison to check if two objects are equal.\n_.isEqual = (a, b) ->\n  # Check object identity.\n  return true if a is b\n  # Different types?\n  atype = typeof(a); btype = typeof(b)\n  return false if atype isnt btype\n  # Basic equality test (watch out for coercions).\n  return true if `a == b`\n  # One is falsy and the other truthy.\n  return false if (!a and b) or (a and !b)\n  # One of them implements an `isEqual()`?\n  return a.isEqual(b) if a.isEqual\n  # Check dates' integer values.\n  return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)\n  # Both are NaN?\n  return false if _.isNaN(a) and _.isNaN(b)\n  # Compare regular expressions.\n  if _.isRegExp(a) and _.isRegExp(b)\n    return a.source is b.source and\n           a.global is b.global and\n           a.ignoreCase is b.ignoreCase and\n           a.multiline is b.multiline\n  # If a is not an object by this point, we can't handle it.\n  return false if atype isnt 'object'\n  # Check for different array lengths before comparing contents.\n  return false if a.length and (a.length isnt b.length)\n  # Nothing else worked, deep compare the contents.\n  aKeys = _.keys(a); bKeys = _.keys(b)\n  # Different object sizes?\n  return false if aKeys.length isnt bKeys.length\n  # Recursive comparison of contents.\n  return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])\n  true\n\n\n# Is a given array or object empty?\n_.isEmpty = (obj) ->\n  return obj.length is 0 if _.isArray(obj) or _.isString(obj)\n  return false for own key of obj\n  true\n\n\n# Is a given value a DOM element?\n_.isElement = (obj) -> obj and obj.nodeType is 1\n\n\n# Is a given value an array?\n_.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)\n\n\n# Is a given variable an arguments object?\n_.isArguments = (obj) -> obj and obj.callee\n\n\n# Is the given value a function?\n_.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)\n\n\n# Is the given value a string?\n_.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))\n\n\n# Is a given value a number?\n_.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'\n\n\n# Is a given value a boolean?\n_.isBoolean = (obj) -> obj is true or obj is false\n\n\n# Is a given value a Date?\n_.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)\n\n\n# Is the given value a regular expression?\n_.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))\n\n\n# Is the given value NaN -- this one is interesting. `NaN != NaN`, and\n# `isNaN(undefined) == true`, so we make sure it's a number first.\n_.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)\n\n\n# Is a given value equal to null?\n_.isNull = (obj) -> obj is null\n\n\n# Is a given variable undefined?\n_.isUndefined = (obj) -> typeof obj is 'undefined'\n\n\n# Utility Functions\n# -----------------\n\n# Run Underscore.js in noConflict mode, returning the `_` variable to its\n# previous owner. Returns a reference to the Underscore object.\n_.noConflict = ->\n  root._ = previousUnderscore\n  this\n\n\n# Keep the identity function around for default iterators.\n_.identity = (value) -> value\n\n\n# Run a function `n` times.\n_.times = (n, iterator, context) ->\n  iterator.call context, i for i in [0...n]\n\n\n# Break out of the middle of an iteration.\n_.breakLoop = -> throw breaker\n\n\n# Add your own custom functions to the Underscore object, ensuring that\n# they're correctly added to the OOP wrapper as well.\n_.mixin = (obj) ->\n  for name in _.functions(obj)\n    addToWrapper name, _[name] = obj[name]\n\n\n# Generate a unique integer id (unique within the entire client session).\n# Useful for temporary DOM ids.\nidCounter = 0\n_.uniqueId = (prefix) ->\n  (prefix or '') + idCounter++\n\n\n# By default, Underscore uses **ERB**-style template delimiters, change the\n# following template settings to use alternative delimiters.\n_.templateSettings = {\n  start: '<%'\n  end: '%>'\n  interpolate: /<%=(.+?)%>/g\n}\n\n\n# JavaScript templating a-la **ERB**, pilfered from John Resig's\n# *Secrets of the JavaScript Ninja*, page 83.\n# Single-quote fix from Rick Strahl.\n# With alterations for arbitrary delimiters, and to preserve whitespace.\n_.template = (str, data) ->\n  c = _.templateSettings\n  endMatch = new RegExp(\"'(?=[^\"+c.end.substr(0, 1)+\"]*\"+escapeRegExp(c.end)+\")\",\"g\")\n  fn = new Function 'obj',\n    'var p=[],print=function(){p.push.apply(p,arguments);};' +\n    'with(obj||{}){p.push(\\'' +\n    str.replace(/\\r/g, '\\\\r')\n       .replace(/\\n/g, '\\\\n')\n       .replace(/\\t/g, '\\\\t')\n       .replace(endMatch,\"���\")\n       .split(\"'\").join(\"\\\\'\")\n       .split(\"���\").join(\"'\")\n       .replace(c.interpolate, \"',$1,'\")\n       .split(c.start).join(\"');\")\n       .split(c.end).join(\"p.push('\") +\n       \"');}return p.join('');\"\n  if data then fn(data) else fn\n\n\n# Aliases\n# -------\n\n_.forEach = _.each\n_.foldl = _.inject = _.reduce\n_.foldr = _.reduceRight\n_.select = _.filter\n_.all = _.every\n_.any = _.some\n_.contains = _.include\n_.head = _.first\n_.tail = _.rest\n_.methods = _.functions\n\n\n# Setup the OOP Wrapper\n# ---------------------\n\n# If Underscore is called as a function, it returns a wrapped object that\n# can be used OO-style. This wrapper holds altered versions of all the\n# underscore functions. Wrapped objects may be chained.\nwrapper = (obj) ->\n  this._wrapped = obj\n  this\n\n\n# Helper function to continue chaining intermediate results.\nresult = (obj, chain) ->\n  if chain then _(obj).chain() else obj\n\n\n# A method to easily add functions to the OOP wrapper.\naddToWrapper = (name, func) ->\n  wrapper.prototype[name] = ->\n    args = _.toArray arguments\n    unshift.call args, this._wrapped\n    result func.apply(_, args), this._chain\n\n\n# Add all ofthe Underscore functions to the wrapper object.\n_.mixin _\n\n\n# Add all mutator Array functions to the wrapper.\n_.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->\n  method = Array.prototype[name]\n  wrapper.prototype[name] = ->\n    method.apply(this._wrapped, arguments)\n    result(this._wrapped, this._chain)\n\n\n# Add all accessor Array functions to the wrapper.\n_.each ['concat', 'join', 'slice'], (name) ->\n  method = Array.prototype[name]\n  wrapper.prototype[name] = ->\n    result(method.apply(this._wrapped, arguments), this._chain)\n\n\n# Start chaining a wrapped Underscore object.\nwrapper::chain = ->\n  this._chain = true\n  this\n\n\n# Extracts the result from a wrapped and chained object.\nwrapper::value = -> this._wrapped\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>application/vnd.coffeescript</code>, <code>text/coffeescript</code>, <code>text/x-coffeescript</code>.</p>\n\n    <p>The CoffeeScript mode was written by Jeff Pickhardt.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/commonlisp/commonlisp.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"commonlisp\", function (config) {\n  var specialForm = /^(block|let*|return-from|catch|load-time-value|setq|eval-when|locally|symbol-macrolet|flet|macrolet|tagbody|function|multiple-value-call|the|go|multiple-value-prog1|throw|if|progn|unwind-protect|labels|progv|let|quote)$/;\n  var assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/;\n  var numLiteral = /^(?:[+\\-]?(?:\\d+|\\d*\\.\\d+)(?:[efd][+\\-]?\\d+)?|[+\\-]?\\d+(?:\\/[+\\-]?\\d+)?|#b[+\\-]?[01]+|#o[+\\-]?[0-7]+|#x[+\\-]?[\\da-f]+)/;\n  var symbol = /[^\\s'`,@()\\[\\]\";]/;\n  var type;\n\n  function readSym(stream) {\n    var ch;\n    while (ch = stream.next()) {\n      if (ch == \"\\\\\") stream.next();\n      else if (!symbol.test(ch)) { stream.backUp(1); break; }\n    }\n    return stream.current();\n  }\n\n  function base(stream, state) {\n    if (stream.eatSpace()) {type = \"ws\"; return null;}\n    if (stream.match(numLiteral)) return \"number\";\n    var ch = stream.next();\n    if (ch == \"\\\\\") ch = stream.next();\n\n    if (ch == '\"') return (state.tokenize = inString)(stream, state);\n    else if (ch == \"(\") { type = \"open\"; return \"bracket\"; }\n    else if (ch == \")\" || ch == \"]\") { type = \"close\"; return \"bracket\"; }\n    else if (ch == \";\") { stream.skipToEnd(); type = \"ws\"; return \"comment\"; }\n    else if (/['`,@]/.test(ch)) return null;\n    else if (ch == \"|\") {\n      if (stream.skipTo(\"|\")) { stream.next(); return \"symbol\"; }\n      else { stream.skipToEnd(); return \"error\"; }\n    } else if (ch == \"#\") {\n      var ch = stream.next();\n      if (ch == \"(\") { type = \"open\"; return \"bracket\"; }\n      else if (/[+\\-=\\.']/.test(ch)) return null;\n      else if (/\\d/.test(ch) && stream.match(/^\\d*#/)) return null;\n      else if (ch == \"|\") return (state.tokenize = inComment)(stream, state);\n      else if (ch == \":\") { readSym(stream); return \"meta\"; }\n      else if (ch == \"\\\\\") { stream.next(); readSym(stream); return \"string-2\" }\n      else return \"error\";\n    } else {\n      var name = readSym(stream);\n      if (name == \".\") return null;\n      type = \"symbol\";\n      if (name == \"nil\" || name == \"t\" || name.charAt(0) == \":\") return \"atom\";\n      if (state.lastType == \"open\" && (specialForm.test(name) || assumeBody.test(name))) return \"keyword\";\n      if (name.charAt(0) == \"&\") return \"variable-2\";\n      return \"variable\";\n    }\n  }\n\n  function inString(stream, state) {\n    var escaped = false, next;\n    while (next = stream.next()) {\n      if (next == '\"' && !escaped) { state.tokenize = base; break; }\n      escaped = !escaped && next == \"\\\\\";\n    }\n    return \"string\";\n  }\n\n  function inComment(stream, state) {\n    var next, last;\n    while (next = stream.next()) {\n      if (next == \"#\" && last == \"|\") { state.tokenize = base; break; }\n      last = next;\n    }\n    type = \"ws\";\n    return \"comment\";\n  }\n\n  return {\n    startState: function () {\n      return {ctx: {prev: null, start: 0, indentTo: 0}, lastType: null, tokenize: base};\n    },\n\n    token: function (stream, state) {\n      if (stream.sol() && typeof state.ctx.indentTo != \"number\")\n        state.ctx.indentTo = state.ctx.start + 1;\n\n      type = null;\n      var style = state.tokenize(stream, state);\n      if (type != \"ws\") {\n        if (state.ctx.indentTo == null) {\n          if (type == \"symbol\" && assumeBody.test(stream.current()))\n            state.ctx.indentTo = state.ctx.start + config.indentUnit;\n          else\n            state.ctx.indentTo = \"next\";\n        } else if (state.ctx.indentTo == \"next\") {\n          state.ctx.indentTo = stream.column();\n        }\n        state.lastType = type;\n      }\n      if (type == \"open\") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};\n      else if (type == \"close\") state.ctx = state.ctx.prev || state.ctx;\n      return style;\n    },\n\n    indent: function (state, _textAfter) {\n      var i = state.ctx.indentTo;\n      return typeof i == \"number\" ? i : state.ctx.start + 1;\n    },\n\n    closeBrackets: {pairs: \"()[]{}\\\"\\\"\"},\n    lineComment: \";;\",\n    blockCommentStart: \"#|\",\n    blockCommentEnd: \"|#\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-common-lisp\", \"commonlisp\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/commonlisp/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Common Lisp mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"commonlisp.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Common Lisp</a>\n  </ul>\n</div>\n\n<article>\n<h2>Common Lisp mode</h2>\n<form><textarea id=\"code\" name=\"code\">(in-package :cl-postgres)\n\n;; These are used to synthesize reader and writer names for integer\n;; reading/writing functions when the amount of bytes and the\n;; signedness is known. Both the macro that creates the functions and\n;; some macros that use them create names this way.\n(eval-when (:compile-toplevel :load-toplevel :execute)\n  (defun integer-reader-name (bytes signed)\n    (intern (with-standard-io-syntax\n              (format nil \"~a~a~a~a\" '#:read- (if signed \"\" '#:u) '#:int bytes))))\n  (defun integer-writer-name (bytes signed)\n    (intern (with-standard-io-syntax\n              (format nil \"~a~a~a~a\" '#:write- (if signed \"\" '#:u) '#:int bytes)))))\n\n(defmacro integer-reader (bytes)\n  \"Create a function to read integers from a binary stream.\"\n  (let ((bits (* bytes 8)))\n    (labels ((return-form (signed)\n               (if signed\n                   `(if (logbitp ,(1- bits) result)\n                        (dpb result (byte ,(1- bits) 0) -1)\n                        result)\n                   `result))\n             (generate-reader (signed)\n               `(defun ,(integer-reader-name bytes signed) (socket)\n                  (declare (type stream socket)\n                           #.*optimize*)\n                  ,(if (= bytes 1)\n                       `(let ((result (the (unsigned-byte 8) (read-byte socket))))\n                          (declare (type (unsigned-byte 8) result))\n                          ,(return-form signed))\n                       `(let ((result 0))\n                          (declare (type (unsigned-byte ,bits) result))\n                          ,@(loop :for byte :from (1- bytes) :downto 0\n                                   :collect `(setf (ldb (byte 8 ,(* 8 byte)) result)\n                                                   (the (unsigned-byte 8) (read-byte socket))))\n                          ,(return-form signed))))))\n      `(progn\n;; This causes weird errors on SBCL in some circumstances. Disabled for now.\n;;         (declaim (inline ,(integer-reader-name bytes t)\n;;                          ,(integer-reader-name bytes nil)))\n         (declaim (ftype (function (t) (signed-byte ,bits))\n                         ,(integer-reader-name bytes t)))\n         ,(generate-reader t)\n         (declaim (ftype (function (t) (unsigned-byte ,bits))\n                         ,(integer-reader-name bytes nil)))\n         ,(generate-reader nil)))))\n\n(defmacro integer-writer (bytes)\n  \"Create a function to write integers to a binary stream.\"\n  (let ((bits (* 8 bytes)))\n    `(progn\n      (declaim (inline ,(integer-writer-name bytes t)\n                       ,(integer-writer-name bytes nil)))\n      (defun ,(integer-writer-name bytes nil) (socket value)\n        (declare (type stream socket)\n                 (type (unsigned-byte ,bits) value)\n                 #.*optimize*)\n        ,@(if (= bytes 1)\n              `((write-byte value socket))\n              (loop :for byte :from (1- bytes) :downto 0\n                    :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)\n                               socket)))\n        (values))\n      (defun ,(integer-writer-name bytes t) (socket value)\n        (declare (type stream socket)\n                 (type (signed-byte ,bits) value)\n                 #.*optimize*)\n        ,@(if (= bytes 1)\n              `((write-byte (ldb (byte 8 0) value) socket))\n              (loop :for byte :from (1- bytes) :downto 0\n                    :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)\n                               socket)))\n        (values)))))\n\n;; All the instances of the above that we need.\n\n(integer-reader 1)\n(integer-reader 2)\n(integer-reader 4)\n(integer-reader 8)\n\n(integer-writer 1)\n(integer-writer 2)\n(integer-writer 4)\n\n(defun write-bytes (socket bytes)\n  \"Write a byte-array to a stream.\"\n  (declare (type stream socket)\n           (type (simple-array (unsigned-byte 8)) bytes)\n           #.*optimize*)\n  (write-sequence bytes socket))\n\n(defun write-str (socket string)\n  \"Write a null-terminated string to a stream \\(encoding it when UTF-8\nsupport is enabled.).\"\n  (declare (type stream socket)\n           (type string string)\n           #.*optimize*)\n  (enc-write-string string socket)\n  (write-uint1 socket 0))\n\n(declaim (ftype (function (t unsigned-byte)\n                          (simple-array (unsigned-byte 8) (*)))\n                read-bytes))\n(defun read-bytes (socket length)\n  \"Read a byte array of the given length from a stream.\"\n  (declare (type stream socket)\n           (type fixnum length)\n           #.*optimize*)\n  (let ((result (make-array length :element-type '(unsigned-byte 8))))\n    (read-sequence result socket)\n    result))\n\n(declaim (ftype (function (t) string) read-str))\n(defun read-str (socket)\n  \"Read a null-terminated string from a stream. Takes care of encoding\nwhen UTF-8 support is enabled.\"\n  (declare (type stream socket)\n           #.*optimize*)\n  (enc-read-string socket :null-terminated t))\n\n(defun skip-bytes (socket length)\n  \"Skip a given number of bytes in a binary stream.\"\n  (declare (type stream socket)\n           (type (unsigned-byte 32) length)\n           #.*optimize*)\n  (dotimes (i length)\n    (read-byte socket)))\n\n(defun skip-str (socket)\n  \"Skip a null-terminated string.\"\n  (declare (type stream socket)\n           #.*optimize*)\n  (loop :for char :of-type fixnum = (read-byte socket)\n        :until (zerop char)))\n\n(defun ensure-socket-is-closed (socket &amp;key abort)\n  (when (open-stream-p socket)\n    (handler-case\n        (close socket :abort abort)\n      (error (error)\n        (warn \"Ignoring the error which happened while trying to close PostgreSQL socket: ~A\" error)))))\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {lineNumbers: true});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-common-lisp</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/crystal/crystal.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"crystal\", function(config) {\n    function wordRegExp(words, end) {\n      return new RegExp((end ? \"\" : \"^\") + \"(?:\" + words.join(\"|\") + \")\" + (end ? \"$\" : \"\\\\b\"));\n    }\n\n    function chain(tokenize, stream, state) {\n      state.tokenize.push(tokenize);\n      return tokenize(stream, state);\n    }\n\n    var operators = /^(?:[-+/%|&^]|\\*\\*?|[<>]{2})/;\n    var conditionalOperators = /^(?:[=!]~|===|<=>|[<>=!]=?|[|&]{2}|~)/;\n    var indexingOperators = /^(?:\\[\\][?=]?)/;\n    var anotherOperators = /^(?:\\.(?:\\.{2})?|->|[?:])/;\n    var idents = /^[a-z_\\u009F-\\uFFFF][a-zA-Z0-9_\\u009F-\\uFFFF]*/;\n    var types = /^[A-Z_\\u009F-\\uFFFF][a-zA-Z0-9_\\u009F-\\uFFFF]*/;\n    var keywords = wordRegExp([\n      \"abstract\", \"alias\", \"as\", \"asm\", \"begin\", \"break\", \"case\", \"class\", \"def\", \"do\",\n      \"else\", \"elsif\", \"end\", \"ensure\", \"enum\", \"extend\", \"for\", \"fun\", \"if\",\n      \"include\", \"instance_sizeof\", \"lib\", \"macro\", \"module\", \"next\", \"of\", \"out\", \"pointerof\",\n      \"private\", \"protected\", \"rescue\", \"return\", \"require\", \"select\", \"sizeof\", \"struct\",\n      \"super\", \"then\", \"type\", \"typeof\", \"uninitialized\", \"union\", \"unless\", \"until\", \"when\", \"while\", \"with\",\n      \"yield\", \"__DIR__\", \"__END_LINE__\", \"__FILE__\", \"__LINE__\"\n    ]);\n    var atomWords = wordRegExp([\"true\", \"false\", \"nil\", \"self\"]);\n    var indentKeywordsArray = [\n      \"def\", \"fun\", \"macro\",\n      \"class\", \"module\", \"struct\", \"lib\", \"enum\", \"union\",\n      \"do\", \"for\"\n    ];\n    var indentKeywords = wordRegExp(indentKeywordsArray);\n    var indentExpressionKeywordsArray = [\"if\", \"unless\", \"case\", \"while\", \"until\", \"begin\", \"then\"];\n    var indentExpressionKeywords = wordRegExp(indentExpressionKeywordsArray);\n    var dedentKeywordsArray = [\"end\", \"else\", \"elsif\", \"rescue\", \"ensure\"];\n    var dedentKeywords = wordRegExp(dedentKeywordsArray);\n    var dedentPunctualsArray = [\"\\\\)\", \"\\\\}\", \"\\\\]\"];\n    var dedentPunctuals = new RegExp(\"^(?:\" + dedentPunctualsArray.join(\"|\") + \")$\");\n    var nextTokenizer = {\n      \"def\": tokenFollowIdent, \"fun\": tokenFollowIdent, \"macro\": tokenMacroDef,\n      \"class\": tokenFollowType, \"module\": tokenFollowType, \"struct\": tokenFollowType,\n      \"lib\": tokenFollowType, \"enum\": tokenFollowType, \"union\": tokenFollowType\n    };\n    var matching = {\"[\": \"]\", \"{\": \"}\", \"(\": \")\", \"<\": \">\"};\n\n    function tokenBase(stream, state) {\n      if (stream.eatSpace()) {\n        return null;\n      }\n\n      // Macros\n      if (state.lastToken != \"\\\\\" && stream.match(\"{%\", false)) {\n        return chain(tokenMacro(\"%\", \"%\"), stream, state);\n      }\n\n      if (state.lastToken != \"\\\\\" && stream.match(\"{{\", false)) {\n        return chain(tokenMacro(\"{\", \"}\"), stream, state);\n      }\n\n      // Comments\n      if (stream.peek() == \"#\") {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n\n      // Variables and keywords\n      var matched;\n      if (stream.match(idents)) {\n        stream.eat(/[?!]/);\n\n        matched = stream.current();\n        if (stream.eat(\":\")) {\n          return \"atom\";\n        } else if (state.lastToken == \".\") {\n          return \"property\";\n        } else if (keywords.test(matched)) {\n          if (indentKeywords.test(matched)) {\n            if (!(matched == \"fun\" && state.blocks.indexOf(\"lib\") >= 0) && !(matched == \"def\" && state.lastToken == \"abstract\")) {\n              state.blocks.push(matched);\n              state.currentIndent += 1;\n            }\n          } else if ((state.lastStyle == \"operator\" || !state.lastStyle) && indentExpressionKeywords.test(matched)) {\n            state.blocks.push(matched);\n            state.currentIndent += 1;\n          } else if (matched == \"end\") {\n            state.blocks.pop();\n            state.currentIndent -= 1;\n          }\n\n          if (nextTokenizer.hasOwnProperty(matched)) {\n            state.tokenize.push(nextTokenizer[matched]);\n          }\n\n          return \"keyword\";\n        } else if (atomWords.test(matched)) {\n          return \"atom\";\n        }\n\n        return \"variable\";\n      }\n\n      // Class variables and instance variables\n      // or attributes\n      if (stream.eat(\"@\")) {\n        if (stream.peek() == \"[\") {\n          return chain(tokenNest(\"[\", \"]\", \"meta\"), stream, state);\n        }\n\n        stream.eat(\"@\");\n        stream.match(idents) || stream.match(types);\n        return \"variable-2\";\n      }\n\n      // Constants and types\n      if (stream.match(types)) {\n        return \"tag\";\n      }\n\n      // Symbols or ':' operator\n      if (stream.eat(\":\")) {\n        if (stream.eat(\"\\\"\")) {\n          return chain(tokenQuote(\"\\\"\", \"atom\", false), stream, state);\n        } else if (stream.match(idents) || stream.match(types) ||\n                   stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators)) {\n          return \"atom\";\n        }\n        stream.eat(\":\");\n        return \"operator\";\n      }\n\n      // Strings\n      if (stream.eat(\"\\\"\")) {\n        return chain(tokenQuote(\"\\\"\", \"string\", true), stream, state);\n      }\n\n      // Strings or regexps or macro variables or '%' operator\n      if (stream.peek() == \"%\") {\n        var style = \"string\";\n        var embed = true;\n        var delim;\n\n        if (stream.match(\"%r\")) {\n          // Regexps\n          style = \"string-2\";\n          delim = stream.next();\n        } else if (stream.match(\"%w\")) {\n          embed = false;\n          delim = stream.next();\n        } else if (stream.match(\"%q\")) {\n          embed = false;\n          delim = stream.next();\n        } else {\n          if(delim = stream.match(/^%([^\\w\\s=])/)) {\n            delim = delim[1];\n          } else if (stream.match(/^%[a-zA-Z0-9_\\u009F-\\uFFFF]*/)) {\n            // Macro variables\n            return \"meta\";\n          } else {\n            // '%' operator\n            return \"operator\";\n          }\n        }\n\n        if (matching.hasOwnProperty(delim)) {\n          delim = matching[delim];\n        }\n        return chain(tokenQuote(delim, style, embed), stream, state);\n      }\n\n      // Here Docs\n      if (matched = stream.match(/^<<-('?)([A-Z]\\w*)\\1/)) {\n        return chain(tokenHereDoc(matched[2], !matched[1]), stream, state)\n      }\n\n      // Characters\n      if (stream.eat(\"'\")) {\n        stream.match(/^(?:[^']|\\\\(?:[befnrtv0'\"]|[0-7]{3}|u(?:[0-9a-fA-F]{4}|\\{[0-9a-fA-F]{1,6}\\})))/);\n        stream.eat(\"'\");\n        return \"atom\";\n      }\n\n      // Numbers\n      if (stream.eat(\"0\")) {\n        if (stream.eat(\"x\")) {\n          stream.match(/^[0-9a-fA-F]+/);\n        } else if (stream.eat(\"o\")) {\n          stream.match(/^[0-7]+/);\n        } else if (stream.eat(\"b\")) {\n          stream.match(/^[01]+/);\n        }\n        return \"number\";\n      }\n\n      if (stream.eat(/^\\d/)) {\n        stream.match(/^\\d*(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/);\n        return \"number\";\n      }\n\n      // Operators\n      if (stream.match(operators)) {\n        stream.eat(\"=\"); // Operators can follow assign symbol.\n        return \"operator\";\n      }\n\n      if (stream.match(conditionalOperators) || stream.match(anotherOperators)) {\n        return \"operator\";\n      }\n\n      // Parens and braces\n      if (matched = stream.match(/[({[]/, false)) {\n        matched = matched[0];\n        return chain(tokenNest(matched, matching[matched], null), stream, state);\n      }\n\n      // Escapes\n      if (stream.eat(\"\\\\\")) {\n        stream.next();\n        return \"meta\";\n      }\n\n      stream.next();\n      return null;\n    }\n\n    function tokenNest(begin, end, style, started) {\n      return function (stream, state) {\n        if (!started && stream.match(begin)) {\n          state.tokenize[state.tokenize.length - 1] = tokenNest(begin, end, style, true);\n          state.currentIndent += 1;\n          return style;\n        }\n\n        var nextStyle = tokenBase(stream, state);\n        if (stream.current() === end) {\n          state.tokenize.pop();\n          state.currentIndent -= 1;\n          nextStyle = style;\n        }\n\n        return nextStyle;\n      };\n    }\n\n    function tokenMacro(begin, end, started) {\n      return function (stream, state) {\n        if (!started && stream.match(\"{\" + begin)) {\n          state.currentIndent += 1;\n          state.tokenize[state.tokenize.length - 1] = tokenMacro(begin, end, true);\n          return \"meta\";\n        }\n\n        if (stream.match(end + \"}\")) {\n          state.currentIndent -= 1;\n          state.tokenize.pop();\n          return \"meta\";\n        }\n\n        return tokenBase(stream, state);\n      };\n    }\n\n    function tokenMacroDef(stream, state) {\n      if (stream.eatSpace()) {\n        return null;\n      }\n\n      var matched;\n      if (matched = stream.match(idents)) {\n        if (matched == \"def\") {\n          return \"keyword\";\n        }\n        stream.eat(/[?!]/);\n      }\n\n      state.tokenize.pop();\n      return \"def\";\n    }\n\n    function tokenFollowIdent(stream, state) {\n      if (stream.eatSpace()) {\n        return null;\n      }\n\n      if (stream.match(idents)) {\n        stream.eat(/[!?]/);\n      } else {\n        stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators);\n      }\n      state.tokenize.pop();\n      return \"def\";\n    }\n\n    function tokenFollowType(stream, state) {\n      if (stream.eatSpace()) {\n        return null;\n      }\n\n      stream.match(types);\n      state.tokenize.pop();\n      return \"def\";\n    }\n\n    function tokenQuote(end, style, embed) {\n      return function (stream, state) {\n        var escaped = false;\n\n        while (stream.peek()) {\n          if (!escaped) {\n            if (stream.match(\"{%\", false)) {\n              state.tokenize.push(tokenMacro(\"%\", \"%\"));\n              return style;\n            }\n\n            if (stream.match(\"{{\", false)) {\n              state.tokenize.push(tokenMacro(\"{\", \"}\"));\n              return style;\n            }\n\n            if (embed && stream.match(\"#{\", false)) {\n              state.tokenize.push(tokenNest(\"#{\", \"}\", \"meta\"));\n              return style;\n            }\n\n            var ch = stream.next();\n\n            if (ch == end) {\n              state.tokenize.pop();\n              return style;\n            }\n\n            escaped = embed && ch == \"\\\\\";\n          } else {\n            stream.next();\n            escaped = false;\n          }\n        }\n\n        return style;\n      };\n    }\n\n    function tokenHereDoc(phrase, embed) {\n      return function (stream, state) {\n        if (stream.sol()) {\n          stream.eatSpace()\n          if (stream.match(phrase)) {\n            state.tokenize.pop();\n            return \"string\";\n          }\n        }\n\n        var escaped = false;\n        while (stream.peek()) {\n          if (!escaped) {\n            if (stream.match(\"{%\", false)) {\n              state.tokenize.push(tokenMacro(\"%\", \"%\"));\n              return \"string\";\n            }\n\n            if (stream.match(\"{{\", false)) {\n              state.tokenize.push(tokenMacro(\"{\", \"}\"));\n              return \"string\";\n            }\n\n            if (embed && stream.match(\"#{\", false)) {\n              state.tokenize.push(tokenNest(\"#{\", \"}\", \"meta\"));\n              return \"string\";\n            }\n\n            escaped = embed && stream.next() == \"\\\\\";\n          } else {\n            stream.next();\n            escaped = false;\n          }\n        }\n\n        return \"string\";\n      }\n    }\n\n    return {\n      startState: function () {\n        return {\n          tokenize: [tokenBase],\n          currentIndent: 0,\n          lastToken: null,\n          lastStyle: null,\n          blocks: []\n        };\n      },\n\n      token: function (stream, state) {\n        var style = state.tokenize[state.tokenize.length - 1](stream, state);\n        var token = stream.current();\n\n        if (style && style != \"comment\") {\n          state.lastToken = token;\n          state.lastStyle = style;\n        }\n\n        return style;\n      },\n\n      indent: function (state, textAfter) {\n        textAfter = textAfter.replace(/^\\s*(?:\\{%)?\\s*|\\s*(?:%\\})?\\s*$/g, \"\");\n\n        if (dedentKeywords.test(textAfter) || dedentPunctuals.test(textAfter)) {\n          return config.indentUnit * (state.currentIndent - 1);\n        }\n\n        return config.indentUnit * state.currentIndent;\n      },\n\n      fold: \"indent\",\n      electricInput: wordRegExp(dedentPunctualsArray.concat(dedentKeywordsArray), true),\n      lineComment: '#'\n    };\n  });\n\n  CodeMirror.defineMIME(\"text/x-crystal\", \"crystal\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/crystal/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Crystal mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"crystal.js\"></script>\n<style>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n  .cm-s-default span.cm-arrow { color: red; }\n</style>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Crystal</a>\n  </ul>\n</div>\n\n<article>\n<h2>Crystal mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n# Features of Crystal\n# - Ruby-inspired syntax.\n# - Statically type-checked but without having to specify the type of variables or method arguments.\n# - Be able to call C code by writing bindings to it in Crystal.\n# - Have compile-time evaluation and generation of code, to avoid boilerplate code.\n# - Compile to efficient native code.\n\n# A very basic HTTP server\nrequire \"http/server\"\n\nserver = HTTP::Server.new(8080) do |request|\n  HTTP::Response.ok \"text/plain\", \"Hello world, got #{request.path}!\"\nend\n\nputs \"Listening on http://0.0.0.0:8080\"\nserver.listen\n\nmodule Foo\n  abstract def abstract_method : String\n\n  @[AlwaysInline]\n  def with_foofoo\n    with Foo.new(self) yield\n  end\n\n  struct Foo\n    def initialize(@foo : ::Foo)\n    end\n\n    def hello_world\n      @foo.abstract_method\n    end\n  end\nend\n\nclass Bar\n  include Foo\n\n  @@foobar = 12345\n\n  def initialize(@bar : Int32)\n  end\n\n  macro alias_method(name, method)\n    def {{ name }}(*args)\n      {{ method }}(*args)\n    end\n  end\n\n  def a_method\n    \"Hello, World\"\n  end\n\n  alias_method abstract_method, a_method\n\n  def show_instance_vars : Nil\n    {% for var in @type.instance_vars %}\n      puts \"@{{ var }} = #{ @{{ var }} }\"\n    {% end %}\n  end\nend\n\nclass Baz &lt; Bar; end\n\nlib LibC\n  fun c_puts = \"puts\"(str : Char*) : Int\nend\n\nbaz = Baz.new(100)\nbaz.show_instance_vars\nbaz.with_foofoo do\n  LibC.c_puts hello_world\nend\n</textarea></form>\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    mode: \"text/x-crystal\",\n    matchBrackets: true,\n    indentUnit: 2\n  });\n</script>\n\n<p><strong>MIME types defined:</strong> <code>text/x-crystal</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/css/css.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"css\", function(config, parserConfig) {\n  var inline = parserConfig.inline\n  if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode(\"text/css\");\n\n  var indentUnit = config.indentUnit,\n      tokenHooks = parserConfig.tokenHooks,\n      documentTypes = parserConfig.documentTypes || {},\n      mediaTypes = parserConfig.mediaTypes || {},\n      mediaFeatures = parserConfig.mediaFeatures || {},\n      mediaValueKeywords = parserConfig.mediaValueKeywords || {},\n      propertyKeywords = parserConfig.propertyKeywords || {},\n      nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},\n      fontProperties = parserConfig.fontProperties || {},\n      counterDescriptors = parserConfig.counterDescriptors || {},\n      colorKeywords = parserConfig.colorKeywords || {},\n      valueKeywords = parserConfig.valueKeywords || {},\n      allowNested = parserConfig.allowNested,\n      lineComment = parserConfig.lineComment,\n      supportsAtComponent = parserConfig.supportsAtComponent === true;\n\n  var type, override;\n  function ret(style, tp) { type = tp; return style; }\n\n  // Tokenizers\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (tokenHooks[ch]) {\n      var result = tokenHooks[ch](stream, state);\n      if (result !== false) return result;\n    }\n    if (ch == \"@\") {\n      stream.eatWhile(/[\\w\\\\\\-]/);\n      return ret(\"def\", stream.current());\n    } else if (ch == \"=\" || (ch == \"~\" || ch == \"|\") && stream.eat(\"=\")) {\n      return ret(null, \"compare\");\n    } else if (ch == \"\\\"\" || ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    } else if (ch == \"#\") {\n      stream.eatWhile(/[\\w\\\\\\-]/);\n      return ret(\"atom\", \"hash\");\n    } else if (ch == \"!\") {\n      stream.match(/^\\s*\\w*/);\n      return ret(\"keyword\", \"important\");\n    } else if (/\\d/.test(ch) || ch == \".\" && stream.eat(/\\d/)) {\n      stream.eatWhile(/[\\w.%]/);\n      return ret(\"number\", \"unit\");\n    } else if (ch === \"-\") {\n      if (/[\\d.]/.test(stream.peek())) {\n        stream.eatWhile(/[\\w.%]/);\n        return ret(\"number\", \"unit\");\n      } else if (stream.match(/^-[\\w\\\\\\-]*/)) {\n        stream.eatWhile(/[\\w\\\\\\-]/);\n        if (stream.match(/^\\s*:/, false))\n          return ret(\"variable-2\", \"variable-definition\");\n        return ret(\"variable-2\", \"variable\");\n      } else if (stream.match(/^\\w+-/)) {\n        return ret(\"meta\", \"meta\");\n      }\n    } else if (/[,+>*\\/]/.test(ch)) {\n      return ret(null, \"select-op\");\n    } else if (ch == \".\" && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {\n      return ret(\"qualifier\", \"qualifier\");\n    } else if (/[:;{}\\[\\]\\(\\)]/.test(ch)) {\n      return ret(null, ch);\n    } else if (stream.match(/[\\w-.]+(?=\\()/)) {\n      if (/^(url(-prefix)?|domain|regexp)$/.test(stream.current().toLowerCase())) {\n        state.tokenize = tokenParenthesized;\n      }\n      return ret(\"variable callee\", \"variable\");\n    } else if (/[\\w\\\\\\-]/.test(ch)) {\n      stream.eatWhile(/[\\w\\\\\\-]/);\n      return ret(\"property\", \"word\");\n    } else {\n      return ret(null, null);\n    }\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && !escaped) {\n          if (quote == \")\") stream.backUp(1);\n          break;\n        }\n        escaped = !escaped && ch == \"\\\\\";\n      }\n      if (ch == quote || !escaped && quote != \")\") state.tokenize = null;\n      return ret(\"string\", \"string\");\n    };\n  }\n\n  function tokenParenthesized(stream, state) {\n    stream.next(); // Must be '('\n    if (!stream.match(/\\s*[\\\"\\')]/, false))\n      state.tokenize = tokenString(\")\");\n    else\n      state.tokenize = null;\n    return ret(null, \"(\");\n  }\n\n  // Context management\n\n  function Context(type, indent, prev) {\n    this.type = type;\n    this.indent = indent;\n    this.prev = prev;\n  }\n\n  function pushContext(state, stream, type, indent) {\n    state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);\n    return type;\n  }\n\n  function popContext(state) {\n    if (state.context.prev)\n      state.context = state.context.prev;\n    return state.context.type;\n  }\n\n  function pass(type, stream, state) {\n    return states[state.context.type](type, stream, state);\n  }\n  function popAndPass(type, stream, state, n) {\n    for (var i = n || 1; i > 0; i--)\n      state.context = state.context.prev;\n    return pass(type, stream, state);\n  }\n\n  // Parser\n\n  function wordAsValue(stream) {\n    var word = stream.current().toLowerCase();\n    if (valueKeywords.hasOwnProperty(word))\n      override = \"atom\";\n    else if (colorKeywords.hasOwnProperty(word))\n      override = \"keyword\";\n    else\n      override = \"variable\";\n  }\n\n  var states = {};\n\n  states.top = function(type, stream, state) {\n    if (type == \"{\") {\n      return pushContext(state, stream, \"block\");\n    } else if (type == \"}\" && state.context.prev) {\n      return popContext(state);\n    } else if (supportsAtComponent && /@component/i.test(type)) {\n      return pushContext(state, stream, \"atComponentBlock\");\n    } else if (/^@(-moz-)?document$/i.test(type)) {\n      return pushContext(state, stream, \"documentTypes\");\n    } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {\n      return pushContext(state, stream, \"atBlock\");\n    } else if (/^@(font-face|counter-style)/i.test(type)) {\n      state.stateArg = type;\n      return \"restricted_atBlock_before\";\n    } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {\n      return \"keyframes\";\n    } else if (type && type.charAt(0) == \"@\") {\n      return pushContext(state, stream, \"at\");\n    } else if (type == \"hash\") {\n      override = \"builtin\";\n    } else if (type == \"word\") {\n      override = \"tag\";\n    } else if (type == \"variable-definition\") {\n      return \"maybeprop\";\n    } else if (type == \"interpolation\") {\n      return pushContext(state, stream, \"interpolation\");\n    } else if (type == \":\") {\n      return \"pseudo\";\n    } else if (allowNested && type == \"(\") {\n      return pushContext(state, stream, \"parens\");\n    }\n    return state.context.type;\n  };\n\n  states.block = function(type, stream, state) {\n    if (type == \"word\") {\n      var word = stream.current().toLowerCase();\n      if (propertyKeywords.hasOwnProperty(word)) {\n        override = \"property\";\n        return \"maybeprop\";\n      } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {\n        override = \"string-2\";\n        return \"maybeprop\";\n      } else if (allowNested) {\n        override = stream.match(/^\\s*:(?:\\s|$)/, false) ? \"property\" : \"tag\";\n        return \"block\";\n      } else {\n        override += \" error\";\n        return \"maybeprop\";\n      }\n    } else if (type == \"meta\") {\n      return \"block\";\n    } else if (!allowNested && (type == \"hash\" || type == \"qualifier\")) {\n      override = \"error\";\n      return \"block\";\n    } else {\n      return states.top(type, stream, state);\n    }\n  };\n\n  states.maybeprop = function(type, stream, state) {\n    if (type == \":\") return pushContext(state, stream, \"prop\");\n    return pass(type, stream, state);\n  };\n\n  states.prop = function(type, stream, state) {\n    if (type == \";\") return popContext(state);\n    if (type == \"{\" && allowNested) return pushContext(state, stream, \"propBlock\");\n    if (type == \"}\" || type == \"{\") return popAndPass(type, stream, state);\n    if (type == \"(\") return pushContext(state, stream, \"parens\");\n\n    if (type == \"hash\" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {\n      override += \" error\";\n    } else if (type == \"word\") {\n      wordAsValue(stream);\n    } else if (type == \"interpolation\") {\n      return pushContext(state, stream, \"interpolation\");\n    }\n    return \"prop\";\n  };\n\n  states.propBlock = function(type, _stream, state) {\n    if (type == \"}\") return popContext(state);\n    if (type == \"word\") { override = \"property\"; return \"maybeprop\"; }\n    return state.context.type;\n  };\n\n  states.parens = function(type, stream, state) {\n    if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state);\n    if (type == \")\") return popContext(state);\n    if (type == \"(\") return pushContext(state, stream, \"parens\");\n    if (type == \"interpolation\") return pushContext(state, stream, \"interpolation\");\n    if (type == \"word\") wordAsValue(stream);\n    return \"parens\";\n  };\n\n  states.pseudo = function(type, stream, state) {\n    if (type == \"meta\") return \"pseudo\";\n\n    if (type == \"word\") {\n      override = \"variable-3\";\n      return state.context.type;\n    }\n    return pass(type, stream, state);\n  };\n\n  states.documentTypes = function(type, stream, state) {\n    if (type == \"word\" && documentTypes.hasOwnProperty(stream.current())) {\n      override = \"tag\";\n      return state.context.type;\n    } else {\n      return states.atBlock(type, stream, state);\n    }\n  };\n\n  states.atBlock = function(type, stream, state) {\n    if (type == \"(\") return pushContext(state, stream, \"atBlock_parens\");\n    if (type == \"}\" || type == \";\") return popAndPass(type, stream, state);\n    if (type == \"{\") return popContext(state) && pushContext(state, stream, allowNested ? \"block\" : \"top\");\n\n    if (type == \"interpolation\") return pushContext(state, stream, \"interpolation\");\n\n    if (type == \"word\") {\n      var word = stream.current().toLowerCase();\n      if (word == \"only\" || word == \"not\" || word == \"and\" || word == \"or\")\n        override = \"keyword\";\n      else if (mediaTypes.hasOwnProperty(word))\n        override = \"attribute\";\n      else if (mediaFeatures.hasOwnProperty(word))\n        override = \"property\";\n      else if (mediaValueKeywords.hasOwnProperty(word))\n        override = \"keyword\";\n      else if (propertyKeywords.hasOwnProperty(word))\n        override = \"property\";\n      else if (nonStandardPropertyKeywords.hasOwnProperty(word))\n        override = \"string-2\";\n      else if (valueKeywords.hasOwnProperty(word))\n        override = \"atom\";\n      else if (colorKeywords.hasOwnProperty(word))\n        override = \"keyword\";\n      else\n        override = \"error\";\n    }\n    return state.context.type;\n  };\n\n  states.atComponentBlock = function(type, stream, state) {\n    if (type == \"}\")\n      return popAndPass(type, stream, state);\n    if (type == \"{\")\n      return popContext(state) && pushContext(state, stream, allowNested ? \"block\" : \"top\", false);\n    if (type == \"word\")\n      override = \"error\";\n    return state.context.type;\n  };\n\n  states.atBlock_parens = function(type, stream, state) {\n    if (type == \")\") return popContext(state);\n    if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state, 2);\n    return states.atBlock(type, stream, state);\n  };\n\n  states.restricted_atBlock_before = function(type, stream, state) {\n    if (type == \"{\")\n      return pushContext(state, stream, \"restricted_atBlock\");\n    if (type == \"word\" && state.stateArg == \"@counter-style\") {\n      override = \"variable\";\n      return \"restricted_atBlock_before\";\n    }\n    return pass(type, stream, state);\n  };\n\n  states.restricted_atBlock = function(type, stream, state) {\n    if (type == \"}\") {\n      state.stateArg = null;\n      return popContext(state);\n    }\n    if (type == \"word\") {\n      if ((state.stateArg == \"@font-face\" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||\n          (state.stateArg == \"@counter-style\" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))\n        override = \"error\";\n      else\n        override = \"property\";\n      return \"maybeprop\";\n    }\n    return \"restricted_atBlock\";\n  };\n\n  states.keyframes = function(type, stream, state) {\n    if (type == \"word\") { override = \"variable\"; return \"keyframes\"; }\n    if (type == \"{\") return pushContext(state, stream, \"top\");\n    return pass(type, stream, state);\n  };\n\n  states.at = function(type, stream, state) {\n    if (type == \";\") return popContext(state);\n    if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state);\n    if (type == \"word\") override = \"tag\";\n    else if (type == \"hash\") override = \"builtin\";\n    return \"at\";\n  };\n\n  states.interpolation = function(type, stream, state) {\n    if (type == \"}\") return popContext(state);\n    if (type == \"{\" || type == \";\") return popAndPass(type, stream, state);\n    if (type == \"word\") override = \"variable\";\n    else if (type != \"variable\" && type != \"(\" && type != \")\") override = \"error\";\n    return \"interpolation\";\n  };\n\n  return {\n    startState: function(base) {\n      return {tokenize: null,\n              state: inline ? \"block\" : \"top\",\n              stateArg: null,\n              context: new Context(inline ? \"block\" : \"top\", base || 0, null)};\n    },\n\n    token: function(stream, state) {\n      if (!state.tokenize && stream.eatSpace()) return null;\n      var style = (state.tokenize || tokenBase)(stream, state);\n      if (style && typeof style == \"object\") {\n        type = style[1];\n        style = style[0];\n      }\n      override = style;\n      if (type != \"comment\")\n        state.state = states[state.state](type, stream, state);\n      return override;\n    },\n\n    indent: function(state, textAfter) {\n      var cx = state.context, ch = textAfter && textAfter.charAt(0);\n      var indent = cx.indent;\n      if (cx.type == \"prop\" && (ch == \"}\" || ch == \")\")) cx = cx.prev;\n      if (cx.prev) {\n        if (ch == \"}\" && (cx.type == \"block\" || cx.type == \"top\" ||\n                          cx.type == \"interpolation\" || cx.type == \"restricted_atBlock\")) {\n          // Resume indentation from parent context.\n          cx = cx.prev;\n          indent = cx.indent;\n        } else if (ch == \")\" && (cx.type == \"parens\" || cx.type == \"atBlock_parens\") ||\n            ch == \"{\" && (cx.type == \"at\" || cx.type == \"atBlock\")) {\n          // Dedent relative to current context.\n          indent = Math.max(0, cx.indent - indentUnit);\n        }\n      }\n      return indent;\n    },\n\n    electricChars: \"}\",\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    blockCommentContinue: \" * \",\n    lineComment: lineComment,\n    fold: \"brace\"\n  };\n});\n\n  function keySet(array) {\n    var keys = {};\n    for (var i = 0; i < array.length; ++i) {\n      keys[array[i].toLowerCase()] = true;\n    }\n    return keys;\n  }\n\n  var documentTypes_ = [\n    \"domain\", \"regexp\", \"url\", \"url-prefix\"\n  ], documentTypes = keySet(documentTypes_);\n\n  var mediaTypes_ = [\n    \"all\", \"aural\", \"braille\", \"handheld\", \"print\", \"projection\", \"screen\",\n    \"tty\", \"tv\", \"embossed\"\n  ], mediaTypes = keySet(mediaTypes_);\n\n  var mediaFeatures_ = [\n    \"width\", \"min-width\", \"max-width\", \"height\", \"min-height\", \"max-height\",\n    \"device-width\", \"min-device-width\", \"max-device-width\", \"device-height\",\n    \"min-device-height\", \"max-device-height\", \"aspect-ratio\",\n    \"min-aspect-ratio\", \"max-aspect-ratio\", \"device-aspect-ratio\",\n    \"min-device-aspect-ratio\", \"max-device-aspect-ratio\", \"color\", \"min-color\",\n    \"max-color\", \"color-index\", \"min-color-index\", \"max-color-index\",\n    \"monochrome\", \"min-monochrome\", \"max-monochrome\", \"resolution\",\n    \"min-resolution\", \"max-resolution\", \"scan\", \"grid\", \"orientation\",\n    \"device-pixel-ratio\", \"min-device-pixel-ratio\", \"max-device-pixel-ratio\",\n    \"pointer\", \"any-pointer\", \"hover\", \"any-hover\"\n  ], mediaFeatures = keySet(mediaFeatures_);\n\n  var mediaValueKeywords_ = [\n    \"landscape\", \"portrait\", \"none\", \"coarse\", \"fine\", \"on-demand\", \"hover\",\n    \"interlace\", \"progressive\"\n  ], mediaValueKeywords = keySet(mediaValueKeywords_);\n\n  var propertyKeywords_ = [\n    \"align-content\", \"align-items\", \"align-self\", \"alignment-adjust\",\n    \"alignment-baseline\", \"anchor-point\", \"animation\", \"animation-delay\",\n    \"animation-direction\", \"animation-duration\", \"animation-fill-mode\",\n    \"animation-iteration-count\", \"animation-name\", \"animation-play-state\",\n    \"animation-timing-function\", \"appearance\", \"azimuth\", \"backface-visibility\",\n    \"background\", \"background-attachment\", \"background-blend-mode\", \"background-clip\",\n    \"background-color\", \"background-image\", \"background-origin\", \"background-position\",\n    \"background-repeat\", \"background-size\", \"baseline-shift\", \"binding\",\n    \"bleed\", \"bookmark-label\", \"bookmark-level\", \"bookmark-state\",\n    \"bookmark-target\", \"border\", \"border-bottom\", \"border-bottom-color\",\n    \"border-bottom-left-radius\", \"border-bottom-right-radius\",\n    \"border-bottom-style\", \"border-bottom-width\", \"border-collapse\",\n    \"border-color\", \"border-image\", \"border-image-outset\",\n    \"border-image-repeat\", \"border-image-slice\", \"border-image-source\",\n    \"border-image-width\", \"border-left\", \"border-left-color\",\n    \"border-left-style\", \"border-left-width\", \"border-radius\", \"border-right\",\n    \"border-right-color\", \"border-right-style\", \"border-right-width\",\n    \"border-spacing\", \"border-style\", \"border-top\", \"border-top-color\",\n    \"border-top-left-radius\", \"border-top-right-radius\", \"border-top-style\",\n    \"border-top-width\", \"border-width\", \"bottom\", \"box-decoration-break\",\n    \"box-shadow\", \"box-sizing\", \"break-after\", \"break-before\", \"break-inside\",\n    \"caption-side\", \"caret-color\", \"clear\", \"clip\", \"color\", \"color-profile\", \"column-count\",\n    \"column-fill\", \"column-gap\", \"column-rule\", \"column-rule-color\",\n    \"column-rule-style\", \"column-rule-width\", \"column-span\", \"column-width\",\n    \"columns\", \"content\", \"counter-increment\", \"counter-reset\", \"crop\", \"cue\",\n    \"cue-after\", \"cue-before\", \"cursor\", \"direction\", \"display\",\n    \"dominant-baseline\", \"drop-initial-after-adjust\",\n    \"drop-initial-after-align\", \"drop-initial-before-adjust\",\n    \"drop-initial-before-align\", \"drop-initial-size\", \"drop-initial-value\",\n    \"elevation\", \"empty-cells\", \"fit\", \"fit-position\", \"flex\", \"flex-basis\",\n    \"flex-direction\", \"flex-flow\", \"flex-grow\", \"flex-shrink\", \"flex-wrap\",\n    \"float\", \"float-offset\", \"flow-from\", \"flow-into\", \"font\", \"font-feature-settings\",\n    \"font-family\", \"font-kerning\", \"font-language-override\", \"font-size\", \"font-size-adjust\",\n    \"font-stretch\", \"font-style\", \"font-synthesis\", \"font-variant\",\n    \"font-variant-alternates\", \"font-variant-caps\", \"font-variant-east-asian\",\n    \"font-variant-ligatures\", \"font-variant-numeric\", \"font-variant-position\",\n    \"font-weight\", \"grid\", \"grid-area\", \"grid-auto-columns\", \"grid-auto-flow\",\n    \"grid-auto-rows\", \"grid-column\", \"grid-column-end\", \"grid-column-gap\",\n    \"grid-column-start\", \"grid-gap\", \"grid-row\", \"grid-row-end\", \"grid-row-gap\",\n    \"grid-row-start\", \"grid-template\", \"grid-template-areas\", \"grid-template-columns\",\n    \"grid-template-rows\", \"hanging-punctuation\", \"height\", \"hyphens\",\n    \"icon\", \"image-orientation\", \"image-rendering\", \"image-resolution\",\n    \"inline-box-align\", \"justify-content\", \"justify-items\", \"justify-self\", \"left\", \"letter-spacing\",\n    \"line-break\", \"line-height\", \"line-stacking\", \"line-stacking-ruby\",\n    \"line-stacking-shift\", \"line-stacking-strategy\", \"list-style\",\n    \"list-style-image\", \"list-style-position\", \"list-style-type\", \"margin\",\n    \"margin-bottom\", \"margin-left\", \"margin-right\", \"margin-top\",\n    \"marks\", \"marquee-direction\", \"marquee-loop\",\n    \"marquee-play-count\", \"marquee-speed\", \"marquee-style\", \"max-height\",\n    \"max-width\", \"min-height\", \"min-width\", \"mix-blend-mode\", \"move-to\", \"nav-down\", \"nav-index\",\n    \"nav-left\", \"nav-right\", \"nav-up\", \"object-fit\", \"object-position\",\n    \"opacity\", \"order\", \"orphans\", \"outline\",\n    \"outline-color\", \"outline-offset\", \"outline-style\", \"outline-width\",\n    \"overflow\", \"overflow-style\", \"overflow-wrap\", \"overflow-x\", \"overflow-y\",\n    \"padding\", \"padding-bottom\", \"padding-left\", \"padding-right\", \"padding-top\",\n    \"page\", \"page-break-after\", \"page-break-before\", \"page-break-inside\",\n    \"page-policy\", \"pause\", \"pause-after\", \"pause-before\", \"perspective\",\n    \"perspective-origin\", \"pitch\", \"pitch-range\", \"place-content\", \"place-items\", \"place-self\", \"play-during\", \"position\",\n    \"presentation-level\", \"punctuation-trim\", \"quotes\", \"region-break-after\",\n    \"region-break-before\", \"region-break-inside\", \"region-fragment\",\n    \"rendering-intent\", \"resize\", \"rest\", \"rest-after\", \"rest-before\", \"richness\",\n    \"right\", \"rotation\", \"rotation-point\", \"ruby-align\", \"ruby-overhang\",\n    \"ruby-position\", \"ruby-span\", \"shape-image-threshold\", \"shape-inside\", \"shape-margin\",\n    \"shape-outside\", \"size\", \"speak\", \"speak-as\", \"speak-header\",\n    \"speak-numeral\", \"speak-punctuation\", \"speech-rate\", \"stress\", \"string-set\",\n    \"tab-size\", \"table-layout\", \"target\", \"target-name\", \"target-new\",\n    \"target-position\", \"text-align\", \"text-align-last\", \"text-decoration\",\n    \"text-decoration-color\", \"text-decoration-line\", \"text-decoration-skip\",\n    \"text-decoration-style\", \"text-emphasis\", \"text-emphasis-color\",\n    \"text-emphasis-position\", \"text-emphasis-style\", \"text-height\",\n    \"text-indent\", \"text-justify\", \"text-outline\", \"text-overflow\", \"text-shadow\",\n    \"text-size-adjust\", \"text-space-collapse\", \"text-transform\", \"text-underline-position\",\n    \"text-wrap\", \"top\", \"transform\", \"transform-origin\", \"transform-style\",\n    \"transition\", \"transition-delay\", \"transition-duration\",\n    \"transition-property\", \"transition-timing-function\", \"unicode-bidi\",\n    \"user-select\", \"vertical-align\", \"visibility\", \"voice-balance\", \"voice-duration\",\n    \"voice-family\", \"voice-pitch\", \"voice-range\", \"voice-rate\", \"voice-stress\",\n    \"voice-volume\", \"volume\", \"white-space\", \"widows\", \"width\", \"will-change\", \"word-break\",\n    \"word-spacing\", \"word-wrap\", \"z-index\",\n    // SVG-specific\n    \"clip-path\", \"clip-rule\", \"mask\", \"enable-background\", \"filter\", \"flood-color\",\n    \"flood-opacity\", \"lighting-color\", \"stop-color\", \"stop-opacity\", \"pointer-events\",\n    \"color-interpolation\", \"color-interpolation-filters\",\n    \"color-rendering\", \"fill\", \"fill-opacity\", \"fill-rule\", \"image-rendering\",\n    \"marker\", \"marker-end\", \"marker-mid\", \"marker-start\", \"shape-rendering\", \"stroke\",\n    \"stroke-dasharray\", \"stroke-dashoffset\", \"stroke-linecap\", \"stroke-linejoin\",\n    \"stroke-miterlimit\", \"stroke-opacity\", \"stroke-width\", \"text-rendering\",\n    \"baseline-shift\", \"dominant-baseline\", \"glyph-orientation-horizontal\",\n    \"glyph-orientation-vertical\", \"text-anchor\", \"writing-mode\"\n  ], propertyKeywords = keySet(propertyKeywords_);\n\n  var nonStandardPropertyKeywords_ = [\n    \"scrollbar-arrow-color\", \"scrollbar-base-color\", \"scrollbar-dark-shadow-color\",\n    \"scrollbar-face-color\", \"scrollbar-highlight-color\", \"scrollbar-shadow-color\",\n    \"scrollbar-3d-light-color\", \"scrollbar-track-color\", \"shape-inside\",\n    \"searchfield-cancel-button\", \"searchfield-decoration\", \"searchfield-results-button\",\n    \"searchfield-results-decoration\", \"zoom\"\n  ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);\n\n  var fontProperties_ = [\n    \"font-family\", \"src\", \"unicode-range\", \"font-variant\", \"font-feature-settings\",\n    \"font-stretch\", \"font-weight\", \"font-style\"\n  ], fontProperties = keySet(fontProperties_);\n\n  var counterDescriptors_ = [\n    \"additive-symbols\", \"fallback\", \"negative\", \"pad\", \"prefix\", \"range\",\n    \"speak-as\", \"suffix\", \"symbols\", \"system\"\n  ], counterDescriptors = keySet(counterDescriptors_);\n\n  var colorKeywords_ = [\n    \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\",\n    \"bisque\", \"black\", \"blanchedalmond\", \"blue\", \"blueviolet\", \"brown\",\n    \"burlywood\", \"cadetblue\", \"chartreuse\", \"chocolate\", \"coral\", \"cornflowerblue\",\n    \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"darkcyan\", \"darkgoldenrod\",\n    \"darkgray\", \"darkgreen\", \"darkkhaki\", \"darkmagenta\", \"darkolivegreen\",\n    \"darkorange\", \"darkorchid\", \"darkred\", \"darksalmon\", \"darkseagreen\",\n    \"darkslateblue\", \"darkslategray\", \"darkturquoise\", \"darkviolet\",\n    \"deeppink\", \"deepskyblue\", \"dimgray\", \"dodgerblue\", \"firebrick\",\n    \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\",\n    \"gold\", \"goldenrod\", \"gray\", \"grey\", \"green\", \"greenyellow\", \"honeydew\",\n    \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\",\n    \"lavenderblush\", \"lawngreen\", \"lemonchiffon\", \"lightblue\", \"lightcoral\",\n    \"lightcyan\", \"lightgoldenrodyellow\", \"lightgray\", \"lightgreen\", \"lightpink\",\n    \"lightsalmon\", \"lightseagreen\", \"lightskyblue\", \"lightslategray\",\n    \"lightsteelblue\", \"lightyellow\", \"lime\", \"limegreen\", \"linen\", \"magenta\",\n    \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"mediumpurple\",\n    \"mediumseagreen\", \"mediumslateblue\", \"mediumspringgreen\", \"mediumturquoise\",\n    \"mediumvioletred\", \"midnightblue\", \"mintcream\", \"mistyrose\", \"moccasin\",\n    \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\",\n    \"orchid\", \"palegoldenrod\", \"palegreen\", \"paleturquoise\", \"palevioletred\",\n    \"papayawhip\", \"peachpuff\", \"peru\", \"pink\", \"plum\", \"powderblue\",\n    \"purple\", \"rebeccapurple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\",\n    \"salmon\", \"sandybrown\", \"seagreen\", \"seashell\", \"sienna\", \"silver\", \"skyblue\",\n    \"slateblue\", \"slategray\", \"snow\", \"springgreen\", \"steelblue\", \"tan\",\n    \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\",\n    \"whitesmoke\", \"yellow\", \"yellowgreen\"\n  ], colorKeywords = keySet(colorKeywords_);\n\n  var valueKeywords_ = [\n    \"above\", \"absolute\", \"activeborder\", \"additive\", \"activecaption\", \"afar\",\n    \"after-white-space\", \"ahead\", \"alias\", \"all\", \"all-scroll\", \"alphabetic\", \"alternate\",\n    \"always\", \"amharic\", \"amharic-abegede\", \"antialiased\", \"appworkspace\",\n    \"arabic-indic\", \"armenian\", \"asterisks\", \"attr\", \"auto\", \"auto-flow\", \"avoid\", \"avoid-column\", \"avoid-page\",\n    \"avoid-region\", \"background\", \"backwards\", \"baseline\", \"below\", \"bidi-override\", \"binary\",\n    \"bengali\", \"blink\", \"block\", \"block-axis\", \"bold\", \"bolder\", \"border\", \"border-box\",\n    \"both\", \"bottom\", \"break\", \"break-all\", \"break-word\", \"bullets\", \"button\", \"button-bevel\",\n    \"buttonface\", \"buttonhighlight\", \"buttonshadow\", \"buttontext\", \"calc\", \"cambodian\",\n    \"capitalize\", \"caps-lock-indicator\", \"caption\", \"captiontext\", \"caret\",\n    \"cell\", \"center\", \"checkbox\", \"circle\", \"cjk-decimal\", \"cjk-earthly-branch\",\n    \"cjk-heavenly-stem\", \"cjk-ideographic\", \"clear\", \"clip\", \"close-quote\",\n    \"col-resize\", \"collapse\", \"color\", \"color-burn\", \"color-dodge\", \"column\", \"column-reverse\",\n    \"compact\", \"condensed\", \"contain\", \"content\", \"contents\",\n    \"content-box\", \"context-menu\", \"continuous\", \"copy\", \"counter\", \"counters\", \"cover\", \"crop\",\n    \"cross\", \"crosshair\", \"currentcolor\", \"cursive\", \"cyclic\", \"darken\", \"dashed\", \"decimal\",\n    \"decimal-leading-zero\", \"default\", \"default-button\", \"dense\", \"destination-atop\",\n    \"destination-in\", \"destination-out\", \"destination-over\", \"devanagari\", \"difference\",\n    \"disc\", \"discard\", \"disclosure-closed\", \"disclosure-open\", \"document\",\n    \"dot-dash\", \"dot-dot-dash\",\n    \"dotted\", \"double\", \"down\", \"e-resize\", \"ease\", \"ease-in\", \"ease-in-out\", \"ease-out\",\n    \"element\", \"ellipse\", \"ellipsis\", \"embed\", \"end\", \"ethiopic\", \"ethiopic-abegede\",\n    \"ethiopic-abegede-am-et\", \"ethiopic-abegede-gez\", \"ethiopic-abegede-ti-er\",\n    \"ethiopic-abegede-ti-et\", \"ethiopic-halehame-aa-er\",\n    \"ethiopic-halehame-aa-et\", \"ethiopic-halehame-am-et\",\n    \"ethiopic-halehame-gez\", \"ethiopic-halehame-om-et\",\n    \"ethiopic-halehame-sid-et\", \"ethiopic-halehame-so-et\",\n    \"ethiopic-halehame-ti-er\", \"ethiopic-halehame-ti-et\", \"ethiopic-halehame-tig\",\n    \"ethiopic-numeric\", \"ew-resize\", \"exclusion\", \"expanded\", \"extends\", \"extra-condensed\",\n    \"extra-expanded\", \"fantasy\", \"fast\", \"fill\", \"fixed\", \"flat\", \"flex\", \"flex-end\", \"flex-start\", \"footnotes\",\n    \"forwards\", \"from\", \"geometricPrecision\", \"georgian\", \"graytext\", \"grid\", \"groove\",\n    \"gujarati\", \"gurmukhi\", \"hand\", \"hangul\", \"hangul-consonant\", \"hard-light\", \"hebrew\",\n    \"help\", \"hidden\", \"hide\", \"higher\", \"highlight\", \"highlighttext\",\n    \"hiragana\", \"hiragana-iroha\", \"horizontal\", \"hsl\", \"hsla\", \"hue\", \"icon\", \"ignore\",\n    \"inactiveborder\", \"inactivecaption\", \"inactivecaptiontext\", \"infinite\",\n    \"infobackground\", \"infotext\", \"inherit\", \"initial\", \"inline\", \"inline-axis\",\n    \"inline-block\", \"inline-flex\", \"inline-grid\", \"inline-table\", \"inset\", \"inside\", \"intrinsic\", \"invert\",\n    \"italic\", \"japanese-formal\", \"japanese-informal\", \"justify\", \"kannada\",\n    \"katakana\", \"katakana-iroha\", \"keep-all\", \"khmer\",\n    \"korean-hangul-formal\", \"korean-hanja-formal\", \"korean-hanja-informal\",\n    \"landscape\", \"lao\", \"large\", \"larger\", \"left\", \"level\", \"lighter\", \"lighten\",\n    \"line-through\", \"linear\", \"linear-gradient\", \"lines\", \"list-item\", \"listbox\", \"listitem\",\n    \"local\", \"logical\", \"loud\", \"lower\", \"lower-alpha\", \"lower-armenian\",\n    \"lower-greek\", \"lower-hexadecimal\", \"lower-latin\", \"lower-norwegian\",\n    \"lower-roman\", \"lowercase\", \"ltr\", \"luminosity\", \"malayalam\", \"match\", \"matrix\", \"matrix3d\",\n    \"media-controls-background\", \"media-current-time-display\",\n    \"media-fullscreen-button\", \"media-mute-button\", \"media-play-button\",\n    \"media-return-to-realtime-button\", \"media-rewind-button\",\n    \"media-seek-back-button\", \"media-seek-forward-button\", \"media-slider\",\n    \"media-sliderthumb\", \"media-time-remaining-display\", \"media-volume-slider\",\n    \"media-volume-slider-container\", \"media-volume-sliderthumb\", \"medium\",\n    \"menu\", \"menulist\", \"menulist-button\", \"menulist-text\",\n    \"menulist-textfield\", \"menutext\", \"message-box\", \"middle\", \"min-intrinsic\",\n    \"mix\", \"mongolian\", \"monospace\", \"move\", \"multiple\", \"multiply\", \"myanmar\", \"n-resize\",\n    \"narrower\", \"ne-resize\", \"nesw-resize\", \"no-close-quote\", \"no-drop\",\n    \"no-open-quote\", \"no-repeat\", \"none\", \"normal\", \"not-allowed\", \"nowrap\",\n    \"ns-resize\", \"numbers\", \"numeric\", \"nw-resize\", \"nwse-resize\", \"oblique\", \"octal\", \"opacity\", \"open-quote\",\n    \"optimizeLegibility\", \"optimizeSpeed\", \"oriya\", \"oromo\", \"outset\",\n    \"outside\", \"outside-shape\", \"overlay\", \"overline\", \"padding\", \"padding-box\",\n    \"painted\", \"page\", \"paused\", \"persian\", \"perspective\", \"plus-darker\", \"plus-lighter\",\n    \"pointer\", \"polygon\", \"portrait\", \"pre\", \"pre-line\", \"pre-wrap\", \"preserve-3d\",\n    \"progress\", \"push-button\", \"radial-gradient\", \"radio\", \"read-only\",\n    \"read-write\", \"read-write-plaintext-only\", \"rectangle\", \"region\",\n    \"relative\", \"repeat\", \"repeating-linear-gradient\",\n    \"repeating-radial-gradient\", \"repeat-x\", \"repeat-y\", \"reset\", \"reverse\",\n    \"rgb\", \"rgba\", \"ridge\", \"right\", \"rotate\", \"rotate3d\", \"rotateX\", \"rotateY\",\n    \"rotateZ\", \"round\", \"row\", \"row-resize\", \"row-reverse\", \"rtl\", \"run-in\", \"running\",\n    \"s-resize\", \"sans-serif\", \"saturation\", \"scale\", \"scale3d\", \"scaleX\", \"scaleY\", \"scaleZ\", \"screen\",\n    \"scroll\", \"scrollbar\", \"scroll-position\", \"se-resize\", \"searchfield\",\n    \"searchfield-cancel-button\", \"searchfield-decoration\",\n    \"searchfield-results-button\", \"searchfield-results-decoration\", \"self-start\", \"self-end\",\n    \"semi-condensed\", \"semi-expanded\", \"separate\", \"serif\", \"show\", \"sidama\",\n    \"simp-chinese-formal\", \"simp-chinese-informal\", \"single\",\n    \"skew\", \"skewX\", \"skewY\", \"skip-white-space\", \"slide\", \"slider-horizontal\",\n    \"slider-vertical\", \"sliderthumb-horizontal\", \"sliderthumb-vertical\", \"slow\",\n    \"small\", \"small-caps\", \"small-caption\", \"smaller\", \"soft-light\", \"solid\", \"somali\",\n    \"source-atop\", \"source-in\", \"source-out\", \"source-over\", \"space\", \"space-around\", \"space-between\", \"space-evenly\", \"spell-out\", \"square\",\n    \"square-button\", \"start\", \"static\", \"status-bar\", \"stretch\", \"stroke\", \"sub\",\n    \"subpixel-antialiased\", \"super\", \"sw-resize\", \"symbolic\", \"symbols\", \"system-ui\", \"table\",\n    \"table-caption\", \"table-cell\", \"table-column\", \"table-column-group\",\n    \"table-footer-group\", \"table-header-group\", \"table-row\", \"table-row-group\",\n    \"tamil\",\n    \"telugu\", \"text\", \"text-bottom\", \"text-top\", \"textarea\", \"textfield\", \"thai\",\n    \"thick\", \"thin\", \"threeddarkshadow\", \"threedface\", \"threedhighlight\",\n    \"threedlightshadow\", \"threedshadow\", \"tibetan\", \"tigre\", \"tigrinya-er\",\n    \"tigrinya-er-abegede\", \"tigrinya-et\", \"tigrinya-et-abegede\", \"to\", \"top\",\n    \"trad-chinese-formal\", \"trad-chinese-informal\", \"transform\",\n    \"translate\", \"translate3d\", \"translateX\", \"translateY\", \"translateZ\",\n    \"transparent\", \"ultra-condensed\", \"ultra-expanded\", \"underline\", \"unset\", \"up\",\n    \"upper-alpha\", \"upper-armenian\", \"upper-greek\", \"upper-hexadecimal\",\n    \"upper-latin\", \"upper-norwegian\", \"upper-roman\", \"uppercase\", \"urdu\", \"url\",\n    \"var\", \"vertical\", \"vertical-text\", \"visible\", \"visibleFill\", \"visiblePainted\",\n    \"visibleStroke\", \"visual\", \"w-resize\", \"wait\", \"wave\", \"wider\",\n    \"window\", \"windowframe\", \"windowtext\", \"words\", \"wrap\", \"wrap-reverse\", \"x-large\", \"x-small\", \"xor\",\n    \"xx-large\", \"xx-small\"\n  ], valueKeywords = keySet(valueKeywords_);\n\n  var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)\n    .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)\n    .concat(valueKeywords_);\n  CodeMirror.registerHelper(\"hintWords\", \"css\", allWords);\n\n  function tokenCComment(stream, state) {\n    var maybeEnd = false, ch;\n    while ((ch = stream.next()) != null) {\n      if (maybeEnd && ch == \"/\") {\n        state.tokenize = null;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return [\"comment\", \"comment\"];\n  }\n\n  CodeMirror.defineMIME(\"text/css\", {\n    documentTypes: documentTypes,\n    mediaTypes: mediaTypes,\n    mediaFeatures: mediaFeatures,\n    mediaValueKeywords: mediaValueKeywords,\n    propertyKeywords: propertyKeywords,\n    nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n    fontProperties: fontProperties,\n    counterDescriptors: counterDescriptors,\n    colorKeywords: colorKeywords,\n    valueKeywords: valueKeywords,\n    tokenHooks: {\n      \"/\": function(stream, state) {\n        if (!stream.eat(\"*\")) return false;\n        state.tokenize = tokenCComment;\n        return tokenCComment(stream, state);\n      }\n    },\n    name: \"css\"\n  });\n\n  CodeMirror.defineMIME(\"text/x-scss\", {\n    mediaTypes: mediaTypes,\n    mediaFeatures: mediaFeatures,\n    mediaValueKeywords: mediaValueKeywords,\n    propertyKeywords: propertyKeywords,\n    nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n    colorKeywords: colorKeywords,\n    valueKeywords: valueKeywords,\n    fontProperties: fontProperties,\n    allowNested: true,\n    lineComment: \"//\",\n    tokenHooks: {\n      \"/\": function(stream, state) {\n        if (stream.eat(\"/\")) {\n          stream.skipToEnd();\n          return [\"comment\", \"comment\"];\n        } else if (stream.eat(\"*\")) {\n          state.tokenize = tokenCComment;\n          return tokenCComment(stream, state);\n        } else {\n          return [\"operator\", \"operator\"];\n        }\n      },\n      \":\": function(stream) {\n        if (stream.match(/\\s*\\{/, false))\n          return [null, null]\n        return false;\n      },\n      \"$\": function(stream) {\n        stream.match(/^[\\w-]+/);\n        if (stream.match(/^\\s*:/, false))\n          return [\"variable-2\", \"variable-definition\"];\n        return [\"variable-2\", \"variable\"];\n      },\n      \"#\": function(stream) {\n        if (!stream.eat(\"{\")) return false;\n        return [null, \"interpolation\"];\n      }\n    },\n    name: \"css\",\n    helperType: \"scss\"\n  });\n\n  CodeMirror.defineMIME(\"text/x-less\", {\n    mediaTypes: mediaTypes,\n    mediaFeatures: mediaFeatures,\n    mediaValueKeywords: mediaValueKeywords,\n    propertyKeywords: propertyKeywords,\n    nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n    colorKeywords: colorKeywords,\n    valueKeywords: valueKeywords,\n    fontProperties: fontProperties,\n    allowNested: true,\n    lineComment: \"//\",\n    tokenHooks: {\n      \"/\": function(stream, state) {\n        if (stream.eat(\"/\")) {\n          stream.skipToEnd();\n          return [\"comment\", \"comment\"];\n        } else if (stream.eat(\"*\")) {\n          state.tokenize = tokenCComment;\n          return tokenCComment(stream, state);\n        } else {\n          return [\"operator\", \"operator\"];\n        }\n      },\n      \"@\": function(stream) {\n        if (stream.eat(\"{\")) return [null, \"interpolation\"];\n        if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\\b/i, false)) return false;\n        stream.eatWhile(/[\\w\\\\\\-]/);\n        if (stream.match(/^\\s*:/, false))\n          return [\"variable-2\", \"variable-definition\"];\n        return [\"variable-2\", \"variable\"];\n      },\n      \"&\": function() {\n        return [\"atom\", \"atom\"];\n      }\n    },\n    name: \"css\",\n    helperType: \"less\"\n  });\n\n  CodeMirror.defineMIME(\"text/x-gss\", {\n    documentTypes: documentTypes,\n    mediaTypes: mediaTypes,\n    mediaFeatures: mediaFeatures,\n    propertyKeywords: propertyKeywords,\n    nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n    fontProperties: fontProperties,\n    counterDescriptors: counterDescriptors,\n    colorKeywords: colorKeywords,\n    valueKeywords: valueKeywords,\n    supportsAtComponent: true,\n    tokenHooks: {\n      \"/\": function(stream, state) {\n        if (!stream.eat(\"*\")) return false;\n        state.tokenize = tokenCComment;\n        return tokenCComment(stream, state);\n      }\n    },\n    name: \"css\",\n    helperType: \"gss\"\n  });\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/css/gss.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Closure Stylesheets (GSS) mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../addon/hint/show-hint.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"css.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"../../addon/hint/show-hint.js\"></script>\n<script src=\"../../addon/hint/css-hint.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Closure Stylesheets (GSS)</a>\n  </ul>\n</div>\n\n<article>\n<h2>Closure Stylesheets (GSS) mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n/* Some example Closure Stylesheets */\n\n@provide 'some.styles';\n\n@require 'other.styles';\n\n@component {\n\n@def FONT_FAMILY           \"Times New Roman\", Georgia, Serif;\n@def FONT_SIZE_NORMAL      15px;\n@def FONT_NORMAL           normal FONT_SIZE_NORMAL FONT_FAMILY;\n\n@def BG_COLOR              rgb(235, 239, 249);\n\n@def DIALOG_BORDER_COLOR   rgb(107, 144, 218);\n@def DIALOG_BG_COLOR       BG_COLOR;\n\n@def LEFT_HAND_NAV_WIDTH    180px;\n@def LEFT_HAND_NAV_PADDING  3px;\n\n@defmixin size(WIDTH, HEIGHT) {\n  width: WIDTH;\n  height: HEIGHT;\n}\n\nbody {\n  background-color: BG_COLOR;\n  margin: 0;\n  padding: 3em 6em;\n  font: FONT_NORMAL;\n  color: #000;\n}\n\n#navigation a {\n  font-weight: bold;\n  text-decoration: none !important;\n}\n\n.dialog {\n  background-color: DIALOG_BG_COLOR;\n  border: 1px solid DIALOG_BORDER_COLOR;\n}\n\n.content {\n  position: absolute;\n  margin-left: add(LEFT_HAND_NAV_PADDING,  /* padding left */\n                   LEFT_HAND_NAV_WIDTH,\n                   LEFT_HAND_NAV_PADDING); /* padding right */\n\n}\n\n.logo {\n  @mixin size(150px, 55px);\n  background-image: url('http://www.google.com/images/logo_sm.gif');\n}\n\n}\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        extraKeys: {\"Ctrl-Space\": \"autocomplete\"},\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-gss\"\n      });\n    </script>\n\n    <p>A mode for <a href=\"https://github.com/google/closure-stylesheets\">Closure Stylesheets</a> (GSS).</p>\n    <p><strong>MIME type defined:</strong> <code>text/x-gss</code>.</p>\n\n    <p><strong>Parsing/Highlighting Tests:</strong> <a href=\"../../test/index.html#gss_*\">normal</a>,  <a href=\"../../test/index.html#verbose,gss_*\">verbose</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/css/gss_test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  \"use strict\";\n\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"text/x-gss\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), \"gss\"); }\n\n  MT(\"atComponent\",\n     \"[def @component] {\",\n     \"[tag foo] {\",\n     \"  [property color]: [keyword black];\",\n     \"}\",\n     \"}\");\n\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/css/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: CSS mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../addon/hint/show-hint.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"css.js\"></script>\n<script src=\"../../addon/hint/show-hint.js\"></script>\n<script src=\"../../addon/hint/css-hint.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">CSS</a>\n  </ul>\n</div>\n\n<article>\n<h2>CSS mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n/* Some example CSS */\n\n@import url(\"something.css\");\n\nbody {\n  margin: 0;\n  padding: 3em 6em;\n  font-family: tahoma, arial, sans-serif;\n  color: #000;\n}\n\n#navigation a {\n  font-weight: bold;\n  text-decoration: none !important;\n}\n\nh1 {\n  font-size: 2.5em;\n}\n\nh2 {\n  font-size: 1.7em;\n}\n\nh1:before, h2:before {\n  content: \"::\";\n}\n\ncode {\n  font-family: courier, monospace;\n  font-size: 80%;\n  color: #418A8A;\n}\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        extraKeys: {\"Ctrl-Space\": \"autocomplete\"}\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/css</code>, <code>text/x-scss</code> (<a href=\"scss.html\">demo</a>), <code>text/x-less</code> (<a href=\"less.html\">demo</a>).</p>\n\n    <p><strong>Parsing/Highlighting Tests:</strong> <a href=\"../../test/index.html#css_*\">normal</a>,  <a href=\"../../test/index.html#verbose,css_*\">verbose</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/css/less.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: LESS mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"css.js\"></script>\n<style>.CodeMirror {border: 1px solid #ddd; line-height: 1.2;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">LESS</a>\n  </ul>\n</div>\n\n<article>\n<h2>LESS mode</h2>\n<form><textarea id=\"code\" name=\"code\">@media screen and (device-aspect-ratio: 16/9) { … }\n@media screen and (device-aspect-ratio: 1280/720) { … }\n@media screen and (device-aspect-ratio: 2560/1440) { … }\n\nhtml:lang(fr-be)\n\ntr:nth-child(2n+1) /* represents every odd row of an HTML table */\n\nimg:nth-of-type(2n+1) { float: right; }\nimg:nth-of-type(2n) { float: left; }\n\nbody > h2:not(:first-of-type):not(:last-of-type)\n\nhtml|*:not(:link):not(:visited)\n*|*:not(:hover)\np::first-line { text-transform: uppercase }\n\n@namespace foo url(http://www.example.com);\nfoo|h1 { color: blue }  /* first rule */\n\nspan[hello=\"Ocean\"][goodbye=\"Land\"]\n\nE[foo]{\n  padding:65px;\n}\n\ninput[type=\"search\"]::-webkit-search-decoration,\ninput[type=\"search\"]::-webkit-search-cancel-button {\n  -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5\n}\nbutton::-moz-focus-inner,\ninput::-moz-focus-inner { // Inner padding and border oddities in FF3/4\n  padding: 0;\n  border: 0;\n}\n.btn {\n  // reset here as of 2.0.3 due to Recess property order\n  border-color: #ccc;\n  border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);\n}\nfieldset span button, fieldset span input[type=\"file\"] {\n  font-size:12px;\n\tfont-family:Arial, Helvetica, sans-serif;\n}\n\n.rounded-corners (@radius: 5px) {\n  border-radius: @radius;\n  -webkit-border-radius: @radius;\n  -moz-border-radius: @radius;\n}\n\n@import url(\"something.css\");\n\n@light-blue:   hsl(190, 50%, 65%);\n\n#menu {\n  position: absolute;\n  width: 100%;\n  z-index: 3;\n  clear: both;\n  display: block;\n  background-color: @blue;\n  height: 42px;\n  border-top: 2px solid lighten(@alpha-blue, 20%);\n  border-bottom: 2px solid darken(@alpha-blue, 25%);\n  .box-shadow(0, 1px, 8px, 0.6);\n  -moz-box-shadow: 0 0 0 #000; // Because firefox sucks.\n\n  &.docked {\n    background-color: hsla(210, 60%, 40%, 0.4);\n  }\n  &:hover {\n    background-color: @blue;\n  }\n\n  #dropdown {\n    margin: 0 0 0 117px;\n    padding: 0;\n    padding-top: 5px;\n    display: none;\n    width: 190px;\n    border-top: 2px solid @medium;\n    color: @highlight;\n    border: 2px solid darken(@medium, 25%);\n    border-left-color: darken(@medium, 15%);\n    border-right-color: darken(@medium, 15%);\n    border-top-width: 0;\n    background-color: darken(@medium, 10%);\n    ul {\n      padding: 0px;  \n    }\n    li {\n      font-size: 14px;\n      display: block;\n      text-align: left;\n      padding: 0;\n      border: 0;\n      a {\n        display: block;\n        padding: 0px 15px;  \n        text-decoration: none;\n        color: white;  \n        &:hover {\n          background-color: darken(@medium, 15%);\n          text-decoration: none;\n        }\n      }\n    }\n    .border-radius(5px, bottom);\n    .box-shadow(0, 6px, 8px, 0.5);\n  }\n}\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-less\"\n      });\n    </script>\n\n    <p>The LESS mode is a sub-mode of the <a href=\"index.html\">CSS mode</a> (defined in <code>css.js</code>).</p>\n\n    <p><strong>Parsing/Highlighting Tests:</strong> <a href=\"../../test/index.html#less_*\">normal</a>,  <a href=\"../../test/index.html#verbose,less_*\">verbose</a>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/css/less_test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  \"use strict\";\n\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"text/x-less\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), \"less\"); }\n\n  MT(\"variable\",\n     \"[variable-2 @base]: [atom #f04615];\",\n     \"[qualifier .class] {\",\n     \"  [property width]: [variable&callee percentage]([number 0.5]); [comment // returns `50%`]\",\n     \"  [property color]: [variable&callee saturate]([variable-2 @base], [number 5%]);\",\n     \"}\");\n\n  MT(\"amp\",\n     \"[qualifier .child], [qualifier .sibling] {\",\n     \"  [qualifier .parent] [atom &] {\",\n     \"    [property color]: [keyword black];\",\n     \"  }\",\n     \"  [atom &] + [atom &] {\",\n     \"    [property color]: [keyword red];\",\n     \"  }\",\n     \"}\");\n\n  MT(\"mixin\",\n     \"[qualifier .mixin] ([variable dark]; [variable-2 @color]) {\",\n     \"  [property color]: [variable&callee darken]([variable-2 @color], [number 10%]);\",\n     \"}\",\n     \"[qualifier .mixin] ([variable light]; [variable-2 @color]) {\",\n     \"  [property color]: [variable&callee lighten]([variable-2 @color], [number 10%]);\",\n     \"}\",\n     \"[qualifier .mixin] ([variable-2 @_]; [variable-2 @color]) {\",\n     \"  [property display]: [atom block];\",\n     \"}\",\n     \"[variable-2 @switch]: [variable light];\",\n     \"[qualifier .class] {\",\n     \"  [qualifier .mixin]([variable-2 @switch]; [atom #888]);\",\n     \"}\");\n\n  MT(\"nest\",\n     \"[qualifier .one] {\",\n     \"  [def @media] ([property width]: [number 400px]) {\",\n     \"    [property font-size]: [number 1.2em];\",\n     \"    [def @media] [attribute print] [keyword and] [property color] {\",\n     \"      [property color]: [keyword blue];\",\n     \"    }\",\n     \"  }\",\n     \"}\");\n\n\n  MT(\"interpolation\", \".@{[variable foo]} { [property font-weight]: [atom bold]; }\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/css/scss.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: SCSS mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"css.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">SCSS</a>\n  </ul>\n</div>\n\n<article>\n<h2>SCSS mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n/* Some example SCSS */\n\n@import \"compass/css3\";\n$variable: #333;\n\n$blue: #3bbfce;\n$margin: 16px;\n\n.content-navigation {\n  #nested {\n    background-color: black;\n  }\n  border-color: $blue;\n  color:\n    darken($blue, 9%);\n}\n\n.border {\n  padding: $margin / 2;\n  margin: $margin / 2;\n  border-color: $blue;\n}\n\n@mixin table-base {\n  th {\n    text-align: center;\n    font-weight: bold;\n  }\n  td, th {padding: 2px}\n}\n\ntable.hl {\n  margin: 2em 0;\n  td.ln {\n    text-align: right;\n  }\n}\n\nli {\n  font: {\n    family: serif;\n    weight: bold;\n    size: 1.2em;\n  }\n}\n\n@mixin left($dist) {\n  float: left;\n  margin-left: $dist;\n}\n\n#data {\n  @include left(10px);\n  @include table-base;\n}\n\n.source {\n  @include flow-into(target);\n  border: 10px solid green;\n  margin: 20px;\n  width: 200px; }\n\n.new-container {\n  @include flow-from(target);\n  border: 10px solid red;\n  margin: 20px;\n  width: 200px; }\n\nbody {\n  margin: 0;\n  padding: 3em 6em;\n  font-family: tahoma, arial, sans-serif;\n  color: #000;\n}\n\n@mixin yellow() {\n  background: yellow;\n}\n\n.big {\n  font-size: 14px;\n}\n\n.nested {\n  @include border-radius(3px);\n  @extend .big;\n  p {\n    background: whitesmoke;\n    a {\n      color: red;\n    }\n  }\n}\n\n#navigation a {\n  font-weight: bold;\n  text-decoration: none !important;\n}\n\nh1 {\n  font-size: 2.5em;\n}\n\nh2 {\n  font-size: 1.7em;\n}\n\nh1:before, h2:before {\n  content: \"::\";\n}\n\ncode {\n  font-family: courier, monospace;\n  font-size: 80%;\n  color: #418A8A;\n}\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-scss\"\n      });\n    </script>\n\n    <p>The SCSS mode is a sub-mode of the <a href=\"index.html\">CSS mode</a> (defined in <code>css.js</code>).</p>\n\n    <p><strong>Parsing/Highlighting Tests:</strong> <a href=\"../../test/index.html#scss_*\">normal</a>,  <a href=\"../../test/index.html#verbose,scss_*\">verbose</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/css/scss_test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"text/x-scss\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), \"scss\"); }\n\n  MT('url_with_quotation',\n    \"[tag foo] { [property background]:[variable&callee url]([string test.jpg]) }\");\n\n  MT('url_with_double_quotes',\n    \"[tag foo] { [property background]:[variable&callee url]([string \\\"test.jpg\\\"]) }\");\n\n  MT('url_with_single_quotes',\n    \"[tag foo] { [property background]:[variable&callee url]([string \\'test.jpg\\']) }\");\n\n  MT('string',\n    \"[def @import] [string \\\"compass/css3\\\"]\");\n\n  MT('important_keyword',\n    \"[tag foo] { [property background]:[variable&callee url]([string \\'test.jpg\\']) [keyword !important] }\");\n\n  MT('variable',\n    \"[variable-2 $blue]:[atom #333]\");\n\n  MT('variable_as_attribute',\n    \"[tag foo] { [property color]:[variable-2 $blue] }\");\n\n  MT('numbers',\n    \"[tag foo] { [property padding]:[number 10px] [number 10] [number 10em] [number 8in] }\");\n\n  MT('number_percentage',\n    \"[tag foo] { [property width]:[number 80%] }\");\n\n  MT('selector',\n    \"[builtin #hello][qualifier .world]{}\");\n\n  MT('singleline_comment',\n    \"[comment // this is a comment]\");\n\n  MT('multiline_comment',\n    \"[comment /*foobar*/]\");\n\n  MT('attribute_with_hyphen',\n    \"[tag foo] { [property font-size]:[number 10px] }\");\n\n  MT('string_after_attribute',\n    \"[tag foo] { [property content]:[string \\\"::\\\"] }\");\n\n  MT('directives',\n    \"[def @include] [qualifier .mixin]\");\n\n  MT('basic_structure',\n    \"[tag p] { [property background]:[keyword red]; }\");\n\n  MT('nested_structure',\n    \"[tag p] { [tag a] { [property color]:[keyword red]; } }\");\n\n  MT('mixin',\n    \"[def @mixin] [tag table-base] {}\");\n\n  MT('number_without_semicolon',\n    \"[tag p] {[property width]:[number 12]}\",\n    \"[tag a] {[property color]:[keyword red];}\");\n\n  MT('atom_in_nested_block',\n    \"[tag p] { [tag a] { [property color]:[atom #000]; } }\");\n\n  MT('interpolation_in_property',\n    \"[tag foo] { #{[variable-2 $hello]}:[number 2]; }\");\n\n  MT('interpolation_in_selector',\n    \"[tag foo]#{[variable-2 $hello]} { [property color]:[atom #000]; }\");\n\n  MT('interpolation_error',\n    \"[tag foo]#{[variable foo]} { [property color]:[atom #000]; }\");\n\n  MT(\"divide_operator\",\n    \"[tag foo] { [property width]:[number 4] [operator /] [number 2] }\");\n\n  MT('nested_structure_with_id_selector',\n    \"[tag p] { [builtin #hello] { [property color]:[keyword red]; } }\");\n\n  MT('indent_mixin',\n     \"[def @mixin] [tag container] (\",\n     \"  [variable-2 $a]: [number 10],\",\n     \"  [variable-2 $b]: [number 10])\",\n     \"{}\");\n\n  MT('indent_nested',\n     \"[tag foo] {\",\n     \"  [tag bar] {\",\n     \"  }\",\n     \"}\");\n\n  MT('indent_parentheses',\n     \"[tag foo] {\",\n     \"  [property color]: [variable&callee darken]([variable-2 $blue],\",\n     \"    [number 9%]);\",\n     \"}\");\n\n  MT('indent_vardef',\n     \"[variable-2 $name]:\",\n     \"  [string 'val'];\",\n     \"[tag tag] {\",\n     \"  [tag inner] {\",\n     \"    [property margin]: [number 3px];\",\n     \"  }\",\n     \"}\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/css/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"css\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  // Error, because \"foobarhello\" is neither a known type or property, but\n  // property was expected (after \"and\"), and it should be in parentheses.\n  MT(\"atMediaUnknownType\",\n     \"[def @media] [attribute screen] [keyword and] [error foobarhello] { }\");\n\n  // Soft error, because \"foobarhello\" is not a known property or type.\n  MT(\"atMediaUnknownProperty\",\n     \"[def @media] [attribute screen] [keyword and] ([error foobarhello]) { }\");\n\n  // Make sure nesting works with media queries\n  MT(\"atMediaMaxWidthNested\",\n     \"[def @media] [attribute screen] [keyword and] ([property max-width]: [number 25px]) { [tag foo] { } }\");\n\n  MT(\"atMediaFeatureValueKeyword\",\n     \"[def @media] ([property orientation]: [keyword landscape]) { }\");\n\n  MT(\"atMediaUnknownFeatureValueKeyword\",\n     \"[def @media] ([property orientation]: [error upsidedown]) { }\");\n\n  MT(\"atMediaUppercase\",\n     \"[def @MEDIA] ([property orienTAtion]: [keyword landScape]) { }\");\n\n  MT(\"tagSelector\",\n     \"[tag foo] { }\");\n\n  MT(\"classSelector\",\n     \"[qualifier .foo-bar_hello] { }\");\n\n  MT(\"idSelector\",\n     \"[builtin #foo] { [error #foo] }\");\n\n  MT(\"tagSelectorUnclosed\",\n     \"[tag foo] { [property margin]: [number 0] } [tag bar] { }\");\n\n  MT(\"tagStringNoQuotes\",\n     \"[tag foo] { [property font-family]: [variable hello] [variable world]; }\");\n\n  MT(\"tagStringDouble\",\n     \"[tag foo] { [property font-family]: [string \\\"hello world\\\"]; }\");\n\n  MT(\"tagStringSingle\",\n     \"[tag foo] { [property font-family]: [string 'hello world']; }\");\n\n  MT(\"tagColorKeyword\",\n     \"[tag foo] {\",\n     \"  [property color]: [keyword black];\",\n     \"  [property color]: [keyword navy];\",\n     \"  [property color]: [keyword yellow];\",\n     \"}\");\n\n  MT(\"tagColorHex3\",\n     \"[tag foo] { [property background]: [atom #fff]; }\");\n\n  MT(\"tagColorHex4\",\n     \"[tag foo] { [property background]: [atom #ffff]; }\");\n\n  MT(\"tagColorHex6\",\n     \"[tag foo] { [property background]: [atom #ffffff]; }\");\n\n  MT(\"tagColorHex8\",\n     \"[tag foo] { [property background]: [atom #ffffffff]; }\");\n\n  MT(\"tagColorHex5Invalid\",\n     \"[tag foo] { [property background]: [atom&error #fffff]; }\");\n\n  MT(\"tagColorHexInvalid\",\n     \"[tag foo] { [property background]: [atom&error #ffg]; }\");\n\n  MT(\"tagNegativeNumber\",\n     \"[tag foo] { [property margin]: [number -5px]; }\");\n\n  MT(\"tagPositiveNumber\",\n     \"[tag foo] { [property padding]: [number 5px]; }\");\n\n  MT(\"tagVendor\",\n     \"[tag foo] { [meta -foo-][property box-sizing]: [meta -foo-][atom border-box]; }\");\n\n  MT(\"tagBogusProperty\",\n     \"[tag foo] { [property&error barhelloworld]: [number 0]; }\");\n\n  MT(\"tagTwoProperties\",\n     \"[tag foo] { [property margin]: [number 0]; [property padding]: [number 0]; }\");\n\n  MT(\"tagTwoPropertiesURL\",\n     \"[tag foo] { [property background]: [variable&callee url]([string //example.com/foo.png]); [property padding]: [number 0]; }\");\n\n  MT(\"indent_tagSelector\",\n     \"[tag strong], [tag em] {\",\n     \"  [property background]: [variable&callee rgba](\",\n     \"    [number 255], [number 255], [number 0], [number .2]\",\n     \"  );\",\n     \"}\");\n\n  MT(\"indent_atMedia\",\n     \"[def @media] {\",\n     \"  [tag foo] {\",\n     \"    [property color]:\",\n     \"      [keyword yellow];\",\n     \"  }\",\n     \"}\");\n\n  MT(\"indent_comma\",\n     \"[tag foo] {\",\n     \"  [property font-family]: [variable verdana],\",\n     \"    [atom sans-serif];\",\n     \"}\");\n\n  MT(\"indent_parentheses\",\n     \"[tag foo]:[variable-3 before] {\",\n     \"  [property background]: [variable&callee url](\",\n     \"[string     blahblah]\",\n     \"[string     etc]\",\n     \"[string   ]) [keyword !important];\",\n     \"}\");\n\n  MT(\"font_face\",\n     \"[def @font-face] {\",\n     \"  [property font-family]: [string 'myfont'];\",\n     \"  [error nonsense]: [string 'abc'];\",\n     \"  [property src]: [variable&callee url]([string http://blah]),\",\n     \"    [variable&callee url]([string http://foo]);\",\n     \"}\");\n\n  MT(\"empty_url\",\n     \"[def @import] [variable&callee url]() [attribute screen];\");\n\n  MT(\"parens\",\n     \"[qualifier .foo] {\",\n     \"  [property background-image]: [variable&callee fade]([atom #000], [number 20%]);\",\n     \"  [property border-image]: [variable&callee linear-gradient](\",\n     \"    [atom to] [atom bottom],\",\n     \"    [variable&callee fade]([atom #000], [number 20%]) [number 0%],\",\n     \"    [variable&callee fade]([atom #000], [number 20%]) [number 100%]\",\n     \"  );\",\n     \"}\");\n\n  MT(\"css_variable\",\n     \":[variable-3 root] {\",\n     \"  [variable-2 --main-color]: [atom #06c];\",\n     \"}\",\n     \"[tag h1][builtin #foo] {\",\n     \"  [property color]: [variable&callee var]([variable-2 --main-color]);\",\n     \"}\");\n\n  MT(\"blank_css_variable\",\n     \":[variable-3 root] {\",\n     \"  [variable-2 --]: [atom #06c];\",\n     \"}\",\n     \"[tag h1][builtin #foo] {\",\n     \"  [property color]: [variable&callee var]([variable-2 --]);\",\n     \"}\");\n\n  MT(\"supports\",\n     \"[def @supports] ([keyword not] (([property text-align-last]: [atom justify]) [keyword or] ([meta -moz-][property text-align-last]: [atom justify])) {\",\n     \"  [property text-align-last]: [atom justify];\",\n     \"}\");\n\n   MT(\"document\",\n      \"[def @document] [variable&callee url]([string http://blah]),\",\n      \"  [variable&callee url-prefix]([string https://]),\",\n      \"  [variable&callee domain]([string blah.com]),\",\n      \"  [variable&callee regexp]([string \\\".*blah.+\\\"]) {\",\n      \"    [builtin #id] {\",\n      \"      [property background-color]: [keyword white];\",\n      \"    }\",\n      \"    [tag foo] {\",\n      \"      [property font-family]: [variable Verdana], [atom sans-serif];\",\n      \"    }\",\n      \"}\");\n\n   MT(\"document_url\",\n      \"[def @document] [variable&callee url]([string http://blah]) { [qualifier .class] { } }\");\n\n   MT(\"document_urlPrefix\",\n      \"[def @document] [variable&callee url-prefix]([string https://]) { [builtin #id] { } }\");\n\n   MT(\"document_domain\",\n      \"[def @document] [variable&callee domain]([string blah.com]) { [tag foo] { } }\");\n\n   MT(\"document_regexp\",\n      \"[def @document] [variable&callee regexp]([string \\\".*blah.+\\\"]) { [builtin #id] { } }\");\n\n   MT(\"counter-style\",\n      \"[def @counter-style] [variable binary] {\",\n      \"  [property system]: [atom numeric];\",\n      \"  [property symbols]: [number 0] [number 1];\",\n      \"  [property suffix]: [string \\\".\\\"];\",\n      \"  [property range]: [atom infinite];\",\n      \"  [property speak-as]: [atom numeric];\",\n      \"}\");\n\n   MT(\"counter-style-additive-symbols\",\n      \"[def @counter-style] [variable simple-roman] {\",\n      \"  [property system]: [atom additive];\",\n      \"  [property additive-symbols]: [number 10] [variable X], [number 5] [variable V], [number 1] [variable I];\",\n      \"  [property range]: [number 1] [number 49];\",\n      \"}\");\n\n   MT(\"counter-style-use\",\n      \"[tag ol][qualifier .roman] { [property list-style]: [variable simple-roman]; }\");\n\n   MT(\"counter-style-symbols\",\n      \"[tag ol] { [property list-style]: [variable&callee symbols]([atom cyclic] [string \\\"*\\\"] [string \\\"\\\\2020\\\"] [string \\\"\\\\2021\\\"] [string \\\"\\\\A7\\\"]); }\");\n\n  MT(\"comment-does-not-disrupt\",\n     \"[def @font-face] [comment /* foo */] {\",\n     \"  [property src]: [variable&callee url]([string x]);\",\n     \"  [property font-family]: [variable One];\",\n     \"}\")\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/cypher/cypher.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// By the Neo4j Team and contributors.\n// https://github.com/neo4j-contrib/CodeMirror\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n  var wordRegexp = function(words) {\n    return new RegExp(\"^(?:\" + words.join(\"|\") + \")$\", \"i\");\n  };\n\n  CodeMirror.defineMode(\"cypher\", function(config) {\n    var tokenBase = function(stream/*, state*/) {\n      var ch = stream.next();\n      if (ch ==='\"') {\n        stream.match(/.*?\"/);\n        return \"string\";\n      }\n      if (ch === \"'\") {\n        stream.match(/.*?'/);\n        return \"string\";\n      }\n      if (/[{}\\(\\),\\.;\\[\\]]/.test(ch)) {\n        curPunc = ch;\n        return \"node\";\n      } else if (ch === \"/\" && stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      } else if (operatorChars.test(ch)) {\n        stream.eatWhile(operatorChars);\n        return null;\n      } else {\n        stream.eatWhile(/[_\\w\\d]/);\n        if (stream.eat(\":\")) {\n          stream.eatWhile(/[\\w\\d_\\-]/);\n          return \"atom\";\n        }\n        var word = stream.current();\n        if (funcs.test(word)) return \"builtin\";\n        if (preds.test(word)) return \"def\";\n        if (keywords.test(word)) return \"keyword\";\n        return \"variable\";\n      }\n    };\n    var pushContext = function(state, type, col) {\n      return state.context = {\n        prev: state.context,\n        indent: state.indent,\n        col: col,\n        type: type\n      };\n    };\n    var popContext = function(state) {\n      state.indent = state.context.indent;\n      return state.context = state.context.prev;\n    };\n    var indentUnit = config.indentUnit;\n    var curPunc;\n    var funcs = wordRegexp([\"abs\", \"acos\", \"allShortestPaths\", \"asin\", \"atan\", \"atan2\", \"avg\", \"ceil\", \"coalesce\", \"collect\", \"cos\", \"cot\", \"count\", \"degrees\", \"e\", \"endnode\", \"exp\", \"extract\", \"filter\", \"floor\", \"haversin\", \"head\", \"id\", \"keys\", \"labels\", \"last\", \"left\", \"length\", \"log\", \"log10\", \"lower\", \"ltrim\", \"max\", \"min\", \"node\", \"nodes\", \"percentileCont\", \"percentileDisc\", \"pi\", \"radians\", \"rand\", \"range\", \"reduce\", \"rel\", \"relationship\", \"relationships\", \"replace\", \"reverse\", \"right\", \"round\", \"rtrim\", \"shortestPath\", \"sign\", \"sin\", \"size\", \"split\", \"sqrt\", \"startnode\", \"stdev\", \"stdevp\", \"str\", \"substring\", \"sum\", \"tail\", \"tan\", \"timestamp\", \"toFloat\", \"toInt\", \"toString\", \"trim\", \"type\", \"upper\"]);\n    var preds = wordRegexp([\"all\", \"and\", \"any\", \"contains\", \"exists\", \"has\", \"in\", \"none\", \"not\", \"or\", \"single\", \"xor\"]);\n    var keywords = wordRegexp([\"as\", \"asc\", \"ascending\", \"assert\", \"by\", \"case\", \"commit\", \"constraint\", \"create\", \"csv\", \"cypher\", \"delete\", \"desc\", \"descending\", \"detach\", \"distinct\", \"drop\", \"else\", \"end\", \"ends\", \"explain\", \"false\", \"fieldterminator\", \"foreach\", \"from\", \"headers\", \"in\", \"index\", \"is\", \"join\", \"limit\", \"load\", \"match\", \"merge\", \"null\", \"on\", \"optional\", \"order\", \"periodic\", \"profile\", \"remove\", \"return\", \"scan\", \"set\", \"skip\", \"start\", \"starts\", \"then\", \"true\", \"union\", \"unique\", \"unwind\", \"using\", \"when\", \"where\", \"with\", \"call\", \"yield\"]);\n    var operatorChars = /[*+\\-<>=&|~%^]/;\n\n    return {\n      startState: function(/*base*/) {\n        return {\n          tokenize: tokenBase,\n          context: null,\n          indent: 0,\n          col: 0\n        };\n      },\n      token: function(stream, state) {\n        if (stream.sol()) {\n          if (state.context && (state.context.align == null)) {\n            state.context.align = false;\n          }\n          state.indent = stream.indentation();\n        }\n        if (stream.eatSpace()) {\n          return null;\n        }\n        var style = state.tokenize(stream, state);\n        if (style !== \"comment\" && state.context && (state.context.align == null) && state.context.type !== \"pattern\") {\n          state.context.align = true;\n        }\n        if (curPunc === \"(\") {\n          pushContext(state, \")\", stream.column());\n        } else if (curPunc === \"[\") {\n          pushContext(state, \"]\", stream.column());\n        } else if (curPunc === \"{\") {\n          pushContext(state, \"}\", stream.column());\n        } else if (/[\\]\\}\\)]/.test(curPunc)) {\n          while (state.context && state.context.type === \"pattern\") {\n            popContext(state);\n          }\n          if (state.context && curPunc === state.context.type) {\n            popContext(state);\n          }\n        } else if (curPunc === \".\" && state.context && state.context.type === \"pattern\") {\n          popContext(state);\n        } else if (/atom|string|variable/.test(style) && state.context) {\n          if (/[\\}\\]]/.test(state.context.type)) {\n            pushContext(state, \"pattern\", stream.column());\n          } else if (state.context.type === \"pattern\" && !state.context.align) {\n            state.context.align = true;\n            state.context.col = stream.column();\n          }\n        }\n        return style;\n      },\n      indent: function(state, textAfter) {\n        var firstChar = textAfter && textAfter.charAt(0);\n        var context = state.context;\n        if (/[\\]\\}]/.test(firstChar)) {\n          while (context && context.type === \"pattern\") {\n            context = context.prev;\n          }\n        }\n        var closing = context && firstChar === context.type;\n        if (!context) return 0;\n        if (context.type === \"keywords\") return CodeMirror.commands.newlineAndIndent;\n        if (context.align) return context.col + (closing ? 0 : 1);\n        return context.indent + (closing ? 0 : indentUnit);\n      }\n    };\n  });\n\n  CodeMirror.modeExtensions[\"cypher\"] = {\n    autoFormatLineBreaks: function(text) {\n      var i, lines, reProcessedPortion;\n      var lines = text.split(\"\\n\");\n      var reProcessedPortion = /\\s+\\b(return|where|order by|match|with|skip|limit|create|delete|set)\\b\\s/g;\n      for (var i = 0; i < lines.length; i++)\n        lines[i] = lines[i].replace(reProcessedPortion, \" \\n$1 \").trim();\n      return lines.join(\"\\n\");\n    }\n  };\n\n  CodeMirror.defineMIME(\"application/x-cypher-query\", \"cypher\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/cypher/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Cypher Mode for CodeMirror</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\" />\n<link rel=\"stylesheet\" href=\"../../theme/neo.css\" />\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"cypher.js\"></script>\n<style>\n.CodeMirror {\n    border-top: 1px solid black;\n    border-bottom: 1px solid black;\n}\n        </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Cypher Mode for CodeMirror</a>\n  </ul>\n</div>\n\n<article>\n<h2>Cypher Mode for CodeMirror</h2>\n<form>\n            <textarea id=\"code\" name=\"code\">// Cypher Mode for CodeMirror, using the neo theme\nMATCH (joe { name: 'Joe' })-[:knows*2..2]-(friend_of_friend)\nWHERE NOT (joe)-[:knows]-(friend_of_friend)\nRETURN friend_of_friend.name, COUNT(*)\nORDER BY COUNT(*) DESC , friend_of_friend.name\n</textarea>\n            </form>\n            <p><strong>MIME types defined:</strong> \n            <code><a href=\"?mime=application/x-cypher-query\">application/x-cypher-query</a></code>\n        </p>\n<script>\nwindow.onload = function() {\n  var mime = 'application/x-cypher-query';\n  // get mime type\n  if (window.location.href.indexOf('mime=') > -1) {\n    mime = window.location.href.substr(window.location.href.indexOf('mime=') + 5);\n  }\n  window.editor = CodeMirror.fromTextArea(document.getElementById('code'), {\n    mode: mime,\n    indentWithTabs: true,\n    smartIndent: true,\n    lineNumbers: true,\n    matchBrackets: true,\n    autofocus: true,\n    theme: 'neo'\n  });\n};\n</script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/cypher/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, \"cypher\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"unbalancedDoubledQuotedString\",\n      \"[string \\\"a'b\\\"][variable c]\");\n\n  MT(\"unbalancedSingleQuotedString\",\n      \"[string 'a\\\"b'][variable c]\");\n\n  MT(\"doubleQuotedString\",\n      \"[string \\\"a\\\"][variable b]\");\n\n  MT(\"singleQuotedString\",\n      \"[string 'a'][variable b]\");\n\n  MT(\"single attribute (with content)\",\n      \"[node {][atom a:][string 'a'][node }]\");\n\n  MT(\"multiple attribute, singleQuotedString (with content)\",\n      \"[node {][atom a:][string 'a'][node ,][atom b:][string 'b'][node }]\");\n\n  MT(\"multiple attribute, doubleQuotedString (with content)\",\n      \"[node {][atom a:][string \\\"a\\\"][node ,][atom b:][string \\\"b\\\"][node }]\");\n\n  MT(\"single attribute (without content)\",\n      \"[node {][atom a:][string 'a'][node }]\");\n\n  MT(\"multiple attribute, singleQuotedString (without content)\",\n      \"[node {][atom a:][string ''][node ,][atom b:][string ''][node }]\");\n\n  MT(\"multiple attribute, doubleQuotedString (without content)\",\n      \"[node {][atom a:][string \\\"\\\"][node ,][atom b:][string \\\"\\\"][node }]\");\n })();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/d/d.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"d\", function(config, parserConfig) {\n  var indentUnit = config.indentUnit,\n      statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,\n      keywords = parserConfig.keywords || {},\n      builtin = parserConfig.builtin || {},\n      blockKeywords = parserConfig.blockKeywords || {},\n      atoms = parserConfig.atoms || {},\n      hooks = parserConfig.hooks || {},\n      multiLineStrings = parserConfig.multiLineStrings;\n  var isOperatorChar = /[+\\-*&%=<>!?|\\/]/;\n\n  var curPunc;\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (hooks[ch]) {\n      var result = hooks[ch](stream, state);\n      if (result !== false) return result;\n    }\n    if (ch == '\"' || ch == \"'\" || ch == \"`\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n    if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n      curPunc = ch;\n      return null;\n    }\n    if (/\\d/.test(ch)) {\n      stream.eatWhile(/[\\w\\.]/);\n      return \"number\";\n    }\n    if (ch == \"/\") {\n      if (stream.eat(\"+\")) {\n        state.tokenize = tokenNestedComment;\n        return tokenNestedComment(stream, state);\n      }\n      if (stream.eat(\"*\")) {\n        state.tokenize = tokenComment;\n        return tokenComment(stream, state);\n      }\n      if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n    }\n    if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return \"operator\";\n    }\n    stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n    var cur = stream.current();\n    if (keywords.propertyIsEnumerable(cur)) {\n      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n      return \"keyword\";\n    }\n    if (builtin.propertyIsEnumerable(cur)) {\n      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n      return \"builtin\";\n    }\n    if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n    return \"variable\";\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {end = true; break;}\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end || !(escaped || multiLineStrings))\n        state.tokenize = null;\n      return \"string\";\n    };\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = null;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function tokenNestedComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = null;\n        break;\n      }\n      maybeEnd = (ch == \"+\");\n    }\n    return \"comment\";\n  }\n\n  function Context(indented, column, type, align, prev) {\n    this.indented = indented;\n    this.column = column;\n    this.type = type;\n    this.align = align;\n    this.prev = prev;\n  }\n  function pushContext(state, col, type) {\n    var indent = state.indented;\n    if (state.context && state.context.type == \"statement\")\n      indent = state.context.indented;\n    return state.context = new Context(indent, col, type, null, state.context);\n  }\n  function popContext(state) {\n    var t = state.context.type;\n    if (t == \")\" || t == \"]\" || t == \"}\")\n      state.indented = state.context.indented;\n    return state.context = state.context.prev;\n  }\n\n  // Interface\n\n  return {\n    startState: function(basecolumn) {\n      return {\n        tokenize: null,\n        context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", false),\n        indented: 0,\n        startOfLine: true\n      };\n    },\n\n    token: function(stream, state) {\n      var ctx = state.context;\n      if (stream.sol()) {\n        if (ctx.align == null) ctx.align = false;\n        state.indented = stream.indentation();\n        state.startOfLine = true;\n      }\n      if (stream.eatSpace()) return null;\n      curPunc = null;\n      var style = (state.tokenize || tokenBase)(stream, state);\n      if (style == \"comment\" || style == \"meta\") return style;\n      if (ctx.align == null) ctx.align = true;\n\n      if ((curPunc == \";\" || curPunc == \":\" || curPunc == \",\") && ctx.type == \"statement\") popContext(state);\n      else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n      else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n      else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n      else if (curPunc == \"}\") {\n        while (ctx.type == \"statement\") ctx = popContext(state);\n        if (ctx.type == \"}\") ctx = popContext(state);\n        while (ctx.type == \"statement\") ctx = popContext(state);\n      }\n      else if (curPunc == ctx.type) popContext(state);\n      else if (((ctx.type == \"}\" || ctx.type == \"top\") && curPunc != ';') || (ctx.type == \"statement\" && curPunc == \"newstatement\"))\n        pushContext(state, stream.column(), \"statement\");\n      state.startOfLine = false;\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;\n      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);\n      if (ctx.type == \"statement\" && firstChar == \"}\") ctx = ctx.prev;\n      var closing = firstChar == ctx.type;\n      if (ctx.type == \"statement\") return ctx.indented + (firstChar == \"{\" ? 0 : statementIndentUnit);\n      else if (ctx.align) return ctx.column + (closing ? 0 : 1);\n      else return ctx.indented + (closing ? 0 : indentUnit);\n    },\n\n    electricChars: \"{}\",\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    blockCommentContinue: \" * \",\n    lineComment: \"//\",\n    fold: \"brace\"\n  };\n});\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  var blockKeywords = \"body catch class do else enum for foreach foreach_reverse if in interface mixin \" +\n                      \"out scope struct switch try union unittest version while with\";\n\n  CodeMirror.defineMIME(\"text/x-d\", {\n    name: \"d\",\n    keywords: words(\"abstract alias align asm assert auto break case cast cdouble cent cfloat const continue \" +\n                    \"debug default delegate delete deprecated export extern final finally function goto immutable \" +\n                    \"import inout invariant is lazy macro module new nothrow override package pragma private \" +\n                    \"protected public pure ref return shared short static super synchronized template this \" +\n                    \"throw typedef typeid typeof volatile __FILE__ __LINE__ __gshared __traits __vector __parameters \" +\n                    blockKeywords),\n    blockKeywords: words(blockKeywords),\n    builtin: words(\"bool byte char creal dchar double float idouble ifloat int ireal long real short ubyte \" +\n                   \"ucent uint ulong ushort wchar wstring void size_t sizediff_t\"),\n    atoms: words(\"exit failure success true false null\"),\n    hooks: {\n      \"@\": function(stream, _state) {\n        stream.eatWhile(/[\\w\\$_]/);\n        return \"meta\";\n      }\n    }\n  });\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/d/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: D mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"d.js\"></script>\n<style>.CodeMirror {border: 2px inset #dee;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">D</a>\n  </ul>\n</div>\n\n<article>\n<h2>D mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n/* D demo code // copied from phobos/sd/metastrings.d */\n// Written in the D programming language.\n\n/**\nTemplates with which to do compile-time manipulation of strings.\n\nMacros:\n WIKI = Phobos/StdMetastrings\n\nCopyright: Copyright Digital Mars 2007 - 2009.\nLicense:   <a href=\"http://www.boost.org/LICENSE_1_0.txt\">Boost License 1.0</a>.\nAuthors:   $(WEB digitalmars.com, Walter Bright),\n           Don Clugston\nSource:    $(PHOBOSSRC std/_metastrings.d)\n*/\n/*\n         Copyright Digital Mars 2007 - 2009.\nDistributed under the Boost Software License, Version 1.0.\n   (See accompanying file LICENSE_1_0.txt or copy at\n         http://www.boost.org/LICENSE_1_0.txt)\n */\nmodule std.metastrings;\n\n/**\nFormats constants into a string at compile time.  Analogous to $(XREF\nstring,format).\n\nParameters:\n\nA = tuple of constants, which can be strings, characters, or integral\n    values.\n\nFormats:\n *    The formats supported are %s for strings, and %%\n *    for the % character.\nExample:\n---\nimport std.metastrings;\nimport std.stdio;\n\nvoid main()\n{\n  string s = Format!(\"Arg %s = %s\", \"foo\", 27);\n  writefln(s); // \"Arg foo = 27\"\n}\n * ---\n */\n\ntemplate Format(A...)\n{\n    static if (A.length == 0)\n        enum Format = \"\";\n    else static if (is(typeof(A[0]) : const(char)[]))\n        enum Format = FormatString!(A[0], A[1..$]);\n    else\n        enum Format = toStringNow!(A[0]) ~ Format!(A[1..$]);\n}\n\ntemplate FormatString(const(char)[] F, A...)\n{\n    static if (F.length == 0)\n        enum FormatString = Format!(A);\n    else static if (F.length == 1)\n        enum FormatString = F[0] ~ Format!(A);\n    else static if (F[0..2] == \"%s\")\n        enum FormatString\n            = toStringNow!(A[0]) ~ FormatString!(F[2..$],A[1..$]);\n    else static if (F[0..2] == \"%%\")\n        enum FormatString = \"%\" ~ FormatString!(F[2..$],A);\n    else\n    {\n        static assert(F[0] != '%', \"unrecognized format %\" ~ F[1]);\n        enum FormatString = F[0] ~ FormatString!(F[1..$],A);\n    }\n}\n\nunittest\n{\n    auto s = Format!(\"hel%slo\", \"world\", -138, 'c', true);\n    assert(s == \"helworldlo-138ctrue\", \"[\" ~ s ~ \"]\");\n}\n\n/**\n * Convert constant argument to a string.\n */\n\ntemplate toStringNow(ulong v)\n{\n    static if (v < 10)\n        enum toStringNow = \"\" ~ cast(char)(v + '0');\n    else\n        enum toStringNow = toStringNow!(v / 10) ~ toStringNow!(v % 10);\n}\n\nunittest\n{\n    static assert(toStringNow!(1uL << 62) == \"4611686018427387904\");\n}\n\n/// ditto\ntemplate toStringNow(long v)\n{\n    static if (v < 0)\n        enum toStringNow = \"-\" ~ toStringNow!(cast(ulong) -v);\n    else\n        enum toStringNow = toStringNow!(cast(ulong) v);\n}\n\nunittest\n{\n    static assert(toStringNow!(0x100000000) == \"4294967296\");\n    static assert(toStringNow!(-138L) == \"-138\");\n}\n\n/// ditto\ntemplate toStringNow(uint U)\n{\n    enum toStringNow = toStringNow!(cast(ulong)U);\n}\n\n/// ditto\ntemplate toStringNow(int I)\n{\n    enum toStringNow = toStringNow!(cast(long)I);\n}\n\n/// ditto\ntemplate toStringNow(bool B)\n{\n    enum toStringNow = B ? \"true\" : \"false\";\n}\n\n/// ditto\ntemplate toStringNow(string S)\n{\n    enum toStringNow = S;\n}\n\n/// ditto\ntemplate toStringNow(char C)\n{\n    enum toStringNow = \"\" ~ C;\n}\n\n\n/********\n * Parse unsigned integer literal from the start of string s.\n * returns:\n *    .value = the integer literal as a string,\n *    .rest = the string following the integer literal\n * Otherwise:\n *    .value = null,\n *    .rest = s\n */\n\ntemplate parseUinteger(const(char)[] s)\n{\n    static if (s.length == 0)\n    {\n        enum value = \"\";\n        enum rest = \"\";\n    }\n    else static if (s[0] >= '0' && s[0] <= '9')\n    {\n        enum value = s[0] ~ parseUinteger!(s[1..$]).value;\n        enum rest = parseUinteger!(s[1..$]).rest;\n    }\n    else\n    {\n        enum value = \"\";\n        enum rest = s;\n    }\n}\n\n/********\nParse integer literal optionally preceded by $(D '-') from the start\nof string $(D s).\n\nReturns:\n   .value = the integer literal as a string,\n   .rest = the string following the integer literal\n\nOtherwise:\n   .value = null,\n   .rest = s\n*/\n\ntemplate parseInteger(const(char)[] s)\n{\n    static if (s.length == 0)\n    {\n        enum value = \"\";\n        enum rest = \"\";\n    }\n    else static if (s[0] >= '0' && s[0] <= '9')\n    {\n        enum value = s[0] ~ parseUinteger!(s[1..$]).value;\n        enum rest = parseUinteger!(s[1..$]).rest;\n    }\n    else static if (s.length >= 2 &&\n            s[0] == '-' && s[1] >= '0' && s[1] <= '9')\n    {\n        enum value = s[0..2] ~ parseUinteger!(s[2..$]).value;\n        enum rest = parseUinteger!(s[2..$]).rest;\n    }\n    else\n    {\n        enum value = \"\";\n        enum rest = s;\n    }\n}\n\nunittest\n{\n    assert(parseUinteger!(\"1234abc\").value == \"1234\");\n    assert(parseUinteger!(\"1234abc\").rest == \"abc\");\n    assert(parseInteger!(\"-1234abc\").value == \"-1234\");\n    assert(parseInteger!(\"-1234abc\").rest == \"abc\");\n}\n\n/**\nDeprecated aliases held for backward compatibility.\n*/\ndeprecated alias toStringNow ToString;\n/// Ditto\ndeprecated alias parseUinteger ParseUinteger;\n/// Ditto\ndeprecated alias parseUinteger ParseInteger;\n\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        indentUnit: 4,\n        mode: \"text/x-d\"\n      });\n    </script>\n\n    <p>Simple mode that handle D-Syntax (<a href=\"http://www.dlang.org\">DLang Homepage</a>).</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-d</code>\n    .</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/d/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"d\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"nested_comments\",\n     \"[comment /+]\",\"[comment comment]\",\"[comment +/]\",\"[variable void] [variable main](){}\");\n\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dart/dart.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../clike/clike\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../clike/clike\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var keywords = (\"this super static final const abstract class extends external factory \" +\n    \"implements mixin get native set typedef with enum throw rethrow \" +\n    \"assert break case continue default in return new deferred async await covariant \" +\n    \"try catch finally do else for if switch while import library export \" +\n    \"part of show hide is as\").split(\" \");\n  var blockKeywords = \"try catch finally do else for if switch while\".split(\" \");\n  var atoms = \"true false null\".split(\" \");\n  var builtins = \"void bool num int double dynamic var String\".split(\" \");\n\n  function set(words) {\n    var obj = {};\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  function pushInterpolationStack(state) {\n    (state.interpolationStack || (state.interpolationStack = [])).push(state.tokenize);\n  }\n\n  function popInterpolationStack(state) {\n    return (state.interpolationStack || (state.interpolationStack = [])).pop();\n  }\n\n  function sizeInterpolationStack(state) {\n    return state.interpolationStack ? state.interpolationStack.length : 0;\n  }\n\n  CodeMirror.defineMIME(\"application/dart\", {\n    name: \"clike\",\n    keywords: set(keywords),\n    blockKeywords: set(blockKeywords),\n    builtin: set(builtins),\n    atoms: set(atoms),\n    hooks: {\n      \"@\": function(stream) {\n        stream.eatWhile(/[\\w\\$_\\.]/);\n        return \"meta\";\n      },\n\n      // custom string handling to deal with triple-quoted strings and string interpolation\n      \"'\": function(stream, state) {\n        return tokenString(\"'\", stream, state, false);\n      },\n      \"\\\"\": function(stream, state) {\n        return tokenString(\"\\\"\", stream, state, false);\n      },\n      \"r\": function(stream, state) {\n        var peek = stream.peek();\n        if (peek == \"'\" || peek == \"\\\"\") {\n          return tokenString(stream.next(), stream, state, true);\n        }\n        return false;\n      },\n\n      \"}\": function(_stream, state) {\n        // \"}\" is end of interpolation, if interpolation stack is non-empty\n        if (sizeInterpolationStack(state) > 0) {\n          state.tokenize = popInterpolationStack(state);\n          return null;\n        }\n        return false;\n      },\n\n      \"/\": function(stream, state) {\n        if (!stream.eat(\"*\")) return false\n        state.tokenize = tokenNestedComment(1)\n        return state.tokenize(stream, state)\n      }\n    }\n  });\n\n  function tokenString(quote, stream, state, raw) {\n    var tripleQuoted = false;\n    if (stream.eat(quote)) {\n      if (stream.eat(quote)) tripleQuoted = true;\n      else return \"string\"; //empty string\n    }\n    function tokenStringHelper(stream, state) {\n      var escaped = false;\n      while (!stream.eol()) {\n        if (!raw && !escaped && stream.peek() == \"$\") {\n          pushInterpolationStack(state);\n          state.tokenize = tokenInterpolation;\n          return \"string\";\n        }\n        var next = stream.next();\n        if (next == quote && !escaped && (!tripleQuoted || stream.match(quote + quote))) {\n          state.tokenize = null;\n          break;\n        }\n        escaped = !raw && !escaped && next == \"\\\\\";\n      }\n      return \"string\";\n    }\n    state.tokenize = tokenStringHelper;\n    return tokenStringHelper(stream, state);\n  }\n\n  function tokenInterpolation(stream, state) {\n    stream.eat(\"$\");\n    if (stream.eat(\"{\")) {\n      // let clike handle the content of ${...},\n      // we take over again when \"}\" appears (see hooks).\n      state.tokenize = null;\n    } else {\n      state.tokenize = tokenInterpolationIdentifier;\n    }\n    return null;\n  }\n\n  function tokenInterpolationIdentifier(stream, state) {\n    stream.eatWhile(/[\\w_]/);\n    state.tokenize = popInterpolationStack(state);\n    return \"variable\";\n  }\n\n  function tokenNestedComment(depth) {\n    return function (stream, state) {\n      var ch\n      while (ch = stream.next()) {\n        if (ch == \"*\" && stream.eat(\"/\")) {\n          if (depth == 1) {\n            state.tokenize = null\n            break\n          } else {\n            state.tokenize = tokenNestedComment(depth - 1)\n            return state.tokenize(stream, state)\n          }\n        } else if (ch == \"/\" && stream.eat(\"*\")) {\n          state.tokenize = tokenNestedComment(depth + 1)\n          return state.tokenize(stream, state)\n        }\n      }\n      return \"comment\"\n    }\n  }\n\n  CodeMirror.registerHelper(\"hintWords\", \"application/dart\", keywords.concat(atoms).concat(builtins));\n\n  // This is needed to make loading through meta.js work.\n  CodeMirror.defineMode(\"dart\", function(conf) {\n    return CodeMirror.getMode(conf, \"application/dart\");\n  }, \"clike\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dart/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Dart mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../clike/clike.js\"></script>\n<script src=\"dart.js\"></script>\n<style>.CodeMirror {border: 1px solid #dee;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Dart</a>\n  </ul>\n</div>\n\n<article>\n<h2>Dart mode</h2>\n<form>\n<textarea id=\"code\" name=\"code\">\nimport 'dart:math' show Random;\n\nvoid main() {\n  print(new Die(n: 12).roll());\n}\n\n// Define a class.\nclass Die {\n  // Define a class variable.\n  static Random shaker = new Random();\n\n  // Define instance variables.\n  int sides, value;\n\n  // Define a method using shorthand syntax.\n  String toString() => '$value';\n\n  // Define a constructor.\n  Die({int n: 6}) {\n    if (4 <= n && n <= 20) {\n      sides = n;\n    } else {\n      // Support for errors and exceptions.\n      throw new ArgumentError(/* */);\n    }\n  }\n\n  // Define an instance method.\n  int roll() {\n    return value = shaker.nextInt(sides) + 1;\n  }\n}\n</textarea>\n</form>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    mode: \"application/dart\"\n  });\n</script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/diff/diff.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"diff\", function() {\n\n  var TOKEN_NAMES = {\n    '+': 'positive',\n    '-': 'negative',\n    '@': 'meta'\n  };\n\n  return {\n    token: function(stream) {\n      var tw_pos = stream.string.search(/[\\t ]+?$/);\n\n      if (!stream.sol() || tw_pos === 0) {\n        stream.skipToEnd();\n        return (\"error \" + (\n          TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, '');\n      }\n\n      var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd();\n\n      if (tw_pos === -1) {\n        stream.skipToEnd();\n      } else {\n        stream.pos = tw_pos;\n      }\n\n      return token_name;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-diff\", \"diff\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/diff/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Diff mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"diff.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}\n      span.cm-meta {color: #a0b !important;}\n      span.cm-error { background-color: black; opacity: 0.4;}\n      span.cm-error.cm-string { background-color: red; }\n      span.cm-error.cm-tag { background-color: #2b2; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Diff</a>\n  </ul>\n</div>\n\n<article>\n<h2>Diff mode</h2>\n<form><textarea id=\"code\" name=\"code\">\ndiff --git a/index.html b/index.html\nindex c1d9156..7764744 100644\n--- a/index.html\n+++ b/index.html\n@@ -95,7 +95,8 @@ StringStream.prototype = {\n     <script>\n       var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n         lineNumbers: true,\n-        autoMatchBrackets: true\n+        autoMatchBrackets: true,\n+      onGutterClick: function(x){console.log(x);}\n       });\n     </script>\n   </body>\ndiff --git a/lib/codemirror.js b/lib/codemirror.js\nindex 04646a9..9a39cc7 100644\n--- a/lib/codemirror.js\n+++ b/lib/codemirror.js\n@@ -399,10 +399,16 @@ var CodeMirror = (function() {\n     }\n \n     function onMouseDown(e) {\n-      var start = posFromMouse(e), last = start;    \n+      var start = posFromMouse(e), last = start, target = e.target();\n       if (!start) return;\n       setCursor(start.line, start.ch, false);\n       if (e.button() != 1) return;\n+      if (target.parentNode == gutter) {    \n+        if (options.onGutterClick)\n+          options.onGutterClick(indexOf(gutter.childNodes, target) + showingFrom);\n+        return;\n+      }\n+\n       if (!focused) onFocus();\n \n       e.stop();\n@@ -808,7 +814,7 @@ var CodeMirror = (function() {\n       for (var i = showingFrom; i < showingTo; ++i) {\n         var marker = lines[i].gutterMarker;\n         if (marker) html.push('<div class=\"' + marker.style + '\">' + htmlEscape(marker.text) + '</div>');\n-        else html.push(\"<div>\" + (options.lineNumbers ? i + 1 : \"\\u00a0\") + \"</div>\");\n+        else html.push(\"<div>\" + (options.lineNumbers ? i + options.firstLineNumber : \"\\u00a0\") + \"</div>\");\n       }\n       gutter.style.display = \"none\"; // TODO test whether this actually helps\n       gutter.innerHTML = html.join(\"\");\n@@ -1371,10 +1377,8 @@ var CodeMirror = (function() {\n         if (option == \"parser\") setParser(value);\n         else if (option === \"lineNumbers\") setLineNumbers(value);\n         else if (option === \"gutter\") setGutter(value);\n-        else if (option === \"readOnly\") options.readOnly = value;\n-        else if (option === \"indentUnit\") {options.indentUnit = indentUnit = value; setParser(options.parser);}\n-        else if (/^(?:enterMode|tabMode|indentWithTabs|readOnly|autoMatchBrackets|undoDepth)$/.test(option)) options[option] = value;\n-        else throw new Error(\"Can't set option \" + option);\n+        else if (option === \"indentUnit\") {options.indentUnit = value; setParser(options.parser);}\n+        else options[option] = value;\n       },\n       cursorCoords: cursorCoords,\n       undo: operation(undo),\n@@ -1402,7 +1406,8 @@ var CodeMirror = (function() {\n       replaceRange: operation(replaceRange),\n \n       operation: function(f){return operation(f)();},\n-      refresh: function(){updateDisplay([{from: 0, to: lines.length}]);}\n+      refresh: function(){updateDisplay([{from: 0, to: lines.length}]);},\n+      getInputField: function(){return input;}\n     };\n     return instance;\n   }\n@@ -1420,6 +1425,7 @@ var CodeMirror = (function() {\n     readOnly: false,\n     onChange: null,\n     onCursorActivity: null,\n+    onGutterClick: null,\n     autoMatchBrackets: false,\n     workTime: 200,\n     workDelay: 300,\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-diff</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/django/django.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../htmlmixed/htmlmixed\"),\n        require(\"../../addon/mode/overlay\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../htmlmixed/htmlmixed\",\n            \"../../addon/mode/overlay\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"django:inner\", function() {\n    var keywords = [\"block\", \"endblock\", \"for\", \"endfor\", \"true\", \"false\", \"filter\", \"endfilter\",\n                    \"loop\", \"none\", \"self\", \"super\", \"if\", \"elif\", \"endif\", \"as\", \"else\", \"import\",\n                    \"with\", \"endwith\", \"without\", \"context\", \"ifequal\", \"endifequal\", \"ifnotequal\",\n                    \"endifnotequal\", \"extends\", \"include\", \"load\", \"comment\", \"endcomment\",\n                    \"empty\", \"url\", \"static\", \"trans\", \"blocktrans\", \"endblocktrans\", \"now\",\n                    \"regroup\", \"lorem\", \"ifchanged\", \"endifchanged\", \"firstof\", \"debug\", \"cycle\",\n                    \"csrf_token\", \"autoescape\", \"endautoescape\", \"spaceless\", \"endspaceless\",\n                    \"ssi\", \"templatetag\", \"verbatim\", \"endverbatim\", \"widthratio\"],\n        filters = [\"add\", \"addslashes\", \"capfirst\", \"center\", \"cut\", \"date\",\n                   \"default\", \"default_if_none\", \"dictsort\",\n                   \"dictsortreversed\", \"divisibleby\", \"escape\", \"escapejs\",\n                   \"filesizeformat\", \"first\", \"floatformat\", \"force_escape\",\n                   \"get_digit\", \"iriencode\", \"join\", \"last\", \"length\",\n                   \"length_is\", \"linebreaks\", \"linebreaksbr\", \"linenumbers\",\n                   \"ljust\", \"lower\", \"make_list\", \"phone2numeric\", \"pluralize\",\n                   \"pprint\", \"random\", \"removetags\", \"rjust\", \"safe\",\n                   \"safeseq\", \"slice\", \"slugify\", \"stringformat\", \"striptags\",\n                   \"time\", \"timesince\", \"timeuntil\", \"title\", \"truncatechars\",\n                   \"truncatechars_html\", \"truncatewords\", \"truncatewords_html\",\n                   \"unordered_list\", \"upper\", \"urlencode\", \"urlize\",\n                   \"urlizetrunc\", \"wordcount\", \"wordwrap\", \"yesno\"],\n        operators = [\"==\", \"!=\", \"<\", \">\", \"<=\", \">=\"],\n        wordOperators = [\"in\", \"not\", \"or\", \"and\"];\n\n    keywords = new RegExp(\"^\\\\b(\" + keywords.join(\"|\") + \")\\\\b\");\n    filters = new RegExp(\"^\\\\b(\" + filters.join(\"|\") + \")\\\\b\");\n    operators = new RegExp(\"^\\\\b(\" + operators.join(\"|\") + \")\\\\b\");\n    wordOperators = new RegExp(\"^\\\\b(\" + wordOperators.join(\"|\") + \")\\\\b\");\n\n    // We have to return \"null\" instead of null, in order to avoid string\n    // styling as the default, when using Django templates inside HTML\n    // element attributes\n    function tokenBase (stream, state) {\n      // Attempt to identify a variable, template or comment tag respectively\n      if (stream.match(\"{{\")) {\n        state.tokenize = inVariable;\n        return \"tag\";\n      } else if (stream.match(\"{%\")) {\n        state.tokenize = inTag;\n        return \"tag\";\n      } else if (stream.match(\"{#\")) {\n        state.tokenize = inComment;\n        return \"comment\";\n      }\n\n      // Ignore completely any stream series that do not match the\n      // Django template opening tags.\n      while (stream.next() != null && !stream.match(/\\{[{%#]/, false)) {}\n      return null;\n    }\n\n    // A string can be included in either single or double quotes (this is\n    // the delimiter). Mark everything as a string until the start delimiter\n    // occurs again.\n    function inString (delimiter, previousTokenizer) {\n      return function (stream, state) {\n        if (!state.escapeNext && stream.eat(delimiter)) {\n          state.tokenize = previousTokenizer;\n        } else {\n          if (state.escapeNext) {\n            state.escapeNext = false;\n          }\n\n          var ch = stream.next();\n\n          // Take into account the backslash for escaping characters, such as\n          // the string delimiter.\n          if (ch == \"\\\\\") {\n            state.escapeNext = true;\n          }\n        }\n\n        return \"string\";\n      };\n    }\n\n    // Apply Django template variable syntax highlighting\n    function inVariable (stream, state) {\n      // Attempt to match a dot that precedes a property\n      if (state.waitDot) {\n        state.waitDot = false;\n\n        if (stream.peek() != \".\") {\n          return \"null\";\n        }\n\n        // Dot followed by a non-word character should be considered an error.\n        if (stream.match(/\\.\\W+/)) {\n          return \"error\";\n        } else if (stream.eat(\".\")) {\n          state.waitProperty = true;\n          return \"null\";\n        } else {\n          throw Error (\"Unexpected error while waiting for property.\");\n        }\n      }\n\n      // Attempt to match a pipe that precedes a filter\n      if (state.waitPipe) {\n        state.waitPipe = false;\n\n        if (stream.peek() != \"|\") {\n          return \"null\";\n        }\n\n        // Pipe followed by a non-word character should be considered an error.\n        if (stream.match(/\\.\\W+/)) {\n          return \"error\";\n        } else if (stream.eat(\"|\")) {\n          state.waitFilter = true;\n          return \"null\";\n        } else {\n          throw Error (\"Unexpected error while waiting for filter.\");\n        }\n      }\n\n      // Highlight properties\n      if (state.waitProperty) {\n        state.waitProperty = false;\n        if (stream.match(/\\b(\\w+)\\b/)) {\n          state.waitDot = true;  // A property can be followed by another property\n          state.waitPipe = true;  // A property can be followed by a filter\n          return \"property\";\n        }\n      }\n\n      // Highlight filters\n      if (state.waitFilter) {\n          state.waitFilter = false;\n        if (stream.match(filters)) {\n          return \"variable-2\";\n        }\n      }\n\n      // Ignore all white spaces\n      if (stream.eatSpace()) {\n        state.waitProperty = false;\n        return \"null\";\n      }\n\n      // Identify numbers\n      if (stream.match(/\\b\\d+(\\.\\d+)?\\b/)) {\n        return \"number\";\n      }\n\n      // Identify strings\n      if (stream.match(\"'\")) {\n        state.tokenize = inString(\"'\", state.tokenize);\n        return \"string\";\n      } else if (stream.match('\"')) {\n        state.tokenize = inString('\"', state.tokenize);\n        return \"string\";\n      }\n\n      // Attempt to find the variable\n      if (stream.match(/\\b(\\w+)\\b/) && !state.foundVariable) {\n        state.waitDot = true;\n        state.waitPipe = true;  // A property can be followed by a filter\n        return \"variable\";\n      }\n\n      // If found closing tag reset\n      if (stream.match(\"}}\")) {\n        state.waitProperty = null;\n        state.waitFilter = null;\n        state.waitDot = null;\n        state.waitPipe = null;\n        state.tokenize = tokenBase;\n        return \"tag\";\n      }\n\n      // If nothing was found, advance to the next character\n      stream.next();\n      return \"null\";\n    }\n\n    function inTag (stream, state) {\n      // Attempt to match a dot that precedes a property\n      if (state.waitDot) {\n        state.waitDot = false;\n\n        if (stream.peek() != \".\") {\n          return \"null\";\n        }\n\n        // Dot followed by a non-word character should be considered an error.\n        if (stream.match(/\\.\\W+/)) {\n          return \"error\";\n        } else if (stream.eat(\".\")) {\n          state.waitProperty = true;\n          return \"null\";\n        } else {\n          throw Error (\"Unexpected error while waiting for property.\");\n        }\n      }\n\n      // Attempt to match a pipe that precedes a filter\n      if (state.waitPipe) {\n        state.waitPipe = false;\n\n        if (stream.peek() != \"|\") {\n          return \"null\";\n        }\n\n        // Pipe followed by a non-word character should be considered an error.\n        if (stream.match(/\\.\\W+/)) {\n          return \"error\";\n        } else if (stream.eat(\"|\")) {\n          state.waitFilter = true;\n          return \"null\";\n        } else {\n          throw Error (\"Unexpected error while waiting for filter.\");\n        }\n      }\n\n      // Highlight properties\n      if (state.waitProperty) {\n        state.waitProperty = false;\n        if (stream.match(/\\b(\\w+)\\b/)) {\n          state.waitDot = true;  // A property can be followed by another property\n          state.waitPipe = true;  // A property can be followed by a filter\n          return \"property\";\n        }\n      }\n\n      // Highlight filters\n      if (state.waitFilter) {\n          state.waitFilter = false;\n        if (stream.match(filters)) {\n          return \"variable-2\";\n        }\n      }\n\n      // Ignore all white spaces\n      if (stream.eatSpace()) {\n        state.waitProperty = false;\n        return \"null\";\n      }\n\n      // Identify numbers\n      if (stream.match(/\\b\\d+(\\.\\d+)?\\b/)) {\n        return \"number\";\n      }\n\n      // Identify strings\n      if (stream.match(\"'\")) {\n        state.tokenize = inString(\"'\", state.tokenize);\n        return \"string\";\n      } else if (stream.match('\"')) {\n        state.tokenize = inString('\"', state.tokenize);\n        return \"string\";\n      }\n\n      // Attempt to match an operator\n      if (stream.match(operators)) {\n        return \"operator\";\n      }\n\n      // Attempt to match a word operator\n      if (stream.match(wordOperators)) {\n        return \"keyword\";\n      }\n\n      // Attempt to match a keyword\n      var keywordMatch = stream.match(keywords);\n      if (keywordMatch) {\n        if (keywordMatch[0] == \"comment\") {\n          state.blockCommentTag = true;\n        }\n        return \"keyword\";\n      }\n\n      // Attempt to match a variable\n      if (stream.match(/\\b(\\w+)\\b/)) {\n        state.waitDot = true;\n        state.waitPipe = true;  // A property can be followed by a filter\n        return \"variable\";\n      }\n\n      // If found closing tag reset\n      if (stream.match(\"%}\")) {\n        state.waitProperty = null;\n        state.waitFilter = null;\n        state.waitDot = null;\n        state.waitPipe = null;\n        // If the tag that closes is a block comment tag, we want to mark the\n        // following code as comment, until the tag closes.\n        if (state.blockCommentTag) {\n          state.blockCommentTag = false;  // Release the \"lock\"\n          state.tokenize = inBlockComment;\n        } else {\n          state.tokenize = tokenBase;\n        }\n        return \"tag\";\n      }\n\n      // If nothing was found, advance to the next character\n      stream.next();\n      return \"null\";\n    }\n\n    // Mark everything as comment inside the tag and the tag itself.\n    function inComment (stream, state) {\n      if (stream.match(/^.*?#\\}/)) state.tokenize = tokenBase\n      else stream.skipToEnd()\n      return \"comment\";\n    }\n\n    // Mark everything as a comment until the `blockcomment` tag closes.\n    function inBlockComment (stream, state) {\n      if (stream.match(/\\{%\\s*endcomment\\s*%\\}/, false)) {\n        state.tokenize = inTag;\n        stream.match(\"{%\");\n        return \"tag\";\n      } else {\n        stream.next();\n        return \"comment\";\n      }\n    }\n\n    return {\n      startState: function () {\n        return {tokenize: tokenBase};\n      },\n      token: function (stream, state) {\n        return state.tokenize(stream, state);\n      },\n      blockCommentStart: \"{% comment %}\",\n      blockCommentEnd: \"{% endcomment %}\"\n    };\n  });\n\n  CodeMirror.defineMode(\"django\", function(config) {\n    var htmlBase = CodeMirror.getMode(config, \"text/html\");\n    var djangoInner = CodeMirror.getMode(config, \"django:inner\");\n    return CodeMirror.overlayMode(htmlBase, djangoInner);\n  });\n\n  CodeMirror.defineMIME(\"text/x-django\", \"django\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/django/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Django template mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/mdn-like.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/overlay.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"django.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Django</a>\n  </ul>\n</div>\n\n<article>\n<h2>Django template mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n<!doctype html>\n<html>\n  <head>\n    <title>My Django web application</title>\n  </head>\n  <body>\n    <h1>\n      {{ page.title|capfirst }}\n    </h1>\n    <ul class=\"my-list\">\n      {# traverse a list of items and produce links to their views. #}\n      {% for item in items %}\n      <li>\n        <a href=\"{% url 'item_view' item.name|slugify %}\">\n          {{ item.name }}\n        </a>\n      </li>\n      {% empty %}\n      <li>You have no items in your list.</li>\n      {% endfor %}\n    </ul>\n    {% comment \"this is a forgotten footer\" %}\n    <footer></footer>\n    {% endcomment %}\n  </body>\n</html>\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"django\",\n        indentUnit: 2,\n        indentWithTabs: true,\n        theme: \"mdn-like\"\n      });\n    </script>\n\n    <p>Mode for HTML with embedded Django template markup.</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-django</code></p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dockerfile/dockerfile.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../../addon/mode/simple\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../../addon/mode/simple\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var from = \"from\";\n  var fromRegex = new RegExp(\"^(\\\\s*)\\\\b(\" + from + \")\\\\b\", \"i\");\n\n  var shells = [\"run\", \"cmd\", \"entrypoint\", \"shell\"];\n  var shellsAsArrayRegex = new RegExp(\"^(\\\\s*)(\" + shells.join('|') + \")(\\\\s+\\\\[)\", \"i\");\n\n  var expose = \"expose\";\n  var exposeRegex = new RegExp(\"^(\\\\s*)(\" + expose + \")(\\\\s+)\", \"i\");\n\n  var others = [\n    \"arg\", \"from\", \"maintainer\", \"label\", \"env\",\n    \"add\", \"copy\", \"volume\", \"user\",\n    \"workdir\", \"onbuild\", \"stopsignal\", \"healthcheck\", \"shell\"\n  ];\n\n  // Collect all Dockerfile directives\n  var instructions = [from, expose].concat(shells).concat(others),\n      instructionRegex = \"(\" + instructions.join('|') + \")\",\n      instructionOnlyLine = new RegExp(\"^(\\\\s*)\" + instructionRegex + \"(\\\\s*)(#.*)?$\", \"i\"),\n      instructionWithArguments = new RegExp(\"^(\\\\s*)\" + instructionRegex + \"(\\\\s+)\", \"i\");\n\n  CodeMirror.defineSimpleMode(\"dockerfile\", {\n    start: [\n      // Block comment: This is a line starting with a comment\n      {\n        regex: /^\\s*#.*$/,\n        sol: true,\n        token: \"comment\"\n      },\n      {\n        regex: fromRegex,\n        token: [null, \"keyword\"],\n        sol: true,\n        next: \"from\"\n      },\n      // Highlight an instruction without any arguments (for convenience)\n      {\n        regex: instructionOnlyLine,\n        token: [null, \"keyword\", null, \"error\"],\n        sol: true\n      },\n      {\n        regex: shellsAsArrayRegex,\n        token: [null, \"keyword\", null],\n        sol: true,\n        next: \"array\"\n      },\n      {\n        regex: exposeRegex,\n        token: [null, \"keyword\", null],\n        sol: true,\n        next: \"expose\"\n      },\n      // Highlight an instruction followed by arguments\n      {\n        regex: instructionWithArguments,\n        token: [null, \"keyword\", null],\n        sol: true,\n        next: \"arguments\"\n      },\n      {\n        regex: /./,\n        token: null\n      }\n    ],\n    from: [\n      {\n        regex: /\\s*$/,\n        token: null,\n        next: \"start\"\n      },\n      {\n        // Line comment without instruction arguments is an error\n        regex: /(\\s*)(#.*)$/,\n        token: [null, \"error\"],\n        next: \"start\"\n      },\n      {\n        regex: /(\\s*\\S+\\s+)(as)/i,\n        token: [null, \"keyword\"],\n        next: \"start\"\n      },\n      // Fail safe return to start\n      {\n        token: null,\n        next: \"start\"\n      }\n    ],\n    single: [\n      {\n        regex: /(?:[^\\\\']|\\\\.)/,\n        token: \"string\"\n      },\n      {\n        regex: /'/,\n        token: \"string\",\n        pop: true\n      }\n    ],\n    double: [\n      {\n        regex: /(?:[^\\\\\"]|\\\\.)/,\n        token: \"string\"\n      },\n      {\n        regex: /\"/,\n        token: \"string\",\n        pop: true\n      }\n    ],\n    array: [\n      {\n        regex: /\\]/,\n        token: null,\n        next: \"start\"\n      },\n      {\n        regex: /\"(?:[^\\\\\"]|\\\\.)*\"?/,\n        token: \"string\"\n      }\n    ],\n    expose: [\n      {\n        regex: /\\d+$/,\n        token: \"number\",\n        next: \"start\"\n      },\n      {\n        regex: /[^\\d]+$/,\n        token: null,\n        next: \"start\"\n      },\n      {\n        regex: /\\d+/,\n        token: \"number\"\n      },\n      {\n        regex: /[^\\d]+/,\n        token: null\n      },\n      // Fail safe return to start\n      {\n        token: null,\n        next: \"start\"\n      }\n    ],\n    arguments: [\n      {\n        regex: /^\\s*#.*$/,\n        sol: true,\n        token: \"comment\"\n      },\n      {\n        regex: /\"(?:[^\\\\\"]|\\\\.)*\"?$/,\n        token: \"string\",\n        next: \"start\"\n      },\n      {\n        regex: /\"/,\n        token: \"string\",\n        push: \"double\"\n      },\n      {\n        regex: /'(?:[^\\\\']|\\\\.)*'?$/,\n        token: \"string\",\n        next: \"start\"\n      },\n      {\n        regex: /'/,\n        token: \"string\",\n        push: \"single\"\n      },\n      {\n        regex: /[^#\"']+[\\\\`]$/,\n        token: null\n      },\n      {\n        regex: /[^#\"']+$/,\n        token: null,\n        next: \"start\"\n      },\n      {\n        regex: /[^#\"']+/,\n        token: null\n      },\n      // Fail safe return to start\n      {\n        token: null,\n        next: \"start\"\n      }\n    ],\n    meta: {\n      lineComment: \"#\"\n    }\n  });\n\n  CodeMirror.defineMIME(\"text/x-dockerfile\", \"dockerfile\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dockerfile/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Dockerfile mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/simple.js\"></script>\n<script src=\"dockerfile.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Dockerfile</a>\n  </ul>\n</div>\n\n<article>\n<h2>Dockerfile mode</h2>\n<form><textarea id=\"code\" name=\"code\"># Install Ghost blogging platform and run development environment\n#\n# VERSION 1.0.0\n\nFROM ubuntu:12.10\nMAINTAINER Amer Grgic \"amer@livebyt.es\"\nWORKDIR /data/ghost\n\n# Install dependencies for nginx installation\nRUN apt-get update\nRUN apt-get install -y python g++ make software-properties-common --force-yes\nRUN add-apt-repository ppa:chris-lea/node.js\nRUN apt-get update\n# Install unzip\nRUN apt-get install -y unzip\n# Install curl\nRUN apt-get install -y curl\n# Install nodejs & npm\nRUN apt-get install -y rlwrap\nRUN apt-get install -y nodejs \n# Download Ghost v0.4.1\nRUN curl -L https://ghost.org/zip/ghost-latest.zip -o /tmp/ghost.zip\n# Unzip Ghost zip to /data/ghost\nRUN unzip -uo /tmp/ghost.zip -d /data/ghost\n# Add custom config js to /data/ghost\nADD ./config.example.js /data/ghost/config.js\n# Install Ghost with NPM\nRUN cd /data/ghost/ && npm install --production\n# Expose port 2368\nEXPOSE 2368\n# Run Ghost\nCMD [\"npm\",\"start\"]\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"dockerfile\"\n      });\n    </script>\n\n    <p>Dockerfile syntax highlighting for CodeMirror. Depends on\n    the <a href=\"../../demo/simplemode.html\">simplemode</a> addon.</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-dockerfile</code></p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dockerfile/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"text/x-dockerfile\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"simple_nodejs_dockerfile\",\n     \"[keyword FROM] node:carbon\",\n     \"[comment # Create app directory]\",\n     \"[keyword WORKDIR] /usr/src/app\",\n     \"[comment # Install app dependencies]\",\n     \"[comment # A wildcard is used to ensure both package.json AND package-lock.json are copied]\",\n     \"[comment # where available (npm@5+)]\",\n     \"[keyword COPY] package*.json ./\",\n     \"[keyword RUN] npm install\",\n     \"[keyword COPY] . .\",\n     \"[keyword EXPOSE] [number 8080] [number 3000]\",\n     \"[keyword ENV] NODE_ENV development\",\n     \"[keyword CMD] [[ [string \\\"npm\\\"], [string \\\"start\\\"] ]]\");\n\n  // Ideally the last space should not be highlighted.\n  MT(\"instruction_without_args_1\",\n     \"[keyword CMD] \");\n\n  MT(\"instruction_without_args_2\",\n     \"[comment # An instruction without args...]\",\n     \"[keyword ARG] [error #...is an error]\");\n\n  MT(\"multiline\",\n     \"[keyword RUN] apt-get update && apt-get install -y \\\\\",\n     \"  mercurial \\\\\",\n     \"  subversion \\\\\",\n     \"  && apt-get clean \\\\\",\n     \"  && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*\");\n\n  MT(\"from_comment\",\n     \"  [keyword FROM] debian:stretch # I tend to use stable as that is more stable\",\n     \"  [keyword FROM] debian:stretch [keyword AS] stable # I am even more stable\",\n     \" [keyword FROM] [error # this is an error]\");\n\n  MT(\"from_as\",\n     \"[keyword FROM] golang:1.9.2-alpine3.6 [keyword AS] build\",\n     \"[keyword COPY] --from=build /bin/project /bin/project\",\n     \"[keyword ENTRYPOINT] [[ [string \\\"/bin/project\\\"] ]]\",\n     \"[keyword CMD] [[ [string \\\"--help\\\"] ]]\");\n\n  MT(\"arg\",\n     \"[keyword ARG] VERSION=latest\",\n     \"[keyword FROM] busybox:$VERSION\",\n     \"[keyword ARG] VERSION\",\n     \"[keyword RUN] echo $VERSION > image_version\");\n\n  MT(\"label\",\n     \"[keyword LABEL] com.example.label-with-value=[string \\\"foo\\\"]\");\n\n  MT(\"label_multiline\",\n     \"[keyword LABEL] description=[string \\\"This text illustrates ]\\\\\",\n     \"[string that label-values can span multiple lines.\\\"]\");\n\n  MT(\"maintainer\",\n     \"[keyword MAINTAINER] Foo Bar [string \\\"foo@bar.com\\\"] \",\n     \"[keyword MAINTAINER] Bar Baz <bar@baz.com>\");\n\n  MT(\"env\",\n     \"[keyword ENV] BUNDLE_PATH=[string \\\"$GEM_HOME\\\"] \\\\\",\n     \"  BUNDLE_APP_CONFIG=[string \\\"$GEM_HOME\\\"]\");\n\n  MT(\"verify_keyword\",\n     \"[keyword RUN] add-apt-repository ppa:chris-lea/node.js\");\n\n  MT(\"scripts\",\n     \"[comment # Set an entrypoint, to automatically install node modules]\",\n     \"[keyword ENTRYPOINT] [[ [string \\\"/bin/bash\\\"], [string \\\"-c\\\"], [string \\\"if [[ ! -d node_modules ]]; then npm install; fi; exec \\\\\\\"${@:0}\\\\\\\";\\\"] ]]\",\n     \"[keyword CMD] npm start\",\n     \"[keyword RUN] npm run build && \\\\\",\n     \"[comment # a comment between the shell commands]\",\n     \"  npm run test\");\n\n  MT(\"strings_single\",\n     \"[keyword FROM] buildpack-deps:stretch\",\n     \"[keyword RUN] { \\\\\",\n     \"        echo [string 'install: --no-document']; \\\\\",\n     \"        echo [string 'update: --no-document']; \\\\\",\n     \"    } >> /usr/local/etc/gemrc\");\n\n  MT(\"strings_single_multiline\",\n     \"[keyword RUN] set -ex \\\\\",\n     \"    \\\\\",\n     \"    && buildDeps=[string ' ]\\\\\",\n     \"[string        bison ]\\\\\",\n     \"[string        dpkg-dev ]\\\\\",\n     \"[string        libgdbm-dev ]\\\\\",\n     \"[string        ruby ]\\\\\",\n     \"[string    '] \\\\\",\n     \"    && apt-get update\");\n\n  MT(\"strings_single_multiline_2\",\n     \"[keyword RUN] echo [string 'say \\\\' ]\\\\\",\n     \"[string   it works'] \");\n\n  MT(\"strings_double\",\n     \"[keyword RUN] apt-get install -y --no-install-recommends $buildDeps \\\\\",\n     \" \\\\\",\n     \" && wget -O ruby.tar.xz [string \\\"https://cache.ruby-lang.org/pub/ruby/${RUBY_MAJOR%-rc}/ruby-$RUBY_VERSION.tar.xz\\\"] \\\\\",\n     \" && echo [string \\\"$RUBY_DOWNLOAD_SHA256 *ruby.tar.xz\\\"] | sha256sum -c - \");\n\n  MT(\"strings_double_multiline\",\n     \"[keyword RUN] echo [string \\\"say \\\\\\\" ]\\\\\",\n     \"[string   it works\\\"] \");\n\n  MT(\"escape\",\n     \"[comment # escape=`]\",\n     \"[keyword FROM] microsoft/windowsservercore\",\n     \"[keyword RUN] powershell.exe -Command `\",\n     \"    $ErrorActionPreference = [string 'Stop']; `\",\n     \"    wget https://www.python.org/ftp/python/3.5.1/python-3.5.1.exe -OutFile c:\\python-3.5.1.exe ; `\",\n     \"    Start-Process c:\\python-3.5.1.exe -ArgumentList [string '/quiet InstallAllUsers=1 PrependPath=1'] -Wait ; `\",\n     \"    Remove-Item c:\\python-3.5.1.exe -Force)\");\n\n  MT(\"escape_strings\",\n     \"[comment # escape=`]\",\n     \"[keyword FROM] python:3.6-windowsservercore [keyword AS] python\",\n     \"[keyword RUN] $env:PATH = [string 'C:\\\\Python;C:\\\\Python\\\\Scripts;{0}'] -f $env:PATH ; `\",\n     // It should not consider \\' as escaped.\n     // \"  Set-ItemProperty -Path [string 'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Environment\\\\'] -Name Path -Value $env:PATH ;\");\n     \"  Set-ItemProperty -Path [string 'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Environment\\\\' -Name Path -Value $env:PATH ;]\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dtd/dtd.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/*\n  DTD mode\n  Ported to CodeMirror by Peter Kroon <plakroon@gmail.com>\n  Report bugs/issues here: https://github.com/codemirror/CodeMirror/issues\n  GitHub: @peterkroon\n*/\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"dtd\", function(config) {\n  var indentUnit = config.indentUnit, type;\n  function ret(style, tp) {type = tp; return style;}\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n\n    if (ch == \"<\" && stream.eat(\"!\") ) {\n      if (stream.eatWhile(/[\\-]/)) {\n        state.tokenize = tokenSGMLComment;\n        return tokenSGMLComment(stream, state);\n      } else if (stream.eatWhile(/[\\w]/)) return ret(\"keyword\", \"doindent\");\n    } else if (ch == \"<\" && stream.eat(\"?\")) { //xml declaration\n      state.tokenize = inBlock(\"meta\", \"?>\");\n      return ret(\"meta\", ch);\n    } else if (ch == \"#\" && stream.eatWhile(/[\\w]/)) return ret(\"atom\", \"tag\");\n    else if (ch == \"|\") return ret(\"keyword\", \"seperator\");\n    else if (ch.match(/[\\(\\)\\[\\]\\-\\.,\\+\\?>]/)) return ret(null, ch);//if(ch === \">\") return ret(null, \"endtag\"); else\n    else if (ch.match(/[\\[\\]]/)) return ret(\"rule\", ch);\n    else if (ch == \"\\\"\" || ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    } else if (stream.eatWhile(/[a-zA-Z\\?\\+\\d]/)) {\n      var sc = stream.current();\n      if( sc.substr(sc.length-1,sc.length).match(/\\?|\\+/) !== null )stream.backUp(1);\n      return ret(\"tag\", \"tag\");\n    } else if (ch == \"%\" || ch == \"*\" ) return ret(\"number\", \"number\");\n    else {\n      stream.eatWhile(/[\\w\\\\\\-_%.{,]/);\n      return ret(null, null);\n    }\n  }\n\n  function tokenSGMLComment(stream, state) {\n    var dashes = 0, ch;\n    while ((ch = stream.next()) != null) {\n      if (dashes >= 2 && ch == \">\") {\n        state.tokenize = tokenBase;\n        break;\n      }\n      dashes = (ch == \"-\") ? dashes + 1 : 0;\n    }\n    return ret(\"comment\", \"comment\");\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && !escaped) {\n          state.tokenize = tokenBase;\n          break;\n        }\n        escaped = !escaped && ch == \"\\\\\";\n      }\n      return ret(\"string\", \"tag\");\n    };\n  }\n\n  function inBlock(style, terminator) {\n    return function(stream, state) {\n      while (!stream.eol()) {\n        if (stream.match(terminator)) {\n          state.tokenize = tokenBase;\n          break;\n        }\n        stream.next();\n      }\n      return style;\n    };\n  }\n\n  return {\n    startState: function(base) {\n      return {tokenize: tokenBase,\n              baseIndent: base || 0,\n              stack: []};\n    },\n\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      var style = state.tokenize(stream, state);\n\n      var context = state.stack[state.stack.length-1];\n      if (stream.current() == \"[\" || type === \"doindent\" || type == \"[\") state.stack.push(\"rule\");\n      else if (type === \"endtag\") state.stack[state.stack.length-1] = \"endtag\";\n      else if (stream.current() == \"]\" || type == \"]\" || (type == \">\" && context == \"rule\")) state.stack.pop();\n      else if (type == \"[\") state.stack.push(\"[\");\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      var n = state.stack.length;\n\n      if( textAfter.match(/\\]\\s+|\\]/) )n=n-1;\n      else if(textAfter.substr(textAfter.length-1, textAfter.length) === \">\"){\n        if(textAfter.substr(0,1) === \"<\") {}\n        else if( type == \"doindent\" && textAfter.length > 1 ) {}\n        else if( type == \"doindent\")n--;\n        else if( type == \">\" && textAfter.length > 1) {}\n        else if( type == \"tag\" && textAfter !== \">\") {}\n        else if( type == \"tag\" && state.stack[state.stack.length-1] == \"rule\")n--;\n        else if( type == \"tag\")n++;\n        else if( textAfter === \">\" && state.stack[state.stack.length-1] == \"rule\" && type === \">\")n--;\n        else if( textAfter === \">\" && state.stack[state.stack.length-1] == \"rule\") {}\n        else if( textAfter.substr(0,1) !== \"<\" && textAfter.substr(0,1) === \">\" )n=n-1;\n        else if( textAfter === \">\") {}\n        else n=n-1;\n        //over rule them all\n        if(type == null || type == \"]\")n--;\n      }\n\n      return state.baseIndent + n * indentUnit;\n    },\n\n    electricChars: \"]>\"\n  };\n});\n\nCodeMirror.defineMIME(\"application/xml-dtd\", \"dtd\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dtd/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: DTD mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"dtd.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">DTD</a>\n  </ul>\n</div>\n\n<article>\n<h2>DTD mode</h2>\n<form><textarea id=\"code\" name=\"code\"><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<!ATTLIST title\n  xmlns\tCDATA\t#FIXED\t\"http://docbook.org/ns/docbook\"\n  role\tCDATA\t#IMPLIED\n  %db.common.attributes;\n  %db.common.linking.attributes;\n>\n\n<!--\n  Try: http://docbook.org/xml/5.0/dtd/docbook.dtd\n-->\n\n<!DOCTYPE xsl:stylesheet\n  [\n    <!ENTITY nbsp   \"&amp;#160;\">\n    <!ENTITY copy   \"&amp;#169;\">\n    <!ENTITY reg    \"&amp;#174;\">\n    <!ENTITY trade  \"&amp;#8482;\">\n    <!ENTITY mdash  \"&amp;#8212;\">\n    <!ENTITY ldquo  \"&amp;#8220;\">\n    <!ENTITY rdquo  \"&amp;#8221;\">\n    <!ENTITY pound  \"&amp;#163;\">\n    <!ENTITY yen    \"&amp;#165;\">\n    <!ENTITY euro   \"&amp;#8364;\">\n    <!ENTITY mathml \"http://www.w3.org/1998/Math/MathML\">\n  ]\n>\n\n<!ELEMENT title (#PCDATA|inlinemediaobject|remark|superscript|subscript|xref|link|olink|anchor|biblioref|alt|annotation|indexterm|abbrev|acronym|date|emphasis|footnote|footnoteref|foreignphrase|phrase|quote|wordasword|firstterm|glossterm|coref|trademark|productnumber|productname|database|application|hardware|citation|citerefentry|citetitle|citebiblioid|author|person|personname|org|orgname|editor|jobtitle|replaceable|package|parameter|termdef|nonterminal|systemitem|option|optional|property|inlineequation|tag|markup|token|symbol|literal|code|constant|email|uri|guiicon|guibutton|guimenuitem|guimenu|guisubmenu|guilabel|menuchoice|mousebutton|keycombo|keycap|keycode|keysym|shortcut|accel|prompt|envar|filename|command|computeroutput|userinput|function|varname|returnvalue|type|classname|exceptionname|interfacename|methodname|modifier|initializer|ooclass|ooexception|oointerface|errorcode|errortext|errorname|errortype)*>\n\n<!ENTITY % db.common.attributes \"\n  xml:id\tID\t#IMPLIED\n  version\tCDATA\t#IMPLIED\n  xml:lang\tCDATA\t#IMPLIED\n  xml:base\tCDATA\t#IMPLIED\n  remap\tCDATA\t#IMPLIED\n  xreflabel\tCDATA\t#IMPLIED\n  revisionflag\t(changed|added|deleted|off)\t#IMPLIED\n  dir\t(ltr|rtl|lro|rlo)\t#IMPLIED\n  arch\tCDATA\t#IMPLIED\n  audience\tCDATA\t#IMPLIED\n  condition\tCDATA\t#IMPLIED\n  conformance\tCDATA\t#IMPLIED\n  os\tCDATA\t#IMPLIED\n  revision\tCDATA\t#IMPLIED\n  security\tCDATA\t#IMPLIED\n  userlevel\tCDATA\t#IMPLIED\n  vendor\tCDATA\t#IMPLIED\n  wordsize\tCDATA\t#IMPLIED\n  annotations\tCDATA\t#IMPLIED\n\n\"></textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"dtd\", alignCDATA: true},\n        lineNumbers: true,\n        lineWrapping: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>application/xml-dtd</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dylan/dylan.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nfunction forEach(arr, f) {\n  for (var i = 0; i < arr.length; i++) f(arr[i], i)\n}\nfunction some(arr, f) {\n  for (var i = 0; i < arr.length; i++) if (f(arr[i], i)) return true\n  return false\n}\n\nCodeMirror.defineMode(\"dylan\", function(_config) {\n  // Words\n  var words = {\n    // Words that introduce unnamed definitions like \"define interface\"\n    unnamedDefinition: [\"interface\"],\n\n    // Words that introduce simple named definitions like \"define library\"\n    namedDefinition: [\"module\", \"library\", \"macro\",\n                      \"C-struct\", \"C-union\",\n                      \"C-function\", \"C-callable-wrapper\"\n                     ],\n\n    // Words that introduce type definitions like \"define class\".\n    // These are also parameterized like \"define method\" and are\n    // appended to otherParameterizedDefinitionWords\n    typeParameterizedDefinition: [\"class\", \"C-subtype\", \"C-mapped-subtype\"],\n\n    // Words that introduce trickier definitions like \"define method\".\n    // These require special definitions to be added to startExpressions\n    otherParameterizedDefinition: [\"method\", \"function\",\n                                   \"C-variable\", \"C-address\"\n                                  ],\n\n    // Words that introduce module constant definitions.\n    // These must also be simple definitions and are\n    // appended to otherSimpleDefinitionWords\n    constantSimpleDefinition: [\"constant\"],\n\n    // Words that introduce module variable definitions.\n    // These must also be simple definitions and are\n    // appended to otherSimpleDefinitionWords\n    variableSimpleDefinition: [\"variable\"],\n\n    // Other words that introduce simple definitions\n    // (without implicit bodies).\n    otherSimpleDefinition: [\"generic\", \"domain\",\n                            \"C-pointer-type\",\n                            \"table\"\n                           ],\n\n    // Words that begin statements with implicit bodies.\n    statement: [\"if\", \"block\", \"begin\", \"method\", \"case\",\n                \"for\", \"select\", \"when\", \"unless\", \"until\",\n                \"while\", \"iterate\", \"profiling\", \"dynamic-bind\"\n               ],\n\n    // Patterns that act as separators in compound statements.\n    // This may include any general pattern that must be indented\n    // specially.\n    separator: [\"finally\", \"exception\", \"cleanup\", \"else\",\n                \"elseif\", \"afterwards\"\n               ],\n\n    // Keywords that do not require special indentation handling,\n    // but which should be highlighted\n    other: [\"above\", \"below\", \"by\", \"from\", \"handler\", \"in\",\n            \"instance\", \"let\", \"local\", \"otherwise\", \"slot\",\n            \"subclass\", \"then\", \"to\", \"keyed-by\", \"virtual\"\n           ],\n\n    // Condition signaling function calls\n    signalingCalls: [\"signal\", \"error\", \"cerror\",\n                     \"break\", \"check-type\", \"abort\"\n                    ]\n  };\n\n  words[\"otherDefinition\"] =\n    words[\"unnamedDefinition\"]\n    .concat(words[\"namedDefinition\"])\n    .concat(words[\"otherParameterizedDefinition\"]);\n\n  words[\"definition\"] =\n    words[\"typeParameterizedDefinition\"]\n    .concat(words[\"otherDefinition\"]);\n\n  words[\"parameterizedDefinition\"] =\n    words[\"typeParameterizedDefinition\"]\n    .concat(words[\"otherParameterizedDefinition\"]);\n\n  words[\"simpleDefinition\"] =\n    words[\"constantSimpleDefinition\"]\n    .concat(words[\"variableSimpleDefinition\"])\n    .concat(words[\"otherSimpleDefinition\"]);\n\n  words[\"keyword\"] =\n    words[\"statement\"]\n    .concat(words[\"separator\"])\n    .concat(words[\"other\"]);\n\n  // Patterns\n  var symbolPattern = \"[-_a-zA-Z?!*@<>$%]+\";\n  var symbol = new RegExp(\"^\" + symbolPattern);\n  var patterns = {\n    // Symbols with special syntax\n    symbolKeyword: symbolPattern + \":\",\n    symbolClass: \"<\" + symbolPattern + \">\",\n    symbolGlobal: \"\\\\*\" + symbolPattern + \"\\\\*\",\n    symbolConstant: \"\\\\$\" + symbolPattern\n  };\n  var patternStyles = {\n    symbolKeyword: \"atom\",\n    symbolClass: \"tag\",\n    symbolGlobal: \"variable-2\",\n    symbolConstant: \"variable-3\"\n  };\n\n  // Compile all patterns to regular expressions\n  for (var patternName in patterns)\n    if (patterns.hasOwnProperty(patternName))\n      patterns[patternName] = new RegExp(\"^\" + patterns[patternName]);\n\n  // Names beginning \"with-\" and \"without-\" are commonly\n  // used as statement macro\n  patterns[\"keyword\"] = [/^with(?:out)?-[-_a-zA-Z?!*@<>$%]+/];\n\n  var styles = {};\n  styles[\"keyword\"] = \"keyword\";\n  styles[\"definition\"] = \"def\";\n  styles[\"simpleDefinition\"] = \"def\";\n  styles[\"signalingCalls\"] = \"builtin\";\n\n  // protected words lookup table\n  var wordLookup = {};\n  var styleLookup = {};\n\n  forEach([\n    \"keyword\",\n    \"definition\",\n    \"simpleDefinition\",\n    \"signalingCalls\"\n  ], function(type) {\n    forEach(words[type], function(word) {\n      wordLookup[word] = type;\n      styleLookup[word] = styles[type];\n    });\n  });\n\n\n  function chain(stream, state, f) {\n    state.tokenize = f;\n    return f(stream, state);\n  }\n\n  function tokenBase(stream, state) {\n    // String\n    var ch = stream.peek();\n    if (ch == \"'\" || ch == '\"') {\n      stream.next();\n      return chain(stream, state, tokenString(ch, \"string\"));\n    }\n    // Comment\n    else if (ch == \"/\") {\n      stream.next();\n      if (stream.eat(\"*\")) {\n        return chain(stream, state, tokenComment);\n      } else if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n      stream.backUp(1);\n    }\n    // Decimal\n    else if (/[+\\-\\d\\.]/.test(ch)) {\n      if (stream.match(/^[+-]?[0-9]*\\.[0-9]*([esdx][+-]?[0-9]+)?/i) ||\n          stream.match(/^[+-]?[0-9]+([esdx][+-]?[0-9]+)/i) ||\n          stream.match(/^[+-]?\\d+/)) {\n        return \"number\";\n      }\n    }\n    // Hash\n    else if (ch == \"#\") {\n      stream.next();\n      // Symbol with string syntax\n      ch = stream.peek();\n      if (ch == '\"') {\n        stream.next();\n        return chain(stream, state, tokenString('\"', \"string\"));\n      }\n      // Binary number\n      else if (ch == \"b\") {\n        stream.next();\n        stream.eatWhile(/[01]/);\n        return \"number\";\n      }\n      // Hex number\n      else if (ch == \"x\") {\n        stream.next();\n        stream.eatWhile(/[\\da-f]/i);\n        return \"number\";\n      }\n      // Octal number\n      else if (ch == \"o\") {\n        stream.next();\n        stream.eatWhile(/[0-7]/);\n        return \"number\";\n      }\n      // Token concatenation in macros\n      else if (ch == '#') {\n        stream.next();\n        return \"punctuation\";\n      }\n      // Sequence literals\n      else if ((ch == '[') || (ch == '(')) {\n        stream.next();\n        return \"bracket\";\n      // Hash symbol\n      } else if (stream.match(/f|t|all-keys|include|key|next|rest/i)) {\n        return \"atom\";\n      } else {\n        stream.eatWhile(/[-a-zA-Z]/);\n        return \"error\";\n      }\n    } else if (ch == \"~\") {\n      stream.next();\n      ch = stream.peek();\n      if (ch == \"=\") {\n        stream.next();\n        ch = stream.peek();\n        if (ch == \"=\") {\n          stream.next();\n          return \"operator\";\n        }\n        return \"operator\";\n      }\n      return \"operator\";\n    } else if (ch == \":\") {\n      stream.next();\n      ch = stream.peek();\n      if (ch == \"=\") {\n        stream.next();\n        return \"operator\";\n      } else if (ch == \":\") {\n        stream.next();\n        return \"punctuation\";\n      }\n    } else if (\"[](){}\".indexOf(ch) != -1) {\n      stream.next();\n      return \"bracket\";\n    } else if (\".,\".indexOf(ch) != -1) {\n      stream.next();\n      return \"punctuation\";\n    } else if (stream.match(\"end\")) {\n      return \"keyword\";\n    }\n    for (var name in patterns) {\n      if (patterns.hasOwnProperty(name)) {\n        var pattern = patterns[name];\n        if ((pattern instanceof Array && some(pattern, function(p) {\n          return stream.match(p);\n        })) || stream.match(pattern))\n          return patternStyles[name];\n      }\n    }\n    if (/[+\\-*\\/^=<>&|]/.test(ch)) {\n      stream.next();\n      return \"operator\";\n    }\n    if (stream.match(\"define\")) {\n      return \"def\";\n    } else {\n      stream.eatWhile(/[\\w\\-]/);\n      // Keyword\n      if (wordLookup.hasOwnProperty(stream.current())) {\n        return styleLookup[stream.current()];\n      } else if (stream.current().match(symbol)) {\n        return \"variable\";\n      } else {\n        stream.next();\n        return \"variable-2\";\n      }\n    }\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;\n    while ((ch = stream.next())) {\n      if (ch == \"/\" && maybeEnd) {\n        if (nestedCount > 0) {\n          nestedCount--;\n        } else {\n          state.tokenize = tokenBase;\n          break;\n        }\n      } else if (ch == \"*\" && maybeNested) {\n        nestedCount++;\n      }\n      maybeEnd = (ch == \"*\");\n      maybeNested = (ch == \"/\");\n    }\n    return \"comment\";\n  }\n\n  function tokenString(quote, style) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {\n          end = true;\n          break;\n        }\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end || !escaped) {\n        state.tokenize = tokenBase;\n      }\n      return style;\n    };\n  }\n\n  // Interface\n  return {\n    startState: function() {\n      return {\n        tokenize: tokenBase,\n        currentIndent: 0\n      };\n    },\n    token: function(stream, state) {\n      if (stream.eatSpace())\n        return null;\n      var style = state.tokenize(stream, state);\n      return style;\n    },\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-dylan\", \"dylan\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dylan/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Dylan mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"../../addon/comment/continuecomment.js\"></script>\n<script src=\"../../addon/comment/comment.js\"></script>\n<script src=\"dylan.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Dylan</a>\n  </ul>\n</div>\n\n<article>\n<h2>Dylan mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\nModule:       locators-internals\nSynopsis:     Abstract modeling of locations\nAuthor:       Andy Armstrong\nCopyright:    Original Code is Copyright (c) 1995-2004 Functional Objects, Inc.\n              All rights reserved.\nLicense:      See License.txt in this distribution for details.\nWarranty:     Distributed WITHOUT WARRANTY OF ANY KIND\n\ndefine open generic locator-server\n    (locator :: <locator>) => (server :: false-or(<server-locator>));\ndefine open generic locator-host\n    (locator :: <locator>) => (host :: false-or(<string>));\ndefine open generic locator-volume\n    (locator :: <locator>) => (volume :: false-or(<string>));\ndefine open generic locator-directory\n    (locator :: <locator>) => (directory :: false-or(<directory-locator>));\ndefine open generic locator-relative?\n    (locator :: <locator>) => (relative? :: <boolean>);\ndefine open generic locator-path\n    (locator :: <locator>) => (path :: <sequence>);\ndefine open generic locator-base\n    (locator :: <locator>) => (base :: false-or(<string>));\ndefine open generic locator-extension\n    (locator :: <locator>) => (extension :: false-or(<string>));\n\n/// Locator classes\n\ndefine open abstract class <directory-locator> (<physical-locator>)\nend class <directory-locator>;\n\ndefine open abstract class <file-locator> (<physical-locator>)\nend class <file-locator>;\n\ndefine method as\n    (class == <directory-locator>, string :: <string>)\n => (locator :: <directory-locator>)\n  as(<native-directory-locator>, string)\nend method as;\n\ndefine method make\n    (class == <directory-locator>,\n     #key server :: false-or(<server-locator>) = #f,\n          path :: <sequence> = #[],\n          relative? :: <boolean> = #f,\n          name :: false-or(<string>) = #f)\n => (locator :: <directory-locator>)\n  make(<native-directory-locator>,\n       server:    server,\n       path:      path,\n       relative?: relative?,\n       name:      name)\nend method make;\n\ndefine method as\n    (class == <file-locator>, string :: <string>)\n => (locator :: <file-locator>)\n  as(<native-file-locator>, string)\nend method as;\n\ndefine method make\n    (class == <file-locator>,\n     #key directory :: false-or(<directory-locator>) = #f,\n          base :: false-or(<string>) = #f,\n          extension :: false-or(<string>) = #f,\n          name :: false-or(<string>) = #f)\n => (locator :: <file-locator>)\n  make(<native-file-locator>,\n       directory: directory,\n       base:      base,\n       extension: extension,\n       name:      name)\nend method make;\n\n/// Locator coercion\n\n//---*** andrewa: This caching scheme doesn't work yet, so disable it.\ndefine constant $cache-locators?        = #f;\ndefine constant $cache-locator-strings? = #f;\n\ndefine constant $locator-to-string-cache = make(<object-table>, weak: #\"key\");\ndefine constant $string-to-locator-cache = make(<string-table>, weak: #\"value\");\n\ndefine open generic locator-as-string\n    (class :: subclass(<string>), locator :: <locator>)\n => (string :: <string>);\n\ndefine open generic string-as-locator\n    (class :: subclass(<locator>), string :: <string>)\n => (locator :: <locator>);\n\ndefine sealed sideways method as\n    (class :: subclass(<string>), locator :: <locator>)\n => (string :: <string>)\n  let string = element($locator-to-string-cache, locator, default: #f);\n  if (string)\n    as(class, string)\n  else\n    let string = locator-as-string(class, locator);\n    if ($cache-locator-strings?)\n      element($locator-to-string-cache, locator) := string;\n    else\n      string\n    end\n  end\nend method as;\n\ndefine sealed sideways method as\n    (class :: subclass(<locator>), string :: <string>)\n => (locator :: <locator>)\n  let locator = element($string-to-locator-cache, string, default: #f);\n  if (instance?(locator, class))\n    locator\n  else\n    let locator = string-as-locator(class, string);\n    if ($cache-locators?)\n      element($string-to-locator-cache, string) := locator;\n    else\n      locator\n    end\n  end\nend method as;\n\n/// Locator conditions\n\ndefine class <locator-error> (<format-string-condition>, <error>)\nend class <locator-error>;\n\ndefine function locator-error\n    (format-string :: <string>, #rest format-arguments)\n  error(make(<locator-error>, \n             format-string:    format-string,\n             format-arguments: format-arguments))\nend function locator-error;\n\n/// Useful locator protocols\n\ndefine open generic locator-test\n    (locator :: <directory-locator>) => (test :: <function>);\n\ndefine method locator-test\n    (locator :: <directory-locator>) => (test :: <function>)\n  \\=\nend method locator-test;\n\ndefine open generic locator-might-have-links?\n    (locator :: <directory-locator>) => (links? :: <boolean>);\n\ndefine method locator-might-have-links?\n    (locator :: <directory-locator>) => (links? :: singleton(#f))\n  #f\nend method locator-might-have-links?;\n\ndefine method locator-relative?\n    (locator :: <file-locator>) => (relative? :: <boolean>)\n  let directory = locator.locator-directory;\n  ~directory | directory.locator-relative?\nend method locator-relative?;\n\ndefine method current-directory-locator?\n    (locator :: <directory-locator>) => (current-directory? :: <boolean>)\n  locator.locator-relative?\n    & locator.locator-path = #[#\"self\"]\nend method current-directory-locator?;\n\ndefine method locator-directory\n    (locator :: <directory-locator>) => (parent :: false-or(<directory-locator>))\n  let path = locator.locator-path;\n  unless (empty?(path))\n    make(object-class(locator),\n         server:    locator.locator-server,\n         path:      copy-sequence(path, end: path.size - 1),\n         relative?: locator.locator-relative?)\n  end\nend method locator-directory;\n\n/// Simplify locator\n\ndefine open generic simplify-locator\n    (locator :: <physical-locator>)\n => (simplified-locator :: <physical-locator>);\n\ndefine method simplify-locator\n    (locator :: <directory-locator>)\n => (simplified-locator :: <directory-locator>)\n  let path = locator.locator-path;\n  let relative? = locator.locator-relative?;\n  let resolve-parent? = ~locator.locator-might-have-links?;\n  let simplified-path\n    = simplify-path(path, \n                    resolve-parent?: resolve-parent?,\n                    relative?: relative?);\n  if (path ~= simplified-path)\n    make(object-class(locator),\n         server:    locator.locator-server,\n         path:      simplified-path,\n         relative?: locator.locator-relative?)\n  else\n    locator\n  end\nend method simplify-locator;\n\ndefine method simplify-locator\n    (locator :: <file-locator>) => (simplified-locator :: <file-locator>)\n  let directory = locator.locator-directory;\n  let simplified-directory = directory & simplify-locator(directory);\n  if (directory ~= simplified-directory)\n    make(object-class(locator),\n         directory: simplified-directory,\n         base:      locator.locator-base,\n         extension: locator.locator-extension)\n  else\n    locator\n  end\nend method simplify-locator;\n\n/// Subdirectory locator\n\ndefine open generic subdirectory-locator\n    (locator :: <directory-locator>, #rest sub-path)\n => (subdirectory :: <directory-locator>);\n\ndefine method subdirectory-locator\n    (locator :: <directory-locator>, #rest sub-path)\n => (subdirectory :: <directory-locator>)\n  let old-path = locator.locator-path;\n  let new-path = concatenate-as(<simple-object-vector>, old-path, sub-path);\n  make(object-class(locator),\n       server:    locator.locator-server,\n       path:      new-path,\n       relative?: locator.locator-relative?)\nend method subdirectory-locator;\n\n/// Relative locator\n\ndefine open generic relative-locator\n    (locator :: <physical-locator>, from-locator :: <physical-locator>)\n => (relative-locator :: <physical-locator>);\n\ndefine method relative-locator\n    (locator :: <directory-locator>, from-locator :: <directory-locator>)\n => (relative-locator :: <directory-locator>)\n  let path = locator.locator-path;\n  let from-path = from-locator.locator-path;\n  case\n    ~locator.locator-relative? & from-locator.locator-relative? =>\n      locator-error\n        (\"Cannot find relative path of absolute locator %= from relative locator %=\",\n         locator, from-locator);\n    locator.locator-server ~= from-locator.locator-server =>\n      locator;\n    path = from-path =>\n      make(object-class(locator),\n           path: vector(#\"self\"),\n           relative?: #t);\n    otherwise =>\n      make(object-class(locator),\n           path: relative-path(path, from-path, test: locator.locator-test),\n           relative?: #t);\n  end\nend method relative-locator;\n\ndefine method relative-locator\n    (locator :: <file-locator>, from-directory :: <directory-locator>)\n => (relative-locator :: <file-locator>)\n  let directory = locator.locator-directory;\n  let relative-directory = directory & relative-locator(directory, from-directory);\n  if (relative-directory ~= directory)\n    simplify-locator\n      (make(object-class(locator),\n            directory: relative-directory,\n            base:      locator.locator-base,\n            extension: locator.locator-extension))\n  else\n    locator\n  end\nend method relative-locator;\n\ndefine method relative-locator\n    (locator :: <physical-locator>, from-locator :: <file-locator>)\n => (relative-locator :: <physical-locator>)\n  let from-directory = from-locator.locator-directory;\n  case\n    from-directory =>\n      relative-locator(locator, from-directory);\n    ~locator.locator-relative? =>\n      locator-error\n        (\"Cannot find relative path of absolute locator %= from relative locator %=\",\n         locator, from-locator);\n    otherwise =>\n      locator;\n  end\nend method relative-locator;\n\n/// Merge locators\n\ndefine open generic merge-locators\n    (locator :: <physical-locator>, from-locator :: <physical-locator>)\n => (merged-locator :: <physical-locator>);\n\n/// Merge locators\n\ndefine method merge-locators\n    (locator :: <directory-locator>, from-locator :: <directory-locator>)\n => (merged-locator :: <directory-locator>)\n  if (locator.locator-relative?)\n    let path = concatenate(from-locator.locator-path, locator.locator-path);\n    simplify-locator\n      (make(object-class(locator),\n            server:    from-locator.locator-server,\n            path:      path,\n            relative?: from-locator.locator-relative?))\n  else\n    locator\n  end\nend method merge-locators;\n\ndefine method merge-locators\n    (locator :: <file-locator>, from-locator :: <directory-locator>)\n => (merged-locator :: <file-locator>)\n  let directory = locator.locator-directory;\n  let merged-directory \n    = if (directory)\n        merge-locators(directory, from-locator)\n      else\n        simplify-locator(from-locator)\n      end;\n  if (merged-directory ~= directory)\n    make(object-class(locator),\n         directory: merged-directory,\n         base:      locator.locator-base,\n         extension: locator.locator-extension)\n  else\n    locator\n  end\nend method merge-locators;\n\ndefine method merge-locators\n    (locator :: <physical-locator>, from-locator :: <file-locator>)\n => (merged-locator :: <physical-locator>)\n  let from-directory = from-locator.locator-directory;\n  if (from-directory)\n    merge-locators(locator, from-directory)\n  else\n    locator\n  end\nend method merge-locators;\n\n/// Locator protocols\n\ndefine sideways method supports-open-locator?\n    (locator :: <file-locator>) => (openable? :: <boolean>)\n  ~locator.locator-relative?\nend method supports-open-locator?;\n\ndefine sideways method open-locator\n    (locator :: <file-locator>, #rest keywords, #key, #all-keys)\n => (stream :: <stream>)\n  apply(open-file-stream, locator, keywords)\nend method open-locator;\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"text/x-dylan\",\n        lineNumbers: true,\n        matchBrackets: true,\n        continueComments: \"Enter\",\n        extraKeys: {\"Ctrl-Q\": \"toggleComment\"},\n        tabMode: \"indent\",\n        indentUnit: 2\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-dylan</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/dylan/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"dylan\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT('comments',\n     '[comment // This is a line comment]',\n     '[comment /* This is a block comment */]',\n     '[comment /* This is a multi]',\n     '[comment line comment]',\n     '[comment */]',\n     '[comment /* And this is a /*]',\n     '[comment /* nested */ comment */]');\n\n  MT('unary_operators',\n     '[operator -][variable a]',\n     '[operator -] [variable a]',\n     '[operator ~][variable a]',\n     '[operator ~] [variable a]');\n\n  MT('binary_operators',\n     '[variable a] [operator +] [variable b]',\n     '[variable a] [operator -] [variable b]',\n     '[variable a] [operator *] [variable b]',\n     '[variable a] [operator /] [variable b]',\n     '[variable a] [operator ^] [variable b]',\n     '[variable a] [operator =] [variable b]',\n     '[variable a] [operator ==] [variable b]',\n     '[variable a] [operator ~=] [variable b]',\n     '[variable a] [operator ~==] [variable b]',\n     '[variable a] [operator <] [variable b]',\n     '[variable a] [operator <=] [variable b]',\n     '[variable a] [operator >] [variable b]',\n     '[variable a] [operator >=] [variable b]',\n     '[variable a] [operator &] [variable b]',\n     '[variable a] [operator |] [variable b]',\n     '[variable a] [operator :=] [variable b]');\n\n  MT('integers',\n     '[number 1]',\n     '[number 123]',\n     '[number -123]',\n     '[number +456]',\n     '[number #b010]',\n     '[number #o073]',\n     '[number #xabcDEF123]');\n\n  MT('floats',\n     '[number .3]',\n     '[number -1.]',\n     '[number -2.335]',\n     '[number +3.78d1]',\n     '[number 3.78s-1]',\n     '[number -3.32e+5]');\n\n  MT('characters_and_strings',\n     \"[string 'a']\",\n     \"[string '\\\\\\\\'']\",\n     '[string \"\"]',\n     '[string \"a\"]',\n     '[string \"abc def\"]',\n     '[string \"More escaped characters: \\\\\\\\\\\\\\\\ \\\\\\\\a \\\\\\\\b \\\\\\\\e \\\\\\\\f \\\\\\\\n \\\\\\\\r \\\\\\\\t \\\\\\\\0 ...\"]');\n\n  MT('brackets',\n     '[bracket #[[]]]',\n     '[bracket #()]',\n     '[bracket #(][number 1][bracket )]',\n     '[bracket [[][number 1][punctuation ,] [number 3][bracket ]]]',\n     '[bracket ()]',\n     '[bracket {}]',\n     '[keyword if] [bracket (][variable foo][bracket )]',\n     '[bracket (][number 1][bracket )]',\n     '[bracket [[][number 1][bracket ]]]');\n\n  MT('hash_words',\n     '[punctuation ##]',\n     '[atom #f]', '[atom #F]',\n     '[atom #t]', '[atom #T]',\n     '[atom #all-keys]',\n     '[atom #include]',\n     '[atom #key]',\n     '[atom #next]',\n     '[atom #rest]',\n     '[string #\"foo\"]',\n     '[error #invalid]');\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ebnf/ebnf.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"ebnf\", function (config) {\n    var commentType = {slash: 0, parenthesis: 1};\n    var stateType = {comment: 0, _string: 1, characterClass: 2};\n    var bracesMode = null;\n\n    if (config.bracesMode)\n      bracesMode = CodeMirror.getMode(config, config.bracesMode);\n\n    return {\n      startState: function () {\n        return {\n          stringType: null,\n          commentType: null,\n          braced: 0,\n          lhs: true,\n          localState: null,\n          stack: [],\n          inDefinition: false\n        };\n      },\n      token: function (stream, state) {\n        if (!stream) return;\n\n        //check for state changes\n        if (state.stack.length === 0) {\n          //strings\n          if ((stream.peek() == '\"') || (stream.peek() == \"'\")) {\n            state.stringType = stream.peek();\n            stream.next(); // Skip quote\n            state.stack.unshift(stateType._string);\n          } else if (stream.match(/^\\/\\*/)) { //comments starting with /*\n            state.stack.unshift(stateType.comment);\n            state.commentType = commentType.slash;\n          } else if (stream.match(/^\\(\\*/)) { //comments starting with (*\n            state.stack.unshift(stateType.comment);\n            state.commentType = commentType.parenthesis;\n          }\n        }\n\n        //return state\n        //stack has\n        switch (state.stack[0]) {\n        case stateType._string:\n          while (state.stack[0] === stateType._string && !stream.eol()) {\n            if (stream.peek() === state.stringType) {\n              stream.next(); // Skip quote\n              state.stack.shift(); // Clear flag\n            } else if (stream.peek() === \"\\\\\") {\n              stream.next();\n              stream.next();\n            } else {\n              stream.match(/^.[^\\\\\\\"\\']*/);\n            }\n          }\n          return state.lhs ? \"property string\" : \"string\"; // Token style\n\n        case stateType.comment:\n          while (state.stack[0] === stateType.comment && !stream.eol()) {\n            if (state.commentType === commentType.slash && stream.match(/\\*\\//)) {\n              state.stack.shift(); // Clear flag\n              state.commentType = null;\n            } else if (state.commentType === commentType.parenthesis && stream.match(/\\*\\)/)) {\n              state.stack.shift(); // Clear flag\n              state.commentType = null;\n            } else {\n              stream.match(/^.[^\\*]*/);\n            }\n          }\n          return \"comment\";\n\n        case stateType.characterClass:\n          while (state.stack[0] === stateType.characterClass && !stream.eol()) {\n            if (!(stream.match(/^[^\\]\\\\]+/) || stream.match(/^\\\\./))) {\n              state.stack.shift();\n            }\n          }\n          return \"operator\";\n        }\n\n        var peek = stream.peek();\n\n        if (bracesMode !== null && (state.braced || peek === \"{\")) {\n          if (state.localState === null)\n            state.localState = CodeMirror.startState(bracesMode);\n\n          var token = bracesMode.token(stream, state.localState),\n          text = stream.current();\n\n          if (!token) {\n            for (var i = 0; i < text.length; i++) {\n              if (text[i] === \"{\") {\n                if (state.braced === 0) {\n                  token = \"matchingbracket\";\n                }\n                state.braced++;\n              } else if (text[i] === \"}\") {\n                state.braced--;\n                if (state.braced === 0) {\n                  token = \"matchingbracket\";\n                }\n              }\n            }\n          }\n          return token;\n        }\n\n        //no stack\n        switch (peek) {\n        case \"[\":\n          stream.next();\n          state.stack.unshift(stateType.characterClass);\n          return \"bracket\";\n        case \":\":\n        case \"|\":\n        case \";\":\n          stream.next();\n          return \"operator\";\n        case \"%\":\n          if (stream.match(\"%%\")) {\n            return \"header\";\n          } else if (stream.match(/[%][A-Za-z]+/)) {\n            return \"keyword\";\n          } else if (stream.match(/[%][}]/)) {\n            return \"matchingbracket\";\n          }\n          break;\n        case \"/\":\n          if (stream.match(/[\\/][A-Za-z]+/)) {\n          return \"keyword\";\n        }\n        case \"\\\\\":\n          if (stream.match(/[\\][a-z]+/)) {\n            return \"string-2\";\n          }\n        case \".\":\n          if (stream.match(\".\")) {\n            return \"atom\";\n          }\n        case \"*\":\n        case \"-\":\n        case \"+\":\n        case \"^\":\n          if (stream.match(peek)) {\n            return \"atom\";\n          }\n        case \"$\":\n          if (stream.match(\"$$\")) {\n            return \"builtin\";\n          } else if (stream.match(/[$][0-9]+/)) {\n            return \"variable-3\";\n          }\n        case \"<\":\n          if (stream.match(/<<[a-zA-Z_]+>>/)) {\n            return \"builtin\";\n          }\n        }\n\n        if (stream.match(/^\\/\\//)) {\n          stream.skipToEnd();\n          return \"comment\";\n        } else if (stream.match(/return/)) {\n          return \"operator\";\n        } else if (stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/)) {\n          if (stream.match(/(?=[\\(.])/)) {\n            return \"variable\";\n          } else if (stream.match(/(?=[\\s\\n]*[:=])/)) {\n            return \"def\";\n          }\n          return \"variable-2\";\n        } else if ([\"[\", \"]\", \"(\", \")\"].indexOf(stream.peek()) != -1) {\n          stream.next();\n          return \"bracket\";\n        } else if (!stream.eatSpace()) {\n          stream.next();\n        }\n        return null;\n      }\n    };\n  });\n\n  CodeMirror.defineMIME(\"text/x-ebnf\", \"ebnf\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ebnf/index.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <title>CodeMirror: EBNF Mode</title>\n    <meta charset=\"utf-8\"/>\n    <link rel=stylesheet href=\"../../doc/docs.css\">\n\n    <link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n    <script src=\"../../lib/codemirror.js\"></script>\n    <script src=\"../javascript/javascript.js\"></script>\n    <script src=\"ebnf.js\"></script>\n    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n  </head>\n  <body>\n    <div id=nav>\n      <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n      <ul>\n        <li><a href=\"../../index.html\">Home</a>\n        <li><a href=\"../../doc/manual.html\">Manual</a>\n        <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n      </ul>\n      <ul>\n        <li><a href=\"../index.html\">Language modes</a>\n        <li><a class=active href=\"#\">EBNF Mode</a>\n      </ul>\n    </div>\n\n    <article>\n      <h2>EBNF Mode (bracesMode setting = \"javascript\")</h2>\n      <form><textarea id=\"code\" name=\"code\">\n/* description: Parses end executes mathematical expressions. */\n\n/* lexical grammar */\n%lex\n\n%%\n\\s+                   /* skip whitespace */\n[0-9]+(\".\"[0-9]+)?\\b  return 'NUMBER';\n\"*\"                   return '*';\n\"/\"                   return '/';\n\"-\"                   return '-';\n\"+\"                   return '+';\n\"^\"                   return '^';\n\"(\"                   return '(';\n\")\"                   return ')';\n\"PI\"                  return 'PI';\n\"E\"                   return 'E';\n&lt;&lt;EOF&gt;&gt;               return 'EOF';\n\n/lex\n\n/* operator associations and precedence */\n\n%left '+' '-'\n%left '*' '/'\n%left '^'\n%left UMINUS\n\n%start expressions\n\n%% /* language grammar */\n\nexpressions\n: e EOF\n{print($1); return $1;}\n;\n\ne\n: e '+' e\n{$$ = $1+$3;}\n| e '-' e\n{$$ = $1-$3;}\n| e '*' e\n{$$ = $1*$3;}\n| e '/' e\n{$$ = $1/$3;}\n| e '^' e\n{$$ = Math.pow($1, $3);}\n| '-' e %prec UMINUS\n{$$ = -$2;}\n| '(' e ')'\n{$$ = $2;}\n| NUMBER\n{$$ = Number(yytext);}\n| E\n{$$ = Math.E;}\n| PI\n{$$ = Math.PI;}\n;</textarea></form>\n      <script>\n        var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n          mode: {name: \"ebnf\"},\n          lineNumbers: true,\n          bracesMode: 'javascript'\n        });\n      </script>\n      <h3>The EBNF Mode</h3>\n      <p> Created by <a href=\"https://github.com/robertleeplummerjr\">Robert Plummer</a></p>\n    </article>\n  </body>\n</html>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ecl/ecl.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"ecl\", function(config) {\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  function metaHook(stream, state) {\n    if (!state.startOfLine) return false;\n    stream.skipToEnd();\n    return \"meta\";\n  }\n\n  var indentUnit = config.indentUnit;\n  var keyword = words(\"abs acos allnodes ascii asin asstring atan atan2 ave case choose choosen choosesets clustersize combine correlation cos cosh count covariance cron dataset dedup define denormalize distribute distributed distribution ebcdic enth error evaluate event eventextra eventname exists exp failcode failmessage fetch fromunicode getisvalid global graph group hash hash32 hash64 hashcrc hashmd5 having if index intformat isvalid iterate join keyunicode length library limit ln local log loop map matched matchlength matchposition matchtext matchunicode max merge mergejoin min nolocal nonempty normalize parse pipe power preload process project pull random range rank ranked realformat recordof regexfind regexreplace regroup rejected rollup round roundup row rowdiff sample set sin sinh sizeof soapcall sort sorted sqrt stepped stored sum table tan tanh thisnode topn tounicode transfer trim truncate typeof ungroup unicodeorder variance which workunit xmldecode xmlencode xmltext xmlunicode\");\n  var variable = words(\"apply assert build buildindex evaluate fail keydiff keypatch loadxml nothor notify output parallel sequential soapcall wait\");\n  var variable_2 = words(\"__compressed__ all and any as atmost before beginc++ best between case const counter csv descend encrypt end endc++ endmacro except exclusive expire export extend false few first flat from full function group header heading hole ifblock import in interface joined keep keyed last left limit load local locale lookup macro many maxcount maxlength min skew module named nocase noroot noscan nosort not of only opt or outer overwrite packed partition penalty physicallength pipe quote record relationship repeat return right scan self separator service shared skew skip sql store terminator thor threshold token transform trim true type unicodeorder unsorted validate virtual whole wild within xml xpath\");\n  var variable_3 = words(\"ascii big_endian boolean data decimal ebcdic integer pattern qstring real record rule set of string token udecimal unicode unsigned varstring varunicode\");\n  var builtin = words(\"checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when\");\n  var blockKeywords = words(\"catch class do else finally for if switch try while\");\n  var atoms = words(\"true false null\");\n  var hooks = {\"#\": metaHook};\n  var isOperatorChar = /[+\\-*&%=<>!?|\\/]/;\n\n  var curPunc;\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (hooks[ch]) {\n      var result = hooks[ch](stream, state);\n      if (result !== false) return result;\n    }\n    if (ch == '\"' || ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n    if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n      curPunc = ch;\n      return null;\n    }\n    if (/\\d/.test(ch)) {\n      stream.eatWhile(/[\\w\\.]/);\n      return \"number\";\n    }\n    if (ch == \"/\") {\n      if (stream.eat(\"*\")) {\n        state.tokenize = tokenComment;\n        return tokenComment(stream, state);\n      }\n      if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n    }\n    if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return \"operator\";\n    }\n    stream.eatWhile(/[\\w\\$_]/);\n    var cur = stream.current().toLowerCase();\n    if (keyword.propertyIsEnumerable(cur)) {\n      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n      return \"keyword\";\n    } else if (variable.propertyIsEnumerable(cur)) {\n      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n      return \"variable\";\n    } else if (variable_2.propertyIsEnumerable(cur)) {\n      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n      return \"variable-2\";\n    } else if (variable_3.propertyIsEnumerable(cur)) {\n      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n      return \"variable-3\";\n    } else if (builtin.propertyIsEnumerable(cur)) {\n      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n      return \"builtin\";\n    } else { //Data types are of from KEYWORD##\n                var i = cur.length - 1;\n                while(i >= 0 && (!isNaN(cur[i]) || cur[i] == '_'))\n                        --i;\n\n                if (i > 0) {\n                        var cur2 = cur.substr(0, i + 1);\n                if (variable_3.propertyIsEnumerable(cur2)) {\n                        if (blockKeywords.propertyIsEnumerable(cur2)) curPunc = \"newstatement\";\n                        return \"variable-3\";\n                }\n            }\n    }\n    if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n    return null;\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {end = true; break;}\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end || !escaped)\n        state.tokenize = tokenBase;\n      return \"string\";\n    };\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function Context(indented, column, type, align, prev) {\n    this.indented = indented;\n    this.column = column;\n    this.type = type;\n    this.align = align;\n    this.prev = prev;\n  }\n  function pushContext(state, col, type) {\n    return state.context = new Context(state.indented, col, type, null, state.context);\n  }\n  function popContext(state) {\n    var t = state.context.type;\n    if (t == \")\" || t == \"]\" || t == \"}\")\n      state.indented = state.context.indented;\n    return state.context = state.context.prev;\n  }\n\n  // Interface\n\n  return {\n    startState: function(basecolumn) {\n      return {\n        tokenize: null,\n        context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", false),\n        indented: 0,\n        startOfLine: true\n      };\n    },\n\n    token: function(stream, state) {\n      var ctx = state.context;\n      if (stream.sol()) {\n        if (ctx.align == null) ctx.align = false;\n        state.indented = stream.indentation();\n        state.startOfLine = true;\n      }\n      if (stream.eatSpace()) return null;\n      curPunc = null;\n      var style = (state.tokenize || tokenBase)(stream, state);\n      if (style == \"comment\" || style == \"meta\") return style;\n      if (ctx.align == null) ctx.align = true;\n\n      if ((curPunc == \";\" || curPunc == \":\") && ctx.type == \"statement\") popContext(state);\n      else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n      else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n      else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n      else if (curPunc == \"}\") {\n        while (ctx.type == \"statement\") ctx = popContext(state);\n        if (ctx.type == \"}\") ctx = popContext(state);\n        while (ctx.type == \"statement\") ctx = popContext(state);\n      }\n      else if (curPunc == ctx.type) popContext(state);\n      else if (ctx.type == \"}\" || ctx.type == \"top\" || (ctx.type == \"statement\" && curPunc == \"newstatement\"))\n        pushContext(state, stream.column(), \"statement\");\n      state.startOfLine = false;\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize != tokenBase && state.tokenize != null) return 0;\n      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);\n      if (ctx.type == \"statement\" && firstChar == \"}\") ctx = ctx.prev;\n      var closing = firstChar == ctx.type;\n      if (ctx.type == \"statement\") return ctx.indented + (firstChar == \"{\" ? 0 : indentUnit);\n      else if (ctx.align) return ctx.column + (closing ? 0 : 1);\n      else return ctx.indented + (closing ? 0 : indentUnit);\n    },\n\n    electricChars: \"{}\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-ecl\", \"ecl\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ecl/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: ECL mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"ecl.js\"></script>\n<style>.CodeMirror {border: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">ECL</a>\n  </ul>\n</div>\n\n<article>\n<h2>ECL mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n/*\nsample useless code to demonstrate ecl syntax highlighting\nthis is a multiline comment!\n*/\n\n//  this is a singleline comment!\n\nimport ut;\nr := \n  record\n   string22 s1 := '123';\n   integer4 i1 := 123;\n  end;\n#option('tmp', true);\nd := dataset('tmp::qb', r, thor);\noutput(d);\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p>Based on CodeMirror's clike mode.  For more information see <a href=\"http://hpccsystems.com\">HPCC Systems</a> web site.</p>\n    <p><strong>MIME types defined:</strong> <code>text/x-ecl</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/eiffel/eiffel.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"eiffel\", function() {\n  function wordObj(words) {\n    var o = {};\n    for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true;\n    return o;\n  }\n  var keywords = wordObj([\n    'note',\n    'across',\n    'when',\n    'variant',\n    'until',\n    'unique',\n    'undefine',\n    'then',\n    'strip',\n    'select',\n    'retry',\n    'rescue',\n    'require',\n    'rename',\n    'reference',\n    'redefine',\n    'prefix',\n    'once',\n    'old',\n    'obsolete',\n    'loop',\n    'local',\n    'like',\n    'is',\n    'inspect',\n    'infix',\n    'include',\n    'if',\n    'frozen',\n    'from',\n    'external',\n    'export',\n    'ensure',\n    'end',\n    'elseif',\n    'else',\n    'do',\n    'creation',\n    'create',\n    'check',\n    'alias',\n    'agent',\n    'separate',\n    'invariant',\n    'inherit',\n    'indexing',\n    'feature',\n    'expanded',\n    'deferred',\n    'class',\n    'Void',\n    'True',\n    'Result',\n    'Precursor',\n    'False',\n    'Current',\n    'create',\n    'attached',\n    'detachable',\n    'as',\n    'and',\n    'implies',\n    'not',\n    'or'\n  ]);\n  var operators = wordObj([\":=\", \"and then\",\"and\", \"or\",\"<<\",\">>\"]);\n\n  function chain(newtok, stream, state) {\n    state.tokenize.push(newtok);\n    return newtok(stream, state);\n  }\n\n  function tokenBase(stream, state) {\n    if (stream.eatSpace()) return null;\n    var ch = stream.next();\n    if (ch == '\"'||ch == \"'\") {\n      return chain(readQuoted(ch, \"string\"), stream, state);\n    } else if (ch == \"-\"&&stream.eat(\"-\")) {\n      stream.skipToEnd();\n      return \"comment\";\n    } else if (ch == \":\"&&stream.eat(\"=\")) {\n      return \"operator\";\n    } else if (/[0-9]/.test(ch)) {\n      stream.eatWhile(/[xXbBCc0-9\\.]/);\n      stream.eat(/[\\?\\!]/);\n      return \"ident\";\n    } else if (/[a-zA-Z_0-9]/.test(ch)) {\n      stream.eatWhile(/[a-zA-Z_0-9]/);\n      stream.eat(/[\\?\\!]/);\n      return \"ident\";\n    } else if (/[=+\\-\\/*^%<>~]/.test(ch)) {\n      stream.eatWhile(/[=+\\-\\/*^%<>~]/);\n      return \"operator\";\n    } else {\n      return null;\n    }\n  }\n\n  function readQuoted(quote, style,  unescaped) {\n    return function(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && (unescaped || !escaped)) {\n          state.tokenize.pop();\n          break;\n        }\n        escaped = !escaped && ch == \"%\";\n      }\n      return style;\n    };\n  }\n\n  return {\n    startState: function() {\n      return {tokenize: [tokenBase]};\n    },\n\n    token: function(stream, state) {\n      var style = state.tokenize[state.tokenize.length-1](stream, state);\n      if (style == \"ident\") {\n        var word = stream.current();\n        style = keywords.propertyIsEnumerable(stream.current()) ? \"keyword\"\n          : operators.propertyIsEnumerable(stream.current()) ? \"operator\"\n          : /^[A-Z][A-Z_0-9]*$/g.test(word) ? \"tag\"\n          : /^0[bB][0-1]+$/g.test(word) ? \"number\"\n          : /^0[cC][0-7]+$/g.test(word) ? \"number\"\n          : /^0[xX][a-fA-F0-9]+$/g.test(word) ? \"number\"\n          : /^([0-9]+\\.[0-9]*)|([0-9]*\\.[0-9]+)$/g.test(word) ? \"number\"\n          : /^[0-9]+$/g.test(word) ? \"number\"\n          : \"variable\";\n      }\n      return style;\n    },\n    lineComment: \"--\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-eiffel\", \"eiffel\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/eiffel/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Eiffel mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/neat.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"eiffel.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      .cm-s-default span.cm-arrow { color: red; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Eiffel</a>\n  </ul>\n</div>\n\n<article>\n<h2>Eiffel mode</h2>\n<form><textarea id=\"code\" name=\"code\">\nnote\n    description: \"[\n        Project-wide universal properties.\n        This class is an ancestor to all developer-written classes.\n        ANY may be customized for individual projects or teams.\n        ]\"\n\n    library: \"Free implementation of ELKS library\"\n    status: \"See notice at end of class.\"\n    legal: \"See notice at end of class.\"\n    date: \"$Date: 2013-01-25 11:49:00 -0800 (Fri, 25 Jan 2013) $\"\n    revision: \"$Revision: 712 $\"\n\nclass\n    ANY\n\nfeature -- Customization\n\nfeature -- Access\n\n    generator: STRING\n            -- Name of current object's generating class\n            -- (base class of the type of which it is a direct instance)\n        external\n            \"built_in\"\n        ensure\n            generator_not_void: Result /= Void\n            generator_not_empty: not Result.is_empty\n        end\n\n    generating_type: TYPE [detachable like Current]\n            -- Type of current object\n            -- (type of which it is a direct instance)\n        do\n            Result := {detachable like Current}\n        ensure\n            generating_type_not_void: Result /= Void\n        end\n\nfeature -- Status report\n\n    conforms_to (other: ANY): BOOLEAN\n            -- Does type of current object conform to type\n            -- of `other' (as per Eiffel: The Language, chapter 13)?\n        require\n            other_not_void: other /= Void\n        external\n            \"built_in\"\n        end\n\n    same_type (other: ANY): BOOLEAN\n            -- Is type of current object identical to type of `other'?\n        require\n            other_not_void: other /= Void\n        external\n            \"built_in\"\n        ensure\n            definition: Result = (conforms_to (other) and\n                                        other.conforms_to (Current))\n        end\n\nfeature -- Comparison\n\n    is_equal (other: like Current): BOOLEAN\n            -- Is `other' attached to an object considered\n            -- equal to current object?\n        require\n            other_not_void: other /= Void\n        external\n            \"built_in\"\n        ensure\n            symmetric: Result implies other ~ Current\n            consistent: standard_is_equal (other) implies Result\n        end\n\n    frozen standard_is_equal (other: like Current): BOOLEAN\n            -- Is `other' attached to an object of the same type\n            -- as current object, and field-by-field identical to it?\n        require\n            other_not_void: other /= Void\n        external\n            \"built_in\"\n        ensure\n            same_type: Result implies same_type (other)\n            symmetric: Result implies other.standard_is_equal (Current)\n        end\n\n    frozen equal (a: detachable ANY; b: like a): BOOLEAN\n            -- Are `a' and `b' either both void or attached\n            -- to objects considered equal?\n        do\n            if a = Void then\n                Result := b = Void\n            else\n                Result := b /= Void and then\n                            a.is_equal (b)\n            end\n        ensure\n            definition: Result = (a = Void and b = Void) or else\n                        ((a /= Void and b /= Void) and then\n                        a.is_equal (b))\n        end\n\n    frozen standard_equal (a: detachable ANY; b: like a): BOOLEAN\n            -- Are `a' and `b' either both void or attached to\n            -- field-by-field identical objects of the same type?\n            -- Always uses default object comparison criterion.\n        do\n            if a = Void then\n                Result := b = Void\n            else\n                Result := b /= Void and then\n                            a.standard_is_equal (b)\n            end\n        ensure\n            definition: Result = (a = Void and b = Void) or else\n                        ((a /= Void and b /= Void) and then\n                        a.standard_is_equal (b))\n        end\n\n    frozen is_deep_equal (other: like Current): BOOLEAN\n            -- Are `Current' and `other' attached to isomorphic object structures?\n        require\n            other_not_void: other /= Void\n        external\n            \"built_in\"\n        ensure\n            shallow_implies_deep: standard_is_equal (other) implies Result\n            same_type: Result implies same_type (other)\n            symmetric: Result implies other.is_deep_equal (Current)\n        end\n\n    frozen deep_equal (a: detachable ANY; b: like a): BOOLEAN\n            -- Are `a' and `b' either both void\n            -- or attached to isomorphic object structures?\n        do\n            if a = Void then\n                Result := b = Void\n            else\n                Result := b /= Void and then a.is_deep_equal (b)\n            end\n        ensure\n            shallow_implies_deep: standard_equal (a, b) implies Result\n            both_or_none_void: (a = Void) implies (Result = (b = Void))\n            same_type: (Result and (a /= Void)) implies (b /= Void and then a.same_type (b))\n            symmetric: Result implies deep_equal (b, a)\n        end\n\nfeature -- Duplication\n\n    frozen twin: like Current\n            -- New object equal to `Current'\n            -- `twin' calls `copy'; to change copying/twinning semantics, redefine `copy'.\n        external\n            \"built_in\"\n        ensure\n            twin_not_void: Result /= Void\n            is_equal: Result ~ Current\n        end\n\n    copy (other: like Current)\n            -- Update current object using fields of object attached\n            -- to `other', so as to yield equal objects.\n        require\n            other_not_void: other /= Void\n            type_identity: same_type (other)\n        external\n            \"built_in\"\n        ensure\n            is_equal: Current ~ other\n        end\n\n    frozen standard_copy (other: like Current)\n            -- Copy every field of `other' onto corresponding field\n            -- of current object.\n        require\n            other_not_void: other /= Void\n            type_identity: same_type (other)\n        external\n            \"built_in\"\n        ensure\n            is_standard_equal: standard_is_equal (other)\n        end\n\n    frozen clone (other: detachable ANY): like other\n            -- Void if `other' is void; otherwise new object\n            -- equal to `other'\n            --\n            -- For non-void `other', `clone' calls `copy';\n            -- to change copying/cloning semantics, redefine `copy'.\n        obsolete\n            \"Use `twin' instead.\"\n        do\n            if other /= Void then\n                Result := other.twin\n            end\n        ensure\n            equal: Result ~ other\n        end\n\n    frozen standard_clone (other: detachable ANY): like other\n            -- Void if `other' is void; otherwise new object\n            -- field-by-field identical to `other'.\n            -- Always uses default copying semantics.\n        obsolete\n            \"Use `standard_twin' instead.\"\n        do\n            if other /= Void then\n                Result := other.standard_twin\n            end\n        ensure\n            equal: standard_equal (Result, other)\n        end\n\n    frozen standard_twin: like Current\n            -- New object field-by-field identical to `other'.\n            -- Always uses default copying semantics.\n        external\n            \"built_in\"\n        ensure\n            standard_twin_not_void: Result /= Void\n            equal: standard_equal (Result, Current)\n        end\n\n    frozen deep_twin: like Current\n            -- New object structure recursively duplicated from Current.\n        external\n            \"built_in\"\n        ensure\n            deep_twin_not_void: Result /= Void\n            deep_equal: deep_equal (Current, Result)\n        end\n\n    frozen deep_clone (other: detachable ANY): like other\n            -- Void if `other' is void: otherwise, new object structure\n            -- recursively duplicated from the one attached to `other'\n        obsolete\n            \"Use `deep_twin' instead.\"\n        do\n            if other /= Void then\n                Result := other.deep_twin\n            end\n        ensure\n            deep_equal: deep_equal (other, Result)\n        end\n\n    frozen deep_copy (other: like Current)\n            -- Effect equivalent to that of:\n            --      `copy' (`other' . `deep_twin')\n        require\n            other_not_void: other /= Void\n        do\n            copy (other.deep_twin)\n        ensure\n            deep_equal: deep_equal (Current, other)\n        end\n\nfeature {NONE} -- Retrieval\n\n    frozen internal_correct_mismatch\n            -- Called from runtime to perform a proper dynamic dispatch on `correct_mismatch'\n            -- from MISMATCH_CORRECTOR.\n        local\n            l_msg: STRING\n            l_exc: EXCEPTIONS\n        do\n            if attached {MISMATCH_CORRECTOR} Current as l_corrector then\n                l_corrector.correct_mismatch\n            else\n                create l_msg.make_from_string (\"Mismatch: \")\n                create l_exc\n                l_msg.append (generating_type.name)\n                l_exc.raise_retrieval_exception (l_msg)\n            end\n        end\n\nfeature -- Output\n\n    io: STD_FILES\n            -- Handle to standard file setup\n        once\n            create Result\n            Result.set_output_default\n        ensure\n            io_not_void: Result /= Void\n        end\n\n    out: STRING\n            -- New string containing terse printable representation\n            -- of current object\n        do\n            Result := tagged_out\n        ensure\n            out_not_void: Result /= Void\n        end\n\n    frozen tagged_out: STRING\n            -- New string containing terse printable representation\n            -- of current object\n        external\n            \"built_in\"\n        ensure\n            tagged_out_not_void: Result /= Void\n        end\n\n    print (o: detachable ANY)\n            -- Write terse external representation of `o'\n            -- on standard output.\n        do\n            if o /= Void then\n                io.put_string (o.out)\n            end\n        end\n\nfeature -- Platform\n\n    Operating_environment: OPERATING_ENVIRONMENT\n            -- Objects available from the operating system\n        once\n            create Result\n        ensure\n            operating_environment_not_void: Result /= Void\n        end\n\nfeature {NONE} -- Initialization\n\n    default_create\n            -- Process instances of classes with no creation clause.\n            -- (Default: do nothing.)\n        do\n        end\n\nfeature -- Basic operations\n\n    default_rescue\n            -- Process exception for routines with no Rescue clause.\n            -- (Default: do nothing.)\n        do\n        end\n\n    frozen do_nothing\n            -- Execute a null action.\n        do\n        end\n\n    frozen default: detachable like Current\n            -- Default value of object's type\n        do\n        end\n\n    frozen default_pointer: POINTER\n            -- Default value of type `POINTER'\n            -- (Avoid the need to write `p'.`default' for\n            -- some `p' of type `POINTER'.)\n        do\n        ensure\n            -- Result = Result.default\n        end\n\n    frozen as_attached: attached like Current\n            -- Attached version of Current\n            -- (Can be used during transitional period to convert\n            -- non-void-safe classes to void-safe ones.)\n        do\n            Result := Current\n        end\n\ninvariant\n    reflexive_equality: standard_is_equal (Current)\n    reflexive_conformance: conforms_to (Current)\n\nnote\n    copyright: \"Copyright (c) 1984-2012, Eiffel Software and others\"\n    license:   \"Eiffel Forum License v2 (see http://www.eiffel.com/licensing/forum.txt)\"\n    source: \"[\n            Eiffel Software\n            5949 Hollister Ave., Goleta, CA 93117 USA\n            Telephone 805-685-1006, Fax 805-685-6869\n            Website http://www.eiffel.com\n            Customer support http://support.eiffel.com\n        ]\"\n\nend\n\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"text/x-eiffel\",\n        indentUnit: 4,\n        lineNumbers: true,\n        theme: \"neat\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-eiffel</code>.</p>\n \n <p> Created by <a href=\"https://github.com/ynh\">YNH</a>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/elm/elm.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"elm\", function() {\n\n    function switchState(source, setState, f) {\n      setState(f);\n      return f(source, setState);\n    }\n\n    // These should all be Unicode extended, as per the Haskell 2010 report\n    var smallRE = /[a-z_]/;\n    var largeRE = /[A-Z]/;\n    var digitRE = /[0-9]/;\n    var hexitRE = /[0-9A-Fa-f]/;\n    var octitRE = /[0-7]/;\n    var idRE = /[a-z_A-Z0-9\\']/;\n    var symbolRE = /[-!#$%&*+.\\/<=>?@\\\\^|~:\\u03BB\\u2192]/;\n    var specialRE = /[(),;[\\]`{}]/;\n    var whiteCharRE = /[ \\t\\v\\f]/; // newlines are handled in tokenizer\n\n    function normal() {\n      return function (source, setState) {\n        if (source.eatWhile(whiteCharRE)) {\n          return null;\n        }\n\n        var ch = source.next();\n        if (specialRE.test(ch)) {\n          if (ch == '{' && source.eat('-')) {\n            var t = \"comment\";\n            if (source.eat('#')) t = \"meta\";\n            return switchState(source, setState, ncomment(t, 1));\n          }\n          return null;\n        }\n\n        if (ch == '\\'') {\n          if (source.eat('\\\\'))\n            source.next();  // should handle other escapes here\n          else\n            source.next();\n\n          if (source.eat('\\''))\n            return \"string\";\n          return \"error\";\n        }\n\n        if (ch == '\"') {\n          return switchState(source, setState, stringLiteral);\n        }\n\n        if (largeRE.test(ch)) {\n          source.eatWhile(idRE);\n          if (source.eat('.'))\n            return \"qualifier\";\n          return \"variable-2\";\n        }\n\n        if (smallRE.test(ch)) {\n          var isDef = source.pos === 1;\n          source.eatWhile(idRE);\n          return isDef ? \"type\" : \"variable\";\n        }\n\n        if (digitRE.test(ch)) {\n          if (ch == '0') {\n            if (source.eat(/[xX]/)) {\n              source.eatWhile(hexitRE); // should require at least 1\n              return \"integer\";\n            }\n            if (source.eat(/[oO]/)) {\n              source.eatWhile(octitRE); // should require at least 1\n              return \"number\";\n            }\n          }\n          source.eatWhile(digitRE);\n          var t = \"number\";\n          if (source.eat('.')) {\n            t = \"number\";\n            source.eatWhile(digitRE); // should require at least 1\n          }\n          if (source.eat(/[eE]/)) {\n            t = \"number\";\n            source.eat(/[-+]/);\n            source.eatWhile(digitRE); // should require at least 1\n          }\n          return t;\n        }\n\n        if (symbolRE.test(ch)) {\n          if (ch == '-' && source.eat(/-/)) {\n            source.eatWhile(/-/);\n            if (!source.eat(symbolRE)) {\n              source.skipToEnd();\n              return \"comment\";\n            }\n          }\n          source.eatWhile(symbolRE);\n          return \"builtin\";\n        }\n\n        return \"error\";\n      }\n    }\n\n    function ncomment(type, nest) {\n      if (nest == 0) {\n        return normal();\n      }\n      return function(source, setState) {\n        var currNest = nest;\n        while (!source.eol()) {\n          var ch = source.next();\n          if (ch == '{' && source.eat('-')) {\n            ++currNest;\n          } else if (ch == '-' && source.eat('}')) {\n            --currNest;\n            if (currNest == 0) {\n              setState(normal());\n              return type;\n            }\n          }\n        }\n        setState(ncomment(type, currNest));\n        return type;\n      }\n    }\n\n    function stringLiteral(source, setState) {\n      while (!source.eol()) {\n        var ch = source.next();\n        if (ch == '\"') {\n          setState(normal());\n          return \"string\";\n        }\n        if (ch == '\\\\') {\n          if (source.eol() || source.eat(whiteCharRE)) {\n            setState(stringGap);\n            return \"string\";\n          }\n          if (!source.eat('&')) source.next(); // should handle other escapes here\n        }\n      }\n      setState(normal());\n      return \"error\";\n    }\n\n    function stringGap(source, setState) {\n      if (source.eat('\\\\')) {\n        return switchState(source, setState, stringLiteral);\n      }\n      source.next();\n      setState(normal());\n      return \"error\";\n    }\n\n\n    var wellKnownWords = (function() {\n      var wkw = {};\n\n      var keywords = [\n        \"case\", \"of\", \"as\",\n        \"if\", \"then\", \"else\",\n        \"let\", \"in\",\n        \"infix\", \"infixl\", \"infixr\",\n        \"type\", \"alias\",\n        \"input\", \"output\", \"foreign\", \"loopback\",\n        \"module\", \"where\", \"import\", \"exposing\",\n        \"_\", \"..\", \"|\", \":\", \"=\", \"\\\\\", \"\\\"\", \"->\", \"<-\"\n      ];\n\n      for (var i = keywords.length; i--;)\n        wkw[keywords[i]] = \"keyword\";\n\n      return wkw;\n    })();\n\n\n\n    return {\n      startState: function ()  { return { f: normal() }; },\n      copyState:  function (s) { return { f: s.f }; },\n\n      token: function(stream, state) {\n        var t = state.f(stream, function(s) { state.f = s; });\n        var w = stream.current();\n        return (wellKnownWords.hasOwnProperty(w)) ? wellKnownWords[w] : t;\n      }\n    };\n\n  });\n\n  CodeMirror.defineMIME(\"text/x-elm\", \"elm\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/elm/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Elm mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"elm.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Elm</a>\n  </ul>\n</div>\n\n<article>\n<h2>Elm mode</h2>\n\n<div><textarea id=\"code\" name=\"code\">\nimport Color exposing (..)\nimport Graphics.Collage exposing (..)\nimport Graphics.Element exposing (..)\nimport Time exposing (..)\n\nmain =\n  Signal.map clock (every second)\n\nclock t =\n  collage 400 400\n    [ filled    lightGrey   (ngon 12 110)\n    , outlined (solid grey) (ngon 12 110)\n    , hand orange   100  t\n    , hand charcoal 100 (t/60)\n    , hand charcoal 60  (t/720)\n    ]\n\nhand clr len time =\n  let angle = degrees (90 - 6 * inSeconds time)\n  in\n      segment (0,0) (fromPolar (len,angle))\n        |> traced (solid clr)\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"text/x-elm\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-elm</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/erlang/erlang.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/*jshint unused:true, eqnull:true, curly:true, bitwise:true */\n/*jshint undef:true, latedef:true, trailing:true */\n/*global CodeMirror:true */\n\n// erlang mode.\n// tokenizer -> token types -> CodeMirror styles\n// tokenizer maintains a parse stack\n// indenter uses the parse stack\n\n// TODO indenter:\n//   bit syntax\n//   old guard/bif/conversion clashes (e.g. \"float/1\")\n//   type/spec/opaque\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMIME(\"text/x-erlang\", \"erlang\");\n\nCodeMirror.defineMode(\"erlang\", function(cmCfg) {\n  \"use strict\";\n\n/////////////////////////////////////////////////////////////////////////////\n// constants\n\n  var typeWords = [\n    \"-type\", \"-spec\", \"-export_type\", \"-opaque\"];\n\n  var keywordWords = [\n    \"after\",\"begin\",\"catch\",\"case\",\"cond\",\"end\",\"fun\",\"if\",\n    \"let\",\"of\",\"query\",\"receive\",\"try\",\"when\"];\n\n  var separatorRE    = /[\\->,;]/;\n  var separatorWords = [\n    \"->\",\";\",\",\"];\n\n  var operatorAtomWords = [\n    \"and\",\"andalso\",\"band\",\"bnot\",\"bor\",\"bsl\",\"bsr\",\"bxor\",\n    \"div\",\"not\",\"or\",\"orelse\",\"rem\",\"xor\"];\n\n  var operatorSymbolRE    = /[\\+\\-\\*\\/<>=\\|:!]/;\n  var operatorSymbolWords = [\n    \"=\",\"+\",\"-\",\"*\",\"/\",\">\",\">=\",\"<\",\"=<\",\"=:=\",\"==\",\"=/=\",\"/=\",\"||\",\"<-\",\"!\"];\n\n  var openParenRE    = /[<\\(\\[\\{]/;\n  var openParenWords = [\n    \"<<\",\"(\",\"[\",\"{\"];\n\n  var closeParenRE    = /[>\\)\\]\\}]/;\n  var closeParenWords = [\n    \"}\",\"]\",\")\",\">>\"];\n\n  var guardWords = [\n    \"is_atom\",\"is_binary\",\"is_bitstring\",\"is_boolean\",\"is_float\",\n    \"is_function\",\"is_integer\",\"is_list\",\"is_number\",\"is_pid\",\n    \"is_port\",\"is_record\",\"is_reference\",\"is_tuple\",\n    \"atom\",\"binary\",\"bitstring\",\"boolean\",\"function\",\"integer\",\"list\",\n    \"number\",\"pid\",\"port\",\"record\",\"reference\",\"tuple\"];\n\n  var bifWords = [\n    \"abs\",\"adler32\",\"adler32_combine\",\"alive\",\"apply\",\"atom_to_binary\",\n    \"atom_to_list\",\"binary_to_atom\",\"binary_to_existing_atom\",\n    \"binary_to_list\",\"binary_to_term\",\"bit_size\",\"bitstring_to_list\",\n    \"byte_size\",\"check_process_code\",\"contact_binary\",\"crc32\",\n    \"crc32_combine\",\"date\",\"decode_packet\",\"delete_module\",\n    \"disconnect_node\",\"element\",\"erase\",\"exit\",\"float\",\"float_to_list\",\n    \"garbage_collect\",\"get\",\"get_keys\",\"group_leader\",\"halt\",\"hd\",\n    \"integer_to_list\",\"internal_bif\",\"iolist_size\",\"iolist_to_binary\",\n    \"is_alive\",\"is_atom\",\"is_binary\",\"is_bitstring\",\"is_boolean\",\n    \"is_float\",\"is_function\",\"is_integer\",\"is_list\",\"is_number\",\"is_pid\",\n    \"is_port\",\"is_process_alive\",\"is_record\",\"is_reference\",\"is_tuple\",\n    \"length\",\"link\",\"list_to_atom\",\"list_to_binary\",\"list_to_bitstring\",\n    \"list_to_existing_atom\",\"list_to_float\",\"list_to_integer\",\n    \"list_to_pid\",\"list_to_tuple\",\"load_module\",\"make_ref\",\"module_loaded\",\n    \"monitor_node\",\"node\",\"node_link\",\"node_unlink\",\"nodes\",\"notalive\",\n    \"now\",\"open_port\",\"pid_to_list\",\"port_close\",\"port_command\",\n    \"port_connect\",\"port_control\",\"pre_loaded\",\"process_flag\",\n    \"process_info\",\"processes\",\"purge_module\",\"put\",\"register\",\n    \"registered\",\"round\",\"self\",\"setelement\",\"size\",\"spawn\",\"spawn_link\",\n    \"spawn_monitor\",\"spawn_opt\",\"split_binary\",\"statistics\",\n    \"term_to_binary\",\"time\",\"throw\",\"tl\",\"trunc\",\"tuple_size\",\n    \"tuple_to_list\",\"unlink\",\"unregister\",\"whereis\"];\n\n// upper case: [A-Z] [Ø-Þ] [À-Ö]\n// lower case: [a-z] [ß-ö] [ø-ÿ]\n  var anumRE       = /[\\w@Ø-ÞÀ-Öß-öø-ÿ]/;\n  var escapesRE    =\n    /[0-7]{1,3}|[bdefnrstv\\\\\"']|\\^[a-zA-Z]|x[0-9a-zA-Z]{2}|x{[0-9a-zA-Z]+}/;\n\n/////////////////////////////////////////////////////////////////////////////\n// tokenizer\n\n  function tokenizer(stream,state) {\n    // in multi-line string\n    if (state.in_string) {\n      state.in_string = (!doubleQuote(stream));\n      return rval(state,stream,\"string\");\n    }\n\n    // in multi-line atom\n    if (state.in_atom) {\n      state.in_atom = (!singleQuote(stream));\n      return rval(state,stream,\"atom\");\n    }\n\n    // whitespace\n    if (stream.eatSpace()) {\n      return rval(state,stream,\"whitespace\");\n    }\n\n    // attributes and type specs\n    if (!peekToken(state) &&\n        stream.match(/-\\s*[a-zß-öø-ÿ][\\wØ-ÞÀ-Öß-öø-ÿ]*/)) {\n      if (is_member(stream.current(),typeWords)) {\n        return rval(state,stream,\"type\");\n      }else{\n        return rval(state,stream,\"attribute\");\n      }\n    }\n\n    var ch = stream.next();\n\n    // comment\n    if (ch == '%') {\n      stream.skipToEnd();\n      return rval(state,stream,\"comment\");\n    }\n\n    // colon\n    if (ch == \":\") {\n      return rval(state,stream,\"colon\");\n    }\n\n    // macro\n    if (ch == '?') {\n      stream.eatSpace();\n      stream.eatWhile(anumRE);\n      return rval(state,stream,\"macro\");\n    }\n\n    // record\n    if (ch == \"#\") {\n      stream.eatSpace();\n      stream.eatWhile(anumRE);\n      return rval(state,stream,\"record\");\n    }\n\n    // dollar escape\n    if (ch == \"$\") {\n      if (stream.next() == \"\\\\\" && !stream.match(escapesRE)) {\n        return rval(state,stream,\"error\");\n      }\n      return rval(state,stream,\"number\");\n    }\n\n    // dot\n    if (ch == \".\") {\n      return rval(state,stream,\"dot\");\n    }\n\n    // quoted atom\n    if (ch == '\\'') {\n      if (!(state.in_atom = (!singleQuote(stream)))) {\n        if (stream.match(/\\s*\\/\\s*[0-9]/,false)) {\n          stream.match(/\\s*\\/\\s*[0-9]/,true);\n          return rval(state,stream,\"fun\");      // 'f'/0 style fun\n        }\n        if (stream.match(/\\s*\\(/,false) || stream.match(/\\s*:/,false)) {\n          return rval(state,stream,\"function\");\n        }\n      }\n      return rval(state,stream,\"atom\");\n    }\n\n    // string\n    if (ch == '\"') {\n      state.in_string = (!doubleQuote(stream));\n      return rval(state,stream,\"string\");\n    }\n\n    // variable\n    if (/[A-Z_Ø-ÞÀ-Ö]/.test(ch)) {\n      stream.eatWhile(anumRE);\n      return rval(state,stream,\"variable\");\n    }\n\n    // atom/keyword/BIF/function\n    if (/[a-z_ß-öø-ÿ]/.test(ch)) {\n      stream.eatWhile(anumRE);\n\n      if (stream.match(/\\s*\\/\\s*[0-9]/,false)) {\n        stream.match(/\\s*\\/\\s*[0-9]/,true);\n        return rval(state,stream,\"fun\");      // f/0 style fun\n      }\n\n      var w = stream.current();\n\n      if (is_member(w,keywordWords)) {\n        return rval(state,stream,\"keyword\");\n      }else if (is_member(w,operatorAtomWords)) {\n        return rval(state,stream,\"operator\");\n      }else if (stream.match(/\\s*\\(/,false)) {\n        // 'put' and 'erlang:put' are bifs, 'foo:put' is not\n        if (is_member(w,bifWords) &&\n            ((peekToken(state).token != \":\") ||\n             (peekToken(state,2).token == \"erlang\"))) {\n          return rval(state,stream,\"builtin\");\n        }else if (is_member(w,guardWords)) {\n          return rval(state,stream,\"guard\");\n        }else{\n          return rval(state,stream,\"function\");\n        }\n      }else if (lookahead(stream) == \":\") {\n        if (w == \"erlang\") {\n          return rval(state,stream,\"builtin\");\n        } else {\n          return rval(state,stream,\"function\");\n        }\n      }else if (is_member(w,[\"true\",\"false\"])) {\n        return rval(state,stream,\"boolean\");\n      }else{\n        return rval(state,stream,\"atom\");\n      }\n    }\n\n    // number\n    var digitRE      = /[0-9]/;\n    var radixRE      = /[0-9a-zA-Z]/;         // 36#zZ style int\n    if (digitRE.test(ch)) {\n      stream.eatWhile(digitRE);\n      if (stream.eat('#')) {                // 36#aZ  style integer\n        if (!stream.eatWhile(radixRE)) {\n          stream.backUp(1);                 //\"36#\" - syntax error\n        }\n      } else if (stream.eat('.')) {       // float\n        if (!stream.eatWhile(digitRE)) {\n          stream.backUp(1);        // \"3.\" - probably end of function\n        } else {\n          if (stream.eat(/[eE]/)) {        // float with exponent\n            if (stream.eat(/[-+]/)) {\n              if (!stream.eatWhile(digitRE)) {\n                stream.backUp(2);            // \"2e-\" - syntax error\n              }\n            } else {\n              if (!stream.eatWhile(digitRE)) {\n                stream.backUp(1);            // \"2e\" - syntax error\n              }\n            }\n          }\n        }\n      }\n      return rval(state,stream,\"number\");   // normal integer\n    }\n\n    // open parens\n    if (nongreedy(stream,openParenRE,openParenWords)) {\n      return rval(state,stream,\"open_paren\");\n    }\n\n    // close parens\n    if (nongreedy(stream,closeParenRE,closeParenWords)) {\n      return rval(state,stream,\"close_paren\");\n    }\n\n    // separators\n    if (greedy(stream,separatorRE,separatorWords)) {\n      return rval(state,stream,\"separator\");\n    }\n\n    // operators\n    if (greedy(stream,operatorSymbolRE,operatorSymbolWords)) {\n      return rval(state,stream,\"operator\");\n    }\n\n    return rval(state,stream,null);\n  }\n\n/////////////////////////////////////////////////////////////////////////////\n// utilities\n  function nongreedy(stream,re,words) {\n    if (stream.current().length == 1 && re.test(stream.current())) {\n      stream.backUp(1);\n      while (re.test(stream.peek())) {\n        stream.next();\n        if (is_member(stream.current(),words)) {\n          return true;\n        }\n      }\n      stream.backUp(stream.current().length-1);\n    }\n    return false;\n  }\n\n  function greedy(stream,re,words) {\n    if (stream.current().length == 1 && re.test(stream.current())) {\n      while (re.test(stream.peek())) {\n        stream.next();\n      }\n      while (0 < stream.current().length) {\n        if (is_member(stream.current(),words)) {\n          return true;\n        }else{\n          stream.backUp(1);\n        }\n      }\n      stream.next();\n    }\n    return false;\n  }\n\n  function doubleQuote(stream) {\n    return quote(stream, '\"', '\\\\');\n  }\n\n  function singleQuote(stream) {\n    return quote(stream,'\\'','\\\\');\n  }\n\n  function quote(stream,quoteChar,escapeChar) {\n    while (!stream.eol()) {\n      var ch = stream.next();\n      if (ch == quoteChar) {\n        return true;\n      }else if (ch == escapeChar) {\n        stream.next();\n      }\n    }\n    return false;\n  }\n\n  function lookahead(stream) {\n    var m = stream.match(/([\\n\\s]+|%[^\\n]*\\n)*(.)/,false);\n    return m ? m.pop() : \"\";\n  }\n\n  function is_member(element,list) {\n    return (-1 < list.indexOf(element));\n  }\n\n  function rval(state,stream,type) {\n\n    // parse stack\n    pushToken(state,realToken(type,stream));\n\n    // map erlang token type to CodeMirror style class\n    //     erlang             -> CodeMirror tag\n    switch (type) {\n      case \"atom\":        return \"atom\";\n      case \"attribute\":   return \"attribute\";\n      case \"boolean\":     return \"atom\";\n      case \"builtin\":     return \"builtin\";\n      case \"close_paren\": return null;\n      case \"colon\":       return null;\n      case \"comment\":     return \"comment\";\n      case \"dot\":         return null;\n      case \"error\":       return \"error\";\n      case \"fun\":         return \"meta\";\n      case \"function\":    return \"tag\";\n      case \"guard\":       return \"property\";\n      case \"keyword\":     return \"keyword\";\n      case \"macro\":       return \"variable-2\";\n      case \"number\":      return \"number\";\n      case \"open_paren\":  return null;\n      case \"operator\":    return \"operator\";\n      case \"record\":      return \"bracket\";\n      case \"separator\":   return null;\n      case \"string\":      return \"string\";\n      case \"type\":        return \"def\";\n      case \"variable\":    return \"variable\";\n      default:            return null;\n    }\n  }\n\n  function aToken(tok,col,ind,typ) {\n    return {token:  tok,\n            column: col,\n            indent: ind,\n            type:   typ};\n  }\n\n  function realToken(type,stream) {\n    return aToken(stream.current(),\n                 stream.column(),\n                 stream.indentation(),\n                 type);\n  }\n\n  function fakeToken(type) {\n    return aToken(type,0,0,type);\n  }\n\n  function peekToken(state,depth) {\n    var len = state.tokenStack.length;\n    var dep = (depth ? depth : 1);\n\n    if (len < dep) {\n      return false;\n    }else{\n      return state.tokenStack[len-dep];\n    }\n  }\n\n  function pushToken(state,token) {\n\n    if (!(token.type == \"comment\" || token.type == \"whitespace\")) {\n      state.tokenStack = maybe_drop_pre(state.tokenStack,token);\n      state.tokenStack = maybe_drop_post(state.tokenStack);\n    }\n  }\n\n  function maybe_drop_pre(s,token) {\n    var last = s.length-1;\n\n    if (0 < last && s[last].type === \"record\" && token.type === \"dot\") {\n      s.pop();\n    }else if (0 < last && s[last].type === \"group\") {\n      s.pop();\n      s.push(token);\n    }else{\n      s.push(token);\n    }\n    return s;\n  }\n\n  function maybe_drop_post(s) {\n    if (!s.length) return s\n    var last = s.length-1;\n\n    if (s[last].type === \"dot\") {\n      return [];\n    }\n    if (last > 1 && s[last].type === \"fun\" && s[last-1].token === \"fun\") {\n      return s.slice(0,last-1);\n    }\n    switch (s[last].token) {\n      case \"}\":    return d(s,{g:[\"{\"]});\n      case \"]\":    return d(s,{i:[\"[\"]});\n      case \")\":    return d(s,{i:[\"(\"]});\n      case \">>\":   return d(s,{i:[\"<<\"]});\n      case \"end\":  return d(s,{i:[\"begin\",\"case\",\"fun\",\"if\",\"receive\",\"try\"]});\n      case \",\":    return d(s,{e:[\"begin\",\"try\",\"when\",\"->\",\n                                  \",\",\"(\",\"[\",\"{\",\"<<\"]});\n      case \"->\":   return d(s,{r:[\"when\"],\n                               m:[\"try\",\"if\",\"case\",\"receive\"]});\n      case \";\":    return d(s,{E:[\"case\",\"fun\",\"if\",\"receive\",\"try\",\"when\"]});\n      case \"catch\":return d(s,{e:[\"try\"]});\n      case \"of\":   return d(s,{e:[\"case\"]});\n      case \"after\":return d(s,{e:[\"receive\",\"try\"]});\n      default:     return s;\n    }\n  }\n\n  function d(stack,tt) {\n    // stack is a stack of Token objects.\n    // tt is an object; {type:tokens}\n    // type is a char, tokens is a list of token strings.\n    // The function returns (possibly truncated) stack.\n    // It will descend the stack, looking for a Token such that Token.token\n    //  is a member of tokens. If it does not find that, it will normally (but\n    //  see \"E\" below) return stack. If it does find a match, it will remove\n    //  all the Tokens between the top and the matched Token.\n    // If type is \"m\", that is all it does.\n    // If type is \"i\", it will also remove the matched Token and the top Token.\n    // If type is \"g\", like \"i\", but add a fake \"group\" token at the top.\n    // If type is \"r\", it will remove the matched Token, but not the top Token.\n    // If type is \"e\", it will keep the matched Token but not the top Token.\n    // If type is \"E\", it behaves as for type \"e\", except if there is no match,\n    //  in which case it will return an empty stack.\n\n    for (var type in tt) {\n      var len = stack.length-1;\n      var tokens = tt[type];\n      for (var i = len-1; -1 < i ; i--) {\n        if (is_member(stack[i].token,tokens)) {\n          var ss = stack.slice(0,i);\n          switch (type) {\n              case \"m\": return ss.concat(stack[i]).concat(stack[len]);\n              case \"r\": return ss.concat(stack[len]);\n              case \"i\": return ss;\n              case \"g\": return ss.concat(fakeToken(\"group\"));\n              case \"E\": return ss.concat(stack[i]);\n              case \"e\": return ss.concat(stack[i]);\n          }\n        }\n      }\n    }\n    return (type == \"E\" ? [] : stack);\n  }\n\n/////////////////////////////////////////////////////////////////////////////\n// indenter\n\n  function indenter(state,textAfter) {\n    var t;\n    var unit = cmCfg.indentUnit;\n    var wordAfter = wordafter(textAfter);\n    var currT = peekToken(state,1);\n    var prevT = peekToken(state,2);\n\n    if (state.in_string || state.in_atom) {\n      return CodeMirror.Pass;\n    }else if (!prevT) {\n      return 0;\n    }else if (currT.token == \"when\") {\n      return currT.column+unit;\n    }else if (wordAfter === \"when\" && prevT.type === \"function\") {\n      return prevT.indent+unit;\n    }else if (wordAfter === \"(\" && currT.token === \"fun\") {\n      return  currT.column+3;\n    }else if (wordAfter === \"catch\" && (t = getToken(state,[\"try\"]))) {\n      return t.column;\n    }else if (is_member(wordAfter,[\"end\",\"after\",\"of\"])) {\n      t = getToken(state,[\"begin\",\"case\",\"fun\",\"if\",\"receive\",\"try\"]);\n      return t ? t.column : CodeMirror.Pass;\n    }else if (is_member(wordAfter,closeParenWords)) {\n      t = getToken(state,openParenWords);\n      return t ? t.column : CodeMirror.Pass;\n    }else if (is_member(currT.token,[\",\",\"|\",\"||\"]) ||\n              is_member(wordAfter,[\",\",\"|\",\"||\"])) {\n      t = postcommaToken(state);\n      return t ? t.column+t.token.length : unit;\n    }else if (currT.token == \"->\") {\n      if (is_member(prevT.token, [\"receive\",\"case\",\"if\",\"try\"])) {\n        return prevT.column+unit+unit;\n      }else{\n        return prevT.column+unit;\n      }\n    }else if (is_member(currT.token,openParenWords)) {\n      return currT.column+currT.token.length;\n    }else{\n      t = defaultToken(state);\n      return truthy(t) ? t.column+unit : 0;\n    }\n  }\n\n  function wordafter(str) {\n    var m = str.match(/,|[a-z]+|\\}|\\]|\\)|>>|\\|+|\\(/);\n\n    return truthy(m) && (m.index === 0) ? m[0] : \"\";\n  }\n\n  function postcommaToken(state) {\n    var objs = state.tokenStack.slice(0,-1);\n    var i = getTokenIndex(objs,\"type\",[\"open_paren\"]);\n\n    return truthy(objs[i]) ? objs[i] : false;\n  }\n\n  function defaultToken(state) {\n    var objs = state.tokenStack;\n    var stop = getTokenIndex(objs,\"type\",[\"open_paren\",\"separator\",\"keyword\"]);\n    var oper = getTokenIndex(objs,\"type\",[\"operator\"]);\n\n    if (truthy(stop) && truthy(oper) && stop < oper) {\n      return objs[stop+1];\n    } else if (truthy(stop)) {\n      return objs[stop];\n    } else {\n      return false;\n    }\n  }\n\n  function getToken(state,tokens) {\n    var objs = state.tokenStack;\n    var i = getTokenIndex(objs,\"token\",tokens);\n\n    return truthy(objs[i]) ? objs[i] : false;\n  }\n\n  function getTokenIndex(objs,propname,propvals) {\n\n    for (var i = objs.length-1; -1 < i ; i--) {\n      if (is_member(objs[i][propname],propvals)) {\n        return i;\n      }\n    }\n    return false;\n  }\n\n  function truthy(x) {\n    return (x !== false) && (x != null);\n  }\n\n/////////////////////////////////////////////////////////////////////////////\n// this object defines the mode\n\n  return {\n    startState:\n      function() {\n        return {tokenStack: [],\n                in_string:  false,\n                in_atom:    false};\n      },\n\n    token:\n      function(stream, state) {\n        return tokenizer(stream, state);\n      },\n\n    indent:\n      function(state, textAfter) {\n        return indenter(state,textAfter);\n      },\n\n    lineComment: \"%\"\n  };\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/erlang/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Erlang mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/erlang-dark.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"erlang.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Erlang</a>\n  </ul>\n</div>\n\n<article>\n<h2>Erlang mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n%% -*- mode: erlang; erlang-indent-level: 2 -*-\n%%% Created :  7 May 2012 by mats cronqvist <masse@klarna.com>\n\n%% @doc\n%% Demonstrates how to print a record.\n%% @end\n\n-module('ex').\n-author('mats cronqvist').\n-export([demo/0,\n         rec_info/1]).\n\n-record(demo,{a=\"One\",b=\"Two\",c=\"Three\",d=\"Four\"}).\n\nrec_info(demo) -> record_info(fields,demo).\n\ndemo() -> expand_recs(?MODULE,#demo{a=\"A\",b=\"BB\"}).\n\nexpand_recs(M,List) when is_list(List) ->\n  [expand_recs(M,L)||L<-List];\nexpand_recs(M,Tup) when is_tuple(Tup) ->\n  case tuple_size(Tup) of\n    L when L < 1 -> Tup;\n    L ->\n      try\n        Fields = M:rec_info(element(1,Tup)),\n        L = length(Fields)+1,\n        lists:zip(Fields,expand_recs(M,tl(tuple_to_list(Tup))))\n      catch\n        _:_ -> list_to_tuple(expand_recs(M,tuple_to_list(Tup)))\n      end\n  end;\nexpand_recs(_,Term) ->\n  Term.\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        extraKeys: {\"Tab\":  \"indentAuto\"},\n        theme: \"erlang-dark\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-erlang</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/factor/factor.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Factor syntax highlight - simple mode\n//\n// by Dimage Sapelkin (https://github.com/kerabromsmu)\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../../addon/mode/simple\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../../addon/mode/simple\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineSimpleMode(\"factor\", {\n    // The start state contains the rules that are intially used\n    start: [\n      // comments\n      {regex: /#?!.*/, token: \"comment\"},\n      // strings \"\"\", multiline --> state\n      {regex: /\"\"\"/, token: \"string\", next: \"string3\"},\n      {regex: /(STRING:)(\\s)/, token: [\"keyword\", null], next: \"string2\"},\n      {regex: /\\S*?\"/, token: \"string\", next: \"string\"},\n      // numbers: dec, hex, unicode, bin, fractional, complex\n      {regex: /(?:0x[\\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\\-?\\d+.?\\d*)(?=\\s)/, token: \"number\"},\n      //{regex: /[+-]?/} //fractional\n      // definition: defining word, defined word, etc\n      {regex: /((?:GENERIC)|\\:?\\:)(\\s+)(\\S+)(\\s+)(\\()/, token: [\"keyword\", null, \"def\", null, \"bracket\"], next: \"stack\"},\n      // method definition: defining word, type, defined word, etc\n      {regex: /(M\\:)(\\s+)(\\S+)(\\s+)(\\S+)/, token: [\"keyword\", null, \"def\", null, \"tag\"]},\n      // vocabulary using --> state\n      {regex: /USING\\:/, token: \"keyword\", next: \"vocabulary\"},\n      // vocabulary definition/use\n      {regex: /(USE\\:|IN\\:)(\\s+)(\\S+)(?=\\s|$)/, token: [\"keyword\", null, \"tag\"]},\n      // definition: a defining word, defined word\n      {regex: /(\\S+\\:)(\\s+)(\\S+)(?=\\s|$)/, token: [\"keyword\", null, \"def\"]},\n      // \"keywords\", incl. ; t f . [ ] { } defining words\n      {regex: /(?:;|\\\\|t|f|if|loop|while|until|do|PRIVATE>|<PRIVATE|\\.|\\S*\\[|\\]|\\S*\\{|\\})(?=\\s|$)/, token: \"keyword\"},\n      // <constructors> and the like\n      {regex: /\\S+[\\)>\\.\\*\\?]+(?=\\s|$)/, token: \"builtin\"},\n      {regex: /[\\)><]+\\S+(?=\\s|$)/, token: \"builtin\"},\n      // operators\n      {regex: /(?:[\\+\\-\\=\\/\\*<>])(?=\\s|$)/, token: \"keyword\"},\n      // any id (?)\n      {regex: /\\S+/, token: \"variable\"},\n      {regex: /\\s+|./, token: null}\n    ],\n    vocabulary: [\n      {regex: /;/, token: \"keyword\", next: \"start\"},\n      {regex: /\\S+/, token: \"tag\"},\n      {regex: /\\s+|./, token: null}\n    ],\n    string: [\n      {regex: /(?:[^\\\\]|\\\\.)*?\"/, token: \"string\", next: \"start\"},\n      {regex: /.*/, token: \"string\"}\n    ],\n    string2: [\n      {regex: /^;/, token: \"keyword\", next: \"start\"},\n      {regex: /.*/, token: \"string\"}\n    ],\n    string3: [\n      {regex: /(?:[^\\\\]|\\\\.)*?\"\"\"/, token: \"string\", next: \"start\"},\n      {regex: /.*/, token: \"string\"}\n    ],\n    stack: [\n      {regex: /\\)/, token: \"bracket\", next: \"start\"},\n      {regex: /--/, token: \"bracket\"},\n      {regex: /\\S+/, token: \"meta\"},\n      {regex: /\\s+|./, token: null}\n    ],\n    // The meta property contains global information about the mode. It\n    // can contain properties like lineComment, which are supported by\n    // all modes, and also directives like dontIndentStates, which are\n    // specific to simple modes.\n    meta: {\n      dontIndentStates: [\"start\", \"vocabulary\", \"string\", \"string3\", \"stack\"],\n      lineComment: [ \"!\", \"#!\" ]\n    }\n  });\n\n  CodeMirror.defineMIME(\"text/x-factor\", \"factor\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/factor/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Factor mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link href='http://fonts.googleapis.com/css?family=Droid+Sans+Mono' rel='stylesheet' type='text/css'>\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/simple.js\"></script>\n<script src=\"factor.js\"></script>\n<style>\n.CodeMirror {\n    font-family: 'Droid Sans Mono', monospace;\n    font-size: 14px;\n}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Factor</a>\n  </ul>\n</div>\n\n<article>\n\n<h2>Factor mode</h2>\n\n<form><textarea id=\"code\" name=\"code\">\n! Copyright (C) 2008 Slava Pestov.\n! See http://factorcode.org/license.txt for BSD license.\n\n! A simple time server\n\nUSING: accessors calendar calendar.format io io.encodings.ascii\nio.servers kernel threads ;\nIN: time-server\n\n: handle-time-client ( -- )\n    now timestamp>rfc822 print ;\n\n: <time-server> ( -- threaded-server )\n    ascii <threaded-server>\n        \"time-server\" >>name\n        1234 >>insecure\n        [ handle-time-client ] >>handler ;\n\n: start-time-server ( -- )\n    <time-server> start-server drop ;\n\nMAIN: start-time-server\n</textarea>\n  </form>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    lineWrapping: true,\n    indentUnit: 2,\n    tabSize: 2,\n    autofocus: true,\n    mode: \"text/x-factor\"\n  });\n</script>\n<p/>\n<p>Simple mode that handles Factor Syntax (<a href=\"http://en.wikipedia.org/wiki/Factor_(programming_language)\">Factor on WikiPedia</a>).</p>\n\n<p><strong>MIME types defined:</strong> <code>text/x-factor</code>.</p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/fcl/fcl.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"fcl\", function(config) {\n  var indentUnit = config.indentUnit;\n\n  var keywords = {\n      \"term\": true,\n      \"method\": true, \"accu\": true,\n      \"rule\": true, \"then\": true, \"is\": true, \"and\": true, \"or\": true,\n      \"if\": true, \"default\": true\n  };\n\n  var start_blocks = {\n      \"var_input\": true,\n      \"var_output\": true,\n      \"fuzzify\": true,\n      \"defuzzify\": true,\n      \"function_block\": true,\n      \"ruleblock\": true\n  };\n\n  var end_blocks = {\n      \"end_ruleblock\": true,\n      \"end_defuzzify\": true,\n      \"end_function_block\": true,\n      \"end_fuzzify\": true,\n      \"end_var\": true\n  };\n\n  var atoms = {\n      \"true\": true, \"false\": true, \"nan\": true,\n      \"real\": true, \"min\": true, \"max\": true, \"cog\": true, \"cogs\": true\n  };\n\n  var isOperatorChar = /[+\\-*&^%:=<>!|\\/]/;\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n\n    if (/[\\d\\.]/.test(ch)) {\n      if (ch == \".\") {\n        stream.match(/^[0-9]+([eE][\\-+]?[0-9]+)?/);\n      } else if (ch == \"0\") {\n        stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);\n      } else {\n        stream.match(/^[0-9]*\\.?[0-9]*([eE][\\-+]?[0-9]+)?/);\n      }\n      return \"number\";\n    }\n\n    if (ch == \"/\" || ch == \"(\") {\n      if (stream.eat(\"*\")) {\n        state.tokenize = tokenComment;\n        return tokenComment(stream, state);\n      }\n      if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n    }\n    if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return \"operator\";\n    }\n    stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n\n    var cur = stream.current().toLowerCase();\n    if (keywords.propertyIsEnumerable(cur) ||\n        start_blocks.propertyIsEnumerable(cur) ||\n        end_blocks.propertyIsEnumerable(cur)) {\n      return \"keyword\";\n    }\n    if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n    return \"variable\";\n  }\n\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if ((ch == \"/\" || ch == \")\") && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function Context(indented, column, type, align, prev) {\n    this.indented = indented;\n    this.column = column;\n    this.type = type;\n    this.align = align;\n    this.prev = prev;\n  }\n\n  function pushContext(state, col, type) {\n    return state.context = new Context(state.indented, col, type, null, state.context);\n  }\n\n  function popContext(state) {\n    if (!state.context.prev) return;\n    var t = state.context.type;\n    if (t == \"end_block\")\n      state.indented = state.context.indented;\n    return state.context = state.context.prev;\n  }\n\n  // Interface\n\n  return {\n    startState: function(basecolumn) {\n      return {\n        tokenize: null,\n        context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", false),\n        indented: 0,\n        startOfLine: true\n      };\n    },\n\n    token: function(stream, state) {\n        var ctx = state.context;\n        if (stream.sol()) {\n            if (ctx.align == null) ctx.align = false;\n            state.indented = stream.indentation();\n            state.startOfLine = true;\n        }\n        if (stream.eatSpace()) return null;\n\n        var style = (state.tokenize || tokenBase)(stream, state);\n        if (style == \"comment\") return style;\n        if (ctx.align == null) ctx.align = true;\n\n        var cur = stream.current().toLowerCase();\n\n        if (start_blocks.propertyIsEnumerable(cur)) pushContext(state, stream.column(), \"end_block\");\n        else if (end_blocks.propertyIsEnumerable(cur))  popContext(state);\n\n        state.startOfLine = false;\n        return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize != tokenBase && state.tokenize != null) return 0;\n      var ctx = state.context;\n\n      var closing = end_blocks.propertyIsEnumerable(textAfter);\n      if (ctx.align) return ctx.column + (closing ? 0 : 1);\n      else return ctx.indented + (closing ? 0 : indentUnit);\n    },\n\n    electricChars: \"ryk\",\n    fold: \"brace\",\n    blockCommentStart: \"(*\",\n    blockCommentEnd: \"*)\",\n    lineComment: \"//\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-fcl\", \"fcl\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/fcl/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: FCL mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/elegant.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"fcl.js\"></script>\n<style>.CodeMirror {border:1px solid #999; background:#ffc}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">FCL</a>\n  </ul>\n</div>\n\n<article>\n<h2>FCL mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n  FUNCTION_BLOCK Fuzzy_FB\n      VAR_INPUT\n          TimeDay : REAL; (* RANGE(0 .. 23) *)\n          ApplicateHost: REAL;\n          TimeConfiguration: REAL;\n          TimeRequirements: REAL;\n      END_VAR\n\n      VAR_OUTPUT\n          ProbabilityDistribution: REAL;\n          ProbabilityAccess: REAL;\n      END_VAR\n\n      FUZZIFY TimeDay\n          TERM inside := (0, 0) (8, 1) (22,0);\n          TERM outside := (0, 1) (8, 0) (22, 1);\n      END_FUZZIFY\n\n      FUZZIFY ApplicateHost\n          TERM few := (0, 1) (100, 0) (200, 0);\n          TERM many := (0, 0) (100, 0) (200, 1);\n      END_FUZZIFY\n\n      FUZZIFY TimeConfiguration\n          TERM recently := (0, 1) (30, 1) (120, 0);\n          TERM long := (0, 0) (30, 0) (120, 1);\n      END_FUZZIFY\n\n      FUZZIFY TimeRequirements\n          TERM recently := (0, 1) (30, 1) (365, 0);\n          TERM long := (0, 0) (30, 0) (365, 1);\n      END_FUZZIFY\n\n      DEFUZZIFY ProbabilityAccess\n          TERM hight := 1;\n          TERM medium := 0.5;\n          TERM low := 0;\n          ACCU: MAX;\n          METHOD: COGS;\n          DEFAULT := 0;\n      END_DEFUZZIFY\n\n      DEFUZZIFY ProbabilityDistribution\n          TERM hight := 1;\n          TERM medium := 0.5;\n          TERM low := 0;\n          ACCU: MAX;\n          METHOD: COGS;\n          DEFAULT := 0;\n      END_DEFUZZIFY\n\n      RULEBLOCK No1\n          AND : MIN;\n          RULE 1 : IF TimeDay IS outside AND ApplicateHost IS few THEN ProbabilityAccess IS hight;\n          RULE 2 : IF ApplicateHost IS many THEN ProbabilityAccess IS hight;\n          RULE 3 : IF TimeDay IS inside AND ApplicateHost IS few THEN ProbabilityAccess IS low;\n      END_RULEBLOCK\n\n      RULEBLOCK No2\n          AND : MIN;\n          RULE 1 : IF ApplicateHost IS many THEN ProbabilityDistribution IS hight;\n      END_RULEBLOCK\n\n  END_FUNCTION_BLOCK\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        theme: \"elegant\",\n        matchBrackets: true,\n        indentUnit: 8,\n        tabSize: 8,\n        indentWithTabs: true,\n        mode: \"text/x-fcl\"\n      });\n    </script>\n\n    <p><strong>MIME type:</strong> <code>text/x-fcl</code></p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/forth/forth.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Author: Aliaksei Chapyzhenka\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function toWordList(words) {\n    var ret = [];\n    words.split(' ').forEach(function(e){\n      ret.push({name: e});\n    });\n    return ret;\n  }\n\n  var coreWordList = toWordList(\n'INVERT AND OR XOR\\\n 2* 2/ LSHIFT RSHIFT\\\n 0= = 0< < > U< MIN MAX\\\n 2DROP 2DUP 2OVER 2SWAP ?DUP DEPTH DROP DUP OVER ROT SWAP\\\n >R R> R@\\\n + - 1+ 1- ABS NEGATE\\\n S>D * M* UM*\\\n FM/MOD SM/REM UM/MOD */ */MOD / /MOD MOD\\\n HERE , @ ! CELL+ CELLS C, C@ C! CHARS 2@ 2!\\\n ALIGN ALIGNED +! ALLOT\\\n CHAR [CHAR] [ ] BL\\\n FIND EXECUTE IMMEDIATE COUNT LITERAL STATE\\\n ; DOES> >BODY\\\n EVALUATE\\\n SOURCE >IN\\\n <# # #S #> HOLD SIGN BASE >NUMBER HEX DECIMAL\\\n FILL MOVE\\\n . CR EMIT SPACE SPACES TYPE U. .R U.R\\\n ACCEPT\\\n TRUE FALSE\\\n <> U> 0<> 0>\\\n NIP TUCK ROLL PICK\\\n 2>R 2R@ 2R>\\\n WITHIN UNUSED MARKER\\\n I J\\\n TO\\\n COMPILE, [COMPILE]\\\n SAVE-INPUT RESTORE-INPUT\\\n PAD ERASE\\\n 2LITERAL DNEGATE\\\n D- D+ D0< D0= D2* D2/ D< D= DMAX DMIN D>S DABS\\\n M+ M*/ D. D.R 2ROT DU<\\\n CATCH THROW\\\n FREE RESIZE ALLOCATE\\\n CS-PICK CS-ROLL\\\n GET-CURRENT SET-CURRENT FORTH-WORDLIST GET-ORDER SET-ORDER\\\n PREVIOUS SEARCH-WORDLIST WORDLIST FIND ALSO ONLY FORTH DEFINITIONS ORDER\\\n -TRAILING /STRING SEARCH COMPARE CMOVE CMOVE> BLANK SLITERAL');\n\n  var immediateWordList = toWordList('IF ELSE THEN BEGIN WHILE REPEAT UNTIL RECURSE [IF] [ELSE] [THEN] ?DO DO LOOP +LOOP UNLOOP LEAVE EXIT AGAIN CASE OF ENDOF ENDCASE');\n\n  CodeMirror.defineMode('forth', function() {\n    function searchWordList (wordList, word) {\n      var i;\n      for (i = wordList.length - 1; i >= 0; i--) {\n        if (wordList[i].name === word.toUpperCase()) {\n          return wordList[i];\n        }\n      }\n      return undefined;\n    }\n  return {\n    startState: function() {\n      return {\n        state: '',\n        base: 10,\n        coreWordList: coreWordList,\n        immediateWordList: immediateWordList,\n        wordList: []\n      };\n    },\n    token: function (stream, stt) {\n      var mat;\n      if (stream.eatSpace()) {\n        return null;\n      }\n      if (stt.state === '') { // interpretation\n        if (stream.match(/^(\\]|:NONAME)(\\s|$)/i)) {\n          stt.state = ' compilation';\n          return 'builtin compilation';\n        }\n        mat = stream.match(/^(\\:)\\s+(\\S+)(\\s|$)+/);\n        if (mat) {\n          stt.wordList.push({name: mat[2].toUpperCase()});\n          stt.state = ' compilation';\n          return 'def' + stt.state;\n        }\n        mat = stream.match(/^(VARIABLE|2VARIABLE|CONSTANT|2CONSTANT|CREATE|POSTPONE|VALUE|WORD)\\s+(\\S+)(\\s|$)+/i);\n        if (mat) {\n          stt.wordList.push({name: mat[2].toUpperCase()});\n          return 'def' + stt.state;\n        }\n        mat = stream.match(/^(\\'|\\[\\'\\])\\s+(\\S+)(\\s|$)+/);\n        if (mat) {\n          return 'builtin' + stt.state;\n        }\n        } else { // compilation\n        // ; [\n        if (stream.match(/^(\\;|\\[)(\\s)/)) {\n          stt.state = '';\n          stream.backUp(1);\n          return 'builtin compilation';\n        }\n        if (stream.match(/^(\\;|\\[)($)/)) {\n          stt.state = '';\n          return 'builtin compilation';\n        }\n        if (stream.match(/^(POSTPONE)\\s+\\S+(\\s|$)+/)) {\n          return 'builtin';\n        }\n      }\n\n      // dynamic wordlist\n      mat = stream.match(/^(\\S+)(\\s+|$)/);\n      if (mat) {\n        if (searchWordList(stt.wordList, mat[1]) !== undefined) {\n          return 'variable' + stt.state;\n        }\n\n        // comments\n        if (mat[1] === '\\\\') {\n          stream.skipToEnd();\n            return 'comment' + stt.state;\n          }\n\n          // core words\n          if (searchWordList(stt.coreWordList, mat[1]) !== undefined) {\n            return 'builtin' + stt.state;\n          }\n          if (searchWordList(stt.immediateWordList, mat[1]) !== undefined) {\n            return 'keyword' + stt.state;\n          }\n\n          if (mat[1] === '(') {\n            stream.eatWhile(function (s) { return s !== ')'; });\n            stream.eat(')');\n            return 'comment' + stt.state;\n          }\n\n          // // strings\n          if (mat[1] === '.(') {\n            stream.eatWhile(function (s) { return s !== ')'; });\n            stream.eat(')');\n            return 'string' + stt.state;\n          }\n          if (mat[1] === 'S\"' || mat[1] === '.\"' || mat[1] === 'C\"') {\n            stream.eatWhile(function (s) { return s !== '\"'; });\n            stream.eat('\"');\n            return 'string' + stt.state;\n          }\n\n          // numbers\n          if (mat[1] - 0xfffffffff) {\n            return 'number' + stt.state;\n          }\n          // if (mat[1].match(/^[-+]?[0-9]+\\.[0-9]*/)) {\n          //     return 'number' + stt.state;\n          // }\n\n          return 'atom' + stt.state;\n        }\n      }\n    };\n  });\n  CodeMirror.defineMIME(\"text/x-forth\", \"forth\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/forth/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Forth mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link href='http://fonts.googleapis.com/css?family=Droid+Sans+Mono' rel='stylesheet' type='text/css'>\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=stylesheet href=\"../../theme/colorforth.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"forth.js\"></script>\n<style>\n.CodeMirror {\n    font-family: 'Droid Sans Mono', monospace;\n    font-size: 14px;\n}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Forth</a>\n  </ul>\n</div>\n\n<article>\n\n<h2>Forth mode</h2>\n\n<form><textarea id=\"code\" name=\"code\">\n\\ Insertion sort\n\n: cell-  1 cells - ;\n\n: insert ( start end -- start )\n  dup @ >r ( r: v )\n  begin\n    2dup <\n  while\n    r@ over cell- @ <\n  while\n    cell-\n    dup @ over cell+ !\n  repeat then\n  r> swap ! ;\n\n: sort ( array len -- )\n  1 ?do\n    dup i cells + insert\n  loop drop ;</textarea>\n  </form>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    lineWrapping: true,\n    indentUnit: 2,\n    tabSize: 2,\n    autofocus: true,\n    theme: \"colorforth\",\n    mode: \"text/x-forth\"\n  });\n</script>\n\n<p>Simple mode that handle Forth-Syntax (<a href=\"http://en.wikipedia.org/wiki/Forth_%28programming_language%29\">Forth on WikiPedia</a>).</p>\n\n<p><strong>MIME types defined:</strong> <code>text/x-forth</code>.</p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/fortran/fortran.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"fortran\", function() {\n  function words(array) {\n    var keys = {};\n    for (var i = 0; i < array.length; ++i) {\n      keys[array[i]] = true;\n    }\n    return keys;\n  }\n\n  var keywords = words([\n                  \"abstract\", \"accept\", \"allocatable\", \"allocate\",\n                  \"array\", \"assign\", \"asynchronous\", \"backspace\",\n                  \"bind\", \"block\", \"byte\", \"call\", \"case\",\n                  \"class\", \"close\", \"common\", \"contains\",\n                  \"continue\", \"cycle\", \"data\", \"deallocate\",\n                  \"decode\", \"deferred\", \"dimension\", \"do\",\n                  \"elemental\", \"else\", \"encode\", \"end\",\n                  \"endif\", \"entry\", \"enumerator\", \"equivalence\",\n                  \"exit\", \"external\", \"extrinsic\", \"final\",\n                  \"forall\", \"format\", \"function\", \"generic\",\n                  \"go\", \"goto\", \"if\", \"implicit\", \"import\", \"include\",\n                  \"inquire\", \"intent\", \"interface\", \"intrinsic\",\n                  \"module\", \"namelist\", \"non_intrinsic\",\n                  \"non_overridable\", \"none\", \"nopass\",\n                  \"nullify\", \"open\", \"optional\", \"options\",\n                  \"parameter\", \"pass\", \"pause\", \"pointer\",\n                  \"print\", \"private\", \"program\", \"protected\",\n                  \"public\", \"pure\", \"read\", \"recursive\", \"result\",\n                  \"return\", \"rewind\", \"save\", \"select\", \"sequence\",\n                  \"stop\", \"subroutine\", \"target\", \"then\", \"to\", \"type\",\n                  \"use\", \"value\", \"volatile\", \"where\", \"while\",\n                  \"write\"]);\n  var builtins = words([\"abort\", \"abs\", \"access\", \"achar\", \"acos\",\n                          \"adjustl\", \"adjustr\", \"aimag\", \"aint\", \"alarm\",\n                          \"all\", \"allocated\", \"alog\", \"amax\", \"amin\",\n                          \"amod\", \"and\", \"anint\", \"any\", \"asin\",\n                          \"associated\", \"atan\", \"besj\", \"besjn\", \"besy\",\n                          \"besyn\", \"bit_size\", \"btest\", \"cabs\", \"ccos\",\n                          \"ceiling\", \"cexp\", \"char\", \"chdir\", \"chmod\",\n                          \"clog\", \"cmplx\", \"command_argument_count\",\n                          \"complex\", \"conjg\", \"cos\", \"cosh\", \"count\",\n                          \"cpu_time\", \"cshift\", \"csin\", \"csqrt\", \"ctime\",\n                          \"c_funloc\", \"c_loc\", \"c_associated\", \"c_null_ptr\",\n                          \"c_null_funptr\", \"c_f_pointer\", \"c_null_char\",\n                          \"c_alert\", \"c_backspace\", \"c_form_feed\",\n                          \"c_new_line\", \"c_carriage_return\",\n                          \"c_horizontal_tab\", \"c_vertical_tab\", \"dabs\",\n                          \"dacos\", \"dasin\", \"datan\", \"date_and_time\",\n                          \"dbesj\", \"dbesj\", \"dbesjn\", \"dbesy\", \"dbesy\",\n                          \"dbesyn\", \"dble\", \"dcos\", \"dcosh\", \"ddim\", \"derf\",\n                          \"derfc\", \"dexp\", \"digits\", \"dim\", \"dint\", \"dlog\",\n                          \"dlog\", \"dmax\", \"dmin\", \"dmod\", \"dnint\",\n                          \"dot_product\", \"dprod\", \"dsign\", \"dsinh\",\n                          \"dsin\", \"dsqrt\", \"dtanh\", \"dtan\", \"dtime\",\n                          \"eoshift\", \"epsilon\", \"erf\", \"erfc\", \"etime\",\n                          \"exit\", \"exp\", \"exponent\", \"extends_type_of\",\n                          \"fdate\", \"fget\", \"fgetc\", \"float\", \"floor\",\n                          \"flush\", \"fnum\", \"fputc\", \"fput\", \"fraction\",\n                          \"fseek\", \"fstat\", \"ftell\", \"gerror\", \"getarg\",\n                          \"get_command\", \"get_command_argument\",\n                          \"get_environment_variable\", \"getcwd\",\n                          \"getenv\", \"getgid\", \"getlog\", \"getpid\",\n                          \"getuid\", \"gmtime\", \"hostnm\", \"huge\", \"iabs\",\n                          \"iachar\", \"iand\", \"iargc\", \"ibclr\", \"ibits\",\n                          \"ibset\", \"ichar\", \"idate\", \"idim\", \"idint\",\n                          \"idnint\", \"ieor\", \"ierrno\", \"ifix\", \"imag\",\n                          \"imagpart\", \"index\", \"int\", \"ior\", \"irand\",\n                          \"isatty\", \"ishft\", \"ishftc\", \"isign\",\n                          \"iso_c_binding\", \"is_iostat_end\", \"is_iostat_eor\",\n                          \"itime\", \"kill\", \"kind\", \"lbound\", \"len\", \"len_trim\",\n                          \"lge\", \"lgt\", \"link\", \"lle\", \"llt\", \"lnblnk\", \"loc\",\n                          \"log\", \"logical\", \"long\", \"lshift\", \"lstat\", \"ltime\",\n                          \"matmul\", \"max\", \"maxexponent\", \"maxloc\", \"maxval\",\n                          \"mclock\", \"merge\", \"move_alloc\", \"min\", \"minexponent\",\n                          \"minloc\", \"minval\", \"mod\", \"modulo\", \"mvbits\",\n                          \"nearest\", \"new_line\", \"nint\", \"not\", \"or\", \"pack\",\n                          \"perror\", \"precision\", \"present\", \"product\", \"radix\",\n                          \"rand\", \"random_number\", \"random_seed\", \"range\",\n                          \"real\", \"realpart\", \"rename\", \"repeat\", \"reshape\",\n                          \"rrspacing\", \"rshift\", \"same_type_as\", \"scale\",\n                          \"scan\", \"second\", \"selected_int_kind\",\n                          \"selected_real_kind\", \"set_exponent\", \"shape\",\n                          \"short\", \"sign\", \"signal\", \"sinh\", \"sin\", \"sleep\",\n                          \"sngl\", \"spacing\", \"spread\", \"sqrt\", \"srand\", \"stat\",\n                          \"sum\", \"symlnk\", \"system\", \"system_clock\", \"tan\",\n                          \"tanh\", \"time\", \"tiny\", \"transfer\", \"transpose\",\n                          \"trim\", \"ttynam\", \"ubound\", \"umask\", \"unlink\",\n                          \"unpack\", \"verify\", \"xor\", \"zabs\", \"zcos\", \"zexp\",\n                          \"zlog\", \"zsin\", \"zsqrt\"]);\n\n    var dataTypes =  words([\"c_bool\", \"c_char\", \"c_double\", \"c_double_complex\",\n                     \"c_float\", \"c_float_complex\", \"c_funptr\", \"c_int\",\n                     \"c_int16_t\", \"c_int32_t\", \"c_int64_t\", \"c_int8_t\",\n                     \"c_int_fast16_t\", \"c_int_fast32_t\", \"c_int_fast64_t\",\n                     \"c_int_fast8_t\", \"c_int_least16_t\", \"c_int_least32_t\",\n                     \"c_int_least64_t\", \"c_int_least8_t\", \"c_intmax_t\",\n                     \"c_intptr_t\", \"c_long\", \"c_long_double\",\n                     \"c_long_double_complex\", \"c_long_long\", \"c_ptr\",\n                     \"c_short\", \"c_signed_char\", \"c_size_t\", \"character\",\n                     \"complex\", \"double\", \"integer\", \"logical\", \"real\"]);\n  var isOperatorChar = /[+\\-*&=<>\\/\\:]/;\n  var litOperator = new RegExp(\"(\\.and\\.|\\.or\\.|\\.eq\\.|\\.lt\\.|\\.le\\.|\\.gt\\.|\\.ge\\.|\\.ne\\.|\\.not\\.|\\.eqv\\.|\\.neqv\\.)\", \"i\");\n\n  function tokenBase(stream, state) {\n\n    if (stream.match(litOperator)){\n        return 'operator';\n    }\n\n    var ch = stream.next();\n    if (ch == \"!\") {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n    if (ch == '\"' || ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n    if (/[\\[\\]\\(\\),]/.test(ch)) {\n      return null;\n    }\n    if (/\\d/.test(ch)) {\n      stream.eatWhile(/[\\w\\.]/);\n      return \"number\";\n    }\n    if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return \"operator\";\n    }\n    stream.eatWhile(/[\\w\\$_]/);\n    var word = stream.current().toLowerCase();\n\n    if (keywords.hasOwnProperty(word)){\n            return 'keyword';\n    }\n    if (builtins.hasOwnProperty(word) || dataTypes.hasOwnProperty(word)) {\n            return 'builtin';\n    }\n    return \"variable\";\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {\n            end = true;\n            break;\n        }\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end || !escaped) state.tokenize = null;\n      return \"string\";\n    };\n  }\n\n  // Interface\n\n  return {\n    startState: function() {\n      return {tokenize: null};\n    },\n\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      var style = (state.tokenize || tokenBase)(stream, state);\n      if (style == \"comment\" || style == \"meta\") return style;\n      return style;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-fortran\", \"fortran\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/fortran/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Fortran mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"fortran.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Fortran</a>\n  </ul>\n</div>\n\n<article>\n<h2>Fortran mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n! Example Fortran code\n  program average\n\n  ! Read in some numbers and take the average\n  ! As written, if there are no data points, an average of zero is returned\n  ! While this may not be desired behavior, it keeps this example simple\n\n  implicit none\n\n  real, dimension(:), allocatable :: points\n  integer                         :: number_of_points\n  real                            :: average_points=0., positive_average=0., negative_average=0.\n\n  write (*,*) \"Input number of points to average:\"\n  read  (*,*) number_of_points\n\n  allocate (points(number_of_points))\n\n  write (*,*) \"Enter the points to average:\"\n  read  (*,*) points\n\n  ! Take the average by summing points and dividing by number_of_points\n  if (number_of_points > 0) average_points = sum(points) / number_of_points\n\n  ! Now form average over positive and negative points only\n  if (count(points > 0.) > 0) then\n     positive_average = sum(points, points > 0.) / count(points > 0.)\n  end if\n\n  if (count(points < 0.) > 0) then\n     negative_average = sum(points, points < 0.) / count(points < 0.)\n  end if\n\n  deallocate (points)\n\n  ! Print result to terminal\n  write (*,'(a,g12.4)') 'Average = ', average_points\n  write (*,'(a,g12.4)') 'Average of positive points = ', positive_average\n  write (*,'(a,g12.4)') 'Average of negative points = ', negative_average\n\n  end program average\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"text/x-fortran\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-fortran</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/gas/gas.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"gas\", function(_config, parserConfig) {\n  'use strict';\n\n  // If an architecture is specified, its initialization function may\n  // populate this array with custom parsing functions which will be\n  // tried in the event that the standard functions do not find a match.\n  var custom = [];\n\n  // The symbol used to start a line comment changes based on the target\n  // architecture.\n  // If no architecture is pased in \"parserConfig\" then only multiline\n  // comments will have syntax support.\n  var lineCommentStartSymbol = \"\";\n\n  // These directives are architecture independent.\n  // Machine specific directives should go in their respective\n  // architecture initialization function.\n  // Reference:\n  // http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops\n  var directives = {\n    \".abort\" : \"builtin\",\n    \".align\" : \"builtin\",\n    \".altmacro\" : \"builtin\",\n    \".ascii\" : \"builtin\",\n    \".asciz\" : \"builtin\",\n    \".balign\" : \"builtin\",\n    \".balignw\" : \"builtin\",\n    \".balignl\" : \"builtin\",\n    \".bundle_align_mode\" : \"builtin\",\n    \".bundle_lock\" : \"builtin\",\n    \".bundle_unlock\" : \"builtin\",\n    \".byte\" : \"builtin\",\n    \".cfi_startproc\" : \"builtin\",\n    \".comm\" : \"builtin\",\n    \".data\" : \"builtin\",\n    \".def\" : \"builtin\",\n    \".desc\" : \"builtin\",\n    \".dim\" : \"builtin\",\n    \".double\" : \"builtin\",\n    \".eject\" : \"builtin\",\n    \".else\" : \"builtin\",\n    \".elseif\" : \"builtin\",\n    \".end\" : \"builtin\",\n    \".endef\" : \"builtin\",\n    \".endfunc\" : \"builtin\",\n    \".endif\" : \"builtin\",\n    \".equ\" : \"builtin\",\n    \".equiv\" : \"builtin\",\n    \".eqv\" : \"builtin\",\n    \".err\" : \"builtin\",\n    \".error\" : \"builtin\",\n    \".exitm\" : \"builtin\",\n    \".extern\" : \"builtin\",\n    \".fail\" : \"builtin\",\n    \".file\" : \"builtin\",\n    \".fill\" : \"builtin\",\n    \".float\" : \"builtin\",\n    \".func\" : \"builtin\",\n    \".global\" : \"builtin\",\n    \".gnu_attribute\" : \"builtin\",\n    \".hidden\" : \"builtin\",\n    \".hword\" : \"builtin\",\n    \".ident\" : \"builtin\",\n    \".if\" : \"builtin\",\n    \".incbin\" : \"builtin\",\n    \".include\" : \"builtin\",\n    \".int\" : \"builtin\",\n    \".internal\" : \"builtin\",\n    \".irp\" : \"builtin\",\n    \".irpc\" : \"builtin\",\n    \".lcomm\" : \"builtin\",\n    \".lflags\" : \"builtin\",\n    \".line\" : \"builtin\",\n    \".linkonce\" : \"builtin\",\n    \".list\" : \"builtin\",\n    \".ln\" : \"builtin\",\n    \".loc\" : \"builtin\",\n    \".loc_mark_labels\" : \"builtin\",\n    \".local\" : \"builtin\",\n    \".long\" : \"builtin\",\n    \".macro\" : \"builtin\",\n    \".mri\" : \"builtin\",\n    \".noaltmacro\" : \"builtin\",\n    \".nolist\" : \"builtin\",\n    \".octa\" : \"builtin\",\n    \".offset\" : \"builtin\",\n    \".org\" : \"builtin\",\n    \".p2align\" : \"builtin\",\n    \".popsection\" : \"builtin\",\n    \".previous\" : \"builtin\",\n    \".print\" : \"builtin\",\n    \".protected\" : \"builtin\",\n    \".psize\" : \"builtin\",\n    \".purgem\" : \"builtin\",\n    \".pushsection\" : \"builtin\",\n    \".quad\" : \"builtin\",\n    \".reloc\" : \"builtin\",\n    \".rept\" : \"builtin\",\n    \".sbttl\" : \"builtin\",\n    \".scl\" : \"builtin\",\n    \".section\" : \"builtin\",\n    \".set\" : \"builtin\",\n    \".short\" : \"builtin\",\n    \".single\" : \"builtin\",\n    \".size\" : \"builtin\",\n    \".skip\" : \"builtin\",\n    \".sleb128\" : \"builtin\",\n    \".space\" : \"builtin\",\n    \".stab\" : \"builtin\",\n    \".string\" : \"builtin\",\n    \".struct\" : \"builtin\",\n    \".subsection\" : \"builtin\",\n    \".symver\" : \"builtin\",\n    \".tag\" : \"builtin\",\n    \".text\" : \"builtin\",\n    \".title\" : \"builtin\",\n    \".type\" : \"builtin\",\n    \".uleb128\" : \"builtin\",\n    \".val\" : \"builtin\",\n    \".version\" : \"builtin\",\n    \".vtable_entry\" : \"builtin\",\n    \".vtable_inherit\" : \"builtin\",\n    \".warning\" : \"builtin\",\n    \".weak\" : \"builtin\",\n    \".weakref\" : \"builtin\",\n    \".word\" : \"builtin\"\n  };\n\n  var registers = {};\n\n  function x86(_parserConfig) {\n    lineCommentStartSymbol = \"#\";\n\n    registers.ax  = \"variable\";\n    registers.eax = \"variable-2\";\n    registers.rax = \"variable-3\";\n\n    registers.bx  = \"variable\";\n    registers.ebx = \"variable-2\";\n    registers.rbx = \"variable-3\";\n\n    registers.cx  = \"variable\";\n    registers.ecx = \"variable-2\";\n    registers.rcx = \"variable-3\";\n\n    registers.dx  = \"variable\";\n    registers.edx = \"variable-2\";\n    registers.rdx = \"variable-3\";\n\n    registers.si  = \"variable\";\n    registers.esi = \"variable-2\";\n    registers.rsi = \"variable-3\";\n\n    registers.di  = \"variable\";\n    registers.edi = \"variable-2\";\n    registers.rdi = \"variable-3\";\n\n    registers.sp  = \"variable\";\n    registers.esp = \"variable-2\";\n    registers.rsp = \"variable-3\";\n\n    registers.bp  = \"variable\";\n    registers.ebp = \"variable-2\";\n    registers.rbp = \"variable-3\";\n\n    registers.ip  = \"variable\";\n    registers.eip = \"variable-2\";\n    registers.rip = \"variable-3\";\n\n    registers.cs  = \"keyword\";\n    registers.ds  = \"keyword\";\n    registers.ss  = \"keyword\";\n    registers.es  = \"keyword\";\n    registers.fs  = \"keyword\";\n    registers.gs  = \"keyword\";\n  }\n\n  function armv6(_parserConfig) {\n    // Reference:\n    // http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf\n    // http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf\n    lineCommentStartSymbol = \"@\";\n    directives.syntax = \"builtin\";\n\n    registers.r0  = \"variable\";\n    registers.r1  = \"variable\";\n    registers.r2  = \"variable\";\n    registers.r3  = \"variable\";\n    registers.r4  = \"variable\";\n    registers.r5  = \"variable\";\n    registers.r6  = \"variable\";\n    registers.r7  = \"variable\";\n    registers.r8  = \"variable\";\n    registers.r9  = \"variable\";\n    registers.r10 = \"variable\";\n    registers.r11 = \"variable\";\n    registers.r12 = \"variable\";\n\n    registers.sp  = \"variable-2\";\n    registers.lr  = \"variable-2\";\n    registers.pc  = \"variable-2\";\n    registers.r13 = registers.sp;\n    registers.r14 = registers.lr;\n    registers.r15 = registers.pc;\n\n    custom.push(function(ch, stream) {\n      if (ch === '#') {\n        stream.eatWhile(/\\w/);\n        return \"number\";\n      }\n    });\n  }\n\n  var arch = (parserConfig.architecture || \"x86\").toLowerCase();\n  if (arch === \"x86\") {\n    x86(parserConfig);\n  } else if (arch === \"arm\" || arch === \"armv6\") {\n    armv6(parserConfig);\n  }\n\n  function nextUntilUnescaped(stream, end) {\n    var escaped = false, next;\n    while ((next = stream.next()) != null) {\n      if (next === end && !escaped) {\n        return false;\n      }\n      escaped = !escaped && next === \"\\\\\";\n    }\n    return escaped;\n  }\n\n  function clikeComment(stream, state) {\n    var maybeEnd = false, ch;\n    while ((ch = stream.next()) != null) {\n      if (ch === \"/\" && maybeEnd) {\n        state.tokenize = null;\n        break;\n      }\n      maybeEnd = (ch === \"*\");\n    }\n    return \"comment\";\n  }\n\n  return {\n    startState: function() {\n      return {\n        tokenize: null\n      };\n    },\n\n    token: function(stream, state) {\n      if (state.tokenize) {\n        return state.tokenize(stream, state);\n      }\n\n      if (stream.eatSpace()) {\n        return null;\n      }\n\n      var style, cur, ch = stream.next();\n\n      if (ch === \"/\") {\n        if (stream.eat(\"*\")) {\n          state.tokenize = clikeComment;\n          return clikeComment(stream, state);\n        }\n      }\n\n      if (ch === lineCommentStartSymbol) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n\n      if (ch === '\"') {\n        nextUntilUnescaped(stream, '\"');\n        return \"string\";\n      }\n\n      if (ch === '.') {\n        stream.eatWhile(/\\w/);\n        cur = stream.current().toLowerCase();\n        style = directives[cur];\n        return style || null;\n      }\n\n      if (ch === '=') {\n        stream.eatWhile(/\\w/);\n        return \"tag\";\n      }\n\n      if (ch === '{') {\n        return \"braket\";\n      }\n\n      if (ch === '}') {\n        return \"braket\";\n      }\n\n      if (/\\d/.test(ch)) {\n        if (ch === \"0\" && stream.eat(\"x\")) {\n          stream.eatWhile(/[0-9a-fA-F]/);\n          return \"number\";\n        }\n        stream.eatWhile(/\\d/);\n        return \"number\";\n      }\n\n      if (/\\w/.test(ch)) {\n        stream.eatWhile(/\\w/);\n        if (stream.eat(\":\")) {\n          return 'tag';\n        }\n        cur = stream.current().toLowerCase();\n        style = registers[cur];\n        return style || null;\n      }\n\n      for (var i = 0; i < custom.length; i++) {\n        style = custom[i](ch, stream, state);\n        if (style) {\n          return style;\n        }\n      }\n    },\n\n    lineComment: lineCommentStartSymbol,\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\"\n  };\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/gas/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Gas mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"gas.js\"></script>\n<style>.CodeMirror {border: 2px inset #dee;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Gas</a>\n  </ul>\n</div>\n\n<article>\n<h2>Gas mode</h2>\n<form>\n<textarea id=\"code\" name=\"code\">\n.syntax unified\n.global main\n\n/* \n *  A\n *  multi-line\n *  comment.\n */\n\n@ A single line comment.\n\nmain:\n        push    {sp, lr}\n        ldr     r0, =message\n        bl      puts\n        mov     r0, #0\n        pop     {sp, pc}\n\nmessage:\n        .asciz \"Hello world!<br />\"\n</textarea>\n        </form>\n\n        <script>\n            var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n                lineNumbers: true,\n                mode: {name: \"gas\", architecture: \"ARMv6\"},\n            });\n        </script>\n\n        <p>Handles AT&amp;T assembler syntax (more specifically this handles\n        the GNU Assembler (gas) syntax.)\n        It takes a single optional configuration parameter:\n        <code>architecture</code>, which can be one of <code>\"ARM\"</code>,\n        <code>\"ARMv6\"</code> or <code>\"x86\"</code>.\n        Including the parameter adds syntax for the registers and special\n        directives for the supplied architecture.\n\n        <p><strong>MIME types defined:</strong> <code>text/x-gas</code></p>\n    </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/gfm/gfm.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../markdown/markdown\"), require(\"../../addon/mode/overlay\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../markdown/markdown\", \"../../addon/mode/overlay\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nvar urlRE = /^((?:(?:aaas?|about|acap|adiumxtra|af[ps]|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|cap|chrome(?:-extension)?|cid|coap|com-eventbrite-attendee|content|crid|cvs|data|dav|dict|dlna-(?:playcontainer|playsingle)|dns|doi|dtn|dvb|ed2k|facetime|feed|file|finger|fish|ftp|geo|gg|git|gizmoproject|go|gopher|gtalk|h323|hcp|https?|iax|icap|icon|im|imap|info|ipn|ipp|irc[6s]?|iris(?:\\.beep|\\.lwz|\\.xpc|\\.xpcs)?|itms|jar|javascript|jms|keyparc|lastfm|ldaps?|magnet|mailto|maps|market|message|mid|mms|ms-help|msnim|msrps?|mtqp|mumble|mupdate|mvn|news|nfs|nih?|nntp|notes|oid|opaquelocktoken|palm|paparazzi|platform|pop|pres|proxy|psyc|query|res(?:ource)?|rmi|rsync|rtmp|rtsp|secondlife|service|session|sftp|sgn|shttp|sieve|sips?|skype|sm[bs]|snmp|soap\\.beeps?|soldat|spotify|ssh|steam|svn|tag|teamspeak|tel(?:net)?|tftp|things|thismessage|tip|tn3270|tv|udp|unreal|urn|ut2004|vemmi|ventrilo|view-source|webcal|wss?|wtai|wyciwyg|xcon(?:-userid)?|xfire|xmlrpc\\.beeps?|xmpp|xri|ymsgr|z39\\.50[rs]?):(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]|\\([^\\s()<>]*\\))+(?:\\([^\\s()<>]*\\)|[^\\s`*!()\\[\\]{};:'\".,<>?«»“”‘’]))/i\n\nCodeMirror.defineMode(\"gfm\", function(config, modeConfig) {\n  var codeDepth = 0;\n  function blankLine(state) {\n    state.code = false;\n    return null;\n  }\n  var gfmOverlay = {\n    startState: function() {\n      return {\n        code: false,\n        codeBlock: false,\n        ateSpace: false\n      };\n    },\n    copyState: function(s) {\n      return {\n        code: s.code,\n        codeBlock: s.codeBlock,\n        ateSpace: s.ateSpace\n      };\n    },\n    token: function(stream, state) {\n      state.combineTokens = null;\n\n      // Hack to prevent formatting override inside code blocks (block and inline)\n      if (state.codeBlock) {\n        if (stream.match(/^```+/)) {\n          state.codeBlock = false;\n          return null;\n        }\n        stream.skipToEnd();\n        return null;\n      }\n      if (stream.sol()) {\n        state.code = false;\n      }\n      if (stream.sol() && stream.match(/^```+/)) {\n        stream.skipToEnd();\n        state.codeBlock = true;\n        return null;\n      }\n      // If this block is changed, it may need to be updated in Markdown mode\n      if (stream.peek() === '`') {\n        stream.next();\n        var before = stream.pos;\n        stream.eatWhile('`');\n        var difference = 1 + stream.pos - before;\n        if (!state.code) {\n          codeDepth = difference;\n          state.code = true;\n        } else {\n          if (difference === codeDepth) { // Must be exact\n            state.code = false;\n          }\n        }\n        return null;\n      } else if (state.code) {\n        stream.next();\n        return null;\n      }\n      // Check if space. If so, links can be formatted later on\n      if (stream.eatSpace()) {\n        state.ateSpace = true;\n        return null;\n      }\n      if (stream.sol() || state.ateSpace) {\n        state.ateSpace = false;\n        if (modeConfig.gitHubSpice !== false) {\n          if(stream.match(/^(?:[a-zA-Z0-9\\-_]+\\/)?(?:[a-zA-Z0-9\\-_]+@)?(?=.{0,6}\\d)(?:[a-f0-9]{7,40}\\b)/)) {\n            // User/Project@SHA\n            // User@SHA\n            // SHA\n            state.combineTokens = true;\n            return \"link\";\n          } else if (stream.match(/^(?:[a-zA-Z0-9\\-_]+\\/)?(?:[a-zA-Z0-9\\-_]+)?#[0-9]+\\b/)) {\n            // User/Project#Num\n            // User#Num\n            // #Num\n            state.combineTokens = true;\n            return \"link\";\n          }\n        }\n      }\n      if (stream.match(urlRE) &&\n          stream.string.slice(stream.start - 2, stream.start) != \"](\" &&\n          (stream.start == 0 || /\\W/.test(stream.string.charAt(stream.start - 1)))) {\n        // URLs\n        // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls\n        // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine\n        // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL\n        state.combineTokens = true;\n        return \"link\";\n      }\n      stream.next();\n      return null;\n    },\n    blankLine: blankLine\n  };\n\n  var markdownConfig = {\n    taskLists: true,\n    strikethrough: true,\n    emoji: true\n  };\n  for (var attr in modeConfig) {\n    markdownConfig[attr] = modeConfig[attr];\n  }\n  markdownConfig.name = \"markdown\";\n  return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);\n\n}, \"markdown\");\n\n  CodeMirror.defineMIME(\"text/x-gfm\", \"gfm\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/gfm/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: GFM mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/overlay.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../markdown/markdown.js\"></script>\n<script src=\"gfm.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../css/css.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"../clike/clike.js\"></script>\n<script src=\"../meta.js\"></script>\n<style>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n  .cm-s-default .cm-emoji {color: #009688;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">GFM</a>\n  </ul>\n</div>\n\n<article>\n<h2>GFM mode</h2>\n<form><textarea id=\"code\" name=\"code\">\nGitHub Flavored Markdown\n========================\n\nEverything from markdown plus GFM features:\n\n## URL autolinking\n\nUnderscores_are_allowed_between_words.\n\n## Strikethrough text\n\nGFM adds syntax to strikethrough text, which is missing from standard Markdown.\n\n~~Mistaken text.~~\n~~**works with other formatting**~~\n\n~~spans across\nlines~~\n\n## Fenced code blocks (and syntax highlighting)\n\n```javascript\nfor (var i = 0; i &lt; items.length; i++) {\n    console.log(items[i], i); // log them\n}\n```\n\n## Task Lists\n\n- [ ] Incomplete task list item\n- [x] **Completed** task list item\n\n## A bit of GitHub spice\n\nSee http://github.github.com/github-flavored-markdown/.\n\n(Set `gitHubSpice: false` in mode options to disable):\n\n* SHA: be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2\n* User@SHA ref: mojombo@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2\n* User/Project@SHA: mojombo/god@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2\n* \\#Num: #1\n* User/#Num: mojombo#1\n* User/Project#Num: mojombo/god#1\n\n(Set `emoji: false` in mode options to disable):\n\n* emoji: :smile:\n\n\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {\n          name: \"gfm\",\n          tokenTypeOverrides: {\n            emoji: \"emoji\"\n          }\n        },\n        lineNumbers: true,\n        theme: \"default\"\n      });\n    </script>\n\n    <p>Optionally depends on other modes for properly highlighted code blocks.</p>\n\n    <p>Gfm mode supports these options (apart those from base Markdown mode):</p>\n    <ul>\n      <li>\n        <d1>\n          <dt><code>gitHubSpice: boolean</code></dt>\n          <dd>Hashes, issues... (default: <code>true</code>).</dd>\n        </d1>\n      </li>\n      <li>\n        <d1>\n          <dt><code>taskLists: boolean</code></dt>\n          <dd><code>- [ ]</code> syntax (default: <code>true</code>).</dd>\n        </d1>\n      </li>\n      <li>\n        <d1>\n          <dt><code>strikethrough: boolean</code></dt>\n          <dd><code>~~foo~~</code> syntax (default: <code>true</code>).</dd>\n        </d1>\n      </li>\n      <li>\n        <d1>\n          <dt><code>emoji: boolean</code></dt>\n          <dd><code>:emoji:</code> syntax (default: <code>true</code>).</dd>\n        </d1>\n      </li>\n    </ul>\n\n    <p><strong>Parsing/Highlighting Tests:</strong> <a href=\"../../test/index.html#gfm_*\">normal</a>,  <a href=\"../../test/index.html#verbose,gfm_*\">verbose</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/gfm/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var config = {tabSize: 4, indentUnit: 2}\n  var mode = CodeMirror.getMode(config, \"gfm\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n  var modeHighlightFormatting = CodeMirror.getMode(config, {name: \"gfm\", highlightFormatting: true});\n  function FT(name) { test.mode(name, modeHighlightFormatting, Array.prototype.slice.call(arguments, 1)); }\n\n  FT(\"codeBackticks\",\n     \"[comment&formatting&formatting-code `][comment foo][comment&formatting&formatting-code `]\");\n\n  FT(\"doubleBackticks\",\n     \"[comment&formatting&formatting-code ``][comment foo ` bar][comment&formatting&formatting-code ``]\");\n\n  FT(\"taskList\",\n     \"[variable-2&formatting&formatting-list&formatting-list-ul - ][meta&formatting&formatting-task [ ]]][variable-2  foo]\",\n     \"[variable-2&formatting&formatting-list&formatting-list-ul - ][property&formatting&formatting-task [x]]][variable-2  foo]\");\n\n  FT(\"formatting_strikethrough\",\n     \"[strikethrough&formatting&formatting-strikethrough ~~][strikethrough foo][strikethrough&formatting&formatting-strikethrough ~~]\");\n\n  FT(\"formatting_strikethrough\",\n     \"foo [strikethrough&formatting&formatting-strikethrough ~~][strikethrough bar][strikethrough&formatting&formatting-strikethrough ~~]\");\n\n  FT(\"formatting_emoji\",\n     \"foo [builtin&formatting&formatting-emoji :smile:] foo\");\n\n  MT(\"emInWordAsterisk\",\n     \"foo[em *bar*]hello\");\n\n  MT(\"emInWordUnderscore\",\n     \"foo_bar_hello\");\n\n  MT(\"emStrongUnderscore\",\n     \"[em&strong ___foo___] bar\");\n\n  MT(\"taskListAsterisk\",\n     \"[variable-2 * ][link&variable-2 [[]]][variable-2 foo]\", // Invalid; must have space or x between []\n     \"[variable-2 * ][link&variable-2 [[ ]]][variable-2 bar]\", // Invalid; must have space after ]\n     \"[variable-2 * ][link&variable-2 [[x]]][variable-2 hello]\", // Invalid; must have space after ]\n     \"[variable-2 * ][meta [ ]]][variable-2  ][link&variable-2 [[world]]]\", // Valid; tests reference style links\n     \"    [variable-3 * ][property [x]]][variable-3  foo]\"); // Valid; can be nested\n\n  MT(\"taskListPlus\",\n     \"[variable-2 + ][link&variable-2 [[]]][variable-2 foo]\", // Invalid; must have space or x between []\n     \"[variable-2 + ][link&variable-2 [[x]]][variable-2 hello]\", // Invalid; must have space after ]\n     \"[variable-2 + ][meta [ ]]][variable-2  ][link&variable-2 [[world]]]\", // Valid; tests reference style links\n     \"    [variable-3 + ][property [x]]][variable-3  foo]\"); // Valid; can be nested\n\n  MT(\"taskListDash\",\n     \"[variable-2 - ][link&variable-2 [[]]][variable-2 foo]\", // Invalid; must have space or x between []\n     \"[variable-2 - ][link&variable-2 [[x]]][variable-2 hello]\", // Invalid; must have space after ]\n     \"[variable-2 - ][meta [ ]]][variable-2  world]\", // Valid; tests reference style links\n     \"    [variable-3 - ][property [x]]][variable-3  foo]\"); // Valid; can be nested\n\n  MT(\"taskListNumber\",\n     \"[variable-2 1. ][link&variable-2 [[]]][variable-2 foo]\", // Invalid; must have space or x between []\n     \"[variable-2 2. ][link&variable-2 [[ ]]][variable-2 bar]\", // Invalid; must have space after ]\n     \"[variable-2 3. ][meta [ ]]][variable-2  world]\", // Valid; tests reference style links\n     \"    [variable-3 1. ][property [x]]][variable-3  foo]\"); // Valid; can be nested\n\n  MT(\"SHA\",\n     \"foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar\");\n\n  MT(\"SHAEmphasis\",\n     \"[em *foo ][em&link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]\");\n\n  MT(\"shortSHA\",\n     \"foo [link be6a8cc] bar\");\n\n  MT(\"tooShortSHA\",\n     \"foo be6a8c bar\");\n\n  MT(\"longSHA\",\n     \"foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar\");\n\n  MT(\"badSHA\",\n     \"foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar\");\n\n  MT(\"userSHA\",\n     \"foo [link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] hello\");\n\n  MT(\"userSHAEmphasis\",\n     \"[em *foo ][em&link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]\");\n\n  MT(\"userProjectSHA\",\n     \"foo [link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] world\");\n\n  MT(\"userProjectSHAEmphasis\",\n     \"[em *foo ][em&link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]\");\n\n  MT(\"wordSHA\",\n     \"ask for feedbac\")\n\n  MT(\"num\",\n     \"foo [link #1] bar\");\n\n  MT(\"numEmphasis\",\n     \"[em *foo ][em&link #1][em *]\");\n\n  MT(\"badNum\",\n     \"foo #1bar hello\");\n\n  MT(\"userNum\",\n     \"foo [link bar#1] hello\");\n\n  MT(\"userNumEmphasis\",\n     \"[em *foo ][em&link bar#1][em *]\");\n\n  MT(\"userProjectNum\",\n     \"foo [link bar/hello#1] world\");\n\n  MT(\"userProjectNumEmphasis\",\n     \"[em *foo ][em&link bar/hello#1][em *]\");\n\n  MT(\"vanillaLink\",\n     \"foo [link http://www.example.com/] bar\");\n\n  MT(\"vanillaLinkNoScheme\",\n     \"foo [link www.example.com] bar\");\n\n  MT(\"vanillaLinkHttps\",\n     \"foo [link https://www.example.com/] bar\");\n\n  MT(\"vanillaLinkDataSchema\",\n     \"foo [link data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==] bar\");\n\n  MT(\"vanillaLinkPunctuation\",\n     \"foo [link http://www.example.com/]. bar\");\n\n  MT(\"vanillaLinkExtension\",\n     \"foo [link http://www.example.com/index.html] bar\");\n\n  MT(\"vanillaLinkEmphasis\",\n     \"foo [em *][em&link http://www.example.com/index.html][em *] bar\");\n\n  MT(\"notALink\",\n     \"foo asfd:asdf bar\");\n\n  MT(\"notALink\",\n     \"[comment ``foo `bar` http://www.example.com/``] hello\");\n\n  MT(\"notALink\",\n     \"[comment `foo]\",\n     \"[comment&link http://www.example.com/]\",\n     \"[comment `] foo\",\n     \"\",\n     \"[link http://www.example.com/]\");\n\n  MT(\"strikethrough\",\n     \"[strikethrough ~~foo~~]\");\n\n  MT(\"strikethroughWithStartingSpace\",\n     \"~~ foo~~\");\n\n  MT(\"strikethroughUnclosedStrayTildes\",\n    \"[strikethrough ~~foo~~~]\");\n\n  MT(\"strikethroughUnclosedStrayTildes\",\n     \"[strikethrough ~~foo ~~]\");\n\n  MT(\"strikethroughUnclosedStrayTildes\",\n    \"[strikethrough ~~foo ~~ bar]\");\n\n  MT(\"strikethroughUnclosedStrayTildes\",\n    \"[strikethrough ~~foo ~~ bar~~]hello\");\n\n  MT(\"strikethroughOneLetter\",\n     \"[strikethrough ~~a~~]\");\n\n  MT(\"strikethroughWrapped\",\n     \"[strikethrough ~~foo]\",\n     \"[strikethrough foo~~]\");\n\n  MT(\"strikethroughParagraph\",\n     \"[strikethrough ~~foo]\",\n     \"\",\n     \"foo[strikethrough ~~bar]\");\n\n  MT(\"strikethroughEm\",\n     \"[strikethrough ~~foo][em&strikethrough *bar*][strikethrough ~~]\");\n\n  MT(\"strikethroughEm\",\n     \"[em *][em&strikethrough ~~foo~~][em *]\");\n\n  MT(\"strikethroughStrong\",\n     \"[strikethrough ~~][strong&strikethrough **foo**][strikethrough ~~]\");\n\n  MT(\"strikethroughStrong\",\n     \"[strong **][strong&strikethrough ~~foo~~][strong **]\");\n\n  MT(\"emoji\",\n     \"text [builtin :blush:] text [builtin :v:] text [builtin :+1:] text\",\n     \":text text: [builtin :smiley_cat:]\");\n\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/gherkin/gherkin.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/*\nGherkin mode - http://www.cukes.info/\nReport bugs/issues here: https://github.com/codemirror/CodeMirror/issues\n*/\n\n// Following Objs from Brackets implementation: https://github.com/tregusti/brackets-gherkin/blob/master/main.js\n//var Quotes = {\n//  SINGLE: 1,\n//  DOUBLE: 2\n//};\n\n//var regex = {\n//  keywords: /(Feature| {2}(Scenario|In order to|As|I)| {4}(Given|When|Then|And))/\n//};\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"gherkin\", function () {\n  return {\n    startState: function () {\n      return {\n        lineNumber: 0,\n        tableHeaderLine: false,\n        allowFeature: true,\n        allowBackground: false,\n        allowScenario: false,\n        allowSteps: false,\n        allowPlaceholders: false,\n        allowMultilineArgument: false,\n        inMultilineString: false,\n        inMultilineTable: false,\n        inKeywordLine: false\n      };\n    },\n    token: function (stream, state) {\n      if (stream.sol()) {\n        state.lineNumber++;\n        state.inKeywordLine = false;\n        if (state.inMultilineTable) {\n            state.tableHeaderLine = false;\n            if (!stream.match(/\\s*\\|/, false)) {\n              state.allowMultilineArgument = false;\n              state.inMultilineTable = false;\n            }\n        }\n      }\n\n      stream.eatSpace();\n\n      if (state.allowMultilineArgument) {\n\n        // STRING\n        if (state.inMultilineString) {\n          if (stream.match('\"\"\"')) {\n            state.inMultilineString = false;\n            state.allowMultilineArgument = false;\n          } else {\n            stream.match(/.*/);\n          }\n          return \"string\";\n        }\n\n        // TABLE\n        if (state.inMultilineTable) {\n          if (stream.match(/\\|\\s*/)) {\n            return \"bracket\";\n          } else {\n            stream.match(/[^\\|]*/);\n            return state.tableHeaderLine ? \"header\" : \"string\";\n          }\n        }\n\n        // DETECT START\n        if (stream.match('\"\"\"')) {\n          // String\n          state.inMultilineString = true;\n          return \"string\";\n        } else if (stream.match(\"|\")) {\n          // Table\n          state.inMultilineTable = true;\n          state.tableHeaderLine = true;\n          return \"bracket\";\n        }\n\n      }\n\n      // LINE COMMENT\n      if (stream.match(/#.*/)) {\n        return \"comment\";\n\n      // TAG\n      } else if (!state.inKeywordLine && stream.match(/@\\S+/)) {\n        return \"tag\";\n\n      // FEATURE\n      } else if (!state.inKeywordLine && state.allowFeature && stream.match(/(機能|功能|フィーチャ|기능|โครงหลัก|ความสามารถ|ความต้องการทางธุรกิจ|ಹೆಚ್ಚಳ|గుణము|ਮੁਹਾਂਦਰਾ|ਨਕਸ਼ ਨੁਹਾਰ|ਖਾਸੀਅਤ|रूप लेख|وِیژگی|خاصية|תכונה|Функціонал|Функция|Функционалност|Функционал|Үзенчәлеклелек|Свойство|Особина|Мөмкинлек|Могућност|Λειτουργία|Δυνατότητα|Właściwość|Vlastnosť|Trajto|Tính năng|Savybė|Pretty much|Požiadavka|Požadavek|Potrzeba biznesowa|Özellik|Osobina|Ominaisuus|Omadus|OH HAI|Mogućnost|Mogucnost|Jellemző|Hwæt|Hwaet|Funzionalità|Funktionalitéit|Funktionalität|Funkcja|Funkcionalnost|Funkcionalitāte|Funkcia|Fungsi|Functionaliteit|Funcționalitate|Funcţionalitate|Functionalitate|Funcionalitat|Funcionalidade|Fonctionnalité|Fitur|Fīča|Feature|Eiginleiki|Egenskap|Egenskab|Característica|Caracteristica|Business Need|Aspekt|Arwedd|Ahoy matey!|Ability):/)) {\n        state.allowScenario = true;\n        state.allowBackground = true;\n        state.allowPlaceholders = false;\n        state.allowSteps = false;\n        state.allowMultilineArgument = false;\n        state.inKeywordLine = true;\n        return \"keyword\";\n\n      // BACKGROUND\n      } else if (!state.inKeywordLine && state.allowBackground && stream.match(/(背景|배경|แนวคิด|ಹಿನ್ನೆಲೆ|నేపథ్యం|ਪਿਛੋਕੜ|पृष्ठभूमि|زمینه|الخلفية|רקע|Тарих|Предыстория|Предистория|Позадина|Передумова|Основа|Контекст|Кереш|Υπόβαθρο|Założenia|Yo\\-ho\\-ho|Tausta|Taust|Situācija|Rerefons|Pozadina|Pozadie|Pozadí|Osnova|Latar Belakang|Kontext|Konteksts|Kontekstas|Kontekst|Háttér|Hannergrond|Grundlage|Geçmiş|Fundo|Fono|First off|Dis is what went down|Dasar|Contexto|Contexte|Context|Contesto|Cenário de Fundo|Cenario de Fundo|Cefndir|Bối cảnh|Bakgrunnur|Bakgrunn|Bakgrund|Baggrund|Background|B4|Antecedents|Antecedentes|Ær|Aer|Achtergrond):/)) {\n        state.allowPlaceholders = false;\n        state.allowSteps = true;\n        state.allowBackground = false;\n        state.allowMultilineArgument = false;\n        state.inKeywordLine = true;\n        return \"keyword\";\n\n      // SCENARIO OUTLINE\n      } else if (!state.inKeywordLine && state.allowScenario && stream.match(/(場景大綱|场景大纲|劇本大綱|剧本大纲|テンプレ|シナリオテンプレート|シナリオテンプレ|シナリオアウトライン|시나리오 개요|สรุปเหตุการณ์|โครงสร้างของเหตุการณ์|ವಿವರಣೆ|కథనం|ਪਟਕਥਾ ਰੂਪ ਰੇਖਾ|ਪਟਕਥਾ ਢਾਂਚਾ|परिदृश्य रूपरेखा|سيناريو مخطط|الگوی سناریو|תבנית תרחיש|Сценарийның төзелеше|Сценарий структураси|Структура сценарію|Структура сценария|Структура сценарија|Скица|Рамка на сценарий|Концепт|Περιγραφή Σεναρίου|Wharrimean is|Template Situai|Template Senario|Template Keadaan|Tapausaihio|Szenariogrundriss|Szablon scenariusza|Swa hwær swa|Swa hwaer swa|Struktura scenarija|Structură scenariu|Structura scenariu|Skica|Skenario konsep|Shiver me timbers|Senaryo taslağı|Schema dello scenario|Scenariomall|Scenariomal|Scenario Template|Scenario Outline|Scenario Amlinellol|Scenārijs pēc parauga|Scenarijaus šablonas|Reckon it's like|Raamstsenaarium|Plang vum Szenario|Plan du Scénario|Plan du scénario|Osnova scénáře|Osnova Scenára|Náčrt Scenáru|Náčrt Scénáře|Náčrt Scenára|MISHUN SRSLY|Menggariskan Senario|Lýsing Dæma|Lýsing Atburðarásar|Konturo de la scenaro|Koncept|Khung tình huống|Khung kịch bản|Forgatókönyv vázlat|Esquema do Cenário|Esquema do Cenario|Esquema del escenario|Esquema de l'escenari|Esbozo do escenario|Delineação do Cenário|Delineacao do Cenario|All y'all|Abstrakt Scenario|Abstract Scenario):/)) {\n        state.allowPlaceholders = true;\n        state.allowSteps = true;\n        state.allowMultilineArgument = false;\n        state.inKeywordLine = true;\n        return \"keyword\";\n\n      // EXAMPLES\n      } else if (state.allowScenario && stream.match(/(例子|例|サンプル|예|ชุดของเหตุการณ์|ชุดของตัวอย่าง|ಉದಾಹರಣೆಗಳು|ఉదాహరణలు|ਉਦਾਹਰਨਾਂ|उदाहरण|نمونه ها|امثلة|דוגמאות|Үрнәкләр|Сценарији|Примеры|Примери|Приклади|Мисоллар|Мисаллар|Σενάρια|Παραδείγματα|You'll wanna|Voorbeelden|Variantai|Tapaukset|Se þe|Se the|Se ðe|Scenarios|Scenariji|Scenarijai|Przykłady|Primjeri|Primeri|Příklady|Príklady|Piemēri|Példák|Pavyzdžiai|Paraugs|Örnekler|Juhtumid|Exemplos|Exemples|Exemple|Exempel|EXAMPLZ|Examples|Esempi|Enghreifftiau|Ekzemploj|Eksempler|Ejemplos|Dữ liệu|Dead men tell no tales|Dæmi|Contoh|Cenários|Cenarios|Beispiller|Beispiele|Atburðarásir):/)) {\n        state.allowPlaceholders = false;\n        state.allowSteps = true;\n        state.allowBackground = false;\n        state.allowMultilineArgument = true;\n        return \"keyword\";\n\n      // SCENARIO\n      } else if (!state.inKeywordLine && state.allowScenario && stream.match(/(場景|场景|劇本|剧本|シナリオ|시나리오|เหตุการณ์|ಕಥಾಸಾರಾಂಶ|సన్నివేశం|ਪਟਕਥਾ|परिदृश्य|سيناريو|سناریو|תרחיש|Сценарій|Сценарио|Сценарий|Пример|Σενάριο|Tình huống|The thing of it is|Tapaus|Szenario|Swa|Stsenaarium|Skenario|Situai|Senaryo|Senario|Scenaro|Scenariusz|Scenariu|Scénario|Scenario|Scenarijus|Scenārijs|Scenarij|Scenarie|Scénář|Scenár|Primer|MISHUN|Kịch bản|Keadaan|Heave to|Forgatókönyv|Escenario|Escenari|Cenário|Cenario|Awww, look mate|Atburðarás):/)) {\n        state.allowPlaceholders = false;\n        state.allowSteps = true;\n        state.allowBackground = false;\n        state.allowMultilineArgument = false;\n        state.inKeywordLine = true;\n        return \"keyword\";\n\n      // STEPS\n      } else if (!state.inKeywordLine && state.allowSteps && stream.match(/(那麼|那么|而且|當|当|并且|同時|同时|前提|假设|假設|假定|假如|但是|但し|並且|もし|ならば|ただし|しかし|かつ|하지만|조건|먼저|만일|만약|단|그리고|그러면|และ |เมื่อ |แต่ |ดังนั้น |กำหนดให้ |ಸ್ಥಿತಿಯನ್ನು |ಮತ್ತು |ನೀಡಿದ |ನಂತರ |ಆದರೆ |మరియు |చెప్పబడినది |కాని |ఈ పరిస్థితిలో |అప్పుడు |ਪਰ |ਤਦ |ਜੇਕਰ |ਜਿਵੇਂ ਕਿ |ਜਦੋਂ |ਅਤੇ |यदि |परन्तु |पर |तब |तदा |तथा |जब |चूंकि |किन्तु |कदा |और |अगर |و |هنگامی |متى |لكن |عندما |ثم |بفرض |با فرض |اما |اذاً |آنگاه |כאשר |וגם |בהינתן |אזי |אז |אבל |Якщо |Һәм |Унда |Тоді |Тогда |То |Также |Та |Пусть |Припустимо, що |Припустимо |Онда |Но |Нехай |Нәтиҗәдә |Лекин |Ләкин |Коли |Когда |Когато |Када |Кад |К тому же |І |И |Задато |Задати |Задате |Если |Допустим |Дано |Дадено |Вә |Ва |Бирок |Әмма |Әйтик |Әгәр |Аммо |Али |Але |Агар |А також |А |Τότε |Όταν |Και |Δεδομένου |Αλλά |Þurh |Þegar |Þa þe |Þá |Þa |Zatati |Zakładając |Zadato |Zadate |Zadano |Zadani |Zadan |Za předpokladu |Za predpokladu |Youse know when youse got |Youse know like when |Yna |Yeah nah |Y'know |Y |Wun |Wtedy |When y'all |When |Wenn |WEN |wann |Ve |Và |Und |Un |ugeholl |Too right |Thurh |Thì |Then y'all |Then |Tha the |Tha |Tetapi |Tapi |Tak |Tada |Tad |Stel |Soit |Siis |Și |Şi |Si |Sed |Se |Så |Quando |Quand |Quan |Pryd |Potom |Pokud |Pokiaľ |Però |Pero |Pak |Oraz |Onda |Ond |Oletetaan |Og |Och |O zaman |Niin |Nhưng |När |Når |Mutta |Men |Mas |Maka |Majd |Mając |Mais |Maar |mä |Ma |Lorsque |Lorsqu'|Logo |Let go and haul |Kun |Kuid |Kui |Kiedy |Khi |Ketika |Kemudian |Keď |Když |Kaj |Kai |Kada |Kad |Jeżeli |Jeśli |Ja |It's just unbelievable |Ir |I CAN HAZ |I |Ha |Givun |Givet |Given y'all |Given |Gitt |Gegeven |Gegeben seien |Gegeben sei |Gdy |Gangway! |Fakat |Étant donnés |Etant donnés |Étant données |Etant données |Étant donnée |Etant donnée |Étant donné |Etant donné |Et |És |Entonces |Entón |Então |Entao |En |Eğer ki |Ef |Eeldades |E |Ðurh |Duota |Dun |Donitaĵo |Donat |Donada |Do |Diyelim ki |Diberi |Dengan |Den youse gotta |DEN |De |Dato |Dați fiind |Daţi fiind |Dati fiind |Dati |Date fiind |Date |Data |Dat fiind |Dar |Dann |dann |Dan |Dados |Dado |Dadas |Dada |Ða ðe |Ða |Cuando |Cho |Cando |Când |Cand |Cal |But y'all |But at the end of the day I reckon |BUT |But |Buh |Blimey! |Biết |Bet |Bagi |Aye |awer |Avast! |Atunci |Atesa |Atès |Apabila |Anrhegedig a |Angenommen |And y'all |And |AN |An |an |Amikor |Amennyiben |Ama |Als |Alors |Allora |Ali |Aleshores |Ale |Akkor |Ak |Adott |Ac |Aber |A zároveň |A tiež |A taktiež |A také |A |a |7 |\\* )/)) {\n        state.inStep = true;\n        state.allowPlaceholders = true;\n        state.allowMultilineArgument = true;\n        state.inKeywordLine = true;\n        return \"keyword\";\n\n      // INLINE STRING\n      } else if (stream.match(/\"[^\"]*\"?/)) {\n        return \"string\";\n\n      // PLACEHOLDER\n      } else if (state.allowPlaceholders && stream.match(/<[^>]*>?/)) {\n        return \"variable\";\n\n      // Fall through\n      } else {\n        stream.next();\n        stream.eatWhile(/[^@\"<#]/);\n        return null;\n      }\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-feature\", \"gherkin\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/gherkin/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Gherkin mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"gherkin.js\"></script>\n<style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Gherkin</a>\n  </ul>\n</div>\n\n<article>\n<h2>Gherkin mode</h2>\n<form><textarea id=\"code\" name=\"code\">\nFeature: Using Google\n  Background: \n    Something something\n    Something else\n  Scenario: Has a homepage\n    When I navigate to the google home page\n    Then the home page should contain the menu and the search form\n  Scenario: Searching for a term \n    When I navigate to the google home page\n    When I search for Tofu\n    Then the search results page is displayed\n    Then the search results page contains 10 individual search results\n    Then the search results contain a link to the wikipedia tofu page\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-feature</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/go/go.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"go\", function(config) {\n  var indentUnit = config.indentUnit;\n\n  var keywords = {\n    \"break\":true, \"case\":true, \"chan\":true, \"const\":true, \"continue\":true,\n    \"default\":true, \"defer\":true, \"else\":true, \"fallthrough\":true, \"for\":true,\n    \"func\":true, \"go\":true, \"goto\":true, \"if\":true, \"import\":true,\n    \"interface\":true, \"map\":true, \"package\":true, \"range\":true, \"return\":true,\n    \"select\":true, \"struct\":true, \"switch\":true, \"type\":true, \"var\":true,\n    \"bool\":true, \"byte\":true, \"complex64\":true, \"complex128\":true,\n    \"float32\":true, \"float64\":true, \"int8\":true, \"int16\":true, \"int32\":true,\n    \"int64\":true, \"string\":true, \"uint8\":true, \"uint16\":true, \"uint32\":true,\n    \"uint64\":true, \"int\":true, \"uint\":true, \"uintptr\":true, \"error\": true,\n    \"rune\":true\n  };\n\n  var atoms = {\n    \"true\":true, \"false\":true, \"iota\":true, \"nil\":true, \"append\":true,\n    \"cap\":true, \"close\":true, \"complex\":true, \"copy\":true, \"delete\":true, \"imag\":true,\n    \"len\":true, \"make\":true, \"new\":true, \"panic\":true, \"print\":true,\n    \"println\":true, \"real\":true, \"recover\":true\n  };\n\n  var isOperatorChar = /[+\\-*&^%:=<>!|\\/]/;\n\n  var curPunc;\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (ch == '\"' || ch == \"'\" || ch == \"`\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n    if (/[\\d\\.]/.test(ch)) {\n      if (ch == \".\") {\n        stream.match(/^[0-9]+([eE][\\-+]?[0-9]+)?/);\n      } else if (ch == \"0\") {\n        stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);\n      } else {\n        stream.match(/^[0-9]*\\.?[0-9]*([eE][\\-+]?[0-9]+)?/);\n      }\n      return \"number\";\n    }\n    if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n      curPunc = ch;\n      return null;\n    }\n    if (ch == \"/\") {\n      if (stream.eat(\"*\")) {\n        state.tokenize = tokenComment;\n        return tokenComment(stream, state);\n      }\n      if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n    }\n    if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return \"operator\";\n    }\n    stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n    var cur = stream.current();\n    if (keywords.propertyIsEnumerable(cur)) {\n      if (cur == \"case\" || cur == \"default\") curPunc = \"case\";\n      return \"keyword\";\n    }\n    if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n    return \"variable\";\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {end = true; break;}\n        escaped = !escaped && quote != \"`\" && next == \"\\\\\";\n      }\n      if (end || !(escaped || quote == \"`\"))\n        state.tokenize = tokenBase;\n      return \"string\";\n    };\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function Context(indented, column, type, align, prev) {\n    this.indented = indented;\n    this.column = column;\n    this.type = type;\n    this.align = align;\n    this.prev = prev;\n  }\n  function pushContext(state, col, type) {\n    return state.context = new Context(state.indented, col, type, null, state.context);\n  }\n  function popContext(state) {\n    if (!state.context.prev) return;\n    var t = state.context.type;\n    if (t == \")\" || t == \"]\" || t == \"}\")\n      state.indented = state.context.indented;\n    return state.context = state.context.prev;\n  }\n\n  // Interface\n\n  return {\n    startState: function(basecolumn) {\n      return {\n        tokenize: null,\n        context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", false),\n        indented: 0,\n        startOfLine: true\n      };\n    },\n\n    token: function(stream, state) {\n      var ctx = state.context;\n      if (stream.sol()) {\n        if (ctx.align == null) ctx.align = false;\n        state.indented = stream.indentation();\n        state.startOfLine = true;\n        if (ctx.type == \"case\") ctx.type = \"}\";\n      }\n      if (stream.eatSpace()) return null;\n      curPunc = null;\n      var style = (state.tokenize || tokenBase)(stream, state);\n      if (style == \"comment\") return style;\n      if (ctx.align == null) ctx.align = true;\n\n      if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n      else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n      else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n      else if (curPunc == \"case\") ctx.type = \"case\";\n      else if (curPunc == \"}\" && ctx.type == \"}\") popContext(state);\n      else if (curPunc == ctx.type) popContext(state);\n      state.startOfLine = false;\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;\n      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);\n      if (ctx.type == \"case\" && /^(?:case|default)\\b/.test(textAfter)) {\n        state.context.type = \"}\";\n        return ctx.indented;\n      }\n      var closing = firstChar == ctx.type;\n      if (ctx.align) return ctx.column + (closing ? 0 : 1);\n      else return ctx.indented + (closing ? 0 : indentUnit);\n    },\n\n    electricChars: \"{}):\",\n    closeBrackets: \"()[]{}''\\\"\\\"``\",\n    fold: \"brace\",\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    lineComment: \"//\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-go\", \"go\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/go/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Go mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/elegant.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"go.js\"></script>\n<style>.CodeMirror {border:1px solid #999; background:#ffc}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Go</a>\n  </ul>\n</div>\n\n<article>\n<h2>Go mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n// Prime Sieve in Go.\n// Taken from the Go specification.\n// Copyright © The Go Authors.\n\npackage main\n\nimport \"fmt\"\n\n// Send the sequence 2, 3, 4, ... to channel 'ch'.\nfunc generate(ch chan&lt;- int) {\n\tfor i := 2; ; i++ {\n\t\tch &lt;- i  // Send 'i' to channel 'ch'\n\t}\n}\n\n// Copy the values from channel 'src' to channel 'dst',\n// removing those divisible by 'prime'.\nfunc filter(src &lt;-chan int, dst chan&lt;- int, prime int) {\n\tfor i := range src {    // Loop over values received from 'src'.\n\t\tif i%prime != 0 {\n\t\t\tdst &lt;- i  // Send 'i' to channel 'dst'.\n\t\t}\n\t}\n}\n\n// The prime sieve: Daisy-chain filter processes together.\nfunc sieve() {\n\tch := make(chan int)  // Create a new channel.\n\tgo generate(ch)       // Start generate() as a subprocess.\n\tfor {\n\t\tprime := &lt;-ch\n\t\tfmt.Print(prime, \"\\n\")\n\t\tch1 := make(chan int)\n\t\tgo filter(ch, ch1, prime)\n\t\tch = ch1\n\t}\n}\n\nfunc main() {\n\tsieve()\n}\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        theme: \"elegant\",\n        matchBrackets: true,\n        indentUnit: 8,\n        tabSize: 8,\n        indentWithTabs: true,\n        mode: \"text/x-go\"\n      });\n    </script>\n\n    <p><strong>MIME type:</strong> <code>text/x-go</code></p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/groovy/groovy.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"groovy\", function(config) {\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n  var keywords = words(\n    \"abstract as assert boolean break byte case catch char class const continue def default \" +\n    \"do double else enum extends final finally float for goto if implements import in \" +\n    \"instanceof int interface long native new package private protected public return \" +\n    \"short static strictfp super switch synchronized threadsafe throw throws trait transient \" +\n    \"try void volatile while\");\n  var blockKeywords = words(\"catch class def do else enum finally for if interface switch trait try while\");\n  var standaloneKeywords = words(\"return break continue\");\n  var atoms = words(\"null true false this\");\n\n  var curPunc;\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (ch == '\"' || ch == \"'\") {\n      return startString(ch, stream, state);\n    }\n    if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n      curPunc = ch;\n      return null;\n    }\n    if (/\\d/.test(ch)) {\n      stream.eatWhile(/[\\w\\.]/);\n      if (stream.eat(/eE/)) { stream.eat(/\\+\\-/); stream.eatWhile(/\\d/); }\n      return \"number\";\n    }\n    if (ch == \"/\") {\n      if (stream.eat(\"*\")) {\n        state.tokenize.push(tokenComment);\n        return tokenComment(stream, state);\n      }\n      if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n      if (expectExpression(state.lastToken, false)) {\n        return startString(ch, stream, state);\n      }\n    }\n    if (ch == \"-\" && stream.eat(\">\")) {\n      curPunc = \"->\";\n      return null;\n    }\n    if (/[+\\-*&%=<>!?|\\/~]/.test(ch)) {\n      stream.eatWhile(/[+\\-*&%=<>|~]/);\n      return \"operator\";\n    }\n    stream.eatWhile(/[\\w\\$_]/);\n    if (ch == \"@\") { stream.eatWhile(/[\\w\\$_\\.]/); return \"meta\"; }\n    if (state.lastToken == \".\") return \"property\";\n    if (stream.eat(\":\")) { curPunc = \"proplabel\"; return \"property\"; }\n    var cur = stream.current();\n    if (atoms.propertyIsEnumerable(cur)) { return \"atom\"; }\n    if (keywords.propertyIsEnumerable(cur)) {\n      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n      else if (standaloneKeywords.propertyIsEnumerable(cur)) curPunc = \"standalone\";\n      return \"keyword\";\n    }\n    return \"variable\";\n  }\n  tokenBase.isBase = true;\n\n  function startString(quote, stream, state) {\n    var tripleQuoted = false;\n    if (quote != \"/\" && stream.eat(quote)) {\n      if (stream.eat(quote)) tripleQuoted = true;\n      else return \"string\";\n    }\n    function t(stream, state) {\n      var escaped = false, next, end = !tripleQuoted;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {\n          if (!tripleQuoted) { break; }\n          if (stream.match(quote + quote)) { end = true; break; }\n        }\n        if (quote == '\"' && next == \"$\" && !escaped && stream.eat(\"{\")) {\n          state.tokenize.push(tokenBaseUntilBrace());\n          return \"string\";\n        }\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end) state.tokenize.pop();\n      return \"string\";\n    }\n    state.tokenize.push(t);\n    return t(stream, state);\n  }\n\n  function tokenBaseUntilBrace() {\n    var depth = 1;\n    function t(stream, state) {\n      if (stream.peek() == \"}\") {\n        depth--;\n        if (depth == 0) {\n          state.tokenize.pop();\n          return state.tokenize[state.tokenize.length-1](stream, state);\n        }\n      } else if (stream.peek() == \"{\") {\n        depth++;\n      }\n      return tokenBase(stream, state);\n    }\n    t.isBase = true;\n    return t;\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize.pop();\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function expectExpression(last, newline) {\n    return !last || last == \"operator\" || last == \"->\" || /[\\.\\[\\{\\(,;:]/.test(last) ||\n      last == \"newstatement\" || last == \"keyword\" || last == \"proplabel\" ||\n      (last == \"standalone\" && !newline);\n  }\n\n  function Context(indented, column, type, align, prev) {\n    this.indented = indented;\n    this.column = column;\n    this.type = type;\n    this.align = align;\n    this.prev = prev;\n  }\n  function pushContext(state, col, type) {\n    return state.context = new Context(state.indented, col, type, null, state.context);\n  }\n  function popContext(state) {\n    var t = state.context.type;\n    if (t == \")\" || t == \"]\" || t == \"}\")\n      state.indented = state.context.indented;\n    return state.context = state.context.prev;\n  }\n\n  // Interface\n\n  return {\n    startState: function(basecolumn) {\n      return {\n        tokenize: [tokenBase],\n        context: new Context((basecolumn || 0) - config.indentUnit, 0, \"top\", false),\n        indented: 0,\n        startOfLine: true,\n        lastToken: null\n      };\n    },\n\n    token: function(stream, state) {\n      var ctx = state.context;\n      if (stream.sol()) {\n        if (ctx.align == null) ctx.align = false;\n        state.indented = stream.indentation();\n        state.startOfLine = true;\n        // Automatic semicolon insertion\n        if (ctx.type == \"statement\" && !expectExpression(state.lastToken, true)) {\n          popContext(state); ctx = state.context;\n        }\n      }\n      if (stream.eatSpace()) return null;\n      curPunc = null;\n      var style = state.tokenize[state.tokenize.length-1](stream, state);\n      if (style == \"comment\") return style;\n      if (ctx.align == null) ctx.align = true;\n\n      if ((curPunc == \";\" || curPunc == \":\") && ctx.type == \"statement\") popContext(state);\n      // Handle indentation for {x -> \\n ... }\n      else if (curPunc == \"->\" && ctx.type == \"statement\" && ctx.prev.type == \"}\") {\n        popContext(state);\n        state.context.align = false;\n      }\n      else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n      else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n      else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n      else if (curPunc == \"}\") {\n        while (ctx.type == \"statement\") ctx = popContext(state);\n        if (ctx.type == \"}\") ctx = popContext(state);\n        while (ctx.type == \"statement\") ctx = popContext(state);\n      }\n      else if (curPunc == ctx.type) popContext(state);\n      else if (ctx.type == \"}\" || ctx.type == \"top\" || (ctx.type == \"statement\" && curPunc == \"newstatement\"))\n        pushContext(state, stream.column(), \"statement\");\n      state.startOfLine = false;\n      state.lastToken = curPunc || style;\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (!state.tokenize[state.tokenize.length-1].isBase) return CodeMirror.Pass;\n      var firstChar = textAfter && textAfter.charAt(0), ctx = state.context;\n      if (ctx.type == \"statement\" && !expectExpression(state.lastToken, true)) ctx = ctx.prev;\n      var closing = firstChar == ctx.type;\n      if (ctx.type == \"statement\") return ctx.indented + (firstChar == \"{\" ? 0 : config.indentUnit);\n      else if (ctx.align) return ctx.column + (closing ? 0 : 1);\n      else return ctx.indented + (closing ? 0 : config.indentUnit);\n    },\n\n    electricChars: \"{}\",\n    closeBrackets: {triples: \"'\\\"\"},\n    fold: \"brace\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-groovy\", \"groovy\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/groovy/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Groovy mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"groovy.js\"></script>\n<style>.CodeMirror {border-top: 1px solid #500; border-bottom: 1px solid #500;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Groovy</a>\n  </ul>\n</div>\n\n<article>\n<h2>Groovy mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n//Pattern for groovy script\ndef p = ~/.*\\.groovy/\nnew File( 'd:\\\\scripts' ).eachFileMatch(p) {f ->\n  // imports list\n  def imports = []\n  f.eachLine {\n    // condition to detect an import instruction\n    ln -> if ( ln =~ '^import .*' ) {\n      imports << \"${ln - 'import '}\"\n    }\n  }\n  // print thmen\n  if ( ! imports.empty ) {\n    println f\n    imports.each{ println \"   $it\" }\n  }\n}\n\n/* Coin changer demo code from http://groovy.codehaus.org */\n\nenum UsCoin {\n  quarter(25), dime(10), nickel(5), penny(1)\n  UsCoin(v) { value = v }\n  final value\n}\n\nenum OzzieCoin {\n  fifty(50), twenty(20), ten(10), five(5)\n  OzzieCoin(v) { value = v }\n  final value\n}\n\ndef plural(word, count) {\n  if (count == 1) return word\n  word[-1] == 'y' ? word[0..-2] + \"ies\" : word + \"s\"\n}\n\ndef change(currency, amount) {\n  currency.values().inject([]){ list, coin ->\n     int count = amount / coin.value\n     amount = amount % coin.value\n     list += \"$count ${plural(coin.toString(), count)}\"\n  }\n}\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-groovy\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-groovy</code></p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/haml/haml.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../htmlmixed/htmlmixed\"), require(\"../ruby/ruby\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../htmlmixed/htmlmixed\", \"../ruby/ruby\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\n  // full haml mode. This handled embedded ruby and html fragments too\n  CodeMirror.defineMode(\"haml\", function(config) {\n    var htmlMode = CodeMirror.getMode(config, {name: \"htmlmixed\"});\n    var rubyMode = CodeMirror.getMode(config, \"ruby\");\n\n    function rubyInQuote(endQuote) {\n      return function(stream, state) {\n        var ch = stream.peek();\n        if (ch == endQuote && state.rubyState.tokenize.length == 1) {\n          // step out of ruby context as it seems to complete processing all the braces\n          stream.next();\n          state.tokenize = html;\n          return \"closeAttributeTag\";\n        } else {\n          return ruby(stream, state);\n        }\n      };\n    }\n\n    function ruby(stream, state) {\n      if (stream.match(\"-#\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n      return rubyMode.token(stream, state.rubyState);\n    }\n\n    function html(stream, state) {\n      var ch = stream.peek();\n\n      // handle haml declarations. All declarations that cant be handled here\n      // will be passed to html mode\n      if (state.previousToken.style == \"comment\" ) {\n        if (state.indented > state.previousToken.indented) {\n          stream.skipToEnd();\n          return \"commentLine\";\n        }\n      }\n\n      if (state.startOfLine) {\n        if (ch == \"!\" && stream.match(\"!!\")) {\n          stream.skipToEnd();\n          return \"tag\";\n        } else if (stream.match(/^%[\\w:#\\.]+=/)) {\n          state.tokenize = ruby;\n          return \"hamlTag\";\n        } else if (stream.match(/^%[\\w:]+/)) {\n          return \"hamlTag\";\n        } else if (ch == \"/\" ) {\n          stream.skipToEnd();\n          return \"comment\";\n        }\n      }\n\n      if (state.startOfLine || state.previousToken.style == \"hamlTag\") {\n        if ( ch == \"#\" || ch == \".\") {\n          stream.match(/[\\w-#\\.]*/);\n          return \"hamlAttribute\";\n        }\n      }\n\n      // donot handle --> as valid ruby, make it HTML close comment instead\n      if (state.startOfLine && !stream.match(\"-->\", false) && (ch == \"=\" || ch == \"-\" )) {\n        state.tokenize = ruby;\n        return state.tokenize(stream, state);\n      }\n\n      if (state.previousToken.style == \"hamlTag\" ||\n          state.previousToken.style == \"closeAttributeTag\" ||\n          state.previousToken.style == \"hamlAttribute\") {\n        if (ch == \"(\") {\n          state.tokenize = rubyInQuote(\")\");\n          return state.tokenize(stream, state);\n        } else if (ch == \"{\") {\n          if (!stream.match(/^\\{%.*/)) {\n            state.tokenize = rubyInQuote(\"}\");\n            return state.tokenize(stream, state);\n          }\n        }\n      }\n\n      return htmlMode.token(stream, state.htmlState);\n    }\n\n    return {\n      // default to html mode\n      startState: function() {\n        var htmlState = CodeMirror.startState(htmlMode);\n        var rubyState = CodeMirror.startState(rubyMode);\n        return {\n          htmlState: htmlState,\n          rubyState: rubyState,\n          indented: 0,\n          previousToken: { style: null, indented: 0},\n          tokenize: html\n        };\n      },\n\n      copyState: function(state) {\n        return {\n          htmlState : CodeMirror.copyState(htmlMode, state.htmlState),\n          rubyState: CodeMirror.copyState(rubyMode, state.rubyState),\n          indented: state.indented,\n          previousToken: state.previousToken,\n          tokenize: state.tokenize\n        };\n      },\n\n      token: function(stream, state) {\n        if (stream.sol()) {\n          state.indented = stream.indentation();\n          state.startOfLine = true;\n        }\n        if (stream.eatSpace()) return null;\n        var style = state.tokenize(stream, state);\n        state.startOfLine = false;\n        // dont record comment line as we only want to measure comment line with\n        // the opening comment block\n        if (style && style != \"commentLine\") {\n          state.previousToken = { style: style, indented: state.indented };\n        }\n        // if current state is ruby and the previous token is not `,` reset the\n        // tokenize to html\n        if (stream.eol() && state.tokenize == ruby) {\n          stream.backUp(1);\n          var ch = stream.peek();\n          stream.next();\n          if (ch && ch != \",\") {\n            state.tokenize = html;\n          }\n        }\n        // reprocess some of the specific style tag when finish setting previousToken\n        if (style == \"hamlTag\") {\n          style = \"tag\";\n        } else if (style == \"commentLine\") {\n          style = \"comment\";\n        } else if (style == \"hamlAttribute\") {\n          style = \"attribute\";\n        } else if (style == \"closeAttributeTag\") {\n          style = null;\n        }\n        return style;\n      }\n    };\n  }, \"htmlmixed\", \"ruby\");\n\n  CodeMirror.defineMIME(\"text/x-haml\", \"haml\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/haml/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: HAML mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../ruby/ruby.js\"></script>\n<script src=\"haml.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">HAML</a>\n  </ul>\n</div>\n\n<article>\n<h2>HAML mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n!!!\n#content\n.left.column(title=\"title\"){:href => \"/hello\", :test => \"#{hello}_#{world}\"}\n    <!-- This is a comment -->\n    %h2 Welcome to our site!\n    %p= puts \"HAML MODE\"\n  .right.column\n    = render :partial => \"sidebar\"\n\n.container\n  .row\n    .span8\n      %h1.title= @page_title\n%p.title= @page_title\n%p\n  /\n    The same as HTML comment\n    Hello multiline comment\n\n  -# haml comment\n      This wont be displayed\n      nor will this\n  Date/Time:\n  - now = DateTime.now\n  %strong= now\n  - if now > DateTime.parse(\"December 31, 2006\")\n    = \"Happy new \" + \"year!\"\n\n%title\n  = @title\n  \\= @title\n  <h1>Title</h1>\n  <h1 title=\"HELLO\">\n    Title\n  </h1>\n    </textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"text/x-haml\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-haml</code>.</p>\n\n    <p><strong>Parsing/Highlighting Tests:</strong> <a href=\"../../test/index.html#haml_*\">normal</a>,  <a href=\"../../test/index.html#verbose,haml_*\">verbose</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/haml/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, \"haml\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  // Requires at least one media query\n  MT(\"elementName\",\n     \"[tag %h1] Hey There\");\n\n  MT(\"oneElementPerLine\",\n     \"[tag %h1] Hey There %h2\");\n\n  MT(\"idSelector\",\n     \"[tag %h1][attribute #test] Hey There\");\n\n  MT(\"classSelector\",\n     \"[tag %h1][attribute .hello] Hey There\");\n\n  MT(\"docType\",\n     \"[tag !!! XML]\");\n\n  MT(\"comment\",\n     \"[comment / Hello WORLD]\");\n\n  MT(\"notComment\",\n     \"[tag %h1] This is not a / comment \");\n\n  MT(\"attributes\",\n     \"[tag %a]([variable title][operator =][string \\\"test\\\"]){[atom :title] [operator =>] [string \\\"test\\\"]}\");\n\n  MT(\"htmlCode\",\n     \"[tag&bracket <][tag h1][tag&bracket >]Title[tag&bracket </][tag h1][tag&bracket >]\");\n\n  MT(\"rubyBlock\",\n     \"[operator =][variable-2 @item]\");\n\n  MT(\"selectorRubyBlock\",\n     \"[tag %a.selector=] [variable-2 @item]\");\n\n  MT(\"nestedRubyBlock\",\n      \"[tag %a]\",\n      \"   [operator =][variable puts] [string \\\"test\\\"]\");\n\n  MT(\"multilinePlaintext\",\n      \"[tag %p]\",\n      \"  Hello,\",\n      \"  World\");\n\n  MT(\"multilineRuby\",\n      \"[tag %p]\",\n      \"  [comment -# this is a comment]\",\n      \"     [comment and this is a comment too]\",\n      \"  Date/Time\",\n      \"  [operator -] [variable now] [operator =] [tag DateTime][operator .][property now]\",\n      \"  [tag %strong=] [variable now]\",\n      \"  [operator -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][property parse]([string \\\"December 31, 2006\\\"])\",\n      \"     [operator =][string \\\"Happy\\\"]\",\n      \"     [operator =][string \\\"Belated\\\"]\",\n      \"     [operator =][string \\\"Birthday\\\"]\");\n\n  MT(\"multilineComment\",\n      \"[comment /]\",\n      \"  [comment Multiline]\",\n      \"  [comment Comment]\");\n\n  MT(\"hamlComment\",\n     \"[comment -# this is a comment]\");\n\n  MT(\"multilineHamlComment\",\n     \"[comment -# this is a comment]\",\n     \"   [comment and this is a comment too]\");\n\n  MT(\"multilineHTMLComment\",\n    \"[comment <!--]\",\n    \"  [comment what a comment]\",\n    \"  [comment -->]\");\n\n  MT(\"hamlAfterRubyTag\",\n    \"[attribute .block]\",\n    \"  [tag %strong=] [variable now]\",\n    \"  [attribute .test]\",\n    \"     [operator =][variable now]\",\n    \"  [attribute .right]\");\n\n  MT(\"stretchedRuby\",\n     \"[operator =] [variable puts] [string \\\"Hello\\\"],\",\n     \"   [string \\\"World\\\"]\");\n\n  MT(\"interpolationInHashAttribute\",\n     //\"[tag %div]{[atom :id] [operator =>] [string \\\"#{][variable test][string }_#{][variable ting][string }\\\"]} test\");\n     \"[tag %div]{[atom :id] [operator =>] [string \\\"#{][variable test][string }_#{][variable ting][string }\\\"]} test\");\n\n  MT(\"interpolationInHTMLAttribute\",\n     \"[tag %div]([variable title][operator =][string \\\"#{][variable test][string }_#{][variable ting]()[string }\\\"]) Test\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/handlebars/handlebars.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../../addon/mode/simple\"), require(\"../../addon/mode/multiplex\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../../addon/mode/simple\", \"../../addon/mode/multiplex\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineSimpleMode(\"handlebars-tags\", {\n    start: [\n      { regex: /\\{\\{!--/, push: \"dash_comment\", token: \"comment\" },\n      { regex: /\\{\\{!/,   push: \"comment\", token: \"comment\" },\n      { regex: /\\{\\{/,    push: \"handlebars\", token: \"tag\" }\n    ],\n    handlebars: [\n      { regex: /\\}\\}/, pop: true, token: \"tag\" },\n\n      // Double and single quotes\n      { regex: /\"(?:[^\\\\\"]|\\\\.)*\"?/, token: \"string\" },\n      { regex: /'(?:[^\\\\']|\\\\.)*'?/, token: \"string\" },\n\n      // Handlebars keywords\n      { regex: />|[#\\/]([A-Za-z_]\\w*)/, token: \"keyword\" },\n      { regex: /(?:else|this)\\b/, token: \"keyword\" },\n\n      // Numeral\n      { regex: /\\d+/i, token: \"number\" },\n\n      // Atoms like = and .\n      { regex: /=|~|@|true|false/, token: \"atom\" },\n\n      // Paths\n      { regex: /(?:\\.\\.\\/)*(?:[A-Za-z_][\\w\\.]*)+/, token: \"variable-2\" }\n    ],\n    dash_comment: [\n      { regex: /--\\}\\}/, pop: true, token: \"comment\" },\n\n      // Commented code\n      { regex: /./, token: \"comment\"}\n    ],\n    comment: [\n      { regex: /\\}\\}/, pop: true, token: \"comment\" },\n      { regex: /./, token: \"comment\" }\n    ],\n    meta: {\n      blockCommentStart: \"{{--\",\n      blockCommentEnd: \"--}}\"\n    }\n  });\n\n  CodeMirror.defineMode(\"handlebars\", function(config, parserConfig) {\n    var handlebars = CodeMirror.getMode(config, \"handlebars-tags\");\n    if (!parserConfig || !parserConfig.base) return handlebars;\n    return CodeMirror.multiplexingMode(\n      CodeMirror.getMode(config, parserConfig.base),\n      {open: \"{{\", close: \"}}\", mode: handlebars, parseDelimiters: true}\n    );\n  });\n\n  CodeMirror.defineMIME(\"text/x-handlebars-template\", \"handlebars\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/handlebars/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Handlebars mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/simple.js\"></script>\n<script src=\"../../addon/mode/multiplex.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"handlebars.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">HTML mixed</a>\n  </ul>\n</div>\n\n<article>\n<h2>Handlebars</h2>\n<form><textarea id=\"code\" name=\"code\">\n{{> breadcrumbs}}\n\n{{!--\n  You can use the t function to get\n  content translated to the current locale, es:\n  {{t 'article_list'}}\n--}}\n\n<h1>{{t 'article_list'}}</h1>\n\n{{! one line comment }}\n\n{{#each articles}}\n  {{~title}}\n  <p>{{excerpt body size=120 ellipsis=true}}</p>\n\n  {{#with author}}\n    written by {{first_name}} {{last_name}}\n    from category: {{../category.title}}\n    {{#if @../last}}foobar!{{/if}}\n  {{/with~}}\n\n  {{#if promoted.latest}}Read this one! {{else}} This is ok! {{/if}}\n\n  {{#if @last}}<hr>{{/if}}\n{{/each}}\n\n{{#form new_comment}}\n  <input type=\"text\" name=\"body\">\n{{/form}}\n\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: {name: \"handlebars\", base: \"text/html\"}\n      });\n    </script>\n    \n    <p>Handlebars syntax highlighting for CodeMirror.</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-handlebars-template</code></p>\n\n    <p>Supported options: <code>base</code> to set the mode to\n    wrap. For example, use</p>\n    <pre>mode: {name: \"handlebars\", base: \"text/html\"}</pre>\n    <p>to highlight an HTML template.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/haskell/haskell.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"haskell\", function(_config, modeConfig) {\n\n  function switchState(source, setState, f) {\n    setState(f);\n    return f(source, setState);\n  }\n\n  // These should all be Unicode extended, as per the Haskell 2010 report\n  var smallRE = /[a-z_]/;\n  var largeRE = /[A-Z]/;\n  var digitRE = /\\d/;\n  var hexitRE = /[0-9A-Fa-f]/;\n  var octitRE = /[0-7]/;\n  var idRE = /[a-z_A-Z0-9'\\xa1-\\uffff]/;\n  var symbolRE = /[-!#$%&*+.\\/<=>?@\\\\^|~:]/;\n  var specialRE = /[(),;[\\]`{}]/;\n  var whiteCharRE = /[ \\t\\v\\f]/; // newlines are handled in tokenizer\n\n  function normal(source, setState) {\n    if (source.eatWhile(whiteCharRE)) {\n      return null;\n    }\n\n    var ch = source.next();\n    if (specialRE.test(ch)) {\n      if (ch == '{' && source.eat('-')) {\n        var t = \"comment\";\n        if (source.eat('#')) {\n          t = \"meta\";\n        }\n        return switchState(source, setState, ncomment(t, 1));\n      }\n      return null;\n    }\n\n    if (ch == '\\'') {\n      if (source.eat('\\\\')) {\n        source.next();  // should handle other escapes here\n      }\n      else {\n        source.next();\n      }\n      if (source.eat('\\'')) {\n        return \"string\";\n      }\n      return \"string error\";\n    }\n\n    if (ch == '\"') {\n      return switchState(source, setState, stringLiteral);\n    }\n\n    if (largeRE.test(ch)) {\n      source.eatWhile(idRE);\n      if (source.eat('.')) {\n        return \"qualifier\";\n      }\n      return \"variable-2\";\n    }\n\n    if (smallRE.test(ch)) {\n      source.eatWhile(idRE);\n      return \"variable\";\n    }\n\n    if (digitRE.test(ch)) {\n      if (ch == '0') {\n        if (source.eat(/[xX]/)) {\n          source.eatWhile(hexitRE); // should require at least 1\n          return \"integer\";\n        }\n        if (source.eat(/[oO]/)) {\n          source.eatWhile(octitRE); // should require at least 1\n          return \"number\";\n        }\n      }\n      source.eatWhile(digitRE);\n      var t = \"number\";\n      if (source.match(/^\\.\\d+/)) {\n        t = \"number\";\n      }\n      if (source.eat(/[eE]/)) {\n        t = \"number\";\n        source.eat(/[-+]/);\n        source.eatWhile(digitRE); // should require at least 1\n      }\n      return t;\n    }\n\n    if (ch == \".\" && source.eat(\".\"))\n      return \"keyword\";\n\n    if (symbolRE.test(ch)) {\n      if (ch == '-' && source.eat(/-/)) {\n        source.eatWhile(/-/);\n        if (!source.eat(symbolRE)) {\n          source.skipToEnd();\n          return \"comment\";\n        }\n      }\n      var t = \"variable\";\n      if (ch == ':') {\n        t = \"variable-2\";\n      }\n      source.eatWhile(symbolRE);\n      return t;\n    }\n\n    return \"error\";\n  }\n\n  function ncomment(type, nest) {\n    if (nest == 0) {\n      return normal;\n    }\n    return function(source, setState) {\n      var currNest = nest;\n      while (!source.eol()) {\n        var ch = source.next();\n        if (ch == '{' && source.eat('-')) {\n          ++currNest;\n        }\n        else if (ch == '-' && source.eat('}')) {\n          --currNest;\n          if (currNest == 0) {\n            setState(normal);\n            return type;\n          }\n        }\n      }\n      setState(ncomment(type, currNest));\n      return type;\n    };\n  }\n\n  function stringLiteral(source, setState) {\n    while (!source.eol()) {\n      var ch = source.next();\n      if (ch == '\"') {\n        setState(normal);\n        return \"string\";\n      }\n      if (ch == '\\\\') {\n        if (source.eol() || source.eat(whiteCharRE)) {\n          setState(stringGap);\n          return \"string\";\n        }\n        if (source.eat('&')) {\n        }\n        else {\n          source.next(); // should handle other escapes here\n        }\n      }\n    }\n    setState(normal);\n    return \"string error\";\n  }\n\n  function stringGap(source, setState) {\n    if (source.eat('\\\\')) {\n      return switchState(source, setState, stringLiteral);\n    }\n    source.next();\n    setState(normal);\n    return \"error\";\n  }\n\n\n  var wellKnownWords = (function() {\n    var wkw = {};\n    function setType(t) {\n      return function () {\n        for (var i = 0; i < arguments.length; i++)\n          wkw[arguments[i]] = t;\n      };\n    }\n\n    setType(\"keyword\")(\n      \"case\", \"class\", \"data\", \"default\", \"deriving\", \"do\", \"else\", \"foreign\",\n      \"if\", \"import\", \"in\", \"infix\", \"infixl\", \"infixr\", \"instance\", \"let\",\n      \"module\", \"newtype\", \"of\", \"then\", \"type\", \"where\", \"_\");\n\n    setType(\"keyword\")(\n      \"\\.\\.\", \":\", \"::\", \"=\", \"\\\\\", \"<-\", \"->\", \"@\", \"~\", \"=>\");\n\n    setType(\"builtin\")(\n      \"!!\", \"$!\", \"$\", \"&&\", \"+\", \"++\", \"-\", \".\", \"/\", \"/=\", \"<\", \"<*\", \"<=\",\n      \"<$>\", \"<*>\", \"=<<\", \"==\", \">\", \">=\", \">>\", \">>=\", \"^\", \"^^\", \"||\", \"*\",\n      \"*>\", \"**\");\n\n    setType(\"builtin\")(\n      \"Applicative\", \"Bool\", \"Bounded\", \"Char\", \"Double\", \"EQ\", \"Either\", \"Enum\",\n      \"Eq\", \"False\", \"FilePath\", \"Float\", \"Floating\", \"Fractional\", \"Functor\",\n      \"GT\", \"IO\", \"IOError\", \"Int\", \"Integer\", \"Integral\", \"Just\", \"LT\", \"Left\",\n      \"Maybe\", \"Monad\", \"Nothing\", \"Num\", \"Ord\", \"Ordering\", \"Rational\", \"Read\",\n      \"ReadS\", \"Real\", \"RealFloat\", \"RealFrac\", \"Right\", \"Show\", \"ShowS\",\n      \"String\", \"True\");\n\n    setType(\"builtin\")(\n      \"abs\", \"acos\", \"acosh\", \"all\", \"and\", \"any\", \"appendFile\", \"asTypeOf\",\n      \"asin\", \"asinh\", \"atan\", \"atan2\", \"atanh\", \"break\", \"catch\", \"ceiling\",\n      \"compare\", \"concat\", \"concatMap\", \"const\", \"cos\", \"cosh\", \"curry\",\n      \"cycle\", \"decodeFloat\", \"div\", \"divMod\", \"drop\", \"dropWhile\", \"either\",\n      \"elem\", \"encodeFloat\", \"enumFrom\", \"enumFromThen\", \"enumFromThenTo\",\n      \"enumFromTo\", \"error\", \"even\", \"exp\", \"exponent\", \"fail\", \"filter\",\n      \"flip\", \"floatDigits\", \"floatRadix\", \"floatRange\", \"floor\", \"fmap\",\n      \"foldl\", \"foldl1\", \"foldr\", \"foldr1\", \"fromEnum\", \"fromInteger\",\n      \"fromIntegral\", \"fromRational\", \"fst\", \"gcd\", \"getChar\", \"getContents\",\n      \"getLine\", \"head\", \"id\", \"init\", \"interact\", \"ioError\", \"isDenormalized\",\n      \"isIEEE\", \"isInfinite\", \"isNaN\", \"isNegativeZero\", \"iterate\", \"last\",\n      \"lcm\", \"length\", \"lex\", \"lines\", \"log\", \"logBase\", \"lookup\", \"map\",\n      \"mapM\", \"mapM_\", \"max\", \"maxBound\", \"maximum\", \"maybe\", \"min\", \"minBound\",\n      \"minimum\", \"mod\", \"negate\", \"not\", \"notElem\", \"null\", \"odd\", \"or\",\n      \"otherwise\", \"pi\", \"pred\", \"print\", \"product\", \"properFraction\", \"pure\",\n      \"putChar\", \"putStr\", \"putStrLn\", \"quot\", \"quotRem\", \"read\", \"readFile\",\n      \"readIO\", \"readList\", \"readLn\", \"readParen\", \"reads\", \"readsPrec\",\n      \"realToFrac\", \"recip\", \"rem\", \"repeat\", \"replicate\", \"return\", \"reverse\",\n      \"round\", \"scaleFloat\", \"scanl\", \"scanl1\", \"scanr\", \"scanr1\", \"seq\",\n      \"sequence\", \"sequence_\", \"show\", \"showChar\", \"showList\", \"showParen\",\n      \"showString\", \"shows\", \"showsPrec\", \"significand\", \"signum\", \"sin\",\n      \"sinh\", \"snd\", \"span\", \"splitAt\", \"sqrt\", \"subtract\", \"succ\", \"sum\",\n      \"tail\", \"take\", \"takeWhile\", \"tan\", \"tanh\", \"toEnum\", \"toInteger\",\n      \"toRational\", \"truncate\", \"uncurry\", \"undefined\", \"unlines\", \"until\",\n      \"unwords\", \"unzip\", \"unzip3\", \"userError\", \"words\", \"writeFile\", \"zip\",\n      \"zip3\", \"zipWith\", \"zipWith3\");\n\n    var override = modeConfig.overrideKeywords;\n    if (override) for (var word in override) if (override.hasOwnProperty(word))\n      wkw[word] = override[word];\n\n    return wkw;\n  })();\n\n\n\n  return {\n    startState: function ()  { return { f: normal }; },\n    copyState:  function (s) { return { f: s.f }; },\n\n    token: function(stream, state) {\n      var t = state.f(stream, function(s) { state.f = s; });\n      var w = stream.current();\n      return wellKnownWords.hasOwnProperty(w) ? wellKnownWords[w] : t;\n    },\n\n    blockCommentStart: \"{-\",\n    blockCommentEnd: \"-}\",\n    lineComment: \"--\"\n  };\n\n});\n\nCodeMirror.defineMIME(\"text/x-haskell\", \"haskell\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/haskell/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Haskell mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/elegant.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"haskell.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Haskell</a>\n  </ul>\n</div>\n\n<article>\n<h2>Haskell mode</h2>\n<form><textarea id=\"code\" name=\"code\">\nmodule UniquePerms (\n    uniquePerms\n    )\nwhere\n\n-- | Find all unique permutations of a list where there might be duplicates.\nuniquePerms :: (Eq a) => [a] -> [[a]]\nuniquePerms = permBag . makeBag\n\n-- | An unordered collection where duplicate values are allowed,\n-- but represented with a single value and a count.\ntype Bag a = [(a, Int)]\n\nmakeBag :: (Eq a) => [a] -> Bag a\nmakeBag [] = []\nmakeBag (a:as) = mix a $ makeBag as\n  where\n    mix a []                        = [(a,1)]\n    mix a (bn@(b,n):bs) | a == b    = (b,n+1):bs\n                        | otherwise = bn : mix a bs\n\npermBag :: Bag a -> [[a]]\npermBag [] = [[]]\npermBag bs = concatMap (\\(f,cs) -> map (f:) $ permBag cs) . oneOfEach $ bs\n  where\n    oneOfEach [] = []\n    oneOfEach (an@(a,n):bs) =\n        let bs' = if n == 1 then bs else (a,n-1):bs\n        in (a,bs') : mapSnd (an:) (oneOfEach bs)\n    \n    apSnd f (a,b) = (a, f b)\n    mapSnd = map . apSnd\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        theme: \"elegant\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-haskell</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/haskell-literate/haskell-literate.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function (mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../haskell/haskell\"))\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../haskell/haskell\"], mod)\n  else // Plain browser env\n    mod(CodeMirror)\n})(function (CodeMirror) {\n  \"use strict\"\n\n  CodeMirror.defineMode(\"haskell-literate\", function (config, parserConfig) {\n    var baseMode = CodeMirror.getMode(config, (parserConfig && parserConfig.base) || \"haskell\")\n\n    return {\n      startState: function () {\n        return {\n          inCode: false,\n          baseState: CodeMirror.startState(baseMode)\n        }\n      },\n      token: function (stream, state) {\n        if (stream.sol()) {\n          if (state.inCode = stream.eat(\">\"))\n            return \"meta\"\n        }\n        if (state.inCode) {\n          return baseMode.token(stream, state.baseState)\n        } else {\n          stream.skipToEnd()\n          return \"comment\"\n        }\n      },\n      innerMode: function (state) {\n        return state.inCode ? {state: state.baseState, mode: baseMode} : null\n      }\n    }\n  }, \"haskell\")\n\n  CodeMirror.defineMIME(\"text/x-literate-haskell\", \"haskell-literate\")\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/haskell-literate/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Haskell-literate mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"haskell-literate.js\"></script>\n<script src=\"../haskell/haskell.js\"></script>\n<style>.CodeMirror {\n  border-top    : 1px solid #DDDDDD;\n  border-bottom : 1px solid #DDDDDD;\n}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo\n                                                          src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Haskell-literate</a>\n  </ul>\n</div>\n\n<article>\n  <h2>Haskell literate mode</h2>\n  <form>\n    <textarea id=\"code\" name=\"code\">\n> {-# LANGUAGE OverloadedStrings #-}\n> {-# OPTIONS_GHC -fno-warn-unused-do-bind #-}\n> import Control.Applicative ((<$>), (<*>))\n> import Data.Maybe (isJust)\n\n> import Data.Text (Text)\n> import Text.Blaze ((!))\n> import qualified Data.Text as T\n> import qualified Happstack.Server as Happstack\n> import qualified Text.Blaze.Html5 as H\n> import qualified Text.Blaze.Html5.Attributes as A\n\n> import Text.Digestive\n> import Text.Digestive.Blaze.Html5\n> import Text.Digestive.Happstack\n> import Text.Digestive.Util\n\nSimple forms and validation\n---------------------------\n\nLet's start by creating a very simple datatype to represent a user:\n\n> data User = User\n>     { userName :: Text\n>     , userMail :: Text\n>     } deriving (Show)\n\nAnd dive in immediately to create a `Form` for a user. The `Form v m a` type\nhas three parameters:\n\n- `v`: the type for messages and errors (usually a `String`-like type, `Text` in\n  this case);\n- `m`: the monad we are operating in, not specified here;\n- `a`: the return type of the `Form`, in this case, this is obviously `User`.\n\n> userForm :: Monad m => Form Text m User\n\nWe create forms by using the `Applicative` interface. A few form types are\nprovided in the `Text.Digestive.Form` module, such as `text`, `string`,\n`bool`...\n\nIn the `digestive-functors` library, the developer is required to label each\nfield using the `.:` operator. This might look like a bit of a burden, but it\nallows you to do some really useful stuff, like separating the `Form` from the\nactual HTML layout.\n\n> userForm = User\n>     <$> \"name\" .: text Nothing\n>     <*> \"mail\" .: check \"Not a valid email address\" checkEmail (text Nothing)\n\nThe `check` function enables you to validate the result of a form. For example,\nwe can validate the email address with a really naive `checkEmail` function.\n\n> checkEmail :: Text -> Bool\n> checkEmail = isJust . T.find (== '@')\n\nMore validation\n---------------\n\nFor our example, we also want descriptions of Haskell libraries, and in order to\ndo that, we need package versions...\n\n> type Version = [Int]\n\nWe want to let the user input a version number such as `0.1.0.0`. This means we\nneed to validate if the input `Text` is of this form, and then we need to parse\nit to a `Version` type. Fortunately, we can do this in a single function:\n`validate` allows conversion between values, which can optionally fail.\n\n`readMaybe :: Read a => String -> Maybe a` is a utility function imported from\n`Text.Digestive.Util`.\n\n> validateVersion :: Text -> Result Text Version\n> validateVersion = maybe (Error \"Cannot parse version\") Success .\n>     mapM (readMaybe . T.unpack) . T.split (== '.')\n\nA quick test in GHCi:\n\n    ghci> validateVersion (T.pack \"0.3.2.1\")\n    Success [0,3,2,1]\n    ghci> validateVersion (T.pack \"0.oops\")\n    Error \"Cannot parse version\"\n\nIt works! This means we can now easily add a `Package` type and a `Form` for it:\n\n> data Category = Web | Text | Math\n>     deriving (Bounded, Enum, Eq, Show)\n\n> data Package = Package Text Version Category\n>     deriving (Show)\n\n> packageForm :: Monad m => Form Text m Package\n> packageForm = Package\n>     <$> \"name\"     .: text Nothing\n>     <*> \"version\"  .: validate validateVersion (text (Just \"0.0.0.1\"))\n>     <*> \"category\" .: choice categories Nothing\n>   where\n>     categories = [(x, T.pack (show x)) | x <- [minBound .. maxBound]]\n\nComposing forms\n---------------\n\nA release has an author and a package. Let's use this to illustrate the\ncomposability of the digestive-functors library: we can reuse the forms we have\nwritten earlier on.\n\n> data Release = Release User Package\n>     deriving (Show)\n\n> releaseForm :: Monad m => Form Text m Release\n> releaseForm = Release\n>     <$> \"author\"  .: userForm\n>     <*> \"package\" .: packageForm\n\nViews\n-----\n\nAs mentioned before, one of the advantages of using digestive-functors is\nseparation of forms and their actual HTML layout. In order to do this, we have\nanother type, `View`.\n\nWe can get a `View` from a `Form` by supplying input. A `View` contains more\ninformation than a `Form`, it has:\n\n- the original form;\n- the input given by the user;\n- any errors that have occurred.\n\nIt is this view that we convert to HTML. For this tutorial, we use the\n[blaze-html] library, and some helpers from the `digestive-functors-blaze`\nlibrary.\n\n[blaze-html]: http://jaspervdj.be/blaze/\n\nLet's write a view for the `User` form. As you can see, we here refer to the\ndifferent fields in the `userForm`. The `errorList` will generate a list of\nerrors for the `\"mail\"` field.\n\n> userView :: View H.Html -> H.Html\n> userView view = do\n>     label     \"name\" view \"Name: \"\n>     inputText \"name\" view\n>     H.br\n>\n>     errorList \"mail\" view\n>     label     \"mail\" view \"Email address: \"\n>     inputText \"mail\" view\n>     H.br\n\nLike forms, views are also composable: let's illustrate that by adding a view\nfor the `releaseForm`, in which we reuse `userView`. In order to do this, we\ntake only the parts relevant to the author from the view by using `subView`. We\ncan then pass the resulting view to our own `userView`.\nWe have no special view code for `Package`, so we can just add that to\n`releaseView` as well. `childErrorList` will generate a list of errors for each\nchild of the specified form. In this case, this means a list of errors from\n`\"package.name\"` and `\"package.version\"`. Note how we use `foo.bar` to refer to\nnested forms.\n\n> releaseView :: View H.Html -> H.Html\n> releaseView view = do\n>     H.h2 \"Author\"\n>     userView $ subView \"author\" view\n>\n>     H.h2 \"Package\"\n>     childErrorList \"package\" view\n>\n>     label     \"package.name\" view \"Name: \"\n>     inputText \"package.name\" view\n>     H.br\n>\n>     label     \"package.version\" view \"Version: \"\n>     inputText \"package.version\" view\n>     H.br\n>\n>     label       \"package.category\" view \"Category: \"\n>     inputSelect \"package.category\" view\n>     H.br\n\nThe attentive reader might have wondered what the type parameter for `View` is:\nit is the `String`-like type used for e.g. error messages.\nBut wait! We have\n    releaseForm :: Monad m => Form Text m Release\n    releaseView :: View H.Html -> H.Html\n... doesn't this mean that we need a `View Text` rather than a `View Html`?  The\nanswer is yes -- but having `View Html` allows us to write these views more\neasily with the `digestive-functors-blaze` library. Fortunately, we will be able\nto fix this using the `Functor` instance of `View`.\n    fmap :: Monad m => (v -> w) -> View v -> View w\nA backend\n---------\nTo finish this tutorial, we need to be able to actually run this code. We need\nan HTTP server for that, and we use [Happstack] for this tutorial. The\n`digestive-functors-happstack` library gives about everything we need for this.\n[Happstack]: http://happstack.com/\n\n> site :: Happstack.ServerPart Happstack.Response\n> site = do\n>     Happstack.decodeBody $ Happstack.defaultBodyPolicy \"/tmp\" 4096 4096 4096\n>     r <- runForm \"test\" releaseForm\n>     case r of\n>         (view, Nothing) -> do\n>             let view' = fmap H.toHtml view\n>             Happstack.ok $ Happstack.toResponse $\n>                 template $\n>                     form view' \"/\" $ do\n>                         releaseView view'\n>                         H.br\n>                         inputSubmit \"Submit\"\n>         (_, Just release) -> Happstack.ok $ Happstack.toResponse $\n>             template $ do\n>                 css\n>                 H.h1 \"Release received\"\n>                 H.p $ H.toHtml $ show release\n>\n> main :: IO ()\n> main = Happstack.simpleHTTP Happstack.nullConf site\n\nUtilities\n---------\n\n> template :: H.Html -> H.Html\n> template body = H.docTypeHtml $ do\n>     H.head $ do\n>         H.title \"digestive-functors tutorial\"\n>         css\n>     H.body body\n> css :: H.Html\n> css = H.style ! A.type_ \"text/css\" $ do\n>     \"label {width: 130px; float: left; clear: both}\"\n>     \"ul.digestive-functors-error-list {\"\n>     \"    color: red;\"\n>     \"    list-style-type: none;\"\n>     \"    padding-left: 0px;\"\n>     \"}\"\n    </textarea>\n  </form>\n\n  <p><strong>MIME types\n  defined:</strong> <code>text/x-literate-haskell</code>.</p>\n\n  <p>Parser configuration parameters recognized: <code>base</code> to\n  set the base mode (defaults to <code>\"haskell\"</code>).</p>\n\n  <script>\n    var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {mode: \"haskell-literate\"});\n  </script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/haxe/haxe.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"haxe\", function(config, parserConfig) {\n  var indentUnit = config.indentUnit;\n\n  // Tokenizer\n\n  function kw(type) {return {type: type, style: \"keyword\"};}\n  var A = kw(\"keyword a\"), B = kw(\"keyword b\"), C = kw(\"keyword c\");\n  var operator = kw(\"operator\"), atom = {type: \"atom\", style: \"atom\"}, attribute = {type:\"attribute\", style: \"attribute\"};\n  var type = kw(\"typedef\");\n  var keywords = {\n    \"if\": A, \"while\": A, \"else\": B, \"do\": B, \"try\": B,\n    \"return\": C, \"break\": C, \"continue\": C, \"new\": C, \"throw\": C,\n    \"var\": kw(\"var\"), \"inline\":attribute, \"static\": attribute, \"using\":kw(\"import\"),\n    \"public\": attribute, \"private\": attribute, \"cast\": kw(\"cast\"), \"import\": kw(\"import\"), \"macro\": kw(\"macro\"),\n    \"function\": kw(\"function\"), \"catch\": kw(\"catch\"), \"untyped\": kw(\"untyped\"), \"callback\": kw(\"cb\"),\n    \"for\": kw(\"for\"), \"switch\": kw(\"switch\"), \"case\": kw(\"case\"), \"default\": kw(\"default\"),\n    \"in\": operator, \"never\": kw(\"property_access\"), \"trace\":kw(\"trace\"),\n    \"class\": type, \"abstract\":type, \"enum\":type, \"interface\":type, \"typedef\":type, \"extends\":type, \"implements\":type, \"dynamic\":type,\n    \"true\": atom, \"false\": atom, \"null\": atom\n  };\n\n  var isOperatorChar = /[+\\-*&%=<>!?|]/;\n\n  function chain(stream, state, f) {\n    state.tokenize = f;\n    return f(stream, state);\n  }\n\n  function toUnescaped(stream, end) {\n    var escaped = false, next;\n    while ((next = stream.next()) != null) {\n      if (next == end && !escaped)\n        return true;\n      escaped = !escaped && next == \"\\\\\";\n    }\n  }\n\n  // Used as scratch variables to communicate multiple values without\n  // consing up tons of objects.\n  var type, content;\n  function ret(tp, style, cont) {\n    type = tp; content = cont;\n    return style;\n  }\n\n  function haxeTokenBase(stream, state) {\n    var ch = stream.next();\n    if (ch == '\"' || ch == \"'\") {\n      return chain(stream, state, haxeTokenString(ch));\n    } else if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n      return ret(ch);\n    } else if (ch == \"0\" && stream.eat(/x/i)) {\n      stream.eatWhile(/[\\da-f]/i);\n      return ret(\"number\", \"number\");\n    } else if (/\\d/.test(ch) || ch == \"-\" && stream.eat(/\\d/)) {\n      stream.match(/^\\d*(?:\\.\\d*(?!\\.))?(?:[eE][+\\-]?\\d+)?/);\n      return ret(\"number\", \"number\");\n    } else if (state.reAllowed && (ch == \"~\" && stream.eat(/\\//))) {\n      toUnescaped(stream, \"/\");\n      stream.eatWhile(/[gimsu]/);\n      return ret(\"regexp\", \"string-2\");\n    } else if (ch == \"/\") {\n      if (stream.eat(\"*\")) {\n        return chain(stream, state, haxeTokenComment);\n      } else if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return ret(\"comment\", \"comment\");\n      } else {\n        stream.eatWhile(isOperatorChar);\n        return ret(\"operator\", null, stream.current());\n      }\n    } else if (ch == \"#\") {\n        stream.skipToEnd();\n        return ret(\"conditional\", \"meta\");\n    } else if (ch == \"@\") {\n      stream.eat(/:/);\n      stream.eatWhile(/[\\w_]/);\n      return ret (\"metadata\", \"meta\");\n    } else if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return ret(\"operator\", null, stream.current());\n    } else {\n      var word;\n      if(/[A-Z]/.test(ch)) {\n        stream.eatWhile(/[\\w_<>]/);\n        word = stream.current();\n        return ret(\"type\", \"variable-3\", word);\n      } else {\n        stream.eatWhile(/[\\w_]/);\n        var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];\n        return (known && state.kwAllowed) ? ret(known.type, known.style, word) :\n                       ret(\"variable\", \"variable\", word);\n      }\n    }\n  }\n\n  function haxeTokenString(quote) {\n    return function(stream, state) {\n      if (toUnescaped(stream, quote))\n        state.tokenize = haxeTokenBase;\n      return ret(\"string\", \"string\");\n    };\n  }\n\n  function haxeTokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = haxeTokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return ret(\"comment\", \"comment\");\n  }\n\n  // Parser\n\n  var atomicTypes = {\"atom\": true, \"number\": true, \"variable\": true, \"string\": true, \"regexp\": true};\n\n  function HaxeLexical(indented, column, type, align, prev, info) {\n    this.indented = indented;\n    this.column = column;\n    this.type = type;\n    this.prev = prev;\n    this.info = info;\n    if (align != null) this.align = align;\n  }\n\n  function inScope(state, varname) {\n    for (var v = state.localVars; v; v = v.next)\n      if (v.name == varname) return true;\n  }\n\n  function parseHaxe(state, style, type, content, stream) {\n    var cc = state.cc;\n    // Communicate our context to the combinators.\n    // (Less wasteful than consing up a hundred closures on every call.)\n    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;\n\n    if (!state.lexical.hasOwnProperty(\"align\"))\n      state.lexical.align = true;\n\n    while(true) {\n      var combinator = cc.length ? cc.pop() : statement;\n      if (combinator(type, content)) {\n        while(cc.length && cc[cc.length - 1].lex)\n          cc.pop()();\n        if (cx.marked) return cx.marked;\n        if (type == \"variable\" && inScope(state, content)) return \"variable-2\";\n        if (type == \"variable\" && imported(state, content)) return \"variable-3\";\n        return style;\n      }\n    }\n  }\n\n  function imported(state, typename) {\n    if (/[a-z]/.test(typename.charAt(0)))\n      return false;\n    var len = state.importedtypes.length;\n    for (var i = 0; i<len; i++)\n      if(state.importedtypes[i]==typename) return true;\n  }\n\n  function registerimport(importname) {\n    var state = cx.state;\n    for (var t = state.importedtypes; t; t = t.next)\n      if(t.name == importname) return;\n    state.importedtypes = { name: importname, next: state.importedtypes };\n  }\n  // Combinator utils\n\n  var cx = {state: null, column: null, marked: null, cc: null};\n  function pass() {\n    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);\n  }\n  function cont() {\n    pass.apply(null, arguments);\n    return true;\n  }\n  function inList(name, list) {\n    for (var v = list; v; v = v.next)\n      if (v.name == name) return true;\n    return false;\n  }\n  function register(varname) {\n    var state = cx.state;\n    if (state.context) {\n      cx.marked = \"def\";\n      if (inList(varname, state.localVars)) return;\n      state.localVars = {name: varname, next: state.localVars};\n    } else if (state.globalVars) {\n      if (inList(varname, state.globalVars)) return;\n      state.globalVars = {name: varname, next: state.globalVars};\n    }\n  }\n\n  // Combinators\n\n  var defaultVars = {name: \"this\", next: null};\n  function pushcontext() {\n    if (!cx.state.context) cx.state.localVars = defaultVars;\n    cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};\n  }\n  function popcontext() {\n    cx.state.localVars = cx.state.context.vars;\n    cx.state.context = cx.state.context.prev;\n  }\n  popcontext.lex = true;\n  function pushlex(type, info) {\n    var result = function() {\n      var state = cx.state;\n      state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info);\n    };\n    result.lex = true;\n    return result;\n  }\n  function poplex() {\n    var state = cx.state;\n    if (state.lexical.prev) {\n      if (state.lexical.type == \")\")\n        state.indented = state.lexical.indented;\n      state.lexical = state.lexical.prev;\n    }\n  }\n  poplex.lex = true;\n\n  function expect(wanted) {\n    function f(type) {\n      if (type == wanted) return cont();\n      else if (wanted == \";\") return pass();\n      else return cont(f);\n    }\n    return f;\n  }\n\n  function statement(type) {\n    if (type == \"@\") return cont(metadef);\n    if (type == \"var\") return cont(pushlex(\"vardef\"), vardef1, expect(\";\"), poplex);\n    if (type == \"keyword a\") return cont(pushlex(\"form\"), expression, statement, poplex);\n    if (type == \"keyword b\") return cont(pushlex(\"form\"), statement, poplex);\n    if (type == \"{\") return cont(pushlex(\"}\"), pushcontext, block, poplex, popcontext);\n    if (type == \";\") return cont();\n    if (type == \"attribute\") return cont(maybeattribute);\n    if (type == \"function\") return cont(functiondef);\n    if (type == \"for\") return cont(pushlex(\"form\"), expect(\"(\"), pushlex(\")\"), forspec1, expect(\")\"),\n                                   poplex, statement, poplex);\n    if (type == \"variable\") return cont(pushlex(\"stat\"), maybelabel);\n    if (type == \"switch\") return cont(pushlex(\"form\"), expression, pushlex(\"}\", \"switch\"), expect(\"{\"),\n                                      block, poplex, poplex);\n    if (type == \"case\") return cont(expression, expect(\":\"));\n    if (type == \"default\") return cont(expect(\":\"));\n    if (type == \"catch\") return cont(pushlex(\"form\"), pushcontext, expect(\"(\"), funarg, expect(\")\"),\n                                     statement, poplex, popcontext);\n    if (type == \"import\") return cont(importdef, expect(\";\"));\n    if (type == \"typedef\") return cont(typedef);\n    return pass(pushlex(\"stat\"), expression, expect(\";\"), poplex);\n  }\n  function expression(type) {\n    if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);\n    if (type == \"type\" ) return cont(maybeoperator);\n    if (type == \"function\") return cont(functiondef);\n    if (type == \"keyword c\") return cont(maybeexpression);\n    if (type == \"(\") return cont(pushlex(\")\"), maybeexpression, expect(\")\"), poplex, maybeoperator);\n    if (type == \"operator\") return cont(expression);\n    if (type == \"[\") return cont(pushlex(\"]\"), commasep(maybeexpression, \"]\"), poplex, maybeoperator);\n    if (type == \"{\") return cont(pushlex(\"}\"), commasep(objprop, \"}\"), poplex, maybeoperator);\n    return cont();\n  }\n  function maybeexpression(type) {\n    if (type.match(/[;\\}\\)\\],]/)) return pass();\n    return pass(expression);\n  }\n\n  function maybeoperator(type, value) {\n    if (type == \"operator\" && /\\+\\+|--/.test(value)) return cont(maybeoperator);\n    if (type == \"operator\" || type == \":\") return cont(expression);\n    if (type == \";\") return;\n    if (type == \"(\") return cont(pushlex(\")\"), commasep(expression, \")\"), poplex, maybeoperator);\n    if (type == \".\") return cont(property, maybeoperator);\n    if (type == \"[\") return cont(pushlex(\"]\"), expression, expect(\"]\"), poplex, maybeoperator);\n  }\n\n  function maybeattribute(type) {\n    if (type == \"attribute\") return cont(maybeattribute);\n    if (type == \"function\") return cont(functiondef);\n    if (type == \"var\") return cont(vardef1);\n  }\n\n  function metadef(type) {\n    if(type == \":\") return cont(metadef);\n    if(type == \"variable\") return cont(metadef);\n    if(type == \"(\") return cont(pushlex(\")\"), commasep(metaargs, \")\"), poplex, statement);\n  }\n  function metaargs(type) {\n    if(type == \"variable\") return cont();\n  }\n\n  function importdef (type, value) {\n    if(type == \"variable\" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }\n    else if(type == \"variable\" || type == \"property\" || type == \".\" || value == \"*\") return cont(importdef);\n  }\n\n  function typedef (type, value)\n  {\n    if(type == \"variable\" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }\n    else if (type == \"type\" && /[A-Z]/.test(value.charAt(0))) { return cont(); }\n  }\n\n  function maybelabel(type) {\n    if (type == \":\") return cont(poplex, statement);\n    return pass(maybeoperator, expect(\";\"), poplex);\n  }\n  function property(type) {\n    if (type == \"variable\") {cx.marked = \"property\"; return cont();}\n  }\n  function objprop(type) {\n    if (type == \"variable\") cx.marked = \"property\";\n    if (atomicTypes.hasOwnProperty(type)) return cont(expect(\":\"), expression);\n  }\n  function commasep(what, end) {\n    function proceed(type) {\n      if (type == \",\") return cont(what, proceed);\n      if (type == end) return cont();\n      return cont(expect(end));\n    }\n    return function(type) {\n      if (type == end) return cont();\n      else return pass(what, proceed);\n    };\n  }\n  function block(type) {\n    if (type == \"}\") return cont();\n    return pass(statement, block);\n  }\n  function vardef1(type, value) {\n    if (type == \"variable\"){register(value); return cont(typeuse, vardef2);}\n    return cont();\n  }\n  function vardef2(type, value) {\n    if (value == \"=\") return cont(expression, vardef2);\n    if (type == \",\") return cont(vardef1);\n  }\n  function forspec1(type, value) {\n    if (type == \"variable\") {\n      register(value);\n      return cont(forin, expression)\n    } else {\n      return pass()\n    }\n  }\n  function forin(_type, value) {\n    if (value == \"in\") return cont();\n  }\n  function functiondef(type, value) {\n    //function names starting with upper-case letters are recognised as types, so cludging them together here.\n    if (type == \"variable\" || type == \"type\") {register(value); return cont(functiondef);}\n    if (value == \"new\") return cont(functiondef);\n    if (type == \"(\") return cont(pushlex(\")\"), pushcontext, commasep(funarg, \")\"), poplex, typeuse, statement, popcontext);\n  }\n  function typeuse(type) {\n    if(type == \":\") return cont(typestring);\n  }\n  function typestring(type) {\n    if(type == \"type\") return cont();\n    if(type == \"variable\") return cont();\n    if(type == \"{\") return cont(pushlex(\"}\"), commasep(typeprop, \"}\"), poplex);\n  }\n  function typeprop(type) {\n    if(type == \"variable\") return cont(typeuse);\n  }\n  function funarg(type, value) {\n    if (type == \"variable\") {register(value); return cont(typeuse);}\n  }\n\n  // Interface\n  return {\n    startState: function(basecolumn) {\n      var defaulttypes = [\"Int\", \"Float\", \"String\", \"Void\", \"Std\", \"Bool\", \"Dynamic\", \"Array\"];\n      var state = {\n        tokenize: haxeTokenBase,\n        reAllowed: true,\n        kwAllowed: true,\n        cc: [],\n        lexical: new HaxeLexical((basecolumn || 0) - indentUnit, 0, \"block\", false),\n        localVars: parserConfig.localVars,\n        importedtypes: defaulttypes,\n        context: parserConfig.localVars && {vars: parserConfig.localVars},\n        indented: 0\n      };\n      if (parserConfig.globalVars && typeof parserConfig.globalVars == \"object\")\n        state.globalVars = parserConfig.globalVars;\n      return state;\n    },\n\n    token: function(stream, state) {\n      if (stream.sol()) {\n        if (!state.lexical.hasOwnProperty(\"align\"))\n          state.lexical.align = false;\n        state.indented = stream.indentation();\n      }\n      if (stream.eatSpace()) return null;\n      var style = state.tokenize(stream, state);\n      if (type == \"comment\") return style;\n      state.reAllowed = !!(type == \"operator\" || type == \"keyword c\" || type.match(/^[\\[{}\\(,;:]$/));\n      state.kwAllowed = type != '.';\n      return parseHaxe(state, style, type, content, stream);\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize != haxeTokenBase) return 0;\n      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;\n      if (lexical.type == \"stat\" && firstChar == \"}\") lexical = lexical.prev;\n      var type = lexical.type, closing = firstChar == type;\n      if (type == \"vardef\") return lexical.indented + 4;\n      else if (type == \"form\" && firstChar == \"{\") return lexical.indented;\n      else if (type == \"stat\" || type == \"form\") return lexical.indented + indentUnit;\n      else if (lexical.info == \"switch\" && !closing)\n        return lexical.indented + (/^(?:case|default)\\b/.test(textAfter) ? indentUnit : 2 * indentUnit);\n      else if (lexical.align) return lexical.column + (closing ? 0 : 1);\n      else return lexical.indented + (closing ? 0 : indentUnit);\n    },\n\n    electricChars: \"{}\",\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    lineComment: \"//\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-haxe\", \"haxe\");\n\nCodeMirror.defineMode(\"hxml\", function () {\n\n  return {\n    startState: function () {\n      return {\n        define: false,\n        inString: false\n      };\n    },\n    token: function (stream, state) {\n      var ch = stream.peek();\n      var sol = stream.sol();\n\n      ///* comments */\n      if (ch == \"#\") {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n      if (sol && ch == \"-\") {\n        var style = \"variable-2\";\n\n        stream.eat(/-/);\n\n        if (stream.peek() == \"-\") {\n          stream.eat(/-/);\n          style = \"keyword a\";\n        }\n\n        if (stream.peek() == \"D\") {\n          stream.eat(/[D]/);\n          style = \"keyword c\";\n          state.define = true;\n        }\n\n        stream.eatWhile(/[A-Z]/i);\n        return style;\n      }\n\n      var ch = stream.peek();\n\n      if (state.inString == false && ch == \"'\") {\n        state.inString = true;\n        stream.next();\n      }\n\n      if (state.inString == true) {\n        if (stream.skipTo(\"'\")) {\n\n        } else {\n          stream.skipToEnd();\n        }\n\n        if (stream.peek() == \"'\") {\n          stream.next();\n          state.inString = false;\n        }\n\n        return \"string\";\n      }\n\n      stream.next();\n      return null;\n    },\n    lineComment: \"#\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-hxml\", \"hxml\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/haxe/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Haxe mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"haxe.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Haxe</a>\n  </ul>\n</div>\n\n<article>\n<h2>Haxe mode</h2>\n\n\n<div><p><textarea id=\"code-haxe\" name=\"code\">\nimport one.two.Three;\n\n@attr(\"test\")\nclass Foo&lt;T&gt; extends Three\n{\n\tpublic function new()\n\t{\n\t\tnoFoo = 12;\n\t}\n\t\n\tpublic static inline function doFoo(obj:{k:Int, l:Float}):Int\n\t{\n\t\tfor(i in 0...10)\n\t\t{\n\t\t\tobj.k++;\n\t\t\ttrace(i);\n\t\t\tvar var1 = new Array();\n\t\t\tif(var1.length > 1)\n\t\t\t\tthrow \"Error\";\n\t\t}\n\t\t// The following line should not be colored, the variable is scoped out\n\t\tvar1;\n\t\t/* Multi line\n\t\t * Comment test\n\t\t */\n\t\treturn obj.k;\n\t}\n\tprivate function bar():Void\n\t{\n\t\t#if flash\n\t\tvar t1:String = \"1.21\";\n\t\t#end\n\t\ttry {\n\t\t\tdoFoo({k:3, l:1.2});\n\t\t}\n\t\tcatch (e : String) {\n\t\t\ttrace(e);\n\t\t}\n\t\tvar t2:Float = cast(3.2);\n\t\tvar t3:haxe.Timer = new haxe.Timer();\n\t\tvar t4 = {k:Std.int(t2), l:Std.parseFloat(t1)};\n\t\tvar t5 = ~/123+.*$/i;\n\t\tdoFoo(t4);\n\t\tuntyped t1 = 4;\n\t\tbob = new Foo&lt;Int&gt;\n\t}\n\tpublic var okFoo(default, never):Float;\n\tvar noFoo(getFoo, null):Int;\n\tfunction getFoo():Int {\n\t\treturn noFoo;\n\t}\n\t\n\tpublic var three:Int;\n}\nenum Color\n{\n\tred;\n\tgreen;\n\tblue;\n\tgrey( v : Int );\n\trgb (r:Int,g:Int,b:Int);\n}\n</textarea></p>\n\n<p>Hxml mode:</p>\n\n<p><textarea id=\"code-hxml\">\n-cp test\n-js path/to/file.js\n#-remap nme:flash\n--next\n-D source-map-content\n-cmd 'test'\n-lib lime\n</textarea></p>\n</div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code-haxe\"), {\n      \tmode: \"haxe\",\n        lineNumbers: true,\n        indentUnit: 4,\n        indentWithTabs: true\n      });\n      \n      editor = CodeMirror.fromTextArea(document.getElementById(\"code-hxml\"), {\n      \tmode: \"hxml\",\n        lineNumbers: true,\n        indentUnit: 4,\n        indentWithTabs: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-haxe, text/x-hxml</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/htmlembedded/htmlembedded.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../htmlmixed/htmlmixed\"),\n        require(\"../../addon/mode/multiplex\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../htmlmixed/htmlmixed\",\n            \"../../addon/mode/multiplex\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"htmlembedded\", function(config, parserConfig) {\n    var closeComment = parserConfig.closeComment || \"--%>\"\n    return CodeMirror.multiplexingMode(CodeMirror.getMode(config, \"htmlmixed\"), {\n      open: parserConfig.openComment || \"<%--\",\n      close: closeComment,\n      delimStyle: \"comment\",\n      mode: {token: function(stream) {\n        stream.skipTo(closeComment) || stream.skipToEnd()\n        return \"comment\"\n      }}\n    }, {\n      open: parserConfig.open || parserConfig.scriptStartRegex || \"<%\",\n      close: parserConfig.close || parserConfig.scriptEndRegex || \"%>\",\n      mode: CodeMirror.getMode(config, parserConfig.scriptingModeSpec)\n    });\n  }, \"htmlmixed\");\n\n  CodeMirror.defineMIME(\"application/x-ejs\", {name: \"htmlembedded\", scriptingModeSpec:\"javascript\"});\n  CodeMirror.defineMIME(\"application/x-aspx\", {name: \"htmlembedded\", scriptingModeSpec:\"text/x-csharp\"});\n  CodeMirror.defineMIME(\"application/x-jsp\", {name: \"htmlembedded\", scriptingModeSpec:\"text/x-java\"});\n  CodeMirror.defineMIME(\"application/x-erb\", {name: \"htmlembedded\", scriptingModeSpec:\"ruby\"});\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/htmlembedded/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Html Embedded Scripts mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../css/css.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"../../addon/mode/multiplex.js\"></script>\n<script src=\"htmlembedded.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Html Embedded Scripts</a>\n  </ul>\n</div>\n\n<article>\n<h2>Html Embedded Scripts mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n<%\nfunction hello(who) {\n\treturn \"Hello \" + who;\n}\n%>\nThis is an example of EJS (embedded javascript)\n<p>The program says <%= hello(\"world\") %>.</p>\n<script>\n\talert(\"And here is some normal JS code\"); // also colored\n</script>\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"application/x-ejs\",\n        indentUnit: 4,\n        indentWithTabs: true\n      });\n    </script>\n\n    <p>Mode for html embedded scripts like JSP and ASP.NET. Depends on multiplex and HtmlMixed which in turn depends on\n    JavaScript, CSS and XML.<br />Other dependencies include those of the scripting language chosen.</p>\n\n    <p><strong>MIME types defined:</strong> <code>application/x-aspx</code> (ASP.NET),\n    <code>application/x-ejs</code> (Embedded Javascript), <code>application/x-jsp</code> (JavaServer Pages)\n    and <code>application/x-erb</code></p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/htmlmixed/htmlmixed.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../xml/xml\"), require(\"../javascript/javascript\"), require(\"../css/css\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../xml/xml\", \"../javascript/javascript\", \"../css/css\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var defaultTags = {\n    script: [\n      [\"lang\", /(javascript|babel)/i, \"javascript\"],\n      [\"type\", /^(?:text|application)\\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, \"javascript\"],\n      [\"type\", /./, \"text/plain\"],\n      [null, null, \"javascript\"]\n    ],\n    style:  [\n      [\"lang\", /^css$/i, \"css\"],\n      [\"type\", /^(text\\/)?(x-)?(stylesheet|css)$/i, \"css\"],\n      [\"type\", /./, \"text/plain\"],\n      [null, null, \"css\"]\n    ]\n  };\n\n  function maybeBackup(stream, pat, style) {\n    var cur = stream.current(), close = cur.search(pat);\n    if (close > -1) {\n      stream.backUp(cur.length - close);\n    } else if (cur.match(/<\\/?$/)) {\n      stream.backUp(cur.length);\n      if (!stream.match(pat, false)) stream.match(cur);\n    }\n    return style;\n  }\n\n  var attrRegexpCache = {};\n  function getAttrRegexp(attr) {\n    var regexp = attrRegexpCache[attr];\n    if (regexp) return regexp;\n    return attrRegexpCache[attr] = new RegExp(\"\\\\s+\" + attr + \"\\\\s*=\\\\s*('|\\\")?([^'\\\"]+)('|\\\")?\\\\s*\");\n  }\n\n  function getAttrValue(text, attr) {\n    var match = text.match(getAttrRegexp(attr))\n    return match ? /^\\s*(.*?)\\s*$/.exec(match[2])[1] : \"\"\n  }\n\n  function getTagRegexp(tagName, anchored) {\n    return new RegExp((anchored ? \"^\" : \"\") + \"<\\/\\s*\" + tagName + \"\\s*>\", \"i\");\n  }\n\n  function addTags(from, to) {\n    for (var tag in from) {\n      var dest = to[tag] || (to[tag] = []);\n      var source = from[tag];\n      for (var i = source.length - 1; i >= 0; i--)\n        dest.unshift(source[i])\n    }\n  }\n\n  function findMatchingMode(tagInfo, tagText) {\n    for (var i = 0; i < tagInfo.length; i++) {\n      var spec = tagInfo[i];\n      if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];\n    }\n  }\n\n  CodeMirror.defineMode(\"htmlmixed\", function (config, parserConfig) {\n    var htmlMode = CodeMirror.getMode(config, {\n      name: \"xml\",\n      htmlMode: true,\n      multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,\n      multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag\n    });\n\n    var tags = {};\n    var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;\n    addTags(defaultTags, tags);\n    if (configTags) addTags(configTags, tags);\n    if (configScript) for (var i = configScript.length - 1; i >= 0; i--)\n      tags.script.unshift([\"type\", configScript[i].matches, configScript[i].mode])\n\n    function html(stream, state) {\n      var style = htmlMode.token(stream, state.htmlState), tag = /\\btag\\b/.test(style), tagName\n      if (tag && !/[<>\\s\\/]/.test(stream.current()) &&\n          (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) &&\n          tags.hasOwnProperty(tagName)) {\n        state.inTag = tagName + \" \"\n      } else if (state.inTag && tag && />$/.test(stream.current())) {\n        var inTag = /^([\\S]+) (.*)/.exec(state.inTag)\n        state.inTag = null\n        var modeSpec = stream.current() == \">\" && findMatchingMode(tags[inTag[1]], inTag[2])\n        var mode = CodeMirror.getMode(config, modeSpec)\n        var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);\n        state.token = function (stream, state) {\n          if (stream.match(endTagA, false)) {\n            state.token = html;\n            state.localState = state.localMode = null;\n            return null;\n          }\n          return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));\n        };\n        state.localMode = mode;\n        state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, \"\", \"\"));\n      } else if (state.inTag) {\n        state.inTag += stream.current()\n        if (stream.eol()) state.inTag += \" \"\n      }\n      return style;\n    };\n\n    return {\n      startState: function () {\n        var state = CodeMirror.startState(htmlMode);\n        return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};\n      },\n\n      copyState: function (state) {\n        var local;\n        if (state.localState) {\n          local = CodeMirror.copyState(state.localMode, state.localState);\n        }\n        return {token: state.token, inTag: state.inTag,\n                localMode: state.localMode, localState: local,\n                htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};\n      },\n\n      token: function (stream, state) {\n        return state.token(stream, state);\n      },\n\n      indent: function (state, textAfter, line) {\n        if (!state.localMode || /^\\s*<\\//.test(textAfter))\n          return htmlMode.indent(state.htmlState, textAfter, line);\n        else if (state.localMode.indent)\n          return state.localMode.indent(state.localState, textAfter, line);\n        else\n          return CodeMirror.Pass;\n      },\n\n      innerMode: function (state) {\n        return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};\n      }\n    };\n  }, \"xml\", \"javascript\", \"css\");\n\n  CodeMirror.defineMIME(\"text/html\", \"htmlmixed\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/htmlmixed/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: HTML mixed mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/selection/selection-pointer.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../css/css.js\"></script>\n<script src=\"../vbscript/vbscript.js\"></script>\n<script src=\"htmlmixed.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">HTML mixed</a>\n  </ul>\n</div>\n\n<article>\n<h2>HTML mixed mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n<html style=\"color: green\">\n  <!-- this is a comment -->\n  <head>\n    <title>Mixed HTML Example</title>\n    <style>\n      h1 {font-family: comic sans; color: #f0f;}\n      div {background: yellow !important;}\n      body {\n        max-width: 50em;\n        margin: 1em 2em 1em 5em;\n      }\n    </style>\n  </head>\n  <body>\n    <h1>Mixed HTML Example</h1>\n    <script>\n      function jsFunc(arg1, arg2) {\n        if (arg1 && arg2) document.body.innerHTML = \"achoo\";\n      }\n    </script>\n  </body>\n</html>\n</textarea></form>\n    <script>\n      // Define an extended mixed-mode that understands vbscript and\n      // leaves mustache/handlebars embedded templates in html mode\n      var mixedMode = {\n        name: \"htmlmixed\",\n        scriptTypes: [{matches: /\\/x-handlebars-template|\\/x-mustache/i,\n                       mode: null},\n                      {matches: /(text|application)\\/(x-)?vb(a|script)/i,\n                       mode: \"vbscript\"}]\n      };\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: mixedMode,\n        selectionPointer: true\n      });\n    </script>\n\n    <p>The HTML mixed mode depends on the XML, JavaScript, and CSS modes.</p>\n\n    <p>It takes an optional mode configuration\n    option, <code>tags</code>, which can be used to add custom\n    behavior for specific tags. When given, it should be an object\n    mapping tag names (for example <code>script</code>) to arrays or\n    three-element arrays. Those inner arrays indicate [attributeName,\n    valueRegexp, <a href=\"../../doc/manual.html#option_mode\">modeSpec</a>]\n    specifications. For example, you could use <code>[\"type\", /^foo$/,\n    \"foo\"]</code> to map the attribute <code>type=\"foo\"</code> to\n    the <code>foo</code> mode. When the first two fields are null\n    (<code>[null, null, \"mode\"]</code>), the given mode is used for\n    any such tag that doesn't match any of the previously given\n    attributes. For example:</p>\n\n    <pre>var myModeSpec = {\n  name: \"htmlmixed\",\n  tags: {\n    style: [[\"type\", /^text\\/(x-)?scss$/, \"text/x-scss\"],\n            [null, null, \"css\"]],\n    custom: [[null, null, \"customMode\"]]\n  }\n}</pre>\n\n    <p><strong>MIME types defined:</strong> <code>text/html</code>\n    (redefined, only takes effect if you load this parser after the\n    XML parser).</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/http/http.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"http\", function() {\n  function failFirstLine(stream, state) {\n    stream.skipToEnd();\n    state.cur = header;\n    return \"error\";\n  }\n\n  function start(stream, state) {\n    if (stream.match(/^HTTP\\/\\d\\.\\d/)) {\n      state.cur = responseStatusCode;\n      return \"keyword\";\n    } else if (stream.match(/^[A-Z]+/) && /[ \\t]/.test(stream.peek())) {\n      state.cur = requestPath;\n      return \"keyword\";\n    } else {\n      return failFirstLine(stream, state);\n    }\n  }\n\n  function responseStatusCode(stream, state) {\n    var code = stream.match(/^\\d+/);\n    if (!code) return failFirstLine(stream, state);\n\n    state.cur = responseStatusText;\n    var status = Number(code[0]);\n    if (status >= 100 && status < 200) {\n      return \"positive informational\";\n    } else if (status >= 200 && status < 300) {\n      return \"positive success\";\n    } else if (status >= 300 && status < 400) {\n      return \"positive redirect\";\n    } else if (status >= 400 && status < 500) {\n      return \"negative client-error\";\n    } else if (status >= 500 && status < 600) {\n      return \"negative server-error\";\n    } else {\n      return \"error\";\n    }\n  }\n\n  function responseStatusText(stream, state) {\n    stream.skipToEnd();\n    state.cur = header;\n    return null;\n  }\n\n  function requestPath(stream, state) {\n    stream.eatWhile(/\\S/);\n    state.cur = requestProtocol;\n    return \"string-2\";\n  }\n\n  function requestProtocol(stream, state) {\n    if (stream.match(/^HTTP\\/\\d\\.\\d$/)) {\n      state.cur = header;\n      return \"keyword\";\n    } else {\n      return failFirstLine(stream, state);\n    }\n  }\n\n  function header(stream) {\n    if (stream.sol() && !stream.eat(/[ \\t]/)) {\n      if (stream.match(/^.*?:/)) {\n        return \"atom\";\n      } else {\n        stream.skipToEnd();\n        return \"error\";\n      }\n    } else {\n      stream.skipToEnd();\n      return \"string\";\n    }\n  }\n\n  function body(stream) {\n    stream.skipToEnd();\n    return null;\n  }\n\n  return {\n    token: function(stream, state) {\n      var cur = state.cur;\n      if (cur != header && cur != body && stream.eatSpace()) return null;\n      return cur(stream, state);\n    },\n\n    blankLine: function(state) {\n      state.cur = body;\n    },\n\n    startState: function() {\n      return {cur: start};\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"message/http\", \"http\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/http/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: HTTP mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"http.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">HTTP</a>\n  </ul>\n</div>\n\n<article>\n<h2>HTTP mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\nPOST /somewhere HTTP/1.1\nHost: example.com\nIf-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT\nContent-Type: application/x-www-form-urlencoded;\n\tcharset=utf-8\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Ubuntu/12.04 Chromium/20.0.1132.47 Chrome/20.0.1132.47 Safari/536.11\n\nThis is the request body!\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>message/http</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/idl/idl.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function wordRegexp(words) {\n    return new RegExp('^((' + words.join(')|(') + '))\\\\b', 'i');\n  };\n\n  var builtinArray = [\n    'a_correlate', 'abs', 'acos', 'adapt_hist_equal', 'alog',\n    'alog2', 'alog10', 'amoeba', 'annotate', 'app_user_dir',\n    'app_user_dir_query', 'arg_present', 'array_equal', 'array_indices',\n    'arrow', 'ascii_template', 'asin', 'assoc', 'atan',\n    'axis', 'axis', 'bandpass_filter', 'bandreject_filter', 'barplot',\n    'bar_plot', 'beseli', 'beselj', 'beselk', 'besely',\n    'beta', 'biginteger', 'bilinear', 'bin_date', 'binary_template',\n    'bindgen', 'binomial', 'bit_ffs', 'bit_population', 'blas_axpy',\n    'blk_con', 'boolarr', 'boolean', 'boxplot', 'box_cursor',\n    'breakpoint', 'broyden', 'bubbleplot', 'butterworth', 'bytarr',\n    'byte', 'byteorder', 'bytscl', 'c_correlate', 'calendar',\n    'caldat', 'call_external', 'call_function', 'call_method',\n    'call_procedure', 'canny', 'catch', 'cd', 'cdf', 'ceil',\n    'chebyshev', 'check_math', 'chisqr_cvf', 'chisqr_pdf', 'choldc',\n    'cholsol', 'cindgen', 'cir_3pnt', 'clipboard', 'close',\n    'clust_wts', 'cluster', 'cluster_tree', 'cmyk_convert', 'code_coverage',\n    'color_convert', 'color_exchange', 'color_quan', 'color_range_map',\n    'colorbar', 'colorize_sample', 'colormap_applicable',\n    'colormap_gradient', 'colormap_rotation', 'colortable',\n    'comfit', 'command_line_args', 'common', 'compile_opt', 'complex',\n    'complexarr', 'complexround', 'compute_mesh_normals', 'cond', 'congrid',\n    'conj', 'constrained_min', 'contour', 'contour', 'convert_coord',\n    'convol', 'convol_fft', 'coord2to3', 'copy_lun', 'correlate',\n    'cos', 'cosh', 'cpu', 'cramer', 'createboxplotdata',\n    'create_cursor', 'create_struct', 'create_view', 'crossp', 'crvlength',\n    'ct_luminance', 'cti_test', 'cursor', 'curvefit', 'cv_coord',\n    'cvttobm', 'cw_animate', 'cw_animate_getp', 'cw_animate_load',\n    'cw_animate_run', 'cw_arcball', 'cw_bgroup', 'cw_clr_index',\n    'cw_colorsel', 'cw_defroi', 'cw_field', 'cw_filesel', 'cw_form',\n    'cw_fslider', 'cw_light_editor', 'cw_light_editor_get',\n    'cw_light_editor_set', 'cw_orient', 'cw_palette_editor',\n    'cw_palette_editor_get', 'cw_palette_editor_set', 'cw_pdmenu',\n    'cw_rgbslider', 'cw_tmpl', 'cw_zoom', 'db_exists',\n    'dblarr', 'dcindgen', 'dcomplex', 'dcomplexarr', 'define_key',\n    'define_msgblk', 'define_msgblk_from_file', 'defroi', 'defsysv',\n    'delvar', 'dendro_plot', 'dendrogram', 'deriv', 'derivsig',\n    'determ', 'device', 'dfpmin', 'diag_matrix', 'dialog_dbconnect',\n    'dialog_message', 'dialog_pickfile', 'dialog_printersetup',\n    'dialog_printjob', 'dialog_read_image',\n    'dialog_write_image', 'dictionary', 'digital_filter', 'dilate', 'dindgen',\n    'dissolve', 'dist', 'distance_measure', 'dlm_load', 'dlm_register',\n    'doc_library', 'double', 'draw_roi', 'edge_dog', 'efont',\n    'eigenql', 'eigenvec', 'ellipse', 'elmhes', 'emboss',\n    'empty', 'enable_sysrtn', 'eof', 'eos', 'erase',\n    'erf', 'erfc', 'erfcx', 'erode', 'errorplot',\n    'errplot', 'estimator_filter', 'execute', 'exit', 'exp',\n    'expand', 'expand_path', 'expint', 'extrac', 'extract_slice',\n    'f_cvf', 'f_pdf', 'factorial', 'fft', 'file_basename',\n    'file_chmod', 'file_copy', 'file_delete', 'file_dirname',\n    'file_expand_path', 'file_gunzip', 'file_gzip', 'file_info',\n    'file_lines', 'file_link', 'file_mkdir', 'file_move',\n    'file_poll_input', 'file_readlink', 'file_same',\n    'file_search', 'file_tar', 'file_test', 'file_untar', 'file_unzip',\n    'file_which', 'file_zip', 'filepath', 'findgen', 'finite',\n    'fix', 'flick', 'float', 'floor', 'flow3',\n    'fltarr', 'flush', 'format_axis_values', 'forward_function', 'free_lun',\n    'fstat', 'fulstr', 'funct', 'function', 'fv_test',\n    'fx_root', 'fz_roots', 'gamma', 'gamma_ct', 'gauss_cvf',\n    'gauss_pdf', 'gauss_smooth', 'gauss2dfit', 'gaussfit',\n    'gaussian_function', 'gaussint', 'get_drive_list', 'get_dxf_objects',\n    'get_kbrd', 'get_login_info',\n    'get_lun', 'get_screen_size', 'getenv', 'getwindows', 'greg2jul',\n    'grib', 'grid_input', 'grid_tps', 'grid3', 'griddata',\n    'gs_iter', 'h_eq_ct', 'h_eq_int', 'hanning', 'hash',\n    'hdf', 'hdf5', 'heap_free', 'heap_gc', 'heap_nosave',\n    'heap_refcount', 'heap_save', 'help', 'hilbert', 'hist_2d',\n    'hist_equal', 'histogram', 'hls', 'hough', 'hqr',\n    'hsv', 'i18n_multibytetoutf8',\n    'i18n_multibytetowidechar', 'i18n_utf8tomultibyte',\n    'i18n_widechartomultibyte',\n    'ibeta', 'icontour', 'iconvertcoord', 'idelete', 'identity',\n    'idl_base64', 'idl_container', 'idl_validname',\n    'idlexbr_assistant', 'idlitsys_createtool',\n    'idlunit', 'iellipse', 'igamma', 'igetcurrent', 'igetdata',\n    'igetid', 'igetproperty', 'iimage', 'image', 'image_cont',\n    'image_statistics', 'image_threshold', 'imaginary', 'imap', 'indgen',\n    'int_2d', 'int_3d', 'int_tabulated', 'intarr', 'interpol',\n    'interpolate', 'interval_volume', 'invert', 'ioctl', 'iopen',\n    'ir_filter', 'iplot', 'ipolygon', 'ipolyline', 'iputdata',\n    'iregister', 'ireset', 'iresolve', 'irotate', 'isa',\n    'isave', 'iscale', 'isetcurrent', 'isetproperty', 'ishft',\n    'isocontour', 'isosurface', 'isurface', 'itext', 'itranslate',\n    'ivector', 'ivolume', 'izoom', 'journal', 'json_parse',\n    'json_serialize', 'jul2greg', 'julday', 'keyword_set', 'krig2d',\n    'kurtosis', 'kw_test', 'l64indgen', 'la_choldc', 'la_cholmprove',\n    'la_cholsol', 'la_determ', 'la_eigenproblem', 'la_eigenql', 'la_eigenvec',\n    'la_elmhes', 'la_gm_linear_model', 'la_hqr', 'la_invert',\n    'la_least_square_equality', 'la_least_squares', 'la_linear_equation',\n    'la_ludc', 'la_lumprove', 'la_lusol',\n    'la_svd', 'la_tridc', 'la_trimprove', 'la_triql', 'la_trired',\n    'la_trisol', 'label_date', 'label_region', 'ladfit', 'laguerre',\n    'lambda', 'lambdap', 'lambertw', 'laplacian', 'least_squares_filter',\n    'leefilt', 'legend', 'legendre', 'linbcg', 'lindgen',\n    'linfit', 'linkimage', 'list', 'll_arc_distance', 'lmfit',\n    'lmgr', 'lngamma', 'lnp_test', 'loadct', 'locale_get',\n    'logical_and', 'logical_or', 'logical_true', 'lon64arr', 'lonarr',\n    'long', 'long64', 'lsode', 'lu_complex', 'ludc',\n    'lumprove', 'lusol', 'm_correlate', 'machar', 'make_array',\n    'make_dll', 'make_rt', 'map', 'mapcontinents', 'mapgrid',\n    'map_2points', 'map_continents', 'map_grid', 'map_image', 'map_patch',\n    'map_proj_forward', 'map_proj_image', 'map_proj_info',\n    'map_proj_init', 'map_proj_inverse',\n    'map_set', 'matrix_multiply', 'matrix_power', 'max', 'md_test',\n    'mean', 'meanabsdev', 'mean_filter', 'median', 'memory',\n    'mesh_clip', 'mesh_decimate', 'mesh_issolid',\n    'mesh_merge', 'mesh_numtriangles',\n    'mesh_obj', 'mesh_smooth', 'mesh_surfacearea',\n    'mesh_validate', 'mesh_volume',\n    'message', 'min', 'min_curve_surf', 'mk_html_help', 'modifyct',\n    'moment', 'morph_close', 'morph_distance',\n    'morph_gradient', 'morph_hitormiss',\n    'morph_open', 'morph_thin', 'morph_tophat', 'multi', 'n_elements',\n    'n_params', 'n_tags', 'ncdf', 'newton', 'noise_hurl',\n    'noise_pick', 'noise_scatter', 'noise_slur', 'norm', 'obj_class',\n    'obj_destroy', 'obj_hasmethod', 'obj_isa', 'obj_new', 'obj_valid',\n    'objarr', 'on_error', 'on_ioerror', 'online_help', 'openr',\n    'openu', 'openw', 'oplot', 'oploterr', 'orderedhash',\n    'p_correlate', 'parse_url', 'particle_trace', 'path_cache', 'path_sep',\n    'pcomp', 'plot', 'plot3d', 'plot', 'plot_3dbox',\n    'plot_field', 'ploterr', 'plots', 'polar_contour', 'polar_surface',\n    'polyfill', 'polyshade', 'pnt_line', 'point_lun', 'polarplot',\n    'poly', 'poly_2d', 'poly_area', 'poly_fit', 'polyfillv',\n    'polygon', 'polyline', 'polywarp', 'popd', 'powell',\n    'pref_commit', 'pref_get', 'pref_set', 'prewitt', 'primes',\n    'print', 'printf', 'printd', 'pro', 'product',\n    'profile', 'profiler', 'profiles', 'project_vol', 'ps_show_fonts',\n    'psafm', 'pseudo', 'ptr_free', 'ptr_new', 'ptr_valid',\n    'ptrarr', 'pushd', 'qgrid3', 'qhull', 'qromb',\n    'qromo', 'qsimp', 'query_*', 'query_ascii', 'query_bmp',\n    'query_csv', 'query_dicom', 'query_gif', 'query_image', 'query_jpeg',\n    'query_jpeg2000', 'query_mrsid', 'query_pict', 'query_png', 'query_ppm',\n    'query_srf', 'query_tiff', 'query_video', 'query_wav', 'r_correlate',\n    'r_test', 'radon', 'randomn', 'randomu', 'ranks',\n    'rdpix', 'read', 'readf', 'read_ascii', 'read_binary',\n    'read_bmp', 'read_csv', 'read_dicom', 'read_gif', 'read_image',\n    'read_interfile', 'read_jpeg', 'read_jpeg2000', 'read_mrsid', 'read_pict',\n    'read_png', 'read_ppm', 'read_spr', 'read_srf', 'read_sylk',\n    'read_tiff', 'read_video', 'read_wav', 'read_wave', 'read_x11_bitmap',\n    'read_xwd', 'reads', 'readu', 'real_part', 'rebin',\n    'recall_commands', 'recon3', 'reduce_colors', 'reform', 'region_grow',\n    'register_cursor', 'regress', 'replicate',\n    'replicate_inplace', 'resolve_all',\n    'resolve_routine', 'restore', 'retall', 'return', 'reverse',\n    'rk4', 'roberts', 'rot', 'rotate', 'round',\n    'routine_filepath', 'routine_info', 'rs_test', 's_test', 'save',\n    'savgol', 'scale3', 'scale3d', 'scatterplot', 'scatterplot3d',\n    'scope_level', 'scope_traceback', 'scope_varfetch',\n    'scope_varname', 'search2d',\n    'search3d', 'sem_create', 'sem_delete', 'sem_lock', 'sem_release',\n    'set_plot', 'set_shading', 'setenv', 'sfit', 'shade_surf',\n    'shade_surf_irr', 'shade_volume', 'shift', 'shift_diff', 'shmdebug',\n    'shmmap', 'shmunmap', 'shmvar', 'show3', 'showfont',\n    'signum', 'simplex', 'sin', 'sindgen', 'sinh',\n    'size', 'skewness', 'skip_lun', 'slicer3', 'slide_image',\n    'smooth', 'sobel', 'socket', 'sort', 'spawn',\n    'sph_4pnt', 'sph_scat', 'spher_harm', 'spl_init', 'spl_interp',\n    'spline', 'spline_p', 'sprsab', 'sprsax', 'sprsin',\n    'sprstp', 'sqrt', 'standardize', 'stddev', 'stop',\n    'strarr', 'strcmp', 'strcompress', 'streamline', 'streamline',\n    'stregex', 'stretch', 'string', 'strjoin', 'strlen',\n    'strlowcase', 'strmatch', 'strmessage', 'strmid', 'strpos',\n    'strput', 'strsplit', 'strtrim', 'struct_assign', 'struct_hide',\n    'strupcase', 'surface', 'surface', 'surfr', 'svdc',\n    'svdfit', 'svsol', 'swap_endian', 'swap_endian_inplace', 'symbol',\n    'systime', 't_cvf', 't_pdf', 't3d', 'tag_names',\n    'tan', 'tanh', 'tek_color', 'temporary', 'terminal_size',\n    'tetra_clip', 'tetra_surface', 'tetra_volume', 'text', 'thin',\n    'thread', 'threed', 'tic', 'time_test2', 'timegen',\n    'timer', 'timestamp', 'timestamptovalues', 'tm_test', 'toc',\n    'total', 'trace', 'transpose', 'tri_surf', 'triangulate',\n    'trigrid', 'triql', 'trired', 'trisol', 'truncate_lun',\n    'ts_coef', 'ts_diff', 'ts_fcast', 'ts_smooth', 'tv',\n    'tvcrs', 'tvlct', 'tvrd', 'tvscl', 'typename',\n    'uindgen', 'uint', 'uintarr', 'ul64indgen', 'ulindgen',\n    'ulon64arr', 'ulonarr', 'ulong', 'ulong64', 'uniq',\n    'unsharp_mask', 'usersym', 'value_locate', 'variance', 'vector',\n    'vector_field', 'vel', 'velovect', 'vert_t3d', 'voigt',\n    'volume', 'voronoi', 'voxel_proj', 'wait', 'warp_tri',\n    'watershed', 'wdelete', 'wf_draw', 'where', 'widget_base',\n    'widget_button', 'widget_combobox', 'widget_control',\n    'widget_displaycontextmenu', 'widget_draw',\n    'widget_droplist', 'widget_event', 'widget_info',\n    'widget_label', 'widget_list',\n    'widget_propertysheet', 'widget_slider', 'widget_tab',\n    'widget_table', 'widget_text',\n    'widget_tree', 'widget_tree_move', 'widget_window',\n    'wiener_filter', 'window',\n    'window', 'write_bmp', 'write_csv', 'write_gif', 'write_image',\n    'write_jpeg', 'write_jpeg2000', 'write_nrif', 'write_pict', 'write_png',\n    'write_ppm', 'write_spr', 'write_srf', 'write_sylk', 'write_tiff',\n    'write_video', 'write_wav', 'write_wave', 'writeu', 'wset',\n    'wshow', 'wtn', 'wv_applet', 'wv_cwt', 'wv_cw_wavelet',\n    'wv_denoise', 'wv_dwt', 'wv_fn_coiflet',\n    'wv_fn_daubechies', 'wv_fn_gaussian',\n    'wv_fn_haar', 'wv_fn_morlet', 'wv_fn_paul',\n    'wv_fn_symlet', 'wv_import_data',\n    'wv_import_wavelet', 'wv_plot3d_wps', 'wv_plot_multires',\n    'wv_pwt', 'wv_tool_denoise',\n    'xbm_edit', 'xdisplayfile', 'xdxf', 'xfont', 'xinteranimate',\n    'xloadct', 'xmanager', 'xmng_tmpl', 'xmtool', 'xobjview',\n    'xobjview_rotate', 'xobjview_write_image',\n    'xpalette', 'xpcolor', 'xplot3d',\n    'xregistered', 'xroi', 'xsq_test', 'xsurface', 'xvaredit',\n    'xvolume', 'xvolume_rotate', 'xvolume_write_image',\n    'xyouts', 'zlib_compress', 'zlib_uncompress', 'zoom', 'zoom_24'\n  ];\n  var builtins = wordRegexp(builtinArray);\n\n  var keywordArray = [\n    'begin', 'end', 'endcase', 'endfor',\n    'endwhile', 'endif', 'endrep', 'endforeach',\n    'break', 'case', 'continue', 'for',\n    'foreach', 'goto', 'if', 'then', 'else',\n    'repeat', 'until', 'switch', 'while',\n    'do', 'pro', 'function'\n  ];\n  var keywords = wordRegexp(keywordArray);\n\n  CodeMirror.registerHelper(\"hintWords\", \"idl\", builtinArray.concat(keywordArray));\n\n  var identifiers = new RegExp('^[_a-z\\xa1-\\uffff][_a-z0-9\\xa1-\\uffff]*', 'i');\n\n  var singleOperators = /[+\\-*&=<>\\/@#~$]/;\n  var boolOperators = new RegExp('(and|or|eq|lt|le|gt|ge|ne|not)', 'i');\n\n  function tokenBase(stream) {\n    // whitespaces\n    if (stream.eatSpace()) return null;\n\n    // Handle one line Comments\n    if (stream.match(';')) {\n      stream.skipToEnd();\n      return 'comment';\n    }\n\n    // Handle Number Literals\n    if (stream.match(/^[0-9\\.+-]/, false)) {\n      if (stream.match(/^[+-]?0x[0-9a-fA-F]+/))\n        return 'number';\n      if (stream.match(/^[+-]?\\d*\\.\\d+([EeDd][+-]?\\d+)?/))\n        return 'number';\n      if (stream.match(/^[+-]?\\d+([EeDd][+-]?\\d+)?/))\n        return 'number';\n    }\n\n    // Handle Strings\n    if (stream.match(/^\"([^\"]|(\"\"))*\"/)) { return 'string'; }\n    if (stream.match(/^'([^']|(''))*'/)) { return 'string'; }\n\n    // Handle words\n    if (stream.match(keywords)) { return 'keyword'; }\n    if (stream.match(builtins)) { return 'builtin'; }\n    if (stream.match(identifiers)) { return 'variable'; }\n\n    if (stream.match(singleOperators) || stream.match(boolOperators)) {\n      return 'operator'; }\n\n    // Handle non-detected items\n    stream.next();\n    return null;\n  };\n\n  CodeMirror.defineMode('idl', function() {\n    return {\n      token: function(stream) {\n        return tokenBase(stream);\n      }\n    };\n  });\n\n  CodeMirror.defineMIME('text/x-idl', 'idl');\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/idl/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: IDL mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"idl.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">IDL</a>\n  </ul>\n</div>\n\n<article>\n<h2>IDL mode</h2>\n\n    <div><textarea id=\"code\" name=\"code\">\n;; Example IDL code\nFUNCTION mean_and_stddev,array\n  ;; This program reads in an array of numbers\n  ;; and returns a structure containing the\n  ;; average and standard deviation\n\n  ave = 0.0\n  count = 0.0\n\n  for i=0,N_ELEMENTS(array)-1 do begin\n      ave = ave + array[i]\n      count = count + 1\n  endfor\n  \n  ave = ave/count\n\n  std = stddev(array)  \n\n  return, {average:ave,std:std}\n\nEND\n\n    </textarea></div>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"idl\",\n               version: 1,\n               singleLineStringErrors: false},\n        lineNumbers: true,\n        indentUnit: 4,\n        matchBrackets: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-idl</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Language Modes</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Language modes</a>\n  </ul>\n</div>\n\n<article>\n\n  <h2>Language modes</h2>\n\n  <p>This is a list of every mode in the distribution. Each mode lives\nin a subdirectory of the <code>mode/</code> directory, and typically\ndefines a single JavaScript file that implements the mode. Loading\nsuch file will make the language available to CodeMirror, through\nthe <a href=\"../doc/manual.html#option_mode\"><code>mode</code></a>\noption.</p>\n\n  <div style=\"-webkit-columns: 100px 2; -moz-columns: 100px 2; columns: 100px 2;\">\n    <ul style=\"margin-top: 0\">\n      <li><a href=\"apl/index.html\">APL</a></li>\n      <li><a href=\"asn.1/index.html\">ASN.1</a></li>\n      <li><a href=\"asterisk/index.html\">Asterisk dialplan</a></li>\n      <li><a href=\"brainfuck/index.html\">Brainfuck</a></li>\n      <li><a href=\"clike/index.html\">C, C++, C#</a></li>\n      <li><a href=\"clike/index.html\">Ceylon</a></li>\n      <li><a href=\"clojure/index.html\">Clojure</a></li>\n      <li><a href=\"css/gss.html\">Closure Stylesheets (GSS)</a></li>\n      <li><a href=\"cmake/index.html\">CMake</a></li>\n      <li><a href=\"cobol/index.html\">COBOL</a></li>\n      <li><a href=\"coffeescript/index.html\">CoffeeScript</a></li>\n      <li><a href=\"commonlisp/index.html\">Common Lisp</a></li>\n      <li><a href=\"crystal/index.html\">Crystal</a></li>\n      <li><a href=\"css/index.html\">CSS</a></li>\n      <li><a href=\"cypher/index.html\">Cypher</a></li>\n      <li><a href=\"python/index.html\">Cython</a></li>\n      <li><a href=\"d/index.html\">D</a></li>\n      <li><a href=\"dart/index.html\">Dart</a></li>\n      <li><a href=\"django/index.html\">Django</a> (templating language)</li>\n      <li><a href=\"dockerfile/index.html\">Dockerfile</a></li>\n      <li><a href=\"diff/index.html\">diff</a></li>\n      <li><a href=\"dtd/index.html\">DTD</a></li>\n      <li><a href=\"dylan/index.html\">Dylan</a></li>\n      <li><a href=\"ebnf/index.html\">EBNF</a></li>\n      <li><a href=\"ecl/index.html\">ECL</a></li>\n      <li><a href=\"eiffel/index.html\">Eiffel</a></li>\n      <li><a href=\"https://github.com/optick/codemirror-mode-elixir\">Elixir</a></li>\n      <li><a href=\"elm/index.html\">Elm</a></li>\n      <li><a href=\"erlang/index.html\">Erlang</a></li>\n      <li><a href=\"factor/index.html\">Factor</a></li>\n      <li><a href=\"fcl/index.html\">FCL</a></li>\n      <li><a href=\"forth/index.html\">Forth</a></li>\n      <li><a href=\"fortran/index.html\">Fortran</a></li>\n      <li><a href=\"mllike/index.html\">F#</a></li>\n      <li><a href=\"gas/index.html\">Gas</a> (AT&amp;T-style assembly)</li>\n      <li><a href=\"gherkin/index.html\">Gherkin</a></li>\n      <li><a href=\"go/index.html\">Go</a></li>\n      <li><a href=\"groovy/index.html\">Groovy</a></li>\n      <li><a href=\"haml/index.html\">HAML</a></li>\n      <li><a href=\"handlebars/index.html\">Handlebars</a></li>\n      <li><a href=\"haskell/index.html\">Haskell</a> (<a href=\"haskell-literate/index.html\">Literate</a>)</li>\n      <li><a href=\"haxe/index.html\">Haxe</a></li>\n      <li><a href=\"htmlembedded/index.html\">HTML embedded</a> (JSP, ASP.NET)</li>\n      <li><a href=\"htmlmixed/index.html\">HTML mixed-mode</a></li>\n      <li><a href=\"http/index.html\">HTTP</a></li>\n      <li><a href=\"idl/index.html\">IDL</a></li>\n      <li><a href=\"clike/index.html\">Java</a></li>\n      <li><a href=\"javascript/index.html\">JavaScript</a> (<a href=\"jsx/index.html\">JSX</a>)</li>\n      <li><a href=\"jinja2/index.html\">Jinja2</a></li>\n      <li><a href=\"julia/index.html\">Julia</a></li>\n      <li><a href=\"clike/index.html\">Kotlin</a></li>\n      <li><a href=\"css/less.html\">LESS</a></li>\n      <li><a href=\"livescript/index.html\">LiveScript</a></li>\n      <li><a href=\"lua/index.html\">Lua</a></li>\n      <li><a href=\"markdown/index.html\">Markdown</a> (<a href=\"gfm/index.html\">GitHub-flavour</a>)</li>\n      <li><a href=\"mathematica/index.html\">Mathematica</a></li>\n      <li><a href=\"mbox/index.html\">mbox</a></li>\n      <li><a href=\"mirc/index.html\">mIRC</a></li>\n      <li><a href=\"modelica/index.html\">Modelica</a></li>\n      <li><a href=\"mscgen/index.html\">MscGen</a></li>\n      <li><a href=\"mumps/index.html\">MUMPS</a></li>\n      <li><a href=\"nginx/index.html\">Nginx</a></li>\n      <li><a href=\"nsis/index.html\">NSIS</a></li>\n      <li><a href=\"ntriples/index.html\">N-Triples/N-Quads</a></li>\n      <li><a href=\"clike/index.html\">Objective C</a></li>\n      <li><a href=\"mllike/index.html\">OCaml</a></li>\n      <li><a href=\"octave/index.html\">Octave</a> (MATLAB)</li>\n      <li><a href=\"oz/index.html\">Oz</a></li>\n      <li><a href=\"pascal/index.html\">Pascal</a></li>\n      <li><a href=\"pegjs/index.html\">PEG.js</a></li>\n      <li><a href=\"perl/index.html\">Perl</a></li>\n      <li><a href=\"asciiarmor/index.html\">PGP (ASCII armor)</a></li>\n      <li><a href=\"php/index.html\">PHP</a></li>\n      <li><a href=\"pig/index.html\">Pig Latin</a></li>\n      <li><a href=\"powershell/index.html\">PowerShell</a></li>\n      <li><a href=\"properties/index.html\">Properties files</a></li>\n      <li><a href=\"protobuf/index.html\">ProtoBuf</a></li>\n      <li><a href=\"pug/index.html\">Pug</a></li>\n      <li><a href=\"puppet/index.html\">Puppet</a></li>\n      <li><a href=\"python/index.html\">Python</a></li>\n      <li><a href=\"q/index.html\">Q</a></li>\n      <li><a href=\"r/index.html\">R</a></li>\n      <li><a href=\"rpm/index.html\">RPM</a></li>\n      <li><a href=\"rst/index.html\">reStructuredText</a></li>\n      <li><a href=\"ruby/index.html\">Ruby</a></li>\n      <li><a href=\"rust/index.html\">Rust</a></li>\n      <li><a href=\"sas/index.html\">SAS</a></li>\n      <li><a href=\"sass/index.html\">Sass</a></li>\n      <li><a href=\"spreadsheet/index.html\">Spreadsheet</a></li>\n      <li><a href=\"clike/scala.html\">Scala</a></li>\n      <li><a href=\"scheme/index.html\">Scheme</a></li>\n      <li><a href=\"css/scss.html\">SCSS</a></li>\n      <li><a href=\"shell/index.html\">Shell</a></li>\n      <li><a href=\"sieve/index.html\">Sieve</a></li>\n      <li><a href=\"slim/index.html\">Slim</a></li>\n      <li><a href=\"smalltalk/index.html\">Smalltalk</a></li>\n      <li><a href=\"smarty/index.html\">Smarty</a></li>\n      <li><a href=\"solr/index.html\">Solr</a></li>\n      <li><a href=\"soy/index.html\">Soy</a></li>\n      <li><a href=\"stylus/index.html\">Stylus</a></li>\n      <li><a href=\"sql/index.html\">SQL</a> (several dialects)</li>\n      <li><a href=\"sparql/index.html\">SPARQL</a></li>\n      <li><a href=\"clike/index.html\">Squirrel</a></li>\n      <li><a href=\"swift/index.html\">Swift</a></li>\n      <li><a href=\"stex/index.html\">sTeX, LaTeX</a></li>\n      <li><a href=\"tcl/index.html\">Tcl</a></li>\n      <li><a href=\"textile/index.html\">Textile</a></li>\n      <li><a href=\"tiddlywiki/index.html\">Tiddlywiki</a></li>\n      <li><a href=\"tiki/index.html\">Tiki wiki</a></li>\n      <li><a href=\"toml/index.html\">TOML</a></li>\n      <li><a href=\"tornado/index.html\">Tornado</a> (templating language)</li>\n      <li><a href=\"troff/index.html\">troff</a> (for manpages)</li>\n      <li><a href=\"ttcn/index.html\">TTCN</a></li>\n      <li><a href=\"ttcn-cfg/index.html\">TTCN Configuration</a></li>\n      <li><a href=\"turtle/index.html\">Turtle</a></li>\n      <li><a href=\"twig/index.html\">Twig</a></li>\n      <li><a href=\"vb/index.html\">VB.NET</a></li>\n      <li><a href=\"vbscript/index.html\">VBScript</a></li>\n      <li><a href=\"velocity/index.html\">Velocity</a></li>\n      <li><a href=\"verilog/index.html\">Verilog/SystemVerilog</a></li>\n      <li><a href=\"vhdl/index.html\">VHDL</a></li>\n      <li><a href=\"vue/index.html\">Vue.js app</a></li>\n      <li><a href=\"webidl/index.html\">Web IDL</a></li>\n      <li><a href=\"xml/index.html\">XML/HTML</a></li>\n      <li><a href=\"xquery/index.html\">XQuery</a></li>\n      <li><a href=\"yacas/index.html\">Yacas</a></li>\n      <li><a href=\"yaml/index.html\">YAML</a></li>\n      <li><a href=\"yaml-frontmatter/index.html\">YAML frontmatter</a></li>\n      <li><a href=\"z80/index.html\">Z80</a></li>\n    </ul>\n  </div>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/javascript/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: JavaScript mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"../../addon/comment/continuecomment.js\"></script>\n<script src=\"../../addon/comment/comment.js\"></script>\n<script src=\"javascript.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">JavaScript</a>\n  </ul>\n</div>\n\n<article>\n<h2>JavaScript mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n// Demo code (the actual new parser character stream implementation)\n\nfunction StringStream(string) {\n  this.pos = 0;\n  this.string = string;\n}\n\nStringStream.prototype = {\n  done: function() {return this.pos >= this.string.length;},\n  peek: function() {return this.string.charAt(this.pos);},\n  next: function() {\n    if (this.pos &lt; this.string.length)\n      return this.string.charAt(this.pos++);\n  },\n  eat: function(match) {\n    var ch = this.string.charAt(this.pos);\n    if (typeof match == \"string\") var ok = ch == match;\n    else var ok = ch &amp;&amp; match.test ? match.test(ch) : match(ch);\n    if (ok) {this.pos++; return ch;}\n  },\n  eatWhile: function(match) {\n    var start = this.pos;\n    while (this.eat(match));\n    if (this.pos > start) return this.string.slice(start, this.pos);\n  },\n  backUp: function(n) {this.pos -= n;},\n  column: function() {return this.pos;},\n  eatSpace: function() {\n    var start = this.pos;\n    while (/\\s/.test(this.string.charAt(this.pos))) this.pos++;\n    return this.pos - start;\n  },\n  match: function(pattern, consume, caseInsensitive) {\n    if (typeof pattern == \"string\") {\n      function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}\n      if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {\n        if (consume !== false) this.pos += str.length;\n        return true;\n      }\n    }\n    else {\n      var match = this.string.slice(this.pos).match(pattern);\n      if (match &amp;&amp; consume !== false) this.pos += match[0].length;\n      return match;\n    }\n  }\n};\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        continueComments: \"Enter\",\n        extraKeys: {\"Ctrl-Q\": \"toggleComment\"}\n      });\n    </script>\n\n    <p>\n      JavaScript mode supports several configuration options:\n      <ul>\n        <li><code>json</code> which will set the mode to expect JSON\n        data rather than a JavaScript program.</li>\n        <li><code>jsonld</code> which will set the mode to expect\n        <a href=\"http://json-ld.org\">JSON-LD</a> linked data rather\n        than a JavaScript program (<a href=\"json-ld.html\">demo</a>).</li>\n        <li><code>typescript</code> which will activate additional\n        syntax highlighting and some other things for TypeScript code\n        (<a href=\"typescript.html\">demo</a>).</li>\n        <li><code>statementIndent</code> which (given a number) will\n        determine the amount of indentation to use for statements\n        continued on a new line.</li>\n        <li><code>wordCharacters</code>, a regexp that indicates which\n        characters should be considered part of an identifier.\n        Defaults to <code>/[\\w$]/</code>, which does not handle\n        non-ASCII identifiers. Can be set to something more elaborate\n        to improve Unicode support.</li>\n      </ul>\n    </p>\n\n    <p><strong>MIME types defined:</strong> <code>text/javascript</code>, <code>application/json</code>, <code>application/ld+json</code>, <code>text/typescript</code>, <code>application/typescript</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/javascript/javascript.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"javascript\", function(config, parserConfig) {\n  var indentUnit = config.indentUnit;\n  var statementIndent = parserConfig.statementIndent;\n  var jsonldMode = parserConfig.jsonld;\n  var jsonMode = parserConfig.json || jsonldMode;\n  var isTS = parserConfig.typescript;\n  var wordRE = parserConfig.wordCharacters || /[\\w$\\xa1-\\uffff]/;\n\n  // Tokenizer\n\n  var keywords = function(){\n    function kw(type) {return {type: type, style: \"keyword\"};}\n    var A = kw(\"keyword a\"), B = kw(\"keyword b\"), C = kw(\"keyword c\"), D = kw(\"keyword d\");\n    var operator = kw(\"operator\"), atom = {type: \"atom\", style: \"atom\"};\n\n    return {\n      \"if\": kw(\"if\"), \"while\": A, \"with\": A, \"else\": B, \"do\": B, \"try\": B, \"finally\": B,\n      \"return\": D, \"break\": D, \"continue\": D, \"new\": kw(\"new\"), \"delete\": C, \"void\": C, \"throw\": C,\n      \"debugger\": kw(\"debugger\"), \"var\": kw(\"var\"), \"const\": kw(\"var\"), \"let\": kw(\"var\"),\n      \"function\": kw(\"function\"), \"catch\": kw(\"catch\"),\n      \"for\": kw(\"for\"), \"switch\": kw(\"switch\"), \"case\": kw(\"case\"), \"default\": kw(\"default\"),\n      \"in\": operator, \"typeof\": operator, \"instanceof\": operator,\n      \"true\": atom, \"false\": atom, \"null\": atom, \"undefined\": atom, \"NaN\": atom, \"Infinity\": atom,\n      \"this\": kw(\"this\"), \"class\": kw(\"class\"), \"super\": kw(\"atom\"),\n      \"yield\": C, \"export\": kw(\"export\"), \"import\": kw(\"import\"), \"extends\": C,\n      \"await\": C\n    };\n  }();\n\n  var isOperatorChar = /[+\\-*&%=<>!?|~^@]/;\n  var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)\"/;\n\n  function readRegexp(stream) {\n    var escaped = false, next, inSet = false;\n    while ((next = stream.next()) != null) {\n      if (!escaped) {\n        if (next == \"/\" && !inSet) return;\n        if (next == \"[\") inSet = true;\n        else if (inSet && next == \"]\") inSet = false;\n      }\n      escaped = !escaped && next == \"\\\\\";\n    }\n  }\n\n  // Used as scratch variables to communicate multiple values without\n  // consing up tons of objects.\n  var type, content;\n  function ret(tp, style, cont) {\n    type = tp; content = cont;\n    return style;\n  }\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (ch == '\"' || ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    } else if (ch == \".\" && stream.match(/^\\d+(?:[eE][+\\-]?\\d+)?/)) {\n      return ret(\"number\", \"number\");\n    } else if (ch == \".\" && stream.match(\"..\")) {\n      return ret(\"spread\", \"meta\");\n    } else if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n      return ret(ch);\n    } else if (ch == \"=\" && stream.eat(\">\")) {\n      return ret(\"=>\", \"operator\");\n    } else if (ch == \"0\" && stream.match(/^(?:x[\\da-f]+|o[0-7]+|b[01]+)n?/i)) {\n      return ret(\"number\", \"number\");\n    } else if (/\\d/.test(ch)) {\n      stream.match(/^\\d*(?:n|(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)?/);\n      return ret(\"number\", \"number\");\n    } else if (ch == \"/\") {\n      if (stream.eat(\"*\")) {\n        state.tokenize = tokenComment;\n        return tokenComment(stream, state);\n      } else if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return ret(\"comment\", \"comment\");\n      } else if (expressionAllowed(stream, state, 1)) {\n        readRegexp(stream);\n        stream.match(/^\\b(([gimyus])(?![gimyus]*\\2))+\\b/);\n        return ret(\"regexp\", \"string-2\");\n      } else {\n        stream.eat(\"=\");\n        return ret(\"operator\", \"operator\", stream.current());\n      }\n    } else if (ch == \"`\") {\n      state.tokenize = tokenQuasi;\n      return tokenQuasi(stream, state);\n    } else if (ch == \"#\") {\n      stream.skipToEnd();\n      return ret(\"error\", \"error\");\n    } else if (isOperatorChar.test(ch)) {\n      if (ch != \">\" || !state.lexical || state.lexical.type != \">\") {\n        if (stream.eat(\"=\")) {\n          if (ch == \"!\" || ch == \"=\") stream.eat(\"=\")\n        } else if (/[<>*+\\-]/.test(ch)) {\n          stream.eat(ch)\n          if (ch == \">\") stream.eat(ch)\n        }\n      }\n      return ret(\"operator\", \"operator\", stream.current());\n    } else if (wordRE.test(ch)) {\n      stream.eatWhile(wordRE);\n      var word = stream.current()\n      if (state.lastType != \".\") {\n        if (keywords.propertyIsEnumerable(word)) {\n          var kw = keywords[word]\n          return ret(kw.type, kw.style, word)\n        }\n        if (word == \"async\" && stream.match(/^(\\s|\\/\\*.*?\\*\\/)*[\\[\\(\\w]/, false))\n          return ret(\"async\", \"keyword\", word)\n      }\n      return ret(\"variable\", \"variable\", word)\n    }\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next;\n      if (jsonldMode && stream.peek() == \"@\" && stream.match(isJsonldKeyword)){\n        state.tokenize = tokenBase;\n        return ret(\"jsonld-keyword\", \"meta\");\n      }\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) break;\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (!escaped) state.tokenize = tokenBase;\n      return ret(\"string\", \"string\");\n    };\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return ret(\"comment\", \"comment\");\n  }\n\n  function tokenQuasi(stream, state) {\n    var escaped = false, next;\n    while ((next = stream.next()) != null) {\n      if (!escaped && (next == \"`\" || next == \"$\" && stream.eat(\"{\"))) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      escaped = !escaped && next == \"\\\\\";\n    }\n    return ret(\"quasi\", \"string-2\", stream.current());\n  }\n\n  var brackets = \"([{}])\";\n  // This is a crude lookahead trick to try and notice that we're\n  // parsing the argument patterns for a fat-arrow function before we\n  // actually hit the arrow token. It only works if the arrow is on\n  // the same line as the arguments and there's no strange noise\n  // (comments) in between. Fallback is to only notice when we hit the\n  // arrow, and not declare the arguments as locals for the arrow\n  // body.\n  function findFatArrow(stream, state) {\n    if (state.fatArrowAt) state.fatArrowAt = null;\n    var arrow = stream.string.indexOf(\"=>\", stream.start);\n    if (arrow < 0) return;\n\n    if (isTS) { // Try to skip TypeScript return type declarations after the arguments\n      var m = /:\\s*(?:\\w+(?:<[^>]*>|\\[\\])?|\\{[^}]*\\})\\s*$/.exec(stream.string.slice(stream.start, arrow))\n      if (m) arrow = m.index\n    }\n\n    var depth = 0, sawSomething = false;\n    for (var pos = arrow - 1; pos >= 0; --pos) {\n      var ch = stream.string.charAt(pos);\n      var bracket = brackets.indexOf(ch);\n      if (bracket >= 0 && bracket < 3) {\n        if (!depth) { ++pos; break; }\n        if (--depth == 0) { if (ch == \"(\") sawSomething = true; break; }\n      } else if (bracket >= 3 && bracket < 6) {\n        ++depth;\n      } else if (wordRE.test(ch)) {\n        sawSomething = true;\n      } else if (/[\"'\\/]/.test(ch)) {\n        return;\n      } else if (sawSomething && !depth) {\n        ++pos;\n        break;\n      }\n    }\n    if (sawSomething && !depth) state.fatArrowAt = pos;\n  }\n\n  // Parser\n\n  var atomicTypes = {\"atom\": true, \"number\": true, \"variable\": true, \"string\": true, \"regexp\": true, \"this\": true, \"jsonld-keyword\": true};\n\n  function JSLexical(indented, column, type, align, prev, info) {\n    this.indented = indented;\n    this.column = column;\n    this.type = type;\n    this.prev = prev;\n    this.info = info;\n    if (align != null) this.align = align;\n  }\n\n  function inScope(state, varname) {\n    for (var v = state.localVars; v; v = v.next)\n      if (v.name == varname) return true;\n    for (var cx = state.context; cx; cx = cx.prev) {\n      for (var v = cx.vars; v; v = v.next)\n        if (v.name == varname) return true;\n    }\n  }\n\n  function parseJS(state, style, type, content, stream) {\n    var cc = state.cc;\n    // Communicate our context to the combinators.\n    // (Less wasteful than consing up a hundred closures on every call.)\n    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;\n\n    if (!state.lexical.hasOwnProperty(\"align\"))\n      state.lexical.align = true;\n\n    while(true) {\n      var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;\n      if (combinator(type, content)) {\n        while(cc.length && cc[cc.length - 1].lex)\n          cc.pop()();\n        if (cx.marked) return cx.marked;\n        if (type == \"variable\" && inScope(state, content)) return \"variable-2\";\n        return style;\n      }\n    }\n  }\n\n  // Combinator utils\n\n  var cx = {state: null, column: null, marked: null, cc: null};\n  function pass() {\n    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);\n  }\n  function cont() {\n    pass.apply(null, arguments);\n    return true;\n  }\n  function inList(name, list) {\n    for (var v = list; v; v = v.next) if (v.name == name) return true\n    return false;\n  }\n  function register(varname) {\n    var state = cx.state;\n    cx.marked = \"def\";\n    if (state.context) {\n      if (state.lexical.info == \"var\" && state.context && state.context.block) {\n        // FIXME function decls are also not block scoped\n        var newContext = registerVarScoped(varname, state.context)\n        if (newContext != null) {\n          state.context = newContext\n          return\n        }\n      } else if (!inList(varname, state.localVars)) {\n        state.localVars = new Var(varname, state.localVars)\n        return\n      }\n    }\n    // Fall through means this is global\n    if (parserConfig.globalVars && !inList(varname, state.globalVars))\n      state.globalVars = new Var(varname, state.globalVars)\n  }\n  function registerVarScoped(varname, context) {\n    if (!context) {\n      return null\n    } else if (context.block) {\n      var inner = registerVarScoped(varname, context.prev)\n      if (!inner) return null\n      if (inner == context.prev) return context\n      return new Context(inner, context.vars, true)\n    } else if (inList(varname, context.vars)) {\n      return context\n    } else {\n      return new Context(context.prev, new Var(varname, context.vars), false)\n    }\n  }\n\n  function isModifier(name) {\n    return name == \"public\" || name == \"private\" || name == \"protected\" || name == \"abstract\" || name == \"readonly\"\n  }\n\n  // Combinators\n\n  function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }\n  function Var(name, next) { this.name = name; this.next = next }\n\n  var defaultVars = new Var(\"this\", new Var(\"arguments\", null))\n  function pushcontext() {\n    cx.state.context = new Context(cx.state.context, cx.state.localVars, false)\n    cx.state.localVars = defaultVars\n  }\n  function pushblockcontext() {\n    cx.state.context = new Context(cx.state.context, cx.state.localVars, true)\n    cx.state.localVars = null\n  }\n  function popcontext() {\n    cx.state.localVars = cx.state.context.vars\n    cx.state.context = cx.state.context.prev\n  }\n  popcontext.lex = true\n  function pushlex(type, info) {\n    var result = function() {\n      var state = cx.state, indent = state.indented;\n      if (state.lexical.type == \"stat\") indent = state.lexical.indented;\n      else for (var outer = state.lexical; outer && outer.type == \")\" && outer.align; outer = outer.prev)\n        indent = outer.indented;\n      state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);\n    };\n    result.lex = true;\n    return result;\n  }\n  function poplex() {\n    var state = cx.state;\n    if (state.lexical.prev) {\n      if (state.lexical.type == \")\")\n        state.indented = state.lexical.indented;\n      state.lexical = state.lexical.prev;\n    }\n  }\n  poplex.lex = true;\n\n  function expect(wanted) {\n    function exp(type) {\n      if (type == wanted) return cont();\n      else if (wanted == \";\" || type == \"}\" || type == \")\" || type == \"]\") return pass();\n      else return cont(exp);\n    };\n    return exp;\n  }\n\n  function statement(type, value) {\n    if (type == \"var\") return cont(pushlex(\"vardef\", value), vardef, expect(\";\"), poplex);\n    if (type == \"keyword a\") return cont(pushlex(\"form\"), parenExpr, statement, poplex);\n    if (type == \"keyword b\") return cont(pushlex(\"form\"), statement, poplex);\n    if (type == \"keyword d\") return cx.stream.match(/^\\s*$/, false) ? cont() : cont(pushlex(\"stat\"), maybeexpression, expect(\";\"), poplex);\n    if (type == \"debugger\") return cont(expect(\";\"));\n    if (type == \"{\") return cont(pushlex(\"}\"), pushblockcontext, block, poplex, popcontext);\n    if (type == \";\") return cont();\n    if (type == \"if\") {\n      if (cx.state.lexical.info == \"else\" && cx.state.cc[cx.state.cc.length - 1] == poplex)\n        cx.state.cc.pop()();\n      return cont(pushlex(\"form\"), parenExpr, statement, poplex, maybeelse);\n    }\n    if (type == \"function\") return cont(functiondef);\n    if (type == \"for\") return cont(pushlex(\"form\"), forspec, statement, poplex);\n    if (type == \"class\" || (isTS && value == \"interface\")) {\n      cx.marked = \"keyword\"\n      return cont(pushlex(\"form\", type == \"class\" ? type : value), className, poplex)\n    }\n    if (type == \"variable\") {\n      if (isTS && value == \"declare\") {\n        cx.marked = \"keyword\"\n        return cont(statement)\n      } else if (isTS && (value == \"module\" || value == \"enum\" || value == \"type\") && cx.stream.match(/^\\s*\\w/, false)) {\n        cx.marked = \"keyword\"\n        if (value == \"enum\") return cont(enumdef);\n        else if (value == \"type\") return cont(typename, expect(\"operator\"), typeexpr, expect(\";\"));\n        else return cont(pushlex(\"form\"), pattern, expect(\"{\"), pushlex(\"}\"), block, poplex, poplex)\n      } else if (isTS && value == \"namespace\") {\n        cx.marked = \"keyword\"\n        return cont(pushlex(\"form\"), expression, statement, poplex)\n      } else if (isTS && value == \"abstract\") {\n        cx.marked = \"keyword\"\n        return cont(statement)\n      } else {\n        return cont(pushlex(\"stat\"), maybelabel);\n      }\n    }\n    if (type == \"switch\") return cont(pushlex(\"form\"), parenExpr, expect(\"{\"), pushlex(\"}\", \"switch\"), pushblockcontext,\n                                      block, poplex, poplex, popcontext);\n    if (type == \"case\") return cont(expression, expect(\":\"));\n    if (type == \"default\") return cont(expect(\":\"));\n    if (type == \"catch\") return cont(pushlex(\"form\"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);\n    if (type == \"export\") return cont(pushlex(\"stat\"), afterExport, poplex);\n    if (type == \"import\") return cont(pushlex(\"stat\"), afterImport, poplex);\n    if (type == \"async\") return cont(statement)\n    if (value == \"@\") return cont(expression, statement)\n    return pass(pushlex(\"stat\"), expression, expect(\";\"), poplex);\n  }\n  function maybeCatchBinding(type) {\n    if (type == \"(\") return cont(funarg, expect(\")\"))\n  }\n  function expression(type, value) {\n    return expressionInner(type, value, false);\n  }\n  function expressionNoComma(type, value) {\n    return expressionInner(type, value, true);\n  }\n  function parenExpr(type) {\n    if (type != \"(\") return pass()\n    return cont(pushlex(\")\"), expression, expect(\")\"), poplex)\n  }\n  function expressionInner(type, value, noComma) {\n    if (cx.state.fatArrowAt == cx.stream.start) {\n      var body = noComma ? arrowBodyNoComma : arrowBody;\n      if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, expect(\"=>\"), body, popcontext);\n      else if (type == \"variable\") return pass(pushcontext, pattern, expect(\"=>\"), body, popcontext);\n    }\n\n    var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;\n    if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);\n    if (type == \"function\") return cont(functiondef, maybeop);\n    if (type == \"class\" || (isTS && value == \"interface\")) { cx.marked = \"keyword\"; return cont(pushlex(\"form\"), classExpression, poplex); }\n    if (type == \"keyword c\" || type == \"async\") return cont(noComma ? expressionNoComma : expression);\n    if (type == \"(\") return cont(pushlex(\")\"), maybeexpression, expect(\")\"), poplex, maybeop);\n    if (type == \"operator\" || type == \"spread\") return cont(noComma ? expressionNoComma : expression);\n    if (type == \"[\") return cont(pushlex(\"]\"), arrayLiteral, poplex, maybeop);\n    if (type == \"{\") return contCommasep(objprop, \"}\", null, maybeop);\n    if (type == \"quasi\") return pass(quasi, maybeop);\n    if (type == \"new\") return cont(maybeTarget(noComma));\n    if (type == \"import\") return cont(expression);\n    return cont();\n  }\n  function maybeexpression(type) {\n    if (type.match(/[;\\}\\)\\],]/)) return pass();\n    return pass(expression);\n  }\n\n  function maybeoperatorComma(type, value) {\n    if (type == \",\") return cont(expression);\n    return maybeoperatorNoComma(type, value, false);\n  }\n  function maybeoperatorNoComma(type, value, noComma) {\n    var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;\n    var expr = noComma == false ? expression : expressionNoComma;\n    if (type == \"=>\") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);\n    if (type == \"operator\") {\n      if (/\\+\\+|--/.test(value) || isTS && value == \"!\") return cont(me);\n      if (isTS && value == \"<\" && cx.stream.match(/^([^>]|<.*?>)*>\\s*\\(/, false))\n        return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, me);\n      if (value == \"?\") return cont(expression, expect(\":\"), expr);\n      return cont(expr);\n    }\n    if (type == \"quasi\") { return pass(quasi, me); }\n    if (type == \";\") return;\n    if (type == \"(\") return contCommasep(expressionNoComma, \")\", \"call\", me);\n    if (type == \".\") return cont(property, me);\n    if (type == \"[\") return cont(pushlex(\"]\"), maybeexpression, expect(\"]\"), poplex, me);\n    if (isTS && value == \"as\") { cx.marked = \"keyword\"; return cont(typeexpr, me) }\n    if (type == \"regexp\") {\n      cx.state.lastType = cx.marked = \"operator\"\n      cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)\n      return cont(expr)\n    }\n  }\n  function quasi(type, value) {\n    if (type != \"quasi\") return pass();\n    if (value.slice(value.length - 2) != \"${\") return cont(quasi);\n    return cont(expression, continueQuasi);\n  }\n  function continueQuasi(type) {\n    if (type == \"}\") {\n      cx.marked = \"string-2\";\n      cx.state.tokenize = tokenQuasi;\n      return cont(quasi);\n    }\n  }\n  function arrowBody(type) {\n    findFatArrow(cx.stream, cx.state);\n    return pass(type == \"{\" ? statement : expression);\n  }\n  function arrowBodyNoComma(type) {\n    findFatArrow(cx.stream, cx.state);\n    return pass(type == \"{\" ? statement : expressionNoComma);\n  }\n  function maybeTarget(noComma) {\n    return function(type) {\n      if (type == \".\") return cont(noComma ? targetNoComma : target);\n      else if (type == \"variable\" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)\n      else return pass(noComma ? expressionNoComma : expression);\n    };\n  }\n  function target(_, value) {\n    if (value == \"target\") { cx.marked = \"keyword\"; return cont(maybeoperatorComma); }\n  }\n  function targetNoComma(_, value) {\n    if (value == \"target\") { cx.marked = \"keyword\"; return cont(maybeoperatorNoComma); }\n  }\n  function maybelabel(type) {\n    if (type == \":\") return cont(poplex, statement);\n    return pass(maybeoperatorComma, expect(\";\"), poplex);\n  }\n  function property(type) {\n    if (type == \"variable\") {cx.marked = \"property\"; return cont();}\n  }\n  function objprop(type, value) {\n    if (type == \"async\") {\n      cx.marked = \"property\";\n      return cont(objprop);\n    } else if (type == \"variable\" || cx.style == \"keyword\") {\n      cx.marked = \"property\";\n      if (value == \"get\" || value == \"set\") return cont(getterSetter);\n      var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params\n      if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\\s*:\\s*/, false)))\n        cx.state.fatArrowAt = cx.stream.pos + m[0].length\n      return cont(afterprop);\n    } else if (type == \"number\" || type == \"string\") {\n      cx.marked = jsonldMode ? \"property\" : (cx.style + \" property\");\n      return cont(afterprop);\n    } else if (type == \"jsonld-keyword\") {\n      return cont(afterprop);\n    } else if (isTS && isModifier(value)) {\n      cx.marked = \"keyword\"\n      return cont(objprop)\n    } else if (type == \"[\") {\n      return cont(expression, maybetype, expect(\"]\"), afterprop);\n    } else if (type == \"spread\") {\n      return cont(expressionNoComma, afterprop);\n    } else if (value == \"*\") {\n      cx.marked = \"keyword\";\n      return cont(objprop);\n    } else if (type == \":\") {\n      return pass(afterprop)\n    }\n  }\n  function getterSetter(type) {\n    if (type != \"variable\") return pass(afterprop);\n    cx.marked = \"property\";\n    return cont(functiondef);\n  }\n  function afterprop(type) {\n    if (type == \":\") return cont(expressionNoComma);\n    if (type == \"(\") return pass(functiondef);\n  }\n  function commasep(what, end, sep) {\n    function proceed(type, value) {\n      if (sep ? sep.indexOf(type) > -1 : type == \",\") {\n        var lex = cx.state.lexical;\n        if (lex.info == \"call\") lex.pos = (lex.pos || 0) + 1;\n        return cont(function(type, value) {\n          if (type == end || value == end) return pass()\n          return pass(what)\n        }, proceed);\n      }\n      if (type == end || value == end) return cont();\n      if (sep && sep.indexOf(\";\") > -1) return pass(what)\n      return cont(expect(end));\n    }\n    return function(type, value) {\n      if (type == end || value == end) return cont();\n      return pass(what, proceed);\n    };\n  }\n  function contCommasep(what, end, info) {\n    for (var i = 3; i < arguments.length; i++)\n      cx.cc.push(arguments[i]);\n    return cont(pushlex(end, info), commasep(what, end), poplex);\n  }\n  function block(type) {\n    if (type == \"}\") return cont();\n    return pass(statement, block);\n  }\n  function maybetype(type, value) {\n    if (isTS) {\n      if (type == \":\" || value == \"in\") return cont(typeexpr);\n      if (value == \"?\") return cont(maybetype);\n    }\n  }\n  function mayberettype(type) {\n    if (isTS && type == \":\") {\n      if (cx.stream.match(/^\\s*\\w+\\s+is\\b/, false)) return cont(expression, isKW, typeexpr)\n      else return cont(typeexpr)\n    }\n  }\n  function isKW(_, value) {\n    if (value == \"is\") {\n      cx.marked = \"keyword\"\n      return cont()\n    }\n  }\n  function typeexpr(type, value) {\n    if (value == \"keyof\" || value == \"typeof\" || value == \"infer\") {\n      cx.marked = \"keyword\"\n      return cont(value == \"typeof\" ? expressionNoComma : typeexpr)\n    }\n    if (type == \"variable\" || value == \"void\") {\n      cx.marked = \"type\"\n      return cont(afterType)\n    }\n    if (type == \"string\" || type == \"number\" || type == \"atom\") return cont(afterType);\n    if (type == \"[\") return cont(pushlex(\"]\"), commasep(typeexpr, \"]\", \",\"), poplex, afterType)\n    if (type == \"{\") return cont(pushlex(\"}\"), commasep(typeprop, \"}\", \",;\"), poplex, afterType)\n    if (type == \"(\") return cont(commasep(typearg, \")\"), maybeReturnType, afterType)\n    if (type == \"<\") return cont(commasep(typeexpr, \">\"), typeexpr)\n  }\n  function maybeReturnType(type) {\n    if (type == \"=>\") return cont(typeexpr)\n  }\n  function typeprop(type, value) {\n    if (type == \"variable\" || cx.style == \"keyword\") {\n      cx.marked = \"property\"\n      return cont(typeprop)\n    } else if (value == \"?\" || type == \"number\" || type == \"string\") {\n      return cont(typeprop)\n    } else if (type == \":\") {\n      return cont(typeexpr)\n    } else if (type == \"[\") {\n      return cont(expect(\"variable\"), maybetype, expect(\"]\"), typeprop)\n    } else if (type == \"(\") {\n      return pass(functiondecl, typeprop)\n    }\n  }\n  function typearg(type, value) {\n    if (type == \"variable\" && cx.stream.match(/^\\s*[?:]/, false) || value == \"?\") return cont(typearg)\n    if (type == \":\") return cont(typeexpr)\n    if (type == \"spread\") return cont(typearg)\n    return pass(typeexpr)\n  }\n  function afterType(type, value) {\n    if (value == \"<\") return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, afterType)\n    if (value == \"|\" || type == \".\" || value == \"&\") return cont(typeexpr)\n    if (type == \"[\") return cont(typeexpr, expect(\"]\"), afterType)\n    if (value == \"extends\" || value == \"implements\") { cx.marked = \"keyword\"; return cont(typeexpr) }\n    if (value == \"?\") return cont(typeexpr, expect(\":\"), typeexpr)\n  }\n  function maybeTypeArgs(_, value) {\n    if (value == \"<\") return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, afterType)\n  }\n  function typeparam() {\n    return pass(typeexpr, maybeTypeDefault)\n  }\n  function maybeTypeDefault(_, value) {\n    if (value == \"=\") return cont(typeexpr)\n  }\n  function vardef(_, value) {\n    if (value == \"enum\") {cx.marked = \"keyword\"; return cont(enumdef)}\n    return pass(pattern, maybetype, maybeAssign, vardefCont);\n  }\n  function pattern(type, value) {\n    if (isTS && isModifier(value)) { cx.marked = \"keyword\"; return cont(pattern) }\n    if (type == \"variable\") { register(value); return cont(); }\n    if (type == \"spread\") return cont(pattern);\n    if (type == \"[\") return contCommasep(eltpattern, \"]\");\n    if (type == \"{\") return contCommasep(proppattern, \"}\");\n  }\n  function proppattern(type, value) {\n    if (type == \"variable\" && !cx.stream.match(/^\\s*:/, false)) {\n      register(value);\n      return cont(maybeAssign);\n    }\n    if (type == \"variable\") cx.marked = \"property\";\n    if (type == \"spread\") return cont(pattern);\n    if (type == \"}\") return pass();\n    if (type == \"[\") return cont(expression, expect(']'), expect(':'), proppattern);\n    return cont(expect(\":\"), pattern, maybeAssign);\n  }\n  function eltpattern() {\n    return pass(pattern, maybeAssign)\n  }\n  function maybeAssign(_type, value) {\n    if (value == \"=\") return cont(expressionNoComma);\n  }\n  function vardefCont(type) {\n    if (type == \",\") return cont(vardef);\n  }\n  function maybeelse(type, value) {\n    if (type == \"keyword b\" && value == \"else\") return cont(pushlex(\"form\", \"else\"), statement, poplex);\n  }\n  function forspec(type, value) {\n    if (value == \"await\") return cont(forspec);\n    if (type == \"(\") return cont(pushlex(\")\"), forspec1, expect(\")\"), poplex);\n  }\n  function forspec1(type) {\n    if (type == \"var\") return cont(vardef, expect(\";\"), forspec2);\n    if (type == \";\") return cont(forspec2);\n    if (type == \"variable\") return cont(formaybeinof);\n    return pass(expression, expect(\";\"), forspec2);\n  }\n  function formaybeinof(_type, value) {\n    if (value == \"in\" || value == \"of\") { cx.marked = \"keyword\"; return cont(expression); }\n    return cont(maybeoperatorComma, forspec2);\n  }\n  function forspec2(type, value) {\n    if (type == \";\") return cont(forspec3);\n    if (value == \"in\" || value == \"of\") { cx.marked = \"keyword\"; return cont(expression); }\n    return pass(expression, expect(\";\"), forspec3);\n  }\n  function forspec3(type) {\n    if (type != \")\") cont(expression);\n  }\n  function functiondef(type, value) {\n    if (value == \"*\") {cx.marked = \"keyword\"; return cont(functiondef);}\n    if (type == \"variable\") {register(value); return cont(functiondef);}\n    if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, mayberettype, statement, popcontext);\n    if (isTS && value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, functiondef)\n  }\n  function functiondecl(type, value) {\n    if (value == \"*\") {cx.marked = \"keyword\"; return cont(functiondecl);}\n    if (type == \"variable\") {register(value); return cont(functiondecl);}\n    if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, mayberettype, popcontext);\n    if (isTS && value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, functiondecl)\n  }\n  function typename(type, value) {\n    if (type == \"keyword\" || type == \"variable\") {\n      cx.marked = \"type\"\n      return cont(typename)\n    } else if (value == \"<\") {\n      return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex)\n    }\n  }\n  function funarg(type, value) {\n    if (value == \"@\") cont(expression, funarg)\n    if (type == \"spread\") return cont(funarg);\n    if (isTS && isModifier(value)) { cx.marked = \"keyword\"; return cont(funarg); }\n    return pass(pattern, maybetype, maybeAssign);\n  }\n  function classExpression(type, value) {\n    // Class expressions may have an optional name.\n    if (type == \"variable\") return className(type, value);\n    return classNameAfter(type, value);\n  }\n  function className(type, value) {\n    if (type == \"variable\") {register(value); return cont(classNameAfter);}\n  }\n  function classNameAfter(type, value) {\n    if (value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, classNameAfter)\n    if (value == \"extends\" || value == \"implements\" || (isTS && type == \",\")) {\n      if (value == \"implements\") cx.marked = \"keyword\";\n      return cont(isTS ? typeexpr : expression, classNameAfter);\n    }\n    if (type == \"{\") return cont(pushlex(\"}\"), classBody, poplex);\n  }\n  function classBody(type, value) {\n    if (type == \"async\" ||\n        (type == \"variable\" &&\n         (value == \"static\" || value == \"get\" || value == \"set\" || (isTS && isModifier(value))) &&\n         cx.stream.match(/^\\s+[\\w$\\xa1-\\uffff]/, false))) {\n      cx.marked = \"keyword\";\n      return cont(classBody);\n    }\n    if (type == \"variable\" || cx.style == \"keyword\") {\n      cx.marked = \"property\";\n      return cont(isTS ? classfield : functiondef, classBody);\n    }\n    if (type == \"number\" || type == \"string\") return cont(isTS ? classfield : functiondef, classBody);\n    if (type == \"[\")\n      return cont(expression, maybetype, expect(\"]\"), isTS ? classfield : functiondef, classBody)\n    if (value == \"*\") {\n      cx.marked = \"keyword\";\n      return cont(classBody);\n    }\n    if (isTS && type == \"(\") return pass(functiondecl, classBody)\n    if (type == \";\" || type == \",\") return cont(classBody);\n    if (type == \"}\") return cont();\n    if (value == \"@\") return cont(expression, classBody)\n  }\n  function classfield(type, value) {\n    if (value == \"?\") return cont(classfield)\n    if (type == \":\") return cont(typeexpr, maybeAssign)\n    if (value == \"=\") return cont(expressionNoComma)\n    var context = cx.state.lexical.prev, isInterface = context && context.info == \"interface\"\n    return pass(isInterface ? functiondecl : functiondef)\n  }\n  function afterExport(type, value) {\n    if (value == \"*\") { cx.marked = \"keyword\"; return cont(maybeFrom, expect(\";\")); }\n    if (value == \"default\") { cx.marked = \"keyword\"; return cont(expression, expect(\";\")); }\n    if (type == \"{\") return cont(commasep(exportField, \"}\"), maybeFrom, expect(\";\"));\n    return pass(statement);\n  }\n  function exportField(type, value) {\n    if (value == \"as\") { cx.marked = \"keyword\"; return cont(expect(\"variable\")); }\n    if (type == \"variable\") return pass(expressionNoComma, exportField);\n  }\n  function afterImport(type) {\n    if (type == \"string\") return cont();\n    if (type == \"(\") return pass(expression);\n    return pass(importSpec, maybeMoreImports, maybeFrom);\n  }\n  function importSpec(type, value) {\n    if (type == \"{\") return contCommasep(importSpec, \"}\");\n    if (type == \"variable\") register(value);\n    if (value == \"*\") cx.marked = \"keyword\";\n    return cont(maybeAs);\n  }\n  function maybeMoreImports(type) {\n    if (type == \",\") return cont(importSpec, maybeMoreImports)\n  }\n  function maybeAs(_type, value) {\n    if (value == \"as\") { cx.marked = \"keyword\"; return cont(importSpec); }\n  }\n  function maybeFrom(_type, value) {\n    if (value == \"from\") { cx.marked = \"keyword\"; return cont(expression); }\n  }\n  function arrayLiteral(type) {\n    if (type == \"]\") return cont();\n    return pass(commasep(expressionNoComma, \"]\"));\n  }\n  function enumdef() {\n    return pass(pushlex(\"form\"), pattern, expect(\"{\"), pushlex(\"}\"), commasep(enummember, \"}\"), poplex, poplex)\n  }\n  function enummember() {\n    return pass(pattern, maybeAssign);\n  }\n\n  function isContinuedStatement(state, textAfter) {\n    return state.lastType == \"operator\" || state.lastType == \",\" ||\n      isOperatorChar.test(textAfter.charAt(0)) ||\n      /[,.]/.test(textAfter.charAt(0));\n  }\n\n  function expressionAllowed(stream, state, backUp) {\n    return state.tokenize == tokenBase &&\n      /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\\[{}\\(,;:]|=>)$/.test(state.lastType) ||\n      (state.lastType == \"quasi\" && /\\{\\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))\n  }\n\n  // Interface\n\n  return {\n    startState: function(basecolumn) {\n      var state = {\n        tokenize: tokenBase,\n        lastType: \"sof\",\n        cc: [],\n        lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, \"block\", false),\n        localVars: parserConfig.localVars,\n        context: parserConfig.localVars && new Context(null, null, false),\n        indented: basecolumn || 0\n      };\n      if (parserConfig.globalVars && typeof parserConfig.globalVars == \"object\")\n        state.globalVars = parserConfig.globalVars;\n      return state;\n    },\n\n    token: function(stream, state) {\n      if (stream.sol()) {\n        if (!state.lexical.hasOwnProperty(\"align\"))\n          state.lexical.align = false;\n        state.indented = stream.indentation();\n        findFatArrow(stream, state);\n      }\n      if (state.tokenize != tokenComment && stream.eatSpace()) return null;\n      var style = state.tokenize(stream, state);\n      if (type == \"comment\") return style;\n      state.lastType = type == \"operator\" && (content == \"++\" || content == \"--\") ? \"incdec\" : type;\n      return parseJS(state, style, type, content, stream);\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize == tokenComment) return CodeMirror.Pass;\n      if (state.tokenize != tokenBase) return 0;\n      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top\n      // Kludge to prevent 'maybelse' from blocking lexical scope pops\n      if (!/^\\s*else\\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {\n        var c = state.cc[i];\n        if (c == poplex) lexical = lexical.prev;\n        else if (c != maybeelse) break;\n      }\n      while ((lexical.type == \"stat\" || lexical.type == \"form\") &&\n             (firstChar == \"}\" || ((top = state.cc[state.cc.length - 1]) &&\n                                   (top == maybeoperatorComma || top == maybeoperatorNoComma) &&\n                                   !/^[,\\.=+\\-*:?[\\(]/.test(textAfter))))\n        lexical = lexical.prev;\n      if (statementIndent && lexical.type == \")\" && lexical.prev.type == \"stat\")\n        lexical = lexical.prev;\n      var type = lexical.type, closing = firstChar == type;\n\n      if (type == \"vardef\") return lexical.indented + (state.lastType == \"operator\" || state.lastType == \",\" ? lexical.info.length + 1 : 0);\n      else if (type == \"form\" && firstChar == \"{\") return lexical.indented;\n      else if (type == \"form\") return lexical.indented + indentUnit;\n      else if (type == \"stat\")\n        return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);\n      else if (lexical.info == \"switch\" && !closing && parserConfig.doubleIndentSwitch != false)\n        return lexical.indented + (/^(?:case|default)\\b/.test(textAfter) ? indentUnit : 2 * indentUnit);\n      else if (lexical.align) return lexical.column + (closing ? 0 : 1);\n      else return lexical.indented + (closing ? 0 : indentUnit);\n    },\n\n    electricInput: /^\\s*(?:case .*?:|default:|\\{|\\})$/,\n    blockCommentStart: jsonMode ? null : \"/*\",\n    blockCommentEnd: jsonMode ? null : \"*/\",\n    blockCommentContinue: jsonMode ? null : \" * \",\n    lineComment: jsonMode ? null : \"//\",\n    fold: \"brace\",\n    closeBrackets: \"()[]{}''\\\"\\\"``\",\n\n    helperType: jsonMode ? \"json\" : \"javascript\",\n    jsonldMode: jsonldMode,\n    jsonMode: jsonMode,\n\n    expressionAllowed: expressionAllowed,\n\n    skipExpression: function(state) {\n      var top = state.cc[state.cc.length - 1]\n      if (top == expression || top == expressionNoComma) state.cc.pop()\n    }\n  };\n});\n\nCodeMirror.registerHelper(\"wordChars\", \"javascript\", /[\\w$]/);\n\nCodeMirror.defineMIME(\"text/javascript\", \"javascript\");\nCodeMirror.defineMIME(\"text/ecmascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/javascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/x-javascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/ecmascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/json\", {name: \"javascript\", json: true});\nCodeMirror.defineMIME(\"application/x-json\", {name: \"javascript\", json: true});\nCodeMirror.defineMIME(\"application/ld+json\", {name: \"javascript\", jsonld: true});\nCodeMirror.defineMIME(\"text/typescript\", { name: \"javascript\", typescript: true });\nCodeMirror.defineMIME(\"application/typescript\", { name: \"javascript\", typescript: true });\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/javascript/json-ld.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: JSON-LD mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"../../addon/comment/continuecomment.js\"></script>\n<script src=\"../../addon/comment/comment.js\"></script>\n<script src=\"javascript.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=\"nav\">\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"/></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">JSON-LD</a>\n  </ul>\n</div>\n\n<article>\n<h2>JSON-LD mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n{\n  \"@context\": {\n    \"name\": \"http://schema.org/name\",\n    \"description\": \"http://schema.org/description\",\n    \"image\": {\n      \"@id\": \"http://schema.org/image\",\n      \"@type\": \"@id\"\n    },\n    \"geo\": \"http://schema.org/geo\",\n    \"latitude\": {\n      \"@id\": \"http://schema.org/latitude\",\n      \"@type\": \"xsd:float\"\n    },\n    \"longitude\": {\n      \"@id\": \"http://schema.org/longitude\",\n      \"@type\": \"xsd:float\"\n    },\n    \"xsd\": \"http://www.w3.org/2001/XMLSchema#\"\n  },\n  \"name\": \"The Empire State Building\",\n  \"description\": \"The Empire State Building is a 102-story landmark in New York City.\",\n  \"image\": \"http://www.civil.usherbrooke.ca/cours/gci215a/empire-state-building.jpg\",\n  \"geo\": {\n    \"latitude\": \"40.75\",\n    \"longitude\": \"73.98\"\n  }\n}\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        matchBrackets: true,\n        autoCloseBrackets: true,\n        mode: \"application/ld+json\",\n        lineWrapping: true\n      });\n    </script>\n    \n    <p>This is a specialization of the <a href=\"index.html\">JavaScript mode</a>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/javascript/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"javascript\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"locals\",\n     \"[keyword function] [def foo]([def a], [def b]) { [keyword var] [def c] [operator =] [number 10]; [keyword return] [variable-2 a] [operator +] [variable-2 c] [operator +] [variable d]; }\");\n\n  MT(\"comma-and-binop\",\n     \"[keyword function](){ [keyword var] [def x] [operator =] [number 1] [operator +] [number 2], [def y]; }\");\n\n  MT(\"destructuring\",\n     \"([keyword function]([def a], [[[def b], [def c] ]]) {\",\n     \"  [keyword let] {[def d], [property foo]: [def c][operator =][number 10], [def x]} [operator =] [variable foo]([variable-2 a]);\",\n     \"  [[[variable-2 c], [variable y] ]] [operator =] [variable-2 c];\",\n     \"})();\");\n\n  MT(\"destructure_trailing_comma\",\n    \"[keyword let] {[def a], [def b],} [operator =] [variable foo];\",\n    \"[keyword let] [def c];\"); // Parser still in good state?\n\n  MT(\"class_body\",\n     \"[keyword class] [def Foo] {\",\n     \"  [property constructor]() {}\",\n     \"  [property sayName]() {\",\n     \"    [keyword return] [string-2 `foo${][variable foo][string-2 }oo`];\",\n     \"  }\",\n     \"}\");\n\n  MT(\"class\",\n     \"[keyword class] [def Point] [keyword extends] [variable SuperThing] {\",\n     \"  [keyword get] [property prop]() { [keyword return] [number 24]; }\",\n     \"  [property constructor]([def x], [def y]) {\",\n     \"    [keyword super]([string 'something']);\",\n     \"    [keyword this].[property x] [operator =] [variable-2 x];\",\n     \"  }\",\n     \"}\");\n\n  MT(\"anonymous_class_expression\",\n     \"[keyword const] [def Adder] [operator =] [keyword class] [keyword extends] [variable Arithmetic] {\",\n     \"  [property add]([def a], [def b]) {}\",\n     \"};\");\n\n  MT(\"named_class_expression\",\n     \"[keyword const] [def Subber] [operator =] [keyword class] [def Subtract] {\",\n     \"  [property sub]([def a], [def b]) {}\",\n     \"};\");\n\n  MT(\"class_async_method\",\n     \"[keyword class] [def Foo] {\",\n     \"  [property sayName1]() {}\",\n     \"  [keyword async] [property sayName2]() {}\",\n     \"}\");\n\n  MT(\"import\",\n     \"[keyword function] [def foo]() {\",\n     \"  [keyword import] [def $] [keyword from] [string 'jquery'];\",\n     \"  [keyword import] { [def encrypt], [def decrypt] } [keyword from] [string 'crypto'];\",\n     \"}\");\n\n  MT(\"import_trailing_comma\",\n     \"[keyword import] {[def foo], [def bar],} [keyword from] [string 'baz']\")\n\n  MT(\"import_dynamic\",\n     \"[keyword import]([string 'baz']).[property then]\")\n\n  MT(\"import_dynamic\",\n     \"[keyword const] [def t] [operator =] [keyword import]([string 'baz']).[property then]\")\n\n  MT(\"const\",\n     \"[keyword function] [def f]() {\",\n     \"  [keyword const] [[ [def a], [def b] ]] [operator =] [[ [number 1], [number 2] ]];\",\n     \"}\");\n\n  MT(\"for/of\",\n     \"[keyword for]([keyword let] [def of] [keyword of] [variable something]) {}\");\n\n  MT(\"for await\",\n     \"[keyword for] [keyword await]([keyword let] [def of] [keyword of] [variable something]) {}\");\n\n  MT(\"generator\",\n     \"[keyword function*] [def repeat]([def n]) {\",\n     \"  [keyword for]([keyword var] [def i] [operator =] [number 0]; [variable-2 i] [operator <] [variable-2 n]; [operator ++][variable-2 i])\",\n     \"    [keyword yield] [variable-2 i];\",\n     \"}\");\n\n  MT(\"let_scoping\",\n     \"[keyword function] [def scoped]([def n]) {\",\n     \"  { [keyword var] [def i]; } [variable-2 i];\",\n     \"  { [keyword let] [def j]; [variable-2 j]; } [variable j];\",\n     \"  [keyword if] ([atom true]) { [keyword const] [def k]; [variable-2 k]; } [variable k];\",\n     \"}\");\n\n  MT(\"switch_scoping\",\n     \"[keyword switch] ([variable x]) {\",\n     \"  [keyword default]:\",\n     \"    [keyword let] [def j];\",\n     \"    [keyword return] [variable-2 j]\",\n     \"}\",\n     \"[variable j];\")\n\n  MT(\"leaving_scope\",\n     \"[keyword function] [def a]() {\",\n     \"  {\",\n     \"    [keyword const] [def x] [operator =] [number 1]\",\n     \"    [keyword if] ([atom true]) {\",\n     \"      [keyword let] [def y] [operator =] [number 2]\",\n     \"      [keyword var] [def z] [operator =] [number 3]\",\n     \"      [variable console].[property log]([variable-2 x], [variable-2 y], [variable-2 z])\",\n     \"    }\",\n     \"    [variable console].[property log]([variable-2 x], [variable y], [variable-2 z])\",\n     \"  }\",\n     \"  [variable console].[property log]([variable x], [variable y], [variable-2 z])\",\n     \"}\")\n\n  MT(\"quotedStringAddition\",\n     \"[keyword let] [def f] [operator =] [variable a] [operator +] [string 'fatarrow'] [operator +] [variable c];\");\n\n  MT(\"quotedFatArrow\",\n     \"[keyword let] [def f] [operator =] [variable a] [operator +] [string '=>'] [operator +] [variable c];\");\n\n  MT(\"fatArrow\",\n     \"[variable array].[property filter]([def a] [operator =>] [variable-2 a] [operator +] [number 1]);\",\n     \"[variable a];\", // No longer in scope\n     \"[keyword let] [def f] [operator =] ([[ [def a], [def b] ]], [def c]) [operator =>] [variable-2 a] [operator +] [variable-2 c];\",\n     \"[variable c];\");\n\n  MT(\"spread\",\n     \"[keyword function] [def f]([def a], [meta ...][def b]) {\",\n     \"  [variable something]([variable-2 a], [meta ...][variable-2 b]);\",\n     \"}\");\n\n  MT(\"quasi\",\n     \"[variable re][string-2 `fofdlakj${][variable x] [operator +] ([variable re][string-2 `foo`]) [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]\");\n\n  MT(\"quasi_no_function\",\n     \"[variable x] [operator =] [string-2 `fofdlakj${][variable x] [operator +] [string-2 `foo`] [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]\");\n\n  MT(\"indent_statement\",\n     \"[keyword var] [def x] [operator =] [number 10]\",\n     \"[variable x] [operator +=] [variable y] [operator +]\",\n     \"  [atom Infinity]\",\n     \"[keyword debugger];\");\n\n  MT(\"indent_if\",\n     \"[keyword if] ([number 1])\",\n     \"  [keyword break];\",\n     \"[keyword else] [keyword if] ([number 2])\",\n     \"  [keyword continue];\",\n     \"[keyword else]\",\n     \"  [number 10];\",\n     \"[keyword if] ([number 1]) {\",\n     \"  [keyword break];\",\n     \"} [keyword else] [keyword if] ([number 2]) {\",\n     \"  [keyword continue];\",\n     \"} [keyword else] {\",\n     \"  [number 10];\",\n     \"}\");\n\n  MT(\"indent_for\",\n     \"[keyword for] ([keyword var] [def i] [operator =] [number 0];\",\n     \"     [variable i] [operator <] [number 100];\",\n     \"     [variable i][operator ++])\",\n     \"  [variable doSomething]([variable i]);\",\n     \"[keyword debugger];\");\n\n  MT(\"indent_c_style\",\n     \"[keyword function] [def foo]()\",\n     \"{\",\n     \"  [keyword debugger];\",\n     \"}\");\n\n  MT(\"indent_else\",\n     \"[keyword for] (;;)\",\n     \"  [keyword if] ([variable foo])\",\n     \"    [keyword if] ([variable bar])\",\n     \"      [number 1];\",\n     \"    [keyword else]\",\n     \"      [number 2];\",\n     \"  [keyword else]\",\n     \"    [number 3];\");\n\n  MT(\"indent_funarg\",\n     \"[variable foo]([number 10000],\",\n     \"    [keyword function]([def a]) {\",\n     \"  [keyword debugger];\",\n     \"};\");\n\n  MT(\"indent_below_if\",\n     \"[keyword for] (;;)\",\n     \"  [keyword if] ([variable foo])\",\n     \"    [number 1];\",\n     \"[number 2];\");\n\n  MT(\"indent_semicolonless_if\",\n     \"[keyword function] [def foo]() {\",\n     \"  [keyword if] ([variable x])\",\n     \"    [variable foo]()\",\n     \"}\")\n\n  MT(\"indent_semicolonless_if_with_statement\",\n     \"[keyword function] [def foo]() {\",\n     \"  [keyword if] ([variable x])\",\n     \"    [variable foo]()\",\n     \"  [variable bar]()\",\n     \"}\")\n\n  MT(\"multilinestring\",\n     \"[keyword var] [def x] [operator =] [string 'foo\\\\]\",\n     \"[string bar'];\");\n\n  MT(\"scary_regexp\",\n     \"[string-2 /foo[[/]]bar/];\");\n\n  MT(\"indent_strange_array\",\n     \"[keyword var] [def x] [operator =] [[\",\n     \"  [number 1],,\",\n     \"  [number 2],\",\n     \"]];\",\n     \"[number 10];\");\n\n  MT(\"param_default\",\n     \"[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {\",\n     \"  [keyword return] [variable-2 x];\",\n     \"}\");\n\n  MT(\n    \"param_destructuring\",\n    \"[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {\",\n    \"  [keyword return] [variable-2 x];\",\n    \"}\");\n\n  MT(\"new_target\",\n     \"[keyword function] [def F]([def target]) {\",\n     \"  [keyword if] ([variable-2 target] [operator &&] [keyword new].[keyword target].[property name]) {\",\n     \"    [keyword return] [keyword new]\",\n     \"      .[keyword target];\",\n     \"  }\",\n     \"}\");\n\n  MT(\"async\",\n     \"[keyword async] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }\");\n\n  MT(\"async_assignment\",\n     \"[keyword const] [def foo] [operator =] [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; };\");\n\n  MT(\"async_object\",\n     \"[keyword let] [def obj] [operator =] { [property async]: [atom false] };\");\n\n  // async be highlighet as keyword and foo as def, but it requires potentially expensive look-ahead. See #4173\n  MT(\"async_object_function\",\n     \"[keyword let] [def obj] [operator =] { [property async] [property foo]([def args]) { [keyword return] [atom true]; } };\");\n\n  MT(\"async_object_properties\",\n     \"[keyword let] [def obj] [operator =] {\",\n     \"  [property prop1]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },\",\n     \"  [property prop2]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },\",\n     \"  [property prop3]: [keyword async] [keyword function] [def prop3]([def args]) { [keyword return] [atom true]; },\",\n     \"};\");\n\n  MT(\"async_arrow\",\n     \"[keyword const] [def foo] [operator =] [keyword async] ([def args]) [operator =>] { [keyword return] [atom true]; };\");\n\n  MT(\"async_jquery\",\n     \"[variable $].[property ajax]({\",\n     \"  [property url]: [variable url],\",\n     \"  [property async]: [atom true],\",\n     \"  [property method]: [string 'GET']\",\n     \"});\");\n\n  MT(\"async_variable\",\n     \"[keyword const] [def async] [operator =] {[property a]: [number 1]};\",\n     \"[keyword const] [def foo] [operator =] [string-2 `bar ${][variable async].[property a][string-2 }`];\")\n\n  MT(\"bigint\", \"[number 1n] [operator +] [number 0x1afn] [operator +] [number 0o064n] [operator +] [number 0b100n];\")\n\n  MT(\"async_comment\",\n     \"[keyword async] [comment /**/] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }\");\n\n  MT(\"indent_switch\",\n     \"[keyword switch] ([variable x]) {\",\n     \"  [keyword default]:\",\n     \"    [keyword return] [number 2]\",\n     \"}\")\n\n  MT(\"regexp_corner_case\",\n     \"[operator +]{} [operator /] [atom undefined];\",\n     \"[[[meta ...][string-2 /\\\\//] ]];\",\n     \"[keyword void] [string-2 /\\\\//];\",\n     \"[keyword do] [string-2 /\\\\//]; [keyword while] ([number 0]);\",\n     \"[keyword if] ([number 0]) {} [keyword else] [string-2 /\\\\//];\",\n     \"[string-2 `${][variable async][operator ++][string-2 }//`];\",\n     \"[string-2 `${]{} [operator /] [string-2 /\\\\//}`];\")\n\n  MT(\"return_eol\",\n     \"[keyword return]\",\n     \"{} [string-2 /5/]\")\n\n  var ts_mode = CodeMirror.getMode({indentUnit: 2}, \"application/typescript\")\n  function TS(name) {\n    test.mode(name, ts_mode, Array.prototype.slice.call(arguments, 1))\n  }\n\n  TS(\"typescript_extend_type\",\n     \"[keyword class] [def Foo] [keyword extends] [type Some][operator <][type Type][operator >] {}\")\n\n  TS(\"typescript_arrow_type\",\n     \"[keyword let] [def x]: ([variable arg]: [type Type]) [operator =>] [type ReturnType]\")\n\n  TS(\"typescript_class\",\n     \"[keyword class] [def Foo] {\",\n     \"  [keyword public] [keyword static] [property main]() {}\",\n     \"  [keyword private] [property _foo]: [type string];\",\n     \"}\")\n\n  TS(\"typescript_literal_types\",\n     \"[keyword import] [keyword *] [keyword as] [def Sequelize] [keyword from] [string 'sequelize'];\",\n     \"[keyword interface] [def MyAttributes] {\",\n     \"  [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];\",\n     \"  [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];\",\n     \"}\",\n     \"[keyword interface] [def MyInstance] [keyword extends] [type Sequelize].[type Instance] [operator <] [type MyAttributes] [operator >] {\",\n     \"  [property rawAttributes]: [type MyAttributes];\",\n     \"  [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];\",\n     \"  [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];\",\n     \"}\")\n\n  TS(\"typescript_extend_operators\",\n     \"[keyword export] [keyword interface] [def UserModel] [keyword extends]\",\n     \"  [type Sequelize].[type Model] [operator <] [type UserInstance], [type UserAttributes] [operator >] {\",\n     \"    [property findById]: (\",\n     \"    [variable userId]: [type number]\",\n     \"    ) [operator =>] [type Promise] [operator <] [type Array] [operator <] { [property id], [property name] } [operator >>];\",\n     \"    [property updateById]: (\",\n     \"    [variable userId]: [type number],\",\n     \"    [variable isActive]: [type boolean]\",\n     \"    ) [operator =>] [type Promise] [operator <] [type AccountHolderNotificationPreferenceInstance] [operator >];\",\n     \"  }\")\n\n  TS(\"typescript_interface_with_const\",\n     \"[keyword const] [def hello]: {\",\n     \"  [property prop1][operator ?]: [type string];\",\n     \"  [property prop2][operator ?]: [type string];\",\n     \"} [operator =] {};\")\n\n  TS(\"typescript_double_extend\",\n     \"[keyword export] [keyword interface] [def UserAttributes] {\",\n     \"  [property id][operator ?]: [type number];\",\n     \"  [property createdAt][operator ?]: [type Date];\",\n     \"}\",\n     \"[keyword export] [keyword interface] [def UserInstance] [keyword extends] [type Sequelize].[type Instance][operator <][type UserAttributes][operator >], [type UserAttributes] {\",\n     \"  [property id]: [type number];\",\n     \"  [property createdAt]: [type Date];\",\n     \"}\");\n\n  TS(\"typescript_index_signature\",\n     \"[keyword interface] [def A] {\",\n     \"  [[ [variable prop]: [type string] ]]: [type any];\",\n     \"  [property prop1]: [type any];\",\n     \"}\");\n\n  TS(\"typescript_generic_class\",\n     \"[keyword class] [def Foo][operator <][type T][operator >] {\",\n     \"  [property bar]() {}\",\n     \"  [property foo](): [type Foo] {}\",\n     \"}\")\n\n  TS(\"typescript_type_when_keyword\",\n     \"[keyword export] [keyword type] [type AB] [operator =] [type A] [operator |] [type B];\",\n     \"[keyword type] [type Flags] [operator =] {\",\n     \"  [property p1]: [type string];\",\n     \"  [property p2]: [type boolean];\",\n     \"};\")\n\n  TS(\"typescript_type_when_not_keyword\",\n     \"[keyword class] [def HasType] {\",\n     \"  [property type]: [type string];\",\n     \"  [property constructor]([def type]: [type string]) {\",\n     \"    [keyword this].[property type] [operator =] [variable-2 type];\",\n     \"  }\",\n     \"  [property setType]({ [def type] }: { [property type]: [type string]; }) {\",\n     \"    [keyword this].[property type] [operator =] [variable-2 type];\",\n     \"  }\",\n     \"}\")\n\n  TS(\"typescript_function_generics\",\n     \"[keyword function] [def a]() {}\",\n     \"[keyword function] [def b][operator <][type IA] [keyword extends] [type object], [type IB] [keyword extends] [type object][operator >]() {}\",\n     \"[keyword function] [def c]() {}\")\n\n  TS(\"typescript_complex_return_type\",\n     \"[keyword function] [def A]() {\",\n     \"  [keyword return] [keyword this].[property property];\",\n     \"}\",\n     \"[keyword function] [def B](): [type Promise][operator <]{ [[ [variable key]: [type string] ]]: [type any] } [operator |] [atom null][operator >] {\",\n     \"  [keyword return] [keyword this].[property property];\",\n     \"}\")\n\n  TS(\"typescript_complex_type_casting\",\n     \"[keyword const] [def giftpay] [operator =] [variable config].[property get]([string 'giftpay']) [keyword as] { [[ [variable platformUuid]: [type string] ]]: { [property version]: [type number]; [property apiCode]: [type string]; } };\")\n\n  TS(\"typescript_keyof\",\n     \"[keyword function] [def x][operator <][type T] [keyword extends] [keyword keyof] [type X][operator >]([def a]: [type T]) {\",\n     \"  [keyword return]\")\n\n  TS(\"typescript_new_typeargs\",\n     \"[keyword let] [def x] [operator =] [keyword new] [variable Map][operator <][type string], [type Date][operator >]([string-2 `foo${][variable bar][string-2 }`])\")\n\n  TS(\"modifiers\",\n     \"[keyword class] [def Foo] {\",\n     \"  [keyword public] [keyword abstract] [property bar]() {}\",\n     \"  [property constructor]([keyword readonly] [keyword private] [def x]) {}\",\n     \"}\")\n\n  TS(\"arrow prop\",\n     \"({[property a]: [def p] [operator =>] [variable-2 p]})\")\n\n  TS(\"generic in function call\",\n     \"[keyword this].[property a][operator <][type Type][operator >]([variable foo]);\",\n     \"[keyword this].[property a][operator <][variable Type][operator >][variable foo];\")\n\n  TS(\"type guard\",\n     \"[keyword class] [def Appler] {\",\n     \"  [keyword static] [property assertApple]([def fruit]: [type Fruit]): [variable-2 fruit] [keyword is] [type Apple] {\",\n     \"    [keyword if] ([operator !]([variable-2 fruit] [keyword instanceof] [variable Apple]))\",\n     \"      [keyword throw] [keyword new] [variable Error]();\",\n     \"  }\",\n     \"}\")\n\n  TS(\"type as variable\",\n     \"[variable type] [operator =] [variable x] [keyword as] [type Bar];\");\n\n  TS(\"enum body\",\n     \"[keyword export] [keyword const] [keyword enum] [def CodeInspectionResultType] {\",\n     \"  [def ERROR] [operator =] [string 'problem_type_error'],\",\n     \"  [def WARNING] [operator =] [string 'problem_type_warning'],\",\n     \"  [def META],\",\n     \"}\")\n\n  TS(\"parenthesized type\",\n     \"[keyword class] [def Foo] {\",\n     \"  [property x] [operator =] [keyword new] [variable A][operator <][type B], [type string][operator |](() [operator =>] [type void])[operator >]();\",\n     \"  [keyword private] [property bar]();\",\n     \"}\")\n\n  TS(\"abstract class\",\n     \"[keyword export] [keyword abstract] [keyword class] [def Foo] {}\")\n\n  TS(\"interface without semicolons\",\n     \"[keyword interface] [def Foo] {\",\n     \"  [property greet]([def x]: [type int]): [type blah]\",\n     \"  [property bar]: [type void]\",\n     \"}\")\n\n  var jsonld_mode = CodeMirror.getMode(\n    {indentUnit: 2},\n    {name: \"javascript\", jsonld: true}\n  );\n  function LD(name) {\n    test.mode(name, jsonld_mode, Array.prototype.slice.call(arguments, 1));\n  }\n\n  LD(\"json_ld_keywords\",\n    '{',\n    '  [meta \"@context\"]: {',\n    '    [meta \"@base\"]: [string \"http://example.com\"],',\n    '    [meta \"@vocab\"]: [string \"http://xmlns.com/foaf/0.1/\"],',\n    '    [property \"likesFlavor\"]: {',\n    '      [meta \"@container\"]: [meta \"@list\"]',\n    '      [meta \"@reverse\"]: [string \"@beFavoriteOf\"]',\n    '    },',\n    '    [property \"nick\"]: { [meta \"@container\"]: [meta \"@set\"] },',\n    '    [property \"nick\"]: { [meta \"@container\"]: [meta \"@index\"] }',\n    '  },',\n    '  [meta \"@graph\"]: [[ {',\n    '    [meta \"@id\"]: [string \"http://dbpedia.org/resource/John_Lennon\"],',\n    '    [property \"name\"]: [string \"John Lennon\"],',\n    '    [property \"modified\"]: {',\n    '      [meta \"@value\"]: [string \"2010-05-29T14:17:39+02:00\"],',\n    '      [meta \"@type\"]: [string \"http://www.w3.org/2001/XMLSchema#dateTime\"]',\n    '    }',\n    '  } ]]',\n    '}');\n\n  LD(\"json_ld_fake\",\n    '{',\n    '  [property \"@fake\"]: [string \"@fake\"],',\n    '  [property \"@contextual\"]: [string \"@identifier\"],',\n    '  [property \"user@domain.com\"]: [string \"@graphical\"],',\n    '  [property \"@ID\"]: [string \"@@ID\"]',\n    '}');\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/javascript/typescript.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: TypeScript mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"javascript.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">TypeScript</a>\n  </ul>\n</div>\n\n<article>\n<h2>TypeScript mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\nclass Greeter {\n  greeting: string;\n  constructor (message: string) {\n    this.greeting = message;\n  }\n  greet() {\n    return \"Hello, \" + this.greeting;\n  }\n}   \n\nvar greeter = new Greeter(\"world\");\n\nvar button = document.createElement('button')\nbutton.innerText = \"Say Hello\"\nbutton.onclick = function() {\n  alert(greeter.greet())\n}\n\ndocument.body.appendChild(button)\n\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/typescript\"\n      });\n    </script>\n\n    <p>This is a specialization of the <a href=\"index.html\">JavaScript mode</a>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/jinja2/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Jinja2 mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"jinja2.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Jinja2</a>\n  </ul>\n</div>\n\n<article>\n<h2>Jinja2 mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n{# this is a comment #}\n{%- for item in li -%}\n  &lt;li&gt;{{ item.label }}&lt;/li&gt;\n{% endfor -%}\n{{ item.sand == true and item.keyword == false ? 1 : 0 }}\n{{ app.get(55, 1.2, true) }}\n{% if app.get(&#39;_route&#39;) == (&#39;_home&#39;) %}home{% endif %}\n{% if app.session.flashbag.has(&#39;message&#39;) %}\n  {% for message in app.session.flashbag.get(&#39;message&#39;) %}\n    {{ message.content }}\n  {% endfor %}\n{% endif %}\n{{ path(&#39;_home&#39;, {&#39;section&#39;: app.request.get(&#39;section&#39;)}) }}\n{{ path(&#39;_home&#39;, {\n    &#39;section&#39;: app.request.get(&#39;section&#39;),\n    &#39;boolean&#39;: true,\n    &#39;number&#39;: 55.33\n  })\n}}\n{% include (&#39;test.incl.html.twig&#39;) %}\n</textarea></form>\n    <script>\n      var editor =\n      CodeMirror.fromTextArea(document.getElementById(\"code\"), {mode:\n        {name: \"jinja2\", htmlMode: true}});\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/jinja2/jinja2.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"jinja2\", function() {\n    var keywords = [\"and\", \"as\", \"block\", \"endblock\", \"by\", \"cycle\", \"debug\", \"else\", \"elif\",\n      \"extends\", \"filter\", \"endfilter\", \"firstof\", \"for\",\n      \"endfor\", \"if\", \"endif\", \"ifchanged\", \"endifchanged\",\n      \"ifequal\", \"endifequal\", \"ifnotequal\",\n      \"endifnotequal\", \"in\", \"include\", \"load\", \"not\", \"now\", \"or\",\n      \"parsed\", \"regroup\", \"reversed\", \"spaceless\",\n      \"endspaceless\", \"ssi\", \"templatetag\", \"openblock\",\n      \"closeblock\", \"openvariable\", \"closevariable\",\n      \"openbrace\", \"closebrace\", \"opencomment\",\n      \"closecomment\", \"widthratio\", \"url\", \"with\", \"endwith\",\n      \"get_current_language\", \"trans\", \"endtrans\", \"noop\", \"blocktrans\",\n      \"endblocktrans\", \"get_available_languages\",\n      \"get_current_language_bidi\", \"plural\"],\n    operator = /^[+\\-*&%=<>!?|~^]/,\n    sign = /^[:\\[\\(\\{]/,\n    atom = [\"true\", \"false\"],\n    number = /^(\\d[+\\-\\*\\/])?\\d+(\\.\\d+)?/;\n\n    keywords = new RegExp(\"((\" + keywords.join(\")|(\") + \"))\\\\b\");\n    atom = new RegExp(\"((\" + atom.join(\")|(\") + \"))\\\\b\");\n\n    function tokenBase (stream, state) {\n      var ch = stream.peek();\n\n      //Comment\n      if (state.incomment) {\n        if(!stream.skipTo(\"#}\")) {\n          stream.skipToEnd();\n        } else {\n          stream.eatWhile(/\\#|}/);\n          state.incomment = false;\n        }\n        return \"comment\";\n      //Tag\n      } else if (state.intag) {\n        //After operator\n        if(state.operator) {\n          state.operator = false;\n          if(stream.match(atom)) {\n            return \"atom\";\n          }\n          if(stream.match(number)) {\n            return \"number\";\n          }\n        }\n        //After sign\n        if(state.sign) {\n          state.sign = false;\n          if(stream.match(atom)) {\n            return \"atom\";\n          }\n          if(stream.match(number)) {\n            return \"number\";\n          }\n        }\n\n        if(state.instring) {\n          if(ch == state.instring) {\n            state.instring = false;\n          }\n          stream.next();\n          return \"string\";\n        } else if(ch == \"'\" || ch == '\"') {\n          state.instring = ch;\n          stream.next();\n          return \"string\";\n        } else if(stream.match(state.intag + \"}\") || stream.eat(\"-\") && stream.match(state.intag + \"}\")) {\n          state.intag = false;\n          return \"tag\";\n        } else if(stream.match(operator)) {\n          state.operator = true;\n          return \"operator\";\n        } else if(stream.match(sign)) {\n          state.sign = true;\n        } else {\n          if(stream.eat(\" \") || stream.sol()) {\n            if(stream.match(keywords)) {\n              return \"keyword\";\n            }\n            if(stream.match(atom)) {\n              return \"atom\";\n            }\n            if(stream.match(number)) {\n              return \"number\";\n            }\n            if(stream.sol()) {\n              stream.next();\n            }\n          } else {\n            stream.next();\n          }\n\n        }\n        return \"variable\";\n      } else if (stream.eat(\"{\")) {\n        if (stream.eat(\"#\")) {\n          state.incomment = true;\n          if(!stream.skipTo(\"#}\")) {\n            stream.skipToEnd();\n          } else {\n            stream.eatWhile(/\\#|}/);\n            state.incomment = false;\n          }\n          return \"comment\";\n        //Open tag\n        } else if (ch = stream.eat(/\\{|%/)) {\n          //Cache close tag\n          state.intag = ch;\n          if(ch == \"{\") {\n            state.intag = \"}\";\n          }\n          stream.eat(\"-\");\n          return \"tag\";\n        }\n      }\n      stream.next();\n    };\n\n    return {\n      startState: function () {\n        return {tokenize: tokenBase};\n      },\n      token: function (stream, state) {\n        return state.tokenize(stream, state);\n      },\n      blockCommentStart: \"{#\",\n      blockCommentEnd: \"#}\"\n    };\n  });\n\n  CodeMirror.defineMIME(\"text/jinja2\", \"jinja2\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/jsx/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: JSX mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"jsx.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">JSX</a>\n  </ul>\n</div>\n\n<article>\n<h2>JSX mode</h2>\n\n<div><textarea id=\"code\" name=\"code\">// Code snippets from http://facebook.github.io/react/docs/jsx-in-depth.html\n\n// Rendering HTML tags\nvar myDivElement = <div className=\"foo\" />;\nReactDOM.render(myDivElement, document.getElementById('example'));\n\n// Rendering React components\nvar MyComponent = React.createClass({/*...*/});\nvar myElement = <MyComponent someProperty={true} />;\nReactDOM.render(myElement, document.getElementById('example'));\n\n// Namespaced components\nvar Form = MyFormComponent;\n\nvar App = (\n  <Form>\n    <Form.Row>\n      <Form.Label />\n      <Form.Input />\n    </Form.Row>\n  </Form>\n);\n\n// Attribute JavaScript expressions\nvar person = <Person name={window.isLoggedIn ? window.name : ''} />;\n\n// Boolean attributes\n<input type=\"button\" disabled />;\n<input type=\"button\" disabled={true} />;\n\n// Child JavaScript expressions\nvar content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;\n\n// Comments\nvar content = (\n  <Nav>\n    {/* child comment, put {} around */}\n    <Person\n      /* multi\n         line\n         comment */\n      name={window.isLoggedIn ? window.name : ''} // end of line comment\n    />\n  </Nav>\n);\n</textarea></div>\n\n<script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true,\n  mode: \"jsx\"\n})\n</script>\n\n<p>JSX Mode for <a href=\"http://facebook.github.io/react\">React</a>'s\nJavaScript syntax extension.</p>\n\n<p><strong>MIME types defined:</strong> <code>text/jsx</code>, <code>text/typescript-jsx</code>.</p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/jsx/jsx.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../xml/xml\"), require(\"../javascript/javascript\"))\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../xml/xml\", \"../javascript/javascript\"], mod)\n  else // Plain browser env\n    mod(CodeMirror)\n})(function(CodeMirror) {\n  \"use strict\"\n\n  // Depth means the amount of open braces in JS context, in XML\n  // context 0 means not in tag, 1 means in tag, and 2 means in tag\n  // and js block comment.\n  function Context(state, mode, depth, prev) {\n    this.state = state; this.mode = mode; this.depth = depth; this.prev = prev\n  }\n\n  function copyContext(context) {\n    return new Context(CodeMirror.copyState(context.mode, context.state),\n                       context.mode,\n                       context.depth,\n                       context.prev && copyContext(context.prev))\n  }\n\n  CodeMirror.defineMode(\"jsx\", function(config, modeConfig) {\n    var xmlMode = CodeMirror.getMode(config, {name: \"xml\", allowMissing: true, multilineTagIndentPastTag: false, allowMissingTagName: true})\n    var jsMode = CodeMirror.getMode(config, modeConfig && modeConfig.base || \"javascript\")\n\n    function flatXMLIndent(state) {\n      var tagName = state.tagName\n      state.tagName = null\n      var result = xmlMode.indent(state, \"\", \"\")\n      state.tagName = tagName\n      return result\n    }\n\n    function token(stream, state) {\n      if (state.context.mode == xmlMode)\n        return xmlToken(stream, state, state.context)\n      else\n        return jsToken(stream, state, state.context)\n    }\n\n    function xmlToken(stream, state, cx) {\n      if (cx.depth == 2) { // Inside a JS /* */ comment\n        if (stream.match(/^.*?\\*\\//)) cx.depth = 1\n        else stream.skipToEnd()\n        return \"comment\"\n      }\n\n      if (stream.peek() == \"{\") {\n        xmlMode.skipAttribute(cx.state)\n\n        var indent = flatXMLIndent(cx.state), xmlContext = cx.state.context\n        // If JS starts on same line as tag\n        if (xmlContext && stream.match(/^[^>]*>\\s*$/, false)) {\n          while (xmlContext.prev && !xmlContext.startOfLine)\n            xmlContext = xmlContext.prev\n          // If tag starts the line, use XML indentation level\n          if (xmlContext.startOfLine) indent -= config.indentUnit\n          // Else use JS indentation level\n          else if (cx.prev.state.lexical) indent = cx.prev.state.lexical.indented\n        // Else if inside of tag\n        } else if (cx.depth == 1) {\n          indent += config.indentUnit\n        }\n\n        state.context = new Context(CodeMirror.startState(jsMode, indent),\n                                    jsMode, 0, state.context)\n        return null\n      }\n\n      if (cx.depth == 1) { // Inside of tag\n        if (stream.peek() == \"<\") { // Tag inside of tag\n          xmlMode.skipAttribute(cx.state)\n          state.context = new Context(CodeMirror.startState(xmlMode, flatXMLIndent(cx.state)),\n                                      xmlMode, 0, state.context)\n          return null\n        } else if (stream.match(\"//\")) {\n          stream.skipToEnd()\n          return \"comment\"\n        } else if (stream.match(\"/*\")) {\n          cx.depth = 2\n          return token(stream, state)\n        }\n      }\n\n      var style = xmlMode.token(stream, cx.state), cur = stream.current(), stop\n      if (/\\btag\\b/.test(style)) {\n        if (/>$/.test(cur)) {\n          if (cx.state.context) cx.depth = 0\n          else state.context = state.context.prev\n        } else if (/^</.test(cur)) {\n          cx.depth = 1\n        }\n      } else if (!style && (stop = cur.indexOf(\"{\")) > -1) {\n        stream.backUp(cur.length - stop)\n      }\n      return style\n    }\n\n    function jsToken(stream, state, cx) {\n      if (stream.peek() == \"<\" && jsMode.expressionAllowed(stream, cx.state)) {\n        jsMode.skipExpression(cx.state)\n        state.context = new Context(CodeMirror.startState(xmlMode, jsMode.indent(cx.state, \"\", \"\")),\n                                    xmlMode, 0, state.context)\n        return null\n      }\n\n      var style = jsMode.token(stream, cx.state)\n      if (!style && cx.depth != null) {\n        var cur = stream.current()\n        if (cur == \"{\") {\n          cx.depth++\n        } else if (cur == \"}\") {\n          if (--cx.depth == 0) state.context = state.context.prev\n        }\n      }\n      return style\n    }\n\n    return {\n      startState: function() {\n        return {context: new Context(CodeMirror.startState(jsMode), jsMode)}\n      },\n\n      copyState: function(state) {\n        return {context: copyContext(state.context)}\n      },\n\n      token: token,\n\n      indent: function(state, textAfter, fullLine) {\n        return state.context.mode.indent(state.context.state, textAfter, fullLine)\n      },\n\n      innerMode: function(state) {\n        return state.context\n      }\n    }\n  }, \"xml\", \"javascript\")\n\n  CodeMirror.defineMIME(\"text/jsx\", \"jsx\")\n  CodeMirror.defineMIME(\"text/typescript-jsx\", {name: \"jsx\", base: {name: \"javascript\", typescript: true}})\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/jsx/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"jsx\")\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)) }\n\n  MT(\"selfclose\",\n     \"[keyword var] [def x] [operator =] [bracket&tag <] [tag foo] [bracket&tag />] [operator +] [number 1];\")\n\n  MT(\"openclose\",\n     \"([bracket&tag <][tag foo][bracket&tag >]hello [atom &amp;][bracket&tag </][tag foo][bracket&tag >][operator ++])\")\n\n  MT(\"openclosefragment\",\n     \"([bracket&tag <><][tag foo][bracket&tag >]hello [atom &amp;][bracket&tag </][tag foo][bracket&tag ></>][operator ++])\")\n\n  MT(\"attr\",\n     \"([bracket&tag <][tag foo] [attribute abc]=[string 'value'][bracket&tag >]hello [atom &amp;][bracket&tag </][tag foo][bracket&tag >][operator ++])\")\n\n  MT(\"braced_attr\",\n     \"([bracket&tag <][tag foo] [attribute abc]={[number 10]}[bracket&tag >]hello [atom &amp;][bracket&tag </][tag foo][bracket&tag >][operator ++])\")\n\n  MT(\"braced_text\",\n     \"([bracket&tag <][tag foo][bracket&tag >]hello {[number 10]} [atom &amp;][bracket&tag </][tag foo][bracket&tag >][operator ++])\")\n\n  MT(\"nested_tag\",\n     \"([bracket&tag <][tag foo][bracket&tag ><][tag bar][bracket&tag ></][tag bar][bracket&tag ></][tag foo][bracket&tag >][operator ++])\")\n\n  MT(\"nested_jsx\",\n     \"[keyword return] (\",\n     \"  [bracket&tag <][tag foo][bracket&tag >]\",\n     \"    say {[number 1] [operator +] [bracket&tag <][tag bar] [attribute attr]={[number 10]}[bracket&tag />]}!\",\n     \"  [bracket&tag </][tag foo][bracket&tag >][operator ++]\",\n     \")\")\n\n  MT(\"preserve_js_context\",\n     \"[variable x] [operator =] [string-2 `quasi${][bracket&tag <][tag foo][bracket&tag />][string-2 }quoted`]\")\n\n  MT(\"string_interpolation\",\n    \"[variable x] [operator =] [string-2 `quasi<code>${] [number 10] [string-2 }</code>`]\")\n\n  MT(\"line_comment\",\n     \"([bracket&tag <][tag foo] [comment // hello]\",\n     \"   [bracket&tag ></][tag foo][bracket&tag >][operator ++])\")\n\n  MT(\"line_comment_not_in_tag\",\n     \"([bracket&tag <][tag foo][bracket&tag >] // hello\",\n     \"  [bracket&tag </][tag foo][bracket&tag >][operator ++])\")\n\n  MT(\"block_comment\",\n     \"([bracket&tag <][tag foo] [comment /* hello]\",\n     \"[comment    line 2]\",\n     \"[comment    line 3 */] [bracket&tag ></][tag foo][bracket&tag >][operator ++])\")\n\n  MT(\"block_comment_not_in_tag\",\n     \"([bracket&tag <][tag foo][bracket&tag >]/* hello\",\n     \"    line 2\",\n     \"    line 3 */ [bracket&tag </][tag foo][bracket&tag >][operator ++])\")\n\n  MT(\"missing_attr\",\n     \"([bracket&tag <][tag foo] [attribute selected][bracket&tag />][operator ++])\")\n\n  MT(\"indent_js\",\n     \"([bracket&tag <][tag foo][bracket&tag >]\",\n     \"    [bracket&tag <][tag bar] [attribute baz]={[keyword function]() {\",\n     \"        [keyword return] [number 10]\",\n     \"      }}[bracket&tag />]\",\n     \"  [bracket&tag </][tag foo][bracket&tag >])\")\n\n  MT(\"spread\",\n     \"([bracket&tag <][tag foo] [attribute bar]={[meta ...][variable baz] [operator /][number 2]}[bracket&tag />])\")\n\n  MT(\"tag_attribute\",\n     \"([bracket&tag <][tag foo] [attribute bar]=[bracket&tag <][tag foo][bracket&tag />/>][operator ++])\")\n\n  var ts_mode = CodeMirror.getMode({indentUnit: 2}, \"text/typescript-jsx\")\n  function TS(name) { test.mode(name, ts_mode, Array.prototype.slice.call(arguments, 1)) }\n\n  TS(\"tsx_react_integration\",\n     \"[keyword interface] [def Props] {\",\n     \"  [property foo]: [type string];\",\n     \"}\",\n     \"[keyword class] [def MyComponent] [keyword extends] [type React].[type Component] [operator <] [type Props], [type any] [operator >] {\",\n     \"  [property render]() {\",\n     \"    [keyword return] [bracket&tag <][tag span][bracket&tag >]{[keyword this].[property props].[property foo]}[bracket&tag </][tag span][bracket&tag >]\",\n     \"  }\",\n     \"}\",\n     \"[bracket&tag <][tag MyComponent] [attribute foo]=[string \\\"bar\\\"] [bracket&tag />]; [comment //ok]\",\n     \"[bracket&tag <][tag MyComponent] [attribute foo]={[number 0]} [bracket&tag />]; [comment //error]\")\n\n})()\n"
  },
  {
    "path": "third_party/CodeMirror/mode/julia/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Julia mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"julia.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Julia</a>\n  </ul>\n</div>\n\n<article>\n<h2>Julia mode</h2>\n\n    <div><textarea id=\"code\" name=\"code\">\n#numbers\n1234\n1234im\n.234\n.234im\n2.23im\n2.3f3\n23e2\n0x234\n\n#strings\n'a'\n\"asdf\"\nr\"regex\"\nb\"bytestring\"\n\n\"\"\"\nmultiline string\n\"\"\"\n\n#identifiers\na\nas123\nfunction_name!\n\n#unicode identifiers\n# a = x\\ddot\na⃗ = ẍ\n# a = v\\dot\na⃗ = v̇\n#F\\vec = m \\cdotp a\\vec\nF⃗ = m·a⃗\n\n#literal identifier multiples\n3x\n4[1, 2, 3]\n\n#dicts and indexing\nx=[1, 2, 3]\nx[end-1]\nx={\"julia\"=>\"language of technical computing\"}\n\n\n#exception handling\ntry\n  f()\ncatch\n  @printf \"Error\"\nfinally\n  g()\nend\n\n#types\nimmutable Color{T<:Number}\n  r::T\n  g::T\n  b::T\nend\n\n#functions\nfunction change!(x::Vector{Float64})\n  for i = 1:length(x)\n    x[i] *= 2\n  end\nend\n\n#function invocation\nf('b', (2, 3)...)\n\n#operators\n|=\n&=\n^=\n\\-\n%=\n*=\n+=\n-=\n<=\n>=\n!=\n==\n%\n*\n+\n-\n<\n>\n!\n=\n|\n&\n^\n\\\n?\n~\n:\n$\n<:\n.<\n.>\n<<\n<<=\n>>\n>>>>\n>>=\n>>>=\n<<=\n<<<=\n.<=\n.>=\n.==\n->\n//\nin\n...\n//\n:=\n.//=\n.*=\n./=\n.^=\n.%=\n.+=\n.-=\n\\=\n\\\\=\n||\n===\n&&\n|=\n.|=\n<:\n>:\n|>\n<|\n::\nx ? y : z\n\n#macros\n@spawnat 2 1+1\n@eval(:x)\n\n#keywords and operators\nif else elseif while for\n begin let end do\ntry catch finally return break continue\nglobal local const \nexport import importall using\nfunction macro module baremodule \ntype immutable quote\ntrue false enumerate\n\n\n    </textarea></div>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"julia\",\n               },\n        lineNumbers: true,\n        indentUnit: 4,\n        matchBrackets: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-julia</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/julia/julia.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"julia\", function(config, parserConf) {\n  function wordRegexp(words, end) {\n    if (typeof end === \"undefined\") { end = \"\\\\b\"; }\n    return new RegExp(\"^((\" + words.join(\")|(\") + \"))\" + end);\n  }\n\n  var octChar = \"\\\\\\\\[0-7]{1,3}\";\n  var hexChar = \"\\\\\\\\x[A-Fa-f0-9]{1,2}\";\n  var sChar = \"\\\\\\\\[abefnrtv0%?'\\\"\\\\\\\\]\";\n  var uChar = \"([^\\\\u0027\\\\u005C\\\\uD800-\\\\uDFFF]|[\\\\uD800-\\\\uDFFF][\\\\uDC00-\\\\uDFFF])\";\n\n  var operators = parserConf.operators || wordRegexp([\n      \"[<>]:\", \"[<>=]=\", \"<<=?\", \">>>?=?\", \"=>\", \"->\", \"\\\\/\\\\/\",\n      \"[\\\\\\\\%*+\\\\-<>!=\\\\/^|&\\\\u00F7\\\\u22BB]=?\", \"\\\\?\", \"\\\\$\", \"~\", \":\",\n      \"\\\\u00D7\", \"\\\\u2208\", \"\\\\u2209\", \"\\\\u220B\", \"\\\\u220C\", \"\\\\u2218\",\n      \"\\\\u221A\", \"\\\\u221B\", \"\\\\u2229\", \"\\\\u222A\", \"\\\\u2260\", \"\\\\u2264\",\n      \"\\\\u2265\", \"\\\\u2286\", \"\\\\u2288\", \"\\\\u228A\", \"\\\\u22C5\",\n      \"\\\\b(in|isa)\\\\b(?!\\.?\\\\()\"], \"\");\n  var delimiters = parserConf.delimiters || /^[;,()[\\]{}]/;\n  var identifiers = parserConf.identifiers ||\n      /^[_A-Za-z\\u00A1-\\u2217\\u2219-\\uFFFF][\\w\\u00A1-\\u2217\\u2219-\\uFFFF]*!*/;\n\n  var chars = wordRegexp([octChar, hexChar, sChar, uChar], \"'\");\n\n  var commonOpeners = [\"begin\", \"function\", \"type\", \"struct\", \"immutable\",\n      \"let\", \"macro\", \"for\", \"while\", \"quote\", \"if\", \"else\", \"elseif\", \"try\",\n                       \"finally\", \"catch\", \"do\"];\n\n  var commonClosers = [\"end\", \"else\", \"elseif\", \"catch\", \"finally\"];\n\n  var commonKeywords = [\"if\", \"else\", \"elseif\", \"while\", \"for\", \"begin\",\n                        \"let\", \"end\", \"do\", \"try\", \"catch\", \"finally\", \"return\", \"break\",\n                        \"continue\", \"global\", \"local\", \"const\", \"export\", \"import\", \"importall\",\n                        \"using\", \"function\", \"where\", \"macro\", \"module\", \"baremodule\", \"struct\",\n                        \"type\", \"mutable\", \"immutable\", \"quote\", \"typealias\", \"abstract\",\n                        \"primitive\", \"bitstype\"];\n\n  var commonBuiltins = [\"true\", \"false\", \"nothing\", \"NaN\", \"Inf\"];\n\n  CodeMirror.registerHelper(\"hintWords\", \"julia\", commonKeywords.concat(commonBuiltins));\n\n  var openers = wordRegexp(commonOpeners);\n  var closers = wordRegexp(commonClosers);\n  var keywords = wordRegexp(commonKeywords);\n  var builtins = wordRegexp(commonBuiltins);\n\n  var macro = /^@[_A-Za-z][\\w]*/;\n  var symbol = /^:[_A-Za-z\\u00A1-\\uFFFF][\\w\\u00A1-\\uFFFF]*!*/;\n  var stringPrefixes = /^(`|([_A-Za-z\\u00A1-\\uFFFF]*\"(\"\")?))/;\n\n  function inArray(state) {\n    return inGenerator(state, '[')\n  }\n\n  function inGenerator(state, bracket, depth) {\n    if (typeof(bracket) === \"undefined\") { bracket = '('; }\n    if (typeof(depth)   === \"undefined\") { depth   = 0;   }\n    var scope = currentScope(state, depth);\n    if ((depth == 0 && scope === \"if\" && inGenerator(state, bracket, depth + 1)) ||\n        (scope === \"for\" && inGenerator(state, bracket, depth + 1)) ||\n        (scope === bracket)) {\n      return true;\n    }\n    return false;\n  }\n\n  function currentScope(state, n) {\n    if (typeof(n) === \"undefined\") { n = 0; }\n    if (state.scopes.length <= n) {\n      return null;\n    }\n    return state.scopes[state.scopes.length - (n + 1)];\n  }\n\n  // tokenizers\n  function tokenBase(stream, state) {\n    // Handle multiline comments\n    if (stream.match(/^#=/, false)) {\n      state.tokenize = tokenComment;\n      return state.tokenize(stream, state);\n    }\n\n    // Handle scope changes\n    var leavingExpr = state.leavingExpr;\n    if (stream.sol()) {\n      leavingExpr = false;\n    }\n    state.leavingExpr = false;\n\n    if (leavingExpr) {\n      if (stream.match(/^'+/)) {\n        return \"operator\";\n      }\n    }\n\n    if (stream.match(/\\.{4,}/)) {\n      return \"error\";\n    } else if (stream.match(/\\.{1,3}/)) {\n      return \"operator\";\n    }\n\n    if (stream.eatSpace()) {\n      return null;\n    }\n\n    var ch = stream.peek();\n\n    // Handle single line comments\n    if (ch === '#') {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n\n    if (ch === '[') {\n      state.scopes.push('[');\n    }\n\n    if (ch === '(') {\n      state.scopes.push('(');\n    }\n\n    if (inArray(state) && ch === ']') {\n      if (currentScope(state) === \"if\") { state.scopes.pop(); }\n      while (currentScope(state) === \"for\") { state.scopes.pop(); }\n      state.scopes.pop();\n      state.leavingExpr = true;\n    }\n\n    if (inGenerator(state) && ch === ')') {\n      if (currentScope(state) === \"if\") { state.scopes.pop(); }\n      while (currentScope(state) === \"for\") { state.scopes.pop(); }\n      state.scopes.pop();\n      state.leavingExpr = true;\n    }\n\n    if (inArray(state)) {\n      if (state.lastToken == \"end\" && stream.match(/^:/)) {\n        return \"operator\";\n      }\n      if (stream.match(/^end/)) {\n        return \"number\";\n      }\n    }\n\n    var match;\n    if (match = stream.match(openers)) {\n      state.scopes.push(match[0]);\n      return \"keyword\";\n    }\n\n    if (stream.match(closers)) {\n      state.scopes.pop();\n      return \"keyword\";\n    }\n\n    // Handle type annotations\n    if (stream.match(/^::(?![:\\$])/)) {\n      state.tokenize = tokenAnnotation;\n      return state.tokenize(stream, state);\n    }\n\n    // Handle symbols\n    if (!leavingExpr && stream.match(symbol) ||\n        stream.match(/:([<>]:|<<=?|>>>?=?|->|\\/\\/|\\.{2,3}|[\\.\\\\%*+\\-<>!\\/^|&]=?|[~\\?\\$])/)) {\n      return \"builtin\";\n    }\n\n    // Handle parametric types\n    //if (stream.match(/^{[^}]*}(?=\\()/)) {\n    //  return \"builtin\";\n    //}\n\n    // Handle operators and Delimiters\n    if (stream.match(operators)) {\n      return \"operator\";\n    }\n\n    // Handle Number Literals\n    if (stream.match(/^\\.?\\d/, false)) {\n      var imMatcher = RegExp(/^im\\b/);\n      var numberLiteral = false;\n      // Floats\n      if (stream.match(/^\\d*\\.(?!\\.)\\d*([Eef][\\+\\-]?\\d+)?/i)) { numberLiteral = true; }\n      if (stream.match(/^\\d+\\.(?!\\.)\\d*/)) { numberLiteral = true; }\n      if (stream.match(/^\\.\\d+/)) { numberLiteral = true; }\n      if (stream.match(/^0x\\.[0-9a-f]+p[\\+\\-]?\\d+/i)) { numberLiteral = true; }\n      // Integers\n      if (stream.match(/^0x[0-9a-f]+/i)) { numberLiteral = true; } // Hex\n      if (stream.match(/^0b[01]+/i)) { numberLiteral = true; } // Binary\n      if (stream.match(/^0o[0-7]+/i)) { numberLiteral = true; } // Octal\n      if (stream.match(/^[1-9]\\d*(e[\\+\\-]?\\d+)?/)) { numberLiteral = true; } // Decimal\n      // Zero by itself with no other piece of number.\n      if (stream.match(/^0(?![\\dx])/i)) { numberLiteral = true; }\n      if (numberLiteral) {\n          // Integer literals may be \"long\"\n          stream.match(imMatcher);\n          state.leavingExpr = true;\n          return \"number\";\n      }\n    }\n\n    // Handle Chars\n    if (stream.match(/^'/)) {\n      state.tokenize = tokenChar;\n      return state.tokenize(stream, state);\n    }\n\n    // Handle Strings\n    if (stream.match(stringPrefixes)) {\n      state.tokenize = tokenStringFactory(stream.current());\n      return state.tokenize(stream, state);\n    }\n\n    if (stream.match(macro)) {\n      return \"meta\";\n    }\n\n    if (stream.match(delimiters)) {\n      return null;\n    }\n\n    if (stream.match(keywords)) {\n      return \"keyword\";\n    }\n\n    if (stream.match(builtins)) {\n      return \"builtin\";\n    }\n\n    var isDefinition = state.isDefinition || state.lastToken == \"function\" ||\n                       state.lastToken == \"macro\" || state.lastToken == \"type\" ||\n                       state.lastToken == \"struct\" || state.lastToken == \"immutable\";\n\n    if (stream.match(identifiers)) {\n      if (isDefinition) {\n        if (stream.peek() === '.') {\n          state.isDefinition = true;\n          return \"variable\";\n        }\n        state.isDefinition = false;\n        return \"def\";\n      }\n      if (stream.match(/^({[^}]*})*\\(/, false)) {\n        state.tokenize = tokenCallOrDef;\n        return state.tokenize(stream, state);\n      }\n      state.leavingExpr = true;\n      return \"variable\";\n    }\n\n    // Handle non-detected items\n    stream.next();\n    return \"error\";\n  }\n\n  function tokenCallOrDef(stream, state) {\n    var match = stream.match(/^(\\(\\s*)/);\n    if (match) {\n      if (state.firstParenPos < 0)\n        state.firstParenPos = state.scopes.length;\n      state.scopes.push('(');\n      state.charsAdvanced += match[1].length;\n    }\n    if (currentScope(state) == '(' && stream.match(/^\\)/)) {\n      state.scopes.pop();\n      state.charsAdvanced += 1;\n      if (state.scopes.length <= state.firstParenPos) {\n        var isDefinition = stream.match(/^(\\s*where\\s+[^\\s=]+)*\\s*?=(?!=)/, false);\n        stream.backUp(state.charsAdvanced);\n        state.firstParenPos = -1;\n        state.charsAdvanced = 0;\n        state.tokenize = tokenBase;\n        if (isDefinition)\n          return \"def\";\n        return \"builtin\";\n      }\n    }\n    // Unfortunately javascript does not support multiline strings, so we have\n    // to undo anything done upto here if a function call or definition splits\n    // over two or more lines.\n    if (stream.match(/^$/g, false)) {\n      stream.backUp(state.charsAdvanced);\n      while (state.scopes.length > state.firstParenPos)\n        state.scopes.pop();\n      state.firstParenPos = -1;\n      state.charsAdvanced = 0;\n      state.tokenize = tokenBase;\n      return \"builtin\";\n    }\n    state.charsAdvanced += stream.match(/^([^()]*)/)[1].length;\n    return state.tokenize(stream, state);\n  }\n\n  function tokenAnnotation(stream, state) {\n    stream.match(/.*?(?=,|;|{|}|\\(|\\)|=|$|\\s)/);\n    if (stream.match(/^{/)) {\n      state.nestedLevels++;\n    } else if (stream.match(/^}/)) {\n      state.nestedLevels--;\n    }\n    if (state.nestedLevels > 0) {\n      stream.match(/.*?(?={|})/) || stream.next();\n    } else if (state.nestedLevels == 0) {\n      state.tokenize = tokenBase;\n    }\n    return \"builtin\";\n  }\n\n  function tokenComment(stream, state) {\n    if (stream.match(/^#=/)) {\n      state.nestedLevels++;\n    }\n    if (!stream.match(/.*?(?=(#=|=#))/)) {\n      stream.skipToEnd();\n    }\n    if (stream.match(/^=#/)) {\n      state.nestedLevels--;\n      if (state.nestedLevels == 0)\n        state.tokenize = tokenBase;\n    }\n    return \"comment\";\n  }\n\n  function tokenChar(stream, state) {\n    var isChar = false, match;\n    if (stream.match(chars)) {\n      isChar = true;\n    } else if (match = stream.match(/\\\\u([a-f0-9]{1,4})(?=')/i)) {\n      var value = parseInt(match[1], 16);\n      if (value <= 55295 || value >= 57344) { // (U+0,U+D7FF), (U+E000,U+FFFF)\n        isChar = true;\n        stream.next();\n      }\n    } else if (match = stream.match(/\\\\U([A-Fa-f0-9]{5,8})(?=')/)) {\n      var value = parseInt(match[1], 16);\n      if (value <= 1114111) { // U+10FFFF\n        isChar = true;\n        stream.next();\n      }\n    }\n    if (isChar) {\n      state.leavingExpr = true;\n      state.tokenize = tokenBase;\n      return \"string\";\n    }\n    if (!stream.match(/^[^']+(?=')/)) { stream.skipToEnd(); }\n    if (stream.match(/^'/)) { state.tokenize = tokenBase; }\n    return \"error\";\n  }\n\n  function tokenStringFactory(delimiter) {\n    if (delimiter.substr(-3) === '\"\"\"') {\n      delimiter = '\"\"\"';\n    } else if (delimiter.substr(-1) === '\"') {\n      delimiter = '\"';\n    }\n    function tokenString(stream, state) {\n      if (stream.eat('\\\\')) {\n        stream.next();\n      } else if (stream.match(delimiter)) {\n        state.tokenize = tokenBase;\n        state.leavingExpr = true;\n        return \"string\";\n      } else {\n        stream.eat(/[`\"]/);\n      }\n      stream.eatWhile(/[^\\\\`\"]/);\n      return \"string\";\n    }\n    return tokenString;\n  }\n\n  var external = {\n    startState: function() {\n      return {\n        tokenize: tokenBase,\n        scopes: [],\n        lastToken: null,\n        leavingExpr: false,\n        isDefinition: false,\n        nestedLevels: 0,\n        charsAdvanced: 0,\n        firstParenPos: -1\n      };\n    },\n\n    token: function(stream, state) {\n      var style = state.tokenize(stream, state);\n      var current = stream.current();\n\n      if (current && style) {\n        state.lastToken = current;\n      }\n\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      var delta = 0;\n      if ( textAfter === ']' || textAfter === ')' || textAfter === \"end\" ||\n           textAfter === \"else\" || textAfter === \"catch\" || textAfter === \"elseif\" ||\n           textAfter === \"finally\" ) {\n        delta = -1;\n      }\n      return (state.scopes.length + delta) * config.indentUnit;\n    },\n\n    electricInput: /\\b(end|else|catch|finally)\\b/,\n    blockCommentStart: \"#=\",\n    blockCommentEnd: \"=#\",\n    lineComment: \"#\",\n    closeBrackets: \"()[]{}\\\"\\\"\",\n    fold: \"indent\"\n  };\n  return external;\n});\n\n\nCodeMirror.defineMIME(\"text/x-julia\", \"julia\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/livescript/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: LiveScript mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/solarized.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"livescript.js\"></script>\n<style>.CodeMirror {font-size: 80%;border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">LiveScript</a>\n  </ul>\n</div>\n\n<article>\n<h2>LiveScript mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n# LiveScript mode for CodeMirror\n# The following script, prelude.ls, is used to\n# demonstrate LiveScript mode for CodeMirror.\n#   https://github.com/gkz/prelude-ls\n\nexport objToFunc = objToFunc = (obj) ->\n  (key) -> obj[key]\n\nexport each = (f, xs) -->\n  if typeof! xs is \\Object\n    for , x of xs then f x\n  else\n    for x in xs then f x\n  xs\n\nexport map = (f, xs) -->\n  f = objToFunc f if typeof! f isnt \\Function\n  type = typeof! xs\n  if type is \\Object\n    {[key, f x] for key, x of xs}\n  else\n    result = [f x for x in xs]\n    if type is \\String then result * '' else result\n\nexport filter = (f, xs) -->\n  f = objToFunc f if typeof! f isnt \\Function\n  type = typeof! xs\n  if type is \\Object\n    {[key, x] for key, x of xs when f x}\n  else\n    result = [x for x in xs when f x]\n    if type is \\String then result * '' else result\n\nexport reject = (f, xs) -->\n  f = objToFunc f if typeof! f isnt \\Function\n  type = typeof! xs\n  if type is \\Object\n    {[key, x] for key, x of xs when not f x}\n  else\n    result = [x for x in xs when not f x]\n    if type is \\String then result * '' else result\n\nexport partition = (f, xs) -->\n  f = objToFunc f if typeof! f isnt \\Function\n  type = typeof! xs\n  if type is \\Object\n    passed = {}\n    failed = {}\n    for key, x of xs\n      (if f x then passed else failed)[key] = x\n  else\n    passed = []\n    failed = []\n    for x in xs\n      (if f x then passed else failed)push x\n    if type is \\String\n      passed *= ''\n      failed *= ''\n  [passed, failed]\n\nexport find = (f, xs) -->\n  f = objToFunc f if typeof! f isnt \\Function\n  if typeof! xs is \\Object\n    for , x of xs when f x then return x\n  else\n    for x in xs when f x then return x\n  void\n\nexport head = export first = (xs) ->\n  return void if not xs.length\n  xs.0\n\nexport tail = (xs) ->\n  return void if not xs.length\n  xs.slice 1\n\nexport last = (xs) ->\n  return void if not xs.length\n  xs[*-1]\n\nexport initial = (xs) ->\n  return void if not xs.length\n  xs.slice 0 xs.length - 1\n\nexport empty = (xs) ->\n  if typeof! xs is \\Object\n    for x of xs then return false\n    return yes\n  not xs.length\n\nexport values = (obj) ->\n  [x for , x of obj]\n\nexport keys = (obj) ->\n  [x for x of obj]\n\nexport len = (xs) ->\n  xs = values xs if typeof! xs is \\Object\n  xs.length\n\nexport cons = (x, xs) -->\n  if typeof! xs is \\String then x + xs else [x] ++ xs\n\nexport append = (xs, ys) -->\n  if typeof! ys is \\String then xs + ys else xs ++ ys\n\nexport join = (sep, xs) -->\n  xs = values xs if typeof! xs is \\Object\n  xs.join sep\n\nexport reverse = (xs) ->\n  if typeof! xs is \\String\n  then (xs / '')reverse! * ''\n  else xs.slice!reverse!\n\nexport fold = export foldl = (f, memo, xs) -->\n  if typeof! xs is \\Object\n    for , x of xs then memo = f memo, x\n  else\n    for x in xs then memo = f memo, x\n  memo\n\nexport fold1 = export foldl1 = (f, xs) --> fold f, xs.0, xs.slice 1\n\nexport foldr = (f, memo, xs) --> fold f, memo, xs.slice!reverse!\n\nexport foldr1 = (f, xs) -->\n  xs.=slice!reverse!\n  fold f, xs.0, xs.slice 1\n\nexport unfoldr = export unfold = (f, b) -->\n  if (f b)?\n    [that.0] ++ unfoldr f, that.1\n  else\n    []\n\nexport andList = (xs) ->\n  for x in xs when not x\n    return false\n  true\n\nexport orList = (xs) ->\n  for x in xs when x\n    return true\n  false\n\nexport any = (f, xs) -->\n  f = objToFunc f if typeof! f isnt \\Function\n  for x in xs when f x\n    return yes\n  no\n\nexport all = (f, xs) -->\n  f = objToFunc f if typeof! f isnt \\Function\n  for x in xs when not f x\n    return no\n  yes\n\nexport unique = (xs) ->\n  result = []\n  if typeof! xs is \\Object\n    for , x of xs when x not in result then result.push x\n  else\n    for x   in xs when x not in result then result.push x\n  if typeof! xs is \\String then result * '' else result\n\nexport sort = (xs) ->\n  xs.concat!sort (x, y) ->\n    | x > y =>  1\n    | x < y => -1\n    | _     =>  0\n\nexport sortBy = (f, xs) -->\n  return [] unless xs.length\n  xs.concat!sort f\n\nexport compare = (f, x, y) -->\n  | (f x) > (f y) =>  1\n  | (f x) < (f y) => -1\n  | otherwise     =>  0\n\nexport sum = (xs) ->\n  result = 0\n  if typeof! xs is \\Object\n    for , x of xs then result += x\n  else\n    for x   in xs then result += x\n  result\n\nexport product = (xs) ->\n  result = 1\n  if typeof! xs is \\Object\n    for , x of xs then result *= x\n  else\n    for x   in xs then result *= x\n  result\n\nexport mean = export average = (xs) -> (sum xs) / len xs\n\nexport concat = (xss) -> fold append, [], xss\n\nexport concatMap = (f, xs) --> fold ((memo, x) -> append memo, f x), [], xs\n\nexport listToObj = (xs) ->\n  {[x.0, x.1] for x in xs}\n\nexport maximum = (xs) -> fold1 (>?), xs\n\nexport minimum = (xs) -> fold1 (<?), xs\n\nexport scan = export scanl = (f, memo, xs) -->\n  last = memo\n  if typeof! xs is \\Object\n  then [memo] ++ [last = f last, x for , x of xs]\n  else [memo] ++ [last = f last, x for x in xs]\n\nexport scan1 = export scanl1 = (f, xs) --> scan f, xs.0, xs.slice 1\n\nexport scanr = (f, memo, xs) -->\n  xs.=slice!reverse!\n  scan f, memo, xs .reverse!\n\nexport scanr1 = (f, xs) -->\n  xs.=slice!reverse!\n  scan f, xs.0, xs.slice 1 .reverse!\n\nexport replicate = (n, x) -->\n  result = []\n  i = 0\n  while i < n, ++i then result.push x\n  result\n\nexport take = (n, xs) -->\n  | n <= 0\n    if typeof! xs is \\String then '' else []\n  | not xs.length => xs\n  | otherwise     => xs.slice 0, n\n\nexport drop = (n, xs) -->\n  | n <= 0        => xs\n  | not xs.length => xs\n  | otherwise     => xs.slice n\n\nexport splitAt = (n, xs) --> [(take n, xs), (drop n, xs)]\n\nexport takeWhile = (p, xs) -->\n  return xs if not xs.length\n  p = objToFunc p if typeof! p isnt \\Function\n  result = []\n  for x in xs\n    break if not p x\n    result.push x\n  if typeof! xs is \\String then result * '' else result\n\nexport dropWhile = (p, xs) -->\n  return xs if not xs.length\n  p = objToFunc p if typeof! p isnt \\Function\n  i = 0\n  for x in xs\n    break if not p x\n    ++i\n  drop i, xs\n\nexport span = (p, xs) --> [(takeWhile p, xs), (dropWhile p, xs)]\n\nexport breakIt = (p, xs) --> span (not) << p, xs\n\nexport zip = (xs, ys) -->\n  result = []\n  for zs, i in [xs, ys]\n    for z, j in zs\n      result.push [] if i is 0\n      result[j]?push z\n  result\n\nexport zipWith = (f,xs, ys) -->\n  f = objToFunc f if typeof! f isnt \\Function\n  if not xs.length or not ys.length\n    []\n  else\n    [f.apply this, zs for zs in zip.call this, xs, ys]\n\nexport zipAll = (...xss) ->\n  result = []\n  for xs, i in xss\n    for x, j in xs\n      result.push [] if i is 0\n      result[j]?push x\n  result\n\nexport zipAllWith = (f, ...xss) ->\n  f = objToFunc f if typeof! f isnt \\Function\n  if not xss.0.length or not xss.1.length\n    []\n  else\n    [f.apply this, xs for xs in zipAll.apply this, xss]\n\nexport compose = (...funcs) ->\n  ->\n    args = arguments\n    for f in funcs\n      args = [f.apply this, args]\n    args.0\n\nexport curry = (f) ->\n  curry$ f # using util method curry$ from livescript\n\nexport id = (x) -> x\n\nexport flip = (f, x, y) --> f y, x\n\nexport fix = (f) ->\n  ( (g, x) -> -> f(g g) ...arguments ) do\n    (g, x) -> -> f(g g) ...arguments\n\nexport lines = (str) ->\n  return [] if not str.length\n  str / \\\\n\n\nexport unlines = (strs) -> strs * \\\\n\n\nexport words = (str) ->\n  return [] if not str.length\n  str / /[ ]+/\n\nexport unwords = (strs) -> strs * ' '\n\nexport max = (>?)\n\nexport min = (<?)\n\nexport negate = (x) -> -x\n\nexport abs = Math.abs\n\nexport signum = (x) ->\n  | x < 0     => -1\n  | x > 0     =>  1\n  | otherwise =>  0\n\nexport quot = (x, y) --> ~~(x / y)\n\nexport rem = (%)\n\nexport div = (x, y) --> Math.floor x / y\n\nexport mod = (%%)\n\nexport recip = (1 /)\n\nexport pi = Math.PI\n\nexport tau = pi * 2\n\nexport exp = Math.exp\n\nexport sqrt = Math.sqrt\n\n# changed from log as log is a\n# common function for logging things\nexport ln = Math.log\n\nexport pow = (^)\n\nexport sin = Math.sin\n\nexport tan = Math.tan\n\nexport cos = Math.cos\n\nexport asin = Math.asin\n\nexport acos = Math.acos\n\nexport atan = Math.atan\n\nexport atan2 = (x, y) --> Math.atan2 x, y\n\n# sinh\n# tanh\n# cosh\n# asinh\n# atanh\n# acosh\n\nexport truncate = (x) -> ~~x\n\nexport round = Math.round\n\nexport ceiling = Math.ceil\n\nexport floor = Math.floor\n\nexport isItNaN = (x) -> x isnt x\n\nexport even = (x) -> x % 2 == 0\n\nexport odd = (x) -> x % 2 != 0\n\nexport gcd = (x, y) -->\n  x = Math.abs x\n  y = Math.abs y\n  until y is 0\n    z = x % y\n    x = y\n    y = z\n  x\n\nexport lcm = (x, y) -->\n  Math.abs Math.floor (x / (gcd x, y) * y)\n\n# meta\nexport installPrelude = !(target) ->\n  unless target.prelude?isInstalled\n    target <<< out$ # using out$ generated by livescript\n    target <<< target.prelude.isInstalled = true\n\nexport prelude = out$\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        theme: \"solarized light\",\n        lineNumbers: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-livescript</code>.</p>\n\n    <p>The LiveScript mode was written by Kenneth Bentley.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/livescript/livescript.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**\n * Link to the project's GitHub page:\n * https://github.com/duralog/CodeMirror\n */\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode('livescript', function(){\n    var tokenBase = function(stream, state) {\n      var next_rule = state.next || \"start\";\n      if (next_rule) {\n        state.next = state.next;\n        var nr = Rules[next_rule];\n        if (nr.splice) {\n          for (var i$ = 0; i$ < nr.length; ++i$) {\n            var r = nr[i$];\n            if (r.regex && stream.match(r.regex)) {\n              state.next = r.next || state.next;\n              return r.token;\n            }\n          }\n          stream.next();\n          return 'error';\n        }\n        if (stream.match(r = Rules[next_rule])) {\n          if (r.regex && stream.match(r.regex)) {\n            state.next = r.next;\n            return r.token;\n          } else {\n            stream.next();\n            return 'error';\n          }\n        }\n      }\n      stream.next();\n      return 'error';\n    };\n    var external = {\n      startState: function(){\n        return {\n          next: 'start',\n          lastToken: {style: null, indent: 0, content: \"\"}\n        };\n      },\n      token: function(stream, state){\n        while (stream.pos == stream.start)\n          var style = tokenBase(stream, state);\n        state.lastToken = {\n          style: style,\n          indent: stream.indentation(),\n          content: stream.current()\n        };\n        return style.replace(/\\./g, ' ');\n      },\n      indent: function(state){\n        var indentation = state.lastToken.indent;\n        if (state.lastToken.content.match(indenter)) {\n          indentation += 2;\n        }\n        return indentation;\n      }\n    };\n    return external;\n  });\n\n  var identifier = '(?![\\\\d\\\\s])[$\\\\w\\\\xAA-\\\\uFFDC](?:(?!\\\\s)[$\\\\w\\\\xAA-\\\\uFFDC]|-[A-Za-z])*';\n  var indenter = RegExp('(?:[({[=:]|[-~]>|\\\\b(?:e(?:lse|xport)|d(?:o|efault)|t(?:ry|hen)|finally|import(?:\\\\s*all)?|const|var|let|new|catch(?:\\\\s*' + identifier + ')?))\\\\s*$');\n  var keywordend = '(?![$\\\\w]|-[A-Za-z]|\\\\s*:(?![:=]))';\n  var stringfill = {\n    token: 'string',\n    regex: '.+'\n  };\n  var Rules = {\n    start: [\n      {\n        token: 'comment.doc',\n        regex: '/\\\\*',\n        next: 'comment'\n      }, {\n        token: 'comment',\n        regex: '#.*'\n      }, {\n        token: 'keyword',\n        regex: '(?:t(?:h(?:is|row|en)|ry|ypeof!?)|c(?:on(?:tinue|st)|a(?:se|tch)|lass)|i(?:n(?:stanceof)?|mp(?:ort(?:\\\\s+all)?|lements)|[fs])|d(?:e(?:fault|lete|bugger)|o)|f(?:or(?:\\\\s+own)?|inally|unction)|s(?:uper|witch)|e(?:lse|x(?:tends|port)|val)|a(?:nd|rguments)|n(?:ew|ot)|un(?:less|til)|w(?:hile|ith)|o[fr]|return|break|let|var|loop)' + keywordend\n      }, {\n        token: 'constant.language',\n        regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend\n      }, {\n        token: 'invalid.illegal',\n        regex: '(?:p(?:ackage|r(?:ivate|otected)|ublic)|i(?:mplements|nterface)|enum|static|yield)' + keywordend\n      }, {\n        token: 'language.support.class',\n        regex: '(?:R(?:e(?:gExp|ferenceError)|angeError)|S(?:tring|yntaxError)|E(?:rror|valError)|Array|Boolean|Date|Function|Number|Object|TypeError|URIError)' + keywordend\n      }, {\n        token: 'language.support.function',\n        regex: '(?:is(?:NaN|Finite)|parse(?:Int|Float)|Math|JSON|(?:en|de)codeURI(?:Component)?)' + keywordend\n      }, {\n        token: 'variable.language',\n        regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend\n      }, {\n        token: 'identifier',\n        regex: identifier + '\\\\s*:(?![:=])'\n      }, {\n        token: 'variable',\n        regex: identifier\n      }, {\n        token: 'keyword.operator',\n        regex: '(?:\\\\.{3}|\\\\s+\\\\?)'\n      }, {\n        token: 'keyword.variable',\n        regex: '(?:@+|::|\\\\.\\\\.)',\n        next: 'key'\n      }, {\n        token: 'keyword.operator',\n        regex: '\\\\.\\\\s*',\n        next: 'key'\n      }, {\n        token: 'string',\n        regex: '\\\\\\\\\\\\S[^\\\\s,;)}\\\\]]*'\n      }, {\n        token: 'string.doc',\n        regex: '\\'\\'\\'',\n        next: 'qdoc'\n      }, {\n        token: 'string.doc',\n        regex: '\"\"\"',\n        next: 'qqdoc'\n      }, {\n        token: 'string',\n        regex: '\\'',\n        next: 'qstring'\n      }, {\n        token: 'string',\n        regex: '\"',\n        next: 'qqstring'\n      }, {\n        token: 'string',\n        regex: '`',\n        next: 'js'\n      }, {\n        token: 'string',\n        regex: '<\\\\[',\n        next: 'words'\n      }, {\n        token: 'string.regex',\n        regex: '//',\n        next: 'heregex'\n      }, {\n        token: 'string.regex',\n        regex: '\\\\/(?:[^[\\\\/\\\\n\\\\\\\\]*(?:(?:\\\\\\\\.|\\\\[[^\\\\]\\\\n\\\\\\\\]*(?:\\\\\\\\.[^\\\\]\\\\n\\\\\\\\]*)*\\\\])[^[\\\\/\\\\n\\\\\\\\]*)*)\\\\/[gimy$]{0,4}',\n        next: 'key'\n      }, {\n        token: 'constant.numeric',\n        regex: '(?:0x[\\\\da-fA-F][\\\\da-fA-F_]*|(?:[2-9]|[12]\\\\d|3[0-6])r[\\\\da-zA-Z][\\\\da-zA-Z_]*|(?:\\\\d[\\\\d_]*(?:\\\\.\\\\d[\\\\d_]*)?|\\\\.\\\\d[\\\\d_]*)(?:e[+-]?\\\\d[\\\\d_]*)?[\\\\w$]*)'\n      }, {\n        token: 'lparen',\n        regex: '[({[]'\n      }, {\n        token: 'rparen',\n        regex: '[)}\\\\]]',\n        next: 'key'\n      }, {\n        token: 'keyword.operator',\n        regex: '\\\\S+'\n      }, {\n        token: 'text',\n        regex: '\\\\s+'\n      }\n    ],\n    heregex: [\n      {\n        token: 'string.regex',\n        regex: '.*?//[gimy$?]{0,4}',\n        next: 'start'\n      }, {\n        token: 'string.regex',\n        regex: '\\\\s*#{'\n      }, {\n        token: 'comment.regex',\n        regex: '\\\\s+(?:#.*)?'\n      }, {\n        token: 'string.regex',\n        regex: '\\\\S+'\n      }\n    ],\n    key: [\n      {\n        token: 'keyword.operator',\n        regex: '[.?@!]+'\n      }, {\n        token: 'identifier',\n        regex: identifier,\n        next: 'start'\n      }, {\n        token: 'text',\n        regex: '',\n        next: 'start'\n      }\n    ],\n    comment: [\n      {\n        token: 'comment.doc',\n        regex: '.*?\\\\*/',\n        next: 'start'\n      }, {\n        token: 'comment.doc',\n        regex: '.+'\n      }\n    ],\n    qdoc: [\n      {\n        token: 'string',\n        regex: \".*?'''\",\n        next: 'key'\n      }, stringfill\n    ],\n    qqdoc: [\n      {\n        token: 'string',\n        regex: '.*?\"\"\"',\n        next: 'key'\n      }, stringfill\n    ],\n    qstring: [\n      {\n        token: 'string',\n        regex: '[^\\\\\\\\\\']*(?:\\\\\\\\.[^\\\\\\\\\\']*)*\\'',\n        next: 'key'\n      }, stringfill\n    ],\n    qqstring: [\n      {\n        token: 'string',\n        regex: '[^\\\\\\\\\"]*(?:\\\\\\\\.[^\\\\\\\\\"]*)*\"',\n        next: 'key'\n      }, stringfill\n    ],\n    js: [\n      {\n        token: 'string',\n        regex: '[^\\\\\\\\`]*(?:\\\\\\\\.[^\\\\\\\\`]*)*`',\n        next: 'key'\n      }, stringfill\n    ],\n    words: [\n      {\n        token: 'string',\n        regex: '.*?\\\\]>',\n        next: 'key'\n      }, stringfill\n    ]\n  };\n  for (var idx in Rules) {\n    var r = Rules[idx];\n    if (r.splice) {\n      for (var i = 0, len = r.length; i < len; ++i) {\n        var rr = r[i];\n        if (typeof rr.regex === 'string') {\n          Rules[idx][i].regex = new RegExp('^' + rr.regex);\n        }\n      }\n    } else if (typeof rr.regex === 'string') {\n      Rules[idx].regex = new RegExp('^' + r.regex);\n    }\n  }\n\n  CodeMirror.defineMIME('text/x-livescript', 'livescript');\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/lua/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Lua mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/neat.css\">\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"lua.js\"></script>\n<style>.CodeMirror {border: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Lua</a>\n  </ul>\n</div>\n\n<article>\n<h2>Lua mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n--[[\nexample useless code to show lua syntax highlighting\nthis is multiline comment\n]]\n\nfunction blahblahblah(x)\n\n  local table = {\n    \"asd\" = 123,\n    \"x\" = 0.34,  \n  }\n  if x ~= 3 then\n    print( x )\n  elseif x == \"string\"\n    my_custom_function( 0x34 )\n  else\n    unknown_function( \"some string\" )\n  end\n\n  --single line comment\n  \nend\n\nfunction blablabla3()\n\n  for k,v in ipairs( table ) do\n    --abcde..\n    y=[=[\n  x=[[\n      x is a multi line string\n   ]]\n  but its definition is iside a highest level string!\n  ]=]\n    print(\" \\\"\\\" \")\n\n    s = math.sin( x )\n  end\n\nend\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        matchBrackets: true,\n        theme: \"neat\"\n      });\n    </script>\n\n    <p>Loosely based on Franciszek\n    Wawrzak's <a href=\"https://codemirror.net/1/contrib/lua\">CodeMirror\n    1 mode</a>. One configuration parameter is\n    supported, <code>specials</code>, to which you can provide an\n    array of strings to have those identifiers highlighted with\n    the <code>lua-special</code> style.</p>\n    <p><strong>MIME types defined:</strong> <code>text/x-lua</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/lua/lua.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's\n// CodeMirror 1 mode.\n// highlights keywords, strings, comments (no leveling supported! (\"[==[\")), tokens, basic indenting\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"lua\", function(config, parserConfig) {\n  var indentUnit = config.indentUnit;\n\n  function prefixRE(words) {\n    return new RegExp(\"^(?:\" + words.join(\"|\") + \")\", \"i\");\n  }\n  function wordRE(words) {\n    return new RegExp(\"^(?:\" + words.join(\"|\") + \")$\", \"i\");\n  }\n  var specials = wordRE(parserConfig.specials || []);\n\n  // long list of standard functions from lua manual\n  var builtins = wordRE([\n    \"_G\",\"_VERSION\",\"assert\",\"collectgarbage\",\"dofile\",\"error\",\"getfenv\",\"getmetatable\",\"ipairs\",\"load\",\n    \"loadfile\",\"loadstring\",\"module\",\"next\",\"pairs\",\"pcall\",\"print\",\"rawequal\",\"rawget\",\"rawset\",\"require\",\n    \"select\",\"setfenv\",\"setmetatable\",\"tonumber\",\"tostring\",\"type\",\"unpack\",\"xpcall\",\n\n    \"coroutine.create\",\"coroutine.resume\",\"coroutine.running\",\"coroutine.status\",\"coroutine.wrap\",\"coroutine.yield\",\n\n    \"debug.debug\",\"debug.getfenv\",\"debug.gethook\",\"debug.getinfo\",\"debug.getlocal\",\"debug.getmetatable\",\n    \"debug.getregistry\",\"debug.getupvalue\",\"debug.setfenv\",\"debug.sethook\",\"debug.setlocal\",\"debug.setmetatable\",\n    \"debug.setupvalue\",\"debug.traceback\",\n\n    \"close\",\"flush\",\"lines\",\"read\",\"seek\",\"setvbuf\",\"write\",\n\n    \"io.close\",\"io.flush\",\"io.input\",\"io.lines\",\"io.open\",\"io.output\",\"io.popen\",\"io.read\",\"io.stderr\",\"io.stdin\",\n    \"io.stdout\",\"io.tmpfile\",\"io.type\",\"io.write\",\n\n    \"math.abs\",\"math.acos\",\"math.asin\",\"math.atan\",\"math.atan2\",\"math.ceil\",\"math.cos\",\"math.cosh\",\"math.deg\",\n    \"math.exp\",\"math.floor\",\"math.fmod\",\"math.frexp\",\"math.huge\",\"math.ldexp\",\"math.log\",\"math.log10\",\"math.max\",\n    \"math.min\",\"math.modf\",\"math.pi\",\"math.pow\",\"math.rad\",\"math.random\",\"math.randomseed\",\"math.sin\",\"math.sinh\",\n    \"math.sqrt\",\"math.tan\",\"math.tanh\",\n\n    \"os.clock\",\"os.date\",\"os.difftime\",\"os.execute\",\"os.exit\",\"os.getenv\",\"os.remove\",\"os.rename\",\"os.setlocale\",\n    \"os.time\",\"os.tmpname\",\n\n    \"package.cpath\",\"package.loaded\",\"package.loaders\",\"package.loadlib\",\"package.path\",\"package.preload\",\n    \"package.seeall\",\n\n    \"string.byte\",\"string.char\",\"string.dump\",\"string.find\",\"string.format\",\"string.gmatch\",\"string.gsub\",\n    \"string.len\",\"string.lower\",\"string.match\",\"string.rep\",\"string.reverse\",\"string.sub\",\"string.upper\",\n\n    \"table.concat\",\"table.insert\",\"table.maxn\",\"table.remove\",\"table.sort\"\n  ]);\n  var keywords = wordRE([\"and\",\"break\",\"elseif\",\"false\",\"nil\",\"not\",\"or\",\"return\",\n                         \"true\",\"function\", \"end\", \"if\", \"then\", \"else\", \"do\",\n                         \"while\", \"repeat\", \"until\", \"for\", \"in\", \"local\" ]);\n\n  var indentTokens = wordRE([\"function\", \"if\",\"repeat\",\"do\", \"\\\\(\", \"{\"]);\n  var dedentTokens = wordRE([\"end\", \"until\", \"\\\\)\", \"}\"]);\n  var dedentPartial = prefixRE([\"end\", \"until\", \"\\\\)\", \"}\", \"else\", \"elseif\"]);\n\n  function readBracket(stream) {\n    var level = 0;\n    while (stream.eat(\"=\")) ++level;\n    stream.eat(\"[\");\n    return level;\n  }\n\n  function normal(stream, state) {\n    var ch = stream.next();\n    if (ch == \"-\" && stream.eat(\"-\")) {\n      if (stream.eat(\"[\") && stream.eat(\"[\"))\n        return (state.cur = bracketed(readBracket(stream), \"comment\"))(stream, state);\n      stream.skipToEnd();\n      return \"comment\";\n    }\n    if (ch == \"\\\"\" || ch == \"'\")\n      return (state.cur = string(ch))(stream, state);\n    if (ch == \"[\" && /[\\[=]/.test(stream.peek()))\n      return (state.cur = bracketed(readBracket(stream), \"string\"))(stream, state);\n    if (/\\d/.test(ch)) {\n      stream.eatWhile(/[\\w.%]/);\n      return \"number\";\n    }\n    if (/[\\w_]/.test(ch)) {\n      stream.eatWhile(/[\\w\\\\\\-_.]/);\n      return \"variable\";\n    }\n    return null;\n  }\n\n  function bracketed(level, style) {\n    return function(stream, state) {\n      var curlev = null, ch;\n      while ((ch = stream.next()) != null) {\n        if (curlev == null) {if (ch == \"]\") curlev = 0;}\n        else if (ch == \"=\") ++curlev;\n        else if (ch == \"]\" && curlev == level) { state.cur = normal; break; }\n        else curlev = null;\n      }\n      return style;\n    };\n  }\n\n  function string(quote) {\n    return function(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && !escaped) break;\n        escaped = !escaped && ch == \"\\\\\";\n      }\n      if (!escaped) state.cur = normal;\n      return \"string\";\n    };\n  }\n\n  return {\n    startState: function(basecol) {\n      return {basecol: basecol || 0, indentDepth: 0, cur: normal};\n    },\n\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      var style = state.cur(stream, state);\n      var word = stream.current();\n      if (style == \"variable\") {\n        if (keywords.test(word)) style = \"keyword\";\n        else if (builtins.test(word)) style = \"builtin\";\n        else if (specials.test(word)) style = \"variable-2\";\n      }\n      if ((style != \"comment\") && (style != \"string\")){\n        if (indentTokens.test(word)) ++state.indentDepth;\n        else if (dedentTokens.test(word)) --state.indentDepth;\n      }\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      var closing = dedentPartial.test(textAfter);\n      return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0));\n    },\n\n    lineComment: \"--\",\n    blockCommentStart: \"--[[\",\n    blockCommentEnd: \"]]\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-lua\", \"lua\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/markdown/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Markdown mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/continuelist.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"markdown.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      .cm-s-default .cm-trailing-space-a:before,\n      .cm-s-default .cm-trailing-space-b:before {position: absolute; content: \"\\00B7\"; color: #777;}\n      .cm-s-default .cm-trailing-space-new-line:before {position: absolute; content: \"\\21B5\"; color: #777;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Markdown</a>\n  </ul>\n</div>\n\n<article>\n<h2>Markdown mode</h2>\n<form><textarea id=\"code\" name=\"code\">\nMarkdown: Basics\n================\n\n&lt;ul id=\"ProjectSubmenu\"&gt;\n    &lt;li&gt;&lt;a href=\"/projects/markdown/\" title=\"Markdown Project Page\"&gt;Main&lt;/a&gt;&lt;/li&gt;\n    &lt;li&gt;&lt;a class=\"selected\" title=\"Markdown Basics\"&gt;Basics&lt;/a&gt;&lt;/li&gt;\n    &lt;li&gt;&lt;a href=\"/projects/markdown/syntax\" title=\"Markdown Syntax Documentation\"&gt;Syntax&lt;/a&gt;&lt;/li&gt;\n    &lt;li&gt;&lt;a href=\"/projects/markdown/license\" title=\"Pricing and License Information\"&gt;License&lt;/a&gt;&lt;/li&gt;\n    &lt;li&gt;&lt;a href=\"/projects/markdown/dingus\" title=\"Online Markdown Web Form\"&gt;Dingus&lt;/a&gt;&lt;/li&gt;\n&lt;/ul&gt;\n\n\nGetting the Gist of Markdown's Formatting Syntax\n------------------------------------------------\n\nThis page offers a brief overview of what it's like to use Markdown.\nThe [syntax page] [s] provides complete, detailed documentation for\nevery feature, but Markdown should be very easy to pick up simply by\nlooking at a few examples of it in action. The examples on this page\nare written in a before/after style, showing example syntax and the\nHTML output produced by Markdown.\n\nIt's also helpful to simply try Markdown out; the [Dingus] [d] is a\nweb application that allows you type your own Markdown-formatted text\nand translate it to XHTML.\n\n**Note:** This document is itself written using Markdown; you\ncan [see the source for it by adding '.text' to the URL] [src].\n\n  [s]: /projects/markdown/syntax  \"Markdown Syntax\"\n  [d]: /projects/markdown/dingus  \"Markdown Dingus\"\n  [src]: /projects/markdown/basics.text\n\n\n## Paragraphs, Headers, Blockquotes ##\n\nA paragraph is simply one or more consecutive lines of text, separated\nby one or more blank lines. (A blank line is any line that looks like\na blank line -- a line containing nothing but spaces or tabs is\nconsidered blank.) Normal paragraphs should not be indented with\nspaces or tabs.\n\nMarkdown offers two styles of headers: *Setext* and *atx*.\nSetext-style headers for `&lt;h1&gt;` and `&lt;h2&gt;` are created by\n\"underlining\" with equal signs (`=`) and hyphens (`-`), respectively.\nTo create an atx-style header, you put 1-6 hash marks (`#`) at the\nbeginning of the line -- the number of hashes equals the resulting\nHTML header level.\n\nBlockquotes are indicated using email-style '`&gt;`' angle brackets.\n\nMarkdown:\n\n    A First Level Header\n    ====================\n\n    A Second Level Header\n    ---------------------\n\n    Now is the time for all good men to come to\n    the aid of their country. This is just a\n    regular paragraph.\n\n    The quick brown fox jumped over the lazy\n    dog's back.\n\n    ### Header 3\n\n    &gt; This is a blockquote.\n    &gt;\n    &gt; This is the second paragraph in the blockquote.\n    &gt;\n    &gt; ## This is an H2 in a blockquote\n\n\nOutput:\n\n    &lt;h1&gt;A First Level Header&lt;/h1&gt;\n\n    &lt;h2&gt;A Second Level Header&lt;/h2&gt;\n\n    &lt;p&gt;Now is the time for all good men to come to\n    the aid of their country. This is just a\n    regular paragraph.&lt;/p&gt;\n\n    &lt;p&gt;The quick brown fox jumped over the lazy\n    dog's back.&lt;/p&gt;\n\n    &lt;h3&gt;Header 3&lt;/h3&gt;\n\n    &lt;blockquote&gt;\n        &lt;p&gt;This is a blockquote.&lt;/p&gt;\n\n        &lt;p&gt;This is the second paragraph in the blockquote.&lt;/p&gt;\n\n        &lt;h2&gt;This is an H2 in a blockquote&lt;/h2&gt;\n    &lt;/blockquote&gt;\n\n\n\n### Phrase Emphasis ###\n\nMarkdown uses asterisks and underscores to indicate spans of emphasis.\n\nMarkdown:\n\n    Some of these words *are emphasized*.\n    Some of these words _are emphasized also_.\n\n    Use two asterisks for **strong emphasis**.\n    Or, if you prefer, __use two underscores instead__.\n\nOutput:\n\n    &lt;p&gt;Some of these words &lt;em&gt;are emphasized&lt;/em&gt;.\n    Some of these words &lt;em&gt;are emphasized also&lt;/em&gt;.&lt;/p&gt;\n\n    &lt;p&gt;Use two asterisks for &lt;strong&gt;strong emphasis&lt;/strong&gt;.\n    Or, if you prefer, &lt;strong&gt;use two underscores instead&lt;/strong&gt;.&lt;/p&gt;\n\n\n\n## Lists ##\n\nUnordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,\n`+`, and `-`) as list markers. These three markers are\ninterchangable; this:\n\n    *   Candy.\n    *   Gum.\n    *   Booze.\n\nthis:\n\n    +   Candy.\n    +   Gum.\n    +   Booze.\n\nand this:\n\n    -   Candy.\n    -   Gum.\n    -   Booze.\n\nall produce the same output:\n\n    &lt;ul&gt;\n    &lt;li&gt;Candy.&lt;/li&gt;\n    &lt;li&gt;Gum.&lt;/li&gt;\n    &lt;li&gt;Booze.&lt;/li&gt;\n    &lt;/ul&gt;\n\nOrdered (numbered) lists use regular numbers, followed by periods, as\nlist markers:\n\n    1.  Red\n    2.  Green\n    3.  Blue\n\nOutput:\n\n    &lt;ol&gt;\n    &lt;li&gt;Red&lt;/li&gt;\n    &lt;li&gt;Green&lt;/li&gt;\n    &lt;li&gt;Blue&lt;/li&gt;\n    &lt;/ol&gt;\n\nIf you put blank lines between items, you'll get `&lt;p&gt;` tags for the\nlist item text. You can create multi-paragraph list items by indenting\nthe paragraphs by 4 spaces or 1 tab:\n\n    *   A list item.\n\n        With multiple paragraphs.\n\n    *   Another item in the list.\n\nOutput:\n\n    &lt;ul&gt;\n    &lt;li&gt;&lt;p&gt;A list item.&lt;/p&gt;\n    &lt;p&gt;With multiple paragraphs.&lt;/p&gt;&lt;/li&gt;\n    &lt;li&gt;&lt;p&gt;Another item in the list.&lt;/p&gt;&lt;/li&gt;\n    &lt;/ul&gt;\n\n\n\n### Links ###\n\nMarkdown supports two styles for creating links: *inline* and\n*reference*. With both styles, you use square brackets to delimit the\ntext you want to turn into a link.\n\nInline-style links use parentheses immediately after the link text.\nFor example:\n\n    This is an [example link](http://example.com/).\n\nOutput:\n\n    &lt;p&gt;This is an &lt;a href=\"http://example.com/\"&gt;\n    example link&lt;/a&gt;.&lt;/p&gt;\n\nOptionally, you may include a title attribute in the parentheses:\n\n    This is an [example link](http://example.com/ \"With a Title\").\n\nOutput:\n\n    &lt;p&gt;This is an &lt;a href=\"http://example.com/\" title=\"With a Title\"&gt;\n    example link&lt;/a&gt;.&lt;/p&gt;\n\nReference-style links allow you to refer to your links by names, which\nyou define elsewhere in your document:\n\n    I get 10 times more traffic from [Google][1] than from\n    [Yahoo][2] or [MSN][3].\n\n    [1]: http://google.com/        \"Google\"\n    [2]: http://search.yahoo.com/  \"Yahoo Search\"\n    [3]: http://search.msn.com/    \"MSN Search\"\n\nOutput:\n\n    &lt;p&gt;I get 10 times more traffic from &lt;a href=\"http://google.com/\"\n    title=\"Google\"&gt;Google&lt;/a&gt; than from &lt;a href=\"http://search.yahoo.com/\"\n    title=\"Yahoo Search\"&gt;Yahoo&lt;/a&gt; or &lt;a href=\"http://search.msn.com/\"\n    title=\"MSN Search\"&gt;MSN&lt;/a&gt;.&lt;/p&gt;\n\nThe title attribute is optional. Link names may contain letters,\nnumbers and spaces, but are *not* case sensitive:\n\n    I start my morning with a cup of coffee and\n    [The New York Times][NY Times].\n\n    [ny times]: http://www.nytimes.com/\n\nOutput:\n\n    &lt;p&gt;I start my morning with a cup of coffee and\n    &lt;a href=\"http://www.nytimes.com/\"&gt;The New York Times&lt;/a&gt;.&lt;/p&gt;\n\n\n### Images ###\n\nImage syntax is very much like link syntax.\n\nInline (titles are optional):\n\n    ![alt text](/path/to/img.jpg \"Title\")\n\nReference-style:\n\n    ![alt text][id]\n\n    [id]: /path/to/img.jpg \"Title\"\n\nBoth of the above examples produce the same output:\n\n    &lt;img src=\"/path/to/img.jpg\" alt=\"alt text\" title=\"Title\" /&gt;\n\n\n\n### Code ###\n\nIn a regular paragraph, you can create code span by wrapping text in\nbacktick quotes. Any ampersands (`&amp;`) and angle brackets (`&lt;` or\n`&gt;`) will automatically be translated into HTML entities. This makes\nit easy to use Markdown to write about HTML example code:\n\n    I strongly recommend against using any `&lt;blink&gt;` tags.\n\n    I wish SmartyPants used named entities like `&amp;mdash;`\n    instead of decimal-encoded entites like `&amp;#8212;`.\n\nOutput:\n\n    &lt;p&gt;I strongly recommend against using any\n    &lt;code&gt;&amp;lt;blink&amp;gt;&lt;/code&gt; tags.&lt;/p&gt;\n\n    &lt;p&gt;I wish SmartyPants used named entities like\n    &lt;code&gt;&amp;amp;mdash;&lt;/code&gt; instead of decimal-encoded\n    entites like &lt;code&gt;&amp;amp;#8212;&lt;/code&gt;.&lt;/p&gt;\n\n\nTo specify an entire block of pre-formatted code, indent every line of\nthe block by 4 spaces or 1 tab. Just like with code spans, `&amp;`, `&lt;`,\nand `&gt;` characters will be escaped automatically.\n\nMarkdown:\n\n    If you want your page to validate under XHTML 1.0 Strict,\n    you've got to put paragraph tags in your blockquotes:\n\n        &lt;blockquote&gt;\n            &lt;p&gt;For example.&lt;/p&gt;\n        &lt;/blockquote&gt;\n\nOutput:\n\n    &lt;p&gt;If you want your page to validate under XHTML 1.0 Strict,\n    you've got to put paragraph tags in your blockquotes:&lt;/p&gt;\n\n    &lt;pre&gt;&lt;code&gt;&amp;lt;blockquote&amp;gt;\n        &amp;lt;p&amp;gt;For example.&amp;lt;/p&amp;gt;\n    &amp;lt;/blockquote&amp;gt;\n    &lt;/code&gt;&lt;/pre&gt;\n\n## Fenced code blocks (and syntax highlighting)\n\n```javascript\nfor (var i = 0; i < items.length; i++) {\n    console.log(items[i], i); // log them\n}\n```\n\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: 'markdown',\n        lineNumbers: true,\n        theme: \"default\",\n        extraKeys: {\"Enter\": \"newlineAndIndentContinueMarkdownList\"}\n      });\n    </script>\n\n    <p>If you also want support <code>strikethrough</code>, <code>emoji</code> and few other goodies, check out <a href=\"../gfm/index.html\">Github-Flavored Markdown mode</a>.</p>\n\n    <p>Optionally depends on other modes for properly highlighted code blocks,\n      and XML mode for properly highlighted inline XML blocks.</p>\n\n    <p>Markdown mode supports these options:</p>\n    <ul>\n      <li>\n        <d1>\n          <dt><code>highlightFormatting: boolean</code></dt>\n          <dd>Whether to separately highlight markdown meta characterts (<code>*[]()</code>etc.) (default: <code>false</code>).</dd>\n        </d1>\n      </li>\n      <li>\n        <d1>\n          <dt><code>maxBlockquoteDepth: boolean</code></dt>\n          <dd>Maximum allowed blockquote nesting (default: <code>0</code> - infinite nesting).</dd>\n        </d1>\n      </li>\n      <li>\n        <d1>\n          <dt><code>xml: boolean</code></dt>\n          <dd>Whether to highlight inline XML (default: <code>true</code>).</dd>\n        </d1>\n      </li>\n      <li>\n        <d1>\n          <dt><code>fencedCodeBlockHighlighting: boolean</code></dt>\n          <dd>Whether to syntax-highlight fenced code blocks, if given mode is included (default: <code>true</code>).</dd>\n        </d1>\n      </li>\n      <li>\n        <d1>\n          <dt><code>tokenTypeOverrides: Object</code></dt>\n          <dd>When you want ot override default token type names (e.g. <code>{code: \"code\"}</code>).</dd>\n        </d1>\n      </li>\n      <li>\n        <d1>\n          <dt><code>allowAtxHeaderWithoutSpace: boolean</code></dt>\n          <dd>Allow lazy headers without whitespace between hashtag and text (default: <code>false</code>).</dd>\n        </d1>\n      </li>\n    </ul>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-markdown</code>.</p>\n\n    <p><strong>Parsing/Highlighting Tests:</strong> <a href=\"../../test/index.html#markdown_*\">normal</a>,  <a href=\"../../test/index.html#verbose,markdown_*\">verbose</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/markdown/markdown.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../xml/xml\"), require(\"../meta\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../xml/xml\", \"../meta\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"markdown\", function(cmCfg, modeCfg) {\n\n  var htmlMode = CodeMirror.getMode(cmCfg, \"text/html\");\n  var htmlModeMissing = htmlMode.name == \"null\"\n\n  function getMode(name) {\n    if (CodeMirror.findModeByName) {\n      var found = CodeMirror.findModeByName(name);\n      if (found) name = found.mime || found.mimes[0];\n    }\n    var mode = CodeMirror.getMode(cmCfg, name);\n    return mode.name == \"null\" ? null : mode;\n  }\n\n  // Should characters that affect highlighting be highlighted separate?\n  // Does not include characters that will be output (such as `1.` and `-` for lists)\n  if (modeCfg.highlightFormatting === undefined)\n    modeCfg.highlightFormatting = false;\n\n  // Maximum number of nested blockquotes. Set to 0 for infinite nesting.\n  // Excess `>` will emit `error` token.\n  if (modeCfg.maxBlockquoteDepth === undefined)\n    modeCfg.maxBlockquoteDepth = 0;\n\n  // Turn on task lists? (\"- [ ] \" and \"- [x] \")\n  if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;\n\n  // Turn on strikethrough syntax\n  if (modeCfg.strikethrough === undefined)\n    modeCfg.strikethrough = false;\n\n  if (modeCfg.emoji === undefined)\n    modeCfg.emoji = false;\n\n  if (modeCfg.fencedCodeBlockHighlighting === undefined)\n    modeCfg.fencedCodeBlockHighlighting = true;\n\n  if (modeCfg.xml === undefined)\n    modeCfg.xml = true;\n\n  // Allow token types to be overridden by user-provided token types.\n  if (modeCfg.tokenTypeOverrides === undefined)\n    modeCfg.tokenTypeOverrides = {};\n\n  var tokenTypes = {\n    header: \"header\",\n    code: \"comment\",\n    quote: \"quote\",\n    list1: \"variable-2\",\n    list2: \"variable-3\",\n    list3: \"keyword\",\n    hr: \"hr\",\n    image: \"image\",\n    imageAltText: \"image-alt-text\",\n    imageMarker: \"image-marker\",\n    formatting: \"formatting\",\n    linkInline: \"link\",\n    linkEmail: \"link\",\n    linkText: \"link\",\n    linkHref: \"string\",\n    em: \"em\",\n    strong: \"strong\",\n    strikethrough: \"strikethrough\",\n    emoji: \"builtin\"\n  };\n\n  for (var tokenType in tokenTypes) {\n    if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {\n      tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];\n    }\n  }\n\n  var hrRE = /^([*\\-_])(?:\\s*\\1){2,}\\s*$/\n  ,   listRE = /^(?:[*\\-+]|^[0-9]+([.)]))\\s+/\n  ,   taskListRE = /^\\[(x| )\\](?=\\s)/i // Must follow listRE\n  ,   atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/\n  ,   setextHeaderRE = /^ *(?:\\={1,}|-{1,})\\s*$/\n  ,   textRE = /^[^#!\\[\\]*_\\\\<>` \"'(~:]+/\n  ,   fencedCodeRE = /^(~~~+|```+)[ \\t]*([\\w+#-]*)[^\\n`]*$/\n  ,   linkDefRE = /^\\s*\\[[^\\]]+?\\]:.*$/ // naive link-definition\n  ,   punctuation = /[!\"#$%&'()*+,\\-.\\/:;<=>?@\\[\\\\\\]^_`{|}~\\xA1\\xA7\\xAB\\xB6\\xB7\\xBB\\xBF\\u037E\\u0387\\u055A-\\u055F\\u0589\\u058A\\u05BE\\u05C0\\u05C3\\u05C6\\u05F3\\u05F4\\u0609\\u060A\\u060C\\u060D\\u061B\\u061E\\u061F\\u066A-\\u066D\\u06D4\\u0700-\\u070D\\u07F7-\\u07F9\\u0830-\\u083E\\u085E\\u0964\\u0965\\u0970\\u0AF0\\u0DF4\\u0E4F\\u0E5A\\u0E5B\\u0F04-\\u0F12\\u0F14\\u0F3A-\\u0F3D\\u0F85\\u0FD0-\\u0FD4\\u0FD9\\u0FDA\\u104A-\\u104F\\u10FB\\u1360-\\u1368\\u1400\\u166D\\u166E\\u169B\\u169C\\u16EB-\\u16ED\\u1735\\u1736\\u17D4-\\u17D6\\u17D8-\\u17DA\\u1800-\\u180A\\u1944\\u1945\\u1A1E\\u1A1F\\u1AA0-\\u1AA6\\u1AA8-\\u1AAD\\u1B5A-\\u1B60\\u1BFC-\\u1BFF\\u1C3B-\\u1C3F\\u1C7E\\u1C7F\\u1CC0-\\u1CC7\\u1CD3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205E\\u207D\\u207E\\u208D\\u208E\\u2308-\\u230B\\u2329\\u232A\\u2768-\\u2775\\u27C5\\u27C6\\u27E6-\\u27EF\\u2983-\\u2998\\u29D8-\\u29DB\\u29FC\\u29FD\\u2CF9-\\u2CFC\\u2CFE\\u2CFF\\u2D70\\u2E00-\\u2E2E\\u2E30-\\u2E42\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\u3030\\u303D\\u30A0\\u30FB\\uA4FE\\uA4FF\\uA60D-\\uA60F\\uA673\\uA67E\\uA6F2-\\uA6F7\\uA874-\\uA877\\uA8CE\\uA8CF\\uA8F8-\\uA8FA\\uA8FC\\uA92E\\uA92F\\uA95F\\uA9C1-\\uA9CD\\uA9DE\\uA9DF\\uAA5C-\\uAA5F\\uAADE\\uAADF\\uAAF0\\uAAF1\\uABEB\\uFD3E\\uFD3F\\uFE10-\\uFE19\\uFE30-\\uFE52\\uFE54-\\uFE61\\uFE63\\uFE68\\uFE6A\\uFE6B\\uFF01-\\uFF03\\uFF05-\\uFF0A\\uFF0C-\\uFF0F\\uFF1A\\uFF1B\\uFF1F\\uFF20\\uFF3B-\\uFF3D\\uFF3F\\uFF5B\\uFF5D\\uFF5F-\\uFF65]|\\uD800[\\uDD00-\\uDD02\\uDF9F\\uDFD0]|\\uD801\\uDD6F|\\uD802[\\uDC57\\uDD1F\\uDD3F\\uDE50-\\uDE58\\uDE7F\\uDEF0-\\uDEF6\\uDF39-\\uDF3F\\uDF99-\\uDF9C]|\\uD804[\\uDC47-\\uDC4D\\uDCBB\\uDCBC\\uDCBE-\\uDCC1\\uDD40-\\uDD43\\uDD74\\uDD75\\uDDC5-\\uDDC9\\uDDCD\\uDDDB\\uDDDD-\\uDDDF\\uDE38-\\uDE3D\\uDEA9]|\\uD805[\\uDCC6\\uDDC1-\\uDDD7\\uDE41-\\uDE43\\uDF3C-\\uDF3E]|\\uD809[\\uDC70-\\uDC74]|\\uD81A[\\uDE6E\\uDE6F\\uDEF5\\uDF37-\\uDF3B\\uDF44]|\\uD82F\\uDC9F|\\uD836[\\uDE87-\\uDE8B]/\n  ,   expandedTab = \"    \" // CommonMark specifies tab as 4 spaces\n\n  function switchInline(stream, state, f) {\n    state.f = state.inline = f;\n    return f(stream, state);\n  }\n\n  function switchBlock(stream, state, f) {\n    state.f = state.block = f;\n    return f(stream, state);\n  }\n\n  function lineIsEmpty(line) {\n    return !line || !/\\S/.test(line.string)\n  }\n\n  // Blocks\n\n  function blankLine(state) {\n    // Reset linkTitle state\n    state.linkTitle = false;\n    state.linkHref = false;\n    state.linkText = false;\n    // Reset EM state\n    state.em = false;\n    // Reset STRONG state\n    state.strong = false;\n    // Reset strikethrough state\n    state.strikethrough = false;\n    // Reset state.quote\n    state.quote = 0;\n    // Reset state.indentedCode\n    state.indentedCode = false;\n    if (state.f == htmlBlock) {\n      var exit = htmlModeMissing\n      if (!exit) {\n        var inner = CodeMirror.innerMode(htmlMode, state.htmlState)\n        exit = inner.mode.name == \"xml\" && inner.state.tagStart === null &&\n          (!inner.state.context && inner.state.tokenize.isInText)\n      }\n      if (exit) {\n        state.f = inlineNormal;\n        state.block = blockNormal;\n        state.htmlState = null;\n      }\n    }\n    // Reset state.trailingSpace\n    state.trailingSpace = 0;\n    state.trailingSpaceNewLine = false;\n    // Mark this line as blank\n    state.prevLine = state.thisLine\n    state.thisLine = {stream: null}\n    return null;\n  }\n\n  function blockNormal(stream, state) {\n    var firstTokenOnLine = stream.column() === state.indentation;\n    var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream);\n    var prevLineIsIndentedCode = state.indentedCode;\n    var prevLineIsHr = state.prevLine.hr;\n    var prevLineIsList = state.list !== false;\n    var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3;\n\n    state.indentedCode = false;\n\n    var lineIndentation = state.indentation;\n    // compute once per line (on first token)\n    if (state.indentationDiff === null) {\n      state.indentationDiff = state.indentation;\n      if (prevLineIsList) {\n        // Reset inline styles which shouldn't propagate aross list items\n        state.em = false;\n        state.strong = false;\n        state.code = false;\n        state.strikethrough = false;\n\n        state.list = null;\n        // While this list item's marker's indentation is less than the deepest\n        //  list item's content's indentation,pop the deepest list item\n        //  indentation off the stack, and update block indentation state\n        while (lineIndentation < state.listStack[state.listStack.length - 1]) {\n          state.listStack.pop();\n          if (state.listStack.length) {\n            state.indentation = state.listStack[state.listStack.length - 1];\n          // less than the first list's indent -> the line is no longer a list\n          } else {\n            state.list = false;\n          }\n        }\n        if (state.list !== false) {\n          state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1]\n        }\n      }\n    }\n\n    // not comprehensive (currently only for setext detection purposes)\n    var allowsInlineContinuation = (\n        !prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header &&\n        (!prevLineIsList || !prevLineIsIndentedCode) &&\n        !state.prevLine.fencedCodeEnd\n    );\n\n    var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) &&\n      state.indentation <= maxNonCodeIndentation && stream.match(hrRE);\n\n    var match = null;\n    if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd ||\n         state.prevLine.header || prevLineLineIsEmpty)) {\n      stream.skipToEnd();\n      state.indentedCode = true;\n      return tokenTypes.code;\n    } else if (stream.eatSpace()) {\n      return null;\n    } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) {\n      state.quote = 0;\n      state.header = match[1].length;\n      state.thisLine.header = true;\n      if (modeCfg.highlightFormatting) state.formatting = \"header\";\n      state.f = state.inline;\n      return getType(state);\n    } else if (state.indentation <= maxNonCodeIndentation && stream.eat('>')) {\n      state.quote = firstTokenOnLine ? 1 : state.quote + 1;\n      if (modeCfg.highlightFormatting) state.formatting = \"quote\";\n      stream.eatSpace();\n      return getType(state);\n    } else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) {\n      var listType = match[1] ? \"ol\" : \"ul\";\n\n      state.indentation = lineIndentation + stream.current().length;\n      state.list = true;\n      state.quote = 0;\n\n      // Add this list item's content's indentation to the stack\n      state.listStack.push(state.indentation);\n\n      if (modeCfg.taskLists && stream.match(taskListRE, false)) {\n        state.taskList = true;\n      }\n      state.f = state.inline;\n      if (modeCfg.highlightFormatting) state.formatting = [\"list\", \"list-\" + listType];\n      return getType(state);\n    } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) {\n      state.quote = 0;\n      state.fencedEndRE = new RegExp(match[1] + \"+ *$\");\n      // try switching mode\n      state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2]);\n      if (state.localMode) state.localState = CodeMirror.startState(state.localMode);\n      state.f = state.block = local;\n      if (modeCfg.highlightFormatting) state.formatting = \"code-block\";\n      state.code = -1\n      return getType(state);\n    // SETEXT has lowest block-scope precedence after HR, so check it after\n    //  the others (code, blockquote, list...)\n    } else if (\n      // if setext set, indicates line after ---/===\n      state.setext || (\n        // line before ---/===\n        (!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false &&\n        !state.code && !isHr && !linkDefRE.test(stream.string) &&\n        (match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE))\n      )\n    ) {\n      if ( !state.setext ) {\n        state.header = match[0].charAt(0) == '=' ? 1 : 2;\n        state.setext = state.header;\n      } else {\n        state.header = state.setext;\n        // has no effect on type so we can reset it now\n        state.setext = 0;\n        stream.skipToEnd();\n        if (modeCfg.highlightFormatting) state.formatting = \"header\";\n      }\n      state.thisLine.header = true;\n      state.f = state.inline;\n      return getType(state);\n    } else if (isHr) {\n      stream.skipToEnd();\n      state.hr = true;\n      state.thisLine.hr = true;\n      return tokenTypes.hr;\n    } else if (stream.peek() === '[') {\n      return switchInline(stream, state, footnoteLink);\n    }\n\n    return switchInline(stream, state, state.inline);\n  }\n\n  function htmlBlock(stream, state) {\n    var style = htmlMode.token(stream, state.htmlState);\n    if (!htmlModeMissing) {\n      var inner = CodeMirror.innerMode(htmlMode, state.htmlState)\n      if ((inner.mode.name == \"xml\" && inner.state.tagStart === null &&\n           (!inner.state.context && inner.state.tokenize.isInText)) ||\n          (state.md_inside && stream.current().indexOf(\">\") > -1)) {\n        state.f = inlineNormal;\n        state.block = blockNormal;\n        state.htmlState = null;\n      }\n    }\n    return style;\n  }\n\n  function local(stream, state) {\n    var currListInd = state.listStack[state.listStack.length - 1] || 0;\n    var hasExitedList = state.indentation < currListInd;\n    var maxFencedEndInd = currListInd + 3;\n    if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) {\n      if (modeCfg.highlightFormatting) state.formatting = \"code-block\";\n      var returnType;\n      if (!hasExitedList) returnType = getType(state)\n      state.localMode = state.localState = null;\n      state.block = blockNormal;\n      state.f = inlineNormal;\n      state.fencedEndRE = null;\n      state.code = 0\n      state.thisLine.fencedCodeEnd = true;\n      if (hasExitedList) return switchBlock(stream, state, state.block);\n      return returnType;\n    } else if (state.localMode) {\n      return state.localMode.token(stream, state.localState);\n    } else {\n      stream.skipToEnd();\n      return tokenTypes.code;\n    }\n  }\n\n  // Inline\n  function getType(state) {\n    var styles = [];\n\n    if (state.formatting) {\n      styles.push(tokenTypes.formatting);\n\n      if (typeof state.formatting === \"string\") state.formatting = [state.formatting];\n\n      for (var i = 0; i < state.formatting.length; i++) {\n        styles.push(tokenTypes.formatting + \"-\" + state.formatting[i]);\n\n        if (state.formatting[i] === \"header\") {\n          styles.push(tokenTypes.formatting + \"-\" + state.formatting[i] + \"-\" + state.header);\n        }\n\n        // Add `formatting-quote` and `formatting-quote-#` for blockquotes\n        // Add `error` instead if the maximum blockquote nesting depth is passed\n        if (state.formatting[i] === \"quote\") {\n          if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {\n            styles.push(tokenTypes.formatting + \"-\" + state.formatting[i] + \"-\" + state.quote);\n          } else {\n            styles.push(\"error\");\n          }\n        }\n      }\n    }\n\n    if (state.taskOpen) {\n      styles.push(\"meta\");\n      return styles.length ? styles.join(' ') : null;\n    }\n    if (state.taskClosed) {\n      styles.push(\"property\");\n      return styles.length ? styles.join(' ') : null;\n    }\n\n    if (state.linkHref) {\n      styles.push(tokenTypes.linkHref, \"url\");\n    } else { // Only apply inline styles to non-url text\n      if (state.strong) { styles.push(tokenTypes.strong); }\n      if (state.em) { styles.push(tokenTypes.em); }\n      if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }\n      if (state.emoji) { styles.push(tokenTypes.emoji); }\n      if (state.linkText) { styles.push(tokenTypes.linkText); }\n      if (state.code) { styles.push(tokenTypes.code); }\n      if (state.image) { styles.push(tokenTypes.image); }\n      if (state.imageAltText) { styles.push(tokenTypes.imageAltText, \"link\"); }\n      if (state.imageMarker) { styles.push(tokenTypes.imageMarker); }\n    }\n\n    if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + \"-\" + state.header); }\n\n    if (state.quote) {\n      styles.push(tokenTypes.quote);\n\n      // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth\n      if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {\n        styles.push(tokenTypes.quote + \"-\" + state.quote);\n      } else {\n        styles.push(tokenTypes.quote + \"-\" + modeCfg.maxBlockquoteDepth);\n      }\n    }\n\n    if (state.list !== false) {\n      var listMod = (state.listStack.length - 1) % 3;\n      if (!listMod) {\n        styles.push(tokenTypes.list1);\n      } else if (listMod === 1) {\n        styles.push(tokenTypes.list2);\n      } else {\n        styles.push(tokenTypes.list3);\n      }\n    }\n\n    if (state.trailingSpaceNewLine) {\n      styles.push(\"trailing-space-new-line\");\n    } else if (state.trailingSpace) {\n      styles.push(\"trailing-space-\" + (state.trailingSpace % 2 ? \"a\" : \"b\"));\n    }\n\n    return styles.length ? styles.join(' ') : null;\n  }\n\n  function handleText(stream, state) {\n    if (stream.match(textRE, true)) {\n      return getType(state);\n    }\n    return undefined;\n  }\n\n  function inlineNormal(stream, state) {\n    var style = state.text(stream, state);\n    if (typeof style !== 'undefined')\n      return style;\n\n    if (state.list) { // List marker (*, +, -, 1., etc)\n      state.list = null;\n      return getType(state);\n    }\n\n    if (state.taskList) {\n      var taskOpen = stream.match(taskListRE, true)[1] === \" \";\n      if (taskOpen) state.taskOpen = true;\n      else state.taskClosed = true;\n      if (modeCfg.highlightFormatting) state.formatting = \"task\";\n      state.taskList = false;\n      return getType(state);\n    }\n\n    state.taskOpen = false;\n    state.taskClosed = false;\n\n    if (state.header && stream.match(/^#+$/, true)) {\n      if (modeCfg.highlightFormatting) state.formatting = \"header\";\n      return getType(state);\n    }\n\n    var ch = stream.next();\n\n    // Matches link titles present on next line\n    if (state.linkTitle) {\n      state.linkTitle = false;\n      var matchCh = ch;\n      if (ch === '(') {\n        matchCh = ')';\n      }\n      matchCh = (matchCh+'').replace(/([.?*+^\\[\\]\\\\(){}|-])/g, \"\\\\$1\");\n      var regex = '^\\\\s*(?:[^' + matchCh + '\\\\\\\\]+|\\\\\\\\\\\\\\\\|\\\\\\\\.)' + matchCh;\n      if (stream.match(new RegExp(regex), true)) {\n        return tokenTypes.linkHref;\n      }\n    }\n\n    // If this block is changed, it may need to be updated in GFM mode\n    if (ch === '`') {\n      var previousFormatting = state.formatting;\n      if (modeCfg.highlightFormatting) state.formatting = \"code\";\n      stream.eatWhile('`');\n      var count = stream.current().length\n      if (state.code == 0 && (!state.quote || count == 1)) {\n        state.code = count\n        return getType(state)\n      } else if (count == state.code) { // Must be exact\n        var t = getType(state)\n        state.code = 0\n        return t\n      } else {\n        state.formatting = previousFormatting\n        return getType(state)\n      }\n    } else if (state.code) {\n      return getType(state);\n    }\n\n    if (ch === '\\\\') {\n      stream.next();\n      if (modeCfg.highlightFormatting) {\n        var type = getType(state);\n        var formattingEscape = tokenTypes.formatting + \"-escape\";\n        return type ? type + \" \" + formattingEscape : formattingEscape;\n      }\n    }\n\n    if (ch === '!' && stream.match(/\\[[^\\]]*\\] ?(?:\\(|\\[)/, false)) {\n      state.imageMarker = true;\n      state.image = true;\n      if (modeCfg.highlightFormatting) state.formatting = \"image\";\n      return getType(state);\n    }\n\n    if (ch === '[' && state.imageMarker && stream.match(/[^\\]]*\\](\\(.*?\\)| ?\\[.*?\\])/, false)) {\n      state.imageMarker = false;\n      state.imageAltText = true\n      if (modeCfg.highlightFormatting) state.formatting = \"image\";\n      return getType(state);\n    }\n\n    if (ch === ']' && state.imageAltText) {\n      if (modeCfg.highlightFormatting) state.formatting = \"image\";\n      var type = getType(state);\n      state.imageAltText = false;\n      state.image = false;\n      state.inline = state.f = linkHref;\n      return type;\n    }\n\n    if (ch === '[' && !state.image) {\n      if (state.linkText && stream.match(/^.*?\\]/)) return getType(state)\n      state.linkText = true;\n      if (modeCfg.highlightFormatting) state.formatting = \"link\";\n      return getType(state);\n    }\n\n    if (ch === ']' && state.linkText) {\n      if (modeCfg.highlightFormatting) state.formatting = \"link\";\n      var type = getType(state);\n      state.linkText = false;\n      state.inline = state.f = stream.match(/\\(.*?\\)| ?\\[.*?\\]/, false) ? linkHref : inlineNormal\n      return type;\n    }\n\n    if (ch === '<' && stream.match(/^(https?|ftps?):\\/\\/(?:[^\\\\>]|\\\\.)+>/, false)) {\n      state.f = state.inline = linkInline;\n      if (modeCfg.highlightFormatting) state.formatting = \"link\";\n      var type = getType(state);\n      if (type){\n        type += \" \";\n      } else {\n        type = \"\";\n      }\n      return type + tokenTypes.linkInline;\n    }\n\n    if (ch === '<' && stream.match(/^[^> \\\\]+@(?:[^\\\\>]|\\\\.)+>/, false)) {\n      state.f = state.inline = linkInline;\n      if (modeCfg.highlightFormatting) state.formatting = \"link\";\n      var type = getType(state);\n      if (type){\n        type += \" \";\n      } else {\n        type = \"\";\n      }\n      return type + tokenTypes.linkEmail;\n    }\n\n    if (modeCfg.xml && ch === '<' && stream.match(/^(!--|\\?|!\\[CDATA\\[|[a-z][a-z0-9-]*(?:\\s+[a-z_:.\\-]+(?:\\s*=\\s*[^>]+)?)*\\s*(?:>|$))/i, false)) {\n      var end = stream.string.indexOf(\">\", stream.pos);\n      if (end != -1) {\n        var atts = stream.string.substring(stream.start, end);\n        if (/markdown\\s*=\\s*('|\"){0,1}1('|\"){0,1}/.test(atts)) state.md_inside = true;\n      }\n      stream.backUp(1);\n      state.htmlState = CodeMirror.startState(htmlMode);\n      return switchBlock(stream, state, htmlBlock);\n    }\n\n    if (modeCfg.xml && ch === '<' && stream.match(/^\\/\\w*?>/)) {\n      state.md_inside = false;\n      return \"tag\";\n    } else if (ch === \"*\" || ch === \"_\") {\n      var len = 1, before = stream.pos == 1 ? \" \" : stream.string.charAt(stream.pos - 2)\n      while (len < 3 && stream.eat(ch)) len++\n      var after = stream.peek() || \" \"\n      // See http://spec.commonmark.org/0.27/#emphasis-and-strong-emphasis\n      var leftFlanking = !/\\s/.test(after) && (!punctuation.test(after) || /\\s/.test(before) || punctuation.test(before))\n      var rightFlanking = !/\\s/.test(before) && (!punctuation.test(before) || /\\s/.test(after) || punctuation.test(after))\n      var setEm = null, setStrong = null\n      if (len % 2) { // Em\n        if (!state.em && leftFlanking && (ch === \"*\" || !rightFlanking || punctuation.test(before)))\n          setEm = true\n        else if (state.em == ch && rightFlanking && (ch === \"*\" || !leftFlanking || punctuation.test(after)))\n          setEm = false\n      }\n      if (len > 1) { // Strong\n        if (!state.strong && leftFlanking && (ch === \"*\" || !rightFlanking || punctuation.test(before)))\n          setStrong = true\n        else if (state.strong == ch && rightFlanking && (ch === \"*\" || !leftFlanking || punctuation.test(after)))\n          setStrong = false\n      }\n      if (setStrong != null || setEm != null) {\n        if (modeCfg.highlightFormatting) state.formatting = setEm == null ? \"strong\" : setStrong == null ? \"em\" : \"strong em\"\n        if (setEm === true) state.em = ch\n        if (setStrong === true) state.strong = ch\n        var t = getType(state)\n        if (setEm === false) state.em = false\n        if (setStrong === false) state.strong = false\n        return t\n      }\n    } else if (ch === ' ') {\n      if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces\n        if (stream.peek() === ' ') { // Surrounded by spaces, ignore\n          return getType(state);\n        } else { // Not surrounded by spaces, back up pointer\n          stream.backUp(1);\n        }\n      }\n    }\n\n    if (modeCfg.strikethrough) {\n      if (ch === '~' && stream.eatWhile(ch)) {\n        if (state.strikethrough) {// Remove strikethrough\n          if (modeCfg.highlightFormatting) state.formatting = \"strikethrough\";\n          var t = getType(state);\n          state.strikethrough = false;\n          return t;\n        } else if (stream.match(/^[^\\s]/, false)) {// Add strikethrough\n          state.strikethrough = true;\n          if (modeCfg.highlightFormatting) state.formatting = \"strikethrough\";\n          return getType(state);\n        }\n      } else if (ch === ' ') {\n        if (stream.match(/^~~/, true)) { // Probably surrounded by space\n          if (stream.peek() === ' ') { // Surrounded by spaces, ignore\n            return getType(state);\n          } else { // Not surrounded by spaces, back up pointer\n            stream.backUp(2);\n          }\n        }\n      }\n    }\n\n    if (modeCfg.emoji && ch === \":\" && stream.match(/^(?:[a-z_\\d+][a-z_\\d+-]*|\\-[a-z_\\d+][a-z_\\d+-]*):/)) {\n      state.emoji = true;\n      if (modeCfg.highlightFormatting) state.formatting = \"emoji\";\n      var retType = getType(state);\n      state.emoji = false;\n      return retType;\n    }\n\n    if (ch === ' ') {\n      if (stream.match(/^ +$/, false)) {\n        state.trailingSpace++;\n      } else if (state.trailingSpace) {\n        state.trailingSpaceNewLine = true;\n      }\n    }\n\n    return getType(state);\n  }\n\n  function linkInline(stream, state) {\n    var ch = stream.next();\n\n    if (ch === \">\") {\n      state.f = state.inline = inlineNormal;\n      if (modeCfg.highlightFormatting) state.formatting = \"link\";\n      var type = getType(state);\n      if (type){\n        type += \" \";\n      } else {\n        type = \"\";\n      }\n      return type + tokenTypes.linkInline;\n    }\n\n    stream.match(/^[^>]+/, true);\n\n    return tokenTypes.linkInline;\n  }\n\n  function linkHref(stream, state) {\n    // Check if space, and return NULL if so (to avoid marking the space)\n    if(stream.eatSpace()){\n      return null;\n    }\n    var ch = stream.next();\n    if (ch === '(' || ch === '[') {\n      state.f = state.inline = getLinkHrefInside(ch === \"(\" ? \")\" : \"]\");\n      if (modeCfg.highlightFormatting) state.formatting = \"link-string\";\n      state.linkHref = true;\n      return getType(state);\n    }\n    return 'error';\n  }\n\n  var linkRE = {\n    \")\": /^(?:[^\\\\\\(\\)]|\\\\.|\\((?:[^\\\\\\(\\)]|\\\\.)*\\))*?(?=\\))/,\n    \"]\": /^(?:[^\\\\\\[\\]]|\\\\.|\\[(?:[^\\\\\\[\\]]|\\\\.)*\\])*?(?=\\])/\n  }\n\n  function getLinkHrefInside(endChar) {\n    return function(stream, state) {\n      var ch = stream.next();\n\n      if (ch === endChar) {\n        state.f = state.inline = inlineNormal;\n        if (modeCfg.highlightFormatting) state.formatting = \"link-string\";\n        var returnState = getType(state);\n        state.linkHref = false;\n        return returnState;\n      }\n\n      stream.match(linkRE[endChar])\n      state.linkHref = true;\n      return getType(state);\n    };\n  }\n\n  function footnoteLink(stream, state) {\n    if (stream.match(/^([^\\]\\\\]|\\\\.)*\\]:/, false)) {\n      state.f = footnoteLinkInside;\n      stream.next(); // Consume [\n      if (modeCfg.highlightFormatting) state.formatting = \"link\";\n      state.linkText = true;\n      return getType(state);\n    }\n    return switchInline(stream, state, inlineNormal);\n  }\n\n  function footnoteLinkInside(stream, state) {\n    if (stream.match(/^\\]:/, true)) {\n      state.f = state.inline = footnoteUrl;\n      if (modeCfg.highlightFormatting) state.formatting = \"link\";\n      var returnType = getType(state);\n      state.linkText = false;\n      return returnType;\n    }\n\n    stream.match(/^([^\\]\\\\]|\\\\.)+/, true);\n\n    return tokenTypes.linkText;\n  }\n\n  function footnoteUrl(stream, state) {\n    // Check if space, and return NULL if so (to avoid marking the space)\n    if(stream.eatSpace()){\n      return null;\n    }\n    // Match URL\n    stream.match(/^[^\\s]+/, true);\n    // Check for link title\n    if (stream.peek() === undefined) { // End of line, set flag to check next line\n      state.linkTitle = true;\n    } else { // More content on line, check if link title\n      stream.match(/^(?:\\s+(?:\"(?:[^\"\\\\]|\\\\\\\\|\\\\.)+\"|'(?:[^'\\\\]|\\\\\\\\|\\\\.)+'|\\((?:[^)\\\\]|\\\\\\\\|\\\\.)+\\)))?/, true);\n    }\n    state.f = state.inline = inlineNormal;\n    return tokenTypes.linkHref + \" url\";\n  }\n\n  var mode = {\n    startState: function() {\n      return {\n        f: blockNormal,\n\n        prevLine: {stream: null},\n        thisLine: {stream: null},\n\n        block: blockNormal,\n        htmlState: null,\n        indentation: 0,\n\n        inline: inlineNormal,\n        text: handleText,\n\n        formatting: false,\n        linkText: false,\n        linkHref: false,\n        linkTitle: false,\n        code: 0,\n        em: false,\n        strong: false,\n        header: 0,\n        setext: 0,\n        hr: false,\n        taskList: false,\n        list: false,\n        listStack: [],\n        quote: 0,\n        trailingSpace: 0,\n        trailingSpaceNewLine: false,\n        strikethrough: false,\n        emoji: false,\n        fencedEndRE: null\n      };\n    },\n\n    copyState: function(s) {\n      return {\n        f: s.f,\n\n        prevLine: s.prevLine,\n        thisLine: s.thisLine,\n\n        block: s.block,\n        htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),\n        indentation: s.indentation,\n\n        localMode: s.localMode,\n        localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,\n\n        inline: s.inline,\n        text: s.text,\n        formatting: false,\n        linkText: s.linkText,\n        linkTitle: s.linkTitle,\n        linkHref: s.linkHref,\n        code: s.code,\n        em: s.em,\n        strong: s.strong,\n        strikethrough: s.strikethrough,\n        emoji: s.emoji,\n        header: s.header,\n        setext: s.setext,\n        hr: s.hr,\n        taskList: s.taskList,\n        list: s.list,\n        listStack: s.listStack.slice(0),\n        quote: s.quote,\n        indentedCode: s.indentedCode,\n        trailingSpace: s.trailingSpace,\n        trailingSpaceNewLine: s.trailingSpaceNewLine,\n        md_inside: s.md_inside,\n        fencedEndRE: s.fencedEndRE\n      };\n    },\n\n    token: function(stream, state) {\n\n      // Reset state.formatting\n      state.formatting = false;\n\n      if (stream != state.thisLine.stream) {\n        state.header = 0;\n        state.hr = false;\n\n        if (stream.match(/^\\s*$/, true)) {\n          blankLine(state);\n          return null;\n        }\n\n        state.prevLine = state.thisLine\n        state.thisLine = {stream: stream}\n\n        // Reset state.taskList\n        state.taskList = false;\n\n        // Reset state.trailingSpace\n        state.trailingSpace = 0;\n        state.trailingSpaceNewLine = false;\n\n        if (!state.localState) {\n          state.f = state.block;\n          if (state.f != htmlBlock) {\n            var indentation = stream.match(/^\\s*/, true)[0].replace(/\\t/g, expandedTab).length;\n            state.indentation = indentation;\n            state.indentationDiff = null;\n            if (indentation > 0) return null;\n          }\n        }\n      }\n      return state.f(stream, state);\n    },\n\n    innerMode: function(state) {\n      if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};\n      if (state.localState) return {state: state.localState, mode: state.localMode};\n      return {state: state, mode: mode};\n    },\n\n    indent: function(state, textAfter, line) {\n      if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line)\n      if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line)\n      return CodeMirror.Pass\n    },\n\n    blankLine: blankLine,\n\n    getType: getType,\n\n    blockCommentStart: \"<!--\",\n    blockCommentEnd: \"-->\",\n    closeBrackets: \"()[]{}''\\\"\\\"``\",\n    fold: \"markdown\"\n  };\n  return mode;\n}, \"xml\");\n\nCodeMirror.defineMIME(\"text/markdown\", \"markdown\");\n\nCodeMirror.defineMIME(\"text/x-markdown\", \"markdown\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/markdown/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var config = {tabSize: 4, indentUnit: 2}\n  var mode = CodeMirror.getMode(config, \"markdown\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n  var modeHighlightFormatting = CodeMirror.getMode(config, {name: \"markdown\", highlightFormatting: true});\n  function FT(name) { test.mode(name, modeHighlightFormatting, Array.prototype.slice.call(arguments, 1)); }\n  var modeMT_noXml = CodeMirror.getMode(config, {name: \"markdown\", xml: false});\n  function MT_noXml(name) { test.mode(name, modeMT_noXml, Array.prototype.slice.call(arguments, 1)); }\n  var modeMT_noFencedHighlight = CodeMirror.getMode(config, {name: \"markdown\", fencedCodeBlockHighlighting: false});\n  function MT_noFencedHighlight(name) { test.mode(name, modeMT_noFencedHighlight, Array.prototype.slice.call(arguments, 1)); }\n  var modeAtxNoSpace = CodeMirror.getMode(config, {name: \"markdown\", allowAtxHeaderWithoutSpace: true});\n  function AtxNoSpaceTest(name) { test.mode(name, modeAtxNoSpace, Array.prototype.slice.call(arguments, 1)); }\n  var modeOverrideClasses = CodeMirror.getMode(config, {\n    name: \"markdown\",\n    strikethrough: true,\n    emoji: true,\n    tokenTypeOverrides: {\n      \"header\" : \"override-header\",\n      \"code\" : \"override-code\",\n      \"quote\" : \"override-quote\",\n      \"list1\" : \"override-list1\",\n      \"list2\" : \"override-list2\",\n      \"list3\" : \"override-list3\",\n      \"hr\" : \"override-hr\",\n      \"image\" : \"override-image\",\n      \"imageAltText\": \"override-image-alt-text\",\n      \"imageMarker\": \"override-image-marker\",\n      \"linkInline\" : \"override-link-inline\",\n      \"linkEmail\" : \"override-link-email\",\n      \"linkText\" : \"override-link-text\",\n      \"linkHref\" : \"override-link-href\",\n      \"em\" : \"override-em\",\n      \"strong\" : \"override-strong\",\n      \"strikethrough\" : \"override-strikethrough\",\n      \"emoji\" : \"override-emoji\"\n  }});\n  function TokenTypeOverrideTest(name) { test.mode(name, modeOverrideClasses, Array.prototype.slice.call(arguments, 1)); }\n  var modeFormattingOverride = CodeMirror.getMode(config, {\n    name: \"markdown\",\n    highlightFormatting: true,\n    tokenTypeOverrides: {\n      \"formatting\" : \"override-formatting\"\n  }});\n  function FormatTokenTypeOverrideTest(name) { test.mode(name, modeFormattingOverride, Array.prototype.slice.call(arguments, 1)); }\n  var modeET = CodeMirror.getMode(config, {name: \"markdown\", emoji: true});\n  function ET(name) { test.mode(name, modeET, Array.prototype.slice.call(arguments, 1)); }\n\n\n  FT(\"formatting_emAsterisk\",\n     \"[em&formatting&formatting-em *][em foo][em&formatting&formatting-em *]\");\n\n  FT(\"formatting_emUnderscore\",\n     \"[em&formatting&formatting-em _][em foo][em&formatting&formatting-em _]\");\n\n  FT(\"formatting_strongAsterisk\",\n     \"[strong&formatting&formatting-strong **][strong foo][strong&formatting&formatting-strong **]\");\n\n  FT(\"formatting_strongUnderscore\",\n     \"[strong&formatting&formatting-strong __][strong foo][strong&formatting&formatting-strong __]\");\n\n  FT(\"formatting_codeBackticks\",\n     \"[comment&formatting&formatting-code `][comment foo][comment&formatting&formatting-code `]\");\n\n  FT(\"formatting_doubleBackticks\",\n     \"[comment&formatting&formatting-code ``][comment foo ` bar][comment&formatting&formatting-code ``]\");\n\n  FT(\"formatting_atxHeader\",\n     \"[header&header-1&formatting&formatting-header&formatting-header-1 # ][header&header-1 foo # bar ][header&header-1&formatting&formatting-header&formatting-header-1 #]\");\n\n  FT(\"formatting_setextHeader\",\n     \"[header&header-1 foo]\",\n     \"[header&header-1&formatting&formatting-header&formatting-header-1 =]\");\n\n  FT(\"formatting_blockquote\",\n     \"[quote&quote-1&formatting&formatting-quote&formatting-quote-1 > ][quote&quote-1 foo]\");\n\n  FT(\"formatting_list\",\n     \"[variable-2&formatting&formatting-list&formatting-list-ul - ][variable-2 foo]\");\n  FT(\"formatting_list\",\n     \"[variable-2&formatting&formatting-list&formatting-list-ol 1. ][variable-2 foo]\");\n\n  FT(\"formatting_link\",\n     \"[link&formatting&formatting-link [][link foo][link&formatting&formatting-link ]]][string&formatting&formatting-link-string&url (][string&url http://example.com/][string&formatting&formatting-link-string&url )]\");\n\n  FT(\"formatting_linkReference\",\n     \"[link&formatting&formatting-link [][link foo][link&formatting&formatting-link ]]][string&formatting&formatting-link-string&url [][string&url bar][string&formatting&formatting-link-string&url ]]]\",\n     \"[link&formatting&formatting-link [][link bar][link&formatting&formatting-link ]]:] [string&url http://example.com/]\");\n\n  FT(\"formatting_linkWeb\",\n     \"[link&formatting&formatting-link <][link http://example.com/][link&formatting&formatting-link >]\");\n\n  FT(\"formatting_linkEmail\",\n     \"[link&formatting&formatting-link <][link user@example.com][link&formatting&formatting-link >]\");\n\n  FT(\"formatting_escape\",\n     \"[formatting-escape \\\\*]\");\n\n  FT(\"formatting_image\",\n     \"[formatting&formatting-image&image&image-marker !][formatting&formatting-image&image&image-alt-text&link [[][image&image-alt-text&link alt text][formatting&formatting-image&image&image-alt-text&link ]]][formatting&formatting-link-string&string&url (][url&string http://link.to/image.jpg][formatting&formatting-link-string&string&url )]\");\n\n  FT(\"codeBlock\",\n     \"[comment&formatting&formatting-code-block ```css]\",\n     \"[tag foo]\",\n     \"[comment&formatting&formatting-code-block ```]\");\n\n  MT(\"plainText\",\n     \"foo\");\n\n  // Don't style single trailing space\n  MT(\"trailingSpace1\",\n     \"foo \");\n\n  // Two or more trailing spaces should be styled with line break character\n  MT(\"trailingSpace2\",\n     \"foo[trailing-space-a  ][trailing-space-new-line  ]\");\n\n  MT(\"trailingSpace3\",\n     \"foo[trailing-space-a  ][trailing-space-b  ][trailing-space-new-line  ]\");\n\n  MT(\"trailingSpace4\",\n     \"foo[trailing-space-a  ][trailing-space-b  ][trailing-space-a  ][trailing-space-new-line  ]\");\n\n  // Code blocks using 4 spaces (regardless of CodeMirror.tabSize value)\n  MT(\"codeBlocksUsing4Spaces\",\n     \"    [comment foo]\");\n\n  // Code blocks using 4 spaces with internal indentation\n  MT(\"codeBlocksUsing4SpacesIndentation\",\n     \"    [comment bar]\",\n     \"        [comment hello]\",\n     \"            [comment world]\",\n     \"    [comment foo]\",\n     \"bar\");\n\n  // Code blocks should end even after extra indented lines\n  MT(\"codeBlocksWithTrailingIndentedLine\",\n     \"    [comment foo]\",\n     \"        [comment bar]\",\n     \"    [comment baz]\",\n     \"    \",\n     \"hello\");\n\n  // Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value)\n  MT(\"codeBlocksUsing1Tab\",\n     \"\\t[comment foo]\");\n\n  // No code blocks directly after paragraph\n  // http://spec.commonmark.org/0.19/#example-65\n  MT(\"noCodeBlocksAfterParagraph\",\n     \"Foo\",\n     \"    Bar\");\n\n  MT(\"codeBlocksAfterATX\",\n     \"[header&header-1 # foo]\",\n     \"    [comment code]\");\n\n  MT(\"codeBlocksAfterSetext\",\n     \"[header&header-2 foo]\",\n     \"[header&header-2 ---]\",\n     \"    [comment code]\");\n\n  MT(\"codeBlocksAfterFencedCode\",\n     \"[comment ```]\",\n     \"[comment foo]\",\n     \"[comment ```]\",\n     \"    [comment code]\");\n\n  // Inline code using backticks\n  MT(\"inlineCodeUsingBackticks\",\n     \"foo [comment `bar`]\");\n\n  // Block code using single backtick (shouldn't work)\n  MT(\"blockCodeSingleBacktick\",\n     \"[comment `]\",\n     \"[comment foo]\",\n     \"[comment `]\");\n\n  // Unclosed backticks\n  // Instead of simply marking as CODE, it would be nice to have an\n  // incomplete flag for CODE, that is styled slightly different.\n  MT(\"unclosedBackticks\",\n     \"foo [comment `bar]\");\n\n  // Per documentation: \"To include a literal backtick character within a\n  // code span, you can use multiple backticks as the opening and closing\n  // delimiters\"\n  MT(\"doubleBackticks\",\n     \"[comment ``foo ` bar``]\");\n\n  // Tests based on Dingus\n  // http://daringfireball.net/projects/markdown/dingus\n  //\n  // Multiple backticks within an inline code block\n  MT(\"consecutiveBackticks\",\n     \"[comment `foo```bar`]\");\n\n  // Multiple backticks within an inline code block with a second code block\n  MT(\"consecutiveBackticks\",\n     \"[comment `foo```bar`] hello [comment `world`]\");\n\n  // Unclosed with several different groups of backticks\n  MT(\"unclosedBackticks\",\n     \"[comment ``foo ``` bar` hello]\");\n\n  // Closed with several different groups of backticks\n  MT(\"closedBackticks\",\n     \"[comment ``foo ``` bar` hello``] world\");\n\n  // info string cannot contain backtick, thus should result in inline code\n  MT(\"closingFencedMarksOnSameLine\",\n     \"[comment ``` code ```] foo\");\n\n  // atx headers\n  // http://daringfireball.net/projects/markdown/syntax#header\n\n  MT(\"atxH1\",\n     \"[header&header-1 # foo]\");\n\n  MT(\"atxH2\",\n     \"[header&header-2 ## foo]\");\n\n  MT(\"atxH3\",\n     \"[header&header-3 ### foo]\");\n\n  MT(\"atxH4\",\n     \"[header&header-4 #### foo]\");\n\n  MT(\"atxH5\",\n     \"[header&header-5 ##### foo]\");\n\n  MT(\"atxH6\",\n     \"[header&header-6 ###### foo]\");\n\n  // http://spec.commonmark.org/0.19/#example-24\n  MT(\"noAtxH7\",\n     \"####### foo\");\n\n  // http://spec.commonmark.org/0.19/#example-25\n  MT(\"noAtxH1WithoutSpace\",\n     \"#5 bolt\");\n\n  // CommonMark requires a space after # but most parsers don't\n  AtxNoSpaceTest(\"atxNoSpaceAllowed_H1NoSpace\",\n     \"[header&header-1 #foo]\");\n\n  AtxNoSpaceTest(\"atxNoSpaceAllowed_H4NoSpace\",\n     \"[header&header-4 ####foo]\");\n\n  AtxNoSpaceTest(\"atxNoSpaceAllowed_H1Space\",\n     \"[header&header-1 # foo]\");\n\n  // Inline styles should be parsed inside headers\n  MT(\"atxH1inline\",\n     \"[header&header-1 # foo ][header&header-1&em *bar*]\");\n\n  MT(\"atxIndentedTooMuch\",\n     \"[header&header-1 # foo]\",\n     \"    [comment # bar]\");\n\n  // disable atx inside blockquote until we implement proper blockquote inner mode\n  // TODO: fix to be CommonMark-compliant\n  MT(\"atxNestedInsideBlockquote\",\n     \"[quote&quote-1 > # foo]\");\n\n  MT(\"atxAfterBlockquote\",\n     \"[quote&quote-1 > foo]\",\n     \"[header&header-1 # bar]\");\n\n  // Setext headers - H1, H2\n  // Per documentation, \"Any number of underlining =’s or -’s will work.\"\n  // http://daringfireball.net/projects/markdown/syntax#header\n  // Ideally, the text would be marked as `header` as well, but this is\n  // not really feasible at the moment. So, instead, we're testing against\n  // what works today, to avoid any regressions.\n  //\n  // Check if single underlining = works\n  MT(\"setextH1\",\n     \"[header&header-1 foo]\",\n     \"[header&header-1 =]\");\n\n  // Check if 3+ ='s work\n  MT(\"setextH1\",\n     \"[header&header-1 foo]\",\n     \"[header&header-1 ===]\");\n\n  // Check if single underlining - works\n  MT(\"setextH2\",\n     \"[header&header-2 foo]\",\n     \"[header&header-2 -]\");\n\n  // Check if 3+ -'s work\n  MT(\"setextH2\",\n     \"[header&header-2 foo]\",\n     \"[header&header-2 ---]\");\n\n  // http://spec.commonmark.org/0.19/#example-45\n  MT(\"setextH2AllowSpaces\",\n     \"[header&header-2 foo]\",\n     \"   [header&header-2 ----      ]\");\n\n  // http://spec.commonmark.org/0.19/#example-44\n  MT(\"noSetextAfterIndentedCodeBlock\",\n     \"     [comment foo]\",\n     \"[hr ---]\");\n\n  MT(\"setextAfterFencedCode\",\n     \"[comment ```]\",\n     \"[comment foo]\",\n     \"[comment ```]\",\n     \"[header&header-2 bar]\",\n     \"[header&header-2 ---]\");\n\n  MT(\"setextAferATX\",\n     \"[header&header-1 # foo]\",\n     \"[header&header-2 bar]\",\n     \"[header&header-2 ---]\");\n\n  // http://spec.commonmark.org/0.19/#example-51\n  MT(\"noSetextAfterQuote\",\n     \"[quote&quote-1 > foo]\",\n     \"[hr ---]\",\n     \"\",\n     \"[quote&quote-1 > foo]\",\n     \"[quote&quote-1 bar]\",\n     \"[hr ---]\");\n\n  MT(\"noSetextAfterList\",\n     \"[variable-2 - foo]\",\n     \"[hr ---]\");\n\n  MT(\"noSetextAfterList_listContinuation\",\n     \"[variable-2 - foo]\",\n     \"bar\",\n     \"[hr ---]\");\n\n  MT(\"setextAfterList_afterIndentedCode\",\n     \"[variable-2 - foo]\",\n     \"\",\n     \"      [comment bar]\",\n     \"[header&header-2 baz]\",\n     \"[header&header-2 ---]\");\n\n  MT(\"setextAfterList_afterFencedCodeBlocks\",\n     \"[variable-2 - foo]\",\n     \"\",\n     \"      [comment ```]\",\n     \"      [comment bar]\",\n     \"      [comment ```]\",\n     \"[header&header-2 baz]\",\n     \"[header&header-2 ---]\");\n\n  MT(\"setextAfterList_afterHeader\",\n     \"[variable-2 - foo]\",\n     \"  [variable-2&header&header-1 # bar]\",\n     \"[header&header-2 baz]\",\n     \"[header&header-2 ---]\");\n\n  MT(\"setextAfterList_afterHr\",\n     \"[variable-2 - foo]\",\n     \"\",\n     \"  [hr ---]\",\n     \"[header&header-2 bar]\",\n     \"[header&header-2 ---]\");\n\n  MT(\"setext_nestedInlineMarkup\",\n     \"[header&header-1 foo ][em&header&header-1 *bar*]\",\n     \"[header&header-1 =]\");\n\n  MT(\"setext_linkDef\",\n     \"[link [[aaa]]:] [string&url http://google.com 'title']\",\n     \"[hr ---]\");\n\n  // currently, looks max one line ahead, thus won't catch valid CommonMark\n  //  markup\n  MT(\"setext_oneLineLookahead\",\n     \"foo\",\n     \"[header&header-1 bar]\",\n     \"[header&header-1 =]\");\n\n  // ensure we don't regard space after dash as a list\n  MT(\"setext_emptyList\",\n     \"[header&header-2 foo]\",\n     \"[header&header-2 - ]\",\n     \"foo\");\n\n  // Single-line blockquote with trailing space\n  MT(\"blockquoteSpace\",\n     \"[quote&quote-1 > foo]\");\n\n  // Single-line blockquote\n  MT(\"blockquoteNoSpace\",\n     \"[quote&quote-1 >foo]\");\n\n  // No blank line before blockquote\n  MT(\"blockquoteNoBlankLine\",\n     \"foo\",\n     \"[quote&quote-1 > bar]\");\n\n  MT(\"blockquoteNested\",\n     \"[quote&quote-1 > foo]\",\n     \"[quote&quote-1 >][quote&quote-2 > foo]\",\n     \"[quote&quote-1 >][quote&quote-2 >][quote&quote-3 > foo]\");\n\n  // ensure quote-level is inferred correctly even if indented\n  MT(\"blockquoteNestedIndented\",\n     \" [quote&quote-1 > foo]\",\n     \" [quote&quote-1 >][quote&quote-2 > foo]\",\n     \" [quote&quote-1 >][quote&quote-2 >][quote&quote-3 > foo]\");\n\n  // ensure quote-level is inferred correctly even if indented\n  MT(\"blockquoteIndentedTooMuch\",\n     \"foo\",\n     \"    > bar\");\n\n  // Single-line blockquote followed by normal paragraph\n  MT(\"blockquoteThenParagraph\",\n     \"[quote&quote-1 >foo]\",\n     \"\",\n     \"bar\");\n\n  // Multi-line blockquote (lazy mode)\n  MT(\"multiBlockquoteLazy\",\n     \"[quote&quote-1 >foo]\",\n     \"[quote&quote-1 bar]\");\n\n  // Multi-line blockquote followed by normal paragraph (lazy mode)\n  MT(\"multiBlockquoteLazyThenParagraph\",\n     \"[quote&quote-1 >foo]\",\n     \"[quote&quote-1 bar]\",\n     \"\",\n     \"hello\");\n\n  // Multi-line blockquote (non-lazy mode)\n  MT(\"multiBlockquote\",\n     \"[quote&quote-1 >foo]\",\n     \"[quote&quote-1 >bar]\");\n\n  // Multi-line blockquote followed by normal paragraph (non-lazy mode)\n  MT(\"multiBlockquoteThenParagraph\",\n     \"[quote&quote-1 >foo]\",\n     \"[quote&quote-1 >bar]\",\n     \"\",\n     \"hello\");\n\n  // disallow lists inside blockquote for now because it causes problems outside blockquote\n  // TODO: fix to be CommonMark-compliant\n  MT(\"listNestedInBlockquote\",\n     \"[quote&quote-1 > - foo]\");\n\n  // disallow fenced blocks inside blockquote because it causes problems outside blockquote\n  // TODO: fix to be CommonMark-compliant\n  MT(\"fencedBlockNestedInBlockquote\",\n     \"[quote&quote-1 > ```]\",\n     \"[quote&quote-1 > code]\",\n     \"[quote&quote-1 > ```]\",\n     // ensure we still allow inline code\n     \"[quote&quote-1 > ][quote&quote-1&comment `code`]\");\n\n  // Header with leading space after continued blockquote (#3287, negative indentation)\n  MT(\"headerAfterContinuedBlockquote\",\n     \"[quote&quote-1 > foo]\",\n     \"[quote&quote-1 bar]\",\n     \"\",\n     \" [header&header-1 # hello]\");\n\n  // Check list types\n\n  MT(\"listAsterisk\",\n     \"foo\",\n     \"bar\",\n     \"\",\n     \"[variable-2 * foo]\",\n     \"[variable-2 * bar]\");\n\n  MT(\"listPlus\",\n     \"foo\",\n     \"bar\",\n     \"\",\n     \"[variable-2 + foo]\",\n     \"[variable-2 + bar]\");\n\n  MT(\"listDash\",\n     \"foo\",\n     \"bar\",\n     \"\",\n     \"[variable-2 - foo]\",\n     \"[variable-2 - bar]\");\n\n  MT(\"listNumber\",\n     \"foo\",\n     \"bar\",\n     \"\",\n     \"[variable-2 1. foo]\",\n     \"[variable-2 2. bar]\");\n\n  MT(\"listFromParagraph\",\n     \"foo\",\n     \"[variable-2 1. bar]\",\n     \"[variable-2 2. hello]\");\n\n  // List after hr\n  MT(\"listAfterHr\",\n     \"[hr ---]\",\n     \"[variable-2 - bar]\");\n\n  // List after header\n  MT(\"listAfterHeader\",\n     \"[header&header-1 # foo]\",\n     \"[variable-2 - bar]\");\n\n  // hr after list\n  MT(\"hrAfterList\",\n     \"[variable-2 - foo]\",\n     \"[hr -----]\");\n\n  MT(\"hrAfterFencedCode\",\n     \"[comment ```]\",\n     \"[comment code]\",\n     \"[comment ```]\",\n     \"[hr ---]\");\n\n  // allow hr inside lists\n  // (require prev line to be empty or hr, TODO: non-CommonMark-compliant)\n  MT(\"hrInsideList\",\n     \"[variable-2 - foo]\",\n     \"\",\n     \"  [hr ---]\",\n     \"     [hr ---]\",\n     \"\",\n     \"      [comment ---]\");\n\n  MT(\"consecutiveHr\",\n     \"[hr ---]\",\n     \"[hr ---]\",\n     \"[hr ---]\");\n\n  // Formatting in lists (*)\n  MT(\"listAsteriskFormatting\",\n     \"[variable-2 * ][variable-2&em *foo*][variable-2  bar]\",\n     \"[variable-2 * ][variable-2&strong **foo**][variable-2  bar]\",\n     \"[variable-2 * ][variable-2&em&strong ***foo***][variable-2  bar]\",\n     \"[variable-2 * ][variable-2&comment `foo`][variable-2  bar]\");\n\n  // Formatting in lists (+)\n  MT(\"listPlusFormatting\",\n     \"[variable-2 + ][variable-2&em *foo*][variable-2  bar]\",\n     \"[variable-2 + ][variable-2&strong **foo**][variable-2  bar]\",\n     \"[variable-2 + ][variable-2&em&strong ***foo***][variable-2  bar]\",\n     \"[variable-2 + ][variable-2&comment `foo`][variable-2  bar]\");\n\n  // Formatting in lists (-)\n  MT(\"listDashFormatting\",\n     \"[variable-2 - ][variable-2&em *foo*][variable-2  bar]\",\n     \"[variable-2 - ][variable-2&strong **foo**][variable-2  bar]\",\n     \"[variable-2 - ][variable-2&em&strong ***foo***][variable-2  bar]\",\n     \"[variable-2 - ][variable-2&comment `foo`][variable-2  bar]\");\n\n  // Formatting in lists (1.)\n  MT(\"listNumberFormatting\",\n     \"[variable-2 1. ][variable-2&em *foo*][variable-2  bar]\",\n     \"[variable-2 2. ][variable-2&strong **foo**][variable-2  bar]\",\n     \"[variable-2 3. ][variable-2&em&strong ***foo***][variable-2  bar]\",\n     \"[variable-2 4. ][variable-2&comment `foo`][variable-2  bar]\");\n\n  // Paragraph lists\n  MT(\"listParagraph\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"[variable-2 * bar]\");\n\n  // Multi-paragraph lists\n  //\n  // 4 spaces\n  MT(\"listMultiParagraph\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"[variable-2 * bar]\",\n     \"\",\n     \"    [variable-2 hello]\");\n\n  // 4 spaces, extra blank lines (should still be list, per Dingus)\n  MT(\"listMultiParagraphExtra\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"[variable-2 * bar]\",\n     \"\",\n     \"\",\n     \"    [variable-2 hello]\");\n\n  // 4 spaces, plus 1 space (should still be list, per Dingus)\n  MT(\"listMultiParagraphExtraSpace\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"[variable-2 * bar]\",\n     \"\",\n     \"     [variable-2 hello]\",\n     \"\",\n     \"    [variable-2 world]\");\n\n  // 1 tab\n  MT(\"listTab\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"[variable-2 * bar]\",\n     \"\",\n     \"\\t[variable-2 hello]\");\n\n  // No indent\n  MT(\"listNoIndent\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"[variable-2 * bar]\",\n     \"\",\n     \"hello\");\n\n  MT(\"listCommonMarkIndentationCode\",\n     \"[variable-2 * Code blocks also affect]\",\n     \"  [variable-3 * The next level starts where the contents start.]\",\n     \"   [variable-3 *    Anything less than that will keep the item on the same level.]\",\n     \"       [variable-3 * Each list item can indent the first level further and further.]\",\n     \"  [variable-3 * For the most part, this makes sense while writing a list.]\",\n     \"    [keyword * This means two items with same indentation can be different levels.]\",\n     \"     [keyword *  Each level has an indent requirement that can change between items.]\",\n     \"       [keyword * A list item that meets this will be part of the next level.]\",\n     \"   [variable-3 * Otherwise, it will be part of the level where it does meet this.]\",\n     \" [variable-2 * World]\");\n\n  // should handle nested and un-nested lists\n  MT(\"listCommonMark_MixedIndents\",\n     \"[variable-2 * list1]\",\n     \"    [variable-2 list1]\",\n     \"  [variable-2&header&header-1 # heading still part of list1]\",\n     \"  [variable-2 text after heading still part of list1]\",\n     \"\",\n     \"      [comment indented codeblock]\",\n     \"  [variable-2 list1 after code block]\",\n     \"  [variable-3 * list2]\",\n     // amount of spaces on empty lines between lists doesn't matter\n     \"              \",\n     // extra empty lines irrelevant\n     \"\",\n     \"\",\n     \"    [variable-3 indented text part of list2]\",\n     \"    [keyword * list3]\",\n     \"\",\n     \"    [variable-3 text at level of list2]\",\n     \"\",\n     \"  [variable-2 de-indented text part of list1 again]\",\n     \"\",\n     \"  [variable-2&comment ```]\",\n     \"  [comment code]\",\n     \"  [variable-2&comment ```]\",\n     \"\",\n     \"  [variable-2 text after fenced code]\");\n\n  // should correctly parse numbered list content indentation\n  MT(\"listCommonMark_NumeberedListIndent\",\n     \"[variable-2 1000. list with base indent of 6]\",\n     \"\",\n     \"      [variable-2 text must be indented 6 spaces at minimum]\",\n     \"\",\n     \"         [variable-2 9-spaces indented text still part of list]\",\n     \"\",\n     \"          [comment indented codeblock starts at 10 spaces]\",\n     \"\",\n     \"     [comment text indented by 5 spaces no longer belong to list]\");\n\n  // should consider tab as 4 spaces\n  MT(\"listCommonMark_TabIndented\",\n     \"[variable-2 * list]\",\n     \"\\t[variable-3 * list2]\",\n     \"\",\n     \"\\t\\t[variable-3 part of list2]\");\n\n  MT(\"listAfterBlockquote\",\n     \"[quote&quote-1 > foo]\",\n     \"[variable-2 - bar]\");\n\n  // shouldn't create sublist if it's indented more than allowed\n  MT(\"nestedListIndentedTooMuch\",\n     \"[variable-2 - foo]\",\n     \"          [variable-2 - bar]\");\n\n  MT(\"listIndentedTooMuchAfterParagraph\",\n     \"foo\",\n     \"    - bar\");\n\n  // Blockquote\n  MT(\"blockquote\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"[variable-2 * bar]\",\n     \"\",\n     \"    [variable-2&quote&quote-1 > hello]\");\n\n  // Code block\n  MT(\"blockquoteCode\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"[variable-2 * bar]\",\n     \"\",\n     \"        [comment > hello]\",\n     \"\",\n     \"    [variable-2 world]\");\n\n  // Code block followed by text\n  MT(\"blockquoteCodeText\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"    [variable-2 bar]\",\n     \"\",\n     \"        [comment hello]\",\n     \"\",\n     \"    [variable-2 world]\");\n\n  // Nested list\n\n  MT(\"listAsteriskNested\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"    [variable-3 * bar]\");\n\n  MT(\"listPlusNested\",\n     \"[variable-2 + foo]\",\n     \"\",\n     \"    [variable-3 + bar]\");\n\n  MT(\"listDashNested\",\n     \"[variable-2 - foo]\",\n     \"\",\n     \"    [variable-3 - bar]\");\n\n  MT(\"listNumberNested\",\n     \"[variable-2 1. foo]\",\n     \"\",\n     \"    [variable-3 2. bar]\");\n\n  MT(\"listMixed\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"    [variable-3 + bar]\",\n     \"\",\n     \"        [keyword - hello]\",\n     \"\",\n     \"            [variable-2 1. world]\");\n\n  MT(\"listBlockquote\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"    [variable-3 + bar]\",\n     \"\",\n     \"        [quote&quote-1&variable-3 > hello]\");\n\n  MT(\"listCode\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"    [variable-3 + bar]\",\n     \"\",\n     \"            [comment hello]\");\n\n  // Code with internal indentation\n  MT(\"listCodeIndentation\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"        [comment bar]\",\n     \"            [comment hello]\",\n     \"                [comment world]\",\n     \"        [comment foo]\",\n     \"    [variable-2 bar]\");\n\n  // List nesting edge cases\n  MT(\"listNested\",\n    \"[variable-2 * foo]\",\n    \"\",\n    \"    [variable-3 * bar]\",\n    \"\",\n    \"       [variable-3 hello]\"\n  );\n  MT(\"listNested\",\n    \"[variable-2 * foo]\",\n    \"\",\n    \"    [variable-3 * bar]\",\n    \"\",\n    \"      [keyword * foo]\"\n  );\n\n  // Code followed by text\n  MT(\"listCodeText\",\n     \"[variable-2 * foo]\",\n     \"\",\n     \"        [comment bar]\",\n     \"\",\n     \"hello\");\n\n  // Following tests directly from official Markdown documentation\n  // http://daringfireball.net/projects/markdown/syntax#hr\n\n  MT(\"hrSpace\",\n     \"[hr * * *]\");\n\n  MT(\"hr\",\n     \"[hr ***]\");\n\n  MT(\"hrLong\",\n     \"[hr *****]\");\n\n  MT(\"hrSpaceDash\",\n     \"[hr - - -]\");\n\n  MT(\"hrDashLong\",\n     \"[hr ---------------------------------------]\");\n\n  //Images\n  MT(\"Images\",\n     \"[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://link.to/image.jpg)]\")\n\n  //Images with highlight alt text\n  MT(\"imageEm\",\n     \"[image&image-marker !][image&image-alt-text&link [[][image-alt-text&em&image&link *alt text*][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)]\");\n\n  MT(\"imageStrong\",\n     \"[image&image-marker !][image&image-alt-text&link [[][image-alt-text&strong&image&link **alt text**][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)]\");\n\n  MT(\"imageEmStrong\",\n     \"[image&image-marker !][image&image-alt-text&link [[][image&image-alt-text&em&strong&link ***alt text***][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)]\");\n\n  // Inline link with title\n  MT(\"linkTitle\",\n     \"[link [[foo]]][string&url (http://example.com/ \\\"bar\\\")] hello\");\n\n  // Inline link without title\n  MT(\"linkNoTitle\",\n     \"[link [[foo]]][string&url (http://example.com/)] bar\");\n\n  // Inline link with image\n  MT(\"linkImage\",\n     \"[link [[][link&image&image-marker !][link&image&image-alt-text&link [[alt text]]][string&url (http://link.to/image.jpg)][link ]]][string&url (http://example.com/)] bar\");\n\n  // Inline link with Em\n  MT(\"linkEm\",\n     \"[link [[][link&em *foo*][link ]]][string&url (http://example.com/)] bar\");\n\n  // Inline link with Strong\n  MT(\"linkStrong\",\n     \"[link [[][link&strong **foo**][link ]]][string&url (http://example.com/)] bar\");\n\n  // Inline link with EmStrong\n  MT(\"linkEmStrong\",\n     \"[link [[][link&em&strong ***foo***][link ]]][string&url (http://example.com/)] bar\");\n\n  MT(\"multilineLink\",\n     \"[link [[foo]\",\n     \"[link bar]]][string&url (https://foo#_a)]\",\n     \"should not be italics\")\n\n  // Image with title\n  MT(\"imageTitle\",\n     \"[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://example.com/ \\\"bar\\\")] hello\");\n\n  // Image without title\n  MT(\"imageNoTitle\",\n     \"[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://example.com/)] bar\");\n\n  // Image with asterisks\n  MT(\"imageAsterisks\",\n     \"[image&image-marker !][image&image-alt-text&link [[ ][image&image-alt-text&em&link *alt text*][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)] bar\");\n\n  // Not a link. Should be normal text due to square brackets being used\n  // regularly in text, especially in quoted material, and no space is allowed\n  // between square brackets and parentheses (per Dingus).\n  MT(\"notALink\",\n     \"[link [[foo]]] (bar)\");\n\n  // Reference-style links\n  MT(\"linkReference\",\n     \"[link [[foo]]][string&url [[bar]]] hello\");\n\n  // Reference-style links with Em\n  MT(\"linkReferenceEm\",\n     \"[link [[][link&em *foo*][link ]]][string&url [[bar]]] hello\");\n\n  // Reference-style links with Strong\n  MT(\"linkReferenceStrong\",\n     \"[link [[][link&strong **foo**][link ]]][string&url [[bar]]] hello\");\n\n  // Reference-style links with EmStrong\n  MT(\"linkReferenceEmStrong\",\n     \"[link [[][link&em&strong ***foo***][link ]]][string&url [[bar]]] hello\");\n\n  // Reference-style links with optional space separator (per documentation)\n  // \"You can optionally use a space to separate the sets of brackets\"\n  MT(\"linkReferenceSpace\",\n     \"[link [[foo]]] [string&url [[bar]]] hello\");\n\n  // Should only allow a single space (\"...use *a* space...\")\n  MT(\"linkReferenceDoubleSpace\",\n     \"[link [[foo]]]  [link [[bar]]] hello\");\n\n  // Reference-style links with implicit link name\n  MT(\"linkImplicit\",\n     \"[link [[foo]]][string&url [[]]] hello\");\n\n  // @todo It would be nice if, at some point, the document was actually\n  // checked to see if the referenced link exists\n\n  // Link label, for reference-style links (taken from documentation)\n\n  MT(\"labelNoTitle\",\n     \"[link [[foo]]:] [string&url http://example.com/]\");\n\n  MT(\"labelIndented\",\n     \"   [link [[foo]]:] [string&url http://example.com/]\");\n\n  MT(\"labelSpaceTitle\",\n     \"[link [[foo bar]]:] [string&url http://example.com/ \\\"hello\\\"]\");\n\n  MT(\"labelDoubleTitle\",\n     \"[link [[foo bar]]:] [string&url http://example.com/ \\\"hello\\\"] \\\"world\\\"\");\n\n  MT(\"labelTitleDoubleQuotes\",\n     \"[link [[foo]]:] [string&url http://example.com/  \\\"bar\\\"]\");\n\n  MT(\"labelTitleSingleQuotes\",\n     \"[link [[foo]]:] [string&url http://example.com/  'bar']\");\n\n  MT(\"labelTitleParentheses\",\n     \"[link [[foo]]:] [string&url http://example.com/  (bar)]\");\n\n  MT(\"labelTitleInvalid\",\n     \"[link [[foo]]:] [string&url http://example.com/] bar\");\n\n  MT(\"labelLinkAngleBrackets\",\n     \"[link [[foo]]:] [string&url <http://example.com/>  \\\"bar\\\"]\");\n\n  MT(\"labelTitleNextDoubleQuotes\",\n     \"[link [[foo]]:] [string&url http://example.com/]\",\n     \"[string \\\"bar\\\"] hello\");\n\n  MT(\"labelTitleNextSingleQuotes\",\n     \"[link [[foo]]:] [string&url http://example.com/]\",\n     \"[string 'bar'] hello\");\n\n  MT(\"labelTitleNextParentheses\",\n     \"[link [[foo]]:] [string&url http://example.com/]\",\n     \"[string (bar)] hello\");\n\n  MT(\"labelTitleNextMixed\",\n     \"[link [[foo]]:] [string&url http://example.com/]\",\n     \"(bar\\\" hello\");\n\n  MT(\"labelEscape\",\n     \"[link [[foo \\\\]] ]]:] [string&url http://example.com/]\");\n\n  MT(\"labelEscapeColon\",\n     \"[link [[foo \\\\]]: bar]]:] [string&url http://example.com/]\");\n\n  MT(\"labelEscapeEnd\",\n     \"\\\\[[foo\\\\]]: http://example.com/\");\n\n  MT(\"linkWeb\",\n     \"[link <http://example.com/>] foo\");\n\n  MT(\"linkWebDouble\",\n     \"[link <http://example.com/>] foo [link <http://example.com/>]\");\n\n  MT(\"linkEmail\",\n     \"[link <user@example.com>] foo\");\n\n  MT(\"linkEmailDouble\",\n     \"[link <user@example.com>] foo [link <user@example.com>]\");\n\n  MT(\"emAsterisk\",\n     \"[em *foo*] bar\");\n\n  MT(\"emUnderscore\",\n     \"[em _foo_] bar\");\n\n  MT(\"emInWordAsterisk\",\n     \"foo[em *bar*]hello\");\n\n  MT(\"emInWordUnderscore\",\n     \"foo_bar_hello\");\n\n  // Per documentation: \"...surround an * or _ with spaces, it’ll be\n  // treated as a literal asterisk or underscore.\"\n\n  MT(\"emEscapedBySpaceIn\",\n     \"foo [em _bar _ hello_] world\");\n\n  MT(\"emEscapedBySpaceOut\",\n     \"foo _ bar [em _hello_] world\");\n\n  MT(\"emEscapedByNewline\",\n     \"foo\",\n     \"_ bar [em _hello_] world\");\n\n  // Unclosed emphasis characters\n  // Instead of simply marking as EM / STRONG, it would be nice to have an\n  // incomplete flag for EM and STRONG, that is styled slightly different.\n  MT(\"emIncompleteAsterisk\",\n     \"foo [em *bar]\");\n\n  MT(\"emIncompleteUnderscore\",\n     \"foo [em _bar]\");\n\n  MT(\"strongAsterisk\",\n     \"[strong **foo**] bar\");\n\n  MT(\"strongUnderscore\",\n     \"[strong __foo__] bar\");\n\n  MT(\"emStrongAsterisk\",\n     \"[em *foo][em&strong **bar*][strong hello**] world\");\n\n  MT(\"emStrongUnderscore\",\n     \"[em _foo ][em&strong __bar_][strong  hello__] world\");\n\n  // \"...same character must be used to open and close an emphasis span.\"\"\n  MT(\"emStrongMixed\",\n     \"[em _foo][em&strong **bar*hello__ world]\");\n\n  MT(\"emStrongMixed\",\n     \"[em *foo ][em&strong __bar_hello** world]\");\n\n  MT(\"linkWithNestedParens\",\n     \"[link [[foo]]][string&url (bar(baz))]\")\n\n  // These characters should be escaped:\n  // \\   backslash\n  // `   backtick\n  // *   asterisk\n  // _   underscore\n  // {}  curly braces\n  // []  square brackets\n  // ()  parentheses\n  // #   hash mark\n  // +   plus sign\n  // -   minus sign (hyphen)\n  // .   dot\n  // !   exclamation mark\n\n  MT(\"escapeBacktick\",\n     \"foo \\\\`bar\\\\`\");\n\n  MT(\"doubleEscapeBacktick\",\n     \"foo \\\\\\\\[comment `bar\\\\\\\\`]\");\n\n  MT(\"escapeAsterisk\",\n     \"foo \\\\*bar\\\\*\");\n\n  MT(\"doubleEscapeAsterisk\",\n     \"foo \\\\\\\\[em *bar\\\\\\\\*]\");\n\n  MT(\"escapeUnderscore\",\n     \"foo \\\\_bar\\\\_\");\n\n  MT(\"doubleEscapeUnderscore\",\n     \"foo \\\\\\\\[em _bar\\\\\\\\_]\");\n\n  MT(\"escapeHash\",\n     \"\\\\# foo\");\n\n  MT(\"doubleEscapeHash\",\n     \"\\\\\\\\# foo\");\n\n  MT(\"escapeNewline\",\n     \"\\\\\",\n     \"[em *foo*]\");\n\n  // Class override tests\n  TokenTypeOverrideTest(\"overrideHeader1\",\n    \"[override-header&override-header-1 # Foo]\");\n\n  TokenTypeOverrideTest(\"overrideHeader2\",\n    \"[override-header&override-header-2 ## Foo]\");\n\n  TokenTypeOverrideTest(\"overrideHeader3\",\n    \"[override-header&override-header-3 ### Foo]\");\n\n  TokenTypeOverrideTest(\"overrideHeader4\",\n    \"[override-header&override-header-4 #### Foo]\");\n\n  TokenTypeOverrideTest(\"overrideHeader5\",\n    \"[override-header&override-header-5 ##### Foo]\");\n\n  TokenTypeOverrideTest(\"overrideHeader6\",\n    \"[override-header&override-header-6 ###### Foo]\");\n\n  TokenTypeOverrideTest(\"overrideCode\",\n    \"[override-code `foo`]\");\n\n  TokenTypeOverrideTest(\"overrideCodeBlock\",\n    \"[override-code ```]\",\n    \"[override-code foo]\",\n    \"[override-code ```]\");\n\n  TokenTypeOverrideTest(\"overrideQuote\",\n    \"[override-quote&override-quote-1 > foo]\",\n    \"[override-quote&override-quote-1 > bar]\");\n\n  TokenTypeOverrideTest(\"overrideQuoteNested\",\n    \"[override-quote&override-quote-1 > foo]\",\n    \"[override-quote&override-quote-1 >][override-quote&override-quote-2 > bar]\",\n    \"[override-quote&override-quote-1 >][override-quote&override-quote-2 >][override-quote&override-quote-3 > baz]\");\n\n  TokenTypeOverrideTest(\"overrideLists\",\n    \"[override-list1 - foo]\",\n    \"\",\n    \"    [override-list2 + bar]\",\n    \"\",\n    \"        [override-list3 * baz]\",\n    \"\",\n    \"            [override-list1 1. qux]\",\n    \"\",\n    \"                [override-list2 - quux]\");\n\n  TokenTypeOverrideTest(\"overrideHr\",\n    \"[override-hr * * *]\");\n\n  TokenTypeOverrideTest(\"overrideImage\",\n    \"[override-image&override-image-marker !][override-image&override-image-alt-text&link [[alt text]]][override-link-href&url (http://link.to/image.jpg)]\");\n\n  TokenTypeOverrideTest(\"overrideLinkText\",\n    \"[override-link-text [[foo]]][override-link-href&url (http://example.com)]\");\n\n  TokenTypeOverrideTest(\"overrideLinkEmailAndInline\",\n    \"[override-link-email <][override-link-inline foo@example.com>]\");\n\n  TokenTypeOverrideTest(\"overrideEm\",\n    \"[override-em *foo*]\");\n\n  TokenTypeOverrideTest(\"overrideStrong\",\n    \"[override-strong **foo**]\");\n\n  TokenTypeOverrideTest(\"overrideStrikethrough\",\n    \"[override-strikethrough ~~foo~~]\");\n\n  TokenTypeOverrideTest(\"overrideEmoji\",\n    \"[override-emoji :foo:]\");\n\n  FormatTokenTypeOverrideTest(\"overrideFormatting\",\n    \"[override-formatting-escape \\\\*]\");\n\n  // Tests to make sure GFM-specific things aren't getting through\n\n  MT(\"taskList\",\n     \"[variable-2 * ][link&variable-2 [[ ]]][variable-2 bar]\");\n\n  MT(\"fencedCodeBlocks\",\n     \"[comment ```]\",\n     \"[comment foo]\",\n     \"\",\n     \"[comment bar]\",\n     \"[comment ```]\",\n     \"baz\");\n\n  MT(\"fencedCodeBlocks_invalidClosingFence_trailingText\",\n     \"[comment ```]\",\n     \"[comment foo]\",\n     \"[comment ``` must not have trailing text]\",\n     \"[comment baz]\");\n\n  MT(\"fencedCodeBlocks_invalidClosingFence_trailingTabs\",\n     \"[comment ```]\",\n     \"[comment foo]\",\n     \"[comment ```\\t]\",\n     \"[comment baz]\");\n\n  MT(\"fencedCodeBlocks_validClosingFence\",\n     \"[comment ```]\",\n     \"[comment foo]\",\n     // may have trailing spaces\n     \"[comment ```     ]\",\n     \"baz\");\n\n  MT(\"fencedCodeBlocksInList_closingFenceIndented\",\n     \"[variable-2 - list]\",\n     \"    [variable-2&comment ```]\",\n     \"    [comment foo]\",\n     \"     [variable-2&comment ```]\",\n     \"    [variable-2 baz]\");\n\n  MT(\"fencedCodeBlocksInList_closingFenceIndentedTooMuch\",\n     \"[variable-2 - list]\",\n     \"    [variable-2&comment ```]\",\n     \"    [comment foo]\",\n     \"      [comment ```]\",\n     \"    [comment baz]\");\n\n  MT(\"fencedCodeBlockModeSwitching\",\n     \"[comment ```javascript]\",\n     \"[variable foo]\",\n     \"\",\n     \"[comment ```]\",\n     \"bar\");\n\n  MT_noFencedHighlight(\"fencedCodeBlock_noHighlight\",\n     \"[comment ```javascript]\",\n     \"[comment foo]\",\n     \"[comment ```]\");\n\n  MT(\"fencedCodeBlockModeSwitchingObjc\",\n     \"[comment ```objective-c]\",\n     \"[keyword @property] [variable NSString] [operator *] [variable foo];\",\n     \"[comment ```]\",\n     \"bar\");\n\n  MT(\"fencedCodeBlocksMultipleChars\",\n     \"[comment `````]\",\n     \"[comment foo]\",\n     \"[comment ```]\",\n     \"[comment foo]\",\n     \"[comment `````]\",\n     \"bar\");\n\n  MT(\"fencedCodeBlocksTildes\",\n     \"[comment ~~~]\",\n     \"[comment foo]\",\n     \"[comment ~~~]\",\n     \"bar\");\n\n  MT(\"fencedCodeBlocksTildesMultipleChars\",\n     \"[comment ~~~~~]\",\n     \"[comment ~~~]\",\n     \"[comment foo]\",\n     \"[comment ~~~~~]\",\n     \"bar\");\n\n  MT(\"fencedCodeBlocksMultipleChars\",\n     \"[comment `````]\",\n     \"[comment foo]\",\n     \"[comment ```]\",\n     \"[comment foo]\",\n     \"[comment `````]\",\n     \"bar\");\n\n  MT(\"fencedCodeBlocksMixed\",\n     \"[comment ~~~]\",\n     \"[comment ```]\",\n     \"[comment foo]\",\n     \"[comment ~~~]\",\n     \"bar\");\n\n  MT(\"fencedCodeBlocksAfterBlockquote\",\n     \"[quote&quote-1 > foo]\",\n     \"[comment ```]\",\n     \"[comment bar]\",\n     \"[comment ```]\");\n\n  // fencedCode indented too much should act as simple indentedCode\n  //  (hence has no highlight formatting)\n  FT(\"tooMuchIndentedFencedCode\",\n     \"    [comment ```]\",\n     \"    [comment code]\",\n     \"    [comment ```]\");\n\n  MT(\"autoTerminateFencedCodeWhenLeavingList\",\n     \"[variable-2 - list1]\",\n     \"  [variable-3 - list2]\",\n     \"    [variable-3&comment ```]\",\n     \"    [comment code]\",\n     \"  [variable-3 - list2]\",\n     \"  [variable-2&comment ```]\",\n     \"  [comment code]\",\n     \"[quote&quote-1 > foo]\");\n\n  // Tests that require XML mode\n\n  MT(\"xmlMode\",\n     \"[tag&bracket <][tag div][tag&bracket >]\",\n     \"  *foo*\",\n     \"  [tag&bracket <][tag http://github.com][tag&bracket />]\",\n     \"[tag&bracket </][tag div][tag&bracket >]\",\n     \"[link <http://github.com/>]\");\n\n  MT(\"xmlModeWithMarkdownInside\",\n     \"[tag&bracket <][tag div] [attribute markdown]=[string 1][tag&bracket >]\",\n     \"[em *foo*]\",\n     \"[link <http://github.com/>]\",\n     \"[tag </div>]\",\n     \"[link <http://github.com/>]\",\n     \"[tag&bracket <][tag div][tag&bracket >]\",\n     \"[tag&bracket </][tag div][tag&bracket >]\");\n\n  MT(\"xmlModeLineBreakInTags\",\n     \"[tag&bracket <][tag div] [attribute id]=[string \\\"1\\\"]\",\n     \"     [attribute class]=[string \\\"sth\\\"][tag&bracket >]xxx\",\n     \"[tag&bracket </][tag div][tag&bracket >]\");\n\n  MT(\"xmlModeCommentWithBlankLine\",\n     \"[comment <!-- Hello]\",\n     \"\",\n     \"[comment World -->]\");\n\n  MT(\"xmlModeCDATA\",\n     \"[atom <![CDATA[ Hello]\",\n     \"\",\n     \"[atom FooBar]\",\n     \"[atom Test ]]]]>]\");\n\n  MT(\"xmlModePreprocessor\",\n     \"[meta <?php] [meta echo '1234'; ?>]\");\n\n  MT_noXml(\"xmlHighlightDisabled\",\n     \"<div>foo</div>\");\n\n  // Tests Emojis\n\n  ET(\"emojiDefault\",\n    \"[builtin :foobar:]\");\n\n  ET(\"emojiTable\",\n    \" :--:\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mathematica/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Mathematica mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=stylesheet href=../../lib/codemirror.css>\n<script src=../../lib/codemirror.js></script>\n<script src=../../addon/edit/matchbrackets.js></script>\n<script src=mathematica.js></script>\n<style type=text/css>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Mathematica</a>\n  </ul>\n</div>\n\n<article>\n<h2>Mathematica mode</h2>\n\n\n<textarea id=\"mathematicaCode\">\n(* example Mathematica code *)\n(* Dualisiert wird anhand einer Polarität an einer\n   Quadrik $x^t Q x = 0$ mit regulärer Matrix $Q$ (also\n   mit $det(Q) \\neq 0$), z.B. die Identitätsmatrix.\n   $p$ ist eine Liste von Polynomen - ein Ideal. *)\ndualize::\"singular\" = \"Q must be regular: found Det[Q]==0.\";\ndualize[ Q_, p_ ] := Block[\n    { m, n, xv, lv, uv, vars, polys, dual },\n    If[Det[Q] == 0,\n      Message[dualize::\"singular\"],\n      m = Length[p];\n      n = Length[Q] - 1;\n      xv = Table[Subscript[x, i], {i, 0, n}];\n      lv = Table[Subscript[l, i], {i, 1, m}];\n      uv = Table[Subscript[u, i], {i, 0, n}];\n      (* Konstruiere Ideal polys. *)\n      If[m == 0,\n        polys = Q.uv,\n        polys = Join[p, Q.uv - Transpose[Outer[D, p, xv]].lv]\n        ];\n      (* Eliminiere die ersten n + 1 + m Variablen xv und lv\n         aus dem Ideal polys. *)\n      vars = Join[xv, lv];\n      dual = GroebnerBasis[polys, uv, vars];\n      (* Ersetze u mit x im Ergebnis. *)\n      ReplaceAll[dual, Rule[u, x]]\n      ]\n    ]\n</textarea>\n\n<script>\n  var mathematicaEditor = CodeMirror.fromTextArea(document.getElementById('mathematicaCode'), {\n    mode: 'text/x-mathematica',\n    lineNumbers: true,\n    matchBrackets: true\n  });\n</script>\n\n<p><strong>MIME types defined:</strong> <code>text/x-mathematica</code> (Mathematica).</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mathematica/mathematica.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Mathematica mode copyright (c) 2015 by Calin Barbat\n// Based on code by Patrick Scheibe (halirutan)\n// See: https://github.com/halirutan/Mathematica-Source-Highlighting/tree/master/src/lang-mma.js\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode('mathematica', function(_config, _parserConfig) {\n\n  // used pattern building blocks\n  var Identifier = '[a-zA-Z\\\\$][a-zA-Z0-9\\\\$]*';\n  var pBase      = \"(?:\\\\d+)\";\n  var pFloat     = \"(?:\\\\.\\\\d+|\\\\d+\\\\.\\\\d*|\\\\d+)\";\n  var pFloatBase = \"(?:\\\\.\\\\w+|\\\\w+\\\\.\\\\w*|\\\\w+)\";\n  var pPrecision = \"(?:`(?:`?\"+pFloat+\")?)\";\n\n  // regular expressions\n  var reBaseForm        = new RegExp('(?:'+pBase+'(?:\\\\^\\\\^'+pFloatBase+pPrecision+'?(?:\\\\*\\\\^[+-]?\\\\d+)?))');\n  var reFloatForm       = new RegExp('(?:' + pFloat + pPrecision + '?(?:\\\\*\\\\^[+-]?\\\\d+)?)');\n  var reIdInContext     = new RegExp('(?:`?)(?:' + Identifier + ')(?:`(?:' + Identifier + '))*(?:`?)');\n\n  function tokenBase(stream, state) {\n    var ch;\n\n    // get next character\n    ch = stream.next();\n\n    // string\n    if (ch === '\"') {\n      state.tokenize = tokenString;\n      return state.tokenize(stream, state);\n    }\n\n    // comment\n    if (ch === '(') {\n      if (stream.eat('*')) {\n        state.commentLevel++;\n        state.tokenize = tokenComment;\n        return state.tokenize(stream, state);\n      }\n    }\n\n    // go back one character\n    stream.backUp(1);\n\n    // look for numbers\n    // Numbers in a baseform\n    if (stream.match(reBaseForm, true, false)) {\n      return 'number';\n    }\n\n    // Mathematica numbers. Floats (1.2, .2, 1.) can have optionally a precision (`float) or an accuracy definition\n    // (``float). Note: while 1.2` is possible 1.2`` is not. At the end an exponent (float*^+12) can follow.\n    if (stream.match(reFloatForm, true, false)) {\n      return 'number';\n    }\n\n    /* In[23] and Out[34] */\n    if (stream.match(/(?:In|Out)\\[[0-9]*\\]/, true, false)) {\n      return 'atom';\n    }\n\n    // usage\n    if (stream.match(/([a-zA-Z\\$][a-zA-Z0-9\\$]*(?:`[a-zA-Z0-9\\$]+)*::usage)/, true, false)) {\n      return 'meta';\n    }\n\n    // message\n    if (stream.match(/([a-zA-Z\\$][a-zA-Z0-9\\$]*(?:`[a-zA-Z0-9\\$]+)*::[a-zA-Z\\$][a-zA-Z0-9\\$]*):?/, true, false)) {\n      return 'string-2';\n    }\n\n    // this makes a look-ahead match for something like variable:{_Integer}\n    // the match is then forwarded to the mma-patterns tokenizer.\n    if (stream.match(/([a-zA-Z\\$][a-zA-Z0-9\\$]*\\s*:)(?:(?:[a-zA-Z\\$][a-zA-Z0-9\\$]*)|(?:[^:=>~@\\^\\&\\*\\)\\[\\]'\\?,\\|])).*/, true, false)) {\n      return 'variable-2';\n    }\n\n    // catch variables which are used together with Blank (_), BlankSequence (__) or BlankNullSequence (___)\n    // Cannot start with a number, but can have numbers at any other position. Examples\n    // blub__Integer, a1_, b34_Integer32\n    if (stream.match(/[a-zA-Z\\$][a-zA-Z0-9\\$]*_+[a-zA-Z\\$][a-zA-Z0-9\\$]*/, true, false)) {\n      return 'variable-2';\n    }\n    if (stream.match(/[a-zA-Z\\$][a-zA-Z0-9\\$]*_+/, true, false)) {\n      return 'variable-2';\n    }\n    if (stream.match(/_+[a-zA-Z\\$][a-zA-Z0-9\\$]*/, true, false)) {\n      return 'variable-2';\n    }\n\n    // Named characters in Mathematica, like \\[Gamma].\n    if (stream.match(/\\\\\\[[a-zA-Z\\$][a-zA-Z0-9\\$]*\\]/, true, false)) {\n      return 'variable-3';\n    }\n\n    // Match all braces separately\n    if (stream.match(/(?:\\[|\\]|{|}|\\(|\\))/, true, false)) {\n      return 'bracket';\n    }\n\n    // Catch Slots (#, ##, #3, ##9 and the V10 named slots #name). I have never seen someone using more than one digit after #, so we match\n    // only one.\n    if (stream.match(/(?:#[a-zA-Z\\$][a-zA-Z0-9\\$]*|#+[0-9]?)/, true, false)) {\n      return 'variable-2';\n    }\n\n    // Literals like variables, keywords, functions\n    if (stream.match(reIdInContext, true, false)) {\n      return 'keyword';\n    }\n\n    // operators. Note that operators like @@ or /; are matched separately for each symbol.\n    if (stream.match(/(?:\\\\|\\+|\\-|\\*|\\/|,|;|\\.|:|@|~|=|>|<|&|\\||_|`|'|\\^|\\?|!|%)/, true, false)) {\n      return 'operator';\n    }\n\n    // everything else is an error\n    stream.next(); // advance the stream.\n    return 'error';\n  }\n\n  function tokenString(stream, state) {\n    var next, end = false, escaped = false;\n    while ((next = stream.next()) != null) {\n      if (next === '\"' && !escaped) {\n        end = true;\n        break;\n      }\n      escaped = !escaped && next === '\\\\';\n    }\n    if (end && !escaped) {\n      state.tokenize = tokenBase;\n    }\n    return 'string';\n  };\n\n  function tokenComment(stream, state) {\n    var prev, next;\n    while(state.commentLevel > 0 && (next = stream.next()) != null) {\n      if (prev === '(' && next === '*') state.commentLevel++;\n      if (prev === '*' && next === ')') state.commentLevel--;\n      prev = next;\n    }\n    if (state.commentLevel <= 0) {\n      state.tokenize = tokenBase;\n    }\n    return 'comment';\n  }\n\n  return {\n    startState: function() {return {tokenize: tokenBase, commentLevel: 0};},\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      return state.tokenize(stream, state);\n    },\n    blockCommentStart: \"(*\",\n    blockCommentEnd: \"*)\"\n  };\n});\n\nCodeMirror.defineMIME('text/x-mathematica', {\n  name: 'mathematica'\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mbox/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: mbox mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"mbox.js\"></script>\n<style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">mbox</a>\n  </ul>\n</div>\n\n<article>\n<h2>mbox mode</h2>\n<form><textarea id=\"code\" name=\"code\">\nFrom timothygu99@gmail.com Sun Apr 17 01:40:43 2016\nFrom: Timothy Gu &lt;timothygu99@gmail.com&gt;\nDate: Sat, 16 Apr 2016 18:40:43 -0700\nSubject: mbox mode\nMessage-ID: &lt;Z8d+bTT50U/az94FZnyPkDjZmW0=@gmail.com&gt;\n\nmbox mode is working!\n\nTimothy\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>application/mbox</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mbox/mbox.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nvar rfc2822 = [\n  \"From\", \"Sender\", \"Reply-To\", \"To\", \"Cc\", \"Bcc\", \"Message-ID\",\n  \"In-Reply-To\", \"References\", \"Resent-From\", \"Resent-Sender\", \"Resent-To\",\n  \"Resent-Cc\", \"Resent-Bcc\", \"Resent-Message-ID\", \"Return-Path\", \"Received\"\n];\nvar rfc2822NoEmail = [\n  \"Date\", \"Subject\", \"Comments\", \"Keywords\", \"Resent-Date\"\n];\n\nCodeMirror.registerHelper(\"hintWords\", \"mbox\", rfc2822.concat(rfc2822NoEmail));\n\nvar whitespace = /^[ \\t]/;\nvar separator = /^From /; // See RFC 4155\nvar rfc2822Header = new RegExp(\"^(\" + rfc2822.join(\"|\") + \"): \");\nvar rfc2822HeaderNoEmail = new RegExp(\"^(\" + rfc2822NoEmail.join(\"|\") + \"): \");\nvar header = /^[^:]+:/; // Optional fields defined in RFC 2822\nvar email = /^[^ ]+@[^ ]+/;\nvar untilEmail = /^.*?(?=[^ ]+?@[^ ]+)/;\nvar bracketedEmail = /^<.*?>/;\nvar untilBracketedEmail = /^.*?(?=<.*>)/;\n\nfunction styleForHeader(header) {\n  if (header === \"Subject\") return \"header\";\n  return \"string\";\n}\n\nfunction readToken(stream, state) {\n  if (stream.sol()) {\n    // From last line\n    state.inSeparator = false;\n    if (state.inHeader && stream.match(whitespace)) {\n      // Header folding\n      return null;\n    } else {\n      state.inHeader = false;\n      state.header = null;\n    }\n\n    if (stream.match(separator)) {\n      state.inHeaders = true;\n      state.inSeparator = true;\n      return \"atom\";\n    }\n\n    var match;\n    var emailPermitted = false;\n    if ((match = stream.match(rfc2822HeaderNoEmail)) ||\n        (emailPermitted = true) && (match = stream.match(rfc2822Header))) {\n      state.inHeaders = true;\n      state.inHeader = true;\n      state.emailPermitted = emailPermitted;\n      state.header = match[1];\n      return \"atom\";\n    }\n\n    // Use vim's heuristics: recognize custom headers only if the line is in a\n    // block of legitimate headers.\n    if (state.inHeaders && (match = stream.match(header))) {\n      state.inHeader = true;\n      state.emailPermitted = true;\n      state.header = match[1];\n      return \"atom\";\n    }\n\n    state.inHeaders = false;\n    stream.skipToEnd();\n    return null;\n  }\n\n  if (state.inSeparator) {\n    if (stream.match(email)) return \"link\";\n    if (stream.match(untilEmail)) return \"atom\";\n    stream.skipToEnd();\n    return \"atom\";\n  }\n\n  if (state.inHeader) {\n    var style = styleForHeader(state.header);\n\n    if (state.emailPermitted) {\n      if (stream.match(bracketedEmail)) return style + \" link\";\n      if (stream.match(untilBracketedEmail)) return style;\n    }\n    stream.skipToEnd();\n    return style;\n  }\n\n  stream.skipToEnd();\n  return null;\n};\n\nCodeMirror.defineMode(\"mbox\", function() {\n  return {\n    startState: function() {\n      return {\n        // Is in a mbox separator\n        inSeparator: false,\n        // Is in a mail header\n        inHeader: false,\n        // If bracketed email is permitted. Only applicable when inHeader\n        emailPermitted: false,\n        // Name of current header\n        header: null,\n        // Is in a region of mail headers\n        inHeaders: false\n      };\n    },\n    token: readToken,\n    blankLine: function(state) {\n      state.inHeaders = state.inSeparator = state.inHeader = false;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"application/mbox\", \"mbox\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/meta.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.modeInfo = [\n    {name: \"APL\", mime: \"text/apl\", mode: \"apl\", ext: [\"dyalog\", \"apl\"]},\n    {name: \"PGP\", mimes: [\"application/pgp\", \"application/pgp-encrypted\", \"application/pgp-keys\", \"application/pgp-signature\"], mode: \"asciiarmor\", ext: [\"asc\", \"pgp\", \"sig\"]},\n    {name: \"ASN.1\", mime: \"text/x-ttcn-asn\", mode: \"asn.1\", ext: [\"asn\", \"asn1\"]},\n    {name: \"Asterisk\", mime: \"text/x-asterisk\", mode: \"asterisk\", file: /^extensions\\.conf$/i},\n    {name: \"Brainfuck\", mime: \"text/x-brainfuck\", mode: \"brainfuck\", ext: [\"b\", \"bf\"]},\n    {name: \"C\", mime: \"text/x-csrc\", mode: \"clike\", ext: [\"c\", \"h\", \"ino\"]},\n    {name: \"C++\", mime: \"text/x-c++src\", mode: \"clike\", ext: [\"cpp\", \"c++\", \"cc\", \"cxx\", \"hpp\", \"h++\", \"hh\", \"hxx\"], alias: [\"cpp\"]},\n    {name: \"Cobol\", mime: \"text/x-cobol\", mode: \"cobol\", ext: [\"cob\", \"cpy\"]},\n    {name: \"C#\", mime: \"text/x-csharp\", mode: \"clike\", ext: [\"cs\"], alias: [\"csharp\"]},\n    {name: \"Clojure\", mime: \"text/x-clojure\", mode: \"clojure\", ext: [\"clj\", \"cljc\", \"cljx\"]},\n    {name: \"ClojureScript\", mime: \"text/x-clojurescript\", mode: \"clojure\", ext: [\"cljs\"]},\n    {name: \"Closure Stylesheets (GSS)\", mime: \"text/x-gss\", mode: \"css\", ext: [\"gss\"]},\n    {name: \"CMake\", mime: \"text/x-cmake\", mode: \"cmake\", ext: [\"cmake\", \"cmake.in\"], file: /^CMakeLists.txt$/},\n    {name: \"CoffeeScript\", mimes: [\"application/vnd.coffeescript\", \"text/coffeescript\", \"text/x-coffeescript\"], mode: \"coffeescript\", ext: [\"coffee\"], alias: [\"coffee\", \"coffee-script\"]},\n    {name: \"Common Lisp\", mime: \"text/x-common-lisp\", mode: \"commonlisp\", ext: [\"cl\", \"lisp\", \"el\"], alias: [\"lisp\"]},\n    {name: \"Cypher\", mime: \"application/x-cypher-query\", mode: \"cypher\", ext: [\"cyp\", \"cypher\"]},\n    {name: \"Cython\", mime: \"text/x-cython\", mode: \"python\", ext: [\"pyx\", \"pxd\", \"pxi\"]},\n    {name: \"Crystal\", mime: \"text/x-crystal\", mode: \"crystal\", ext: [\"cr\"]},\n    {name: \"CSS\", mime: \"text/css\", mode: \"css\", ext: [\"css\"]},\n    {name: \"CQL\", mime: \"text/x-cassandra\", mode: \"sql\", ext: [\"cql\"]},\n    {name: \"D\", mime: \"text/x-d\", mode: \"d\", ext: [\"d\"]},\n    {name: \"Dart\", mimes: [\"application/dart\", \"text/x-dart\"], mode: \"dart\", ext: [\"dart\"]},\n    {name: \"diff\", mime: \"text/x-diff\", mode: \"diff\", ext: [\"diff\", \"patch\"]},\n    {name: \"Django\", mime: \"text/x-django\", mode: \"django\"},\n    {name: \"Dockerfile\", mime: \"text/x-dockerfile\", mode: \"dockerfile\", file: /^Dockerfile$/},\n    {name: \"DTD\", mime: \"application/xml-dtd\", mode: \"dtd\", ext: [\"dtd\"]},\n    {name: \"Dylan\", mime: \"text/x-dylan\", mode: \"dylan\", ext: [\"dylan\", \"dyl\", \"intr\"]},\n    {name: \"EBNF\", mime: \"text/x-ebnf\", mode: \"ebnf\"},\n    {name: \"ECL\", mime: \"text/x-ecl\", mode: \"ecl\", ext: [\"ecl\"]},\n    {name: \"edn\", mime: \"application/edn\", mode: \"clojure\", ext: [\"edn\"]},\n    {name: \"Eiffel\", mime: \"text/x-eiffel\", mode: \"eiffel\", ext: [\"e\"]},\n    {name: \"Elm\", mime: \"text/x-elm\", mode: \"elm\", ext: [\"elm\"]},\n    {name: \"Embedded Javascript\", mime: \"application/x-ejs\", mode: \"htmlembedded\", ext: [\"ejs\"]},\n    {name: \"Embedded Ruby\", mime: \"application/x-erb\", mode: \"htmlembedded\", ext: [\"erb\"]},\n    {name: \"Erlang\", mime: \"text/x-erlang\", mode: \"erlang\", ext: [\"erl\"]},\n    {name: \"Esper\", mime: \"text/x-esper\", mode: \"sql\"},\n    {name: \"Factor\", mime: \"text/x-factor\", mode: \"factor\", ext: [\"factor\"]},\n    {name: \"FCL\", mime: \"text/x-fcl\", mode: \"fcl\"},\n    {name: \"Forth\", mime: \"text/x-forth\", mode: \"forth\", ext: [\"forth\", \"fth\", \"4th\"]},\n    {name: \"Fortran\", mime: \"text/x-fortran\", mode: \"fortran\", ext: [\"f\", \"for\", \"f77\", \"f90\", \"f95\"]},\n    {name: \"F#\", mime: \"text/x-fsharp\", mode: \"mllike\", ext: [\"fs\"], alias: [\"fsharp\"]},\n    {name: \"Gas\", mime: \"text/x-gas\", mode: \"gas\", ext: [\"s\"]},\n    {name: \"Gherkin\", mime: \"text/x-feature\", mode: \"gherkin\", ext: [\"feature\"]},\n    {name: \"GitHub Flavored Markdown\", mime: \"text/x-gfm\", mode: \"gfm\", file: /^(readme|contributing|history).md$/i},\n    {name: \"Go\", mime: \"text/x-go\", mode: \"go\", ext: [\"go\"]},\n    {name: \"Groovy\", mime: \"text/x-groovy\", mode: \"groovy\", ext: [\"groovy\", \"gradle\"], file: /^Jenkinsfile$/},\n    {name: \"HAML\", mime: \"text/x-haml\", mode: \"haml\", ext: [\"haml\"]},\n    {name: \"Haskell\", mime: \"text/x-haskell\", mode: \"haskell\", ext: [\"hs\"]},\n    {name: \"Haskell (Literate)\", mime: \"text/x-literate-haskell\", mode: \"haskell-literate\", ext: [\"lhs\"]},\n    {name: \"Haxe\", mime: \"text/x-haxe\", mode: \"haxe\", ext: [\"hx\"]},\n    {name: \"HXML\", mime: \"text/x-hxml\", mode: \"haxe\", ext: [\"hxml\"]},\n    {name: \"ASP.NET\", mime: \"application/x-aspx\", mode: \"htmlembedded\", ext: [\"aspx\"], alias: [\"asp\", \"aspx\"]},\n    {name: \"HTML\", mime: \"text/html\", mode: \"htmlmixed\", ext: [\"html\", \"htm\", \"handlebars\", \"hbs\"], alias: [\"xhtml\"]},\n    {name: \"HTTP\", mime: \"message/http\", mode: \"http\"},\n    {name: \"IDL\", mime: \"text/x-idl\", mode: \"idl\", ext: [\"pro\"]},\n    {name: \"Pug\", mime: \"text/x-pug\", mode: \"pug\", ext: [\"jade\", \"pug\"], alias: [\"jade\"]},\n    {name: \"Java\", mime: \"text/x-java\", mode: \"clike\", ext: [\"java\"]},\n    {name: \"Java Server Pages\", mime: \"application/x-jsp\", mode: \"htmlembedded\", ext: [\"jsp\"], alias: [\"jsp\"]},\n    {name: \"JavaScript\", mimes: [\"text/javascript\", \"text/ecmascript\", \"application/javascript\", \"application/x-javascript\", \"application/ecmascript\"],\n     mode: \"javascript\", ext: [\"js\"], alias: [\"ecmascript\", \"js\", \"node\"]},\n    {name: \"JSON\", mimes: [\"application/json\", \"application/x-json\"], mode: \"javascript\", ext: [\"json\", \"map\"], alias: [\"json5\"]},\n    {name: \"JSON-LD\", mime: \"application/ld+json\", mode: \"javascript\", ext: [\"jsonld\"], alias: [\"jsonld\"]},\n    {name: \"JSX\", mime: \"text/jsx\", mode: \"jsx\", ext: [\"jsx\"]},\n    {name: \"Jinja2\", mime: \"text/jinja2\", mode: \"jinja2\", ext: [\"j2\", \"jinja\", \"jinja2\"]},\n    {name: \"Julia\", mime: \"text/x-julia\", mode: \"julia\", ext: [\"jl\"]},\n    {name: \"Kotlin\", mime: \"text/x-kotlin\", mode: \"clike\", ext: [\"kt\"]},\n    {name: \"LESS\", mime: \"text/x-less\", mode: \"css\", ext: [\"less\"]},\n    {name: \"LiveScript\", mime: \"text/x-livescript\", mode: \"livescript\", ext: [\"ls\"], alias: [\"ls\"]},\n    {name: \"Lua\", mime: \"text/x-lua\", mode: \"lua\", ext: [\"lua\"]},\n    {name: \"Markdown\", mime: \"text/x-markdown\", mode: \"markdown\", ext: [\"markdown\", \"md\", \"mkd\"]},\n    {name: \"mIRC\", mime: \"text/mirc\", mode: \"mirc\"},\n    {name: \"MariaDB SQL\", mime: \"text/x-mariadb\", mode: \"sql\"},\n    {name: \"Mathematica\", mime: \"text/x-mathematica\", mode: \"mathematica\", ext: [\"m\", \"nb\"]},\n    {name: \"Modelica\", mime: \"text/x-modelica\", mode: \"modelica\", ext: [\"mo\"]},\n    {name: \"MUMPS\", mime: \"text/x-mumps\", mode: \"mumps\", ext: [\"mps\"]},\n    {name: \"MS SQL\", mime: \"text/x-mssql\", mode: \"sql\"},\n    {name: \"mbox\", mime: \"application/mbox\", mode: \"mbox\", ext: [\"mbox\"]},\n    {name: \"MySQL\", mime: \"text/x-mysql\", mode: \"sql\"},\n    {name: \"Nginx\", mime: \"text/x-nginx-conf\", mode: \"nginx\", file: /nginx.*\\.conf$/i},\n    {name: \"NSIS\", mime: \"text/x-nsis\", mode: \"nsis\", ext: [\"nsh\", \"nsi\"]},\n    {name: \"NTriples\", mimes: [\"application/n-triples\", \"application/n-quads\", \"text/n-triples\"],\n     mode: \"ntriples\", ext: [\"nt\", \"nq\"]},\n    {name: \"Objective-C\", mime: \"text/x-objectivec\", mode: \"clike\", ext: [\"m\", \"mm\"], alias: [\"objective-c\", \"objc\"]},\n    {name: \"OCaml\", mime: \"text/x-ocaml\", mode: \"mllike\", ext: [\"ml\", \"mli\", \"mll\", \"mly\"]},\n    {name: \"Octave\", mime: \"text/x-octave\", mode: \"octave\", ext: [\"m\"]},\n    {name: \"Oz\", mime: \"text/x-oz\", mode: \"oz\", ext: [\"oz\"]},\n    {name: \"Pascal\", mime: \"text/x-pascal\", mode: \"pascal\", ext: [\"p\", \"pas\"]},\n    {name: \"PEG.js\", mime: \"null\", mode: \"pegjs\", ext: [\"jsonld\"]},\n    {name: \"Perl\", mime: \"text/x-perl\", mode: \"perl\", ext: [\"pl\", \"pm\"]},\n    {name: \"PHP\", mimes: [\"text/x-php\", \"application/x-httpd-php\", \"application/x-httpd-php-open\"], mode: \"php\", ext: [\"php\", \"php3\", \"php4\", \"php5\", \"php7\", \"phtml\"]},\n    {name: \"Pig\", mime: \"text/x-pig\", mode: \"pig\", ext: [\"pig\"]},\n    {name: \"Plain Text\", mime: \"text/plain\", mode: \"null\", ext: [\"txt\", \"text\", \"conf\", \"def\", \"list\", \"log\"]},\n    {name: \"PLSQL\", mime: \"text/x-plsql\", mode: \"sql\", ext: [\"pls\"]},\n    {name: \"PowerShell\", mime: \"application/x-powershell\", mode: \"powershell\", ext: [\"ps1\", \"psd1\", \"psm1\"]},\n    {name: \"Properties files\", mime: \"text/x-properties\", mode: \"properties\", ext: [\"properties\", \"ini\", \"in\"], alias: [\"ini\", \"properties\"]},\n    {name: \"ProtoBuf\", mime: \"text/x-protobuf\", mode: \"protobuf\", ext: [\"proto\"]},\n    {name: \"Python\", mime: \"text/x-python\", mode: \"python\", ext: [\"BUILD\", \"bzl\", \"py\", \"pyw\"], file: /^(BUCK|BUILD)$/},\n    {name: \"Puppet\", mime: \"text/x-puppet\", mode: \"puppet\", ext: [\"pp\"]},\n    {name: \"Q\", mime: \"text/x-q\", mode: \"q\", ext: [\"q\"]},\n    {name: \"R\", mime: \"text/x-rsrc\", mode: \"r\", ext: [\"r\", \"R\"], alias: [\"rscript\"]},\n    {name: \"reStructuredText\", mime: \"text/x-rst\", mode: \"rst\", ext: [\"rst\"], alias: [\"rst\"]},\n    {name: \"RPM Changes\", mime: \"text/x-rpm-changes\", mode: \"rpm\"},\n    {name: \"RPM Spec\", mime: \"text/x-rpm-spec\", mode: \"rpm\", ext: [\"spec\"]},\n    {name: \"Ruby\", mime: \"text/x-ruby\", mode: \"ruby\", ext: [\"rb\"], alias: [\"jruby\", \"macruby\", \"rake\", \"rb\", \"rbx\"]},\n    {name: \"Rust\", mime: \"text/x-rustsrc\", mode: \"rust\", ext: [\"rs\"]},\n    {name: \"SAS\", mime: \"text/x-sas\", mode: \"sas\", ext: [\"sas\"]},\n    {name: \"Sass\", mime: \"text/x-sass\", mode: \"sass\", ext: [\"sass\"]},\n    {name: \"Scala\", mime: \"text/x-scala\", mode: \"clike\", ext: [\"scala\"]},\n    {name: \"Scheme\", mime: \"text/x-scheme\", mode: \"scheme\", ext: [\"scm\", \"ss\"]},\n    {name: \"SCSS\", mime: \"text/x-scss\", mode: \"css\", ext: [\"scss\"]},\n    {name: \"Shell\", mimes: [\"text/x-sh\", \"application/x-sh\"], mode: \"shell\", ext: [\"sh\", \"ksh\", \"bash\"], alias: [\"bash\", \"sh\", \"zsh\"], file: /^PKGBUILD$/},\n    {name: \"Sieve\", mime: \"application/sieve\", mode: \"sieve\", ext: [\"siv\", \"sieve\"]},\n    {name: \"Slim\", mimes: [\"text/x-slim\", \"application/x-slim\"], mode: \"slim\", ext: [\"slim\"]},\n    {name: \"Smalltalk\", mime: \"text/x-stsrc\", mode: \"smalltalk\", ext: [\"st\"]},\n    {name: \"Smarty\", mime: \"text/x-smarty\", mode: \"smarty\", ext: [\"tpl\"]},\n    {name: \"Solr\", mime: \"text/x-solr\", mode: \"solr\"},\n    {name: \"SML\", mime: \"text/x-sml\", mode: \"mllike\", ext: [\"sml\", \"sig\", \"fun\", \"smackspec\"]},\n    {name: \"Soy\", mime: \"text/x-soy\", mode: \"soy\", ext: [\"soy\"], alias: [\"closure template\"]},\n    {name: \"SPARQL\", mime: \"application/sparql-query\", mode: \"sparql\", ext: [\"rq\", \"sparql\"], alias: [\"sparul\"]},\n    {name: \"Spreadsheet\", mime: \"text/x-spreadsheet\", mode: \"spreadsheet\", alias: [\"excel\", \"formula\"]},\n    {name: \"SQL\", mime: \"text/x-sql\", mode: \"sql\", ext: [\"sql\"]},\n    {name: \"SQLite\", mime: \"text/x-sqlite\", mode: \"sql\"},\n    {name: \"Squirrel\", mime: \"text/x-squirrel\", mode: \"clike\", ext: [\"nut\"]},\n    {name: \"Stylus\", mime: \"text/x-styl\", mode: \"stylus\", ext: [\"styl\"]},\n    {name: \"Swift\", mime: \"text/x-swift\", mode: \"swift\", ext: [\"swift\"]},\n    {name: \"sTeX\", mime: \"text/x-stex\", mode: \"stex\"},\n    {name: \"LaTeX\", mime: \"text/x-latex\", mode: \"stex\", ext: [\"text\", \"ltx\", \"tex\"], alias: [\"tex\"]},\n    {name: \"SystemVerilog\", mime: \"text/x-systemverilog\", mode: \"verilog\", ext: [\"v\", \"sv\", \"svh\"]},\n    {name: \"Tcl\", mime: \"text/x-tcl\", mode: \"tcl\", ext: [\"tcl\"]},\n    {name: \"Textile\", mime: \"text/x-textile\", mode: \"textile\", ext: [\"textile\"]},\n    {name: \"TiddlyWiki \", mime: \"text/x-tiddlywiki\", mode: \"tiddlywiki\"},\n    {name: \"Tiki wiki\", mime: \"text/tiki\", mode: \"tiki\"},\n    {name: \"TOML\", mime: \"text/x-toml\", mode: \"toml\", ext: [\"toml\"]},\n    {name: \"Tornado\", mime: \"text/x-tornado\", mode: \"tornado\"},\n    {name: \"troff\", mime: \"text/troff\", mode: \"troff\", ext: [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]},\n    {name: \"TTCN\", mime: \"text/x-ttcn\", mode: \"ttcn\", ext: [\"ttcn\", \"ttcn3\", \"ttcnpp\"]},\n    {name: \"TTCN_CFG\", mime: \"text/x-ttcn-cfg\", mode: \"ttcn-cfg\", ext: [\"cfg\"]},\n    {name: \"Turtle\", mime: \"text/turtle\", mode: \"turtle\", ext: [\"ttl\"]},\n    {name: \"TypeScript\", mime: \"application/typescript\", mode: \"javascript\", ext: [\"ts\"], alias: [\"ts\"]},\n    {name: \"TypeScript-JSX\", mime: \"text/typescript-jsx\", mode: \"jsx\", ext: [\"tsx\"], alias: [\"tsx\"]},\n    {name: \"Twig\", mime: \"text/x-twig\", mode: \"twig\"},\n    {name: \"Web IDL\", mime: \"text/x-webidl\", mode: \"webidl\", ext: [\"webidl\"]},\n    {name: \"VB.NET\", mime: \"text/x-vb\", mode: \"vb\", ext: [\"vb\"]},\n    {name: \"VBScript\", mime: \"text/vbscript\", mode: \"vbscript\", ext: [\"vbs\"]},\n    {name: \"Velocity\", mime: \"text/velocity\", mode: \"velocity\", ext: [\"vtl\"]},\n    {name: \"Verilog\", mime: \"text/x-verilog\", mode: \"verilog\", ext: [\"v\"]},\n    {name: \"VHDL\", mime: \"text/x-vhdl\", mode: \"vhdl\", ext: [\"vhd\", \"vhdl\"]},\n    {name: \"Vue.js Component\", mimes: [\"script/x-vue\", \"text/x-vue\"], mode: \"vue\", ext: [\"vue\"]},\n    {name: \"XML\", mimes: [\"application/xml\", \"text/xml\"], mode: \"xml\", ext: [\"xml\", \"xsl\", \"xsd\", \"svg\"], alias: [\"rss\", \"wsdl\", \"xsd\"]},\n    {name: \"XQuery\", mime: \"application/xquery\", mode: \"xquery\", ext: [\"xy\", \"xquery\"]},\n    {name: \"Yacas\", mime: \"text/x-yacas\", mode: \"yacas\", ext: [\"ys\"]},\n    {name: \"YAML\", mimes: [\"text/x-yaml\", \"text/yaml\"], mode: \"yaml\", ext: [\"yaml\", \"yml\"], alias: [\"yml\"]},\n    {name: \"Z80\", mime: \"text/x-z80\", mode: \"z80\", ext: [\"z80\"]},\n    {name: \"mscgen\", mime: \"text/x-mscgen\", mode: \"mscgen\", ext: [\"mscgen\", \"mscin\", \"msc\"]},\n    {name: \"xu\", mime: \"text/x-xu\", mode: \"mscgen\", ext: [\"xu\"]},\n    {name: \"msgenny\", mime: \"text/x-msgenny\", mode: \"mscgen\", ext: [\"msgenny\"]}\n  ];\n  // Ensure all modes have a mime property for backwards compatibility\n  for (var i = 0; i < CodeMirror.modeInfo.length; i++) {\n    var info = CodeMirror.modeInfo[i];\n    if (info.mimes) info.mime = info.mimes[0];\n  }\n\n  CodeMirror.findModeByMIME = function(mime) {\n    mime = mime.toLowerCase();\n    for (var i = 0; i < CodeMirror.modeInfo.length; i++) {\n      var info = CodeMirror.modeInfo[i];\n      if (info.mime == mime) return info;\n      if (info.mimes) for (var j = 0; j < info.mimes.length; j++)\n        if (info.mimes[j] == mime) return info;\n    }\n    if (/\\+xml$/.test(mime)) return CodeMirror.findModeByMIME(\"application/xml\")\n    if (/\\+json$/.test(mime)) return CodeMirror.findModeByMIME(\"application/json\")\n  };\n\n  CodeMirror.findModeByExtension = function(ext) {\n    for (var i = 0; i < CodeMirror.modeInfo.length; i++) {\n      var info = CodeMirror.modeInfo[i];\n      if (info.ext) for (var j = 0; j < info.ext.length; j++)\n        if (info.ext[j] == ext) return info;\n    }\n  };\n\n  CodeMirror.findModeByFileName = function(filename) {\n    for (var i = 0; i < CodeMirror.modeInfo.length; i++) {\n      var info = CodeMirror.modeInfo[i];\n      if (info.file && info.file.test(filename)) return info;\n    }\n    var dot = filename.lastIndexOf(\".\");\n    var ext = dot > -1 && filename.substring(dot + 1, filename.length);\n    if (ext) return CodeMirror.findModeByExtension(ext);\n  };\n\n  CodeMirror.findModeByName = function(name) {\n    name = name.toLowerCase();\n    for (var i = 0; i < CodeMirror.modeInfo.length; i++) {\n      var info = CodeMirror.modeInfo[i];\n      if (info.name.toLowerCase() == name) return info;\n      if (info.alias) for (var j = 0; j < info.alias.length; j++)\n        if (info.alias[j].toLowerCase() == name) return info;\n    }\n  };\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mirc/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: mIRC mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/twilight.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"mirc.js\"></script>\n<style>.CodeMirror {border: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">mIRC</a>\n  </ul>\n</div>\n\n<article>\n<h2>mIRC mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n;AKA Nick Tracker by Ford_Lawnmower irc.GeekShed.net #Script-Help\n;*****************************************************************************;\n;**Start Setup\n;Change JoinDisplay, below, for On Join AKA Display. On = 1 - Off = 0\nalias -l JoinDisplay { return 1 }\n;Change MaxNicks, below, to the number of nicknames you want to store for each hostmask. I wouldn't go over 400 with this ;/\nalias -l MaxNicks { return 20 }\n;Change AKALogo, below, To the text you want displayed before each AKA result.\nalias -l AKALogo { return \u000306\u0007 \u000305A\u000306K\u000307A \u000306\u0007 }\n;**End Setup\n;*****************************************************************************;\nOn *:Join:#: {\n  if ($nick == $me) { .timer 1 1 ialupdateCheck $chan }\n  NickNamesAdd $nick $+($network,$wildsite)\n  if ($JoinDisplay) { .timerNickNames $+ $nick 1 2 NickNames.display $nick $chan $network $wildsite }\n}\non *:Nick: { NickNamesAdd $newnick $+($network,$wildsite) $nick }\nalias -l NickNames.display {\n  if ($gettok($hget(NickNames,$+($3,$4)),0,126) > 1) {\n    echo -g $2 $AKALogo $+(\u000309,$1) $AKALogo \u000307 $mid($replace($hget(NickNames,$+($3,$4)),$chr(126),$chr(44)),2,-1)\n  }\n}\nalias -l NickNamesAdd {\n  if ($hget(NickNames,$2)) {\n    if (!$regex($hget(NickNames,$2),/~\\Q $+ $replacecs($1,\\E,\\E\\\\E\\Q) $+ \\E~/i)) {\n      if ($gettok($hget(NickNames,$2),0,126) <= $MaxNicks) {\n        hadd NickNames $2 $+($hget(NickNames,$2),$1,~)\n      }\n      else {\n        hadd NickNames $2 $+($mid($hget(NickNames,$2),$pos($hget(NickNames,$2),~,2)),$1,~)\n      }\n    }\n  }\n  else {\n    hadd -m NickNames $2 $+(~,$1,~,$iif($3,$+($3,~)))\n  }\n}\nalias -l Fix.All.MindUser {\n  var %Fix.Count = $hfind(NickNames,/[^~]+[0-9]{4}~/,0,r).data\n  while (%Fix.Count) {\n    if ($Fix.MindUser($hget(NickNames,$hfind(NickNames,/[^~]+[0-9]{4}~/,%Fix.Count,r).data))) {\n      echo -ag Record %Fix.Count - $v1 - Was Cleaned\n      hadd NickNames $hfind(NickNames,/[^~]+[0-9]{4}~/,%Fix.Count,r).data $v1\n    }\n    dec %Fix.Count\n  }\n}\nalias -l Fix.MindUser { return $regsubex($1,/[^~]+[0-9]{4}~/g,$null) }\nmenu nicklist,query {\n  -\n  .AKA\n  ..Check $$1: {\n    if ($gettok($hget(NickNames,$+($network,$address($1,2))),0,126) > 1) {\n      NickNames.display $1 $active $network $address($1,2)\n    }\n    else { echo -ag $AKALogo $+(\u000309,$1) \u000307has not been known by any other nicknames while I have been watching. }\n  }\n  ..Cleanup $$1:hadd NickNames $+($network,$address($1,2)) $fix.minduser($hget(NickNames,$+($network,$address($1,2))))\n  ..Clear $$1:hadd NickNames $+($network,$address($1,2)) $+(~,$1,~)\n  ..AKA Search Dialog:dialog $iif($dialog(AKA_Search),-v,-m) AKA_Search AKA_Search\n  -\n}\nmenu status,channel {\n  -\n  .AKA\n  ..AKA Search Dialog:dialog $iif($dialog(AKA_Search),-v,-m) AKA_Search AKA_Search\n  ..Clean All Records:Fix.All.Minduser\n  -\n}\ndialog AKA_Search {\n  title \"AKA Search Engine\"\n  size -1 -1 206 221\n  option dbu\n  edit \"\", 1, 8 5 149 10, autohs\n  button \"Search\", 2, 163 4 32 12\n  radio \"Search HostMask\", 4, 61 22 55 10\n  radio \"Search Nicknames\", 5, 123 22 56 10\n  list 6, 8 38 190 169, sort extsel vsbar\n  button \"Check Selected\", 7, 67 206 40 12\n  button \"Close\", 8, 160 206 38 12, cancel\n  box \"Search Type\", 3, 11 17 183 18\n  button \"Copy to Clipboard\", 9, 111 206 46 12\n}\nOn *:Dialog:Aka_Search:init:*: { did -c $dname 5 }\nOn *:Dialog:Aka_Search:Sclick:2,7,9: {\n  if ($did == 2) && ($did($dname,1)) {\n    did -r $dname 6\n    var %search $+(*,$v1,*), %type $iif($did($dname,5).state,data,item), %matches = $hfind(NickNames,%search,0,w). [ $+ [ %type ] ]\n    while (%matches) {\n      did -a $dname 6 $hfind(NickNames,%search,%matches,w). [ $+ [ %type ] ]\n      dec %matches\n    }\n    did -c $dname 6 1\n  }\n  elseif ($did == 7) && ($did($dname,6).seltext) { echo -ga $AKALogo \u000307 $mid($replace($hget(NickNames,$v1),$chr(126),$chr(44)),2,-1) }\n  elseif ($did == 9) && ($did($dname,6).seltext) { clipboard $mid($v1,$pos($v1,*,1)) }\n}\nOn *:Start:{\n  if (!$hget(NickNames)) { hmake NickNames 10 }\n  if ($isfile(NickNames.hsh)) { hload  NickNames NickNames.hsh }\n}\nOn *:Exit: { if ($hget(NickNames)) { hsave NickNames NickNames.hsh } }\nOn *:Disconnect: { if ($hget(NickNames)) { hsave NickNames NickNames.hsh } }\nOn *:Unload: { hfree NickNames }\nalias -l ialupdateCheck {\n  inc -z $+(%,ialupdateCheck,$network) $calc($nick($1,0) / 4)\n  ;If your ial is already being updated on join .who $1 out.\n  ;If you are using /names to update ial you will still need this line.\n  .who $1\n}\nRaw 352:*: {\n  if ($($+(%,ialupdateCheck,$network),2)) haltdef\n  NickNamesAdd $6 $+($network,$address($6,2))\n}\nRaw 315:*: {\n  if ($($+(%,ialupdateCheck,$network),2)) haltdef\n}\n\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        theme: \"twilight\",\n        lineNumbers: true,\n        matchBrackets: true,\n        indentUnit: 4,\n        mode: \"text/mirc\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/mirc</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mirc/mirc.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n//mIRC mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMIME(\"text/mirc\", \"mirc\");\nCodeMirror.defineMode(\"mirc\", function() {\n  function parseWords(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n  var specials = parseWords(\"$! $$ $& $? $+ $abook $abs $active $activecid \" +\n                            \"$activewid $address $addtok $agent $agentname $agentstat $agentver \" +\n                            \"$alias $and $anick $ansi2mirc $aop $appactive $appstate $asc $asctime \" +\n                            \"$asin $atan $avoice $away $awaymsg $awaytime $banmask $base $bfind \" +\n                            \"$binoff $biton $bnick $bvar $bytes $calc $cb $cd $ceil $chan $chanmodes \" +\n                            \"$chantypes $chat $chr $cid $clevel $click $cmdbox $cmdline $cnick $color \" +\n                            \"$com $comcall $comchan $comerr $compact $compress $comval $cos $count \" +\n                            \"$cr $crc $creq $crlf $ctime $ctimer $ctrlenter $date $day $daylight \" +\n                            \"$dbuh $dbuw $dccignore $dccport $dde $ddename $debug $decode $decompress \" +\n                            \"$deltok $devent $dialog $did $didreg $didtok $didwm $disk $dlevel $dll \" +\n                            \"$dllcall $dname $dns $duration $ebeeps $editbox $emailaddr $encode $error \" +\n                            \"$eval $event $exist $feof $ferr $fgetc $file $filename $filtered $finddir \" +\n                            \"$finddirn $findfile $findfilen $findtok $fline $floor $fopen $fread $fserve \" +\n                            \"$fulladdress $fulldate $fullname $fullscreen $get $getdir $getdot $gettok $gmt \" +\n                            \"$group $halted $hash $height $hfind $hget $highlight $hnick $hotline \" +\n                            \"$hotlinepos $ial $ialchan $ibl $idle $iel $ifmatch $ignore $iif $iil \" +\n                            \"$inelipse $ini $inmidi $inpaste $inpoly $input $inrect $inroundrect \" +\n                            \"$insong $instok $int $inwave $ip $isalias $isbit $isdde $isdir $isfile \" +\n                            \"$isid $islower $istok $isupper $keychar $keyrpt $keyval $knick $lactive \" +\n                            \"$lactivecid $lactivewid $left $len $level $lf $line $lines $link $lock \" +\n                            \"$lock $locked $log $logstamp $logstampfmt $longfn $longip $lower $ltimer \" +\n                            \"$maddress $mask $matchkey $matchtok $md5 $me $menu $menubar $menucontext \" +\n                            \"$menutype $mid $middir $mircdir $mircexe $mircini $mklogfn $mnick $mode \" +\n                            \"$modefirst $modelast $modespl $mouse $msfile $network $newnick $nick $nofile \" +\n                            \"$nopath $noqt $not $notags $notify $null $numeric $numok $oline $onpoly \" +\n                            \"$opnick $or $ord $os $passivedcc $pic $play $pnick $port $portable $portfree \" +\n                            \"$pos $prefix $prop $protect $puttok $qt $query $rand $r $rawmsg $read $readomo \" +\n                            \"$readn $regex $regml $regsub $regsubex $remove $remtok $replace $replacex \" +\n                            \"$reptok $result $rgb $right $round $scid $scon $script $scriptdir $scriptline \" +\n                            \"$sdir $send $server $serverip $sfile $sha1 $shortfn $show $signal $sin \" +\n                            \"$site $sline $snick $snicks $snotify $sock $sockbr $sockerr $sockname \" +\n                            \"$sorttok $sound $sqrt $ssl $sreq $sslready $status $strip $str $stripped \" +\n                            \"$syle $submenu $switchbar $tan $target $ticks $time $timer $timestamp \" +\n                            \"$timestampfmt $timezone $tip $titlebar $toolbar $treebar $trust $ulevel \" +\n                            \"$ulist $upper $uptime $url $usermode $v1 $v2 $var $vcmd $vcmdstat $vcmdver \" +\n                            \"$version $vnick $vol $wid $width $wildsite $wildtok $window $wrap $xor\");\n  var keywords = parseWords(\"abook ajinvite alias aline ame amsg anick aop auser autojoin avoice \" +\n                            \"away background ban bcopy beep bread break breplace bset btrunc bunset bwrite \" +\n                            \"channel clear clearall cline clipboard close cnick color comclose comopen \" +\n                            \"comreg continue copy creq ctcpreply ctcps dcc dccserver dde ddeserver \" +\n                            \"debug dec describe dialog did didtok disable disconnect dlevel dline dll \" +\n                            \"dns dqwindow drawcopy drawdot drawfill drawline drawpic drawrect drawreplace \" +\n                            \"drawrot drawsave drawscroll drawtext ebeeps echo editbox emailaddr enable \" +\n                            \"events exit fclose filter findtext finger firewall flash flist flood flush \" +\n                            \"flushini font fopen fseek fsend fserve fullname fwrite ghide gload gmove \" +\n                            \"gopts goto gplay gpoint gqreq groups gshow gsize gstop gtalk gunload hadd \" +\n                            \"halt haltdef hdec hdel help hfree hinc hload hmake hop hsave ial ialclear \" +\n                            \"ialmark identd if ignore iline inc invite iuser join kick linesep links list \" +\n                            \"load loadbuf localinfo log mdi me menubar mkdir mnick mode msg nick noop notice \" +\n                            \"notify omsg onotice part partall pdcc perform play playctrl pop protect pvoice \" +\n                            \"qme qmsg query queryn quit raw reload remini remote remove rename renwin \" +\n                            \"reseterror resetidle return rlevel rline rmdir run ruser save savebuf saveini \" +\n                            \"say scid scon server set showmirc signam sline sockaccept sockclose socklist \" +\n                            \"socklisten sockmark sockopen sockpause sockread sockrename sockudp sockwrite \" +\n                            \"sound speak splay sreq strip switchbar timer timestamp titlebar tnick tokenize \" +\n                            \"toolbar topic tray treebar ulist unload unset unsetall updatenl url uwho \" +\n                            \"var vcadd vcmd vcrem vol while whois window winhelp write writeint if isalnum \" +\n                            \"isalpha isaop isavoice isban ischan ishop isignore isin isincs isletter islower \" +\n                            \"isnotify isnum ison isop isprotect isreg isupper isvoice iswm iswmcs \" +\n                            \"elseif else goto menu nicklist status title icon size option text edit \" +\n                            \"button check radio box scroll list combo link tab item\");\n  var functions = parseWords(\"if elseif else and not or eq ne in ni for foreach while switch\");\n  var isOperatorChar = /[+\\-*&%=<>!?^\\/\\|]/;\n  function chain(stream, state, f) {\n    state.tokenize = f;\n    return f(stream, state);\n  }\n  function tokenBase(stream, state) {\n    var beforeParams = state.beforeParams;\n    state.beforeParams = false;\n    var ch = stream.next();\n    if (/[\\[\\]{}\\(\\),\\.]/.test(ch)) {\n      if (ch == \"(\" && beforeParams) state.inParams = true;\n      else if (ch == \")\") state.inParams = false;\n      return null;\n    }\n    else if (/\\d/.test(ch)) {\n      stream.eatWhile(/[\\w\\.]/);\n      return \"number\";\n    }\n    else if (ch == \"\\\\\") {\n      stream.eat(\"\\\\\");\n      stream.eat(/./);\n      return \"number\";\n    }\n    else if (ch == \"/\" && stream.eat(\"*\")) {\n      return chain(stream, state, tokenComment);\n    }\n    else if (ch == \";\" && stream.match(/ *\\( *\\(/)) {\n      return chain(stream, state, tokenUnparsed);\n    }\n    else if (ch == \";\" && !state.inParams) {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n    else if (ch == '\"') {\n      stream.eat(/\"/);\n      return \"keyword\";\n    }\n    else if (ch == \"$\") {\n      stream.eatWhile(/[$_a-z0-9A-Z\\.:]/);\n      if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {\n        return \"keyword\";\n      }\n      else {\n        state.beforeParams = true;\n        return \"builtin\";\n      }\n    }\n    else if (ch == \"%\") {\n      stream.eatWhile(/[^,\\s()]/);\n      state.beforeParams = true;\n      return \"string\";\n    }\n    else if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return \"operator\";\n    }\n    else {\n      stream.eatWhile(/[\\w\\$_{}]/);\n      var word = stream.current().toLowerCase();\n      if (keywords && keywords.propertyIsEnumerable(word))\n        return \"keyword\";\n      if (functions && functions.propertyIsEnumerable(word)) {\n        state.beforeParams = true;\n        return \"keyword\";\n      }\n      return null;\n    }\n  }\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n  function tokenUnparsed(stream, state) {\n    var maybeEnd = 0, ch;\n    while (ch = stream.next()) {\n      if (ch == \";\" && maybeEnd == 2) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      if (ch == \")\")\n        maybeEnd++;\n      else if (ch != \" \")\n        maybeEnd = 0;\n    }\n    return \"meta\";\n  }\n  return {\n    startState: function() {\n      return {\n        tokenize: tokenBase,\n        beforeParams: false,\n        inParams: false\n      };\n    },\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      return state.tokenize(stream, state);\n    }\n  };\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mllike/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: ML-like mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=stylesheet href=../../lib/codemirror.css>\n<script src=../../lib/codemirror.js></script>\n<script src=../../addon/edit/matchbrackets.js></script>\n<script src=mllike.js></script>\n<style type=text/css>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">ML-like</a>\n  </ul>\n</div>\n\n<article>\n<h2>OCaml mode</h2>\n\n\n<textarea id=\"ocamlCode\">\n(* Summing a list of integers *)\nlet rec sum xs =\n  match xs with\n    | []       -&gt; 0\n    | x :: xs' -&gt; x + sum xs'\n\n(* Quicksort *)\nlet rec qsort = function\n   | [] -&gt; []\n   | pivot :: rest -&gt;\n       let is_less x = x &lt; pivot in\n       let left, right = List.partition is_less rest in\n       qsort left @ [pivot] @ qsort right\n\n(* Fibonacci Sequence *)\nlet rec fib_aux n a b =\n  match n with\n  | 0 -&gt; a\n  | _ -&gt; fib_aux (n - 1) (a + b) a\nlet fib n = fib_aux n 0 1\n\n(* Birthday paradox *)\nlet year_size = 365.\n\nlet rec birthday_paradox prob people =\n    let prob' = (year_size -. float people) /. year_size *. prob  in\n    if prob' &lt; 0.5 then\n        Printf.printf \"answer = %d\\n\" (people+1)\n    else\n        birthday_paradox prob' (people+1) ;;\n\nbirthday_paradox 1.0 1\n\n(* Church numerals *)\nlet zero f x = x\nlet succ n f x = f (n f x)\nlet one = succ zero\nlet two = succ (succ zero)\nlet add n1 n2 f x = n1 f (n2 f x)\nlet to_string n = n (fun k -&gt; \"S\" ^ k) \"0\"\nlet _ = to_string (add (succ two) two)\n\n(* Elementary functions *)\nlet square x = x * x;;\nlet rec fact x =\n  if x &lt;= 1 then 1 else x * fact (x - 1);;\n\n(* Automatic memory management *)\nlet l = 1 :: 2 :: 3 :: [];;\n[1; 2; 3];;\n5 :: l;;\n\n(* Polymorphism: sorting lists *)\nlet rec sort = function\n  | [] -&gt; []\n  | x :: l -&gt; insert x (sort l)\n\nand insert elem = function\n  | [] -&gt; [elem]\n  | x :: l -&gt;\n      if elem &lt; x then elem :: x :: l else x :: insert elem l;;\n\n(* Imperative features *)\nlet add_polynom p1 p2 =\n  let n1 = Array.length p1\n  and n2 = Array.length p2 in\n  let result = Array.create (max n1 n2) 0 in\n  for i = 0 to n1 - 1 do result.(i) &lt;- p1.(i) done;\n  for i = 0 to n2 - 1 do result.(i) &lt;- result.(i) + p2.(i) done;\n  result;;\nadd_polynom [| 1; 2 |] [| 1; 2; 3 |];;\n\n(* We may redefine fact using a reference cell and a for loop *)\nlet fact n =\n  let result = ref 1 in\n  for i = 2 to n do\n    result := i * !result\n   done;\n   !result;;\nfact 5;;\n\n(* Triangle (graphics) *)\nlet () =\n  ignore( Glut.init Sys.argv );\n  Glut.initDisplayMode ~double_buffer:true ();\n  ignore (Glut.createWindow ~title:\"OpenGL Demo\");\n  let angle t = 10. *. t *. t in\n  let render () =\n    GlClear.clear [ `color ];\n    GlMat.load_identity ();\n    GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. ();\n    GlDraw.begins `triangles;\n    List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.];\n    GlDraw.ends ();\n    Glut.swapBuffers () in\n  GlMat.mode `modelview;\n  Glut.displayFunc ~cb:render;\n  Glut.idleFunc ~cb:(Some Glut.postRedisplay);\n  Glut.mainLoop ()\n\n(* A Hundred Lines of Caml - http://caml.inria.fr/about/taste.en.html *)\n(* OCaml page on Wikipedia - http://en.wikipedia.org/wiki/OCaml *)\n\nmodule type S = sig type t end\n\nlet x = {| \n  this is a long string \n  with many lines and stuff\n  |}\n\nlet b = 0b00110\nlet h = 0x123abcd\nlet e = 1e-10\nlet i = 1.\nlet x = 30_000\nlet o = 0o1234\n\n[1; 2; 3] (* lists *)\n\n1 @ 2\n1. +. 2.\n</textarea>\n\n<h2>F# mode</h2>\n<textarea id=\"fsharpCode\">\nmodule CodeMirror.FSharp\n\nlet rec fib = function\n    | 0 -> 0\n    | 1 -> 1\n    | n -> fib (n - 1) + fib (n - 2)\n\ntype Point =\n    {\n        x : int\n        y : int\n    }\n\ntype Color =\n    | Red\n    | Green\n    | Blue\n\n[0 .. 10]\n|> List.map ((+) 2)\n|> List.fold (fun x y -> x + y) 0\n|> printf \"%i\"\n</textarea>\n\n\n<script>\n  var ocamlEditor = CodeMirror.fromTextArea(document.getElementById('ocamlCode'), {\n    mode: 'text/x-ocaml',\n    lineNumbers: true,\n    matchBrackets: true\n  });\n\n  var fsharpEditor = CodeMirror.fromTextArea(document.getElementById('fsharpCode'), {\n    mode: 'text/x-fsharp',\n    lineNumbers: true,\n    matchBrackets: true\n  });\n</script>\n\n<p><strong>MIME types defined:</strong> <code>text/x-ocaml</code> (OCaml) and <code>text/x-fsharp</code> (F#).</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mllike/mllike.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode('mllike', function(_config, parserConfig) {\n  var words = {\n    'as': 'keyword',\n    'do': 'keyword',\n    'else': 'keyword',\n    'end': 'keyword',\n    'exception': 'keyword',\n    'fun': 'keyword',\n    'functor': 'keyword',\n    'if': 'keyword',\n    'in': 'keyword',\n    'include': 'keyword',\n    'let': 'keyword',\n    'of': 'keyword',\n    'open': 'keyword',\n    'rec': 'keyword',\n    'struct': 'keyword',\n    'then': 'keyword',\n    'type': 'keyword',\n    'val': 'keyword',\n    'while': 'keyword',\n    'with': 'keyword'\n  };\n\n  var extraWords = parserConfig.extraWords || {};\n  for (var prop in extraWords) {\n    if (extraWords.hasOwnProperty(prop)) {\n      words[prop] = parserConfig.extraWords[prop];\n    }\n  }\n  var hintWords = [];\n  for (var k in words) { hintWords.push(k); }\n  CodeMirror.registerHelper(\"hintWords\", \"mllike\", hintWords);\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n\n    if (ch === '\"') {\n      state.tokenize = tokenString;\n      return state.tokenize(stream, state);\n    }\n    if (ch === '{') {\n      if (stream.eat('|')) {\n        state.longString = true;\n        state.tokenize = tokenLongString;\n        return state.tokenize(stream, state);\n      }\n    }\n    if (ch === '(') {\n      if (stream.eat('*')) {\n        state.commentLevel++;\n        state.tokenize = tokenComment;\n        return state.tokenize(stream, state);\n      }\n    }\n    if (ch === '~' || ch === '?') {\n      stream.eatWhile(/\\w/);\n      return 'variable-2';\n    }\n    if (ch === '`') {\n      stream.eatWhile(/\\w/);\n      return 'quote';\n    }\n    if (ch === '/' && parserConfig.slashComments && stream.eat('/')) {\n      stream.skipToEnd();\n      return 'comment';\n    }\n    if (/\\d/.test(ch)) {\n      if (ch === '0' && stream.eat(/[bB]/)) {\n        stream.eatWhile(/[01]/);\n      } if (ch === '0' && stream.eat(/[xX]/)) {\n        stream.eatWhile(/[0-9a-fA-F]/)\n      } if (ch === '0' && stream.eat(/[oO]/)) {\n        stream.eatWhile(/[0-7]/);\n      } else {\n        stream.eatWhile(/[\\d_]/);\n        if (stream.eat('.')) {\n          stream.eatWhile(/[\\d]/);\n        }\n        if (stream.eat(/[eE]/)) {\n          stream.eatWhile(/[\\d\\-+]/);\n        }\n      }\n      return 'number';\n    }\n    if ( /[+\\-*&%=<>!?|@\\.~:]/.test(ch)) {\n      return 'operator';\n    }\n    if (/[\\w\\xa1-\\uffff]/.test(ch)) {\n      stream.eatWhile(/[\\w\\xa1-\\uffff]/);\n      var cur = stream.current();\n      return words.hasOwnProperty(cur) ? words[cur] : 'variable';\n    }\n    return null\n  }\n\n  function tokenString(stream, state) {\n    var next, end = false, escaped = false;\n    while ((next = stream.next()) != null) {\n      if (next === '\"' && !escaped) {\n        end = true;\n        break;\n      }\n      escaped = !escaped && next === '\\\\';\n    }\n    if (end && !escaped) {\n      state.tokenize = tokenBase;\n    }\n    return 'string';\n  };\n\n  function tokenComment(stream, state) {\n    var prev, next;\n    while(state.commentLevel > 0 && (next = stream.next()) != null) {\n      if (prev === '(' && next === '*') state.commentLevel++;\n      if (prev === '*' && next === ')') state.commentLevel--;\n      prev = next;\n    }\n    if (state.commentLevel <= 0) {\n      state.tokenize = tokenBase;\n    }\n    return 'comment';\n  }\n\n  function tokenLongString(stream, state) {\n    var prev, next;\n    while (state.longString && (next = stream.next()) != null) {\n      if (prev === '|' && next === '}') state.longString = false;\n      prev = next;\n    }\n    if (!state.longString) {\n      state.tokenize = tokenBase;\n    }\n    return 'string';\n  }\n\n  return {\n    startState: function() {return {tokenize: tokenBase, commentLevel: 0, longString: false};},\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      return state.tokenize(stream, state);\n    },\n\n    blockCommentStart: \"(*\",\n    blockCommentEnd: \"*)\",\n    lineComment: parserConfig.slashComments ? \"//\" : null\n  };\n});\n\nCodeMirror.defineMIME('text/x-ocaml', {\n  name: 'mllike',\n  extraWords: {\n    'and': 'keyword',\n    'assert': 'keyword',\n    'begin': 'keyword',\n    'class': 'keyword',\n    'constraint': 'keyword',\n    'done': 'keyword',\n    'downto': 'keyword',\n    'external': 'keyword',\n    'function': 'keyword',\n    'initializer': 'keyword',\n    'lazy': 'keyword',\n    'match': 'keyword',\n    'method': 'keyword',\n    'module': 'keyword',\n    'mutable': 'keyword',\n    'new': 'keyword',\n    'nonrec': 'keyword',\n    'object': 'keyword',\n    'private': 'keyword',\n    'sig': 'keyword',\n    'to': 'keyword',\n    'try': 'keyword',\n    'value': 'keyword',\n    'virtual': 'keyword',\n    'when': 'keyword',\n\n    // builtins\n    'raise': 'builtin',\n    'failwith': 'builtin',\n    'true': 'builtin',\n    'false': 'builtin',\n\n    // Pervasives builtins\n    'asr': 'builtin',\n    'land': 'builtin',\n    'lor': 'builtin',\n    'lsl': 'builtin',\n    'lsr': 'builtin',\n    'lxor': 'builtin',\n    'mod': 'builtin',\n    'or': 'builtin',\n\n    // More Pervasives\n    'raise_notrace': 'builtin',\n    'trace': 'builtin',\n    'exit': 'builtin',\n    'print_string': 'builtin',\n    'print_endline': 'builtin',\n\n     'int': 'type',\n     'float': 'type',\n     'bool': 'type',\n     'char': 'type',\n     'string': 'type',\n     'unit': 'type',\n\n     // Modules\n     'List': 'builtin'\n  }\n});\n\nCodeMirror.defineMIME('text/x-fsharp', {\n  name: 'mllike',\n  extraWords: {\n    'abstract': 'keyword',\n    'assert': 'keyword',\n    'base': 'keyword',\n    'begin': 'keyword',\n    'class': 'keyword',\n    'default': 'keyword',\n    'delegate': 'keyword',\n    'do!': 'keyword',\n    'done': 'keyword',\n    'downcast': 'keyword',\n    'downto': 'keyword',\n    'elif': 'keyword',\n    'extern': 'keyword',\n    'finally': 'keyword',\n    'for': 'keyword',\n    'function': 'keyword',\n    'global': 'keyword',\n    'inherit': 'keyword',\n    'inline': 'keyword',\n    'interface': 'keyword',\n    'internal': 'keyword',\n    'lazy': 'keyword',\n    'let!': 'keyword',\n    'match': 'keyword',\n    'member': 'keyword',\n    'module': 'keyword',\n    'mutable': 'keyword',\n    'namespace': 'keyword',\n    'new': 'keyword',\n    'null': 'keyword',\n    'override': 'keyword',\n    'private': 'keyword',\n    'public': 'keyword',\n    'return!': 'keyword',\n    'return': 'keyword',\n    'select': 'keyword',\n    'static': 'keyword',\n    'to': 'keyword',\n    'try': 'keyword',\n    'upcast': 'keyword',\n    'use!': 'keyword',\n    'use': 'keyword',\n    'void': 'keyword',\n    'when': 'keyword',\n    'yield!': 'keyword',\n    'yield': 'keyword',\n\n    // Reserved words\n    'atomic': 'keyword',\n    'break': 'keyword',\n    'checked': 'keyword',\n    'component': 'keyword',\n    'const': 'keyword',\n    'constraint': 'keyword',\n    'constructor': 'keyword',\n    'continue': 'keyword',\n    'eager': 'keyword',\n    'event': 'keyword',\n    'external': 'keyword',\n    'fixed': 'keyword',\n    'method': 'keyword',\n    'mixin': 'keyword',\n    'object': 'keyword',\n    'parallel': 'keyword',\n    'process': 'keyword',\n    'protected': 'keyword',\n    'pure': 'keyword',\n    'sealed': 'keyword',\n    'tailcall': 'keyword',\n    'trait': 'keyword',\n    'virtual': 'keyword',\n    'volatile': 'keyword',\n\n    // builtins\n    'List': 'builtin',\n    'Seq': 'builtin',\n    'Map': 'builtin',\n    'Set': 'builtin',\n    'Option': 'builtin',\n    'int': 'builtin',\n    'string': 'builtin',\n    'not': 'builtin',\n    'true': 'builtin',\n    'false': 'builtin',\n\n    'raise': 'builtin',\n    'failwith': 'builtin'\n  },\n  slashComments: true\n});\n\n\nCodeMirror.defineMIME('text/x-sml', {\n  name: 'mllike',\n  extraWords: {\n    'abstype': 'keyword',\n    'and': 'keyword',\n    'andalso': 'keyword',\n    'case': 'keyword',\n    'datatype': 'keyword',\n    'fn': 'keyword',\n    'handle': 'keyword',\n    'infix': 'keyword',\n    'infixr': 'keyword',\n    'local': 'keyword',\n    'nonfix': 'keyword',\n    'op': 'keyword',\n    'orelse': 'keyword',\n    'raise': 'keyword',\n    'withtype': 'keyword',\n    'eqtype': 'keyword',\n    'sharing': 'keyword',\n    'sig': 'keyword',\n    'signature': 'keyword',\n    'structure': 'keyword',\n    'where': 'keyword',\n    'true': 'keyword',\n    'false': 'keyword',\n\n    // types\n    'int': 'builtin',\n    'real': 'builtin',\n    'string': 'builtin',\n    'char': 'builtin',\n    'bool': 'builtin'\n  },\n  slashComments: true\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/modelica/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Modelica mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<link rel=\"stylesheet\" href=\"../../addon/hint/show-hint.css\">\n<script src=\"../../addon/hint/show-hint.js\"></script>\n<script src=\"modelica.js\"></script>\n<style>.CodeMirror {border: 2px inset #dee;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Modelica</a>\n  </ul>\n</div>\n\n<article>\n<h2>Modelica mode</h2>\n\n<div><textarea id=\"modelica\">\nmodel BouncingBall\n  parameter Real e = 0.7;\n  parameter Real g = 9.81;\n  Real h(start=1);\n  Real v;\n  Boolean flying(start=true);\n  Boolean impact;\n  Real v_new;\nequation\n  impact = h <= 0.0;\n  der(v) = if flying then -g else 0;\n  der(h) = v;\n  when {h <= 0.0 and v <= 0.0, impact} then\n    v_new = if edge(impact) then -e*pre(v) else 0;\n    flying = v_new > 0;\n    reinit(v, v_new);\n  end when;\n  annotation (uses(Modelica(version=\"3.2\")));\nend BouncingBall;\n</textarea></div>\n\n    <script>\n      var modelicaEditor = CodeMirror.fromTextArea(document.getElementById(\"modelica\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-modelica\"\n      });\n      var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault;\n      CodeMirror.keyMap.default[(mac ? \"Cmd\" : \"Ctrl\") + \"-Space\"] = \"autocomplete\";\n    </script>\n\n    <p>Simple mode that tries to handle Modelica as well as it can.</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-modelica</code>\n    (Modlica code).</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/modelica/modelica.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Modelica support for CodeMirror, copyright (c) by Lennart Ochel\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})\n\n(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"modelica\", function(config, parserConfig) {\n\n    var indentUnit = config.indentUnit;\n    var keywords = parserConfig.keywords || {};\n    var builtin = parserConfig.builtin || {};\n    var atoms = parserConfig.atoms || {};\n\n    var isSingleOperatorChar = /[;=\\(:\\),{}.*<>+\\-\\/^\\[\\]]/;\n    var isDoubleOperatorChar = /(:=|<=|>=|==|<>|\\.\\+|\\.\\-|\\.\\*|\\.\\/|\\.\\^)/;\n    var isDigit = /[0-9]/;\n    var isNonDigit = /[_a-zA-Z]/;\n\n    function tokenLineComment(stream, state) {\n      stream.skipToEnd();\n      state.tokenize = null;\n      return \"comment\";\n    }\n\n    function tokenBlockComment(stream, state) {\n      var maybeEnd = false, ch;\n      while (ch = stream.next()) {\n        if (maybeEnd && ch == \"/\") {\n          state.tokenize = null;\n          break;\n        }\n        maybeEnd = (ch == \"*\");\n      }\n      return \"comment\";\n    }\n\n    function tokenString(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == '\"' && !escaped) {\n          state.tokenize = null;\n          state.sol = false;\n          break;\n        }\n        escaped = !escaped && ch == \"\\\\\";\n      }\n\n      return \"string\";\n    }\n\n    function tokenIdent(stream, state) {\n      stream.eatWhile(isDigit);\n      while (stream.eat(isDigit) || stream.eat(isNonDigit)) { }\n\n\n      var cur = stream.current();\n\n      if(state.sol && (cur == \"package\" || cur == \"model\" || cur == \"when\" || cur == \"connector\")) state.level++;\n      else if(state.sol && cur == \"end\" && state.level > 0) state.level--;\n\n      state.tokenize = null;\n      state.sol = false;\n\n      if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n      else if (builtin.propertyIsEnumerable(cur)) return \"builtin\";\n      else if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n      else return \"variable\";\n    }\n\n    function tokenQIdent(stream, state) {\n      while (stream.eat(/[^']/)) { }\n\n      state.tokenize = null;\n      state.sol = false;\n\n      if(stream.eat(\"'\"))\n        return \"variable\";\n      else\n        return \"error\";\n    }\n\n    function tokenUnsignedNuber(stream, state) {\n      stream.eatWhile(isDigit);\n      if (stream.eat('.')) {\n        stream.eatWhile(isDigit);\n      }\n      if (stream.eat('e') || stream.eat('E')) {\n        if (!stream.eat('-'))\n          stream.eat('+');\n        stream.eatWhile(isDigit);\n      }\n\n      state.tokenize = null;\n      state.sol = false;\n      return \"number\";\n    }\n\n    // Interface\n    return {\n      startState: function() {\n        return {\n          tokenize: null,\n          level: 0,\n          sol: true\n        };\n      },\n\n      token: function(stream, state) {\n        if(state.tokenize != null) {\n          return state.tokenize(stream, state);\n        }\n\n        if(stream.sol()) {\n          state.sol = true;\n        }\n\n        // WHITESPACE\n        if(stream.eatSpace()) {\n          state.tokenize = null;\n          return null;\n        }\n\n        var ch = stream.next();\n\n        // LINECOMMENT\n        if(ch == '/' && stream.eat('/')) {\n          state.tokenize = tokenLineComment;\n        }\n        // BLOCKCOMMENT\n        else if(ch == '/' && stream.eat('*')) {\n          state.tokenize = tokenBlockComment;\n        }\n        // TWO SYMBOL TOKENS\n        else if(isDoubleOperatorChar.test(ch+stream.peek())) {\n          stream.next();\n          state.tokenize = null;\n          return \"operator\";\n        }\n        // SINGLE SYMBOL TOKENS\n        else if(isSingleOperatorChar.test(ch)) {\n          state.tokenize = null;\n          return \"operator\";\n        }\n        // IDENT\n        else if(isNonDigit.test(ch)) {\n          state.tokenize = tokenIdent;\n        }\n        // Q-IDENT\n        else if(ch == \"'\" && stream.peek() && stream.peek() != \"'\") {\n          state.tokenize = tokenQIdent;\n        }\n        // STRING\n        else if(ch == '\"') {\n          state.tokenize = tokenString;\n        }\n        // UNSIGNED_NUBER\n        else if(isDigit.test(ch)) {\n          state.tokenize = tokenUnsignedNuber;\n        }\n        // ERROR\n        else {\n          state.tokenize = null;\n          return \"error\";\n        }\n\n        return state.tokenize(stream, state);\n      },\n\n      indent: function(state, textAfter) {\n        if (state.tokenize != null) return CodeMirror.Pass;\n\n        var level = state.level;\n        if(/(algorithm)/.test(textAfter)) level--;\n        if(/(equation)/.test(textAfter)) level--;\n        if(/(initial algorithm)/.test(textAfter)) level--;\n        if(/(initial equation)/.test(textAfter)) level--;\n        if(/(end)/.test(textAfter)) level--;\n\n        if(level > 0)\n          return indentUnit*level;\n        else\n          return 0;\n      },\n\n      blockCommentStart: \"/*\",\n      blockCommentEnd: \"*/\",\n      lineComment: \"//\"\n    };\n  });\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i=0; i<words.length; ++i)\n      obj[words[i]] = true;\n    return obj;\n  }\n\n  var modelicaKeywords = \"algorithm and annotation assert block break class connect connector constant constrainedby der discrete each else elseif elsewhen encapsulated end enumeration equation expandable extends external false final flow for function if import impure in initial inner input loop model not operator or outer output package parameter partial protected public pure record redeclare replaceable return stream then true type when while within\";\n  var modelicaBuiltin = \"abs acos actualStream asin atan atan2 cardinality ceil cos cosh delay div edge exp floor getInstanceName homotopy inStream integer log log10 mod pre reinit rem semiLinear sign sin sinh spatialDistribution sqrt tan tanh\";\n  var modelicaAtoms = \"Real Boolean Integer String\";\n\n  function def(mimes, mode) {\n    if (typeof mimes == \"string\")\n      mimes = [mimes];\n\n    var words = [];\n\n    function add(obj) {\n      if (obj)\n        for (var prop in obj)\n          if (obj.hasOwnProperty(prop))\n            words.push(prop);\n    }\n\n    add(mode.keywords);\n    add(mode.builtin);\n    add(mode.atoms);\n\n    if (words.length) {\n      mode.helperType = mimes[0];\n      CodeMirror.registerHelper(\"hintWords\", mimes[0], words);\n    }\n\n    for (var i=0; i<mimes.length; ++i)\n      CodeMirror.defineMIME(mimes[i], mode);\n  }\n\n  def([\"text/x-modelica\"], {\n    name: \"modelica\",\n    keywords: words(modelicaKeywords),\n    builtin: words(modelicaBuiltin),\n    atoms: words(modelicaAtoms)\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mscgen/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: MscGen mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"mscgen.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">MscGen</a>\n  </ul>\n</div>\n\n<article>\n<h2>MscGen mode</h2>\n\n<div><textarea id=\"mscgen-code\">\n# Sample mscgen program\n# See http://www.mcternan.me.uk/mscgen or\n# https://sverweij.github.io/mscgen_js for more samples\nmsc {\n  # options\n  hscale=\"1.2\";\n\n  # entities/ lifelines\n  a [label=\"Entity A\"],\n  b [label=\"Entity B\", linecolor=\"red\", arclinecolor=\"red\", textbgcolor=\"pink\"],\n  c [label=\"Entity C\"];\n\n  # arcs/ messages\n  a => c [label=\"doSomething(args)\"];\n  b => c [label=\"doSomething(args)\"];\n  c >> * [label=\"everyone asked me\", arcskip=\"1\"];\n  c =>> c [label=\"doing something\"];\n  c -x * [label=\"report back\", arcskip=\"1\"];\n  |||;\n  --- [label=\"shows's over, however ...\"];\n  b => a [label=\"did you see c doing something?\"];\n  a -> b [label=\"nope\"];\n  b :> a [label=\"shall we ask again?\"];\n  a => b [label=\"naah\"];\n  ...;\n}\n</textarea></div>\n\n<h2>Xù mode</h2>\n\n<div><textarea id=\"xu-code\">\n# Xù - expansions to MscGen to support inline expressions\n#      https://github.com/sverweij/mscgen_js/blob/master/wikum/xu.md\n# More samples: https://sverweij.github.io/mscgen_js\nxu {\n  hscale=\"0.8\",\n  width=\"700\";\n\n  a,\n  b [label=\"change store\"],\n  c,\n  d [label=\"necro queue\"],\n  e [label=\"natalis queue\"],\n  f;\n\n  a =>> b [label=\"get change list()\"];\n  a alt f [label=\"changes found\"] { /* alt is a xu specific keyword*/\n    b >> a [label=\"list of changes\"];\n    a =>> c [label=\"cull old stuff (list of changes)\"];\n    b loop e [label=\"for each change\"] { // loop is xu specific as well...\n      /*\n       * Interesting stuff happens.\n       */\n      c =>> b [label=\"get change()\"];\n      b >> c [label=\"change\"];\n      c alt e [label=\"change too old\"] {\n        c =>> d [label=\"queue(change)\"];\n        --- [label=\"change newer than latest run\"];\n        c =>> e [label=\"queue(change)\"];\n        --- [label=\"all other cases\"];\n        ||| [label=\"leave well alone\"];\n      };\n    };\n\n    c >> a [label=\"done\n    processing\"];\n\n    /* shucks! nothing found ...*/\n    --- [label=\"nothing found\"];\n    b >> a [label=\"nothing\"];\n    a note a [label=\"silent exit\"];\n  };\n}\n</textarea></div>\n\n<h2>MsGenny mode</h2>\n<div><textarea id=\"msgenny-code\">\n# MsGenny - simplified version of MscGen / Xù\n#           https://github.com/sverweij/mscgen_js/blob/master/wikum/msgenny.md\n# More samples: https://sverweij.github.io/mscgen_js\na -> b   : a -> b  (signal);\na => b   : a => b  (method);\nb >> a   : b >> a  (return value);\na =>> b  : a =>> b (callback);\na -x b   : a -x b  (lost);\na :> b   : a :> b  (emphasis);\na .. b   : a .. b  (dotted);\na -- b   : \"a -- b straight line\";\na note a : a note a\\n(note),\nb box b  : b box b\\n(action);\na rbox a : a rbox a\\n(reference),\nb abox b : b abox b\\n(state/ condition);\n|||      : ||| (empty row);\n...      : ... (omitted row);\n---      : --- (comment);\n</textarea></div>\n\n    <p>\n      Simple mode for highlighting MscGen and two derived sequence\n      chart languages.\n    </p>\n\n    <script>\n      var mscgenEditor = CodeMirror.fromTextArea(document.getElementById(\"mscgen-code\"), {\n        lineNumbers: true,\n        mode: \"text/x-mscgen\",\n      });\n      var xuEditor = CodeMirror.fromTextArea(document.getElementById(\"xu-code\"), {\n        lineNumbers: true,\n        mode: \"text/x-xu\",\n      });\n      var msgennyEditor = CodeMirror.fromTextArea(document.getElementById(\"msgenny-code\"), {\n        lineNumbers: true,\n        mode: \"text/x-msgenny\",\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong>\n      <code>text/x-mscgen</code>\n      <code>text/x-xu</code>\n      <code>text/x-msgenny</code>\n    </p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mscgen/mscgen.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// mode(s) for the sequence chart dsl's mscgen, xù and msgenny\n// For more information on mscgen, see the site of the original author:\n// http://www.mcternan.me.uk/mscgen\n//\n// This mode for mscgen and the two derivative languages were\n// originally made for use in the mscgen_js interpreter\n// (https://sverweij.github.io/mscgen_js)\n\n(function(mod) {\n  if ( typeof exports == \"object\" && typeof module == \"object\")// CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if ( typeof define == \"function\" && define.amd)// AMD\n    define([\"../../lib/codemirror\"], mod);\n  else// Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var languages = {\n    mscgen: {\n      \"keywords\" : [\"msc\"],\n      \"options\" : [\"hscale\", \"width\", \"arcgradient\", \"wordwraparcs\"],\n      \"constants\" : [\"true\", \"false\", \"on\", \"off\"],\n      \"attributes\" : [\"label\", \"idurl\", \"id\", \"url\", \"linecolor\", \"linecolour\", \"textcolor\", \"textcolour\", \"textbgcolor\", \"textbgcolour\", \"arclinecolor\", \"arclinecolour\", \"arctextcolor\", \"arctextcolour\", \"arctextbgcolor\", \"arctextbgcolour\", \"arcskip\"],\n      \"brackets\" : [\"\\\\{\", \"\\\\}\"], // [ and  ] are brackets too, but these get handled in with lists\n      \"arcsWords\" : [\"note\", \"abox\", \"rbox\", \"box\"],\n      \"arcsOthers\" : [\"\\\\|\\\\|\\\\|\", \"\\\\.\\\\.\\\\.\", \"---\", \"--\", \"<->\", \"==\", \"<<=>>\", \"<=>\", \"\\\\.\\\\.\", \"<<>>\", \"::\", \"<:>\", \"->\", \"=>>\", \"=>\", \">>\", \":>\", \"<-\", \"<<=\", \"<=\", \"<<\", \"<:\", \"x-\", \"-x\"],\n      \"singlecomment\" : [\"//\", \"#\"],\n      \"operators\" : [\"=\"]\n    },\n    xu: {\n      \"keywords\" : [\"msc\", \"xu\"],\n      \"options\" : [\"hscale\", \"width\", \"arcgradient\", \"wordwraparcs\", \"wordwrapentities\", \"watermark\"],\n      \"constants\" : [\"true\", \"false\", \"on\", \"off\", \"auto\"],\n      \"attributes\" : [\"label\", \"idurl\", \"id\", \"url\", \"linecolor\", \"linecolour\", \"textcolor\", \"textcolour\", \"textbgcolor\", \"textbgcolour\", \"arclinecolor\", \"arclinecolour\", \"arctextcolor\", \"arctextcolour\", \"arctextbgcolor\", \"arctextbgcolour\", \"arcskip\", \"title\", \"deactivate\", \"activate\", \"activation\"],\n      \"brackets\" : [\"\\\\{\", \"\\\\}\"],  // [ and  ] are brackets too, but these get handled in with lists\n      \"arcsWords\" : [\"note\", \"abox\", \"rbox\", \"box\", \"alt\", \"else\", \"opt\", \"break\", \"par\", \"seq\", \"strict\", \"neg\", \"critical\", \"ignore\", \"consider\", \"assert\", \"loop\", \"ref\", \"exc\"],\n      \"arcsOthers\" : [\"\\\\|\\\\|\\\\|\", \"\\\\.\\\\.\\\\.\", \"---\", \"--\", \"<->\", \"==\", \"<<=>>\", \"<=>\", \"\\\\.\\\\.\", \"<<>>\", \"::\", \"<:>\", \"->\", \"=>>\", \"=>\", \">>\", \":>\", \"<-\", \"<<=\", \"<=\", \"<<\", \"<:\", \"x-\", \"-x\"],\n      \"singlecomment\" : [\"//\", \"#\"],\n      \"operators\" : [\"=\"]\n    },\n    msgenny: {\n      \"keywords\" : null,\n      \"options\" : [\"hscale\", \"width\", \"arcgradient\", \"wordwraparcs\", \"wordwrapentities\", \"watermark\"],\n      \"constants\" : [\"true\", \"false\", \"on\", \"off\", \"auto\"],\n      \"attributes\" : null,\n      \"brackets\" : [\"\\\\{\", \"\\\\}\"],\n      \"arcsWords\" : [\"note\", \"abox\", \"rbox\", \"box\", \"alt\", \"else\", \"opt\", \"break\", \"par\", \"seq\", \"strict\", \"neg\", \"critical\", \"ignore\", \"consider\", \"assert\", \"loop\", \"ref\", \"exc\"],\n      \"arcsOthers\" : [\"\\\\|\\\\|\\\\|\", \"\\\\.\\\\.\\\\.\", \"---\", \"--\", \"<->\", \"==\", \"<<=>>\", \"<=>\", \"\\\\.\\\\.\", \"<<>>\", \"::\", \"<:>\", \"->\", \"=>>\", \"=>\", \">>\", \":>\", \"<-\", \"<<=\", \"<=\", \"<<\", \"<:\", \"x-\", \"-x\"],\n      \"singlecomment\" : [\"//\", \"#\"],\n      \"operators\" : [\"=\"]\n    }\n  }\n\n  CodeMirror.defineMode(\"mscgen\", function(_, modeConfig) {\n    var language = languages[modeConfig && modeConfig.language || \"mscgen\"]\n    return {\n      startState: startStateFn,\n      copyState: copyStateFn,\n      token: produceTokenFunction(language),\n      lineComment : \"#\",\n      blockCommentStart : \"/*\",\n      blockCommentEnd : \"*/\"\n    };\n  });\n\n  CodeMirror.defineMIME(\"text/x-mscgen\", \"mscgen\");\n  CodeMirror.defineMIME(\"text/x-xu\", {name: \"mscgen\", language: \"xu\"});\n  CodeMirror.defineMIME(\"text/x-msgenny\", {name: \"mscgen\", language: \"msgenny\"});\n\n  function wordRegexpBoundary(pWords) {\n    return new RegExp(\"\\\\b(\" + pWords.join(\"|\") + \")\\\\b\", \"i\");\n  }\n\n  function wordRegexp(pWords) {\n    return new RegExp(\"(\" + pWords.join(\"|\") + \")\", \"i\");\n  }\n\n  function startStateFn() {\n    return {\n      inComment : false,\n      inString : false,\n      inAttributeList : false,\n      inScript : false\n    };\n  }\n\n  function copyStateFn(pState) {\n    return {\n      inComment : pState.inComment,\n      inString : pState.inString,\n      inAttributeList : pState.inAttributeList,\n      inScript : pState.inScript\n    };\n  }\n\n  function produceTokenFunction(pConfig) {\n\n    return function(pStream, pState) {\n      if (pStream.match(wordRegexp(pConfig.brackets), true, true)) {\n        return \"bracket\";\n      }\n      /* comments */\n      if (!pState.inComment) {\n        if (pStream.match(/\\/\\*[^\\*\\/]*/, true, true)) {\n          pState.inComment = true;\n          return \"comment\";\n        }\n        if (pStream.match(wordRegexp(pConfig.singlecomment), true, true)) {\n          pStream.skipToEnd();\n          return \"comment\";\n        }\n      }\n      if (pState.inComment) {\n        if (pStream.match(/[^\\*\\/]*\\*\\//, true, true))\n          pState.inComment = false;\n        else\n          pStream.skipToEnd();\n        return \"comment\";\n      }\n      /* strings */\n      if (!pState.inString && pStream.match(/\\\"(\\\\\\\"|[^\\\"])*/, true, true)) {\n        pState.inString = true;\n        return \"string\";\n      }\n      if (pState.inString) {\n        if (pStream.match(/[^\\\"]*\\\"/, true, true))\n          pState.inString = false;\n        else\n          pStream.skipToEnd();\n        return \"string\";\n      }\n      /* keywords & operators */\n      if (!!pConfig.keywords && pStream.match(wordRegexpBoundary(pConfig.keywords), true, true))\n        return \"keyword\";\n\n      if (pStream.match(wordRegexpBoundary(pConfig.options), true, true))\n        return \"keyword\";\n\n      if (pStream.match(wordRegexpBoundary(pConfig.arcsWords), true, true))\n        return \"keyword\";\n\n      if (pStream.match(wordRegexp(pConfig.arcsOthers), true, true))\n        return \"keyword\";\n\n      if (!!pConfig.operators && pStream.match(wordRegexp(pConfig.operators), true, true))\n        return \"operator\";\n\n      if (!!pConfig.constants && pStream.match(wordRegexp(pConfig.constants), true, true))\n        return \"variable\";\n\n      /* attribute lists */\n      if (!pConfig.inAttributeList && !!pConfig.attributes && pStream.match(/\\[/, true, true)) {\n        pConfig.inAttributeList = true;\n        return \"bracket\";\n      }\n      if (pConfig.inAttributeList) {\n        if (pConfig.attributes !== null && pStream.match(wordRegexpBoundary(pConfig.attributes), true, true)) {\n          return \"attribute\";\n        }\n        if (pStream.match(/]/, true, true)) {\n          pConfig.inAttributeList = false;\n          return \"bracket\";\n        }\n      }\n\n      pStream.next();\n      return \"base\";\n    };\n  }\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mscgen/mscgen_test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"mscgen\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"empty chart\",\n     \"[keyword msc][bracket {]\",\n     \"[base   ]\",\n     \"[bracket }]\"\n   );\n\n  MT(\"comments\",\n    \"[comment // a single line comment]\",\n    \"[comment # another  single line comment /* and */ ignored here]\",\n    \"[comment /* A multi-line comment even though it contains]\",\n    \"[comment msc keywords and \\\"quoted text\\\"*/]\");\n\n  MT(\"strings\",\n    \"[string \\\"// a string\\\"]\",\n    \"[string \\\"a string running over]\",\n    \"[string two lines\\\"]\",\n    \"[string \\\"with \\\\\\\"escaped quote\\\"]\"\n  );\n\n  MT(\"xù/ msgenny keywords classify as 'base'\",\n    \"[base watermark]\",\n    \"[base wordwrapentities]\",\n    \"[base alt loop opt ref else break par seq assert]\"\n  );\n\n  MT(\"xù/ msgenny constants classify as 'base'\",\n    \"[base auto]\"\n  );\n\n  MT(\"mscgen constants classify as 'variable'\",\n    \"[variable true]\", \"[variable false]\", \"[variable on]\", \"[variable off]\"\n  );\n\n  MT(\"mscgen options classify as keyword\",\n    \"[keyword hscale]\", \"[keyword width]\", \"[keyword arcgradient]\", \"[keyword wordwraparcs]\"\n  );\n\n  MT(\"mscgen arcs classify as keyword\",\n    \"[keyword note]\",\"[keyword abox]\",\"[keyword rbox]\",\"[keyword box]\",\n    \"[keyword |||...---]\", \"[keyword ..--==::]\",\n    \"[keyword ->]\", \"[keyword <-]\", \"[keyword <->]\",\n    \"[keyword =>]\", \"[keyword <=]\", \"[keyword <=>]\",\n    \"[keyword =>>]\", \"[keyword <<=]\", \"[keyword <<=>>]\",\n    \"[keyword >>]\", \"[keyword <<]\", \"[keyword <<>>]\",\n    \"[keyword -x]\", \"[keyword x-]\", \"[keyword -X]\", \"[keyword X-]\",\n    \"[keyword :>]\", \"[keyword <:]\", \"[keyword <:>]\"\n  );\n\n  MT(\"within an attribute list, attributes classify as attribute\",\n    \"[bracket [[][attribute label]\",\n    \"[attribute id]\",\"[attribute url]\",\"[attribute idurl]\",\n    \"[attribute linecolor]\",\"[attribute linecolour]\",\"[attribute textcolor]\",\"[attribute textcolour]\",\"[attribute textbgcolor]\",\"[attribute textbgcolour]\",\n    \"[attribute arclinecolor]\",\"[attribute arclinecolour]\",\"[attribute arctextcolor]\",\"[attribute arctextcolour]\",\"[attribute arctextbgcolor]\",\"[attribute arctextbgcolour]\",\n    \"[attribute arcskip][bracket ]]]\"\n  );\n\n  MT(\"outside an attribute list, attributes classify as base\",\n    \"[base label]\",\n    \"[base id]\",\"[base url]\",\"[base idurl]\",\n    \"[base linecolor]\",\"[base linecolour]\",\"[base textcolor]\",\"[base textcolour]\",\"[base textbgcolor]\",\"[base textbgcolour]\",\n    \"[base arclinecolor]\",\"[base arclinecolour]\",\"[base arctextcolor]\",\"[base arctextcolour]\",\"[base arctextbgcolor]\",\"[base arctextbgcolour]\",\n    \"[base arcskip]\"\n  );\n\n  MT(\"a typical program\",\n    \"[comment # typical mscgen program]\",\n    \"[keyword msc][base  ][bracket {]\",\n    \"[keyword wordwraparcs][operator =][variable true][base , ][keyword hscale][operator =][string \\\"0.8\\\"][base , ][keyword arcgradient][operator =][base 30;]\",\n    \"[base   a][bracket [[][attribute label][operator =][string \\\"Entity A\\\"][bracket ]]][base ,]\",\n    \"[base   b][bracket [[][attribute label][operator =][string \\\"Entity B\\\"][bracket ]]][base ,]\",\n    \"[base   c][bracket [[][attribute label][operator =][string \\\"Entity C\\\"][bracket ]]][base ;]\",\n    \"[base   a ][keyword =>>][base  b][bracket [[][attribute label][operator =][string \\\"Hello entity B\\\"][bracket ]]][base ;]\",\n    \"[base   a ][keyword <<][base  b][bracket [[][attribute label][operator =][string \\\"Here's an answer dude!\\\"][bracket ]]][base ;]\",\n    \"[base   c ][keyword :>][base  *][bracket [[][attribute label][operator =][string \\\"What about me?\\\"][base , ][attribute textcolor][operator =][base red][bracket ]]][base ;]\",\n    \"[bracket }]\"\n  );\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mscgen/msgenny_test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"text/x-msgenny\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), \"msgenny\"); }\n\n  MT(\"comments\",\n    \"[comment // a single line comment]\",\n    \"[comment # another  single line comment /* and */ ignored here]\",\n    \"[comment /* A multi-line comment even though it contains]\",\n    \"[comment msc keywords and \\\"quoted text\\\"*/]\");\n\n  MT(\"strings\",\n    \"[string \\\"// a string\\\"]\",\n    \"[string \\\"a string running over]\",\n    \"[string two lines\\\"]\",\n    \"[string \\\"with \\\\\\\"escaped quote\\\"]\"\n  );\n\n  MT(\"xù/ msgenny keywords classify as 'keyword'\",\n    \"[keyword watermark]\",\n    \"[keyword wordwrapentities]\",\n    \"[keyword alt]\",\"[keyword loop]\",\"[keyword opt]\",\"[keyword ref]\",\"[keyword else]\",\"[keyword break]\",\"[keyword par]\",\"[keyword seq]\",\"[keyword assert]\"\n  );\n\n  MT(\"xù/ msgenny constants classify as 'variable'\",\n    \"[variable auto]\",\n    \"[variable true]\", \"[variable false]\", \"[variable on]\", \"[variable off]\"\n  );\n\n  MT(\"mscgen options classify as keyword\",\n    \"[keyword hscale]\", \"[keyword width]\", \"[keyword arcgradient]\", \"[keyword wordwraparcs]\"\n  );\n\n  MT(\"mscgen arcs classify as keyword\",\n    \"[keyword note]\",\"[keyword abox]\",\"[keyword rbox]\",\"[keyword box]\",\n    \"[keyword |||...---]\", \"[keyword ..--==::]\",\n    \"[keyword ->]\", \"[keyword <-]\", \"[keyword <->]\",\n    \"[keyword =>]\", \"[keyword <=]\", \"[keyword <=>]\",\n    \"[keyword =>>]\", \"[keyword <<=]\", \"[keyword <<=>>]\",\n    \"[keyword >>]\", \"[keyword <<]\", \"[keyword <<>>]\",\n    \"[keyword -x]\", \"[keyword x-]\", \"[keyword -X]\", \"[keyword X-]\",\n    \"[keyword :>]\", \"[keyword <:]\", \"[keyword <:>]\"\n  );\n\n  MT(\"within an attribute list, mscgen/ xù attributes classify as base\",\n    \"[base [[label]\",\n    \"[base idurl id url]\",\n    \"[base linecolor linecolour textcolor textcolour textbgcolor textbgcolour]\",\n    \"[base arclinecolor arclinecolour arctextcolor arctextcolour arctextbgcolor arctextbgcolour]\",\n    \"[base arcskip]]]\"\n  );\n\n  MT(\"outside an attribute list, mscgen/ xù attributes classify as base\",\n    \"[base label]\",\n    \"[base idurl id url]\",\n    \"[base linecolor linecolour textcolor textcolour textbgcolor textbgcolour]\",\n    \"[base arclinecolor arclinecolour arctextcolor arctextcolour arctextbgcolor arctextbgcolour]\",\n    \"[base arcskip]\"\n  );\n\n  MT(\"a typical program\",\n    \"[comment # typical msgenny program]\",\n    \"[keyword wordwraparcs][operator =][variable true][base , ][keyword hscale][operator =][string \\\"0.8\\\"][base , ][keyword arcgradient][operator =][base 30;]\",\n    \"[base   a : ][string \\\"Entity A\\\"][base ,]\",\n    \"[base   b : Entity B,]\",\n    \"[base   c : Entity C;]\",\n    \"[base   a ][keyword =>>][base  b: ][string \\\"Hello entity B\\\"][base ;]\",\n    \"[base   a ][keyword alt][base  c][bracket {]\",\n    \"[base     a ][keyword <<][base  b: ][string \\\"Here's an answer dude!\\\"][base ;]\",\n    \"[keyword ---][base : ][string \\\"sorry, won't march - comm glitch\\\"]\",\n    \"[base     a ][keyword x-][base  b: ][string \\\"Here's an answer dude! (won't arrive...)\\\"][base ;]\",\n    \"[bracket }]\",\n    \"[base   c ][keyword :>][base  *: What about me?;]\"\n  );\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mscgen/xu_test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"text/x-xu\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), \"xu\"); }\n\n  MT(\"empty chart\",\n     \"[keyword msc][bracket {]\",\n     \"[base   ]\",\n     \"[bracket }]\"\n  );\n\n  MT(\"empty chart\",\n     \"[keyword xu][bracket {]\",\n     \"[base   ]\",\n     \"[bracket }]\"\n  );\n\n  MT(\"comments\",\n    \"[comment // a single line comment]\",\n    \"[comment # another  single line comment /* and */ ignored here]\",\n    \"[comment /* A multi-line comment even though it contains]\",\n    \"[comment msc keywords and \\\"quoted text\\\"*/]\");\n\n  MT(\"strings\",\n    \"[string \\\"// a string\\\"]\",\n    \"[string \\\"a string running over]\",\n    \"[string two lines\\\"]\",\n    \"[string \\\"with \\\\\\\"escaped quote\\\"]\"\n  );\n\n  MT(\"xù/ msgenny keywords classify as 'keyword'\",\n    \"[keyword watermark]\",\n    \"[keyword alt]\",\"[keyword loop]\",\"[keyword opt]\",\"[keyword ref]\",\"[keyword else]\",\"[keyword break]\",\"[keyword par]\",\"[keyword seq]\",\"[keyword assert]\"\n  );\n\n  MT(\"xù/ msgenny constants classify as 'variable'\",\n    \"[variable auto]\",\n    \"[variable true]\", \"[variable false]\", \"[variable on]\", \"[variable off]\"\n  );\n\n  MT(\"mscgen options classify as keyword\",\n    \"[keyword hscale]\", \"[keyword width]\", \"[keyword arcgradient]\", \"[keyword wordwraparcs]\"\n  );\n\n  MT(\"mscgen arcs classify as keyword\",\n    \"[keyword note]\",\"[keyword abox]\",\"[keyword rbox]\",\"[keyword box]\",\n    \"[keyword |||...---]\", \"[keyword ..--==::]\",\n    \"[keyword ->]\", \"[keyword <-]\", \"[keyword <->]\",\n    \"[keyword =>]\", \"[keyword <=]\", \"[keyword <=>]\",\n    \"[keyword =>>]\", \"[keyword <<=]\", \"[keyword <<=>>]\",\n    \"[keyword >>]\", \"[keyword <<]\", \"[keyword <<>>]\",\n    \"[keyword -x]\", \"[keyword x-]\", \"[keyword -X]\", \"[keyword X-]\",\n    \"[keyword :>]\", \"[keyword <:]\", \"[keyword <:>]\"\n  );\n\n  MT(\"within an attribute list, attributes classify as attribute\",\n    \"[bracket [[][attribute label]\",\n    \"[attribute id]\",\"[attribute url]\",\"[attribute idurl]\",\n    \"[attribute linecolor]\",\"[attribute linecolour]\",\"[attribute textcolor]\",\"[attribute textcolour]\",\"[attribute textbgcolor]\",\"[attribute textbgcolour]\",\n    \"[attribute arclinecolor]\",\"[attribute arclinecolour]\",\"[attribute arctextcolor]\",\"[attribute arctextcolour]\",\"[attribute arctextbgcolor]\",\"[attribute arctextbgcolour]\",\n    \"[attribute arcskip]\",\"[attribute title]\",\n    \"[attribute activate]\",\"[attribute deactivate]\",\"[attribute activation][bracket ]]]\"\n  );\n\n  MT(\"outside an attribute list, attributes classify as base\",\n    \"[base label]\",\n    \"[base id]\",\"[base url]\",\"[base idurl]\",\n    \"[base linecolor]\",\"[base linecolour]\",\"[base textcolor]\",\"[base textcolour]\",\"[base textbgcolor]\",\"[base textbgcolour]\",\n    \"[base arclinecolor]\",\"[base arclinecolour]\",\"[base arctextcolor]\",\"[base arctextcolour]\",\"[base arctextbgcolor]\",\"[base arctextbgcolour]\",\n    \"[base arcskip]\", \"[base title]\"\n  );\n\n  MT(\"a typical program\",\n    \"[comment # typical xu program]\",\n    \"[keyword xu][base  ][bracket {]\",\n    \"[keyword wordwraparcs][operator =][string \\\"true\\\"][base , ][keyword hscale][operator =][string \\\"0.8\\\"][base , ][keyword arcgradient][operator =][base 30, ][keyword width][operator =][variable auto][base ;]\",\n    \"[base   a][bracket [[][attribute label][operator =][string \\\"Entity A\\\"][bracket ]]][base ,]\",\n    \"[base   b][bracket [[][attribute label][operator =][string \\\"Entity B\\\"][bracket ]]][base ,]\",\n    \"[base   c][bracket [[][attribute label][operator =][string \\\"Entity C\\\"][bracket ]]][base ;]\",\n    \"[base   a ][keyword =>>][base  b][bracket [[][attribute label][operator =][string \\\"Hello entity B\\\"][bracket ]]][base ;]\",\n    \"[base   a ][keyword <<][base  b][bracket [[][attribute label][operator =][string \\\"Here's an answer dude!\\\"][base , ][attribute title][operator =][string \\\"This is a title for this message\\\"][bracket ]]][base ;]\",\n    \"[base   c ][keyword :>][base  *][bracket [[][attribute label][operator =][string \\\"What about me?\\\"][base , ][attribute textcolor][operator =][base red][bracket ]]][base ;]\",\n    \"[bracket }]\"\n  );\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mumps/index.html",
    "content": "﻿<!doctype html>\n\n<title>CodeMirror: MUMPS mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"mumps.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">MUMPS</a>\n  </ul>\n</div>\n\n<article>\n<h2>MUMPS mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n ; Lloyd Milligan\n ; 03-30-2015\n ;\n ; MUMPS support for Code Mirror - Excerpts below from routine ^XUS\n ;\nCHECKAV(X1) ;Check A/V code return DUZ or Zero. (Called from XUSRB)\n N %,%1,X,Y,IEN,DA,DIK\n S IEN=0\n ;Start CCOW\n I $E(X1,1,7)=\"~~TOK~~\" D  Q:IEN>0 IEN\n . I $E(X1,8,9)=\"~1\" S IEN=$$CHKASH^XUSRB4($E(X1,8,255))\n . I $E(X1,8,9)=\"~2\" S IEN=$$CHKCCOW^XUSRB4($E(X1,8,255))\n . Q\n ;End CCOW\n S X1=$$UP(X1) S:X1[\":\" XUTT=1,X1=$TR(X1,\":\")\n S X=$P(X1,\";\") Q:X=\"^\" -1 S:XUF %1=\"Access: \"_X\n Q:X'?1.20ANP 0\n S X=$$EN^XUSHSH(X) I '$D(^VA(200,\"A\",X)) D LBAV Q 0\n S %1=\"\",IEN=$O(^VA(200,\"A\",X,0)),XUF(.3)=IEN D USER(IEN)\n S X=$P(X1,\";\",2) S:XUF %1=\"Verify: \"_X S X=$$EN^XUSHSH(X)\n I $P(XUSER(1),\"^\",2)'=X D LBAV Q 0\n I $G(XUFAC(1)) S DIK=\"^XUSEC(4,\",DA=XUFAC(1) D ^DIK\n Q IEN\n ;\n ; Spell out commands\n ;\nSET2() ;EF. Return error code (also called from XUSRB)\n NEW %,X\n SET XUNOW=$$HTFM^XLFDT($H),DT=$P(XUNOW,\".\")\n KILL DUZ,XUSER\n SET (DUZ,DUZ(2))=0,(DUZ(0),DUZ(\"AG\"),XUSER(0),XUSER(1),XUTT,%UCI)=\"\"\n SET %=$$INHIBIT^XUSRB() IF %>0 QUIT %\n SET X=$G(^%ZIS(1,XUDEV,\"XUS\")),XU1=$G(^(1))\n IF $L(X) FOR I=1:1:15 IF $L($P(X,U,I)) SET $P(XOPT,U,I)=$P(X,U,I)\n SET DTIME=600\n IF '$P(XOPT,U,11),$D(^%ZIS(1,XUDEV,90)),^(90)>2800000,^(90)'>DT QUIT 8\n QUIT 0\n ;\n ; Spell out commands and functions\n ;\n IF $PIECE(XUSER(0),U,11),$PIECE(XUSER(0),U,11)'>DT QUIT 11 ;Terminated\n IF $DATA(DUZ(\"ASH\")) QUIT 0 ;If auto handle, Allow to sign-on p434\n IF $PIECE(XUSER(0),U,7) QUIT 5 ;Disuser flag set\n IF '$LENGTH($PIECE(XUSER(1),U,2)) QUIT 21 ;p419, p434\n Q 0\n ;\n  </textarea></div>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n         mode: \"mumps\",\n         lineNumbers: true,\n         lineWrapping: true\n      });\n    </script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/mumps/mumps.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/*\n  This MUMPS Language script was constructed using vbscript.js as a template.\n*/\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"mumps\", function() {\n    function wordRegexp(words) {\n      return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\", \"i\");\n    }\n\n    var singleOperators = new RegExp(\"^[\\\\+\\\\-\\\\*/&#!_?\\\\\\\\<>=\\\\'\\\\[\\\\]]\");\n    var doubleOperators = new RegExp(\"^(('=)|(<=)|(>=)|('>)|('<)|([[)|(]])|(^$))\");\n    var singleDelimiters = new RegExp(\"^[\\\\.,:]\");\n    var brackets = new RegExp(\"[()]\");\n    var identifiers = new RegExp(\"^[%A-Za-z][A-Za-z0-9]*\");\n    var commandKeywords = [\"break\",\"close\",\"do\",\"else\",\"for\",\"goto\", \"halt\", \"hang\", \"if\", \"job\",\"kill\",\"lock\",\"merge\",\"new\",\"open\", \"quit\", \"read\", \"set\", \"tcommit\", \"trollback\", \"tstart\", \"use\", \"view\", \"write\", \"xecute\", \"b\",\"c\",\"d\",\"e\",\"f\",\"g\", \"h\", \"i\", \"j\",\"k\",\"l\",\"m\",\"n\",\"o\", \"q\", \"r\", \"s\", \"tc\", \"tro\", \"ts\", \"u\", \"v\", \"w\", \"x\"];\n    // The following list includes instrinsic functions _and_ special variables\n    var intrinsicFuncsWords = [\"\\\\$ascii\", \"\\\\$char\", \"\\\\$data\", \"\\\\$ecode\", \"\\\\$estack\", \"\\\\$etrap\", \"\\\\$extract\", \"\\\\$find\", \"\\\\$fnumber\", \"\\\\$get\", \"\\\\$horolog\", \"\\\\$io\", \"\\\\$increment\", \"\\\\$job\", \"\\\\$justify\", \"\\\\$length\", \"\\\\$name\", \"\\\\$next\", \"\\\\$order\", \"\\\\$piece\", \"\\\\$qlength\", \"\\\\$qsubscript\", \"\\\\$query\", \"\\\\$quit\", \"\\\\$random\", \"\\\\$reverse\", \"\\\\$select\", \"\\\\$stack\", \"\\\\$test\", \"\\\\$text\", \"\\\\$translate\", \"\\\\$view\", \"\\\\$x\", \"\\\\$y\", \"\\\\$a\", \"\\\\$c\", \"\\\\$d\", \"\\\\$e\", \"\\\\$ec\", \"\\\\$es\", \"\\\\$et\", \"\\\\$f\", \"\\\\$fn\", \"\\\\$g\", \"\\\\$h\", \"\\\\$i\", \"\\\\$j\", \"\\\\$l\", \"\\\\$n\", \"\\\\$na\", \"\\\\$o\", \"\\\\$p\", \"\\\\$q\", \"\\\\$ql\", \"\\\\$qs\", \"\\\\$r\", \"\\\\$re\", \"\\\\$s\", \"\\\\$st\", \"\\\\$t\", \"\\\\$tr\", \"\\\\$v\", \"\\\\$z\"];\n    var intrinsicFuncs = wordRegexp(intrinsicFuncsWords);\n    var command = wordRegexp(commandKeywords);\n\n    function tokenBase(stream, state) {\n      if (stream.sol()) {\n        state.label = true;\n        state.commandMode = 0;\n      }\n\n      // The <space> character has meaning in MUMPS. Ignoring consecutive\n      // spaces would interfere with interpreting whether the next non-space\n      // character belongs to the command or argument context.\n\n      // Examine each character and update a mode variable whose interpretation is:\n      //   >0 => command    0 => argument    <0 => command post-conditional\n      var ch = stream.peek();\n\n      if (ch == \" \" || ch == \"\\t\") { // Pre-process <space>\n        state.label = false;\n        if (state.commandMode == 0)\n          state.commandMode = 1;\n        else if ((state.commandMode < 0) || (state.commandMode == 2))\n          state.commandMode = 0;\n      } else if ((ch != \".\") && (state.commandMode > 0)) {\n        if (ch == \":\")\n          state.commandMode = -1;   // SIS - Command post-conditional\n        else\n          state.commandMode = 2;\n      }\n\n      // Do not color parameter list as line tag\n      if ((ch === \"(\") || (ch === \"\\u0009\"))\n        state.label = false;\n\n      // MUMPS comment starts with \";\"\n      if (ch === \";\") {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n\n      // Number Literals // SIS/RLM - MUMPS permits canonic number followed by concatenate operator\n      if (stream.match(/^[-+]?\\d+(\\.\\d+)?([eE][-+]?\\d+)?/))\n        return \"number\";\n\n      // Handle Strings\n      if (ch == '\"') {\n        if (stream.skipTo('\"')) {\n          stream.next();\n          return \"string\";\n        } else {\n          stream.skipToEnd();\n          return \"error\";\n        }\n      }\n\n      // Handle operators and Delimiters\n      if (stream.match(doubleOperators) || stream.match(singleOperators))\n        return \"operator\";\n\n      // Prevents leading \".\" in DO block from falling through to error\n      if (stream.match(singleDelimiters))\n        return null;\n\n      if (brackets.test(ch)) {\n        stream.next();\n        return \"bracket\";\n      }\n\n      if (state.commandMode > 0 && stream.match(command))\n        return \"variable-2\";\n\n      if (stream.match(intrinsicFuncs))\n        return \"builtin\";\n\n      if (stream.match(identifiers))\n        return \"variable\";\n\n      // Detect dollar-sign when not a documented intrinsic function\n      // \"^\" may introduce a GVN or SSVN - Color same as function\n      if (ch === \"$\" || ch === \"^\") {\n        stream.next();\n        return \"builtin\";\n      }\n\n      // MUMPS Indirection\n      if (ch === \"@\") {\n        stream.next();\n        return \"string-2\";\n      }\n\n      if (/[\\w%]/.test(ch)) {\n        stream.eatWhile(/[\\w%]/);\n        return \"variable\";\n      }\n\n      // Handle non-detected items\n      stream.next();\n      return \"error\";\n    }\n\n    return {\n      startState: function() {\n        return {\n          label: false,\n          commandMode: 0\n        };\n      },\n\n      token: function(stream, state) {\n        var style = tokenBase(stream, state);\n        if (state.label) return \"tag\";\n        return style;\n      }\n    };\n  });\n\n  CodeMirror.defineMIME(\"text/x-mumps\", \"mumps\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/nginx/index.html",
    "content": "<!doctype html>\n<head>\n<title>CodeMirror: NGINX mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"nginx.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n    <link rel=\"stylesheet\" href=\"../../doc/docs.css\">\n  </head>\n\n  <style>\n    body {\n      margin: 0em auto;\n    }\n\n    .CodeMirror, .CodeMirror-scroll {\n      height: 600px;\n    }\n  </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">NGINX</a>\n  </ul>\n</div>\n\n<article>\n<h2>NGINX mode</h2>\n<form><textarea id=\"code\" name=\"code\" style=\"height: 800px;\">\nserver {\n  listen 173.255.219.235:80;\n  server_name website.com.au;\n  rewrite / $scheme://www.$host$request_uri permanent; ## Forcibly prepend a www\n}\n\nserver {\n  listen 173.255.219.235:443;\n  server_name website.com.au;\n  rewrite / $scheme://www.$host$request_uri permanent; ## Forcibly prepend a www\n}\n\nserver {\n\n  listen      173.255.219.235:80;\n  server_name www.website.com.au;\n\n\n\n  root        /data/www;\n  index       index.html index.php;\n\n  location / {\n    index index.html index.php;     ## Allow a static html file to be shown first\n    try_files $uri $uri/ @handler;  ## If missing pass the URI to Magento's front handler\n    expires 30d;                    ## Assume all files are cachable\n  }\n\n  ## These locations would be hidden by .htaccess normally\n  location /app/                { deny all; }\n  location /includes/           { deny all; }\n  location /lib/                { deny all; }\n  location /media/downloadable/ { deny all; }\n  location /pkginfo/            { deny all; }\n  location /report/config.xml   { deny all; }\n  location /var/                { deny all; }\n\n  location /var/export/ { ## Allow admins only to view export folder\n    auth_basic           \"Restricted\"; ## Message shown in login window\n    auth_basic_user_file /rs/passwords/testfile; ## See /etc/nginx/htpassword\n    autoindex            on;\n  }\n\n  location  /. { ## Disable .htaccess and other hidden files\n    return 404;\n  }\n\n  location @handler { ## Magento uses a common front handler\n    rewrite / /index.php;\n  }\n\n  location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler\n    rewrite ^/(.*.php)/ /$1 last;\n  }\n\n  location ~ \\.php$ {\n    if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss\n\n    fastcgi_pass   127.0.0.1:9000;\n    fastcgi_index  index.php;\n    fastcgi_param PATH_INFO $fastcgi_script_name;\n    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;\n    include        /rs/confs/nginx/fastcgi_params;\n  }\n\n}\n\n\nserver {\n\n  listen              173.255.219.235:443;\n  server_name         website.com.au www.website.com.au;\n\n  root   /data/www;\n  index index.html index.php;\n\n  ssl                 on;\n  ssl_certificate     /rs/ssl/ssl.crt;\n  ssl_certificate_key /rs/ssl/ssl.key;\n\n  ssl_session_timeout  5m;\n\n  ssl_protocols  SSLv2 SSLv3 TLSv1;\n  ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;\n  ssl_prefer_server_ciphers   on;\n\n\n\n  location / {\n    index index.html index.php; ## Allow a static html file to be shown first\n    try_files $uri $uri/ @handler; ## If missing pass the URI to Magento's front handler\n    expires 30d; ## Assume all files are cachable\n  }\n\n  ## These locations would be hidden by .htaccess normally\n  location /app/                { deny all; }\n  location /includes/           { deny all; }\n  location /lib/                { deny all; }\n  location /media/downloadable/ { deny all; }\n  location /pkginfo/            { deny all; }\n  location /report/config.xml   { deny all; }\n  location /var/                { deny all; }\n\n  location /var/export/ { ## Allow admins only to view export folder\n    auth_basic           \"Restricted\"; ## Message shown in login window\n    auth_basic_user_file htpasswd; ## See /etc/nginx/htpassword\n    autoindex            on;\n  }\n\n  location  /. { ## Disable .htaccess and other hidden files\n    return 404;\n  }\n\n  location @handler { ## Magento uses a common front handler\n    rewrite / /index.php;\n  }\n\n  location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler\n    rewrite ^/(.*.php)/ /$1 last;\n  }\n\n  location ~ .php$ { ## Execute PHP scripts\n    if (!-e $request_filename) { rewrite  /index.php last; } ## Catch 404s that try_files miss\n\n    fastcgi_pass 127.0.0.1:9000;\n    fastcgi_index  index.php;\n    fastcgi_param PATH_INFO $fastcgi_script_name;\n    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;\n    include        /rs/confs/nginx/fastcgi_params;\n\n    fastcgi_param HTTPS on;\n  }\n\n}\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-nginx-conf</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/nginx/nginx.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"nginx\", function(config) {\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  var keywords = words(\n    /* ngxDirectiveControl */ \"break return rewrite set\" +\n    /* ngxDirective */ \" accept_mutex accept_mutex_delay access_log add_after_body add_before_body add_header addition_types aio alias allow ancient_browser ancient_browser_value auth_basic auth_basic_user_file auth_http auth_http_header auth_http_timeout autoindex autoindex_exact_size autoindex_localtime charset charset_types client_body_buffer_size client_body_in_file_only client_body_in_single_buffer client_body_temp_path client_body_timeout client_header_buffer_size client_header_timeout client_max_body_size connection_pool_size create_full_put_path daemon dav_access dav_methods debug_connection debug_points default_type degradation degrade deny devpoll_changes devpoll_events directio directio_alignment empty_gif env epoll_events error_log eventport_events expires fastcgi_bind fastcgi_buffer_size fastcgi_buffers fastcgi_busy_buffers_size fastcgi_cache fastcgi_cache_key fastcgi_cache_methods fastcgi_cache_min_uses fastcgi_cache_path fastcgi_cache_use_stale fastcgi_cache_valid fastcgi_catch_stderr fastcgi_connect_timeout fastcgi_hide_header fastcgi_ignore_client_abort fastcgi_ignore_headers fastcgi_index fastcgi_intercept_errors fastcgi_max_temp_file_size fastcgi_next_upstream fastcgi_param fastcgi_pass_header fastcgi_pass_request_body fastcgi_pass_request_headers fastcgi_read_timeout fastcgi_send_lowat fastcgi_send_timeout fastcgi_split_path_info fastcgi_store fastcgi_store_access fastcgi_temp_file_write_size fastcgi_temp_path fastcgi_upstream_fail_timeout fastcgi_upstream_max_fails flv geoip_city geoip_country google_perftools_profiles gzip gzip_buffers gzip_comp_level gzip_disable gzip_hash gzip_http_version gzip_min_length gzip_no_buffer gzip_proxied gzip_static gzip_types gzip_vary gzip_window if_modified_since ignore_invalid_headers image_filter image_filter_buffer image_filter_jpeg_quality image_filter_transparency imap_auth imap_capabilities imap_client_buffer index ip_hash keepalive_requests keepalive_timeout kqueue_changes kqueue_events large_client_header_buffers limit_conn limit_conn_log_level limit_rate limit_rate_after limit_req limit_req_log_level limit_req_zone limit_zone lingering_time lingering_timeout lock_file log_format log_not_found log_subrequest map_hash_bucket_size map_hash_max_size master_process memcached_bind memcached_buffer_size memcached_connect_timeout memcached_next_upstream memcached_read_timeout memcached_send_timeout memcached_upstream_fail_timeout memcached_upstream_max_fails merge_slashes min_delete_depth modern_browser modern_browser_value msie_padding msie_refresh multi_accept open_file_cache open_file_cache_errors open_file_cache_events open_file_cache_min_uses open_file_cache_valid open_log_file_cache output_buffers override_charset perl perl_modules perl_require perl_set pid pop3_auth pop3_capabilities port_in_redirect postpone_gzipping postpone_output protocol proxy proxy_bind proxy_buffer proxy_buffer_size proxy_buffering proxy_buffers proxy_busy_buffers_size proxy_cache proxy_cache_key proxy_cache_methods proxy_cache_min_uses proxy_cache_path proxy_cache_use_stale proxy_cache_valid proxy_connect_timeout proxy_headers_hash_bucket_size proxy_headers_hash_max_size proxy_hide_header proxy_ignore_client_abort proxy_ignore_headers proxy_intercept_errors proxy_max_temp_file_size proxy_method proxy_next_upstream proxy_pass_error_message proxy_pass_header proxy_pass_request_body proxy_pass_request_headers proxy_read_timeout proxy_redirect proxy_send_lowat proxy_send_timeout proxy_set_body proxy_set_header proxy_ssl_session_reuse proxy_store proxy_store_access proxy_temp_file_write_size proxy_temp_path proxy_timeout proxy_upstream_fail_timeout proxy_upstream_max_fails random_index read_ahead real_ip_header recursive_error_pages request_pool_size reset_timedout_connection resolver resolver_timeout rewrite_log rtsig_overflow_events rtsig_overflow_test rtsig_overflow_threshold rtsig_signo satisfy secure_link_secret send_lowat send_timeout sendfile sendfile_max_chunk server_name_in_redirect server_names_hash_bucket_size server_names_hash_max_size server_tokens set_real_ip_from smtp_auth smtp_capabilities smtp_client_buffer smtp_greeting_delay so_keepalive source_charset ssi ssi_ignore_recycled_buffers ssi_min_file_chunk ssi_silent_errors ssi_types ssi_value_length ssl ssl_certificate ssl_certificate_key ssl_ciphers ssl_client_certificate ssl_crl ssl_dhparam ssl_engine ssl_prefer_server_ciphers ssl_protocols ssl_session_cache ssl_session_timeout ssl_verify_client ssl_verify_depth starttls stub_status sub_filter sub_filter_once sub_filter_types tcp_nodelay tcp_nopush thread_stack_size timeout timer_resolution types_hash_bucket_size types_hash_max_size underscores_in_headers uninitialized_variable_warn use user userid userid_domain userid_expires userid_mark userid_name userid_p3p userid_path userid_service valid_referers variables_hash_bucket_size variables_hash_max_size worker_connections worker_cpu_affinity worker_priority worker_processes worker_rlimit_core worker_rlimit_nofile worker_rlimit_sigpending worker_threads working_directory xclient xml_entities xslt_stylesheet xslt_typesdrew@li229-23\"\n    );\n\n  var keywords_block = words(\n    /* ngxDirectiveBlock */ \"http mail events server types location upstream charset_map limit_except if geo map\"\n    );\n\n  var keywords_important = words(\n    /* ngxDirectiveImportant */ \"include root server server_name listen internal proxy_pass memcached_pass fastcgi_pass try_files\"\n    );\n\n  var indentUnit = config.indentUnit, type;\n  function ret(style, tp) {type = tp; return style;}\n\n  function tokenBase(stream, state) {\n\n\n    stream.eatWhile(/[\\w\\$_]/);\n\n    var cur = stream.current();\n\n\n    if (keywords.propertyIsEnumerable(cur)) {\n      return \"keyword\";\n    }\n    else if (keywords_block.propertyIsEnumerable(cur)) {\n      return \"variable-2\";\n    }\n    else if (keywords_important.propertyIsEnumerable(cur)) {\n      return \"string-2\";\n    }\n    /**/\n\n    var ch = stream.next();\n    if (ch == \"@\") {stream.eatWhile(/[\\w\\\\\\-]/); return ret(\"meta\", stream.current());}\n    else if (ch == \"/\" && stream.eat(\"*\")) {\n      state.tokenize = tokenCComment;\n      return tokenCComment(stream, state);\n    }\n    else if (ch == \"<\" && stream.eat(\"!\")) {\n      state.tokenize = tokenSGMLComment;\n      return tokenSGMLComment(stream, state);\n    }\n    else if (ch == \"=\") ret(null, \"compare\");\n    else if ((ch == \"~\" || ch == \"|\") && stream.eat(\"=\")) return ret(null, \"compare\");\n    else if (ch == \"\\\"\" || ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n    else if (ch == \"#\") {\n      stream.skipToEnd();\n      return ret(\"comment\", \"comment\");\n    }\n    else if (ch == \"!\") {\n      stream.match(/^\\s*\\w*/);\n      return ret(\"keyword\", \"important\");\n    }\n    else if (/\\d/.test(ch)) {\n      stream.eatWhile(/[\\w.%]/);\n      return ret(\"number\", \"unit\");\n    }\n    else if (/[,.+>*\\/]/.test(ch)) {\n      return ret(null, \"select-op\");\n    }\n    else if (/[;{}:\\[\\]]/.test(ch)) {\n      return ret(null, ch);\n    }\n    else {\n      stream.eatWhile(/[\\w\\\\\\-]/);\n      return ret(\"variable\", \"variable\");\n    }\n  }\n\n  function tokenCComment(stream, state) {\n    var maybeEnd = false, ch;\n    while ((ch = stream.next()) != null) {\n      if (maybeEnd && ch == \"/\") {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return ret(\"comment\", \"comment\");\n  }\n\n  function tokenSGMLComment(stream, state) {\n    var dashes = 0, ch;\n    while ((ch = stream.next()) != null) {\n      if (dashes >= 2 && ch == \">\") {\n        state.tokenize = tokenBase;\n        break;\n      }\n      dashes = (ch == \"-\") ? dashes + 1 : 0;\n    }\n    return ret(\"comment\", \"comment\");\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && !escaped)\n          break;\n        escaped = !escaped && ch == \"\\\\\";\n      }\n      if (!escaped) state.tokenize = tokenBase;\n      return ret(\"string\", \"string\");\n    };\n  }\n\n  return {\n    startState: function(base) {\n      return {tokenize: tokenBase,\n              baseIndent: base || 0,\n              stack: []};\n    },\n\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      type = null;\n      var style = state.tokenize(stream, state);\n\n      var context = state.stack[state.stack.length-1];\n      if (type == \"hash\" && context == \"rule\") style = \"atom\";\n      else if (style == \"variable\") {\n        if (context == \"rule\") style = \"number\";\n        else if (!context || context == \"@media{\") style = \"tag\";\n      }\n\n      if (context == \"rule\" && /^[\\{\\};]$/.test(type))\n        state.stack.pop();\n      if (type == \"{\") {\n        if (context == \"@media\") state.stack[state.stack.length-1] = \"@media{\";\n        else state.stack.push(\"{\");\n      }\n      else if (type == \"}\") state.stack.pop();\n      else if (type == \"@media\") state.stack.push(\"@media\");\n      else if (context == \"{\" && type != \"comment\") state.stack.push(\"rule\");\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      var n = state.stack.length;\n      if (/^\\}/.test(textAfter))\n        n -= state.stack[state.stack.length-1] == \"rule\" ? 2 : 1;\n      return state.baseIndent + n * indentUnit;\n    },\n\n    electricChars: \"}\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-nginx-conf\", \"nginx\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/nsis/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: NSIS mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=stylesheet href=../../lib/codemirror.css>\n<script src=../../lib/codemirror.js></script>\n<script src=\"../../addon/mode/simple.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=nsis.js></script>\n<style type=text/css>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">NSIS</a>\n  </ul>\n</div>\n\n<article>\n<h2>NSIS mode</h2>\n\n\n<textarea id=code>\n; This is a comment\n!ifdef ERROR\n    !error \"Something went wrong\"\n!endif\n\nOutFile \"demo.exe\"\nRequestExecutionLevel user\nSetDetailsPrint listonly\n\n!include \"LogicLib.nsh\"\n!include \"WinVer.nsh\"\n\nSection -mandatory\n\n    Call logWinVer\n\n    ${If} 1 > 0\n      MessageBox MB_OK \"Hello world\"\n    ${EndIf}\n\nSectionEnd\n\nFunction logWinVer\n\n    ${If} ${IsWin10}\n        DetailPrint \"Windows 10!\"\n    ${ElseIf} ${AtLeastWinVista}\n        DetailPrint \"We're post-XP\"\n    ${Else}\n        DetailPrint \"Legacy system\"\n    ${EndIf}\n\nFunctionEnd\n</textarea>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById('code'), {\n    mode: 'nsis',\n    indentWithTabs: true,\n    smartIndent: true,\n    lineNumbers: true,\n    matchBrackets: true\n  });\n</script>\n\n<p><strong>MIME types defined:</strong> <code>text/x-nsis</code>.</p>\n</article>"
  },
  {
    "path": "third_party/CodeMirror/mode/nsis/nsis.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Author: Jan T. Sott (http://github.com/idleberg)\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../../addon/mode/simple\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../../addon/mode/simple\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineSimpleMode(\"nsis\",{\n  start:[\n    // Numbers\n    {regex: /(?:[+-]?)(?:0x[\\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\\d+.?\\d*)/, token: \"number\"},\n\n    // Strings\n    { regex: /\"(?:[^\\\\\"]|\\\\.)*\"?/, token: \"string\" },\n    { regex: /'(?:[^\\\\']|\\\\.)*'?/, token: \"string\" },\n    { regex: /`(?:[^\\\\`]|\\\\.)*`?/, token: \"string\" },\n\n    // Compile Time Commands\n    {regex: /^\\s*(?:\\!(include|addincludedir|addplugindir|appendfile|cd|delfile|echo|error|execute|packhdr|pragma|finalize|getdllversion|gettlbversion|system|tempfile|warning|verbose|define|undef|insertmacro|macro|macroend|makensis|searchparse|searchreplace))\\b/, token: \"keyword\"},\n\n    // Conditional Compilation\n    {regex: /^\\s*(?:\\!(if(?:n?def)?|ifmacron?def|macro))\\b/, token: \"keyword\", indent: true},\n    {regex: /^\\s*(?:\\!(else|endif|macroend))\\b/, token: \"keyword\", dedent: true},\n\n    // Runtime Commands\n    {regex: /^\\s*(?:Abort|AddBrandingImage|AddSize|AllowRootDirInstall|AllowSkipFiles|AutoCloseWindow|BGFont|BGGradient|BrandingText|BringToFront|Call|CallInstDLL|Caption|ChangeUI|CheckBitmap|ClearErrors|CompletedText|ComponentText|CopyFiles|CRCCheck|CreateDirectory|CreateFont|CreateShortCut|Delete|DeleteINISec|DeleteINIStr|DeleteRegKey|DeleteRegValue|DetailPrint|DetailsButtonText|DirText|DirVar|DirVerify|EnableWindow|EnumRegKey|EnumRegValue|Exch|Exec|ExecShell|ExecShellWait|ExecWait|ExpandEnvStrings|File|FileBufSize|FileClose|FileErrorText|FileOpen|FileRead|FileReadByte|FileReadUTF16LE|FileReadWord|FileWriteUTF16LE|FileSeek|FileWrite|FileWriteByte|FileWriteWord|FindClose|FindFirst|FindNext|FindWindow|FlushINI|GetCurInstType|GetCurrentAddress|GetDlgItem|GetDLLVersion|GetDLLVersionLocal|GetErrorLevel|GetFileTime|GetFileTimeLocal|GetFullPathName|GetFunctionAddress|GetInstDirError|GetLabelAddress|GetTempFileName|Goto|HideWindow|Icon|IfAbort|IfErrors|IfFileExists|IfRebootFlag|IfSilent|InitPluginsDir|InstallButtonText|InstallColors|InstallDir|InstallDirRegKey|InstProgressFlags|InstType|InstTypeGetText|InstTypeSetText|Int64Cmp|Int64CmpU|Int64Fmt|IntCmp|IntCmpU|IntFmt|IntOp|IntPtrCmp|IntPtrCmpU|IntPtrOp|IsWindow|LangString|LicenseBkColor|LicenseData|LicenseForceSelection|LicenseLangString|LicenseText|LoadLanguageFile|LockWindow|LogSet|LogText|ManifestDPIAware|ManifestSupportedOS|MessageBox|MiscButtonText|Name|Nop|OutFile|Page|PageCallbacks|PEDllCharacteristics|PESubsysVer|Pop|Push|Quit|ReadEnvStr|ReadINIStr|ReadRegDWORD|ReadRegStr|Reboot|RegDLL|Rename|RequestExecutionLevel|ReserveFile|Return|RMDir|SearchPath|SectionGetFlags|SectionGetInstTypes|SectionGetSize|SectionGetText|SectionIn|SectionSetFlags|SectionSetInstTypes|SectionSetSize|SectionSetText|SendMessage|SetAutoClose|SetBrandingImage|SetCompress|SetCompressor|SetCompressorDictSize|SetCtlColors|SetCurInstType|SetDatablockOptimize|SetDateSave|SetDetailsPrint|SetDetailsView|SetErrorLevel|SetErrors|SetFileAttributes|SetFont|SetOutPath|SetOverwrite|SetRebootFlag|SetRegView|SetShellVarContext|SetSilent|ShowInstDetails|ShowUninstDetails|ShowWindow|SilentInstall|SilentUnInstall|Sleep|SpaceTexts|StrCmp|StrCmpS|StrCpy|StrLen|SubCaption|Unicode|UninstallButtonText|UninstallCaption|UninstallIcon|UninstallSubCaption|UninstallText|UninstPage|UnRegDLL|Var|VIAddVersionKey|VIFileVersion|VIProductVersion|WindowIcon|WriteINIStr|WriteRegBin|WriteRegDWORD|WriteRegExpandStr|WriteRegMultiStr|WriteRegNone|WriteRegStr|WriteUninstaller|XPStyle)\\b/, token: \"keyword\"},\n    {regex: /^\\s*(?:Function|PageEx|Section(?:Group)?)\\b/, token: \"keyword\", indent: true},\n    {regex: /^\\s*(?:(Function|PageEx|Section(?:Group)?)End)\\b/, token: \"keyword\", dedent: true},\n\n    // Command Options\n    {regex: /\\b(?:ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HIDDEN|HKCC|HKCR(32|64)?|HKCU(32|64)?|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM(32|64)?|HKPD|HKU|IDABORT|IDCANCEL|IDD_DIR|IDD_INST|IDD_INSTFILES|IDD_LICENSE|IDD_SELCOM|IDD_UNINST|IDD_VERIFY|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|MB_YESNOCANCEL|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SW_HIDE|SW_SHOWDEFAULT|SW_SHOWMAXIMIZED|SW_SHOWMINIMIZED|SW_SHOWNORMAL|SYSTEM|TEMPORARY)\\b/, token: \"atom\"},\n    {regex: /\\b(?:admin|all|auto|both|bottom|bzip2|components|current|custom|directory|false|force|hide|highest|ifdiff|ifnewer|instfiles|lastused|leave|left|license|listonly|lzma|nevershow|none|normal|notset|off|on|right|show|silent|silentlog|textonly|top|true|try|un\\.components|un\\.custom|un\\.directory|un\\.instfiles|un\\.license|uninstConfirm|user|Win10|Win7|Win8|WinVista|zlib)\\b/, token: \"builtin\"},\n\n    // LogicLib.nsh\n    {regex: /\\$\\{(?:And(?:If(?:Not)?|Unless)|Break|Case(?:Else)?|Continue|Default|Do(?:Until|While)?|Else(?:If(?:Not)?|Unless)?|End(?:If|Select|Switch)|Exit(?:Do|For|While)|For(?:Each)?|If(?:Cmd|Not(?:Then)?|Then)?|Loop(?:Until|While)?|Or(?:If(?:Not)?|Unless)|Select|Switch|Unless|While)\\}/, token: \"variable-2\", indent: true},\n\n    // FileFunc.nsh\n    {regex: /\\$\\{(?:BannerTrimPath|DirState|DriveSpace|Get(BaseName|Drives|ExeName|ExePath|FileAttributes|FileExt|FileName|FileVersion|Options|OptionsS|Parameters|Parent|Root|Size|Time)|Locate|RefreshShellIcons)\\}/, token: \"variable-2\", dedent: true},\n\n    // Memento.nsh\n    {regex: /\\$\\{(?:Memento(?:Section(?:Done|End|Restore|Save)?|UnselectedSection))\\}/, token: \"variable-2\", dedent: true},\n\n    // TextFunc.nsh\n    {regex: /\\$\\{(?:Config(?:Read|ReadS|Write|WriteS)|File(?:Join|ReadFromEnd|Recode)|Line(?:Find|Read|Sum)|Text(?:Compare|CompareS)|TrimNewLines)\\}/, token: \"variable-2\", dedent: true},\n\n    // WinVer.nsh\n    {regex: /\\$\\{(?:(?:At(?:Least|Most)|Is)(?:ServicePack|Win(?:7|8|10|95|98|200(?:0|3|8(?:R2)?)|ME|NT4|Vista|XP))|Is(?:NT|Server))\\}/, token: \"variable\", dedent: true},\n\n    // WordFunc.nsh\n    {regex: /\\$\\{(?:StrFilterS?|Version(?:Compare|Convert)|Word(?:AddS?|Find(?:(?:2|3)X)?S?|InsertS?|ReplaceS?))\\}/, token: \"variable-2\", dedent: true},\n\n    // x64.nsh\n    {regex: /\\$\\{(?:RunningX64)\\}/, token: \"variable\", dedent: true},\n    {regex: /\\$\\{(?:Disable|Enable)X64FSRedirection\\}/, token: \"variable-2\", dedent: true},\n\n    // Line Comment\n    {regex: /(#|;).*/, token: \"comment\"},\n\n    // Block Comment\n    {regex: /\\/\\*/, token: \"comment\", next: \"comment\"},\n\n    // Operator\n    {regex: /[-+\\/*=<>!]+/, token: \"operator\"},\n\n    // Variable\n    {regex: /\\$\\w+/, token: \"variable\"},\n\n    // Constant\n    {regex: /\\${[\\w\\.:-]+}/, token: \"variable-2\"},\n\n    // Language String\n    {regex: /\\$\\([\\w\\.:-]+\\)/, token: \"variable-3\"}\n  ],\n  comment: [\n    {regex: /.*?\\*\\//, token: \"comment\", next: \"start\"},\n    {regex: /.*/, token: \"comment\"}\n  ],\n  meta: {\n    electricInput: /^\\s*((Function|PageEx|Section|Section(Group)?)End|(\\!(endif|macroend))|\\$\\{(End(If|Unless|While)|Loop(Until)|Next)\\})$/,\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    lineComment: [\"#\", \";\"]\n  }\n});\n\nCodeMirror.defineMIME(\"text/x-nsis\", \"nsis\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ntriples/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: N-Triples mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"ntriples.js\"></script>\n<style>\n      .CodeMirror {\n        border: 1px solid #eee;\n        height: auto;\n      }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">N-Triples/N-Quads</a>\n  </ul>\n</div>\n\n<article>\n  <h2><a href=\"https://www.w3.org/TR/n-triples/\">N-Triples</a> mode</h2>\n  <p>The N-Triples mode also works well with on\n    <a href=\"https://www.w3.org/TR/n-quads/\">N-Quad</a> documents.\n  </p>\n<form>\n<textarea id=\"ntriples\" name=\"ntriples\">    \n<http://Sub1>     <http://pred1>     <http://obj> .\n<http://Sub2>     <http://pred2#an2> \"literal 1\" .\n<http://Sub3#an3> <http://pred3>     _:bnode3 .\n_:bnode4          <http://pred4>     \"literal 2\"@lang .\n_:bnode5          <http://pred5>     \"literal 3\"^^<http://type> .\n</textarea>\n</form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"ntriples\"), {});\n    </script>\n    <p><strong>MIME types defined:</strong> <code>application/n-triples</code>.</p>\n\n    <hr />\n    <p><a href=\"https://www.w3.org/TR/n-quads/\">N-Quads</a> add a fourth\n    element to the statement to track which graph the statement is from.\n    Otherwise, it's identical to N-Triples.</p>\n    <form>\n    <textarea id=\"nquads\" name=\"nquads\">\n\n    <http://Sub1>     <http://pred1>     <http://obj>   <http://graph3> .\n    <http://Sub2>     <http://pred2#an2> \"literal 1\"    <http://graph2> .\n    <http://Sub3#an3> <http://pred3>     _:bnode3     <http://graph2> .\n    _:bnode4          <http://pred4>     \"literal 2\"@lang     <http://graph2> .\n    # if a graph labe\n    _:bnode5          <http://pred5>     \"literal 3\"^^<http://type> .\n    </textarea>\n    </form>\n\n    <script>\n      var nquads_editor = CodeMirror.fromTextArea(document.getElementById(\"nquads\"), {});\n    </script>\n    <p><strong>MIME types defined:</strong> <code>application/n-quads</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ntriples/ntriples.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**********************************************************\n* This script provides syntax highlighting support for\n* the N-Triples format.\n* N-Triples format specification:\n*     https://www.w3.org/TR/n-triples/\n***********************************************************/\n\n/*\n    The following expression defines the defined ASF grammar transitions.\n\n    pre_subject ->\n        {\n        ( writing_subject_uri | writing_bnode_uri )\n            -> pre_predicate\n                -> writing_predicate_uri\n                    -> pre_object\n                        -> writing_object_uri | writing_object_bnode |\n                          (\n                            writing_object_literal\n                                -> writing_literal_lang | writing_literal_type\n                          )\n                            -> post_object\n                                -> BEGIN\n         } otherwise {\n             -> ERROR\n         }\n*/\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"ntriples\", function() {\n\n  var Location = {\n    PRE_SUBJECT         : 0,\n    WRITING_SUB_URI     : 1,\n    WRITING_BNODE_URI   : 2,\n    PRE_PRED            : 3,\n    WRITING_PRED_URI    : 4,\n    PRE_OBJ             : 5,\n    WRITING_OBJ_URI     : 6,\n    WRITING_OBJ_BNODE   : 7,\n    WRITING_OBJ_LITERAL : 8,\n    WRITING_LIT_LANG    : 9,\n    WRITING_LIT_TYPE    : 10,\n    POST_OBJ            : 11,\n    ERROR               : 12\n  };\n  function transitState(currState, c) {\n    var currLocation = currState.location;\n    var ret;\n\n    // Opening.\n    if     (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI;\n    else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI;\n    else if(currLocation == Location.PRE_PRED    && c == '<') ret = Location.WRITING_PRED_URI;\n    else if(currLocation == Location.PRE_OBJ     && c == '<') ret = Location.WRITING_OBJ_URI;\n    else if(currLocation == Location.PRE_OBJ     && c == '_') ret = Location.WRITING_OBJ_BNODE;\n    else if(currLocation == Location.PRE_OBJ     && c == '\"') ret = Location.WRITING_OBJ_LITERAL;\n\n    // Closing.\n    else if(currLocation == Location.WRITING_SUB_URI     && c == '>') ret = Location.PRE_PRED;\n    else if(currLocation == Location.WRITING_BNODE_URI   && c == ' ') ret = Location.PRE_PRED;\n    else if(currLocation == Location.WRITING_PRED_URI    && c == '>') ret = Location.PRE_OBJ;\n    else if(currLocation == Location.WRITING_OBJ_URI     && c == '>') ret = Location.POST_OBJ;\n    else if(currLocation == Location.WRITING_OBJ_BNODE   && c == ' ') ret = Location.POST_OBJ;\n    else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '\"') ret = Location.POST_OBJ;\n    else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ;\n    else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ;\n\n    // Closing typed and language literal.\n    else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG;\n    else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE;\n\n    // Spaces.\n    else if( c == ' ' &&\n             (\n               currLocation == Location.PRE_SUBJECT ||\n               currLocation == Location.PRE_PRED    ||\n               currLocation == Location.PRE_OBJ     ||\n               currLocation == Location.POST_OBJ\n             )\n           ) ret = currLocation;\n\n    // Reset.\n    else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT;\n\n    // Error\n    else ret = Location.ERROR;\n\n    currState.location=ret;\n  }\n\n  return {\n    startState: function() {\n       return {\n           location : Location.PRE_SUBJECT,\n           uris     : [],\n           anchors  : [],\n           bnodes   : [],\n           langs    : [],\n           types    : []\n       };\n    },\n    token: function(stream, state) {\n      var ch = stream.next();\n      if(ch == '<') {\n         transitState(state, ch);\n         var parsedURI = '';\n         stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} );\n         state.uris.push(parsedURI);\n         if( stream.match('#', false) ) return 'variable';\n         stream.next();\n         transitState(state, '>');\n         return 'variable';\n      }\n      if(ch == '#') {\n        var parsedAnchor = '';\n        stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false;});\n        state.anchors.push(parsedAnchor);\n        return 'variable-2';\n      }\n      if(ch == '>') {\n          transitState(state, '>');\n          return 'variable';\n      }\n      if(ch == '_') {\n          transitState(state, ch);\n          var parsedBNode = '';\n          stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;});\n          state.bnodes.push(parsedBNode);\n          stream.next();\n          transitState(state, ' ');\n          return 'builtin';\n      }\n      if(ch == '\"') {\n          transitState(state, ch);\n          stream.eatWhile( function(c) { return c != '\"'; } );\n          stream.next();\n          if( stream.peek() != '@' && stream.peek() != '^' ) {\n              transitState(state, '\"');\n          }\n          return 'string';\n      }\n      if( ch == '@' ) {\n          transitState(state, '@');\n          var parsedLang = '';\n          stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;});\n          state.langs.push(parsedLang);\n          stream.next();\n          transitState(state, ' ');\n          return 'string-2';\n      }\n      if( ch == '^' ) {\n          stream.next();\n          transitState(state, '^');\n          var parsedType = '';\n          stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} );\n          state.types.push(parsedType);\n          stream.next();\n          transitState(state, '>');\n          return 'variable';\n      }\n      if( ch == ' ' ) {\n          transitState(state, ch);\n      }\n      if( ch == '.' ) {\n          transitState(state, ch);\n      }\n    }\n  };\n});\n\n// define the registered Media Type for n-triples:\n// https://www.w3.org/TR/n-triples/#n-triples-mediatype\nCodeMirror.defineMIME(\"application/n-triples\", \"ntriples\");\n\n// N-Quads is based on the N-Triples format (so same highlighting works)\n// https://www.w3.org/TR/n-quads/\nCodeMirror.defineMIME(\"application/n-quads\", \"ntriples\");\n\n// previously used, though technically incorrect media type for n-triples\nCodeMirror.defineMIME(\"text/n-triples\", \"ntriples\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/octave/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Octave mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"octave.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Octave</a>\n  </ul>\n</div>\n\n<article>\n<h2>Octave mode</h2>\n\n    <div><textarea id=\"code\" name=\"code\">\n%numbers\n[1234 1234i 1234j]\n[.234 .234j 2.23i]\n[23e2 12E1j 123D-4 0x234]\n\n%strings\n'asda''a'\n\"asda\"\"a\"\n\n%identifiers\na + as123 - __asd__\n\n%operators\n-\n+\n=\n==\n>\n<\n>=\n<=\n&\n~\n...\nbreak zeros default margin round ones rand\nceil floor size clear zeros eye mean std cov\nerror eval function\nabs acos atan asin cos cosh exp log prod sum\nlog10 max min sign sin sinh sqrt tan reshape\nreturn\ncase switch\nelse elseif end if otherwise\ndo for while\ntry catch\nclassdef properties events methods\nglobal persistent\n\n%one line comment\n%{ multi \nline comment %}\n\n    </textarea></div>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"octave\",\n               version: 2,\n               singleLineStringErrors: false},\n        lineNumbers: true,\n        indentUnit: 4,\n        matchBrackets: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-octave</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/octave/octave.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"octave\", function() {\n  function wordRegexp(words) {\n    return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n  }\n\n  var singleOperators = new RegExp(\"^[\\\\+\\\\-\\\\*/&|\\\\^~<>!@'\\\\\\\\]\");\n  var singleDelimiters = new RegExp('^[\\\\(\\\\[\\\\{\\\\},:=;]');\n  var doubleOperators = new RegExp(\"^((==)|(~=)|(<=)|(>=)|(<<)|(>>)|(\\\\.[\\\\+\\\\-\\\\*/\\\\^\\\\\\\\]))\");\n  var doubleDelimiters = new RegExp(\"^((!=)|(\\\\+=)|(\\\\-=)|(\\\\*=)|(/=)|(&=)|(\\\\|=)|(\\\\^=))\");\n  var tripleDelimiters = new RegExp(\"^((>>=)|(<<=))\");\n  var expressionEnd = new RegExp(\"^[\\\\]\\\\)]\");\n  var identifiers = new RegExp(\"^[_A-Za-z\\xa1-\\uffff][_A-Za-z0-9\\xa1-\\uffff]*\");\n\n  var builtins = wordRegexp([\n    'error', 'eval', 'function', 'abs', 'acos', 'atan', 'asin', 'cos',\n    'cosh', 'exp', 'log', 'prod', 'sum', 'log10', 'max', 'min', 'sign', 'sin', 'sinh',\n    'sqrt', 'tan', 'reshape', 'break', 'zeros', 'default', 'margin', 'round', 'ones',\n    'rand', 'syn', 'ceil', 'floor', 'size', 'clear', 'zeros', 'eye', 'mean', 'std', 'cov',\n    'det', 'eig', 'inv', 'norm', 'rank', 'trace', 'expm', 'logm', 'sqrtm', 'linspace', 'plot',\n    'title', 'xlabel', 'ylabel', 'legend', 'text', 'grid', 'meshgrid', 'mesh', 'num2str',\n    'fft', 'ifft', 'arrayfun', 'cellfun', 'input', 'fliplr', 'flipud', 'ismember'\n  ]);\n\n  var keywords = wordRegexp([\n    'return', 'case', 'switch', 'else', 'elseif', 'end', 'endif', 'endfunction',\n    'if', 'otherwise', 'do', 'for', 'while', 'try', 'catch', 'classdef', 'properties', 'events',\n    'methods', 'global', 'persistent', 'endfor', 'endwhile', 'printf', 'sprintf', 'disp', 'until',\n    'continue', 'pkg'\n  ]);\n\n\n  // tokenizers\n  function tokenTranspose(stream, state) {\n    if (!stream.sol() && stream.peek() === '\\'') {\n      stream.next();\n      state.tokenize = tokenBase;\n      return 'operator';\n    }\n    state.tokenize = tokenBase;\n    return tokenBase(stream, state);\n  }\n\n\n  function tokenComment(stream, state) {\n    if (stream.match(/^.*%}/)) {\n      state.tokenize = tokenBase;\n      return 'comment';\n    };\n    stream.skipToEnd();\n    return 'comment';\n  }\n\n  function tokenBase(stream, state) {\n    // whitespaces\n    if (stream.eatSpace()) return null;\n\n    // Handle one line Comments\n    if (stream.match('%{')){\n      state.tokenize = tokenComment;\n      stream.skipToEnd();\n      return 'comment';\n    }\n\n    if (stream.match(/^[%#]/)){\n      stream.skipToEnd();\n      return 'comment';\n    }\n\n    // Handle Number Literals\n    if (stream.match(/^[0-9\\.+-]/, false)) {\n      if (stream.match(/^[+-]?0x[0-9a-fA-F]+[ij]?/)) {\n        stream.tokenize = tokenBase;\n        return 'number'; };\n      if (stream.match(/^[+-]?\\d*\\.\\d+([EeDd][+-]?\\d+)?[ij]?/)) { return 'number'; };\n      if (stream.match(/^[+-]?\\d+([EeDd][+-]?\\d+)?[ij]?/)) { return 'number'; };\n    }\n    if (stream.match(wordRegexp(['nan','NaN','inf','Inf']))) { return 'number'; };\n\n    // Handle Strings\n    var m = stream.match(/^\"(?:[^\"]|\"\")*(\"|$)/) || stream.match(/^'(?:[^']|'')*('|$)/)\n    if (m) { return m[1] ? 'string' : \"string error\"; }\n\n    // Handle words\n    if (stream.match(keywords)) { return 'keyword'; } ;\n    if (stream.match(builtins)) { return 'builtin'; } ;\n    if (stream.match(identifiers)) { return 'variable'; } ;\n\n    if (stream.match(singleOperators) || stream.match(doubleOperators)) { return 'operator'; };\n    if (stream.match(singleDelimiters) || stream.match(doubleDelimiters) || stream.match(tripleDelimiters)) { return null; };\n\n    if (stream.match(expressionEnd)) {\n      state.tokenize = tokenTranspose;\n      return null;\n    };\n\n\n    // Handle non-detected items\n    stream.next();\n    return 'error';\n  };\n\n\n  return {\n    startState: function() {\n      return {\n        tokenize: tokenBase\n      };\n    },\n\n    token: function(stream, state) {\n      var style = state.tokenize(stream, state);\n      if (style === 'number' || style === 'variable'){\n        state.tokenize = tokenTranspose;\n      }\n      return style;\n    },\n\n    lineComment: '%',\n\n    fold: 'indent'\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-octave\", \"octave\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/oz/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Oz mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"oz.js\"></script>\n<script src=\"../../addon/runmode/runmode.js\"></script>\n<style>\n  .CodeMirror {border: 1px solid #aaa;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Oz</a>\n  </ul>\n</div>\n\n<article>\n<h2>Oz mode</h2>\n<textarea id=\"code\" name=\"code\">\ndeclare\nfun {Ints N Max}\n  if N == Max then nil\n  else\n    {Delay 1000}\n    N|{Ints N+1 Max}\n  end\nend\n\nfun {Sum S Stream}\n  case Stream of nil then S\n  [] H|T then S|{Sum H+S T} end\nend\n\nlocal X Y in\n  thread X = {Ints 0 1000} end\n  thread Y = {Sum 0 X} end\n  {Browse Y}\nend\n</textarea>\n<p>MIME type defined: <code>text/x-oz</code>.</p>\n\n<script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    mode: \"text/x-oz\",\n    readOnly: false\n});\n</script>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/oz/oz.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"oz\", function (conf) {\n\n  function wordRegexp(words) {\n    return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n  }\n\n  var singleOperators = /[\\^@!\\|<>#~\\.\\*\\-\\+\\\\/,=]/;\n  var doubleOperators = /(<-)|(:=)|(=<)|(>=)|(<=)|(<:)|(>:)|(=:)|(\\\\=)|(\\\\=:)|(!!)|(==)|(::)/;\n  var tripleOperators = /(:::)|(\\.\\.\\.)|(=<:)|(>=:)/;\n\n  var middle = [\"in\", \"then\", \"else\", \"of\", \"elseof\", \"elsecase\", \"elseif\", \"catch\",\n    \"finally\", \"with\", \"require\", \"prepare\", \"import\", \"export\", \"define\", \"do\"];\n  var end = [\"end\"];\n\n  var atoms = wordRegexp([\"true\", \"false\", \"nil\", \"unit\"]);\n  var commonKeywords = wordRegexp([\"andthen\", \"at\", \"attr\", \"declare\", \"feat\", \"from\", \"lex\",\n    \"mod\", \"div\", \"mode\", \"orelse\", \"parser\", \"prod\", \"prop\", \"scanner\", \"self\", \"syn\", \"token\"]);\n  var openingKeywords = wordRegexp([\"local\", \"proc\", \"fun\", \"case\", \"class\", \"if\", \"cond\", \"or\", \"dis\",\n    \"choice\", \"not\", \"thread\", \"try\", \"raise\", \"lock\", \"for\", \"suchthat\", \"meth\", \"functor\"]);\n  var middleKeywords = wordRegexp(middle);\n  var endKeywords = wordRegexp(end);\n\n  // Tokenizers\n  function tokenBase(stream, state) {\n    if (stream.eatSpace()) {\n      return null;\n    }\n\n    // Brackets\n    if(stream.match(/[{}]/)) {\n      return \"bracket\";\n    }\n\n    // Special [] keyword\n    if (stream.match(/(\\[])/)) {\n        return \"keyword\"\n    }\n\n    // Operators\n    if (stream.match(tripleOperators) || stream.match(doubleOperators)) {\n      return \"operator\";\n    }\n\n    // Atoms\n    if(stream.match(atoms)) {\n      return 'atom';\n    }\n\n    // Opening keywords\n    var matched = stream.match(openingKeywords);\n    if (matched) {\n      if (!state.doInCurrentLine)\n        state.currentIndent++;\n      else\n        state.doInCurrentLine = false;\n\n      // Special matching for signatures\n      if(matched[0] == \"proc\" || matched[0] == \"fun\")\n        state.tokenize = tokenFunProc;\n      else if(matched[0] == \"class\")\n        state.tokenize = tokenClass;\n      else if(matched[0] == \"meth\")\n        state.tokenize = tokenMeth;\n\n      return 'keyword';\n    }\n\n    // Middle and other keywords\n    if (stream.match(middleKeywords) || stream.match(commonKeywords)) {\n      return \"keyword\"\n    }\n\n    // End keywords\n    if (stream.match(endKeywords)) {\n      state.currentIndent--;\n      return 'keyword';\n    }\n\n    // Eat the next char for next comparisons\n    var ch = stream.next();\n\n    // Strings\n    if (ch == '\"' || ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n\n    // Numbers\n    if (/[~\\d]/.test(ch)) {\n      if (ch == \"~\") {\n        if(! /^[0-9]/.test(stream.peek()))\n          return null;\n        else if (( stream.next() == \"0\" && stream.match(/^[xX][0-9a-fA-F]+/)) || stream.match(/^[0-9]*(\\.[0-9]+)?([eE][~+]?[0-9]+)?/))\n          return \"number\";\n      }\n\n      if ((ch == \"0\" && stream.match(/^[xX][0-9a-fA-F]+/)) || stream.match(/^[0-9]*(\\.[0-9]+)?([eE][~+]?[0-9]+)?/))\n        return \"number\";\n\n      return null;\n    }\n\n    // Comments\n    if (ch == \"%\") {\n      stream.skipToEnd();\n      return 'comment';\n    }\n    else if (ch == \"/\") {\n      if (stream.eat(\"*\")) {\n        state.tokenize = tokenComment;\n        return tokenComment(stream, state);\n      }\n    }\n\n    // Single operators\n    if(singleOperators.test(ch)) {\n      return \"operator\";\n    }\n\n    // If nothing match, we skip the entire alphanumerical block\n    stream.eatWhile(/\\w/);\n\n    return \"variable\";\n  }\n\n  function tokenClass(stream, state) {\n    if (stream.eatSpace()) {\n      return null;\n    }\n    stream.match(/([A-Z][A-Za-z0-9_]*)|(`.+`)/);\n    state.tokenize = tokenBase;\n    return \"variable-3\"\n  }\n\n  function tokenMeth(stream, state) {\n    if (stream.eatSpace()) {\n      return null;\n    }\n    stream.match(/([a-zA-Z][A-Za-z0-9_]*)|(`.+`)/);\n    state.tokenize = tokenBase;\n    return \"def\"\n  }\n\n  function tokenFunProc(stream, state) {\n    if (stream.eatSpace()) {\n      return null;\n    }\n\n    if(!state.hasPassedFirstStage && stream.eat(\"{\")) {\n      state.hasPassedFirstStage = true;\n      return \"bracket\";\n    }\n    else if(state.hasPassedFirstStage) {\n      stream.match(/([A-Z][A-Za-z0-9_]*)|(`.+`)|\\$/);\n      state.hasPassedFirstStage = false;\n      state.tokenize = tokenBase;\n      return \"def\"\n    }\n    else {\n      state.tokenize = tokenBase;\n      return null;\n    }\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function tokenString(quote) {\n    return function (stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {\n          end = true;\n          break;\n        }\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end || !escaped)\n        state.tokenize = tokenBase;\n      return \"string\";\n    };\n  }\n\n  function buildElectricInputRegEx() {\n    // Reindentation should occur on [] or on a match of any of\n    // the block closing keywords, at the end of a line.\n    var allClosings = middle.concat(end);\n    return new RegExp(\"[\\\\[\\\\]]|(\" + allClosings.join(\"|\") + \")$\");\n  }\n\n  return {\n\n    startState: function () {\n      return {\n        tokenize: tokenBase,\n        currentIndent: 0,\n        doInCurrentLine: false,\n        hasPassedFirstStage: false\n      };\n    },\n\n    token: function (stream, state) {\n      if (stream.sol())\n        state.doInCurrentLine = 0;\n\n      return state.tokenize(stream, state);\n    },\n\n    indent: function (state, textAfter) {\n      var trueText = textAfter.replace(/^\\s+|\\s+$/g, '');\n\n      if (trueText.match(endKeywords) || trueText.match(middleKeywords) || trueText.match(/(\\[])/))\n        return conf.indentUnit * (state.currentIndent - 1);\n\n      if (state.currentIndent < 0)\n        return 0;\n\n      return state.currentIndent * conf.indentUnit;\n    },\n    fold: \"indent\",\n    electricInput: buildElectricInputRegEx(),\n    lineComment: \"%\",\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-oz\", \"oz\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/pascal/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Pascal mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"pascal.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Pascal</a>\n  </ul>\n</div>\n\n<article>\n<h2>Pascal mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n(* Example Pascal code *)\n\nwhile a <> b do writeln('Waiting');\n \nif a > b then \n  writeln('Condition met')\nelse \n  writeln('Condition not met');\n \nfor i := 1 to 10 do \n  writeln('Iteration: ', i:1);\n \nrepeat\n  a := a + 1\nuntil a = 10;\n \ncase i of\n  0: write('zero');\n  1: write('one');\n  2: write('two')\nend;\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"text/x-pascal\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-pascal</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/pascal/pascal.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"pascal\", function() {\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n  var keywords = words(\n    \"absolute and array asm begin case const constructor destructor div do \" +\n    \"downto else end file for function goto if implementation in inherited \" +\n    \"inline interface label mod nil not object of operator or packed procedure \" +\n    \"program record reintroduce repeat self set shl shr string then to type \" +\n    \"unit until uses var while with xor as class dispinterface except exports \" +\n    \"finalization finally initialization inline is library on out packed \" +\n    \"property raise resourcestring threadvar try absolute abstract alias \" +\n    \"assembler bitpacked break cdecl continue cppdecl cvar default deprecated \" +\n    \"dynamic enumerator experimental export external far far16 forward generic \" +\n    \"helper implements index interrupt iocheck local message name near \" +\n    \"nodefault noreturn nostackframe oldfpccall otherwise overload override \" +\n    \"pascal platform private protected public published read register \" +\n    \"reintroduce result safecall saveregisters softfloat specialize static \" +\n    \"stdcall stored strict unaligned unimplemented varargs virtual write\");\n  var atoms = {\"null\": true};\n\n  var isOperatorChar = /[+\\-*&%=<>!?|\\/]/;\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (ch == \"#\" && state.startOfLine) {\n      stream.skipToEnd();\n      return \"meta\";\n    }\n    if (ch == '\"' || ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n    if (ch == \"(\" && stream.eat(\"*\")) {\n      state.tokenize = tokenComment;\n      return tokenComment(stream, state);\n    }\n    if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n      return null;\n    }\n    if (/\\d/.test(ch)) {\n      stream.eatWhile(/[\\w\\.]/);\n      return \"number\";\n    }\n    if (ch == \"/\") {\n      if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n    }\n    if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return \"operator\";\n    }\n    stream.eatWhile(/[\\w\\$_]/);\n    var cur = stream.current();\n    if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n    if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n    return \"variable\";\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {end = true; break;}\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end || !escaped) state.tokenize = null;\n      return \"string\";\n    };\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \")\" && maybeEnd) {\n        state.tokenize = null;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  // Interface\n\n  return {\n    startState: function() {\n      return {tokenize: null};\n    },\n\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      var style = (state.tokenize || tokenBase)(stream, state);\n      if (style == \"comment\" || style == \"meta\") return style;\n      return style;\n    },\n\n    electricChars: \"{}\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-pascal\", \"pascal\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/pegjs/index.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <title>CodeMirror: PEG.js Mode</title>\n    <meta charset=\"utf-8\"/>\n    <link rel=stylesheet href=\"../../doc/docs.css\">\n\n    <link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n    <script src=\"../../lib/codemirror.js\"></script>\n    <script src=\"../javascript/javascript.js\"></script>\n    <script src=\"pegjs.js\"></script>\n    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n  </head>\n  <body>\n    <div id=nav>\n      <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n      <ul>\n        <li><a href=\"../../index.html\">Home</a>\n        <li><a href=\"../../doc/manual.html\">Manual</a>\n        <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n      </ul>\n      <ul>\n        <li><a href=\"../index.html\">Language modes</a>\n        <li><a class=active href=\"#\">PEG.js Mode</a>\n      </ul>\n    </div>\n\n    <article>\n      <h2>PEG.js Mode</h2>\n      <form><textarea id=\"code\" name=\"code\">\n/*\n * Classic example grammar, which recognizes simple arithmetic expressions like\n * \"2*(3+4)\". The parser generated from this grammar then computes their value.\n */\n\nstart\n  = additive\n\nadditive\n  = left:multiplicative \"+\" right:additive { return left + right; }\n  / multiplicative\n\nmultiplicative\n  = left:primary \"*\" right:multiplicative { return left * right; }\n  / primary\n\nprimary\n  = integer\n  / \"(\" additive:additive \")\" { return additive; }\n\ninteger \"integer\"\n  = digits:[0-9]+ { return parseInt(digits.join(\"\"), 10); }\n\nletter = [a-z]+</textarea></form>\n      <script>\n        var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n          mode: {name: \"pegjs\"},\n          lineNumbers: true\n        });\n      </script>\n      <h3>The PEG.js Mode</h3>\n      <p> Created by Forbes Lindesay.</p>\n    </article>\n  </body>\n</html>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/pegjs/pegjs.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../javascript/javascript\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../javascript/javascript\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"pegjs\", function (config) {\n  var jsMode = CodeMirror.getMode(config, \"javascript\");\n\n  function identifier(stream) {\n    return stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);\n  }\n\n  return {\n    startState: function () {\n      return {\n        inString: false,\n        stringType: null,\n        inComment: false,\n        inCharacterClass: false,\n        braced: 0,\n        lhs: true,\n        localState: null\n      };\n    },\n    token: function (stream, state) {\n      if (stream)\n\n      //check for state changes\n      if (!state.inString && !state.inComment && ((stream.peek() == '\"') || (stream.peek() == \"'\"))) {\n        state.stringType = stream.peek();\n        stream.next(); // Skip quote\n        state.inString = true; // Update state\n      }\n      if (!state.inString && !state.inComment && stream.match(/^\\/\\*/)) {\n        state.inComment = true;\n      }\n\n      //return state\n      if (state.inString) {\n        while (state.inString && !stream.eol()) {\n          if (stream.peek() === state.stringType) {\n            stream.next(); // Skip quote\n            state.inString = false; // Clear flag\n          } else if (stream.peek() === '\\\\') {\n            stream.next();\n            stream.next();\n          } else {\n            stream.match(/^.[^\\\\\\\"\\']*/);\n          }\n        }\n        return state.lhs ? \"property string\" : \"string\"; // Token style\n      } else if (state.inComment) {\n        while (state.inComment && !stream.eol()) {\n          if (stream.match(/\\*\\//)) {\n            state.inComment = false; // Clear flag\n          } else {\n            stream.match(/^.[^\\*]*/);\n          }\n        }\n        return \"comment\";\n      } else if (state.inCharacterClass) {\n          while (state.inCharacterClass && !stream.eol()) {\n            if (!(stream.match(/^[^\\]\\\\]+/) || stream.match(/^\\\\./))) {\n              state.inCharacterClass = false;\n            }\n          }\n      } else if (stream.peek() === '[') {\n        stream.next();\n        state.inCharacterClass = true;\n        return 'bracket';\n      } else if (stream.match(/^\\/\\//)) {\n        stream.skipToEnd();\n        return \"comment\";\n      } else if (state.braced || stream.peek() === '{') {\n        if (state.localState === null) {\n          state.localState = CodeMirror.startState(jsMode);\n        }\n        var token = jsMode.token(stream, state.localState);\n        var text = stream.current();\n        if (!token) {\n          for (var i = 0; i < text.length; i++) {\n            if (text[i] === '{') {\n              state.braced++;\n            } else if (text[i] === '}') {\n              state.braced--;\n            }\n          };\n        }\n        return token;\n      } else if (identifier(stream)) {\n        if (stream.peek() === ':') {\n          return 'variable';\n        }\n        return 'variable-2';\n      } else if (['[', ']', '(', ')'].indexOf(stream.peek()) != -1) {\n        stream.next();\n        return 'bracket';\n      } else if (!stream.eatSpace()) {\n        stream.next();\n      }\n      return null;\n    }\n  };\n}, \"javascript\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/perl/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Perl mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"perl.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Perl</a>\n  </ul>\n</div>\n\n<article>\n<h2>Perl mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n#!/usr/bin/perl\n\nuse Something qw(func1 func2);\n\n# strings\nmy $s1 = qq'single line';\nour $s2 = q(multi-\n              line);\n\n=item Something\n\tExample.\n=cut\n\nmy $html=<<'HTML'\n<html>\n<title>hi!</title>\n</html>\nHTML\n\nprint \"first,\".join(',', 'second', qq~third~);\n\nif($s1 =~ m[(?<!\\s)(l.ne)\\z]o) {\n\t$h->{$1}=$$.' predefined variables';\n\t$s2 =~ s/\\-line//ox;\n\t$s1 =~ s[\n\t\t  line ]\n\t\t[\n\t\t  block\n\t\t]ox;\n}\n\n1; # numbers and comments\n\n__END__\nsomething...\n\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-perl</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/perl/perl.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08)\n// This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl (mail@sabaca.com)\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"perl\",function(){\n        // http://perldoc.perl.org\n        var PERL={                                      //   null - magic touch\n                                                        //   1 - keyword\n                                                        //   2 - def\n                                                        //   3 - atom\n                                                        //   4 - operator\n                                                        //   5 - variable-2 (predefined)\n                                                        //   [x,y] - x=1,2,3; y=must be defined if x{...}\n                                                //      PERL operators\n                '->'                            :   4,\n                '++'                            :   4,\n                '--'                            :   4,\n                '**'                            :   4,\n                                                        //   ! ~ \\ and unary + and -\n                '=~'                            :   4,\n                '!~'                            :   4,\n                '*'                             :   4,\n                '/'                             :   4,\n                '%'                             :   4,\n                'x'                             :   4,\n                '+'                             :   4,\n                '-'                             :   4,\n                '.'                             :   4,\n                '<<'                            :   4,\n                '>>'                            :   4,\n                                                        //   named unary operators\n                '<'                             :   4,\n                '>'                             :   4,\n                '<='                            :   4,\n                '>='                            :   4,\n                'lt'                            :   4,\n                'gt'                            :   4,\n                'le'                            :   4,\n                'ge'                            :   4,\n                '=='                            :   4,\n                '!='                            :   4,\n                '<=>'                           :   4,\n                'eq'                            :   4,\n                'ne'                            :   4,\n                'cmp'                           :   4,\n                '~~'                            :   4,\n                '&'                             :   4,\n                '|'                             :   4,\n                '^'                             :   4,\n                '&&'                            :   4,\n                '||'                            :   4,\n                '//'                            :   4,\n                '..'                            :   4,\n                '...'                           :   4,\n                '?'                             :   4,\n                ':'                             :   4,\n                '='                             :   4,\n                '+='                            :   4,\n                '-='                            :   4,\n                '*='                            :   4,  //   etc. ???\n                ','                             :   4,\n                '=>'                            :   4,\n                '::'                            :   4,\n                                                        //   list operators (rightward)\n                'not'                           :   4,\n                'and'                           :   4,\n                'or'                            :   4,\n                'xor'                           :   4,\n                                                //      PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;)\n                'BEGIN'                         :   [5,1],\n                'END'                           :   [5,1],\n                'PRINT'                         :   [5,1],\n                'PRINTF'                        :   [5,1],\n                'GETC'                          :   [5,1],\n                'READ'                          :   [5,1],\n                'READLINE'                      :   [5,1],\n                'DESTROY'                       :   [5,1],\n                'TIE'                           :   [5,1],\n                'TIEHANDLE'                     :   [5,1],\n                'UNTIE'                         :   [5,1],\n                'STDIN'                         :    5,\n                'STDIN_TOP'                     :    5,\n                'STDOUT'                        :    5,\n                'STDOUT_TOP'                    :    5,\n                'STDERR'                        :    5,\n                'STDERR_TOP'                    :    5,\n                '$ARG'                          :    5,\n                '$_'                            :    5,\n                '@ARG'                          :    5,\n                '@_'                            :    5,\n                '$LIST_SEPARATOR'               :    5,\n                '$\"'                            :    5,\n                '$PROCESS_ID'                   :    5,\n                '$PID'                          :    5,\n                '$$'                            :    5,\n                '$REAL_GROUP_ID'                :    5,\n                '$GID'                          :    5,\n                '$('                            :    5,\n                '$EFFECTIVE_GROUP_ID'           :    5,\n                '$EGID'                         :    5,\n                '$)'                            :    5,\n                '$PROGRAM_NAME'                 :    5,\n                '$0'                            :    5,\n                '$SUBSCRIPT_SEPARATOR'          :    5,\n                '$SUBSEP'                       :    5,\n                '$;'                            :    5,\n                '$REAL_USER_ID'                 :    5,\n                '$UID'                          :    5,\n                '$<'                            :    5,\n                '$EFFECTIVE_USER_ID'            :    5,\n                '$EUID'                         :    5,\n                '$>'                            :    5,\n                '$a'                            :    5,\n                '$b'                            :    5,\n                '$COMPILING'                    :    5,\n                '$^C'                           :    5,\n                '$DEBUGGING'                    :    5,\n                '$^D'                           :    5,\n                '${^ENCODING}'                  :    5,\n                '$ENV'                          :    5,\n                '%ENV'                          :    5,\n                '$SYSTEM_FD_MAX'                :    5,\n                '$^F'                           :    5,\n                '@F'                            :    5,\n                '${^GLOBAL_PHASE}'              :    5,\n                '$^H'                           :    5,\n                '%^H'                           :    5,\n                '@INC'                          :    5,\n                '%INC'                          :    5,\n                '$INPLACE_EDIT'                 :    5,\n                '$^I'                           :    5,\n                '$^M'                           :    5,\n                '$OSNAME'                       :    5,\n                '$^O'                           :    5,\n                '${^OPEN}'                      :    5,\n                '$PERLDB'                       :    5,\n                '$^P'                           :    5,\n                '$SIG'                          :    5,\n                '%SIG'                          :    5,\n                '$BASETIME'                     :    5,\n                '$^T'                           :    5,\n                '${^TAINT}'                     :    5,\n                '${^UNICODE}'                   :    5,\n                '${^UTF8CACHE}'                 :    5,\n                '${^UTF8LOCALE}'                :    5,\n                '$PERL_VERSION'                 :    5,\n                '$^V'                           :    5,\n                '${^WIN32_SLOPPY_STAT}'         :    5,\n                '$EXECUTABLE_NAME'              :    5,\n                '$^X'                           :    5,\n                '$1'                            :    5, // - regexp $1, $2...\n                '$MATCH'                        :    5,\n                '$&'                            :    5,\n                '${^MATCH}'                     :    5,\n                '$PREMATCH'                     :    5,\n                '$`'                            :    5,\n                '${^PREMATCH}'                  :    5,\n                '$POSTMATCH'                    :    5,\n                \"$'\"                            :    5,\n                '${^POSTMATCH}'                 :    5,\n                '$LAST_PAREN_MATCH'             :    5,\n                '$+'                            :    5,\n                '$LAST_SUBMATCH_RESULT'         :    5,\n                '$^N'                           :    5,\n                '@LAST_MATCH_END'               :    5,\n                '@+'                            :    5,\n                '%LAST_PAREN_MATCH'             :    5,\n                '%+'                            :    5,\n                '@LAST_MATCH_START'             :    5,\n                '@-'                            :    5,\n                '%LAST_MATCH_START'             :    5,\n                '%-'                            :    5,\n                '$LAST_REGEXP_CODE_RESULT'      :    5,\n                '$^R'                           :    5,\n                '${^RE_DEBUG_FLAGS}'            :    5,\n                '${^RE_TRIE_MAXBUF}'            :    5,\n                '$ARGV'                         :    5,\n                '@ARGV'                         :    5,\n                'ARGV'                          :    5,\n                'ARGVOUT'                       :    5,\n                '$OUTPUT_FIELD_SEPARATOR'       :    5,\n                '$OFS'                          :    5,\n                '$,'                            :    5,\n                '$INPUT_LINE_NUMBER'            :    5,\n                '$NR'                           :    5,\n                '$.'                            :    5,\n                '$INPUT_RECORD_SEPARATOR'       :    5,\n                '$RS'                           :    5,\n                '$/'                            :    5,\n                '$OUTPUT_RECORD_SEPARATOR'      :    5,\n                '$ORS'                          :    5,\n                '$\\\\'                           :    5,\n                '$OUTPUT_AUTOFLUSH'             :    5,\n                '$|'                            :    5,\n                '$ACCUMULATOR'                  :    5,\n                '$^A'                           :    5,\n                '$FORMAT_FORMFEED'              :    5,\n                '$^L'                           :    5,\n                '$FORMAT_PAGE_NUMBER'           :    5,\n                '$%'                            :    5,\n                '$FORMAT_LINES_LEFT'            :    5,\n                '$-'                            :    5,\n                '$FORMAT_LINE_BREAK_CHARACTERS' :    5,\n                '$:'                            :    5,\n                '$FORMAT_LINES_PER_PAGE'        :    5,\n                '$='                            :    5,\n                '$FORMAT_TOP_NAME'              :    5,\n                '$^'                            :    5,\n                '$FORMAT_NAME'                  :    5,\n                '$~'                            :    5,\n                '${^CHILD_ERROR_NATIVE}'        :    5,\n                '$EXTENDED_OS_ERROR'            :    5,\n                '$^E'                           :    5,\n                '$EXCEPTIONS_BEING_CAUGHT'      :    5,\n                '$^S'                           :    5,\n                '$WARNING'                      :    5,\n                '$^W'                           :    5,\n                '${^WARNING_BITS}'              :    5,\n                '$OS_ERROR'                     :    5,\n                '$ERRNO'                        :    5,\n                '$!'                            :    5,\n                '%OS_ERROR'                     :    5,\n                '%ERRNO'                        :    5,\n                '%!'                            :    5,\n                '$CHILD_ERROR'                  :    5,\n                '$?'                            :    5,\n                '$EVAL_ERROR'                   :    5,\n                '$@'                            :    5,\n                '$OFMT'                         :    5,\n                '$#'                            :    5,\n                '$*'                            :    5,\n                '$ARRAY_BASE'                   :    5,\n                '$['                            :    5,\n                '$OLD_PERL_VERSION'             :    5,\n                '$]'                            :    5,\n                                                //      PERL blocks\n                'if'                            :[1,1],\n                elsif                           :[1,1],\n                'else'                          :[1,1],\n                'while'                         :[1,1],\n                unless                          :[1,1],\n                'for'                           :[1,1],\n                foreach                         :[1,1],\n                                                //      PERL functions\n                'abs'                           :1,     // - absolute value function\n                accept                          :1,     // - accept an incoming socket connect\n                alarm                           :1,     // - schedule a SIGALRM\n                'atan2'                         :1,     // - arctangent of Y/X in the range -PI to PI\n                bind                            :1,     // - binds an address to a socket\n                binmode                         :1,     // - prepare binary files for I/O\n                bless                           :1,     // - create an object\n                bootstrap                       :1,     //\n                'break'                         :1,     // - break out of a \"given\" block\n                caller                          :1,     // - get context of the current subroutine call\n                chdir                           :1,     // - change your current working directory\n                chmod                           :1,     // - changes the permissions on a list of files\n                chomp                           :1,     // - remove a trailing record separator from a string\n                chop                            :1,     // - remove the last character from a string\n                chown                           :1,     // - change the ownership on a list of files\n                chr                             :1,     // - get character this number represents\n                chroot                          :1,     // - make directory new root for path lookups\n                close                           :1,     // - close file (or pipe or socket) handle\n                closedir                        :1,     // - close directory handle\n                connect                         :1,     // - connect to a remote socket\n                'continue'                      :[1,1], // - optional trailing block in a while or foreach\n                'cos'                           :1,     // - cosine function\n                crypt                           :1,     // - one-way passwd-style encryption\n                dbmclose                        :1,     // - breaks binding on a tied dbm file\n                dbmopen                         :1,     // - create binding on a tied dbm file\n                'default'                       :1,     //\n                defined                         :1,     // - test whether a value, variable, or function is defined\n                'delete'                        :1,     // - deletes a value from a hash\n                die                             :1,     // - raise an exception or bail out\n                'do'                            :1,     // - turn a BLOCK into a TERM\n                dump                            :1,     // - create an immediate core dump\n                each                            :1,     // - retrieve the next key/value pair from a hash\n                endgrent                        :1,     // - be done using group file\n                endhostent                      :1,     // - be done using hosts file\n                endnetent                       :1,     // - be done using networks file\n                endprotoent                     :1,     // - be done using protocols file\n                endpwent                        :1,     // - be done using passwd file\n                endservent                      :1,     // - be done using services file\n                eof                             :1,     // - test a filehandle for its end\n                'eval'                          :1,     // - catch exceptions or compile and run code\n                'exec'                          :1,     // - abandon this program to run another\n                exists                          :1,     // - test whether a hash key is present\n                exit                            :1,     // - terminate this program\n                'exp'                           :1,     // - raise I to a power\n                fcntl                           :1,     // - file control system call\n                fileno                          :1,     // - return file descriptor from filehandle\n                flock                           :1,     // - lock an entire file with an advisory lock\n                fork                            :1,     // - create a new process just like this one\n                format                          :1,     // - declare a picture format with use by the write() function\n                formline                        :1,     // - internal function used for formats\n                getc                            :1,     // - get the next character from the filehandle\n                getgrent                        :1,     // - get next group record\n                getgrgid                        :1,     // - get group record given group user ID\n                getgrnam                        :1,     // - get group record given group name\n                gethostbyaddr                   :1,     // - get host record given its address\n                gethostbyname                   :1,     // - get host record given name\n                gethostent                      :1,     // - get next hosts record\n                getlogin                        :1,     // - return who logged in at this tty\n                getnetbyaddr                    :1,     // - get network record given its address\n                getnetbyname                    :1,     // - get networks record given name\n                getnetent                       :1,     // - get next networks record\n                getpeername                     :1,     // - find the other end of a socket connection\n                getpgrp                         :1,     // - get process group\n                getppid                         :1,     // - get parent process ID\n                getpriority                     :1,     // - get current nice value\n                getprotobyname                  :1,     // - get protocol record given name\n                getprotobynumber                :1,     // - get protocol record numeric protocol\n                getprotoent                     :1,     // - get next protocols record\n                getpwent                        :1,     // - get next passwd record\n                getpwnam                        :1,     // - get passwd record given user login name\n                getpwuid                        :1,     // - get passwd record given user ID\n                getservbyname                   :1,     // - get services record given its name\n                getservbyport                   :1,     // - get services record given numeric port\n                getservent                      :1,     // - get next services record\n                getsockname                     :1,     // - retrieve the sockaddr for a given socket\n                getsockopt                      :1,     // - get socket options on a given socket\n                given                           :1,     //\n                glob                            :1,     // - expand filenames using wildcards\n                gmtime                          :1,     // - convert UNIX time into record or string using Greenwich time\n                'goto'                          :1,     // - create spaghetti code\n                grep                            :1,     // - locate elements in a list test true against a given criterion\n                hex                             :1,     // - convert a string to a hexadecimal number\n                'import'                        :1,     // - patch a module's namespace into your own\n                index                           :1,     // - find a substring within a string\n                'int'                           :1,     // - get the integer portion of a number\n                ioctl                           :1,     // - system-dependent device control system call\n                'join'                          :1,     // - join a list into a string using a separator\n                keys                            :1,     // - retrieve list of indices from a hash\n                kill                            :1,     // - send a signal to a process or process group\n                last                            :1,     // - exit a block prematurely\n                lc                              :1,     // - return lower-case version of a string\n                lcfirst                         :1,     // - return a string with just the next letter in lower case\n                length                          :1,     // - return the number of bytes in a string\n                'link'                          :1,     // - create a hard link in the filesytem\n                listen                          :1,     // - register your socket as a server\n                local                           : 2,    // - create a temporary value for a global variable (dynamic scoping)\n                localtime                       :1,     // - convert UNIX time into record or string using local time\n                lock                            :1,     // - get a thread lock on a variable, subroutine, or method\n                'log'                           :1,     // - retrieve the natural logarithm for a number\n                lstat                           :1,     // - stat a symbolic link\n                m                               :null,  // - match a string with a regular expression pattern\n                map                             :1,     // - apply a change to a list to get back a new list with the changes\n                mkdir                           :1,     // - create a directory\n                msgctl                          :1,     // - SysV IPC message control operations\n                msgget                          :1,     // - get SysV IPC message queue\n                msgrcv                          :1,     // - receive a SysV IPC message from a message queue\n                msgsnd                          :1,     // - send a SysV IPC message to a message queue\n                my                              : 2,    // - declare and assign a local variable (lexical scoping)\n                'new'                           :1,     //\n                next                            :1,     // - iterate a block prematurely\n                no                              :1,     // - unimport some module symbols or semantics at compile time\n                oct                             :1,     // - convert a string to an octal number\n                open                            :1,     // - open a file, pipe, or descriptor\n                opendir                         :1,     // - open a directory\n                ord                             :1,     // - find a character's numeric representation\n                our                             : 2,    // - declare and assign a package variable (lexical scoping)\n                pack                            :1,     // - convert a list into a binary representation\n                'package'                       :1,     // - declare a separate global namespace\n                pipe                            :1,     // - open a pair of connected filehandles\n                pop                             :1,     // - remove the last element from an array and return it\n                pos                             :1,     // - find or set the offset for the last/next m//g search\n                print                           :1,     // - output a list to a filehandle\n                printf                          :1,     // - output a formatted list to a filehandle\n                prototype                       :1,     // - get the prototype (if any) of a subroutine\n                push                            :1,     // - append one or more elements to an array\n                q                               :null,  // - singly quote a string\n                qq                              :null,  // - doubly quote a string\n                qr                              :null,  // - Compile pattern\n                quotemeta                       :null,  // - quote regular expression magic characters\n                qw                              :null,  // - quote a list of words\n                qx                              :null,  // - backquote quote a string\n                rand                            :1,     // - retrieve the next pseudorandom number\n                read                            :1,     // - fixed-length buffered input from a filehandle\n                readdir                         :1,     // - get a directory from a directory handle\n                readline                        :1,     // - fetch a record from a file\n                readlink                        :1,     // - determine where a symbolic link is pointing\n                readpipe                        :1,     // - execute a system command and collect standard output\n                recv                            :1,     // - receive a message over a Socket\n                redo                            :1,     // - start this loop iteration over again\n                ref                             :1,     // - find out the type of thing being referenced\n                rename                          :1,     // - change a filename\n                require                         :1,     // - load in external functions from a library at runtime\n                reset                           :1,     // - clear all variables of a given name\n                'return'                        :1,     // - get out of a function early\n                reverse                         :1,     // - flip a string or a list\n                rewinddir                       :1,     // - reset directory handle\n                rindex                          :1,     // - right-to-left substring search\n                rmdir                           :1,     // - remove a directory\n                s                               :null,  // - replace a pattern with a string\n                say                             :1,     // - print with newline\n                scalar                          :1,     // - force a scalar context\n                seek                            :1,     // - reposition file pointer for random-access I/O\n                seekdir                         :1,     // - reposition directory pointer\n                select                          :1,     // - reset default output or do I/O multiplexing\n                semctl                          :1,     // - SysV semaphore control operations\n                semget                          :1,     // - get set of SysV semaphores\n                semop                           :1,     // - SysV semaphore operations\n                send                            :1,     // - send a message over a socket\n                setgrent                        :1,     // - prepare group file for use\n                sethostent                      :1,     // - prepare hosts file for use\n                setnetent                       :1,     // - prepare networks file for use\n                setpgrp                         :1,     // - set the process group of a process\n                setpriority                     :1,     // - set a process's nice value\n                setprotoent                     :1,     // - prepare protocols file for use\n                setpwent                        :1,     // - prepare passwd file for use\n                setservent                      :1,     // - prepare services file for use\n                setsockopt                      :1,     // - set some socket options\n                shift                           :1,     // - remove the first element of an array, and return it\n                shmctl                          :1,     // - SysV shared memory operations\n                shmget                          :1,     // - get SysV shared memory segment identifier\n                shmread                         :1,     // - read SysV shared memory\n                shmwrite                        :1,     // - write SysV shared memory\n                shutdown                        :1,     // - close down just half of a socket connection\n                'sin'                           :1,     // - return the sine of a number\n                sleep                           :1,     // - block for some number of seconds\n                socket                          :1,     // - create a socket\n                socketpair                      :1,     // - create a pair of sockets\n                'sort'                          :1,     // - sort a list of values\n                splice                          :1,     // - add or remove elements anywhere in an array\n                'split'                         :1,     // - split up a string using a regexp delimiter\n                sprintf                         :1,     // - formatted print into a string\n                'sqrt'                          :1,     // - square root function\n                srand                           :1,     // - seed the random number generator\n                stat                            :1,     // - get a file's status information\n                state                           :1,     // - declare and assign a state variable (persistent lexical scoping)\n                study                           :1,     // - optimize input data for repeated searches\n                'sub'                           :1,     // - declare a subroutine, possibly anonymously\n                'substr'                        :1,     // - get or alter a portion of a stirng\n                symlink                         :1,     // - create a symbolic link to a file\n                syscall                         :1,     // - execute an arbitrary system call\n                sysopen                         :1,     // - open a file, pipe, or descriptor\n                sysread                         :1,     // - fixed-length unbuffered input from a filehandle\n                sysseek                         :1,     // - position I/O pointer on handle used with sysread and syswrite\n                system                          :1,     // - run a separate program\n                syswrite                        :1,     // - fixed-length unbuffered output to a filehandle\n                tell                            :1,     // - get current seekpointer on a filehandle\n                telldir                         :1,     // - get current seekpointer on a directory handle\n                tie                             :1,     // - bind a variable to an object class\n                tied                            :1,     // - get a reference to the object underlying a tied variable\n                time                            :1,     // - return number of seconds since 1970\n                times                           :1,     // - return elapsed time for self and child processes\n                tr                              :null,  // - transliterate a string\n                truncate                        :1,     // - shorten a file\n                uc                              :1,     // - return upper-case version of a string\n                ucfirst                         :1,     // - return a string with just the next letter in upper case\n                umask                           :1,     // - set file creation mode mask\n                undef                           :1,     // - remove a variable or function definition\n                unlink                          :1,     // - remove one link to a file\n                unpack                          :1,     // - convert binary structure into normal perl variables\n                unshift                         :1,     // - prepend more elements to the beginning of a list\n                untie                           :1,     // - break a tie binding to a variable\n                use                             :1,     // - load in a module at compile time\n                utime                           :1,     // - set a file's last access and modify times\n                values                          :1,     // - return a list of the values in a hash\n                vec                             :1,     // - test or set particular bits in a string\n                wait                            :1,     // - wait for any child process to die\n                waitpid                         :1,     // - wait for a particular child process to die\n                wantarray                       :1,     // - get void vs scalar vs list context of current subroutine call\n                warn                            :1,     // - print debugging info\n                when                            :1,     //\n                write                           :1,     // - print a picture record\n                y                               :null}; // - transliterate a string\n\n        var RXstyle=\"string-2\";\n        var RXmodifiers=/[goseximacplud]/;              // NOTE: \"m\", \"s\", \"y\" and \"tr\" need to correct real modifiers for each regexp type\n\n        function tokenChain(stream,state,chain,style,tail){     // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;)\n                state.chain=null;                               //                                                          12   3tail\n                state.style=null;\n                state.tail=null;\n                state.tokenize=function(stream,state){\n                        var e=false,c,i=0;\n                        while(c=stream.next()){\n                                if(c===chain[i]&&!e){\n                                        if(chain[++i]!==undefined){\n                                                state.chain=chain[i];\n                                                state.style=style;\n                                                state.tail=tail;}\n                                        else if(tail)\n                                                stream.eatWhile(tail);\n                                        state.tokenize=tokenPerl;\n                                        return style;}\n                                e=!e&&c==\"\\\\\";}\n                        return style;};\n                return state.tokenize(stream,state);}\n\n        function tokenSOMETHING(stream,state,string){\n                state.tokenize=function(stream,state){\n                        if(stream.string==string)\n                                state.tokenize=tokenPerl;\n                        stream.skipToEnd();\n                        return \"string\";};\n                return state.tokenize(stream,state);}\n\n        function tokenPerl(stream,state){\n                if(stream.eatSpace())\n                        return null;\n                if(state.chain)\n                        return tokenChain(stream,state,state.chain,state.style,state.tail);\n                if(stream.match(/^\\-?[\\d\\.]/,false))\n                        if(stream.match(/^(\\-?(\\d*\\.\\d+(e[+-]?\\d+)?|\\d+\\.\\d*)|0x[\\da-fA-F]+|0b[01]+|\\d+(e[+-]?\\d+)?)/))\n                                return 'number';\n                if(stream.match(/^<<(?=\\w)/)){                  // NOTE: <<SOMETHING\\n...\\nSOMETHING\\n\n                        stream.eatWhile(/\\w/);\n                        return tokenSOMETHING(stream,state,stream.current().substr(2));}\n                if(stream.sol()&&stream.match(/^\\=item(?!\\w)/)){// NOTE: \\n=item...\\n=cut\\n\n                        return tokenSOMETHING(stream,state,'=cut');}\n                var ch=stream.next();\n                if(ch=='\"'||ch==\"'\"){                           // NOTE: ' or \" or <<'SOMETHING'\\n...\\nSOMETHING\\n or <<\"SOMETHING\"\\n...\\nSOMETHING\\n\n                        if(prefix(stream, 3)==\"<<\"+ch){\n                                var p=stream.pos;\n                                stream.eatWhile(/\\w/);\n                                var n=stream.current().substr(1);\n                                if(n&&stream.eat(ch))\n                                        return tokenSOMETHING(stream,state,n);\n                                stream.pos=p;}\n                        return tokenChain(stream,state,[ch],\"string\");}\n                if(ch==\"q\"){\n                        var c=look(stream, -2);\n                        if(!(c&&/\\w/.test(c))){\n                                c=look(stream, 0);\n                                if(c==\"x\"){\n                                        c=look(stream, 1);\n                                        if(c==\"(\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\")\"],RXstyle,RXmodifiers);}\n                                        if(c==\"[\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\"]\"],RXstyle,RXmodifiers);}\n                                        if(c==\"{\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\"}\"],RXstyle,RXmodifiers);}\n                                        if(c==\"<\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\">\"],RXstyle,RXmodifiers);}\n                                        if(/[\\^'\"!~\\/]/.test(c)){\n                                                eatSuffix(stream, 1);\n                                                return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}\n                                else if(c==\"q\"){\n                                        c=look(stream, 1);\n                                        if(c==\"(\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\")\"],\"string\");}\n                                        if(c==\"[\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\"]\"],\"string\");}\n                                        if(c==\"{\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\"}\"],\"string\");}\n                                        if(c==\"<\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\">\"],\"string\");}\n                                        if(/[\\^'\"!~\\/]/.test(c)){\n                                                eatSuffix(stream, 1);\n                                                return tokenChain(stream,state,[stream.eat(c)],\"string\");}}\n                                else if(c==\"w\"){\n                                        c=look(stream, 1);\n                                        if(c==\"(\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\")\"],\"bracket\");}\n                                        if(c==\"[\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\"]\"],\"bracket\");}\n                                        if(c==\"{\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\"}\"],\"bracket\");}\n                                        if(c==\"<\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\">\"],\"bracket\");}\n                                        if(/[\\^'\"!~\\/]/.test(c)){\n                                                eatSuffix(stream, 1);\n                                                return tokenChain(stream,state,[stream.eat(c)],\"bracket\");}}\n                                else if(c==\"r\"){\n                                        c=look(stream, 1);\n                                        if(c==\"(\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\")\"],RXstyle,RXmodifiers);}\n                                        if(c==\"[\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\"]\"],RXstyle,RXmodifiers);}\n                                        if(c==\"{\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\"}\"],RXstyle,RXmodifiers);}\n                                        if(c==\"<\"){\n                                                eatSuffix(stream, 2);\n                                                return tokenChain(stream,state,[\">\"],RXstyle,RXmodifiers);}\n                                        if(/[\\^'\"!~\\/]/.test(c)){\n                                                eatSuffix(stream, 1);\n                                                return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}\n                                else if(/[\\^'\"!~\\/(\\[{<]/.test(c)){\n                                        if(c==\"(\"){\n                                                eatSuffix(stream, 1);\n                                                return tokenChain(stream,state,[\")\"],\"string\");}\n                                        if(c==\"[\"){\n                                                eatSuffix(stream, 1);\n                                                return tokenChain(stream,state,[\"]\"],\"string\");}\n                                        if(c==\"{\"){\n                                                eatSuffix(stream, 1);\n                                                return tokenChain(stream,state,[\"}\"],\"string\");}\n                                        if(c==\"<\"){\n                                                eatSuffix(stream, 1);\n                                                return tokenChain(stream,state,[\">\"],\"string\");}\n                                        if(/[\\^'\"!~\\/]/.test(c)){\n                                                return tokenChain(stream,state,[stream.eat(c)],\"string\");}}}}\n                if(ch==\"m\"){\n                        var c=look(stream, -2);\n                        if(!(c&&/\\w/.test(c))){\n                                c=stream.eat(/[(\\[{<\\^'\"!~\\/]/);\n                                if(c){\n                                        if(/[\\^'\"!~\\/]/.test(c)){\n                                                return tokenChain(stream,state,[c],RXstyle,RXmodifiers);}\n                                        if(c==\"(\"){\n                                                return tokenChain(stream,state,[\")\"],RXstyle,RXmodifiers);}\n                                        if(c==\"[\"){\n                                                return tokenChain(stream,state,[\"]\"],RXstyle,RXmodifiers);}\n                                        if(c==\"{\"){\n                                                return tokenChain(stream,state,[\"}\"],RXstyle,RXmodifiers);}\n                                        if(c==\"<\"){\n                                                return tokenChain(stream,state,[\">\"],RXstyle,RXmodifiers);}}}}\n                if(ch==\"s\"){\n                        var c=/[\\/>\\]})\\w]/.test(look(stream, -2));\n                        if(!c){\n                                c=stream.eat(/[(\\[{<\\^'\"!~\\/]/);\n                                if(c){\n                                        if(c==\"[\")\n                                                return tokenChain(stream,state,[\"]\",\"]\"],RXstyle,RXmodifiers);\n                                        if(c==\"{\")\n                                                return tokenChain(stream,state,[\"}\",\"}\"],RXstyle,RXmodifiers);\n                                        if(c==\"<\")\n                                                return tokenChain(stream,state,[\">\",\">\"],RXstyle,RXmodifiers);\n                                        if(c==\"(\")\n                                                return tokenChain(stream,state,[\")\",\")\"],RXstyle,RXmodifiers);\n                                        return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}\n                if(ch==\"y\"){\n                        var c=/[\\/>\\]})\\w]/.test(look(stream, -2));\n                        if(!c){\n                                c=stream.eat(/[(\\[{<\\^'\"!~\\/]/);\n                                if(c){\n                                        if(c==\"[\")\n                                                return tokenChain(stream,state,[\"]\",\"]\"],RXstyle,RXmodifiers);\n                                        if(c==\"{\")\n                                                return tokenChain(stream,state,[\"}\",\"}\"],RXstyle,RXmodifiers);\n                                        if(c==\"<\")\n                                                return tokenChain(stream,state,[\">\",\">\"],RXstyle,RXmodifiers);\n                                        if(c==\"(\")\n                                                return tokenChain(stream,state,[\")\",\")\"],RXstyle,RXmodifiers);\n                                        return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}\n                if(ch==\"t\"){\n                        var c=/[\\/>\\]})\\w]/.test(look(stream, -2));\n                        if(!c){\n                                c=stream.eat(\"r\");if(c){\n                                c=stream.eat(/[(\\[{<\\^'\"!~\\/]/);\n                                if(c){\n                                        if(c==\"[\")\n                                                return tokenChain(stream,state,[\"]\",\"]\"],RXstyle,RXmodifiers);\n                                        if(c==\"{\")\n                                                return tokenChain(stream,state,[\"}\",\"}\"],RXstyle,RXmodifiers);\n                                        if(c==\"<\")\n                                                return tokenChain(stream,state,[\">\",\">\"],RXstyle,RXmodifiers);\n                                        if(c==\"(\")\n                                                return tokenChain(stream,state,[\")\",\")\"],RXstyle,RXmodifiers);\n                                        return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}}\n                if(ch==\"`\"){\n                        return tokenChain(stream,state,[ch],\"variable-2\");}\n                if(ch==\"/\"){\n                        if(!/~\\s*$/.test(prefix(stream)))\n                                return \"operator\";\n                        else\n                                return tokenChain(stream,state,[ch],RXstyle,RXmodifiers);}\n                if(ch==\"$\"){\n                        var p=stream.pos;\n                        if(stream.eatWhile(/\\d/)||stream.eat(\"{\")&&stream.eatWhile(/\\d/)&&stream.eat(\"}\"))\n                                return \"variable-2\";\n                        else\n                                stream.pos=p;}\n                if(/[$@%]/.test(ch)){\n                        var p=stream.pos;\n                        if(stream.eat(\"^\")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(look(stream, -2))&&stream.eat(/[=|\\\\\\-#?@;:&`~\\^!\\[\\]*'\"$+.,\\/<>()]/)){\n                                var c=stream.current();\n                                if(PERL[c])\n                                        return \"variable-2\";}\n                        stream.pos=p;}\n                if(/[$@%&]/.test(ch)){\n                        if(stream.eatWhile(/[\\w$\\[\\]]/)||stream.eat(\"{\")&&stream.eatWhile(/[\\w$\\[\\]]/)&&stream.eat(\"}\")){\n                                var c=stream.current();\n                                if(PERL[c])\n                                        return \"variable-2\";\n                                else\n                                        return \"variable\";}}\n                if(ch==\"#\"){\n                        if(look(stream, -2)!=\"$\"){\n                                stream.skipToEnd();\n                                return \"comment\";}}\n                if(/[:+\\-\\^*$&%@=<>!?|\\/~\\.]/.test(ch)){\n                        var p=stream.pos;\n                        stream.eatWhile(/[:+\\-\\^*$&%@=<>!?|\\/~\\.]/);\n                        if(PERL[stream.current()])\n                                return \"operator\";\n                        else\n                                stream.pos=p;}\n                if(ch==\"_\"){\n                        if(stream.pos==1){\n                                if(suffix(stream, 6)==\"_END__\"){\n                                        return tokenChain(stream,state,['\\0'],\"comment\");}\n                                else if(suffix(stream, 7)==\"_DATA__\"){\n                                        return tokenChain(stream,state,['\\0'],\"variable-2\");}\n                                else if(suffix(stream, 7)==\"_C__\"){\n                                        return tokenChain(stream,state,['\\0'],\"string\");}}}\n                if(/\\w/.test(ch)){\n                        var p=stream.pos;\n                        if(look(stream, -2)==\"{\"&&(look(stream, 0)==\"}\"||stream.eatWhile(/\\w/)&&look(stream, 0)==\"}\"))\n                                return \"string\";\n                        else\n                                stream.pos=p;}\n                if(/[A-Z]/.test(ch)){\n                        var l=look(stream, -2);\n                        var p=stream.pos;\n                        stream.eatWhile(/[A-Z_]/);\n                        if(/[\\da-z]/.test(look(stream, 0))){\n                                stream.pos=p;}\n                        else{\n                                var c=PERL[stream.current()];\n                                if(!c)\n                                        return \"meta\";\n                                if(c[1])\n                                        c=c[0];\n                                if(l!=\":\"){\n                                        if(c==1)\n                                                return \"keyword\";\n                                        else if(c==2)\n                                                return \"def\";\n                                        else if(c==3)\n                                                return \"atom\";\n                                        else if(c==4)\n                                                return \"operator\";\n                                        else if(c==5)\n                                                return \"variable-2\";\n                                        else\n                                                return \"meta\";}\n                                else\n                                        return \"meta\";}}\n                if(/[a-zA-Z_]/.test(ch)){\n                        var l=look(stream, -2);\n                        stream.eatWhile(/\\w/);\n                        var c=PERL[stream.current()];\n                        if(!c)\n                                return \"meta\";\n                        if(c[1])\n                                c=c[0];\n                        if(l!=\":\"){\n                                if(c==1)\n                                        return \"keyword\";\n                                else if(c==2)\n                                        return \"def\";\n                                else if(c==3)\n                                        return \"atom\";\n                                else if(c==4)\n                                        return \"operator\";\n                                else if(c==5)\n                                        return \"variable-2\";\n                                else\n                                        return \"meta\";}\n                        else\n                                return \"meta\";}\n                return null;}\n\n        return {\n            startState: function() {\n                return {\n                    tokenize: tokenPerl,\n                    chain: null,\n                    style: null,\n                    tail: null\n                };\n            },\n            token: function(stream, state) {\n                return (state.tokenize || tokenPerl)(stream, state);\n            },\n            lineComment: '#'\n        };\n});\n\nCodeMirror.registerHelper(\"wordChars\", \"perl\", /[\\w$]/);\n\nCodeMirror.defineMIME(\"text/x-perl\", \"perl\");\n\n// it's like \"peek\", but need for look-ahead or look-behind if index < 0\nfunction look(stream, c){\n  return stream.string.charAt(stream.pos+(c||0));\n}\n\n// return a part of prefix of current stream from current position\nfunction prefix(stream, c){\n  if(c){\n    var x=stream.pos-c;\n    return stream.string.substr((x>=0?x:0),c);}\n  else{\n    return stream.string.substr(0,stream.pos-1);\n  }\n}\n\n// return a part of suffix of current stream from current position\nfunction suffix(stream, c){\n  var y=stream.string.length;\n  var x=y-stream.pos+1;\n  return stream.string.substr(stream.pos,(c&&c<y?c:x));\n}\n\n// eating and vomiting a part of stream from current position\nfunction eatSuffix(stream, c){\n  var x=stream.pos+c;\n  var y;\n  if(x<=0)\n    stream.pos=0;\n  else if(x>=(y=stream.string.length-1))\n    stream.pos=y;\n  else\n    stream.pos=x;\n}\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/php/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: PHP mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../css/css.js\"></script>\n<script src=\"../clike/clike.js\"></script>\n<script src=\"php.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">PHP</a>\n  </ul>\n</div>\n\n<article>\n<h2>PHP mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n<?php\n$a = array('a' => 1, 'b' => 2, 3 => 'c');\n\necho \"$a[a] ${a[3] /* } comment */} {$a[b]} \\$a[a]\";\n\nfunction hello($who) {\n\treturn \"Hello $who!\";\n}\n?>\n<p>The program says <?= hello(\"World\") ?>.</p>\n<script>\n\talert(\"And here is some JS code\"); // also colored\n</script>\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"application/x-httpd-php\",\n        indentUnit: 4,\n        indentWithTabs: true\n      });\n    </script>\n\n    <p>Simple HTML/PHP mode based on\n    the <a href=\"../clike/\">C-like</a> mode. Depends on XML,\n    JavaScript, CSS, HTMLMixed, and C-like modes.</p>\n\n    <p><strong>MIME types defined:</strong> <code>application/x-httpd-php</code> (HTML with PHP code), <code>text/x-php</code> (plain, non-wrapped PHP code).</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/php/php.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../htmlmixed/htmlmixed\"), require(\"../clike/clike\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../htmlmixed/htmlmixed\", \"../clike/clike\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function keywords(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  // Helper for phpString\n  function matchSequence(list, end, escapes) {\n    if (list.length == 0) return phpString(end);\n    return function (stream, state) {\n      var patterns = list[0];\n      for (var i = 0; i < patterns.length; i++) if (stream.match(patterns[i][0])) {\n        state.tokenize = matchSequence(list.slice(1), end);\n        return patterns[i][1];\n      }\n      state.tokenize = phpString(end, escapes);\n      return \"string\";\n    };\n  }\n  function phpString(closing, escapes) {\n    return function(stream, state) { return phpString_(stream, state, closing, escapes); };\n  }\n  function phpString_(stream, state, closing, escapes) {\n    // \"Complex\" syntax\n    if (escapes !== false && stream.match(\"${\", false) || stream.match(\"{$\", false)) {\n      state.tokenize = null;\n      return \"string\";\n    }\n\n    // Simple syntax\n    if (escapes !== false && stream.match(/^\\$[a-zA-Z_][a-zA-Z0-9_]*/)) {\n      // After the variable name there may appear array or object operator.\n      if (stream.match(\"[\", false)) {\n        // Match array operator\n        state.tokenize = matchSequence([\n          [[\"[\", null]],\n          [[/\\d[\\w\\.]*/, \"number\"],\n           [/\\$[a-zA-Z_][a-zA-Z0-9_]*/, \"variable-2\"],\n           [/[\\w\\$]+/, \"variable\"]],\n          [[\"]\", null]]\n        ], closing, escapes);\n      }\n      if (stream.match(/\\-\\>\\w/, false)) {\n        // Match object operator\n        state.tokenize = matchSequence([\n          [[\"->\", null]],\n          [[/[\\w]+/, \"variable\"]]\n        ], closing, escapes);\n      }\n      return \"variable-2\";\n    }\n\n    var escaped = false;\n    // Normal string\n    while (!stream.eol() &&\n           (escaped || escapes === false ||\n            (!stream.match(\"{$\", false) &&\n             !stream.match(/^(\\$[a-zA-Z_][a-zA-Z0-9_]*|\\$\\{)/, false)))) {\n      if (!escaped && stream.match(closing)) {\n        state.tokenize = null;\n        state.tokStack.pop(); state.tokStack.pop();\n        break;\n      }\n      escaped = stream.next() == \"\\\\\" && !escaped;\n    }\n    return \"string\";\n  }\n\n  var phpKeywords = \"abstract and array as break case catch class clone const continue declare default \" +\n    \"do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final \" +\n    \"for foreach function global goto if implements interface instanceof namespace \" +\n    \"new or private protected public static switch throw trait try use var while xor \" +\n    \"die echo empty exit eval include include_once isset list require require_once return \" +\n    \"print unset __halt_compiler self static parent yield insteadof finally\";\n  var phpAtoms = \"true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__ __TRAIT__\";\n  var phpBuiltin = \"func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions extension_loaded get_extension_funcs debug_backtrace constant bin2hex hex2bin sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents file_put_contents stream_select stream_context_create stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists array_intersect_key array_combine array_column pos sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread pg_lowrite pg_loimport pg_loexport http_response_code get_declared_traits getimagesizefromstring socket_import_stream stream_set_chunk_size trait_exists header_register_callback class_uses session_status session_register_shutdown echo print global static exit array empty eval isset unset die include require include_once require_once json_decode json_encode json_last_error json_last_error_msg curl_close curl_copy_handle curl_errno curl_error curl_escape curl_exec curl_file_create curl_getinfo curl_init curl_multi_add_handle curl_multi_close curl_multi_exec curl_multi_getcontent curl_multi_info_read curl_multi_init curl_multi_remove_handle curl_multi_select curl_multi_setopt curl_multi_strerror curl_pause curl_reset curl_setopt_array curl_setopt curl_share_close curl_share_init curl_share_setopt curl_strerror curl_unescape curl_version mysqli_affected_rows mysqli_autocommit mysqli_change_user mysqli_character_set_name mysqli_close mysqli_commit mysqli_connect_errno mysqli_connect_error mysqli_connect mysqli_data_seek mysqli_debug mysqli_dump_debug_info mysqli_errno mysqli_error_list mysqli_error mysqli_fetch_all mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_field_direct mysqli_fetch_field mysqli_fetch_fields mysqli_fetch_lengths mysqli_fetch_object mysqli_fetch_row mysqli_field_count mysqli_field_seek mysqli_field_tell mysqli_free_result mysqli_get_charset mysqli_get_client_info mysqli_get_client_stats mysqli_get_client_version mysqli_get_connection_stats mysqli_get_host_info mysqli_get_proto_info mysqli_get_server_info mysqli_get_server_version mysqli_info mysqli_init mysqli_insert_id mysqli_kill mysqli_more_results mysqli_multi_query mysqli_next_result mysqli_num_fields mysqli_num_rows mysqli_options mysqli_ping mysqli_prepare mysqli_query mysqli_real_connect mysqli_real_escape_string mysqli_real_query mysqli_reap_async_query mysqli_refresh mysqli_rollback mysqli_select_db mysqli_set_charset mysqli_set_local_infile_default mysqli_set_local_infile_handler mysqli_sqlstate mysqli_ssl_set mysqli_stat mysqli_stmt_init mysqli_store_result mysqli_thread_id mysqli_thread_safe mysqli_use_result mysqli_warning_count\";\n  CodeMirror.registerHelper(\"hintWords\", \"php\", [phpKeywords, phpAtoms, phpBuiltin].join(\" \").split(\" \"));\n  CodeMirror.registerHelper(\"wordChars\", \"php\", /[\\w$]/);\n\n  var phpConfig = {\n    name: \"clike\",\n    helperType: \"php\",\n    keywords: keywords(phpKeywords),\n    blockKeywords: keywords(\"catch do else elseif for foreach if switch try while finally\"),\n    defKeywords: keywords(\"class function interface namespace trait\"),\n    atoms: keywords(phpAtoms),\n    builtin: keywords(phpBuiltin),\n    multiLineStrings: true,\n    hooks: {\n      \"$\": function(stream) {\n        stream.eatWhile(/[\\w\\$_]/);\n        return \"variable-2\";\n      },\n      \"<\": function(stream, state) {\n        var before;\n        if (before = stream.match(/<<\\s*/)) {\n          var quoted = stream.eat(/['\"]/);\n          stream.eatWhile(/[\\w\\.]/);\n          var delim = stream.current().slice(before[0].length + (quoted ? 2 : 1));\n          if (quoted) stream.eat(quoted);\n          if (delim) {\n            (state.tokStack || (state.tokStack = [])).push(delim, 0);\n            state.tokenize = phpString(delim, quoted != \"'\");\n            return \"string\";\n          }\n        }\n        return false;\n      },\n      \"#\": function(stream) {\n        while (!stream.eol() && !stream.match(\"?>\", false)) stream.next();\n        return \"comment\";\n      },\n      \"/\": function(stream) {\n        if (stream.eat(\"/\")) {\n          while (!stream.eol() && !stream.match(\"?>\", false)) stream.next();\n          return \"comment\";\n        }\n        return false;\n      },\n      '\"': function(_stream, state) {\n        (state.tokStack || (state.tokStack = [])).push('\"', 0);\n        state.tokenize = phpString('\"');\n        return \"string\";\n      },\n      \"{\": function(_stream, state) {\n        if (state.tokStack && state.tokStack.length)\n          state.tokStack[state.tokStack.length - 1]++;\n        return false;\n      },\n      \"}\": function(_stream, state) {\n        if (state.tokStack && state.tokStack.length > 0 &&\n            !--state.tokStack[state.tokStack.length - 1]) {\n          state.tokenize = phpString(state.tokStack[state.tokStack.length - 2]);\n        }\n        return false;\n      }\n    }\n  };\n\n  CodeMirror.defineMode(\"php\", function(config, parserConfig) {\n    var htmlMode = CodeMirror.getMode(config, (parserConfig && parserConfig.htmlMode) || \"text/html\");\n    var phpMode = CodeMirror.getMode(config, phpConfig);\n\n    function dispatch(stream, state) {\n      var isPHP = state.curMode == phpMode;\n      if (stream.sol() && state.pending && state.pending != '\"' && state.pending != \"'\") state.pending = null;\n      if (!isPHP) {\n        if (stream.match(/^<\\?\\w*/)) {\n          state.curMode = phpMode;\n          if (!state.php) state.php = CodeMirror.startState(phpMode, htmlMode.indent(state.html, \"\", \"\"))\n          state.curState = state.php;\n          return \"meta\";\n        }\n        if (state.pending == '\"' || state.pending == \"'\") {\n          while (!stream.eol() && stream.next() != state.pending) {}\n          var style = \"string\";\n        } else if (state.pending && stream.pos < state.pending.end) {\n          stream.pos = state.pending.end;\n          var style = state.pending.style;\n        } else {\n          var style = htmlMode.token(stream, state.curState);\n        }\n        if (state.pending) state.pending = null;\n        var cur = stream.current(), openPHP = cur.search(/<\\?/), m;\n        if (openPHP != -1) {\n          if (style == \"string\" && (m = cur.match(/[\\'\\\"]$/)) && !/\\?>/.test(cur)) state.pending = m[0];\n          else state.pending = {end: stream.pos, style: style};\n          stream.backUp(cur.length - openPHP);\n        }\n        return style;\n      } else if (isPHP && state.php.tokenize == null && stream.match(\"?>\")) {\n        state.curMode = htmlMode;\n        state.curState = state.html;\n        if (!state.php.context.prev) state.php = null;\n        return \"meta\";\n      } else {\n        return phpMode.token(stream, state.curState);\n      }\n    }\n\n    return {\n      startState: function() {\n        var html = CodeMirror.startState(htmlMode)\n        var php = parserConfig.startOpen ? CodeMirror.startState(phpMode) : null\n        return {html: html,\n                php: php,\n                curMode: parserConfig.startOpen ? phpMode : htmlMode,\n                curState: parserConfig.startOpen ? php : html,\n                pending: null};\n      },\n\n      copyState: function(state) {\n        var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),\n            php = state.php, phpNew = php && CodeMirror.copyState(phpMode, php), cur;\n        if (state.curMode == htmlMode) cur = htmlNew;\n        else cur = phpNew;\n        return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur,\n                pending: state.pending};\n      },\n\n      token: dispatch,\n\n      indent: function(state, textAfter, line) {\n        if ((state.curMode != phpMode && /^\\s*<\\//.test(textAfter)) ||\n            (state.curMode == phpMode && /^\\?>/.test(textAfter)))\n          return htmlMode.indent(state.html, textAfter, line);\n        return state.curMode.indent(state.curState, textAfter, line);\n      },\n\n      blockCommentStart: \"/*\",\n      blockCommentEnd: \"*/\",\n      lineComment: \"//\",\n\n      innerMode: function(state) { return {state: state.curState, mode: state.curMode}; }\n    };\n  }, \"htmlmixed\", \"clike\");\n\n  CodeMirror.defineMIME(\"application/x-httpd-php\", \"php\");\n  CodeMirror.defineMIME(\"application/x-httpd-php-open\", {name: \"php\", startOpen: true});\n  CodeMirror.defineMIME(\"text/x-php\", phpConfig);\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/php/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"php\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT('simple_test',\n     '[meta <?php] ' +\n     '[keyword echo] [string \"aaa\"]; ' +\n     '[meta ?>]');\n\n  MT('variable_interpolation_non_alphanumeric',\n     '[meta <?php]',\n     '[keyword echo] [string \"aaa$~$!$@$#$$$%$^$&$*$($)$.$<$>$/$\\\\$}$\\\\\\\"$:$;$?$|$[[$]]$+$=aaa\"]',\n     '[meta ?>]');\n\n  MT('variable_interpolation_digits',\n     '[meta <?php]',\n     '[keyword echo] [string \"aaa$1$2$3$4$5$6$7$8$9$0aaa\"]',\n     '[meta ?>]');\n\n  MT('variable_interpolation_simple_syntax_1',\n     '[meta <?php]',\n     '[keyword echo] [string \"aaa][variable-2 $aaa][string .aaa\"];',\n     '[meta ?>]');\n\n  MT('variable_interpolation_simple_syntax_2',\n     '[meta <?php]',\n     '[keyword echo] [string \"][variable-2 $aaaa][[','[number 2]',         ']][string aa\"];',\n     '[keyword echo] [string \"][variable-2 $aaaa][[','[number 2345]',      ']][string aa\"];',\n     '[keyword echo] [string \"][variable-2 $aaaa][[','[number 2.3]',       ']][string aa\"];',\n     '[keyword echo] [string \"][variable-2 $aaaa][[','[variable aaaaa]',   ']][string aa\"];',\n     '[keyword echo] [string \"][variable-2 $aaaa][[','[variable-2 $aaaaa]',']][string aa\"];',\n\n     '[keyword echo] [string \"1aaa][variable-2 $aaaa][[','[number 2]',         ']][string aa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $aaaa][[','[number 2345]',      ']][string aa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $aaaa][[','[number 2.3]',       ']][string aa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $aaaa][[','[variable aaaaa]',   ']][string aa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $aaaa][[','[variable-2 $aaaaa]',']][string aa\"];',\n     '[meta ?>]');\n\n  MT('variable_interpolation_simple_syntax_3',\n     '[meta <?php]',\n     '[keyword echo] [string \"aaa][variable-2 $aaaa]->[variable aaaaa][string .aaaaaa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $aaaa][string ->][variable-2 $aaaaa][string .aaaaaa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $aaaa]->[variable aaaaa][string [[2]].aaaaaa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $aaaa]->[variable aaaaa][string ->aaaa2.aaaaaa\"];',\n     '[meta ?>]');\n\n  MT('variable_interpolation_escaping',\n     '[meta <?php] [comment /* Escaping */]',\n     '[keyword echo] [string \"aaa\\\\$aaaa->aaa.aaa\"];',\n     '[keyword echo] [string \"aaa\\\\$aaaa[[2]]aaa.aaa\"];',\n     '[keyword echo] [string \"aaa\\\\$aaaa[[asd]]aaa.aaa\"];',\n     '[keyword echo] [string \"aaa{\\\\$aaaa->aaa.aaa\"];',\n     '[keyword echo] [string \"aaa{\\\\$aaaa[[2]]aaa.aaa\"];',\n     '[keyword echo] [string \"aaa{\\\\aaaaa[[asd]]aaa.aaa\"];',\n     '[keyword echo] [string \"aaa\\\\${aaaa->aaa.aaa\"];',\n     '[keyword echo] [string \"aaa\\\\${aaaa[[2]]aaa.aaa\"];',\n     '[keyword echo] [string \"aaa\\\\${aaaa[[asd]]aaa.aaa\"];',\n     '[meta ?>]');\n\n  MT('variable_interpolation_complex_syntax_1',\n     '[meta <?php]',\n     '[keyword echo] [string \"aaa][variable-2 $]{[variable aaaa]}[string ->aaa.aaa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $]{[variable-2 $aaaa]}[string ->aaa.aaa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $]{[variable-2 $aaaa][[','  [number 42]',']]}[string ->aaa.aaa\"];',\n     '[keyword echo] [string \"aaa][variable-2 $]{[variable aaaa][meta ?>]aaaaaa');\n\n  MT('variable_interpolation_complex_syntax_2',\n     '[meta <?php] [comment /* Monsters */]',\n     '[keyword echo] [string \"][variable-2 $]{[variable aaa][comment /*}?>} $aaa<?php } */]}[string ->aaa.aaa\"];',\n     '[keyword echo] [string \"][variable-2 $]{[variable aaa][comment /*}?>*/][[','  [string \"aaa][variable-2 $aaa][string {}][variable-2 $]{[variable aaa]}[string \"]',']]}[string ->aaa.aaa\"];',\n     '[keyword echo] [string \"][variable-2 $]{[variable aaa][comment /*} } $aaa } */]}[string ->aaa.aaa\"];');\n\n\n  function build_recursive_monsters(nt, t, n){\n    var monsters = [t];\n    for (var i = 1; i <= n; ++i)\n      monsters[i] = nt.join(monsters[i - 1]);\n    return monsters;\n  }\n\n  var m1 = build_recursive_monsters(\n    ['[string \"][variable-2 $]{[variable aaa] [operator +] ', '}[string \"]'],\n    '[comment /* }?>} */] [string \"aaa][variable-2 $aaa][string .aaa\"]',\n    10\n  );\n\n  MT('variable_interpolation_complex_syntax_3_1',\n     '[meta <?php] [comment /* Recursive monsters */]',\n     '[keyword echo] ' + m1[4] + ';',\n     '[keyword echo] ' + m1[7] + ';',\n     '[keyword echo] ' + m1[8] + ';',\n     '[keyword echo] ' + m1[5] + ';',\n     '[keyword echo] ' + m1[1] + ';',\n     '[keyword echo] ' + m1[6] + ';',\n     '[keyword echo] ' + m1[9] + ';',\n     '[keyword echo] ' + m1[0] + ';',\n     '[keyword echo] ' + m1[10] + ';',\n     '[keyword echo] ' + m1[2] + ';',\n     '[keyword echo] ' + m1[3] + ';',\n     '[keyword echo] [string \"end\"];',\n     '[meta ?>]');\n\n  var m2 = build_recursive_monsters(\n    ['[string \"a][variable-2 $]{[variable aaa] [operator +] ', ' [operator +] ', '}[string .a\"]'],\n    '[comment /* }?>{{ */] [string \"a?>}{{aa][variable-2 $aaa][string .a}a?>a\"]',\n    5\n  );\n\n  MT('variable_interpolation_complex_syntax_3_2',\n     '[meta <?php] [comment /* Recursive monsters 2 */]',\n     '[keyword echo] ' + m2[0] + ';',\n     '[keyword echo] ' + m2[1] + ';',\n     '[keyword echo] ' + m2[5] + ';',\n     '[keyword echo] ' + m2[4] + ';',\n     '[keyword echo] ' + m2[2] + ';',\n     '[keyword echo] ' + m2[3] + ';',\n     '[keyword echo] [string \"end\"];',\n     '[meta ?>]');\n\n  function build_recursive_monsters_2(mf1, mf2, nt, t, n){\n    var monsters = [t];\n    for (var i = 1; i <= n; ++i)\n      monsters[i] = nt[0] + mf1[i - 1] + nt[1] + mf2[i - 1] + nt[2] + monsters[i - 1] + nt[3];\n    return monsters;\n  }\n\n  var m3 = build_recursive_monsters_2(\n    m1,\n    m2,\n    ['[string \"a][variable-2 $]{[variable aaa] [operator +] ', ' [operator +] ', ' [operator +] ', '}[string .a\"]'],\n    '[comment /* }?>{{ */] [string \"a?>}{{aa][variable-2 $aaa][string .a}a?>a\"]',\n    4\n  );\n\n  MT('variable_interpolation_complex_syntax_3_3',\n     '[meta <?php] [comment /* Recursive monsters 2 */]',\n     '[keyword echo] ' + m3[4] + ';',\n     '[keyword echo] ' + m3[0] + ';',\n     '[keyword echo] ' + m3[3] + ';',\n     '[keyword echo] ' + m3[1] + ';',\n     '[keyword echo] ' + m3[2] + ';',\n     '[keyword echo] [string \"end\"];',\n     '[meta ?>]');\n\n  MT(\"variable_interpolation_heredoc\",\n     \"[meta <?php]\",\n     \"[string <<<here]\",\n     \"[string doc ][variable-2 $]{[variable yay]}[string more]\",\n     \"[string here]; [comment // normal]\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/pig/index.html",
    "content": "﻿<!doctype html>\n<title>CodeMirror: Pig Latin mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"pig.js\"></script>\n<style>.CodeMirror {border: 2px inset #dee;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Pig Latin</a>\n  </ul>\n</div>\n\n<article>\n<h2>Pig Latin mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n-- Apache Pig (Pig Latin Language) Demo\n/* \nThis is a multiline comment.\n*/\na = LOAD \"\\path\\to\\input\" USING PigStorage('\\t') AS (x:long, y:chararray, z:bytearray);\nb = GROUP a BY (x,y,3+4);\nc = FOREACH b GENERATE flatten(group) as (x,y), SUM(group.$2) as z;\nSTORE c INTO \"\\path\\to\\output\";\n\n--\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        indentUnit: 4,\n        mode: \"text/x-pig\"\n      });\n    </script>\n\n    <p>\n        Simple mode that handles Pig Latin language.\n    </p>\n\n    <p><strong>MIME type defined:</strong> <code>text/x-pig</code>\n    (PIG code)\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/pig/pig.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/*\n *      Pig Latin Mode for CodeMirror 2\n *      @author Prasanth Jayachandran\n *      @link   https://github.com/prasanthj/pig-codemirror-2\n *  This implementation is adapted from PL/SQL mode in CodeMirror 2.\n */\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"pig\", function(_config, parserConfig) {\n  var keywords = parserConfig.keywords,\n  builtins = parserConfig.builtins,\n  types = parserConfig.types,\n  multiLineStrings = parserConfig.multiLineStrings;\n\n  var isOperatorChar = /[*+\\-%<>=&?:\\/!|]/;\n\n  function chain(stream, state, f) {\n    state.tokenize = f;\n    return f(stream, state);\n  }\n\n  function tokenComment(stream, state) {\n    var isEnd = false;\n    var ch;\n    while(ch = stream.next()) {\n      if(ch == \"/\" && isEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      isEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while((next = stream.next()) != null) {\n        if (next == quote && !escaped) {\n          end = true; break;\n        }\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end || !(escaped || multiLineStrings))\n        state.tokenize = tokenBase;\n      return \"error\";\n    };\n  }\n\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n\n    // is a start of string?\n    if (ch == '\"' || ch == \"'\")\n      return chain(stream, state, tokenString(ch));\n    // is it one of the special chars\n    else if(/[\\[\\]{}\\(\\),;\\.]/.test(ch))\n      return null;\n    // is it a number?\n    else if(/\\d/.test(ch)) {\n      stream.eatWhile(/[\\w\\.]/);\n      return \"number\";\n    }\n    // multi line comment or operator\n    else if (ch == \"/\") {\n      if (stream.eat(\"*\")) {\n        return chain(stream, state, tokenComment);\n      }\n      else {\n        stream.eatWhile(isOperatorChar);\n        return \"operator\";\n      }\n    }\n    // single line comment or operator\n    else if (ch==\"-\") {\n      if(stream.eat(\"-\")){\n        stream.skipToEnd();\n        return \"comment\";\n      }\n      else {\n        stream.eatWhile(isOperatorChar);\n        return \"operator\";\n      }\n    }\n    // is it an operator\n    else if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return \"operator\";\n    }\n    else {\n      // get the while word\n      stream.eatWhile(/[\\w\\$_]/);\n      // is it one of the listed keywords?\n      if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {\n        //keywords can be used as variables like flatten(group), group.$0 etc..\n        if (!stream.eat(\")\") && !stream.eat(\".\"))\n          return \"keyword\";\n      }\n      // is it one of the builtin functions?\n      if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase()))\n        return \"variable-2\";\n      // is it one of the listed types?\n      if (types && types.propertyIsEnumerable(stream.current().toUpperCase()))\n        return \"variable-3\";\n      // default is a 'variable'\n      return \"variable\";\n    }\n  }\n\n  // Interface\n  return {\n    startState: function() {\n      return {\n        tokenize: tokenBase,\n        startOfLine: true\n      };\n    },\n\n    token: function(stream, state) {\n      if(stream.eatSpace()) return null;\n      var style = state.tokenize(stream, state);\n      return style;\n    }\n  };\n});\n\n(function() {\n  function keywords(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  // builtin funcs taken from trunk revision 1303237\n  var pBuiltins = \"ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL \"\n    + \"CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS \"\n    + \"DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG \"\n    + \"FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN \"\n    + \"INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER \"\n    + \"ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS \"\n    + \"LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA  \"\n    + \"PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE \"\n    + \"SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG \"\n    + \"TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER \";\n\n  // taken from QueryLexer.g\n  var pKeywords = \"VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP \"\n    + \"JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL \"\n    + \"PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE \"\n    + \"SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE \"\n    + \"NEQ MATCHES TRUE FALSE DUMP\";\n\n  // data types\n  var pTypes = \"BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP \";\n\n  CodeMirror.defineMIME(\"text/x-pig\", {\n    name: \"pig\",\n    builtins: keywords(pBuiltins),\n    keywords: keywords(pKeywords),\n    types: keywords(pTypes)\n  });\n\n  CodeMirror.registerHelper(\"hintWords\", \"pig\", (pBuiltins + pTypes + pKeywords).split(\" \"));\n}());\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/powershell/index.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <title>CodeMirror: Powershell mode</title>\n    <link rel=\"stylesheet\" href=\"../../doc/docs.css\">\n    <link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n    <script src=\"../../lib/codemirror.js\"></script>\n    <script src=\"../../addon/edit/matchbrackets.js\"></script>\n    <script src=\"powershell.js\"></script>\n    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n  </head>\n  <body>\n    <div id=nav>\n      <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n      <ul>\n        <li><a href=\"../../index.html\">Home</a>\n        <li><a href=\"../../doc/manual.html\">Manual</a>\n        <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n      </ul>\n      <ul>\n        <li><a href=\"../index.html\">Language modes</a>\n        <li><a class=active href=\"#\">JavaScript</a>\n      </ul>\n    </div>\n    <article>\n      <h2>PowerShell mode</h2>\n\n      <div><textarea id=\"code\" name=\"code\">\n# Number Literals\n0 12345\n12kb 12mb 12gB 12Tb 12PB 12L 12D 12lkb 12dtb\n1.234 1.234e56 1. 1.e2 .2 .2e34\n1.2MB 1.kb .1dTb 1.e1gb\n0x1 0xabcdef 0x3tb 0xelmb\n\n# String Literals\n'Literal escaping'''\n'Literal $variable'\n\"Escaping 1`\"\"\n\"Escaping 2\"\"\"\n\"Escaped `$variable\"\n\"Text, $variable and more text\"\n\"Text, ${variable with spaces} and more text.\"\n\"Text, $($expression + 3) and more text.\"\n\"Text, $(\"interpolation $(\"inception\")\") and more text.\"\n\n@\"\nMultiline\nstring\n\"@\n# --\n@\"\nMultiline\nstring with quotes \"'\n\"@\n# --\n@'\nMultiline literal\nstring with quotes \"'\n'@\n\n# Array and Hash literals\n@( 'a','b','c' )\n@{ 'key': 'value' }\n\n# Variables\n$Variable = 5\n$global:variable = 5\n${Variable with spaces} = 5\n\n# Operators\n= += -= *= /= %=\n++ -- .. -f * / % + -\n-not ! -bnot\n-split -isplit -csplit\n-join\n-is -isnot -as\n-eq -ieq -ceq -ne -ine -cne\n-gt -igt -cgt -ge -ige -cge\n-lt -ilt -clt -le -ile -cle\n-like -ilike -clike -notlike -inotlike -cnotlike\n-match -imatch -cmatch -notmatch -inotmatch -cnotmatch\n-contains -icontains -ccontains -notcontains -inotcontains -cnotcontains\n-replace -ireplace -creplace\n-band\t-bor -bxor\n-and -or -xor\n\n# Punctuation\n() [] {} , : ` = ; .\n\n# Keywords\nelseif begin function for foreach return else trap while do data dynamicparam\nuntil end break if throw param continue finally in switch exit filter from try\nprocess catch\n\n# Built-in variables\n$$ $? $^ $_\n$args $ConfirmPreference $ConsoleFileName $DebugPreference $Error\n$ErrorActionPreference $ErrorView $ExecutionContext $false $FormatEnumerationLimit\n$HOME $Host $input $MaximumAliasCount $MaximumDriveCount $MaximumErrorCount\n$MaximumFunctionCount $MaximumHistoryCount $MaximumVariableCount $MyInvocation\n$NestedPromptLevel $null $OutputEncoding $PID $PROFILE $ProgressPreference\n$PSBoundParameters $PSCommandPath $PSCulture $PSDefaultParameterValues\n$PSEmailServer $PSHOME $PSScriptRoot $PSSessionApplicationName\n$PSSessionConfigurationName $PSSessionOption $PSUICulture $PSVersionTable $PWD\n$ShellId $StackTrace $true $VerbosePreference $WarningPreference $WhatIfPreference\n$true $false $null\n\n# Built-in functions\nA:\nAdd-Computer Add-Content Add-History Add-Member Add-PSSnapin Add-Type\nB:\nC:\nCheckpoint-Computer Clear-Content Clear-EventLog Clear-History Clear-Host Clear-Item\nClear-ItemProperty Clear-Variable Compare-Object Complete-Transaction Connect-PSSession\nConvertFrom-Csv ConvertFrom-Json ConvertFrom-SecureString ConvertFrom-StringData\nConvert-Path ConvertTo-Csv ConvertTo-Html ConvertTo-Json ConvertTo-SecureString\nConvertTo-Xml Copy-Item Copy-ItemProperty\nD:\nDebug-Process Disable-ComputerRestore Disable-PSBreakpoint Disable-PSRemoting\nDisable-PSSessionConfiguration Disconnect-PSSession\nE:\nEnable-ComputerRestore Enable-PSBreakpoint Enable-PSRemoting Enable-PSSessionConfiguration\nEnter-PSSession Exit-PSSession Export-Alias Export-Clixml Export-Console Export-Counter\nExport-Csv Export-FormatData Export-ModuleMember Export-PSSession\nF:\nForEach-Object Format-Custom Format-List Format-Table Format-Wide\nG:\nGet-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-ComputerRestorePoint\nGet-Content Get-ControlPanelItem Get-Counter Get-Credential Get-Culture Get-Date\nGet-Event Get-EventLog Get-EventSubscriber Get-ExecutionPolicy Get-FormatData Get-Help\nGet-History Get-Host Get-HotFix Get-Item Get-ItemProperty Get-Job Get-Location Get-Member\nGet-Module Get-PfxCertificate Get-Process Get-PSBreakpoint Get-PSCallStack Get-PSDrive\nGet-PSProvider Get-PSSession Get-PSSessionConfiguration Get-PSSnapin Get-Random Get-Service\nGet-TraceSource Get-Transaction Get-TypeData Get-UICulture  Get-Unique Get-Variable Get-Verb\nGet-WinEvent Get-WmiObject Group-Object\nH:\nhelp\nI:\nImport-Alias Import-Clixml Import-Counter Import-Csv Import-LocalizedData Import-Module\nImport-PSSession ImportSystemModules Invoke-Command Invoke-Expression Invoke-History\nInvoke-Item Invoke-RestMethod Invoke-WebRequest Invoke-WmiMethod\nJ:\nJoin-Path\nK:\nL:\nLimit-EventLog\nM:\nMeasure-Command Measure-Object mkdir more Move-Item Move-ItemProperty\nN:\nNew-Alias New-Event New-EventLog New-Item New-ItemProperty New-Module New-ModuleManifest\nNew-Object New-PSDrive New-PSSession New-PSSessionConfigurationFile New-PSSessionOption\nNew-PSTransportOption New-Service New-TimeSpan New-Variable New-WebServiceProxy\nNew-WinEvent\nO:\noss Out-Default Out-File Out-GridView Out-Host Out-Null Out-Printer Out-String\nP:\nPause Pop-Location prompt Push-Location\nQ:\nR:\nRead-Host Receive-Job Receive-PSSession Register-EngineEvent Register-ObjectEvent\nRegister-PSSessionConfiguration Register-WmiEvent Remove-Computer Remove-Event\nRemove-EventLog Remove-Item Remove-ItemProperty Remove-Job Remove-Module\nRemove-PSBreakpoint Remove-PSDrive Remove-PSSession Remove-PSSnapin Remove-TypeData\nRemove-Variable Remove-WmiObject Rename-Computer Rename-Item Rename-ItemProperty\nReset-ComputerMachinePassword Resolve-Path Restart-Computer Restart-Service\nRestore-Computer Resume-Job Resume-Service\nS:\nSave-Help Select-Object Select-String Select-Xml Send-MailMessage Set-Acl Set-Alias\nSet-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item\nSet-ItemProperty Set-Location Set-PSBreakpoint Set-PSDebug\nSet-PSSessionConfiguration Set-Service Set-StrictMode Set-TraceSource Set-Variable\nSet-WmiInstance Show-Command Show-ControlPanelItem Show-EventLog Sort-Object\nSplit-Path Start-Job Start-Process Start-Service Start-Sleep Start-Transaction\nStart-Transcript Stop-Computer Stop-Job Stop-Process Stop-Service Stop-Transcript\nSuspend-Job Suspend-Service\nT:\nTabExpansion2 Tee-Object Test-ComputerSecureChannel Test-Connection\nTest-ModuleManifest Test-Path Test-PSSessionConfigurationFile Trace-Command\nU:\nUnblock-File Undo-Transaction Unregister-Event Unregister-PSSessionConfiguration\nUpdate-FormatData Update-Help Update-List Update-TypeData Use-Transaction\nV:\nW:\nWait-Event Wait-Job Wait-Process Where-Object Write-Debug Write-Error Write-EventLog\nWrite-Host Write-Output Write-Progress Write-Verbose Write-Warning\nX:\nY:\nZ:</textarea></div>\n      <script>\n        var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n          mode: \"powershell\",\n          lineNumbers: true,\n          indentUnit: 4,\n          tabMode: \"shift\",\n          matchBrackets: true\n        });\n      </script>\n\n      <p><strong>MIME types defined:</strong> <code>application/x-powershell</code>.</p>\n    </article>\n  </body>\n</html>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/powershell/powershell.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  'use strict';\n  if (typeof exports == 'object' && typeof module == 'object') // CommonJS\n    mod(require('../../lib/codemirror'));\n  else if (typeof define == 'function' && define.amd) // AMD\n    define(['../../lib/codemirror'], mod);\n  else // Plain browser env\n    mod(window.CodeMirror);\n})(function(CodeMirror) {\n'use strict';\n\nCodeMirror.defineMode('powershell', function() {\n  function buildRegexp(patterns, options) {\n    options = options || {};\n    var prefix = options.prefix !== undefined ? options.prefix : '^';\n    var suffix = options.suffix !== undefined ? options.suffix : '\\\\b';\n\n    for (var i = 0; i < patterns.length; i++) {\n      if (patterns[i] instanceof RegExp) {\n        patterns[i] = patterns[i].source;\n      }\n      else {\n        patterns[i] = patterns[i].replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n      }\n    }\n\n    return new RegExp(prefix + '(' + patterns.join('|') + ')' + suffix, 'i');\n  }\n\n  var notCharacterOrDash = '(?=[^A-Za-z\\\\d\\\\-_]|$)';\n  var varNames = /[\\w\\-:]/\n  var keywords = buildRegexp([\n    /begin|break|catch|continue|data|default|do|dynamicparam/,\n    /else|elseif|end|exit|filter|finally|for|foreach|from|function|if|in/,\n    /param|process|return|switch|throw|trap|try|until|where|while/\n  ], { suffix: notCharacterOrDash });\n\n  var punctuation = /[\\[\\]{},;`\\.]|@[({]/;\n  var wordOperators = buildRegexp([\n    'f',\n    /b?not/,\n    /[ic]?split/, 'join',\n    /is(not)?/, 'as',\n    /[ic]?(eq|ne|[gl][te])/,\n    /[ic]?(not)?(like|match|contains)/,\n    /[ic]?replace/,\n    /b?(and|or|xor)/\n  ], { prefix: '-' });\n  var symbolOperators = /[+\\-*\\/%]=|\\+\\+|--|\\.\\.|[+\\-*&^%:=!|\\/]|<(?!#)|(?!#)>/;\n  var operators = buildRegexp([wordOperators, symbolOperators], { suffix: '' });\n\n  var numbers = /^((0x[\\da-f]+)|((\\d+\\.\\d+|\\d\\.|\\.\\d+|\\d+)(e[\\+\\-]?\\d+)?))[ld]?([kmgtp]b)?/i;\n\n  var identifiers = /^[A-Za-z\\_][A-Za-z\\-\\_\\d]*\\b/;\n\n  var symbolBuiltins = /[A-Z]:|%|\\?/i;\n  var namedBuiltins = buildRegexp([\n    /Add-(Computer|Content|History|Member|PSSnapin|Type)/,\n    /Checkpoint-Computer/,\n    /Clear-(Content|EventLog|History|Host|Item(Property)?|Variable)/,\n    /Compare-Object/,\n    /Complete-Transaction/,\n    /Connect-PSSession/,\n    /ConvertFrom-(Csv|Json|SecureString|StringData)/,\n    /Convert-Path/,\n    /ConvertTo-(Csv|Html|Json|SecureString|Xml)/,\n    /Copy-Item(Property)?/,\n    /Debug-Process/,\n    /Disable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/,\n    /Disconnect-PSSession/,\n    /Enable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/,\n    /(Enter|Exit)-PSSession/,\n    /Export-(Alias|Clixml|Console|Counter|Csv|FormatData|ModuleMember|PSSession)/,\n    /ForEach-Object/,\n    /Format-(Custom|List|Table|Wide)/,\n    new RegExp('Get-(Acl|Alias|AuthenticodeSignature|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Counter|Credential'\n      + '|Culture|Date|Event|EventLog|EventSubscriber|ExecutionPolicy|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job'\n      + '|Location|Member|Module|PfxCertificate|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration'\n      + '|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|Verb|WinEvent|WmiObject)'),\n    /Group-Object/,\n    /Import-(Alias|Clixml|Counter|Csv|LocalizedData|Module|PSSession)/,\n    /ImportSystemModules/,\n    /Invoke-(Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)/,\n    /Join-Path/,\n    /Limit-EventLog/,\n    /Measure-(Command|Object)/,\n    /Move-Item(Property)?/,\n    new RegExp('New-(Alias|Event|EventLog|Item(Property)?|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile'\n      + '|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy|WinEvent)'),\n    /Out-(Default|File|GridView|Host|Null|Printer|String)/,\n    /Pause/,\n    /(Pop|Push)-Location/,\n    /Read-Host/,\n    /Receive-(Job|PSSession)/,\n    /Register-(EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)/,\n    /Remove-(Computer|Event|EventLog|Item(Property)?|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)/,\n    /Rename-(Computer|Item(Property)?)/,\n    /Reset-ComputerMachinePassword/,\n    /Resolve-Path/,\n    /Restart-(Computer|Service)/,\n    /Restore-Computer/,\n    /Resume-(Job|Service)/,\n    /Save-Help/,\n    /Select-(Object|String|Xml)/,\n    /Send-MailMessage/,\n    new RegExp('Set-(Acl|Alias|AuthenticodeSignature|Content|Date|ExecutionPolicy|Item(Property)?|Location|PSBreakpoint|PSDebug' +\n               '|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)'),\n    /Show-(Command|ControlPanelItem|EventLog)/,\n    /Sort-Object/,\n    /Split-Path/,\n    /Start-(Job|Process|Service|Sleep|Transaction|Transcript)/,\n    /Stop-(Computer|Job|Process|Service|Transcript)/,\n    /Suspend-(Job|Service)/,\n    /TabExpansion2/,\n    /Tee-Object/,\n    /Test-(ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)/,\n    /Trace-Command/,\n    /Unblock-File/,\n    /Undo-Transaction/,\n    /Unregister-(Event|PSSessionConfiguration)/,\n    /Update-(FormatData|Help|List|TypeData)/,\n    /Use-Transaction/,\n    /Wait-(Event|Job|Process)/,\n    /Where-Object/,\n    /Write-(Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning)/,\n    /cd|help|mkdir|more|oss|prompt/,\n    /ac|asnp|cat|cd|chdir|clc|clear|clhy|cli|clp|cls|clv|cnsn|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|dnsn|ebp/,\n    /echo|epal|epcsv|epsn|erase|etsn|exsn|fc|fl|foreach|ft|fw|gal|gbp|gc|gci|gcm|gcs|gdr|ghy|gi|gjb|gl|gm|gmo|gp|gps/,\n    /group|gsn|gsnp|gsv|gu|gv|gwmi|h|history|icm|iex|ihy|ii|ipal|ipcsv|ipmo|ipsn|irm|ise|iwmi|iwr|kill|lp|ls|man|md/,\n    /measure|mi|mount|move|mp|mv|nal|ndr|ni|nmo|npssc|nsn|nv|ogv|oh|popd|ps|pushd|pwd|r|rbp|rcjb|rcsn|rd|rdr|ren|ri/,\n    /rjb|rm|rmdir|rmo|rni|rnp|rp|rsn|rsnp|rujb|rv|rvpa|rwmi|sajb|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls/,\n    /sort|sp|spjb|spps|spsv|start|sujb|sv|swmi|tee|trcm|type|where|wjb|write/\n  ], { prefix: '', suffix: '' });\n  var variableBuiltins = buildRegexp([\n    /[$?^_]|Args|ConfirmPreference|ConsoleFileName|DebugPreference|Error|ErrorActionPreference|ErrorView|ExecutionContext/,\n    /FormatEnumerationLimit|Home|Host|Input|MaximumAliasCount|MaximumDriveCount|MaximumErrorCount|MaximumFunctionCount/,\n    /MaximumHistoryCount|MaximumVariableCount|MyInvocation|NestedPromptLevel|OutputEncoding|Pid|Profile|ProgressPreference/,\n    /PSBoundParameters|PSCommandPath|PSCulture|PSDefaultParameterValues|PSEmailServer|PSHome|PSScriptRoot|PSSessionApplicationName/,\n    /PSSessionConfigurationName|PSSessionOption|PSUICulture|PSVersionTable|Pwd|ShellId|StackTrace|VerbosePreference/,\n    /WarningPreference|WhatIfPreference/,\n\n    /Event|EventArgs|EventSubscriber|Sender/,\n    /Matches|Ofs|ForEach|LastExitCode|PSCmdlet|PSItem|PSSenderInfo|This/,\n    /true|false|null/\n  ], { prefix: '\\\\$', suffix: '' });\n\n  var builtins = buildRegexp([symbolBuiltins, namedBuiltins, variableBuiltins], { suffix: notCharacterOrDash });\n\n  var grammar = {\n    keyword: keywords,\n    number: numbers,\n    operator: operators,\n    builtin: builtins,\n    punctuation: punctuation,\n    identifier: identifiers\n  };\n\n  // tokenizers\n  function tokenBase(stream, state) {\n    // Handle Comments\n    //var ch = stream.peek();\n\n    var parent = state.returnStack[state.returnStack.length - 1];\n    if (parent && parent.shouldReturnFrom(state)) {\n      state.tokenize = parent.tokenize;\n      state.returnStack.pop();\n      return state.tokenize(stream, state);\n    }\n\n    if (stream.eatSpace()) {\n      return null;\n    }\n\n    if (stream.eat('(')) {\n      state.bracketNesting += 1;\n      return 'punctuation';\n    }\n\n    if (stream.eat(')')) {\n      state.bracketNesting -= 1;\n      return 'punctuation';\n    }\n\n    for (var key in grammar) {\n      if (stream.match(grammar[key])) {\n        return key;\n      }\n    }\n\n    var ch = stream.next();\n\n    // single-quote string\n    if (ch === \"'\") {\n      return tokenSingleQuoteString(stream, state);\n    }\n\n    if (ch === '$') {\n      return tokenVariable(stream, state);\n    }\n\n    // double-quote string\n    if (ch === '\"') {\n      return tokenDoubleQuoteString(stream, state);\n    }\n\n    if (ch === '<' && stream.eat('#')) {\n      state.tokenize = tokenComment;\n      return tokenComment(stream, state);\n    }\n\n    if (ch === '#') {\n      stream.skipToEnd();\n      return 'comment';\n    }\n\n    if (ch === '@') {\n      var quoteMatch = stream.eat(/[\"']/);\n      if (quoteMatch && stream.eol()) {\n        state.tokenize = tokenMultiString;\n        state.startQuote = quoteMatch[0];\n        return tokenMultiString(stream, state);\n      } else if (stream.eol()) {\n        return 'error';\n      } else if (stream.peek().match(/[({]/)) {\n        return 'punctuation';\n      } else if (stream.peek().match(varNames)) {\n        // splatted variable\n        return tokenVariable(stream, state);\n      }\n    }\n    return 'error';\n  }\n\n  function tokenSingleQuoteString(stream, state) {\n    var ch;\n    while ((ch = stream.peek()) != null) {\n      stream.next();\n\n      if (ch === \"'\" && !stream.eat(\"'\")) {\n        state.tokenize = tokenBase;\n        return 'string';\n      }\n    }\n\n    return 'error';\n  }\n\n  function tokenDoubleQuoteString(stream, state) {\n    var ch;\n    while ((ch = stream.peek()) != null) {\n      if (ch === '$') {\n        state.tokenize = tokenStringInterpolation;\n        return 'string';\n      }\n\n      stream.next();\n      if (ch === '`') {\n        stream.next();\n        continue;\n      }\n\n      if (ch === '\"' && !stream.eat('\"')) {\n        state.tokenize = tokenBase;\n        return 'string';\n      }\n    }\n\n    return 'error';\n  }\n\n  function tokenStringInterpolation(stream, state) {\n    return tokenInterpolation(stream, state, tokenDoubleQuoteString);\n  }\n\n  function tokenMultiStringReturn(stream, state) {\n    state.tokenize = tokenMultiString;\n    state.startQuote = '\"'\n    return tokenMultiString(stream, state);\n  }\n\n  function tokenHereStringInterpolation(stream, state) {\n    return tokenInterpolation(stream, state, tokenMultiStringReturn);\n  }\n\n  function tokenInterpolation(stream, state, parentTokenize) {\n    if (stream.match('$(')) {\n      var savedBracketNesting = state.bracketNesting;\n      state.returnStack.push({\n        /*jshint loopfunc:true */\n        shouldReturnFrom: function(state) {\n          return state.bracketNesting === savedBracketNesting;\n        },\n        tokenize: parentTokenize\n      });\n      state.tokenize = tokenBase;\n      state.bracketNesting += 1;\n      return 'punctuation';\n    } else {\n      stream.next();\n      state.returnStack.push({\n        shouldReturnFrom: function() { return true; },\n        tokenize: parentTokenize\n      });\n      state.tokenize = tokenVariable;\n      return state.tokenize(stream, state);\n    }\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while ((ch = stream.next()) != null) {\n      if (maybeEnd && ch == '>') {\n          state.tokenize = tokenBase;\n          break;\n      }\n      maybeEnd = (ch === '#');\n    }\n    return 'comment';\n  }\n\n  function tokenVariable(stream, state) {\n    var ch = stream.peek();\n    if (stream.eat('{')) {\n      state.tokenize = tokenVariableWithBraces;\n      return tokenVariableWithBraces(stream, state);\n    } else if (ch != undefined && ch.match(varNames)) {\n      stream.eatWhile(varNames);\n      state.tokenize = tokenBase;\n      return 'variable-2';\n    } else {\n      state.tokenize = tokenBase;\n      return 'error';\n    }\n  }\n\n  function tokenVariableWithBraces(stream, state) {\n    var ch;\n    while ((ch = stream.next()) != null) {\n      if (ch === '}') {\n        state.tokenize = tokenBase;\n        break;\n      }\n    }\n    return 'variable-2';\n  }\n\n  function tokenMultiString(stream, state) {\n    var quote = state.startQuote;\n    if (stream.sol() && stream.match(new RegExp(quote + '@'))) {\n      state.tokenize = tokenBase;\n    }\n    else if (quote === '\"') {\n      while (!stream.eol()) {\n        var ch = stream.peek();\n        if (ch === '$') {\n          state.tokenize = tokenHereStringInterpolation;\n          return 'string';\n        }\n\n        stream.next();\n        if (ch === '`') {\n          stream.next();\n        }\n      }\n    }\n    else {\n      stream.skipToEnd();\n    }\n\n    return 'string';\n  }\n\n  var external = {\n    startState: function() {\n      return {\n        returnStack: [],\n        bracketNesting: 0,\n        tokenize: tokenBase\n      };\n    },\n\n    token: function(stream, state) {\n      return state.tokenize(stream, state);\n    },\n\n    blockCommentStart: '<#',\n    blockCommentEnd: '#>',\n    lineComment: '#',\n    fold: 'brace'\n  };\n  return external;\n});\n\nCodeMirror.defineMIME('application/x-powershell', 'powershell');\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/powershell/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"powershell\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  function forEach(arr, f) { for (var i = 0; i < arr.length; i++) f(arr[i], i) }\n\n  MT('comment', '[number 1][comment # A]');\n  MT('comment_multiline', '[number 1][comment <#]',\n    '[comment ABC]',\n  '[comment #>][number 2]');\n\n  forEach([\n    '0', '1234',\n    '12kb', '12mb', '12Gb', '12Tb', '12PB', '12L', '12D', '12lkb', '12dtb',\n    '1.234', '1.234e56', '1.', '1.e2', '.2', '.2e34',\n    '1.2MB', '1.kb', '.1dTB', '1.e1gb', '.2', '.2e34',\n    '0x1', '0xabcdef', '0x3tb', '0xelmb'\n  ], function(number) {\n    MT(\"number_\" + number, \"[number \" + number + \"]\");\n  });\n\n  MT('string_literal_escaping', \"[string 'a''']\");\n  MT('string_literal_variable', \"[string 'a $x']\");\n  MT('string_escaping_1', '[string \"a `\"\"]');\n  MT('string_escaping_2', '[string \"a \"\"\"]');\n  MT('string_variable_escaping', '[string \"a `$x\"]');\n  MT('string_variable', '[string \"a ][variable-2 $x][string  b\"]');\n  MT('string_variable_spaces', '[string \"a ][variable-2 ${x y}][string  b\"]');\n  MT('string_expression', '[string \"a ][punctuation $(][variable-2 $x][operator +][number 3][punctuation )][string  b\"]');\n  MT('string_expression_nested', '[string \"A][punctuation $(][string \"a][punctuation $(][string \"w\"][punctuation )][string b\"][punctuation )][string B\"]');\n\n  MT('string_heredoc', '[string @\"]',\n    '[string abc]',\n  '[string \"@]');\n  MT('string_heredoc_quotes', '[string @\"]',\n    '[string abc \"\\']',\n  '[string \"@]');\n  MT('string_heredoc_variable', '[string @\"]',\n    '[string a ][variable-2 $x][string  b]',\n  '[string \"@]');\n  MT('string_heredoc_nested_string', '[string @\"]',\n    '[string a][punctuation $(][string \"w\"][punctuation )][string b]',\n  '[string \"@]');\n  MT('string_heredoc_literal_quotes', \"[string @']\",\n    '[string abc \"\\']',\n  \"[string '@]\");\n\n  MT('array', \"[punctuation @(][string 'a'][punctuation ,][string 'b'][punctuation )]\");\n  MT('hash', \"[punctuation @{][string 'key'][operator :][string 'value'][punctuation }]\");\n\n  MT('variable', \"[variable-2 $test]\");\n  MT('variable_global',  \"[variable-2 $global:test]\");\n  MT('variable_spaces',  \"[variable-2 ${test test}]\");\n  MT('operator_splat',   \"[variable-2 @x]\");\n  MT('variable_builtin', \"[builtin $ErrorActionPreference]\");\n  MT('variable_builtin_symbols', \"[builtin $$]\");\n\n  MT('operator', \"[operator +]\");\n  MT('operator_unary', \"[operator +][number 3]\");\n  MT('operator_long', \"[operator -match]\");\n\n  forEach([\n    '(', ')', '[[', ']]', '{', '}', ',', '`', ';', '.'\n  ], function(punctuation) {\n    MT(\"punctuation_\" + punctuation.replace(/^[\\[\\]]/,''), \"[punctuation \" + punctuation + \"]\");\n  });\n\n  MT('keyword', \"[keyword if]\");\n\n  MT('call_builtin', \"[builtin Get-ChildItem]\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/properties/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Properties files mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"properties.js\"></script>\n<style>.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Properties files</a>\n  </ul>\n</div>\n\n<article>\n<h2>Properties files mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n# This is a properties file\na.key = A value\nanother.key = http://example.com\n! Exclamation mark as comment\nbut.not=Within ! A value # indeed\n   # Spaces at the beginning of a line\n   spaces.before.key=value\nbackslash=Used for multi\\\n          line entries,\\\n          that's convenient.\n# Unicode sequences\nunicode.key=This is \\u0020 Unicode\nno.multiline=here\n# Colons\ncolons : can be used too\n# Spaces\nspaces\\ in\\ keys=Not very common...\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-properties</code>,\n    <code>text/x-ini</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/properties/properties.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"properties\", function() {\n  return {\n    token: function(stream, state) {\n      var sol = stream.sol() || state.afterSection;\n      var eol = stream.eol();\n\n      state.afterSection = false;\n\n      if (sol) {\n        if (state.nextMultiline) {\n          state.inMultiline = true;\n          state.nextMultiline = false;\n        } else {\n          state.position = \"def\";\n        }\n      }\n\n      if (eol && ! state.nextMultiline) {\n        state.inMultiline = false;\n        state.position = \"def\";\n      }\n\n      if (sol) {\n        while(stream.eatSpace()) {}\n      }\n\n      var ch = stream.next();\n\n      if (sol && (ch === \"#\" || ch === \"!\" || ch === \";\")) {\n        state.position = \"comment\";\n        stream.skipToEnd();\n        return \"comment\";\n      } else if (sol && ch === \"[\") {\n        state.afterSection = true;\n        stream.skipTo(\"]\"); stream.eat(\"]\");\n        return \"header\";\n      } else if (ch === \"=\" || ch === \":\") {\n        state.position = \"quote\";\n        return null;\n      } else if (ch === \"\\\\\" && state.position === \"quote\") {\n        if (stream.eol()) {  // end of line?\n          // Multiline value\n          state.nextMultiline = true;\n        }\n      }\n\n      return state.position;\n    },\n\n    startState: function() {\n      return {\n        position : \"def\",       // Current position, \"def\", \"quote\" or \"comment\"\n        nextMultiline : false,  // Is the next line multiline value\n        inMultiline : false,    // Is the current line a multiline value\n        afterSection : false    // Did we just open a section\n      };\n    }\n\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-properties\", \"properties\");\nCodeMirror.defineMIME(\"text/x-ini\", \"properties\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/protobuf/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: ProtoBuf mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"protobuf.js\"></script>\n<style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">ProtoBuf</a>\n  </ul>\n</div>\n\n<article>\n<h2>ProtoBuf mode</h2>\n<form><textarea id=\"code\" name=\"code\">\npackage addressbook;\n\nmessage Address {\n   required string street = 1;\n   required string postCode = 2;\n}\n\nmessage PhoneNumber {\n   required string number = 1;\n}\n\nmessage Person {\n   optional int32 id = 1;\n   required string name = 2;\n   required string surname = 3;\n   optional Address address = 4;\n   repeated PhoneNumber phoneNumbers = 5;\n   optional uint32 age = 6;\n   repeated uint32 favouriteNumbers = 7;\n   optional string license = 8;\n   enum Gender {\n      MALE = 0;\n      FEMALE = 1;\n   }\n   optional Gender gender = 9;\n   optional fixed64 lastUpdate = 10;\n   required bool deleted = 11 [default = false];\n}\n\n</textarea>\n  <textarea id=\"code2\" name=\"code2\">\nsyntax = \"proto3\";\npackage tutorial;\n\nimport \"google/protobuf/timestamp.proto\";\noption java_package = \"com.example.tutorial\";\noption java_outer_classname = \"AddressBookProtos\";\noption csharp_namespace = \"Google.Protobuf.Examples.AddressBook\";\n\nmessage Person {\n  string name = 1;\n  int32 id = 2;  // Unique ID number for this person.\n  string email = 3;\n\n  enum PhoneType {\n    MOBILE = 0;\n    HOME = 1;\n    WORK = 2;\n  }\n\n  message PhoneNumber {\n    string number = 1;\n    PhoneType type = 2;\n  }\n\n  repeated PhoneNumber phones = 4;\n\n  google.protobuf.Timestamp last_updated = 5;\n}\n\n// Our address book file is just one of these.\nmessage AddressBook {\n  repeated Person people = 1;\n}\nservice Test {\n  rpc SayHello (HelloRequest) returns (HelloReply) {}\n  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}\n}</textarea>\n</form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code2\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-protobuf</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/protobuf/protobuf.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function wordRegexp(words) {\n    return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\", \"i\");\n  };\n\n  var keywordArray = [\n    \"package\", \"message\", \"import\", \"syntax\",\n    \"required\", \"optional\", \"repeated\", \"reserved\", \"default\", \"extensions\", \"packed\",\n    \"bool\", \"bytes\", \"double\", \"enum\", \"float\", \"string\",\n    \"int32\", \"int64\", \"uint32\", \"uint64\", \"sint32\", \"sint64\", \"fixed32\", \"fixed64\", \"sfixed32\", \"sfixed64\",\n    \"option\", \"service\", \"rpc\", \"returns\"\n  ];\n  var keywords = wordRegexp(keywordArray);\n\n  CodeMirror.registerHelper(\"hintWords\", \"protobuf\", keywordArray);\n\n  var identifiers = new RegExp(\"^[_A-Za-z\\xa1-\\uffff][_A-Za-z0-9\\xa1-\\uffff]*\");\n\n  function tokenBase(stream) {\n    // whitespaces\n    if (stream.eatSpace()) return null;\n\n    // Handle one line Comments\n    if (stream.match(\"//\")) {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n\n    // Handle Number Literals\n    if (stream.match(/^[0-9\\.+-]/, false)) {\n      if (stream.match(/^[+-]?0x[0-9a-fA-F]+/))\n        return \"number\";\n      if (stream.match(/^[+-]?\\d*\\.\\d+([EeDd][+-]?\\d+)?/))\n        return \"number\";\n      if (stream.match(/^[+-]?\\d+([EeDd][+-]?\\d+)?/))\n        return \"number\";\n    }\n\n    // Handle Strings\n    if (stream.match(/^\"([^\"]|(\"\"))*\"/)) { return \"string\"; }\n    if (stream.match(/^'([^']|(''))*'/)) { return \"string\"; }\n\n    // Handle words\n    if (stream.match(keywords)) { return \"keyword\"; }\n    if (stream.match(identifiers)) { return \"variable\"; } ;\n\n    // Handle non-detected items\n    stream.next();\n    return null;\n  };\n\n  CodeMirror.defineMode(\"protobuf\", function() {\n    return {token: tokenBase};\n  });\n\n  CodeMirror.defineMIME(\"text/x-protobuf\", \"protobuf\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/pug/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Pug Templating Mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../css/css.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"pug.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Pug Templating Mode</a>\n  </ul>\n</div>\n\n<article>\n<h2>Pug Templating Mode</h2>\n<form><textarea id=\"code\" name=\"code\">\ndoctype html\n  html\n    head\n      title= \"Pug Templating CodeMirror Mode Example\"\n      link(rel='stylesheet', href='/css/bootstrap.min.css')\n      link(rel='stylesheet', href='/css/index.css')\n      script(type='text/javascript', src='/js/jquery-1.9.1.min.js')\n      script(type='text/javascript', src='/js/bootstrap.min.js')\n    body\n      div.header\n        h1 Welcome to this Example\n      div.spots\n        if locals.spots\n          each spot in spots\n            div.spot.well\n         div\n           if spot.logo\n             img.img-rounded.logo(src=spot.logo)\n           else\n             img.img-rounded.logo(src=\"img/placeholder.png\")\n         h3\n           a(href=spot.hash) ##{spot.hash}\n           if spot.title\n             span.title #{spot.title}\n           if spot.desc\n             div #{spot.desc}\n        else\n          h3 There are no spots currently available.\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"pug\", alignCDATA: true},\n        lineNumbers: true\n      });\n    </script>\n    <h3>The Pug Templating Mode</h3>\n      <p> Created by Forbes Lindesay. Managed as part of a Brackets extension at <a href=\"https://github.com/ForbesLindesay/jade-brackets\">https://github.com/ForbesLindesay/jade-brackets</a>.</p>\n    <p><strong>MIME type defined:</strong> <code>text/x-pug</code>, <code>text/x-jade</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/pug/pug.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../javascript/javascript\"), require(\"../css/css\"), require(\"../htmlmixed/htmlmixed\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../javascript/javascript\", \"../css/css\", \"../htmlmixed/htmlmixed\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"pug\", function (config) {\n  // token types\n  var KEYWORD = 'keyword';\n  var DOCTYPE = 'meta';\n  var ID = 'builtin';\n  var CLASS = 'qualifier';\n\n  var ATTRS_NEST = {\n    '{': '}',\n    '(': ')',\n    '[': ']'\n  };\n\n  var jsMode = CodeMirror.getMode(config, 'javascript');\n\n  function State() {\n    this.javaScriptLine = false;\n    this.javaScriptLineExcludesColon = false;\n\n    this.javaScriptArguments = false;\n    this.javaScriptArgumentsDepth = 0;\n\n    this.isInterpolating = false;\n    this.interpolationNesting = 0;\n\n    this.jsState = CodeMirror.startState(jsMode);\n\n    this.restOfLine = '';\n\n    this.isIncludeFiltered = false;\n    this.isEach = false;\n\n    this.lastTag = '';\n    this.scriptType = '';\n\n    // Attributes Mode\n    this.isAttrs = false;\n    this.attrsNest = [];\n    this.inAttributeName = true;\n    this.attributeIsType = false;\n    this.attrValue = '';\n\n    // Indented Mode\n    this.indentOf = Infinity;\n    this.indentToken = '';\n\n    this.innerMode = null;\n    this.innerState = null;\n\n    this.innerModeForLine = false;\n  }\n  /**\n   * Safely copy a state\n   *\n   * @return {State}\n   */\n  State.prototype.copy = function () {\n    var res = new State();\n    res.javaScriptLine = this.javaScriptLine;\n    res.javaScriptLineExcludesColon = this.javaScriptLineExcludesColon;\n    res.javaScriptArguments = this.javaScriptArguments;\n    res.javaScriptArgumentsDepth = this.javaScriptArgumentsDepth;\n    res.isInterpolating = this.isInterpolating;\n    res.interpolationNesting = this.interpolationNesting;\n\n    res.jsState = CodeMirror.copyState(jsMode, this.jsState);\n\n    res.innerMode = this.innerMode;\n    if (this.innerMode && this.innerState) {\n      res.innerState = CodeMirror.copyState(this.innerMode, this.innerState);\n    }\n\n    res.restOfLine = this.restOfLine;\n\n    res.isIncludeFiltered = this.isIncludeFiltered;\n    res.isEach = this.isEach;\n    res.lastTag = this.lastTag;\n    res.scriptType = this.scriptType;\n    res.isAttrs = this.isAttrs;\n    res.attrsNest = this.attrsNest.slice();\n    res.inAttributeName = this.inAttributeName;\n    res.attributeIsType = this.attributeIsType;\n    res.attrValue = this.attrValue;\n    res.indentOf = this.indentOf;\n    res.indentToken = this.indentToken;\n\n    res.innerModeForLine = this.innerModeForLine;\n\n    return res;\n  };\n\n  function javaScript(stream, state) {\n    if (stream.sol()) {\n      // if javaScriptLine was set at end of line, ignore it\n      state.javaScriptLine = false;\n      state.javaScriptLineExcludesColon = false;\n    }\n    if (state.javaScriptLine) {\n      if (state.javaScriptLineExcludesColon && stream.peek() === ':') {\n        state.javaScriptLine = false;\n        state.javaScriptLineExcludesColon = false;\n        return;\n      }\n      var tok = jsMode.token(stream, state.jsState);\n      if (stream.eol()) state.javaScriptLine = false;\n      return tok || true;\n    }\n  }\n  function javaScriptArguments(stream, state) {\n    if (state.javaScriptArguments) {\n      if (state.javaScriptArgumentsDepth === 0 && stream.peek() !== '(') {\n        state.javaScriptArguments = false;\n        return;\n      }\n      if (stream.peek() === '(') {\n        state.javaScriptArgumentsDepth++;\n      } else if (stream.peek() === ')') {\n        state.javaScriptArgumentsDepth--;\n      }\n      if (state.javaScriptArgumentsDepth === 0) {\n        state.javaScriptArguments = false;\n        return;\n      }\n\n      var tok = jsMode.token(stream, state.jsState);\n      return tok || true;\n    }\n  }\n\n  function yieldStatement(stream) {\n    if (stream.match(/^yield\\b/)) {\n        return 'keyword';\n    }\n  }\n\n  function doctype(stream) {\n    if (stream.match(/^(?:doctype) *([^\\n]+)?/)) {\n        return DOCTYPE;\n    }\n  }\n\n  function interpolation(stream, state) {\n    if (stream.match('#{')) {\n      state.isInterpolating = true;\n      state.interpolationNesting = 0;\n      return 'punctuation';\n    }\n  }\n\n  function interpolationContinued(stream, state) {\n    if (state.isInterpolating) {\n      if (stream.peek() === '}') {\n        state.interpolationNesting--;\n        if (state.interpolationNesting < 0) {\n          stream.next();\n          state.isInterpolating = false;\n          return 'punctuation';\n        }\n      } else if (stream.peek() === '{') {\n        state.interpolationNesting++;\n      }\n      return jsMode.token(stream, state.jsState) || true;\n    }\n  }\n\n  function caseStatement(stream, state) {\n    if (stream.match(/^case\\b/)) {\n      state.javaScriptLine = true;\n      return KEYWORD;\n    }\n  }\n\n  function when(stream, state) {\n    if (stream.match(/^when\\b/)) {\n      state.javaScriptLine = true;\n      state.javaScriptLineExcludesColon = true;\n      return KEYWORD;\n    }\n  }\n\n  function defaultStatement(stream) {\n    if (stream.match(/^default\\b/)) {\n      return KEYWORD;\n    }\n  }\n\n  function extendsStatement(stream, state) {\n    if (stream.match(/^extends?\\b/)) {\n      state.restOfLine = 'string';\n      return KEYWORD;\n    }\n  }\n\n  function append(stream, state) {\n    if (stream.match(/^append\\b/)) {\n      state.restOfLine = 'variable';\n      return KEYWORD;\n    }\n  }\n  function prepend(stream, state) {\n    if (stream.match(/^prepend\\b/)) {\n      state.restOfLine = 'variable';\n      return KEYWORD;\n    }\n  }\n  function block(stream, state) {\n    if (stream.match(/^block\\b *(?:(prepend|append)\\b)?/)) {\n      state.restOfLine = 'variable';\n      return KEYWORD;\n    }\n  }\n\n  function include(stream, state) {\n    if (stream.match(/^include\\b/)) {\n      state.restOfLine = 'string';\n      return KEYWORD;\n    }\n  }\n\n  function includeFiltered(stream, state) {\n    if (stream.match(/^include:([a-zA-Z0-9\\-]+)/, false) && stream.match('include')) {\n      state.isIncludeFiltered = true;\n      return KEYWORD;\n    }\n  }\n\n  function includeFilteredContinued(stream, state) {\n    if (state.isIncludeFiltered) {\n      var tok = filter(stream, state);\n      state.isIncludeFiltered = false;\n      state.restOfLine = 'string';\n      return tok;\n    }\n  }\n\n  function mixin(stream, state) {\n    if (stream.match(/^mixin\\b/)) {\n      state.javaScriptLine = true;\n      return KEYWORD;\n    }\n  }\n\n  function call(stream, state) {\n    if (stream.match(/^\\+([-\\w]+)/)) {\n      if (!stream.match(/^\\( *[-\\w]+ *=/, false)) {\n        state.javaScriptArguments = true;\n        state.javaScriptArgumentsDepth = 0;\n      }\n      return 'variable';\n    }\n    if (stream.match(/^\\+#{/, false)) {\n      stream.next();\n      state.mixinCallAfter = true;\n      return interpolation(stream, state);\n    }\n  }\n  function callArguments(stream, state) {\n    if (state.mixinCallAfter) {\n      state.mixinCallAfter = false;\n      if (!stream.match(/^\\( *[-\\w]+ *=/, false)) {\n        state.javaScriptArguments = true;\n        state.javaScriptArgumentsDepth = 0;\n      }\n      return true;\n    }\n  }\n\n  function conditional(stream, state) {\n    if (stream.match(/^(if|unless|else if|else)\\b/)) {\n      state.javaScriptLine = true;\n      return KEYWORD;\n    }\n  }\n\n  function each(stream, state) {\n    if (stream.match(/^(- *)?(each|for)\\b/)) {\n      state.isEach = true;\n      return KEYWORD;\n    }\n  }\n  function eachContinued(stream, state) {\n    if (state.isEach) {\n      if (stream.match(/^ in\\b/)) {\n        state.javaScriptLine = true;\n        state.isEach = false;\n        return KEYWORD;\n      } else if (stream.sol() || stream.eol()) {\n        state.isEach = false;\n      } else if (stream.next()) {\n        while (!stream.match(/^ in\\b/, false) && stream.next());\n        return 'variable';\n      }\n    }\n  }\n\n  function whileStatement(stream, state) {\n    if (stream.match(/^while\\b/)) {\n      state.javaScriptLine = true;\n      return KEYWORD;\n    }\n  }\n\n  function tag(stream, state) {\n    var captures;\n    if (captures = stream.match(/^(\\w(?:[-:\\w]*\\w)?)\\/?/)) {\n      state.lastTag = captures[1].toLowerCase();\n      if (state.lastTag === 'script') {\n        state.scriptType = 'application/javascript';\n      }\n      return 'tag';\n    }\n  }\n\n  function filter(stream, state) {\n    if (stream.match(/^:([\\w\\-]+)/)) {\n      var innerMode;\n      if (config && config.innerModes) {\n        innerMode = config.innerModes(stream.current().substring(1));\n      }\n      if (!innerMode) {\n        innerMode = stream.current().substring(1);\n      }\n      if (typeof innerMode === 'string') {\n        innerMode = CodeMirror.getMode(config, innerMode);\n      }\n      setInnerMode(stream, state, innerMode);\n      return 'atom';\n    }\n  }\n\n  function code(stream, state) {\n    if (stream.match(/^(!?=|-)/)) {\n      state.javaScriptLine = true;\n      return 'punctuation';\n    }\n  }\n\n  function id(stream) {\n    if (stream.match(/^#([\\w-]+)/)) {\n      return ID;\n    }\n  }\n\n  function className(stream) {\n    if (stream.match(/^\\.([\\w-]+)/)) {\n      return CLASS;\n    }\n  }\n\n  function attrs(stream, state) {\n    if (stream.peek() == '(') {\n      stream.next();\n      state.isAttrs = true;\n      state.attrsNest = [];\n      state.inAttributeName = true;\n      state.attrValue = '';\n      state.attributeIsType = false;\n      return 'punctuation';\n    }\n  }\n\n  function attrsContinued(stream, state) {\n    if (state.isAttrs) {\n      if (ATTRS_NEST[stream.peek()]) {\n        state.attrsNest.push(ATTRS_NEST[stream.peek()]);\n      }\n      if (state.attrsNest[state.attrsNest.length - 1] === stream.peek()) {\n        state.attrsNest.pop();\n      } else  if (stream.eat(')')) {\n        state.isAttrs = false;\n        return 'punctuation';\n      }\n      if (state.inAttributeName && stream.match(/^[^=,\\)!]+/)) {\n        if (stream.peek() === '=' || stream.peek() === '!') {\n          state.inAttributeName = false;\n          state.jsState = CodeMirror.startState(jsMode);\n          if (state.lastTag === 'script' && stream.current().trim().toLowerCase() === 'type') {\n            state.attributeIsType = true;\n          } else {\n            state.attributeIsType = false;\n          }\n        }\n        return 'attribute';\n      }\n\n      var tok = jsMode.token(stream, state.jsState);\n      if (state.attributeIsType && tok === 'string') {\n        state.scriptType = stream.current().toString();\n      }\n      if (state.attrsNest.length === 0 && (tok === 'string' || tok === 'variable' || tok === 'keyword')) {\n        try {\n          Function('', 'var x ' + state.attrValue.replace(/,\\s*$/, '').replace(/^!/, ''));\n          state.inAttributeName = true;\n          state.attrValue = '';\n          stream.backUp(stream.current().length);\n          return attrsContinued(stream, state);\n        } catch (ex) {\n          //not the end of an attribute\n        }\n      }\n      state.attrValue += stream.current();\n      return tok || true;\n    }\n  }\n\n  function attributesBlock(stream, state) {\n    if (stream.match(/^&attributes\\b/)) {\n      state.javaScriptArguments = true;\n      state.javaScriptArgumentsDepth = 0;\n      return 'keyword';\n    }\n  }\n\n  function indent(stream) {\n    if (stream.sol() && stream.eatSpace()) {\n      return 'indent';\n    }\n  }\n\n  function comment(stream, state) {\n    if (stream.match(/^ *\\/\\/(-)?([^\\n]*)/)) {\n      state.indentOf = stream.indentation();\n      state.indentToken = 'comment';\n      return 'comment';\n    }\n  }\n\n  function colon(stream) {\n    if (stream.match(/^: */)) {\n      return 'colon';\n    }\n  }\n\n  function text(stream, state) {\n    if (stream.match(/^(?:\\| ?| )([^\\n]+)/)) {\n      return 'string';\n    }\n    if (stream.match(/^(<[^\\n]*)/, false)) {\n      // html string\n      setInnerMode(stream, state, 'htmlmixed');\n      state.innerModeForLine = true;\n      return innerMode(stream, state, true);\n    }\n  }\n\n  function dot(stream, state) {\n    if (stream.eat('.')) {\n      var innerMode = null;\n      if (state.lastTag === 'script' && state.scriptType.toLowerCase().indexOf('javascript') != -1) {\n        innerMode = state.scriptType.toLowerCase().replace(/\"|'/g, '');\n      } else if (state.lastTag === 'style') {\n        innerMode = 'css';\n      }\n      setInnerMode(stream, state, innerMode);\n      return 'dot';\n    }\n  }\n\n  function fail(stream) {\n    stream.next();\n    return null;\n  }\n\n\n  function setInnerMode(stream, state, mode) {\n    mode = CodeMirror.mimeModes[mode] || mode;\n    mode = config.innerModes ? config.innerModes(mode) || mode : mode;\n    mode = CodeMirror.mimeModes[mode] || mode;\n    mode = CodeMirror.getMode(config, mode);\n    state.indentOf = stream.indentation();\n\n    if (mode && mode.name !== 'null') {\n      state.innerMode = mode;\n    } else {\n      state.indentToken = 'string';\n    }\n  }\n  function innerMode(stream, state, force) {\n    if (stream.indentation() > state.indentOf || (state.innerModeForLine && !stream.sol()) || force) {\n      if (state.innerMode) {\n        if (!state.innerState) {\n          state.innerState = state.innerMode.startState ? CodeMirror.startState(state.innerMode, stream.indentation()) : {};\n        }\n        return stream.hideFirstChars(state.indentOf + 2, function () {\n          return state.innerMode.token(stream, state.innerState) || true;\n        });\n      } else {\n        stream.skipToEnd();\n        return state.indentToken;\n      }\n    } else if (stream.sol()) {\n      state.indentOf = Infinity;\n      state.indentToken = null;\n      state.innerMode = null;\n      state.innerState = null;\n    }\n  }\n  function restOfLine(stream, state) {\n    if (stream.sol()) {\n      // if restOfLine was set at end of line, ignore it\n      state.restOfLine = '';\n    }\n    if (state.restOfLine) {\n      stream.skipToEnd();\n      var tok = state.restOfLine;\n      state.restOfLine = '';\n      return tok;\n    }\n  }\n\n\n  function startState() {\n    return new State();\n  }\n  function copyState(state) {\n    return state.copy();\n  }\n  /**\n   * Get the next token in the stream\n   *\n   * @param {Stream} stream\n   * @param {State} state\n   */\n  function nextToken(stream, state) {\n    var tok = innerMode(stream, state)\n      || restOfLine(stream, state)\n      || interpolationContinued(stream, state)\n      || includeFilteredContinued(stream, state)\n      || eachContinued(stream, state)\n      || attrsContinued(stream, state)\n      || javaScript(stream, state)\n      || javaScriptArguments(stream, state)\n      || callArguments(stream, state)\n\n      || yieldStatement(stream, state)\n      || doctype(stream, state)\n      || interpolation(stream, state)\n      || caseStatement(stream, state)\n      || when(stream, state)\n      || defaultStatement(stream, state)\n      || extendsStatement(stream, state)\n      || append(stream, state)\n      || prepend(stream, state)\n      || block(stream, state)\n      || include(stream, state)\n      || includeFiltered(stream, state)\n      || mixin(stream, state)\n      || call(stream, state)\n      || conditional(stream, state)\n      || each(stream, state)\n      || whileStatement(stream, state)\n      || tag(stream, state)\n      || filter(stream, state)\n      || code(stream, state)\n      || id(stream, state)\n      || className(stream, state)\n      || attrs(stream, state)\n      || attributesBlock(stream, state)\n      || indent(stream, state)\n      || text(stream, state)\n      || comment(stream, state)\n      || colon(stream, state)\n      || dot(stream, state)\n      || fail(stream, state);\n\n    return tok === true ? null : tok;\n  }\n  return {\n    startState: startState,\n    copyState: copyState,\n    token: nextToken\n  };\n}, 'javascript', 'css', 'htmlmixed');\n\nCodeMirror.defineMIME('text/x-pug', 'pug');\nCodeMirror.defineMIME('text/x-jade', 'pug');\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/puppet/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Puppet mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"puppet.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      .cm-s-default span.cm-arrow { color: red; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Puppet</a>\n  </ul>\n</div>\n\n<article>\n<h2>Puppet mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n# == Class: automysqlbackup\n#\n# Puppet module to install AutoMySQLBackup for periodic MySQL backups.\n#\n# class { 'automysqlbackup':\n#   backup_dir => '/mnt/backups',\n# }\n#\n\nclass automysqlbackup (\n  $bin_dir = $automysqlbackup::params::bin_dir,\n  $etc_dir = $automysqlbackup::params::etc_dir,\n  $backup_dir = $automysqlbackup::params::backup_dir,\n  $install_multicore = undef,\n  $config = {},\n  $config_defaults = {},\n) inherits automysqlbackup::params {\n\n# Ensure valid paths are assigned\n  validate_absolute_path($bin_dir)\n  validate_absolute_path($etc_dir)\n  validate_absolute_path($backup_dir)\n\n# Create a subdirectory in /etc for config files\n  file { $etc_dir:\n    ensure => directory,\n    owner => 'root',\n    group => 'root',\n    mode => '0750',\n  }\n\n# Create an example backup file, useful for reference\n  file { \"${etc_dir}/automysqlbackup.conf.example\":\n    ensure => file,\n    owner => 'root',\n    group => 'root',\n    mode => '0660',\n    source => 'puppet:///modules/automysqlbackup/automysqlbackup.conf',\n  }\n\n# Add files from the developer\n  file { \"${etc_dir}/AMB_README\":\n    ensure => file,\n    source => 'puppet:///modules/automysqlbackup/AMB_README',\n  }\n  file { \"${etc_dir}/AMB_LICENSE\":\n    ensure => file,\n    source => 'puppet:///modules/automysqlbackup/AMB_LICENSE',\n  }\n\n# Install the actual binary file\n  file { \"${bin_dir}/automysqlbackup\":\n    ensure => file,\n    owner => 'root',\n    group => 'root',\n    mode => '0755',\n    source => 'puppet:///modules/automysqlbackup/automysqlbackup',\n  }\n\n# Create the base backup directory\n  file { $backup_dir:\n    ensure => directory,\n    owner => 'root',\n    group => 'root',\n    mode => '0755',\n  }\n\n# If you'd like to keep your config in hiera and pass it to this class\n  if !empty($config) {\n    create_resources('automysqlbackup::backup', $config, $config_defaults)\n  }\n\n# If using RedHat family, must have the RPMforge repo's enabled\n  if $install_multicore {\n    package { ['pigz', 'pbzip2']: ensure => installed }\n  }\n\n}\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"text/x-puppet\",\n        matchBrackets: true,\n        indentUnit: 4\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-puppet</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/puppet/puppet.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"puppet\", function () {\n  // Stores the words from the define method\n  var words = {};\n  // Taken, mostly, from the Puppet official variable standards regex\n  var variable_regex = /({)?([a-z][a-z0-9_]*)?((::[a-z][a-z0-9_]*)*::)?[a-zA-Z0-9_]+(})?/;\n\n  // Takes a string of words separated by spaces and adds them as\n  // keys with the value of the first argument 'style'\n  function define(style, string) {\n    var split = string.split(' ');\n    for (var i = 0; i < split.length; i++) {\n      words[split[i]] = style;\n    }\n  }\n\n  // Takes commonly known puppet types/words and classifies them to a style\n  define('keyword', 'class define site node include import inherits');\n  define('keyword', 'case if else in and elsif default or');\n  define('atom', 'false true running present absent file directory undef');\n  define('builtin', 'action augeas burst chain computer cron destination dport exec ' +\n    'file filebucket group host icmp iniface interface jump k5login limit log_level ' +\n    'log_prefix macauthorization mailalias maillist mcx mount nagios_command ' +\n    'nagios_contact nagios_contactgroup nagios_host nagios_hostdependency ' +\n    'nagios_hostescalation nagios_hostextinfo nagios_hostgroup nagios_service ' +\n    'nagios_servicedependency nagios_serviceescalation nagios_serviceextinfo ' +\n    'nagios_servicegroup nagios_timeperiod name notify outiface package proto reject ' +\n    'resources router schedule scheduled_task selboolean selmodule service source ' +\n    'sport ssh_authorized_key sshkey stage state table tidy todest toports tosource ' +\n    'user vlan yumrepo zfs zone zpool');\n\n  // After finding a start of a string ('|\") this function attempts to find the end;\n  // If a variable is encountered along the way, we display it differently when it\n  // is encapsulated in a double-quoted string.\n  function tokenString(stream, state) {\n    var current, prev, found_var = false;\n    while (!stream.eol() && (current = stream.next()) != state.pending) {\n      if (current === '$' && prev != '\\\\' && state.pending == '\"') {\n        found_var = true;\n        break;\n      }\n      prev = current;\n    }\n    if (found_var) {\n      stream.backUp(1);\n    }\n    if (current == state.pending) {\n      state.continueString = false;\n    } else {\n      state.continueString = true;\n    }\n    return \"string\";\n  }\n\n  // Main function\n  function tokenize(stream, state) {\n    // Matches one whole word\n    var word = stream.match(/[\\w]+/, false);\n    // Matches attributes (i.e. ensure => present ; 'ensure' would be matched)\n    var attribute = stream.match(/(\\s+)?\\w+\\s+=>.*/, false);\n    // Matches non-builtin resource declarations\n    // (i.e. \"apache::vhost {\" or \"mycustomclasss {\" would be matched)\n    var resource = stream.match(/(\\s+)?[\\w:_]+(\\s+)?{/, false);\n    // Matches virtual and exported resources (i.e. @@user { ; and the like)\n    var special_resource = stream.match(/(\\s+)?[@]{1,2}[\\w:_]+(\\s+)?{/, false);\n\n    // Finally advance the stream\n    var ch = stream.next();\n\n    // Have we found a variable?\n    if (ch === '$') {\n      if (stream.match(variable_regex)) {\n        // If so, and its in a string, assign it a different color\n        return state.continueString ? 'variable-2' : 'variable';\n      }\n      // Otherwise return an invalid variable\n      return \"error\";\n    }\n    // Should we still be looking for the end of a string?\n    if (state.continueString) {\n      // If so, go through the loop again\n      stream.backUp(1);\n      return tokenString(stream, state);\n    }\n    // Are we in a definition (class, node, define)?\n    if (state.inDefinition) {\n      // If so, return def (i.e. for 'class myclass {' ; 'myclass' would be matched)\n      if (stream.match(/(\\s+)?[\\w:_]+(\\s+)?/)) {\n        return 'def';\n      }\n      // Match the rest it the next time around\n      stream.match(/\\s+{/);\n      state.inDefinition = false;\n    }\n    // Are we in an 'include' statement?\n    if (state.inInclude) {\n      // Match and return the included class\n      stream.match(/(\\s+)?\\S+(\\s+)?/);\n      state.inInclude = false;\n      return 'def';\n    }\n    // Do we just have a function on our hands?\n    // In 'ensure_resource(\"myclass\")', 'ensure_resource' is matched\n    if (stream.match(/(\\s+)?\\w+\\(/)) {\n      stream.backUp(1);\n      return 'def';\n    }\n    // Have we matched the prior attribute regex?\n    if (attribute) {\n      stream.match(/(\\s+)?\\w+/);\n      return 'tag';\n    }\n    // Do we have Puppet specific words?\n    if (word && words.hasOwnProperty(word)) {\n      // Negates the initial next()\n      stream.backUp(1);\n      // rs move the stream\n      stream.match(/[\\w]+/);\n      // We want to process these words differently\n      // do to the importance they have in Puppet\n      if (stream.match(/\\s+\\S+\\s+{/, false)) {\n        state.inDefinition = true;\n      }\n      if (word == 'include') {\n        state.inInclude = true;\n      }\n      // Returns their value as state in the prior define methods\n      return words[word];\n    }\n    // Is there a match on a reference?\n    if (/(^|\\s+)[A-Z][\\w:_]+/.test(word)) {\n      // Negate the next()\n      stream.backUp(1);\n      // Match the full reference\n      stream.match(/(^|\\s+)[A-Z][\\w:_]+/);\n      return 'def';\n    }\n    // Have we matched the prior resource regex?\n    if (resource) {\n      stream.match(/(\\s+)?[\\w:_]+/);\n      return 'def';\n    }\n    // Have we matched the prior special_resource regex?\n    if (special_resource) {\n      stream.match(/(\\s+)?[@]{1,2}/);\n      return 'special';\n    }\n    // Match all the comments. All of them.\n    if (ch == \"#\") {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n    // Have we found a string?\n    if (ch == \"'\" || ch == '\"') {\n      // Store the type (single or double)\n      state.pending = ch;\n      // Perform the looping function to find the end\n      return tokenString(stream, state);\n    }\n    // Match all the brackets\n    if (ch == '{' || ch == '}') {\n      return 'bracket';\n    }\n    // Match characters that we are going to assume\n    // are trying to be regex\n    if (ch == '/') {\n      stream.match(/.*?\\//);\n      return 'variable-3';\n    }\n    // Match all the numbers\n    if (ch.match(/[0-9]/)) {\n      stream.eatWhile(/[0-9]+/);\n      return 'number';\n    }\n    // Match the '=' and '=>' operators\n    if (ch == '=') {\n      if (stream.peek() == '>') {\n          stream.next();\n      }\n      return \"operator\";\n    }\n    // Keep advancing through all the rest\n    stream.eatWhile(/[\\w-]/);\n    // Return a blank line for everything else\n    return null;\n  }\n  // Start it all\n  return {\n    startState: function () {\n      var state = {};\n      state.inDefinition = false;\n      state.inInclude = false;\n      state.continueString = false;\n      state.pending = false;\n      return state;\n    },\n    token: function (stream, state) {\n      // Strip the spaces, but regex will account for them eitherway\n      if (stream.eatSpace()) return null;\n      // Go through the main process\n      return tokenize(stream, state);\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-puppet\", \"puppet\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/python/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Python mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"python.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Python</a>\n  </ul>\n</div>\n\n<article>\n<h2>Python mode</h2>\n\n    <div><textarea id=\"code\" name=\"code\">\n# Literals\n1234\n0.0e101\n.123\n0b01010011100\n0o01234567\n0x0987654321abcdef\n7\n2147483647\n3L\n79228162514264337593543950336L\n0x100000000L\n79228162514264337593543950336\n0xdeadbeef\n3.14j\n10.j\n10j\n.001j\n1e100j\n3.14e-10j\n\n\n# String Literals\n'For\\''\n\"God\\\"\"\n\"\"\"so loved\nthe world\"\"\"\n'''that he gave\nhis only begotten\\' '''\n'that whosoever believeth \\\nin him'\n''\n\n# Identifiers\n__a__\na.b\na.b.c\n\n#Unicode identifiers on Python3\n# a = x\\ddot\na⃗ = ẍ\n# a = v\\dot\na⃗ = v̇\n\n#F\\vec = m \\cdot a\\vec\nF⃗ = m•a⃗ \n\n# Operators\n+ - * / % & | ^ ~ < >\n== != <= >= <> << >> // **\nand or not in is\n\n#infix matrix multiplication operator (PEP 465)\nA @ B\n\n# Delimiters\n() [] {} , : ` = ; @ .  # Note that @ and . require the proper context on Python 2.\n+= -= *= /= %= &= |= ^=\n//= >>= <<= **=\n\n# Keywords\nas assert break class continue def del elif else except\nfinally for from global if import lambda pass raise\nreturn try while with yield\n\n# Python 2 Keywords (otherwise Identifiers)\nexec print\n\n# Python 3 Keywords (otherwise Identifiers)\nnonlocal\n\n# Types\nbool classmethod complex dict enumerate float frozenset int list object\nproperty reversed set slice staticmethod str super tuple type\n\n# Python 2 Types (otherwise Identifiers)\nbasestring buffer file long unicode xrange\n\n# Python 3 Types (otherwise Identifiers)\nbytearray bytes filter map memoryview open range zip\n\n# Some Example code\nimport os\nfrom package import ParentClass\n\n@nonsenseDecorator\ndef doesNothing():\n    pass\n\nclass ExampleClass(ParentClass):\n    @staticmethod\n    def example(inputStr):\n        a = list(inputStr)\n        a.reverse()\n        return ''.join(a)\n\n    def __init__(self, mixin = 'Hello'):\n        self.mixin = mixin\n\n# Python 3.6 f-strings (https://www.python.org/dev/peps/pep-0498/)\nf'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.'\nf'He said his name is {name!r}.'\nf\"\"\"He said his name is {name!r}.\"\"\"\nf'{\"quoted string\"}'\nf'{{ {4*10} }}'\nf'This is an error }'\nf'This is ok }}'\nfr'x={4*10}\\n'\n</textarea></div>\n\n\n<h2>Cython mode</h2>\n\n<div><textarea id=\"code-cython\" name=\"code-cython\">\n\nimport numpy as np\ncimport cython\nfrom libc.math cimport sqrt\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\ndef pairwise_cython(double[:, ::1] X):\n    cdef int M = X.shape[0]\n    cdef int N = X.shape[1]\n    cdef double tmp, d\n    cdef double[:, ::1] D = np.empty((M, M), dtype=np.float64)\n    for i in range(M):\n        for j in range(M):\n            d = 0.0\n            for k in range(N):\n                tmp = X[i, k] - X[j, k]\n                d += tmp * tmp\n            D[i, j] = sqrt(d)\n    return np.asarray(D)\n\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"python\",\n               version: 3,\n               singleLineStringErrors: false},\n        lineNumbers: true,\n        indentUnit: 4,\n        matchBrackets: true\n    });\n\n    CodeMirror.fromTextArea(document.getElementById(\"code-cython\"), {\n        mode: {name: \"text/x-cython\",\n               version: 2,\n               singleLineStringErrors: false},\n        lineNumbers: true,\n        indentUnit: 4,\n        matchBrackets: true\n      });\n    </script>\n    <h2>Configuration Options for Python mode:</h2>\n    <ul>\n      <li>version - 2/3 - The version of Python to recognize.  Default is 3.</li>\n      <li>singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.</li>\n      <li>hangingIndent - int - If you want to write long arguments to a function starting on a new line, how much that line should be indented. Defaults to one normal indentation unit.</li>\n    </ul>\n    <h2>Advanced Configuration Options:</h2>\n    <p>Usefull for superset of python syntax like Enthought enaml, IPython magics and  questionmark help</p>\n    <ul>\n      <li>singleOperators - RegEx - Regular Expression for single operator matching,  default : <pre>^[\\\\+\\\\-\\\\*/%&amp;|\\\\^~&lt;&gt;!]</pre> including <pre>@</pre> on Python 3</li>\n      <li>singleDelimiters - RegEx - Regular Expression for single delimiter matching, default :  <pre>^[\\\\(\\\\)\\\\[\\\\]\\\\{\\\\}@,:`=;\\\\.]</pre></li>\n      <li>doubleOperators - RegEx - Regular Expression for double operators matching, default : <pre>^((==)|(!=)|(&lt;=)|(&gt;=)|(&lt;&gt;)|(&lt;&lt;)|(&gt;&gt;)|(//)|(\\\\*\\\\*))</pre></li>\n      <li>doubleDelimiters - RegEx - Regular Expression for double delimiters matching, default : <pre>^((\\\\+=)|(\\\\-=)|(\\\\*=)|(%=)|(/=)|(&amp;=)|(\\\\|=)|(\\\\^=))</pre></li>\n      <li>tripleDelimiters - RegEx - Regular Expression for triple delimiters matching, default : <pre>^((//=)|(&gt;&gt;=)|(&lt;&lt;=)|(\\\\*\\\\*=))</pre></li>\n      <li>identifiers - RegEx - Regular Expression for identifier, default : <pre>^[_A-Za-z][_A-Za-z0-9]*</pre> on Python 2 and <pre>^[_A-Za-z\\u00A1-\\uFFFF][_A-Za-z0-9\\u00A1-\\uFFFF]*</pre> on Python 3.</li>\n      <li>extra_keywords - list of string - List of extra words ton consider as keywords</li>\n      <li>extra_builtins - list of string - List of extra words ton consider as builtins</li>\n    </ul>\n\n\n    <p><strong>MIME types defined:</strong> <code>text/x-python</code> and <code>text/x-cython</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/python/python.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function wordRegexp(words) {\n    return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n  }\n\n  var wordOperators = wordRegexp([\"and\", \"or\", \"not\", \"is\"]);\n  var commonKeywords = [\"as\", \"assert\", \"break\", \"class\", \"continue\",\n                        \"def\", \"del\", \"elif\", \"else\", \"except\", \"finally\",\n                        \"for\", \"from\", \"global\", \"if\", \"import\",\n                        \"lambda\", \"pass\", \"raise\", \"return\",\n                        \"try\", \"while\", \"with\", \"yield\", \"in\"];\n  var commonBuiltins = [\"abs\", \"all\", \"any\", \"bin\", \"bool\", \"bytearray\", \"callable\", \"chr\",\n                        \"classmethod\", \"compile\", \"complex\", \"delattr\", \"dict\", \"dir\", \"divmod\",\n                        \"enumerate\", \"eval\", \"filter\", \"float\", \"format\", \"frozenset\",\n                        \"getattr\", \"globals\", \"hasattr\", \"hash\", \"help\", \"hex\", \"id\",\n                        \"input\", \"int\", \"isinstance\", \"issubclass\", \"iter\", \"len\",\n                        \"list\", \"locals\", \"map\", \"max\", \"memoryview\", \"min\", \"next\",\n                        \"object\", \"oct\", \"open\", \"ord\", \"pow\", \"property\", \"range\",\n                        \"repr\", \"reversed\", \"round\", \"set\", \"setattr\", \"slice\",\n                        \"sorted\", \"staticmethod\", \"str\", \"sum\", \"super\", \"tuple\",\n                        \"type\", \"vars\", \"zip\", \"__import__\", \"NotImplemented\",\n                        \"Ellipsis\", \"__debug__\"];\n  CodeMirror.registerHelper(\"hintWords\", \"python\", commonKeywords.concat(commonBuiltins));\n\n  function top(state) {\n    return state.scopes[state.scopes.length - 1];\n  }\n\n  CodeMirror.defineMode(\"python\", function(conf, parserConf) {\n    var ERRORCLASS = \"error\";\n\n    var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\\(\\)\\[\\]\\{\\}@,:`=;\\.\\\\]/;\n    //               (Backwards-compatiblity with old, cumbersome config system)\n    var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,\n                     parserConf.operators || /^([-+*/%\\/&|^]=?|[<>=]+|\\/\\/=?|\\*\\*=?|!=|[~!@])/]\n    for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)\n\n    var hangingIndent = parserConf.hangingIndent || conf.indentUnit;\n\n    var myKeywords = commonKeywords, myBuiltins = commonBuiltins;\n    if (parserConf.extra_keywords != undefined)\n      myKeywords = myKeywords.concat(parserConf.extra_keywords);\n\n    if (parserConf.extra_builtins != undefined)\n      myBuiltins = myBuiltins.concat(parserConf.extra_builtins);\n\n    var py3 = !(parserConf.version && Number(parserConf.version) < 3)\n    if (py3) {\n      // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator\n      var identifiers = parserConf.identifiers|| /^[_A-Za-z\\u00A1-\\uFFFF][_A-Za-z0-9\\u00A1-\\uFFFF]*/;\n      myKeywords = myKeywords.concat([\"nonlocal\", \"False\", \"True\", \"None\", \"async\", \"await\"]);\n      myBuiltins = myBuiltins.concat([\"ascii\", \"bytes\", \"exec\", \"print\"]);\n      var stringPrefixes = new RegExp(\"^(([rbuf]|(br)|(fr))?('{3}|\\\"{3}|['\\\"]))\", \"i\");\n    } else {\n      var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;\n      myKeywords = myKeywords.concat([\"exec\", \"print\"]);\n      myBuiltins = myBuiltins.concat([\"apply\", \"basestring\", \"buffer\", \"cmp\", \"coerce\", \"execfile\",\n                                      \"file\", \"intern\", \"long\", \"raw_input\", \"reduce\", \"reload\",\n                                      \"unichr\", \"unicode\", \"xrange\", \"False\", \"True\", \"None\"]);\n      var stringPrefixes = new RegExp(\"^(([rubf]|(ur)|(br))?('{3}|\\\"{3}|['\\\"]))\", \"i\");\n    }\n    var keywords = wordRegexp(myKeywords);\n    var builtins = wordRegexp(myBuiltins);\n\n    // tokenizers\n    function tokenBase(stream, state) {\n      var sol = stream.sol() && state.lastToken != \"\\\\\"\n      if (sol) state.indent = stream.indentation()\n      // Handle scope changes\n      if (sol && top(state).type == \"py\") {\n        var scopeOffset = top(state).offset;\n        if (stream.eatSpace()) {\n          var lineOffset = stream.indentation();\n          if (lineOffset > scopeOffset)\n            pushPyScope(state);\n          else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != \"#\")\n            state.errorToken = true;\n          return null;\n        } else {\n          var style = tokenBaseInner(stream, state);\n          if (scopeOffset > 0 && dedent(stream, state))\n            style += \" \" + ERRORCLASS;\n          return style;\n        }\n      }\n      return tokenBaseInner(stream, state);\n    }\n\n    function tokenBaseInner(stream, state) {\n      if (stream.eatSpace()) return null;\n\n      // Handle Comments\n      if (stream.match(/^#.*/)) return \"comment\";\n\n      // Handle Number Literals\n      if (stream.match(/^[0-9\\.]/, false)) {\n        var floatLiteral = false;\n        // Floats\n        if (stream.match(/^[\\d_]*\\.\\d+(e[\\+\\-]?\\d+)?/i)) { floatLiteral = true; }\n        if (stream.match(/^[\\d_]+\\.\\d*/)) { floatLiteral = true; }\n        if (stream.match(/^\\.\\d+/)) { floatLiteral = true; }\n        if (floatLiteral) {\n          // Float literals may be \"imaginary\"\n          stream.eat(/J/i);\n          return \"number\";\n        }\n        // Integers\n        var intLiteral = false;\n        // Hex\n        if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;\n        // Binary\n        if (stream.match(/^0b[01_]+/i)) intLiteral = true;\n        // Octal\n        if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;\n        // Decimal\n        if (stream.match(/^[1-9][\\d_]*(e[\\+\\-]?[\\d_]+)?/)) {\n          // Decimal literals may be \"imaginary\"\n          stream.eat(/J/i);\n          // TODO - Can you have imaginary longs?\n          intLiteral = true;\n        }\n        // Zero by itself with no other piece of number.\n        if (stream.match(/^0(?![\\dx])/i)) intLiteral = true;\n        if (intLiteral) {\n          // Integer literals may be \"long\"\n          stream.eat(/L/i);\n          return \"number\";\n        }\n      }\n\n      // Handle Strings\n      if (stream.match(stringPrefixes)) {\n        var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;\n        if (!isFmtString) {\n          state.tokenize = tokenStringFactory(stream.current(), state.tokenize);\n          return state.tokenize(stream, state);\n        } else {\n          state.tokenize = formatStringFactory(stream.current(), state.tokenize);\n          return state.tokenize(stream, state);\n        }\n      }\n\n      for (var i = 0; i < operators.length; i++)\n        if (stream.match(operators[i])) return \"operator\"\n\n      if (stream.match(delimiters)) return \"punctuation\";\n\n      if (state.lastToken == \".\" && stream.match(identifiers))\n        return \"property\";\n\n      if (stream.match(keywords) || stream.match(wordOperators))\n        return \"keyword\";\n\n      if (stream.match(builtins))\n        return \"builtin\";\n\n      if (stream.match(/^(self|cls)\\b/))\n        return \"variable-2\";\n\n      if (stream.match(identifiers)) {\n        if (state.lastToken == \"def\" || state.lastToken == \"class\")\n          return \"def\";\n        return \"variable\";\n      }\n\n      // Handle non-detected items\n      stream.next();\n      return ERRORCLASS;\n    }\n\n    function formatStringFactory(delimiter, tokenOuter) {\n      while (\"rubf\".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)\n        delimiter = delimiter.substr(1);\n\n      var singleline = delimiter.length == 1;\n      var OUTCLASS = \"string\";\n\n      function tokenNestedExpr(depth) {\n        return function(stream, state) {\n          var inner = tokenBaseInner(stream, state)\n          if (inner == \"punctuation\") {\n            if (stream.current() == \"{\") {\n              state.tokenize = tokenNestedExpr(depth + 1)\n            } else if (stream.current() == \"}\") {\n              if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1)\n              else state.tokenize = tokenString\n            }\n          }\n          return inner\n        }\n      }\n\n      function tokenString(stream, state) {\n        while (!stream.eol()) {\n          stream.eatWhile(/[^'\"\\{\\}\\\\]/);\n          if (stream.eat(\"\\\\\")) {\n            stream.next();\n            if (singleline && stream.eol())\n              return OUTCLASS;\n          } else if (stream.match(delimiter)) {\n            state.tokenize = tokenOuter;\n            return OUTCLASS;\n          } else if (stream.match('{{')) {\n            // ignore {{ in f-str\n            return OUTCLASS;\n          } else if (stream.match('{', false)) {\n            // switch to nested mode\n            state.tokenize = tokenNestedExpr(0)\n            if (stream.current()) return OUTCLASS;\n            else return state.tokenize(stream, state)\n          } else if (stream.match('}}')) {\n            return OUTCLASS;\n          } else if (stream.match('}')) {\n            // single } in f-string is an error\n            return ERRORCLASS;\n          } else {\n            stream.eat(/['\"]/);\n          }\n        }\n        if (singleline) {\n          if (parserConf.singleLineStringErrors)\n            return ERRORCLASS;\n          else\n            state.tokenize = tokenOuter;\n        }\n        return OUTCLASS;\n      }\n      tokenString.isString = true;\n      return tokenString;\n    }\n\n    function tokenStringFactory(delimiter, tokenOuter) {\n      while (\"rubf\".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)\n        delimiter = delimiter.substr(1);\n\n      var singleline = delimiter.length == 1;\n      var OUTCLASS = \"string\";\n\n      function tokenString(stream, state) {\n        while (!stream.eol()) {\n          stream.eatWhile(/[^'\"\\\\]/);\n          if (stream.eat(\"\\\\\")) {\n            stream.next();\n            if (singleline && stream.eol())\n              return OUTCLASS;\n          } else if (stream.match(delimiter)) {\n            state.tokenize = tokenOuter;\n            return OUTCLASS;\n          } else {\n            stream.eat(/['\"]/);\n          }\n        }\n        if (singleline) {\n          if (parserConf.singleLineStringErrors)\n            return ERRORCLASS;\n          else\n            state.tokenize = tokenOuter;\n        }\n        return OUTCLASS;\n      }\n      tokenString.isString = true;\n      return tokenString;\n    }\n\n    function pushPyScope(state) {\n      while (top(state).type != \"py\") state.scopes.pop()\n      state.scopes.push({offset: top(state).offset + conf.indentUnit,\n                         type: \"py\",\n                         align: null})\n    }\n\n    function pushBracketScope(stream, state, type) {\n      var align = stream.match(/^([\\s\\[\\{\\(]|#.*)*$/, false) ? null : stream.column() + 1\n      state.scopes.push({offset: state.indent + hangingIndent,\n                         type: type,\n                         align: align})\n    }\n\n    function dedent(stream, state) {\n      var indented = stream.indentation();\n      while (state.scopes.length > 1 && top(state).offset > indented) {\n        if (top(state).type != \"py\") return true;\n        state.scopes.pop();\n      }\n      return top(state).offset != indented;\n    }\n\n    function tokenLexer(stream, state) {\n      if (stream.sol()) state.beginningOfLine = true;\n\n      var style = state.tokenize(stream, state);\n      var current = stream.current();\n\n      // Handle decorators\n      if (state.beginningOfLine && current == \"@\")\n        return stream.match(identifiers, false) ? \"meta\" : py3 ? \"operator\" : ERRORCLASS;\n\n      if (/\\S/.test(current)) state.beginningOfLine = false;\n\n      if ((style == \"variable\" || style == \"builtin\")\n          && state.lastToken == \"meta\")\n        style = \"meta\";\n\n      // Handle scope changes.\n      if (current == \"pass\" || current == \"return\")\n        state.dedent += 1;\n\n      if (current == \"lambda\") state.lambda = true;\n      if (current == \":\" && !state.lambda && top(state).type == \"py\")\n        pushPyScope(state);\n\n      if (current.length == 1 && !/string|comment/.test(style)) {\n        var delimiter_index = \"[({\".indexOf(current);\n        if (delimiter_index != -1)\n          pushBracketScope(stream, state, \"])}\".slice(delimiter_index, delimiter_index+1));\n\n        delimiter_index = \"])}\".indexOf(current);\n        if (delimiter_index != -1) {\n          if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent\n          else return ERRORCLASS;\n        }\n      }\n      if (state.dedent > 0 && stream.eol() && top(state).type == \"py\") {\n        if (state.scopes.length > 1) state.scopes.pop();\n        state.dedent -= 1;\n      }\n\n      return style;\n    }\n\n    var external = {\n      startState: function(basecolumn) {\n        return {\n          tokenize: tokenBase,\n          scopes: [{offset: basecolumn || 0, type: \"py\", align: null}],\n          indent: basecolumn || 0,\n          lastToken: null,\n          lambda: false,\n          dedent: 0\n        };\n      },\n\n      token: function(stream, state) {\n        var addErr = state.errorToken;\n        if (addErr) state.errorToken = false;\n        var style = tokenLexer(stream, state);\n\n        if (style && style != \"comment\")\n          state.lastToken = (style == \"keyword\" || style == \"punctuation\") ? stream.current() : style;\n        if (style == \"punctuation\") style = null;\n\n        if (stream.eol() && state.lambda)\n          state.lambda = false;\n        return addErr ? style + \" \" + ERRORCLASS : style;\n      },\n\n      indent: function(state, textAfter) {\n        if (state.tokenize != tokenBase)\n          return state.tokenize.isString ? CodeMirror.Pass : 0;\n\n        var scope = top(state), closing = scope.type == textAfter.charAt(0)\n        if (scope.align != null)\n          return scope.align - (closing ? 1 : 0)\n        else\n          return scope.offset - (closing ? hangingIndent : 0)\n      },\n\n      electricInput: /^\\s*[\\}\\]\\)]$/,\n      closeBrackets: {triples: \"'\\\"\"},\n      lineComment: \"#\",\n      fold: \"indent\"\n    };\n    return external;\n  });\n\n  CodeMirror.defineMIME(\"text/x-python\", \"python\");\n\n  var words = function(str) { return str.split(\" \"); };\n\n  CodeMirror.defineMIME(\"text/x-cython\", {\n    name: \"python\",\n    extra_keywords: words(\"by cdef cimport cpdef ctypedef enum except \"+\n                          \"extern gil include nogil property public \"+\n                          \"readonly struct union DEF IF ELIF ELSE\")\n  });\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/python/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 4},\n              {name: \"python\",\n               version: 3,\n               singleLineStringErrors: false});\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  // Error, because \"foobarhello\" is neither a known type or property, but\n  // property was expected (after \"and\"), and it should be in parentheses.\n  MT(\"decoratorStartOfLine\",\n     \"[meta @dec]\",\n     \"[keyword def] [def function]():\",\n     \"    [keyword pass]\");\n\n  MT(\"decoratorIndented\",\n     \"[keyword class] [def Foo]:\",\n     \"    [meta @dec]\",\n     \"    [keyword def] [def function]():\",\n     \"        [keyword pass]\");\n\n  MT(\"matmulWithSpace:\", \"[variable a] [operator @] [variable b]\");\n  MT(\"matmulWithoutSpace:\", \"[variable a][operator @][variable b]\");\n  MT(\"matmulSpaceBefore:\", \"[variable a] [operator @][variable b]\");\n  var before_equal_sign = [\"+\", \"-\", \"*\", \"/\", \"=\", \"!\", \">\", \"<\"];\n  for (var i = 0; i < before_equal_sign.length; ++i) {\n    var c = before_equal_sign[i]\n    MT(\"before_equal_sign_\" + c, \"[variable a] [operator \" + c + \"=] [variable b]\");\n  }\n\n  MT(\"fValidStringPrefix\", \"[string f'this is a]{[variable formatted]}[string string']\");\n  MT(\"fValidExpressioninFString\", \"[string f'expression ]{[number 100][operator *][number 5]}[string string']\");\n  MT(\"fInvalidFString\", \"[error f'this is wrong}]\");\n  MT(\"fNestedFString\", \"[string f'expression ]{[number 100] [operator +] [string f'inner]{[number 5]}[string ']}[string string']\");\n  MT(\"uValidStringPrefix\", \"[string u'this is an unicode string']\");\n\n  MT(\"nestedString\", \"[string f']{[variable b][[ [string \\\"c\\\"] ]]}[string f'] [comment # oops]\")\n\n  MT(\"bracesInFString\", \"[string f']{[variable x] [operator +] {}}[string !']\")\n\n  MT(\"nestedFString\", \"[string f']{[variable b][[ [string f\\\"c\\\"] ]]}[string f'] [comment # oops]\")\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/q/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Q mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"q.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Q</a>\n  </ul>\n</div>\n\n<article>\n<h2>Q mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n/ utilities to quickly load a csv file - for more exhaustive analysis of the csv contents see csvguess.q\n/ 2009.09.20 - updated to match latest csvguess.q \n\n/ .csv.colhdrs[file] - return a list of colhdrs from file\n/ info:.csv.info[file] - return a table of information about the file\n/ columns are: \n/\tc - column name; ci - column index; t - load type; mw - max width; \n/\tdchar - distinct characters in values; rule - rule that caught the type\n/\tmaybe - needs checking, _could_ be say a date, but perhaps just a float?\n/ .csv.info0[file;onlycols] - like .csv.info except that it only analyses <onlycols>\n/ example:\n/\tinfo:.csv.info0[file;(.csv.colhdrs file)like\"*price\"]\n/\tinfo:.csv.infolike[file;\"*price\"]\n/\tshow delete from info where t=\" \"\n/ .csv.data[file;info] - use the info from .csv.info to read the data\n/ .csv.data10[file;info] - like .csv.data but only returns the first 10 rows\n/ bulkload[file;info] - bulk loads file into table DATA (which must be already defined :: DATA:() )\n/ .csv.read[file]/read10[file] - for when you don't care about checking/tweaking the <info> before reading \n\n\\d .csv\nDELIM:\",\"\nZAPHDRS:0b / lowercase and remove _ from colhdrs (junk characters are always removed)\nWIDTHHDR:25000 / number of characters read to get the header\nREADLINES:222 / number of lines read and used to guess the types\nSYMMAXWIDTH:11 / character columns narrower than this are stored as symbols\nSYMMAXGR:10 / max symbol granularity% before we give up and keep as a * string\nFORCECHARWIDTH:30 / every field (of any type) with values this wide or more is forced to character \"*\"\nDISCARDEMPTY:0b / completely ignore empty columns if true else set them to \"C\"\nCHUNKSIZE:50000000 / used in fs2 (modified .Q.fs)\n\nk)nameltrim:{$[~@x;.z.s'x;~(*x)in aA:.Q.a,.Q.A;(+/&\\~x in aA)_x;x]}\nk)fs2:{[f;s]((-7!s)>){[f;s;x]i:1+last@&0xa=r:1:(s;x;CHUNKSIZE);f@`\\:i#r;x+i}[f;s]/0j}\ncleanhdrs:{{$[ZAPHDRS;lower x except\"_\";x]}x where x in DELIM,.Q.an}\ncancast:{nw:x$\"\";if[not x in\"BXCS\";nw:(min 0#;max 0#;::)@\\:nw];$[not any nw in x$(11&count y)#y;$[11<count y;not any nw in x$y;1b];0b]}\n\nread:{[file]data[file;info[file]]}  \nread10:{[file]data10[file;info[file]]}  \n\ncolhdrs:{[file]\n\t`$nameltrim DELIM vs cleanhdrs first read0(file;0;1+first where 0xa=read1(file;0;WIDTHHDR))}\ndata:{[file;info]\n\t(exec c from info where not t=\" \")xcol(exec t from info;enlist DELIM)0:file}\ndata10:{[file;info]\n\tdata[;info](file;0;1+last 11#where 0xa=read1(file;0;15*WIDTHHDR))}\ninfo0:{[file;onlycols]\n\tcolhdrs:`$nameltrim DELIM vs cleanhdrs first head:read0(file;0;1+last where 0xa=read1(file;0;WIDTHHDR));\n\tloadfmts:(count colhdrs)#\"S\";if[count onlycols;loadfmts[where not colhdrs in onlycols]:\"C\"];\n\tbreaks:where 0xa=read1(file;0;floor(10+READLINES)*WIDTHHDR%count head);\n\tnas:count as:colhdrs xcol(loadfmts;enlist DELIM)0:(file;0;1+last((1+READLINES)&count breaks)#breaks);\n\tinfo:([]c:key flip as;v:value flip as);as:();\n\treserved:key`.q;reserved,:.Q.res;reserved,:`i;\n\tinfo:update res:c in reserved from info;\n\tinfo:update ci:i,t:\"?\",ipa:0b,mdot:0,mw:0,rule:0,gr:0,ndv:0,maybe:0b,empty:0b,j10:0b,j12:0b from info;\n\tinfo:update ci:`s#ci from info;\n\tif[count onlycols;info:update t:\" \",rule:10 from info where not c in onlycols];\n\tinfo:update sdv:{string(distinct x)except`}peach v from info; \n\tinfo:update ndv:count each sdv from info;\n\tinfo:update gr:floor 0.5+100*ndv%nas,mw:{max count each x}peach sdv from info where 0<ndv;\n\tinfo:update t:\"*\",rule:20 from info where mw>.csv.FORCECHARWIDTH; / long values\n\tinfo:update t:\"C \"[.csv.DISCARDEMPTY],rule:30,empty:1b from info where t=\"?\",mw=0; / empty columns\n\tinfo:update dchar:{asc distinct raze x}peach sdv from info where t=\"?\";\n\tinfo:update mdot:{max sum each\".\"=x}peach sdv from info where t=\"?\",{\".\"in x}each dchar;\n\tinfo:update t:\"n\",rule:40 from info where t=\"?\",{any x in\"0123456789\"}each dchar; / vaguely numeric..\n\tinfo:update t:\"I\",rule:50,ipa:1b from info where t=\"n\",mw within 7 15,mdot=3,{all x in\".0123456789\"}each dchar,.csv.cancast[\"I\"]peach sdv; / ip-address\n\tinfo:update t:\"J\",rule:60 from info where t=\"n\",mdot=0,{all x in\"+-0123456789\"}each dchar,.csv.cancast[\"J\"]peach sdv;\n\tinfo:update t:\"I\",rule:70 from info where t=\"J\",mw<12,.csv.cancast[\"I\"]peach sdv;\n\tinfo:update t:\"H\",rule:80 from info where t=\"I\",mw<7,.csv.cancast[\"H\"]peach sdv;\n\tinfo:update t:\"F\",rule:90 from info where t=\"n\",mdot<2,mw>1,.csv.cancast[\"F\"]peach sdv;\n\tinfo:update t:\"E\",rule:100,maybe:1b from info where t=\"F\",mw<9;\n\tinfo:update t:\"M\",rule:110,maybe:1b from info where t in\"nIHEF\",mdot<2,mw within 4 7,.csv.cancast[\"M\"]peach sdv; \n\tinfo:update t:\"D\",rule:120,maybe:1b from info where t in\"nI\",mdot in 0 2,mw within 6 11,.csv.cancast[\"D\"]peach sdv; \n\tinfo:update t:\"V\",rule:130,maybe:1b from info where t=\"I\",mw in 5 6,7<count each dchar,{all x like\"*[0-9][0-5][0-9][0-5][0-9]\"}peach sdv,.csv.cancast[\"V\"]peach sdv; / 235959 12345        \n\tinfo:update t:\"U\",rule:140,maybe:1b from info where t=\"H\",mw in 3 4,7<count each dchar,{all x like\"*[0-9][0-5][0-9]\"}peach sdv,.csv.cancast[\"U\"]peach sdv; /2359\n\tinfo:update t:\"U\",rule:150,maybe:0b from info where t=\"n\",mw in 4 5,mdot=0,{all x like\"*[0-9]:[0-5][0-9]\"}peach sdv,.csv.cancast[\"U\"]peach sdv;\n\tinfo:update t:\"T\",rule:160,maybe:0b from info where t=\"n\",mw within 7 12,mdot<2,{all x like\"*[0-9]:[0-5][0-9]:[0-5][0-9]*\"}peach sdv,.csv.cancast[\"T\"]peach sdv;\n\tinfo:update t:\"V\",rule:170,maybe:0b from info where t=\"T\",mw in 7 8,mdot=0,.csv.cancast[\"V\"]peach sdv;\n\tinfo:update t:\"T\",rule:180,maybe:1b from info where t in\"EF\",mw within 7 10,mdot=1,{all x like\"*[0-9][0-5][0-9][0-5][0-9].*\"}peach sdv,.csv.cancast[\"T\"]peach sdv;\n\tinfo:update t:\"Z\",rule:190,maybe:0b from info where t=\"n\",mw within 11 24,mdot<4,.csv.cancast[\"Z\"]peach sdv;\n\tinfo:update t:\"P\",rule:200,maybe:1b from info where t=\"n\",mw within 12 29,mdot<4,{all x like\"[12]*\"}peach sdv,.csv.cancast[\"P\"]peach sdv;\n\tinfo:update t:\"N\",rule:210,maybe:1b from info where t=\"n\",mw within 3 28,mdot=1,.csv.cancast[\"N\"]peach sdv;\n\tinfo:update t:\"?\",rule:220,maybe:0b from info where t=\"n\"; / reset remaining maybe numeric\n\tinfo:update t:\"C\",rule:230,maybe:0b from info where t=\"?\",mw=1; / char\n\tinfo:update t:\"B\",rule:240,maybe:0b from info where t in\"HC\",mw=1,mdot=0,{$[all x in\"01tTfFyYnN\";(any\"0fFnN\"in x)and any\"1tTyY\"in x;0b]}each dchar; / boolean\n\tinfo:update t:\"B\",rule:250,maybe:1b from info where t in\"HC\",mw=1,mdot=0,{all x in\"01tTfFyYnN\"}each dchar; / boolean\n\tinfo:update t:\"X\",rule:260,maybe:0b from info where t=\"?\",mw=2,{$[all x in\"0123456789abcdefABCDEF\";(any .Q.n in x)and any\"abcdefABCDEF\"in x;0b]}each dchar; /hex\n\tinfo:update t:\"S\",rule:270,maybe:1b from info where t=\"?\",mw<.csv.SYMMAXWIDTH,mw>1,gr<.csv.SYMMAXGR; / symbols (max width permitting)\n\tinfo:update t:\"*\",rule:280,maybe:0b from info where t=\"?\"; / the rest as strings\n\t/ flag those S/* columns which could be encoded to integers (.Q.j10/x10/j12/x12) to avoid symbols\n\tinfo:update j12:1b from info where t in\"S*\",mw<13,{all x in .Q.nA}each dchar;\n\tinfo:update j10:1b from info where t in\"S*\",mw<11,{all x in .Q.b6}each dchar; \n\tselect c,ci,t,maybe,empty,res,j10,j12,ipa,mw,mdot,rule,gr,ndv,dchar from info}\ninfo:info0[;()] / by default don't restrict columns\ninfolike:{[file;pattern] info0[file;{x where x like y}[lower colhdrs[file];pattern]]} / .csv.infolike[file;\"*time\"]\n\n\\d .\n/ DATA:()\nbulkload:{[file;info]\n\tif[not`DATA in system\"v\";'`DATA.not.defined];\n\tif[count DATA;'`DATA.not.empty];\n\tloadhdrs:exec c from info where not t=\" \";loadfmts:exec t from info;\n\t.csv.fs2[{[file;loadhdrs;loadfmts] `DATA insert $[count DATA;flip loadhdrs!(loadfmts;.csv.DELIM)0:file;loadhdrs xcol(loadfmts;enlist .csv.DELIM)0:file]}[file;loadhdrs;loadfmts]];\n\tcount DATA}\n@[.:;\"\\\\l csvutil.custom.q\";::]; / save your custom settings in csvutil.custom.q to override those set at the beginning of the file \n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true\n      });\n    </script>\n\n    <p><strong>MIME type defined:</strong> <code>text/x-q</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/q/q.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"q\",function(config){\n  var indentUnit=config.indentUnit,\n      curPunc,\n      keywords=buildRE([\"abs\",\"acos\",\"aj\",\"aj0\",\"all\",\"and\",\"any\",\"asc\",\"asin\",\"asof\",\"atan\",\"attr\",\"avg\",\"avgs\",\"bin\",\"by\",\"ceiling\",\"cols\",\"cor\",\"cos\",\"count\",\"cov\",\"cross\",\"csv\",\"cut\",\"delete\",\"deltas\",\"desc\",\"dev\",\"differ\",\"distinct\",\"div\",\"do\",\"each\",\"ej\",\"enlist\",\"eval\",\"except\",\"exec\",\"exit\",\"exp\",\"fby\",\"fills\",\"first\",\"fkeys\",\"flip\",\"floor\",\"from\",\"get\",\"getenv\",\"group\",\"gtime\",\"hclose\",\"hcount\",\"hdel\",\"hopen\",\"hsym\",\"iasc\",\"idesc\",\"if\",\"ij\",\"in\",\"insert\",\"inter\",\"inv\",\"key\",\"keys\",\"last\",\"like\",\"list\",\"lj\",\"load\",\"log\",\"lower\",\"lsq\",\"ltime\",\"ltrim\",\"mavg\",\"max\",\"maxs\",\"mcount\",\"md5\",\"mdev\",\"med\",\"meta\",\"min\",\"mins\",\"mmax\",\"mmin\",\"mmu\",\"mod\",\"msum\",\"neg\",\"next\",\"not\",\"null\",\"or\",\"over\",\"parse\",\"peach\",\"pj\",\"plist\",\"prd\",\"prds\",\"prev\",\"prior\",\"rand\",\"rank\",\"ratios\",\"raze\",\"read0\",\"read1\",\"reciprocal\",\"reverse\",\"rload\",\"rotate\",\"rsave\",\"rtrim\",\"save\",\"scan\",\"select\",\"set\",\"setenv\",\"show\",\"signum\",\"sin\",\"sqrt\",\"ss\",\"ssr\",\"string\",\"sublist\",\"sum\",\"sums\",\"sv\",\"system\",\"tables\",\"tan\",\"til\",\"trim\",\"txf\",\"type\",\"uj\",\"ungroup\",\"union\",\"update\",\"upper\",\"upsert\",\"value\",\"var\",\"view\",\"views\",\"vs\",\"wavg\",\"where\",\"where\",\"while\",\"within\",\"wj\",\"wj1\",\"wsum\",\"xasc\",\"xbar\",\"xcol\",\"xcols\",\"xdesc\",\"xexp\",\"xgroup\",\"xkey\",\"xlog\",\"xprev\",\"xrank\"]),\n      E=/[|/&^!+:\\\\\\-*%$=~#;@><,?_\\'\\\"\\[\\(\\]\\)\\s{}]/;\n  function buildRE(w){return new RegExp(\"^(\"+w.join(\"|\")+\")$\");}\n  function tokenBase(stream,state){\n    var sol=stream.sol(),c=stream.next();\n    curPunc=null;\n    if(sol)\n      if(c==\"/\")\n        return(state.tokenize=tokenLineComment)(stream,state);\n      else if(c==\"\\\\\"){\n        if(stream.eol()||/\\s/.test(stream.peek()))\n          return stream.skipToEnd(),/^\\\\\\s*$/.test(stream.current())?(state.tokenize=tokenCommentToEOF)(stream):state.tokenize=tokenBase,\"comment\";\n        else\n          return state.tokenize=tokenBase,\"builtin\";\n      }\n    if(/\\s/.test(c))\n      return stream.peek()==\"/\"?(stream.skipToEnd(),\"comment\"):\"whitespace\";\n    if(c=='\"')\n      return(state.tokenize=tokenString)(stream,state);\n    if(c=='`')\n      return stream.eatWhile(/[A-Za-z\\d_:\\/.]/),\"symbol\";\n    if((\".\"==c&&/\\d/.test(stream.peek()))||/\\d/.test(c)){\n      var t=null;\n      stream.backUp(1);\n      if(stream.match(/^\\d{4}\\.\\d{2}(m|\\.\\d{2}([DT](\\d{2}(:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?)?)?)?)/)\n      || stream.match(/^\\d+D(\\d{2}(:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?)?)/)\n      || stream.match(/^\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?/)\n      || stream.match(/^\\d+[ptuv]{1}/))\n        t=\"temporal\";\n      else if(stream.match(/^0[NwW]{1}/)\n      || stream.match(/^0x[\\da-fA-F]*/)\n      || stream.match(/^[01]+[b]{1}/)\n      || stream.match(/^\\d+[chijn]{1}/)\n      || stream.match(/-?\\d*(\\.\\d*)?(e[+\\-]?\\d+)?(e|f)?/))\n        t=\"number\";\n      return(t&&(!(c=stream.peek())||E.test(c)))?t:(stream.next(),\"error\");\n    }\n    if(/[A-Za-z]|\\./.test(c))\n      return stream.eatWhile(/[A-Za-z._\\d]/),keywords.test(stream.current())?\"keyword\":\"variable\";\n    if(/[|/&^!+:\\\\\\-*%$=~#;@><\\.,?_\\']/.test(c))\n      return null;\n    if(/[{}\\(\\[\\]\\)]/.test(c))\n      return null;\n    return\"error\";\n  }\n  function tokenLineComment(stream,state){\n    return stream.skipToEnd(),/\\/\\s*$/.test(stream.current())?(state.tokenize=tokenBlockComment)(stream,state):(state.tokenize=tokenBase),\"comment\";\n  }\n  function tokenBlockComment(stream,state){\n    var f=stream.sol()&&stream.peek()==\"\\\\\";\n    stream.skipToEnd();\n    if(f&&/^\\\\\\s*$/.test(stream.current()))\n      state.tokenize=tokenBase;\n    return\"comment\";\n  }\n  function tokenCommentToEOF(stream){return stream.skipToEnd(),\"comment\";}\n  function tokenString(stream,state){\n    var escaped=false,next,end=false;\n    while((next=stream.next())){\n      if(next==\"\\\"\"&&!escaped){end=true;break;}\n      escaped=!escaped&&next==\"\\\\\";\n    }\n    if(end)state.tokenize=tokenBase;\n    return\"string\";\n  }\n  function pushContext(state,type,col){state.context={prev:state.context,indent:state.indent,col:col,type:type};}\n  function popContext(state){state.indent=state.context.indent;state.context=state.context.prev;}\n  return{\n    startState:function(){\n      return{tokenize:tokenBase,\n             context:null,\n             indent:0,\n             col:0};\n    },\n    token:function(stream,state){\n      if(stream.sol()){\n        if(state.context&&state.context.align==null)\n          state.context.align=false;\n        state.indent=stream.indentation();\n      }\n      //if (stream.eatSpace()) return null;\n      var style=state.tokenize(stream,state);\n      if(style!=\"comment\"&&state.context&&state.context.align==null&&state.context.type!=\"pattern\"){\n        state.context.align=true;\n      }\n      if(curPunc==\"(\")pushContext(state,\")\",stream.column());\n      else if(curPunc==\"[\")pushContext(state,\"]\",stream.column());\n      else if(curPunc==\"{\")pushContext(state,\"}\",stream.column());\n      else if(/[\\]\\}\\)]/.test(curPunc)){\n        while(state.context&&state.context.type==\"pattern\")popContext(state);\n        if(state.context&&curPunc==state.context.type)popContext(state);\n      }\n      else if(curPunc==\".\"&&state.context&&state.context.type==\"pattern\")popContext(state);\n      else if(/atom|string|variable/.test(style)&&state.context){\n        if(/[\\}\\]]/.test(state.context.type))\n          pushContext(state,\"pattern\",stream.column());\n        else if(state.context.type==\"pattern\"&&!state.context.align){\n          state.context.align=true;\n          state.context.col=stream.column();\n        }\n      }\n      return style;\n    },\n    indent:function(state,textAfter){\n      var firstChar=textAfter&&textAfter.charAt(0);\n      var context=state.context;\n      if(/[\\]\\}]/.test(firstChar))\n        while (context&&context.type==\"pattern\")context=context.prev;\n      var closing=context&&firstChar==context.type;\n      if(!context)\n        return 0;\n      else if(context.type==\"pattern\")\n        return context.col;\n      else if(context.align)\n        return context.col+(closing?0:1);\n      else\n        return context.indent+(closing?0:indentUnit);\n    }\n  };\n});\nCodeMirror.defineMIME(\"text/x-q\",\"q\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/r/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: R mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"r.js\"></script>\n<style>\n      .CodeMirror { border-top: 1px solid silver; border-bottom: 1px solid silver; }\n      .cm-s-default span.cm-semi { color: blue; font-weight: bold; }\n      .cm-s-default span.cm-dollar { color: orange; font-weight: bold; }\n      .cm-s-default span.cm-arrow { color: brown; }\n      .cm-s-default span.cm-arg-is { color: brown; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">R</a>\n  </ul>\n</div>\n\n<article>\n<h2>R mode</h2>\n<form><textarea id=\"code\" name=\"code\">\nX <- list(height = 5.4, weight = 54)\ncat(\"Printing objects: \"); print(X)\nprint(\"Accessing individual elements:\")\ncat(sprintf(\"Your height is %s and your weight is %s\\n\", X$height, X$weight))\n\n# Functions:\nsquare <- function(x) {\n  return(x * x)\n}\ncat(sprintf(\"The square of 3 is %s\\n\", square(3)))\n\n# In R, the last expression in a function is, by default, what is\n# returned. The idiomatic way to write the function is:\nsquare <- function(x) {\n  x * x\n}\n# or, for functions with short content:\nsquare <- function(x) x * x\n\n# Function arguments with default values:\ncube <- function(x = 5) x * x * x\ncat(sprintf(\"Calling cube with 2 : %s\\n\", cube(2))  # will give 2^3\ncat(sprintf(\"Calling cube        : %s\\n\", cube())   # will default to 5^3.\n\npowers <- function(x) list(x2 = x*x, x3 = x*x*x, x4 = x*x*x*x)\n\ncat(\"Powers of 3: \"); print(powers(3))\n\n# Data frames\ndf <- data.frame(letters = letters[1:5], '#letter' = 1:5)\nprint(df$letters)\nprint(df$`#letter`)\n\n# Operators:\nm1 <- matrix(1:6, 2, 3)\nm2 <- m1 %*% t(m1)\ncat(\"Matrix product: \"); print(m2)\n\n# Assignments:\na <- 1\nb <<- 2\nc = 3\n4 -> d\n5 ->> e\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-rsrc</code>.</p>\n\n    <p>Development of the CodeMirror R mode was kindly sponsored\n    by <a href=\"https://twitter.com/ubalo\">Ubalo</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/r/r.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.registerHelper(\"wordChars\", \"r\", /[\\w.]/);\n\nCodeMirror.defineMode(\"r\", function(config) {\n  function wordObj(words) {\n    var res = {};\n    for (var i = 0; i < words.length; ++i) res[words[i]] = true;\n    return res;\n  }\n  var commonAtoms = [\"NULL\", \"NA\", \"Inf\", \"NaN\", \"NA_integer_\", \"NA_real_\", \"NA_complex_\", \"NA_character_\", \"TRUE\", \"FALSE\"];\n  var commonBuiltins = [\"list\", \"quote\", \"bquote\", \"eval\", \"return\", \"call\", \"parse\", \"deparse\"];\n  var commonKeywords = [\"if\", \"else\", \"repeat\", \"while\", \"function\", \"for\", \"in\", \"next\", \"break\"];\n  var commonBlockKeywords = [\"if\", \"else\", \"repeat\", \"while\", \"function\", \"for\"];\n\n  CodeMirror.registerHelper(\"hintWords\", \"r\", commonAtoms.concat(commonBuiltins, commonKeywords));\n\n  var atoms = wordObj(commonAtoms);\n  var builtins = wordObj(commonBuiltins);\n  var keywords = wordObj(commonKeywords);\n  var blockkeywords = wordObj(commonBlockKeywords);\n  var opChars = /[+\\-*\\/^<>=!&|~$:]/;\n  var curPunc;\n\n  function tokenBase(stream, state) {\n    curPunc = null;\n    var ch = stream.next();\n    if (ch == \"#\") {\n      stream.skipToEnd();\n      return \"comment\";\n    } else if (ch == \"0\" && stream.eat(\"x\")) {\n      stream.eatWhile(/[\\da-f]/i);\n      return \"number\";\n    } else if (ch == \".\" && stream.eat(/\\d/)) {\n      stream.match(/\\d*(?:e[+\\-]?\\d+)?/);\n      return \"number\";\n    } else if (/\\d/.test(ch)) {\n      stream.match(/\\d*(?:\\.\\d+)?(?:e[+\\-]\\d+)?L?/);\n      return \"number\";\n    } else if (ch == \"'\" || ch == '\"') {\n      state.tokenize = tokenString(ch);\n      return \"string\";\n    } else if (ch == \"`\") {\n      stream.match(/[^`]+`/);\n      return \"variable-3\";\n    } else if (ch == \".\" && stream.match(/.[.\\d]+/)) {\n      return \"keyword\";\n    } else if (/[\\w\\.]/.test(ch) && ch != \"_\") {\n      stream.eatWhile(/[\\w\\.]/);\n      var word = stream.current();\n      if (atoms.propertyIsEnumerable(word)) return \"atom\";\n      if (keywords.propertyIsEnumerable(word)) {\n        // Block keywords start new blocks, except 'else if', which only starts\n        // one new block for the 'if', no block for the 'else'.\n        if (blockkeywords.propertyIsEnumerable(word) &&\n            !stream.match(/\\s*if(\\s+|$)/, false))\n          curPunc = \"block\";\n        return \"keyword\";\n      }\n      if (builtins.propertyIsEnumerable(word)) return \"builtin\";\n      return \"variable\";\n    } else if (ch == \"%\") {\n      if (stream.skipTo(\"%\")) stream.next();\n      return \"operator variable-2\";\n    } else if (\n        (ch == \"<\" && stream.eat(\"-\")) ||\n        (ch == \"<\" && stream.match(\"<-\")) ||\n        (ch == \"-\" && stream.match(/>>?/))\n      ) {\n      return \"operator arrow\";\n    } else if (ch == \"=\" && state.ctx.argList) {\n      return \"arg-is\";\n    } else if (opChars.test(ch)) {\n      if (ch == \"$\") return \"operator dollar\";\n      stream.eatWhile(opChars);\n      return \"operator\";\n    } else if (/[\\(\\){}\\[\\];]/.test(ch)) {\n      curPunc = ch;\n      if (ch == \";\") return \"semi\";\n      return null;\n    } else {\n      return null;\n    }\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      if (stream.eat(\"\\\\\")) {\n        var ch = stream.next();\n        if (ch == \"x\") stream.match(/^[a-f0-9]{2}/i);\n        else if ((ch == \"u\" || ch == \"U\") && stream.eat(\"{\") && stream.skipTo(\"}\")) stream.next();\n        else if (ch == \"u\") stream.match(/^[a-f0-9]{4}/i);\n        else if (ch == \"U\") stream.match(/^[a-f0-9]{8}/i);\n        else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/);\n        return \"string-2\";\n      } else {\n        var next;\n        while ((next = stream.next()) != null) {\n          if (next == quote) { state.tokenize = tokenBase; break; }\n          if (next == \"\\\\\") { stream.backUp(1); break; }\n        }\n        return \"string\";\n      }\n    };\n  }\n\n  var ALIGN_YES = 1, ALIGN_NO = 2, BRACELESS = 4\n\n  function push(state, type, stream) {\n    state.ctx = {type: type,\n                 indent: state.indent,\n                 flags: 0,\n                 column: stream.column(),\n                 prev: state.ctx};\n  }\n  function setFlag(state, flag) {\n    var ctx = state.ctx\n    state.ctx = {type: ctx.type,\n                 indent: ctx.indent,\n                 flags: ctx.flags | flag,\n                 column: ctx.column,\n                 prev: ctx.prev}\n  }\n  function pop(state) {\n    state.indent = state.ctx.indent;\n    state.ctx = state.ctx.prev;\n  }\n\n  return {\n    startState: function() {\n      return {tokenize: tokenBase,\n              ctx: {type: \"top\",\n                    indent: -config.indentUnit,\n                    flags: ALIGN_NO},\n              indent: 0,\n              afterIdent: false};\n    },\n\n    token: function(stream, state) {\n      if (stream.sol()) {\n        if ((state.ctx.flags & 3) == 0) state.ctx.flags |= ALIGN_NO\n        if (state.ctx.flags & BRACELESS) pop(state)\n        state.indent = stream.indentation();\n      }\n      if (stream.eatSpace()) return null;\n      var style = state.tokenize(stream, state);\n      if (style != \"comment\" && (state.ctx.flags & ALIGN_NO) == 0) setFlag(state, ALIGN_YES)\n\n      if ((curPunc == \";\" || curPunc == \"{\" || curPunc == \"}\") && state.ctx.type == \"block\") pop(state);\n      if (curPunc == \"{\") push(state, \"}\", stream);\n      else if (curPunc == \"(\") {\n        push(state, \")\", stream);\n        if (state.afterIdent) state.ctx.argList = true;\n      }\n      else if (curPunc == \"[\") push(state, \"]\", stream);\n      else if (curPunc == \"block\") push(state, \"block\", stream);\n      else if (curPunc == state.ctx.type) pop(state);\n      else if (state.ctx.type == \"block\" && style != \"comment\") setFlag(state, BRACELESS)\n      state.afterIdent = style == \"variable\" || style == \"keyword\";\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize != tokenBase) return 0;\n      var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx,\n          closing = firstChar == ctx.type;\n      if (ctx.flags & BRACELESS) ctx = ctx.prev\n      if (ctx.type == \"block\") return ctx.indent + (firstChar == \"{\" ? 0 : config.indentUnit);\n      else if (ctx.flags & ALIGN_YES) return ctx.column + (closing ? 0 : 1);\n      else return ctx.indent + (closing ? 0 : config.indentUnit);\n    },\n\n    lineComment: \"#\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-rsrc\", \"r\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/rpm/changes/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: RPM changes mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n    <link rel=\"stylesheet\" href=\"../../../lib/codemirror.css\">\n    <script src=\"../../../lib/codemirror.js\"></script>\n    <script src=\"changes.js\"></script>\n    <link rel=\"stylesheet\" href=\"../../../doc/docs.css\">\n    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../../index.html\">Home</a>\n    <li><a href=\"../../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">RPM changes</a>\n  </ul>\n</div>\n\n<article>\n<h2>RPM changes mode</h2>\n\n    <div><textarea id=\"code\" name=\"code\">\n-------------------------------------------------------------------\nTue Oct 18 13:58:40 UTC 2011 - misterx@example.com\n\n- Update to r60.3\n- Fixes bug in the reflect package\n  * disallow Interface method on Value obtained via unexported name\n\n-------------------------------------------------------------------\nThu Oct  6 08:14:24 UTC 2011 - misterx@example.com\n\n- Update to r60.2\n- Fixes memory leak in certain map types\n\n-------------------------------------------------------------------\nWed Oct  5 14:34:10 UTC 2011 - misterx@example.com\n\n- Tweaks for gdb debugging\n- go.spec changes:\n  - move %go_arch definition to %prep section\n  - pass correct location of go specific gdb pretty printer and\n    functions to cpp as HOST_EXTRA_CFLAGS macro\n  - install go gdb functions & printer\n- gdb-printer.patch\n  - patch linker (src/cmd/ld/dwarf.c) to emit correct location of go\n    gdb functions and pretty printer\n</textarea></div>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"changes\"},\n        lineNumbers: true,\n        indentUnit: 4\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-rpm-changes</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/rpm/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: RPM changes mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n    <link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n    <script src=\"../../lib/codemirror.js\"></script>\n    <script src=\"rpm.js\"></script>\n    <link rel=\"stylesheet\" href=\"../../doc/docs.css\">\n    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">RPM</a>\n  </ul>\n</div>\n\n<article>\n<h2>RPM changes mode</h2>\n\n    <div><textarea id=\"code\" name=\"code\">\n-------------------------------------------------------------------\nTue Oct 18 13:58:40 UTC 2011 - misterx@example.com\n\n- Update to r60.3\n- Fixes bug in the reflect package\n  * disallow Interface method on Value obtained via unexported name\n\n-------------------------------------------------------------------\nThu Oct  6 08:14:24 UTC 2011 - misterx@example.com\n\n- Update to r60.2\n- Fixes memory leak in certain map types\n\n-------------------------------------------------------------------\nWed Oct  5 14:34:10 UTC 2011 - misterx@example.com\n\n- Tweaks for gdb debugging\n- go.spec changes:\n  - move %go_arch definition to %prep section\n  - pass correct location of go specific gdb pretty printer and\n    functions to cpp as HOST_EXTRA_CFLAGS macro\n  - install go gdb functions & printer\n- gdb-printer.patch\n  - patch linker (src/cmd/ld/dwarf.c) to emit correct location of go\n    gdb functions and pretty printer\n</textarea></div>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"rpm-changes\"},\n        lineNumbers: true,\n        indentUnit: 4\n      });\n    </script>\n\n<h2>RPM spec mode</h2>\n    \n    <div><textarea id=\"code2\" name=\"code2\">\n#\n# spec file for package minidlna\n#\n# Copyright (c) 2011, Sascha Peilicke <saschpe@gmx.de>\n#\n# All modifications and additions to the file contributed by third parties\n# remain the property of their copyright owners, unless otherwise agreed\n# upon. The license for this file, and modifications and additions to the\n# file, is the same license as for the pristine package itself (unless the\n# license for the pristine package is not an Open Source License, in which\n# case the license is the MIT License). An \"Open Source License\" is a\n# license that conforms to the Open Source Definition (Version 1.9)\n# published by the Open Source Initiative.\n\n\nName:           libupnp6\nVersion:        1.6.13\nRelease:        0\nSummary:        Portable Universal Plug and Play (UPnP) SDK\nGroup:          System/Libraries\nLicense:        BSD-3-Clause\nUrl:            http://sourceforge.net/projects/pupnp/\nSource0:        http://downloads.sourceforge.net/pupnp/libupnp-%{version}.tar.bz2\nBuildRoot:      %{_tmppath}/%{name}-%{version}-build\n\n%description\nThe portable Universal Plug and Play (UPnP) SDK provides support for building\nUPnP-compliant control points, devices, and bridges on several operating\nsystems.\n\n%package -n libupnp-devel\nSummary:        Portable Universal Plug and Play (UPnP) SDK\nGroup:          Development/Libraries/C and C++\nProvides:       pkgconfig(libupnp)\nRequires:       %{name} = %{version}\n\n%description -n libupnp-devel\nThe portable Universal Plug and Play (UPnP) SDK provides support for building\nUPnP-compliant control points, devices, and bridges on several operating\nsystems.\n\n%prep\n%setup -n libupnp-%{version}\n\n%build\n%configure --disable-static\nmake %{?_smp_mflags}\n\n%install\n%makeinstall\nfind %{buildroot} -type f -name '*.la' -exec rm -f {} ';'\n\n%post -p /sbin/ldconfig\n\n%postun -p /sbin/ldconfig\n\n%files\n%defattr(-,root,root,-)\n%doc ChangeLog NEWS README TODO\n%{_libdir}/libixml.so.*\n%{_libdir}/libthreadutil.so.*\n%{_libdir}/libupnp.so.*\n\n%files -n libupnp-devel\n%defattr(-,root,root,-)\n%{_libdir}/pkgconfig/libupnp.pc\n%{_libdir}/libixml.so\n%{_libdir}/libthreadutil.so\n%{_libdir}/libupnp.so\n%{_includedir}/upnp/\n\n%changelog</textarea></div>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code2\"), {\n        mode: {name: \"rpm-spec\"},\n        lineNumbers: true,\n        indentUnit: 4\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-rpm-spec</code>, <code>text/x-rpm-changes</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/rpm/rpm.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"rpm-changes\", function() {\n  var headerSeperator = /^-+$/;\n  var headerLine = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)  ?\\d{1,2} \\d{2}:\\d{2}(:\\d{2})? [A-Z]{3,4} \\d{4} - /;\n  var simpleEmail = /^[\\w+.-]+@[\\w.-]+/;\n\n  return {\n    token: function(stream) {\n      if (stream.sol()) {\n        if (stream.match(headerSeperator)) { return 'tag'; }\n        if (stream.match(headerLine)) { return 'tag'; }\n      }\n      if (stream.match(simpleEmail)) { return 'string'; }\n      stream.next();\n      return null;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-rpm-changes\", \"rpm-changes\");\n\n// Quick and dirty spec file highlighting\n\nCodeMirror.defineMode(\"rpm-spec\", function() {\n  var arch = /^(i386|i586|i686|x86_64|ppc64le|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/;\n\n  var preamble = /^[a-zA-Z0-9()]+:/;\n  var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preinstall|preun|postinstall|postun|pretrans|posttrans|pre|post|triggerin|triggerun|verifyscript|check|triggerpostun|triggerprein|trigger)/;\n  var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros\n  var control_flow_simple = /^%(else|endif)/; // rpm control flow macros\n  var operators = /^(\\!|\\?|\\<\\=|\\<|\\>\\=|\\>|\\=\\=|\\&\\&|\\|\\|)/; // operators in control flow macros\n\n  return {\n    startState: function () {\n        return {\n          controlFlow: false,\n          macroParameters: false,\n          section: false\n        };\n    },\n    token: function (stream, state) {\n      var ch = stream.peek();\n      if (ch == \"#\") { stream.skipToEnd(); return \"comment\"; }\n\n      if (stream.sol()) {\n        if (stream.match(preamble)) { return \"header\"; }\n        if (stream.match(section)) { return \"atom\"; }\n      }\n\n      if (stream.match(/^\\$\\w+/)) { return \"def\"; } // Variables like '$RPM_BUILD_ROOT'\n      if (stream.match(/^\\$\\{\\w+\\}/)) { return \"def\"; } // Variables like '${RPM_BUILD_ROOT}'\n\n      if (stream.match(control_flow_simple)) { return \"keyword\"; }\n      if (stream.match(control_flow_complex)) {\n        state.controlFlow = true;\n        return \"keyword\";\n      }\n      if (state.controlFlow) {\n        if (stream.match(operators)) { return \"operator\"; }\n        if (stream.match(/^(\\d+)/)) { return \"number\"; }\n        if (stream.eol()) { state.controlFlow = false; }\n      }\n\n      if (stream.match(arch)) {\n        if (stream.eol()) { state.controlFlow = false; }\n        return \"number\";\n      }\n\n      // Macros like '%make_install' or '%attr(0775,root,root)'\n      if (stream.match(/^%[\\w]+/)) {\n        if (stream.match(/^\\(/)) { state.macroParameters = true; }\n        return \"keyword\";\n      }\n      if (state.macroParameters) {\n        if (stream.match(/^\\d+/)) { return \"number\";}\n        if (stream.match(/^\\)/)) {\n          state.macroParameters = false;\n          return \"keyword\";\n        }\n      }\n\n      // Macros like '%{defined fedora}'\n      if (stream.match(/^%\\{\\??[\\w \\-\\:\\!]+\\}/)) {\n        if (stream.eol()) { state.controlFlow = false; }\n        return \"def\";\n      }\n\n      //TODO: Include bash script sub-parser (CodeMirror supports that)\n      stream.next();\n      return null;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-rpm-spec\", \"rpm-spec\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/rst/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: reStructuredText mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/overlay.js\"></script>\n<script src=\"rst.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">reStructuredText</a>\n  </ul>\n</div>\n\n<article>\n<h2>reStructuredText mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n.. This is an excerpt from Sphinx documentation: http://sphinx.pocoo.org/_sources/rest.txt\n\n.. highlightlang:: rest\n\n.. _rst-primer:\n\nreStructuredText Primer\n=======================\n\nThis section is a brief introduction to reStructuredText (reST) concepts and\nsyntax, intended to provide authors with enough information to author documents\nproductively.  Since reST was designed to be a simple, unobtrusive markup\nlanguage, this will not take too long.\n\n.. seealso::\n\n   The authoritative `reStructuredText User Documentation\n   &lt;http://docutils.sourceforge.net/rst.html&gt;`_.  The \"ref\" links in this\n   document link to the description of the individual constructs in the reST\n   reference.\n\n\nParagraphs\n----------\n\nThe paragraph (:duref:`ref &lt;paragraphs&gt;`) is the most basic block in a reST\ndocument.  Paragraphs are simply chunks of text separated by one or more blank\nlines.  As in Python, indentation is significant in reST, so all lines of the\nsame paragraph must be left-aligned to the same level of indentation.\n\n\n.. _inlinemarkup:\n\nInline markup\n-------------\n\nThe standard reST inline markup is quite simple: use\n\n* one asterisk: ``*text*`` for emphasis (italics),\n* two asterisks: ``**text**`` for strong emphasis (boldface), and\n* backquotes: ````text```` for code samples.\n\nIf asterisks or backquotes appear in running text and could be confused with\ninline markup delimiters, they have to be escaped with a backslash.\n\nBe aware of some restrictions of this markup:\n\n* it may not be nested,\n* content may not start or end with whitespace: ``* text*`` is wrong,\n* it must be separated from surrounding text by non-word characters.  Use a\n  backslash escaped space to work around that: ``thisis\\ *one*\\ word``.\n\nThese restrictions may be lifted in future versions of the docutils.\n\nreST also allows for custom \"interpreted text roles\"', which signify that the\nenclosed text should be interpreted in a specific way.  Sphinx uses this to\nprovide semantic markup and cross-referencing of identifiers, as described in\nthe appropriate section.  The general syntax is ``:rolename:`content```.\n\nStandard reST provides the following roles:\n\n* :durole:`emphasis` -- alternate spelling for ``*emphasis*``\n* :durole:`strong` -- alternate spelling for ``**strong**``\n* :durole:`literal` -- alternate spelling for ````literal````\n* :durole:`subscript` -- subscript text\n* :durole:`superscript` -- superscript text\n* :durole:`title-reference` -- for titles of books, periodicals, and other\n  materials\n\nSee :ref:`inline-markup` for roles added by Sphinx.\n\n\nLists and Quote-like blocks\n---------------------------\n\nList markup (:duref:`ref &lt;bullet-lists&gt;`) is natural: just place an asterisk at\nthe start of a paragraph and indent properly.  The same goes for numbered lists;\nthey can also be autonumbered using a ``#`` sign::\n\n   * This is a bulleted list.\n   * It has two items, the second\n     item uses two lines.\n\n   1. This is a numbered list.\n   2. It has two items too.\n\n   #. This is a numbered list.\n   #. It has two items too.\n\n\nNested lists are possible, but be aware that they must be separated from the\nparent list items by blank lines::\n\n   * this is\n   * a list\n\n     * with a nested list\n     * and some subitems\n\n   * and here the parent list continues\n\nDefinition lists (:duref:`ref &lt;definition-lists&gt;`) are created as follows::\n\n   term (up to a line of text)\n      Definition of the term, which must be indented\n\n      and can even consist of multiple paragraphs\n\n   next term\n      Description.\n\nNote that the term cannot have more than one line of text.\n\nQuoted paragraphs (:duref:`ref &lt;block-quotes&gt;`) are created by just indenting\nthem more than the surrounding paragraphs.\n\nLine blocks (:duref:`ref &lt;line-blocks&gt;`) are a way of preserving line breaks::\n\n   | These lines are\n   | broken exactly like in\n   | the source file.\n\nThere are also several more special blocks available:\n\n* field lists (:duref:`ref &lt;field-lists&gt;`)\n* option lists (:duref:`ref &lt;option-lists&gt;`)\n* quoted literal blocks (:duref:`ref &lt;quoted-literal-blocks&gt;`)\n* doctest blocks (:duref:`ref &lt;doctest-blocks&gt;`)\n\n\nSource Code\n-----------\n\nLiteral code blocks (:duref:`ref &lt;literal-blocks&gt;`) are introduced by ending a\nparagraph with the special marker ``::``.  The literal block must be indented\n(and, like all paragraphs, separated from the surrounding ones by blank lines)::\n\n   This is a normal text paragraph. The next paragraph is a code sample::\n\n      It is not processed in any way, except\n      that the indentation is removed.\n\n      It can span multiple lines.\n\n   This is a normal text paragraph again.\n\nThe handling of the ``::`` marker is smart:\n\n* If it occurs as a paragraph of its own, that paragraph is completely left\n  out of the document.\n* If it is preceded by whitespace, the marker is removed.\n* If it is preceded by non-whitespace, the marker is replaced by a single\n  colon.\n\nThat way, the second sentence in the above example's first paragraph would be\nrendered as \"The next paragraph is a code sample:\".\n\n\n.. _rst-tables:\n\nTables\n------\n\nTwo forms of tables are supported.  For *grid tables* (:duref:`ref\n&lt;grid-tables&gt;`), you have to \"paint\" the cell grid yourself.  They look like\nthis::\n\n   +------------------------+------------+----------+----------+\n   | Header row, column 1   | Header 2   | Header 3 | Header 4 |\n   | (header rows optional) |            |          |          |\n   +========================+============+==========+==========+\n   | body row 1, column 1   | column 2   | column 3 | column 4 |\n   +------------------------+------------+----------+----------+\n   | body row 2             | ...        | ...      |          |\n   +------------------------+------------+----------+----------+\n\n*Simple tables* (:duref:`ref &lt;simple-tables&gt;`) are easier to write, but\nlimited: they must contain more than one row, and the first column cannot\ncontain multiple lines.  They look like this::\n\n   =====  =====  =======\n   A      B      A and B\n   =====  =====  =======\n   False  False  False\n   True   False  False\n   False  True   False\n   True   True   True\n   =====  =====  =======\n\n\nHyperlinks\n----------\n\nExternal links\n^^^^^^^^^^^^^^\n\nUse ```Link text &lt;http://example.com/&gt;`_`` for inline web links.  If the link\ntext should be the web address, you don't need special markup at all, the parser\nfinds links and mail addresses in ordinary text.\n\nYou can also separate the link and the target definition (:duref:`ref\n&lt;hyperlink-targets&gt;`), like this::\n\n   This is a paragraph that contains `a link`_.\n\n   .. _a link: http://example.com/\n\n\nInternal links\n^^^^^^^^^^^^^^\n\nInternal linking is done via a special reST role provided by Sphinx, see the\nsection on specific markup, :ref:`ref-role`.\n\n\nSections\n--------\n\nSection headers (:duref:`ref &lt;sections&gt;`) are created by underlining (and\noptionally overlining) the section title with a punctuation character, at least\nas long as the text::\n\n   =================\n   This is a heading\n   =================\n\nNormally, there are no heading levels assigned to certain characters as the\nstructure is determined from the succession of headings.  However, for the\nPython documentation, this convention is used which you may follow:\n\n* ``#`` with overline, for parts\n* ``*`` with overline, for chapters\n* ``=``, for sections\n* ``-``, for subsections\n* ``^``, for subsubsections\n* ``\"``, for paragraphs\n\nOf course, you are free to use your own marker characters (see the reST\ndocumentation), and use a deeper nesting level, but keep in mind that most\ntarget formats (HTML, LaTeX) have a limited supported nesting depth.\n\n\nExplicit Markup\n---------------\n\n\"Explicit markup\" (:duref:`ref &lt;explicit-markup-blocks&gt;`) is used in reST for\nmost constructs that need special handling, such as footnotes,\nspecially-highlighted paragraphs, comments, and generic directives.\n\nAn explicit markup block begins with a line starting with ``..`` followed by\nwhitespace and is terminated by the next paragraph at the same level of\nindentation.  (There needs to be a blank line between explicit markup and normal\nparagraphs.  This may all sound a bit complicated, but it is intuitive enough\nwhen you write it.)\n\n\n.. _directives:\n\nDirectives\n----------\n\nA directive (:duref:`ref &lt;directives&gt;`) is a generic block of explicit markup.\nBesides roles, it is one of the extension mechanisms of reST, and Sphinx makes\nheavy use of it.\n\nDocutils supports the following directives:\n\n* Admonitions: :dudir:`attention`, :dudir:`caution`, :dudir:`danger`,\n  :dudir:`error`, :dudir:`hint`, :dudir:`important`, :dudir:`note`,\n  :dudir:`tip`, :dudir:`warning` and the generic :dudir:`admonition`.\n  (Most themes style only \"note\" and \"warning\" specially.)\n\n* Images:\n\n  - :dudir:`image` (see also Images_ below)\n  - :dudir:`figure` (an image with caption and optional legend)\n\n* Additional body elements:\n\n  - :dudir:`contents` (a local, i.e. for the current file only, table of\n    contents)\n  - :dudir:`container` (a container with a custom class, useful to generate an\n    outer ``&lt;div&gt;`` in HTML)\n  - :dudir:`rubric` (a heading without relation to the document sectioning)\n  - :dudir:`topic`, :dudir:`sidebar` (special highlighted body elements)\n  - :dudir:`parsed-literal` (literal block that supports inline markup)\n  - :dudir:`epigraph` (a block quote with optional attribution line)\n  - :dudir:`highlights`, :dudir:`pull-quote` (block quotes with their own\n    class attribute)\n  - :dudir:`compound` (a compound paragraph)\n\n* Special tables:\n\n  - :dudir:`table` (a table with title)\n  - :dudir:`csv-table` (a table generated from comma-separated values)\n  - :dudir:`list-table` (a table generated from a list of lists)\n\n* Special directives:\n\n  - :dudir:`raw` (include raw target-format markup)\n  - :dudir:`include` (include reStructuredText from another file)\n    -- in Sphinx, when given an absolute include file path, this directive takes\n    it as relative to the source directory\n  - :dudir:`class` (assign a class attribute to the next element) [1]_\n\n* HTML specifics:\n\n  - :dudir:`meta` (generation of HTML ``&lt;meta&gt;`` tags)\n  - :dudir:`title` (override document title)\n\n* Influencing markup:\n\n  - :dudir:`default-role` (set a new default role)\n  - :dudir:`role` (create a new role)\n\n  Since these are only per-file, better use Sphinx' facilities for setting the\n  :confval:`default_role`.\n\nDo *not* use the directives :dudir:`sectnum`, :dudir:`header` and\n:dudir:`footer`.\n\nDirectives added by Sphinx are described in :ref:`sphinxmarkup`.\n\nBasically, a directive consists of a name, arguments, options and content. (Keep\nthis terminology in mind, it is used in the next chapter describing custom\ndirectives.)  Looking at this example, ::\n\n   .. function:: foo(x)\n                 foo(y, z)\n      :module: some.module.name\n\n      Return a line of text input from the user.\n\n``function`` is the directive name.  It is given two arguments here, the\nremainder of the first line and the second line, as well as one option\n``module`` (as you can see, options are given in the lines immediately following\nthe arguments and indicated by the colons).  Options must be indented to the\nsame level as the directive content.\n\nThe directive content follows after a blank line and is indented relative to the\ndirective start.\n\n\nImages\n------\n\nreST supports an image directive (:dudir:`ref &lt;image&gt;`), used like so::\n\n   .. image:: gnu.png\n      (options)\n\nWhen used within Sphinx, the file name given (here ``gnu.png``) must either be\nrelative to the source file, or absolute which means that they are relative to\nthe top source directory.  For example, the file ``sketch/spam.rst`` could refer\nto the image ``images/spam.png`` as ``../images/spam.png`` or\n``/images/spam.png``.\n\nSphinx will automatically copy image files over to a subdirectory of the output\ndirectory on building (e.g. the ``_static`` directory for HTML output.)\n\nInterpretation of image size options (``width`` and ``height``) is as follows:\nif the size has no unit or the unit is pixels, the given size will only be\nrespected for output channels that support pixels (i.e. not in LaTeX output).\nOther units (like ``pt`` for points) will be used for HTML and LaTeX output.\n\nSphinx extends the standard docutils behavior by allowing an asterisk for the\nextension::\n\n   .. image:: gnu.*\n\nSphinx then searches for all images matching the provided pattern and determines\ntheir type.  Each builder then chooses the best image out of these candidates.\nFor instance, if the file name ``gnu.*`` was given and two files :file:`gnu.pdf`\nand :file:`gnu.png` existed in the source tree, the LaTeX builder would choose\nthe former, while the HTML builder would prefer the latter.\n\n.. versionchanged:: 0.4\n   Added the support for file names ending in an asterisk.\n\n.. versionchanged:: 0.6\n   Image paths can now be absolute.\n\n\nFootnotes\n---------\n\nFor footnotes (:duref:`ref &lt;footnotes&gt;`), use ``[#name]_`` to mark the footnote\nlocation, and add the footnote body at the bottom of the document after a\n\"Footnotes\" rubric heading, like so::\n\n   Lorem ipsum [#f1]_ dolor sit amet ... [#f2]_\n\n   .. rubric:: Footnotes\n\n   .. [#f1] Text of the first footnote.\n   .. [#f2] Text of the second footnote.\n\nYou can also explicitly number the footnotes (``[1]_``) or use auto-numbered\nfootnotes without names (``[#]_``).\n\n\nCitations\n---------\n\nStandard reST citations (:duref:`ref &lt;citations&gt;`) are supported, with the\nadditional feature that they are \"global\", i.e. all citations can be referenced\nfrom all files.  Use them like so::\n\n   Lorem ipsum [Ref]_ dolor sit amet.\n\n   .. [Ref] Book or article reference, URL or whatever.\n\nCitation usage is similar to footnote usage, but with a label that is not\nnumeric or begins with ``#``.\n\n\nSubstitutions\n-------------\n\nreST supports \"substitutions\" (:duref:`ref &lt;substitution-definitions&gt;`), which\nare pieces of text and/or markup referred to in the text by ``|name|``.  They\nare defined like footnotes with explicit markup blocks, like this::\n\n   .. |name| replace:: replacement *text*\n\nor this::\n\n   .. |caution| image:: warning.png\n                :alt: Warning!\n\nSee the :duref:`reST reference for substitutions &lt;substitution-definitions&gt;`\nfor details.\n\nIf you want to use some substitutions for all documents, put them into\n:confval:`rst_prolog` or put them into a separate file and include it into all\ndocuments you want to use them in, using the :rst:dir:`include` directive.  (Be\nsure to give the include file a file name extension differing from that of other\nsource files, to avoid Sphinx finding it as a standalone document.)\n\nSphinx defines some default substitutions, see :ref:`default-substitutions`.\n\n\nComments\n--------\n\nEvery explicit markup block which isn't a valid markup construct (like the\nfootnotes above) is regarded as a comment (:duref:`ref &lt;comments&gt;`).  For\nexample::\n\n   .. This is a comment.\n\nYou can indent text after a comment start to form multiline comments::\n\n   ..\n      This whole indented block\n      is a comment.\n\n      Still in the comment.\n\n\nSource encoding\n---------------\n\nSince the easiest way to include special characters like em dashes or copyright\nsigns in reST is to directly write them as Unicode characters, one has to\nspecify an encoding.  Sphinx assumes source files to be encoded in UTF-8 by\ndefault; you can change this with the :confval:`source_encoding` config value.\n\n\nGotchas\n-------\n\nThere are some problems one commonly runs into while authoring reST documents:\n\n* **Separation of inline markup:** As said above, inline markup spans must be\n  separated from the surrounding text by non-word characters, you have to use a\n  backslash-escaped space to get around that.  See `the reference\n  &lt;http://docutils.sf.net/docs/ref/rst/restructuredtext.html#inline-markup&gt;`_\n  for the details.\n\n* **No nested inline markup:** Something like ``*see :func:`foo`*`` is not\n  possible.\n\n\n.. rubric:: Footnotes\n\n.. [1] When the default domain contains a :rst:dir:`class` directive, this directive\n       will be shadowed.  Therefore, Sphinx re-exports it as :rst:dir:`rst-class`.\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n      });\n    </script>\n    <p>\n        The <code>python</code> mode will be used for highlighting blocks\n        containing Python/IPython terminal sessions: blocks starting with\n        <code>&gt;&gt;&gt;</code> (for Python) or <code>In [num]:</code> (for\n        IPython).\n\n        Further, the <code>stex</code> mode will be used for highlighting\n        blocks containing LaTex code.\n    </p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-rst</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/rst/rst.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../python/python\"), require(\"../stex/stex\"), require(\"../../addon/mode/overlay\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../python/python\", \"../stex/stex\", \"../../addon/mode/overlay\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode('rst', function (config, options) {\n\n  var rx_strong = /^\\*\\*[^\\*\\s](?:[^\\*]*[^\\*\\s])?\\*\\*/;\n  var rx_emphasis = /^\\*[^\\*\\s](?:[^\\*]*[^\\*\\s])?\\*/;\n  var rx_literal = /^``[^`\\s](?:[^`]*[^`\\s])``/;\n\n  var rx_number = /^(?:[\\d]+(?:[\\.,]\\d+)*)/;\n  var rx_positive = /^(?:\\s\\+[\\d]+(?:[\\.,]\\d+)*)/;\n  var rx_negative = /^(?:\\s\\-[\\d]+(?:[\\.,]\\d+)*)/;\n\n  var rx_uri_protocol = \"[Hh][Tt][Tt][Pp][Ss]?://\";\n  var rx_uri_domain = \"(?:[\\\\d\\\\w.-]+)\\\\.(?:\\\\w{2,6})\";\n  var rx_uri_path = \"(?:/[\\\\d\\\\w\\\\#\\\\%\\\\&\\\\-\\\\.\\\\,\\\\/\\\\:\\\\=\\\\?\\\\~]+)*\";\n  var rx_uri = new RegExp(\"^\" + rx_uri_protocol + rx_uri_domain + rx_uri_path);\n\n  var overlay = {\n    token: function (stream) {\n\n      if (stream.match(rx_strong) && stream.match (/\\W+|$/, false))\n        return 'strong';\n      if (stream.match(rx_emphasis) && stream.match (/\\W+|$/, false))\n        return 'em';\n      if (stream.match(rx_literal) && stream.match (/\\W+|$/, false))\n        return 'string-2';\n      if (stream.match(rx_number))\n        return 'number';\n      if (stream.match(rx_positive))\n        return 'positive';\n      if (stream.match(rx_negative))\n        return 'negative';\n      if (stream.match(rx_uri))\n        return 'link';\n\n      while (stream.next() != null) {\n        if (stream.match(rx_strong, false)) break;\n        if (stream.match(rx_emphasis, false)) break;\n        if (stream.match(rx_literal, false)) break;\n        if (stream.match(rx_number, false)) break;\n        if (stream.match(rx_positive, false)) break;\n        if (stream.match(rx_negative, false)) break;\n        if (stream.match(rx_uri, false)) break;\n      }\n\n      return null;\n    }\n  };\n\n  var mode = CodeMirror.getMode(\n    config, options.backdrop || 'rst-base'\n  );\n\n  return CodeMirror.overlayMode(mode, overlay, true); // combine\n}, 'python', 'stex');\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nCodeMirror.defineMode('rst-base', function (config) {\n\n  ///////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////\n\n  function format(string) {\n    var args = Array.prototype.slice.call(arguments, 1);\n    return string.replace(/{(\\d+)}/g, function (match, n) {\n      return typeof args[n] != 'undefined' ? args[n] : match;\n    });\n  }\n\n  ///////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////\n\n  var mode_python = CodeMirror.getMode(config, 'python');\n  var mode_stex = CodeMirror.getMode(config, 'stex');\n\n  ///////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////\n\n  var SEPA = \"\\\\s+\";\n  var TAIL = \"(?:\\\\s*|\\\\W|$)\",\n  rx_TAIL = new RegExp(format('^{0}', TAIL));\n\n  var NAME =\n    \"(?:[^\\\\W\\\\d_](?:[\\\\w!\\\"#$%&'()\\\\*\\\\+,\\\\-\\\\.\\/:;<=>\\\\?]*[^\\\\W_])?)\",\n  rx_NAME = new RegExp(format('^{0}', NAME));\n  var NAME_WWS =\n    \"(?:[^\\\\W\\\\d_](?:[\\\\w\\\\s!\\\"#$%&'()\\\\*\\\\+,\\\\-\\\\.\\/:;<=>\\\\?]*[^\\\\W_])?)\";\n  var REF_NAME = format('(?:{0}|`{1}`)', NAME, NAME_WWS);\n\n  var TEXT1 = \"(?:[^\\\\s\\\\|](?:[^\\\\|]*[^\\\\s\\\\|])?)\";\n  var TEXT2 = \"(?:[^\\\\`]+)\",\n  rx_TEXT2 = new RegExp(format('^{0}', TEXT2));\n\n  var rx_section = new RegExp(\n    \"^([!'#$%&\\\"()*+,-./:;<=>?@\\\\[\\\\\\\\\\\\]^_`{|}~])\\\\1{3,}\\\\s*$\");\n  var rx_explicit = new RegExp(\n    format('^\\\\.\\\\.{0}', SEPA));\n  var rx_link = new RegExp(\n    format('^_{0}:{1}|^__:{1}', REF_NAME, TAIL));\n  var rx_directive = new RegExp(\n    format('^{0}::{1}', REF_NAME, TAIL));\n  var rx_substitution = new RegExp(\n    format('^\\\\|{0}\\\\|{1}{2}::{3}', TEXT1, SEPA, REF_NAME, TAIL));\n  var rx_footnote = new RegExp(\n    format('^\\\\[(?:\\\\d+|#{0}?|\\\\*)]{1}', REF_NAME, TAIL));\n  var rx_citation = new RegExp(\n    format('^\\\\[{0}\\\\]{1}', REF_NAME, TAIL));\n\n  var rx_substitution_ref = new RegExp(\n    format('^\\\\|{0}\\\\|', TEXT1));\n  var rx_footnote_ref = new RegExp(\n    format('^\\\\[(?:\\\\d+|#{0}?|\\\\*)]_', REF_NAME));\n  var rx_citation_ref = new RegExp(\n    format('^\\\\[{0}\\\\]_', REF_NAME));\n  var rx_link_ref1 = new RegExp(\n    format('^{0}__?', REF_NAME));\n  var rx_link_ref2 = new RegExp(\n    format('^`{0}`_', TEXT2));\n\n  var rx_role_pre = new RegExp(\n    format('^:{0}:`{1}`{2}', NAME, TEXT2, TAIL));\n  var rx_role_suf = new RegExp(\n    format('^`{1}`:{0}:{2}', NAME, TEXT2, TAIL));\n  var rx_role = new RegExp(\n    format('^:{0}:{1}', NAME, TAIL));\n\n  var rx_directive_name = new RegExp(format('^{0}', REF_NAME));\n  var rx_directive_tail = new RegExp(format('^::{0}', TAIL));\n  var rx_substitution_text = new RegExp(format('^\\\\|{0}\\\\|', TEXT1));\n  var rx_substitution_sepa = new RegExp(format('^{0}', SEPA));\n  var rx_substitution_name = new RegExp(format('^{0}', REF_NAME));\n  var rx_substitution_tail = new RegExp(format('^::{0}', TAIL));\n  var rx_link_head = new RegExp(\"^_\");\n  var rx_link_name = new RegExp(format('^{0}|_', REF_NAME));\n  var rx_link_tail = new RegExp(format('^:{0}', TAIL));\n\n  var rx_verbatim = new RegExp('^::\\\\s*$');\n  var rx_examples = new RegExp('^\\\\s+(?:>>>|In \\\\[\\\\d+\\\\]:)\\\\s');\n\n  ///////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////\n\n  function to_normal(stream, state) {\n    var token = null;\n\n    if (stream.sol() && stream.match(rx_examples, false)) {\n      change(state, to_mode, {\n        mode: mode_python, local: CodeMirror.startState(mode_python)\n      });\n    } else if (stream.sol() && stream.match(rx_explicit)) {\n      change(state, to_explicit);\n      token = 'meta';\n    } else if (stream.sol() && stream.match(rx_section)) {\n      change(state, to_normal);\n      token = 'header';\n    } else if (phase(state) == rx_role_pre ||\n               stream.match(rx_role_pre, false)) {\n\n      switch (stage(state)) {\n      case 0:\n        change(state, to_normal, context(rx_role_pre, 1));\n        stream.match(/^:/);\n        token = 'meta';\n        break;\n      case 1:\n        change(state, to_normal, context(rx_role_pre, 2));\n        stream.match(rx_NAME);\n        token = 'keyword';\n\n        if (stream.current().match(/^(?:math|latex)/)) {\n          state.tmp_stex = true;\n        }\n        break;\n      case 2:\n        change(state, to_normal, context(rx_role_pre, 3));\n        stream.match(/^:`/);\n        token = 'meta';\n        break;\n      case 3:\n        if (state.tmp_stex) {\n          state.tmp_stex = undefined; state.tmp = {\n            mode: mode_stex, local: CodeMirror.startState(mode_stex)\n          };\n        }\n\n        if (state.tmp) {\n          if (stream.peek() == '`') {\n            change(state, to_normal, context(rx_role_pre, 4));\n            state.tmp = undefined;\n            break;\n          }\n\n          token = state.tmp.mode.token(stream, state.tmp.local);\n          break;\n        }\n\n        change(state, to_normal, context(rx_role_pre, 4));\n        stream.match(rx_TEXT2);\n        token = 'string';\n        break;\n      case 4:\n        change(state, to_normal, context(rx_role_pre, 5));\n        stream.match(/^`/);\n        token = 'meta';\n        break;\n      case 5:\n        change(state, to_normal, context(rx_role_pre, 6));\n        stream.match(rx_TAIL);\n        break;\n      default:\n        change(state, to_normal);\n      }\n    } else if (phase(state) == rx_role_suf ||\n               stream.match(rx_role_suf, false)) {\n\n      switch (stage(state)) {\n      case 0:\n        change(state, to_normal, context(rx_role_suf, 1));\n        stream.match(/^`/);\n        token = 'meta';\n        break;\n      case 1:\n        change(state, to_normal, context(rx_role_suf, 2));\n        stream.match(rx_TEXT2);\n        token = 'string';\n        break;\n      case 2:\n        change(state, to_normal, context(rx_role_suf, 3));\n        stream.match(/^`:/);\n        token = 'meta';\n        break;\n      case 3:\n        change(state, to_normal, context(rx_role_suf, 4));\n        stream.match(rx_NAME);\n        token = 'keyword';\n        break;\n      case 4:\n        change(state, to_normal, context(rx_role_suf, 5));\n        stream.match(/^:/);\n        token = 'meta';\n        break;\n      case 5:\n        change(state, to_normal, context(rx_role_suf, 6));\n        stream.match(rx_TAIL);\n        break;\n      default:\n        change(state, to_normal);\n      }\n    } else if (phase(state) == rx_role || stream.match(rx_role, false)) {\n\n      switch (stage(state)) {\n      case 0:\n        change(state, to_normal, context(rx_role, 1));\n        stream.match(/^:/);\n        token = 'meta';\n        break;\n      case 1:\n        change(state, to_normal, context(rx_role, 2));\n        stream.match(rx_NAME);\n        token = 'keyword';\n        break;\n      case 2:\n        change(state, to_normal, context(rx_role, 3));\n        stream.match(/^:/);\n        token = 'meta';\n        break;\n      case 3:\n        change(state, to_normal, context(rx_role, 4));\n        stream.match(rx_TAIL);\n        break;\n      default:\n        change(state, to_normal);\n      }\n    } else if (phase(state) == rx_substitution_ref ||\n               stream.match(rx_substitution_ref, false)) {\n\n      switch (stage(state)) {\n      case 0:\n        change(state, to_normal, context(rx_substitution_ref, 1));\n        stream.match(rx_substitution_text);\n        token = 'variable-2';\n        break;\n      case 1:\n        change(state, to_normal, context(rx_substitution_ref, 2));\n        if (stream.match(/^_?_?/)) token = 'link';\n        break;\n      default:\n        change(state, to_normal);\n      }\n    } else if (stream.match(rx_footnote_ref)) {\n      change(state, to_normal);\n      token = 'quote';\n    } else if (stream.match(rx_citation_ref)) {\n      change(state, to_normal);\n      token = 'quote';\n    } else if (stream.match(rx_link_ref1)) {\n      change(state, to_normal);\n      if (!stream.peek() || stream.peek().match(/^\\W$/)) {\n        token = 'link';\n      }\n    } else if (phase(state) == rx_link_ref2 ||\n               stream.match(rx_link_ref2, false)) {\n\n      switch (stage(state)) {\n      case 0:\n        if (!stream.peek() || stream.peek().match(/^\\W$/)) {\n          change(state, to_normal, context(rx_link_ref2, 1));\n        } else {\n          stream.match(rx_link_ref2);\n        }\n        break;\n      case 1:\n        change(state, to_normal, context(rx_link_ref2, 2));\n        stream.match(/^`/);\n        token = 'link';\n        break;\n      case 2:\n        change(state, to_normal, context(rx_link_ref2, 3));\n        stream.match(rx_TEXT2);\n        break;\n      case 3:\n        change(state, to_normal, context(rx_link_ref2, 4));\n        stream.match(/^`_/);\n        token = 'link';\n        break;\n      default:\n        change(state, to_normal);\n      }\n    } else if (stream.match(rx_verbatim)) {\n      change(state, to_verbatim);\n    }\n\n    else {\n      if (stream.next()) change(state, to_normal);\n    }\n\n    return token;\n  }\n\n  ///////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////\n\n  function to_explicit(stream, state) {\n    var token = null;\n\n    if (phase(state) == rx_substitution ||\n        stream.match(rx_substitution, false)) {\n\n      switch (stage(state)) {\n      case 0:\n        change(state, to_explicit, context(rx_substitution, 1));\n        stream.match(rx_substitution_text);\n        token = 'variable-2';\n        break;\n      case 1:\n        change(state, to_explicit, context(rx_substitution, 2));\n        stream.match(rx_substitution_sepa);\n        break;\n      case 2:\n        change(state, to_explicit, context(rx_substitution, 3));\n        stream.match(rx_substitution_name);\n        token = 'keyword';\n        break;\n      case 3:\n        change(state, to_explicit, context(rx_substitution, 4));\n        stream.match(rx_substitution_tail);\n        token = 'meta';\n        break;\n      default:\n        change(state, to_normal);\n      }\n    } else if (phase(state) == rx_directive ||\n               stream.match(rx_directive, false)) {\n\n      switch (stage(state)) {\n      case 0:\n        change(state, to_explicit, context(rx_directive, 1));\n        stream.match(rx_directive_name);\n        token = 'keyword';\n\n        if (stream.current().match(/^(?:math|latex)/))\n          state.tmp_stex = true;\n        else if (stream.current().match(/^python/))\n          state.tmp_py = true;\n        break;\n      case 1:\n        change(state, to_explicit, context(rx_directive, 2));\n        stream.match(rx_directive_tail);\n        token = 'meta';\n\n        if (stream.match(/^latex\\s*$/) || state.tmp_stex) {\n          state.tmp_stex = undefined; change(state, to_mode, {\n            mode: mode_stex, local: CodeMirror.startState(mode_stex)\n          });\n        }\n        break;\n      case 2:\n        change(state, to_explicit, context(rx_directive, 3));\n        if (stream.match(/^python\\s*$/) || state.tmp_py) {\n          state.tmp_py = undefined; change(state, to_mode, {\n            mode: mode_python, local: CodeMirror.startState(mode_python)\n          });\n        }\n        break;\n      default:\n        change(state, to_normal);\n      }\n    } else if (phase(state) == rx_link || stream.match(rx_link, false)) {\n\n      switch (stage(state)) {\n      case 0:\n        change(state, to_explicit, context(rx_link, 1));\n        stream.match(rx_link_head);\n        stream.match(rx_link_name);\n        token = 'link';\n        break;\n      case 1:\n        change(state, to_explicit, context(rx_link, 2));\n        stream.match(rx_link_tail);\n        token = 'meta';\n        break;\n      default:\n        change(state, to_normal);\n      }\n    } else if (stream.match(rx_footnote)) {\n      change(state, to_normal);\n      token = 'quote';\n    } else if (stream.match(rx_citation)) {\n      change(state, to_normal);\n      token = 'quote';\n    }\n\n    else {\n      stream.eatSpace();\n      if (stream.eol()) {\n        change(state, to_normal);\n      } else {\n        stream.skipToEnd();\n        change(state, to_comment);\n        token = 'comment';\n      }\n    }\n\n    return token;\n  }\n\n  ///////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////\n\n  function to_comment(stream, state) {\n    return as_block(stream, state, 'comment');\n  }\n\n  function to_verbatim(stream, state) {\n    return as_block(stream, state, 'meta');\n  }\n\n  function as_block(stream, state, token) {\n    if (stream.eol() || stream.eatSpace()) {\n      stream.skipToEnd();\n      return token;\n    } else {\n      change(state, to_normal);\n      return null;\n    }\n  }\n\n  ///////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////\n\n  function to_mode(stream, state) {\n\n    if (state.ctx.mode && state.ctx.local) {\n\n      if (stream.sol()) {\n        if (!stream.eatSpace()) change(state, to_normal);\n        return null;\n      }\n\n      return state.ctx.mode.token(stream, state.ctx.local);\n    }\n\n    change(state, to_normal);\n    return null;\n  }\n\n  ///////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////\n\n  function context(phase, stage, mode, local) {\n    return {phase: phase, stage: stage, mode: mode, local: local};\n  }\n\n  function change(state, tok, ctx) {\n    state.tok = tok;\n    state.ctx = ctx || {};\n  }\n\n  function stage(state) {\n    return state.ctx.stage || 0;\n  }\n\n  function phase(state) {\n    return state.ctx.phase;\n  }\n\n  ///////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////\n\n  return {\n    startState: function () {\n      return {tok: to_normal, ctx: context(undefined, 0)};\n    },\n\n    copyState: function (state) {\n      var ctx = state.ctx, tmp = state.tmp;\n      if (ctx.local)\n        ctx = {mode: ctx.mode, local: CodeMirror.copyState(ctx.mode, ctx.local)};\n      if (tmp)\n        tmp = {mode: tmp.mode, local: CodeMirror.copyState(tmp.mode, tmp.local)};\n      return {tok: state.tok, ctx: ctx, tmp: tmp};\n    },\n\n    innerMode: function (state) {\n      return state.tmp      ? {state: state.tmp.local, mode: state.tmp.mode}\n      : state.ctx.mode ? {state: state.ctx.local, mode: state.ctx.mode}\n      : null;\n    },\n\n    token: function (stream, state) {\n      return state.tok(stream, state);\n    }\n  };\n}, 'python', 'stex');\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nCodeMirror.defineMIME('text/x-rst', 'rst');\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ruby/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Ruby mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"ruby.js\"></script>\n<style>\n      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n      .cm-s-default span.cm-arrow { color: red; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Ruby</a>\n  </ul>\n</div>\n\n<article>\n<h2>Ruby mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n# Code from http://sandbox.mc.edu/~bennet/ruby/code/poly_rb.html\n#\n# This program evaluates polynomials.  It first asks for the coefficients\n# of a polynomial, which must be entered on one line, highest-order first.\n# It then requests values of x and will compute the value of the poly for\n# each x.  It will repeatly ask for x values, unless you the user enters\n# a blank line.  It that case, it will ask for another polynomial.  If the\n# user types quit for either input, the program immediately exits.\n#\n\n#\n# Function to evaluate a polynomial at x.  The polynomial is given\n# as a list of coefficients, from the greatest to the least.\ndef polyval(x, coef)\n    sum = 0\n    coef = coef.clone           # Don't want to destroy the original\n    while true\n        sum += coef.shift       # Add and remove the next coef\n        break if coef.empty?    # If no more, done entirely.\n        sum *= x                # This happens the right number of times.\n    end\n    return sum\nend\n\n#\n# Function to read a line containing a list of integers and return\n# them as an array of integers.  If the string conversion fails, it\n# throws TypeError.  If the input line is the word 'quit', then it\n# converts it to an end-of-file exception\ndef readints(prompt)\n    # Read a line\n    print prompt\n    line = readline.chomp\n    raise EOFError.new if line == 'quit' # You can also use a real EOF.\n            \n    # Go through each item on the line, converting each one and adding it\n    # to retval.\n    retval = [ ]\n    for str in line.split(/\\s+/)\n        if str =~ /^\\-?\\d+$/\n            retval.push(str.to_i)\n        else\n            raise TypeError.new\n        end\n    end\n\n    return retval\nend\n\n#\n# Take a coeff and an exponent and return the string representation, ignoring\n# the sign of the coefficient.\ndef term_to_str(coef, exp)\n    ret = \"\"\n\n    # Show coeff, unless it's 1 or at the right\n    coef = coef.abs\n    ret = coef.to_s     unless coef == 1 && exp > 0\n    ret += \"x\" if exp > 0                               # x if exponent not 0\n    ret += \"^\" + exp.to_s if exp > 1                    # ^exponent, if > 1.\n\n    return ret\nend\n\n#\n# Create a string of the polynomial in sort-of-readable form.\ndef polystr(p)\n    # Get the exponent of first coefficient, plus 1.\n    exp = p.length\n\n    # Assign exponents to each term, making pairs of coeff and exponent,\n    # Then get rid of the zero terms.\n    p = (p.map { |c| exp -= 1; [ c, exp ] }).select { |p| p[0] != 0 }\n\n    # If there's nothing left, it's a zero\n    return \"0\" if p.empty?\n\n    # *** Now p is a non-empty list of [ coef, exponent ] pairs. ***\n\n    # Convert the first term, preceded by a \"-\" if it's negative.\n    result = (if p[0][0] < 0 then \"-\" else \"\" end) + term_to_str(*p[0])\n\n    # Convert the rest of the terms, in each case adding the appropriate\n    # + or - separating them.  \n    for term in p[1...p.length]\n        # Add the separator then the rep. of the term.\n        result += (if term[0] < 0 then \" - \" else \" + \" end) + \n                term_to_str(*term)\n    end\n\n    return result\nend\n        \n#\n# Run until some kind of endfile.\nbegin\n    # Repeat until an exception or quit gets us out.\n    while true\n        # Read a poly until it works.  An EOF will except out of the\n        # program.\n        print \"\\n\"\n        begin\n            poly = readints(\"Enter a polynomial coefficients: \")\n        rescue TypeError\n            print \"Try again.\\n\"\n            retry\n        end\n        break if poly.empty?\n\n        # Read and evaluate x values until the user types a blank line.\n        # Again, an EOF will except out of the pgm.\n        while true\n            # Request an integer.\n            print \"Enter x value or blank line: \"\n            x = readline.chomp\n            break if x == ''\n            raise EOFError.new if x == 'quit'\n\n            # If it looks bad, let's try again.\n            if x !~ /^\\-?\\d+$/\n                print \"That doesn't look like an integer.  Please try again.\\n\"\n                next\n            end\n\n            # Convert to an integer and print the result.\n            x = x.to_i\n            print \"p(x) = \", polystr(poly), \"\\n\"\n            print \"p(\", x, \") = \", polyval(x, poly), \"\\n\"\n        end\n    end\nrescue EOFError\n    print \"\\n=== EOF ===\\n\"\nrescue Interrupt, SignalException\n    print \"\\n=== Interrupted ===\\n\"\nelse\n    print \"--- Bye ---\\n\"\nend\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"text/x-ruby\",\n        matchBrackets: true,\n        indentUnit: 4\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-ruby</code>.</p>\n\n    <p>Development of the CodeMirror Ruby mode was kindly sponsored\n    by <a href=\"http://ubalo.com/\">Ubalo</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ruby/ruby.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"ruby\", function(config) {\n  function wordObj(words) {\n    var o = {};\n    for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true;\n    return o;\n  }\n  var keywords = wordObj([\n    \"alias\", \"and\", \"BEGIN\", \"begin\", \"break\", \"case\", \"class\", \"def\", \"defined?\", \"do\", \"else\",\n    \"elsif\", \"END\", \"end\", \"ensure\", \"false\", \"for\", \"if\", \"in\", \"module\", \"next\", \"not\", \"or\",\n    \"redo\", \"rescue\", \"retry\", \"return\", \"self\", \"super\", \"then\", \"true\", \"undef\", \"unless\",\n    \"until\", \"when\", \"while\", \"yield\", \"nil\", \"raise\", \"throw\", \"catch\", \"fail\", \"loop\", \"callcc\",\n    \"caller\", \"lambda\", \"proc\", \"public\", \"protected\", \"private\", \"require\", \"load\",\n    \"require_relative\", \"extend\", \"autoload\", \"__END__\", \"__FILE__\", \"__LINE__\", \"__dir__\"\n  ]);\n  var indentWords = wordObj([\"def\", \"class\", \"case\", \"for\", \"while\", \"until\", \"module\", \"then\",\n                             \"catch\", \"loop\", \"proc\", \"begin\"]);\n  var dedentWords = wordObj([\"end\", \"until\"]);\n  var matching = {\"[\": \"]\", \"{\": \"}\", \"(\": \")\"};\n  var curPunc;\n\n  function chain(newtok, stream, state) {\n    state.tokenize.push(newtok);\n    return newtok(stream, state);\n  }\n\n  function tokenBase(stream, state) {\n    if (stream.sol() && stream.match(\"=begin\") && stream.eol()) {\n      state.tokenize.push(readBlockComment);\n      return \"comment\";\n    }\n    if (stream.eatSpace()) return null;\n    var ch = stream.next(), m;\n    if (ch == \"`\" || ch == \"'\" || ch == '\"') {\n      return chain(readQuoted(ch, \"string\", ch == '\"' || ch == \"`\"), stream, state);\n    } else if (ch == \"/\") {\n      if (regexpAhead(stream))\n        return chain(readQuoted(ch, \"string-2\", true), stream, state);\n      else\n        return \"operator\";\n    } else if (ch == \"%\") {\n      var style = \"string\", embed = true;\n      if (stream.eat(\"s\")) style = \"atom\";\n      else if (stream.eat(/[WQ]/)) style = \"string\";\n      else if (stream.eat(/[r]/)) style = \"string-2\";\n      else if (stream.eat(/[wxq]/)) { style = \"string\"; embed = false; }\n      var delim = stream.eat(/[^\\w\\s=]/);\n      if (!delim) return \"operator\";\n      if (matching.propertyIsEnumerable(delim)) delim = matching[delim];\n      return chain(readQuoted(delim, style, embed, true), stream, state);\n    } else if (ch == \"#\") {\n      stream.skipToEnd();\n      return \"comment\";\n    } else if (ch == \"<\" && (m = stream.match(/^<(-)?[\\`\\\"\\']?([a-zA-Z_?]\\w*)[\\`\\\"\\']?(?:;|$)/))) {\n      return chain(readHereDoc(m[2], m[1]), stream, state);\n    } else if (ch == \"0\") {\n      if (stream.eat(\"x\")) stream.eatWhile(/[\\da-fA-F]/);\n      else if (stream.eat(\"b\")) stream.eatWhile(/[01]/);\n      else stream.eatWhile(/[0-7]/);\n      return \"number\";\n    } else if (/\\d/.test(ch)) {\n      stream.match(/^[\\d_]*(?:\\.[\\d_]+)?(?:[eE][+\\-]?[\\d_]+)?/);\n      return \"number\";\n    } else if (ch == \"?\") {\n      while (stream.match(/^\\\\[CM]-/)) {}\n      if (stream.eat(\"\\\\\")) stream.eatWhile(/\\w/);\n      else stream.next();\n      return \"string\";\n    } else if (ch == \":\") {\n      if (stream.eat(\"'\")) return chain(readQuoted(\"'\", \"atom\", false), stream, state);\n      if (stream.eat('\"')) return chain(readQuoted('\"', \"atom\", true), stream, state);\n\n      // :> :>> :< :<< are valid symbols\n      if (stream.eat(/[\\<\\>]/)) {\n        stream.eat(/[\\<\\>]/);\n        return \"atom\";\n      }\n\n      // :+ :- :/ :* :| :& :! are valid symbols\n      if (stream.eat(/[\\+\\-\\*\\/\\&\\|\\:\\!]/)) {\n        return \"atom\";\n      }\n\n      // Symbols can't start by a digit\n      if (stream.eat(/[a-zA-Z$@_\\xa1-\\uffff]/)) {\n        stream.eatWhile(/[\\w$\\xa1-\\uffff]/);\n        // Only one ? ! = is allowed and only as the last character\n        stream.eat(/[\\?\\!\\=]/);\n        return \"atom\";\n      }\n      return \"operator\";\n    } else if (ch == \"@\" && stream.match(/^@?[a-zA-Z_\\xa1-\\uffff]/)) {\n      stream.eat(\"@\");\n      stream.eatWhile(/[\\w\\xa1-\\uffff]/);\n      return \"variable-2\";\n    } else if (ch == \"$\") {\n      if (stream.eat(/[a-zA-Z_]/)) {\n        stream.eatWhile(/[\\w]/);\n      } else if (stream.eat(/\\d/)) {\n        stream.eat(/\\d/);\n      } else {\n        stream.next(); // Must be a special global like $: or $!\n      }\n      return \"variable-3\";\n    } else if (/[a-zA-Z_\\xa1-\\uffff]/.test(ch)) {\n      stream.eatWhile(/[\\w\\xa1-\\uffff]/);\n      stream.eat(/[\\?\\!]/);\n      if (stream.eat(\":\")) return \"atom\";\n      return \"ident\";\n    } else if (ch == \"|\" && (state.varList || state.lastTok == \"{\" || state.lastTok == \"do\")) {\n      curPunc = \"|\";\n      return null;\n    } else if (/[\\(\\)\\[\\]{}\\\\;]/.test(ch)) {\n      curPunc = ch;\n      return null;\n    } else if (ch == \"-\" && stream.eat(\">\")) {\n      return \"arrow\";\n    } else if (/[=+\\-\\/*:\\.^%<>~|]/.test(ch)) {\n      var more = stream.eatWhile(/[=+\\-\\/*:\\.^%<>~|]/);\n      if (ch == \".\" && !more) curPunc = \".\";\n      return \"operator\";\n    } else {\n      return null;\n    }\n  }\n\n  function regexpAhead(stream) {\n    var start = stream.pos, depth = 0, next, found = false, escaped = false\n    while ((next = stream.next()) != null) {\n      if (!escaped) {\n        if (\"[{(\".indexOf(next) > -1) {\n          depth++\n        } else if (\"]})\".indexOf(next) > -1) {\n          depth--\n          if (depth < 0) break\n        } else if (next == \"/\" && depth == 0) {\n          found = true\n          break\n        }\n        escaped = next == \"\\\\\"\n      } else {\n        escaped = false\n      }\n    }\n    stream.backUp(stream.pos - start)\n    return found\n  }\n\n  function tokenBaseUntilBrace(depth) {\n    if (!depth) depth = 1;\n    return function(stream, state) {\n      if (stream.peek() == \"}\") {\n        if (depth == 1) {\n          state.tokenize.pop();\n          return state.tokenize[state.tokenize.length-1](stream, state);\n        } else {\n          state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth - 1);\n        }\n      } else if (stream.peek() == \"{\") {\n        state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth + 1);\n      }\n      return tokenBase(stream, state);\n    };\n  }\n  function tokenBaseOnce() {\n    var alreadyCalled = false;\n    return function(stream, state) {\n      if (alreadyCalled) {\n        state.tokenize.pop();\n        return state.tokenize[state.tokenize.length-1](stream, state);\n      }\n      alreadyCalled = true;\n      return tokenBase(stream, state);\n    };\n  }\n  function readQuoted(quote, style, embed, unescaped) {\n    return function(stream, state) {\n      var escaped = false, ch;\n\n      if (state.context.type === 'read-quoted-paused') {\n        state.context = state.context.prev;\n        stream.eat(\"}\");\n      }\n\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && (unescaped || !escaped)) {\n          state.tokenize.pop();\n          break;\n        }\n        if (embed && ch == \"#\" && !escaped) {\n          if (stream.eat(\"{\")) {\n            if (quote == \"}\") {\n              state.context = {prev: state.context, type: 'read-quoted-paused'};\n            }\n            state.tokenize.push(tokenBaseUntilBrace());\n            break;\n          } else if (/[@\\$]/.test(stream.peek())) {\n            state.tokenize.push(tokenBaseOnce());\n            break;\n          }\n        }\n        escaped = !escaped && ch == \"\\\\\";\n      }\n      return style;\n    };\n  }\n  function readHereDoc(phrase, mayIndent) {\n    return function(stream, state) {\n      if (mayIndent) stream.eatSpace()\n      if (stream.match(phrase)) state.tokenize.pop();\n      else stream.skipToEnd();\n      return \"string\";\n    };\n  }\n  function readBlockComment(stream, state) {\n    if (stream.sol() && stream.match(\"=end\") && stream.eol())\n      state.tokenize.pop();\n    stream.skipToEnd();\n    return \"comment\";\n  }\n\n  return {\n    startState: function() {\n      return {tokenize: [tokenBase],\n              indented: 0,\n              context: {type: \"top\", indented: -config.indentUnit},\n              continuedLine: false,\n              lastTok: null,\n              varList: false};\n    },\n\n    token: function(stream, state) {\n      curPunc = null;\n      if (stream.sol()) state.indented = stream.indentation();\n      var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype;\n      var thisTok = curPunc;\n      if (style == \"ident\") {\n        var word = stream.current();\n        style = state.lastTok == \".\" ? \"property\"\n          : keywords.propertyIsEnumerable(stream.current()) ? \"keyword\"\n          : /^[A-Z]/.test(word) ? \"tag\"\n          : (state.lastTok == \"def\" || state.lastTok == \"class\" || state.varList) ? \"def\"\n          : \"variable\";\n        if (style == \"keyword\") {\n          thisTok = word;\n          if (indentWords.propertyIsEnumerable(word)) kwtype = \"indent\";\n          else if (dedentWords.propertyIsEnumerable(word)) kwtype = \"dedent\";\n          else if ((word == \"if\" || word == \"unless\") && stream.column() == stream.indentation())\n            kwtype = \"indent\";\n          else if (word == \"do\" && state.context.indented < state.indented)\n            kwtype = \"indent\";\n        }\n      }\n      if (curPunc || (style && style != \"comment\")) state.lastTok = thisTok;\n      if (curPunc == \"|\") state.varList = !state.varList;\n\n      if (kwtype == \"indent\" || /[\\(\\[\\{]/.test(curPunc))\n        state.context = {prev: state.context, type: curPunc || style, indented: state.indented};\n      else if ((kwtype == \"dedent\" || /[\\)\\]\\}]/.test(curPunc)) && state.context.prev)\n        state.context = state.context.prev;\n\n      if (stream.eol())\n        state.continuedLine = (curPunc == \"\\\\\" || style == \"operator\");\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize[state.tokenize.length-1] != tokenBase) return CodeMirror.Pass;\n      var firstChar = textAfter && textAfter.charAt(0);\n      var ct = state.context;\n      var closing = ct.type == matching[firstChar] ||\n        ct.type == \"keyword\" && /^(?:end|until|else|elsif|when|rescue)\\b/.test(textAfter);\n      return ct.indented + (closing ? 0 : config.indentUnit) +\n        (state.continuedLine ? config.indentUnit : 0);\n    },\n\n    electricInput: /^\\s*(?:end|rescue|elsif|else|\\})$/,\n    lineComment: \"#\",\n    fold: \"indent\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-ruby\", \"ruby\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ruby/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"ruby\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"divide_equal_operator\",\n     \"[variable bar] [operator /=] [variable foo]\");\n\n  MT(\"divide_equal_operator_no_spacing\",\n     \"[variable foo][operator /=][number 42]\");\n\n  MT(\"complex_regexp\",\n     \"[keyword if] [variable cr] [operator =~] [string-2 /(?: \\\\( #{][tag RE_NOT][string-2 }\\\\( | #{][tag RE_NOT_PAR_OR][string-2 }* #{][tag RE_OPA_OR][string-2 } )/][variable x]\")\n\n  MT(\"indented_heredoc\",\n     \"[keyword def] [def x]\",\n     \"  [variable y] [operator =] [string <<-FOO]\",\n     \"[string     bar]\",\n     \"[string   FOO]\",\n     \"[keyword end]\")\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/rust/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Rust mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/simple.js\"></script>\n<script src=\"rust.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Rust</a>\n  </ul>\n</div>\n\n<article>\n<h2>Rust mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n// Demo code.\n\ntype foo<T> = int;\nenum bar {\n    some(int, foo<float>),\n    none\n}\n\nfn check_crate(x: int) {\n    let v = 10;\n    match foo {\n        1 ... 3 {\n            print_foo();\n            if x {\n                blah().to_string();\n            }\n        }\n        (x, y) { \"bye\" }\n        _ { \"hi\" }\n    }\n}\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        lineWrapping: true,\n        indentUnit: 4,\n        mode: \"rust\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-rustsrc</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/rust/rust.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../../addon/mode/simple\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../../addon/mode/simple\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineSimpleMode(\"rust\",{\n  start: [\n    // string and byte string\n    {regex: /b?\"/, token: \"string\", next: \"string\"},\n    // raw string and raw byte string\n    {regex: /b?r\"/, token: \"string\", next: \"string_raw\"},\n    {regex: /b?r#+\"/, token: \"string\", next: \"string_raw_hash\"},\n    // character\n    {regex: /'(?:[^'\\\\]|\\\\(?:[nrt0'\"]|x[\\da-fA-F]{2}|u\\{[\\da-fA-F]{6}\\}))'/, token: \"string-2\"},\n    // byte\n    {regex: /b'(?:[^']|\\\\(?:['\\\\nrt0]|x[\\da-fA-F]{2}))'/, token: \"string-2\"},\n\n    {regex: /(?:(?:[0-9][0-9_]*)(?:(?:[Ee][+-]?[0-9_]+)|\\.[0-9_]+(?:[Ee][+-]?[0-9_]+)?)(?:f32|f64)?)|(?:0(?:b[01_]+|(?:o[0-7_]+)|(?:x[0-9a-fA-F_]+))|(?:[0-9][0-9_]*))(?:u8|u16|u32|u64|i8|i16|i32|i64|isize|usize)?/,\n     token: \"number\"},\n    {regex: /(let(?:\\s+mut)?|fn|enum|mod|struct|type)(\\s+)([a-zA-Z_][a-zA-Z0-9_]*)/, token: [\"keyword\", null, \"def\"]},\n    {regex: /(?:abstract|alignof|as|box|break|continue|const|crate|do|else|enum|extern|fn|for|final|if|impl|in|loop|macro|match|mod|move|offsetof|override|priv|proc|pub|pure|ref|return|self|sizeof|static|struct|super|trait|type|typeof|unsafe|unsized|use|virtual|where|while|yield)\\b/, token: \"keyword\"},\n    {regex: /\\b(?:Self|isize|usize|char|bool|u8|u16|u32|u64|f16|f32|f64|i8|i16|i32|i64|str|Option)\\b/, token: \"atom\"},\n    {regex: /\\b(?:true|false|Some|None|Ok|Err)\\b/, token: \"builtin\"},\n    {regex: /\\b(fn)(\\s+)([a-zA-Z_][a-zA-Z0-9_]*)/,\n     token: [\"keyword\", null ,\"def\"]},\n    {regex: /#!?\\[.*\\]/, token: \"meta\"},\n    {regex: /\\/\\/.*/, token: \"comment\"},\n    {regex: /\\/\\*/, token: \"comment\", next: \"comment\"},\n    {regex: /[-+\\/*=<>!]+/, token: \"operator\"},\n    {regex: /[a-zA-Z_]\\w*!/,token: \"variable-3\"},\n    {regex: /[a-zA-Z_]\\w*/, token: \"variable\"},\n    {regex: /[\\{\\[\\(]/, indent: true},\n    {regex: /[\\}\\]\\)]/, dedent: true}\n  ],\n  string: [\n    {regex: /\"/, token: \"string\", next: \"start\"},\n    {regex: /(?:[^\\\\\"]|\\\\(?:.|$))*/, token: \"string\"}\n  ],\n  string_raw: [\n    {regex: /\"/, token: \"string\", next: \"start\"},\n    {regex: /[^\"]*/, token: \"string\"}\n  ],\n  string_raw_hash: [\n    {regex: /\"#+/, token: \"string\", next: \"start\"},\n    {regex: /(?:[^\"]|\"(?!#))*/, token: \"string\"}\n  ],\n  comment: [\n    {regex: /.*?\\*\\//, token: \"comment\", next: \"start\"},\n    {regex: /.*/, token: \"comment\"}\n  ],\n  meta: {\n    dontIndentStates: [\"comment\"],\n    electricInput: /^\\s*\\}$/,\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    lineComment: \"//\",\n    fold: \"brace\"\n  }\n});\n\n\nCodeMirror.defineMIME(\"text/x-rustsrc\", \"rust\");\nCodeMirror.defineMIME(\"text/rust\", \"rust\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/rust/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 4}, \"rust\");\n  function MT(name) {test.mode(name, mode, Array.prototype.slice.call(arguments, 1));}\n\n  MT('integer_test',\n     '[number 123i32]',\n     '[number 123u32]',\n     '[number 123_u32]',\n     '[number 0xff_u8]',\n     '[number 0o70_i16]',\n     '[number 0b1111_1111_1001_0000_i32]',\n     '[number 0usize]');\n\n  MT('float_test',\n     '[number 123.0f64]',\n     '[number 0.1f64]',\n     '[number 0.1f32]',\n     '[number 12E+99_f64]');\n\n  MT('string-literals-test',\n     '[string \"foo\"]',\n     '[string r\"foo\"]',\n     '[string \"\\\\\"foo\\\\\"\"]',\n     '[string r#\"\"foo\"\"#]',\n     '[string \"foo #\\\\\"# bar\"]',\n\n     '[string b\"foo\"]',\n     '[string br\"foo\"]',\n     '[string b\"\\\\\"foo\\\\\"\"]',\n     '[string br#\"\"foo\"\"#]',\n     '[string br##\"foo #\" bar\"##]',\n\n     \"[string-2 'h']\",\n     \"[string-2 b'h']\");\n\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sas/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: SAS mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"sas.js\"></script>\n<style>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n  .cm-s-default .cm-trailing-space-a:before,\n  .cm-s-default .cm-trailing-space-b:before {position: absolute; content: \"\\00B7\"; color: #777;}\n  .cm-s-default .cm-trailing-space-new-line:before {position: absolute; content: \"\\21B5\"; color: #777;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">SAS</a>\n  </ul>\n</div>\n\n<article>\n<h2>SAS mode</h2>\n<form><textarea id=\"code\" name=\"code\">\nlibname foo \"/tmp/foobar\";\n%let count=1;\n\n/* Multi line\nComment\n*/\ndata _null_;\n    x=ranuni();\n    * single comment;\n    x2=x**2;\n    sx=sqrt(x);\n    if x=x2 then put \"x must be 1\";\n    else do;\n        put x=;\n    end;\nrun;\n\n/* embedded comment\n* comment;\n*/\n\nproc glm data=sashelp.class;\n    class sex;\n    model weight = height sex;\nrun;\n\nproc sql;\n    select count(*)\n    from sashelp.class;\n\n    create table foo as\n    select * from sashelp.class;\n\n    select *\n    from foo;\nquit;\n</textarea></form>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    mode: 'sas',\n    lineNumbers: true\n  });\n</script>\n\n<p><strong>MIME types defined:</strong> <code>text/x-sas</code>.</p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sas/sas.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n\n// SAS mode copyright (c) 2016 Jared Dean, SAS Institute\n// Created by Jared Dean\n\n// TODO\n// indent and de-indent\n// identify macro variables\n\n\n//Definitions\n//  comment -- text within * ; or /* */\n//  keyword -- SAS language variable\n//  variable -- macro variables starts with '&' or variable formats\n//  variable-2 -- DATA Step, proc, or macro names\n//  string -- text within ' ' or \" \"\n//  operator -- numeric operator + / - * ** le eq ge ... and so on\n//  builtin -- proc %macro data run mend\n//  atom\n//  def\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"sas\", function () {\n    var words = {};\n    var isDoubleOperatorSym = {\n      eq: 'operator',\n      lt: 'operator',\n      le: 'operator',\n      gt: 'operator',\n      ge: 'operator',\n      \"in\": 'operator',\n      ne: 'operator',\n      or: 'operator'\n    };\n    var isDoubleOperatorChar = /(<=|>=|!=|<>)/;\n    var isSingleOperatorChar = /[=\\(:\\),{}.*<>+\\-\\/^\\[\\]]/;\n\n    // Takes a string of words separated by spaces and adds them as\n    // keys with the value of the first argument 'style'\n    function define(style, string, context) {\n      if (context) {\n        var split = string.split(' ');\n        for (var i = 0; i < split.length; i++) {\n          words[split[i]] = {style: style, state: context};\n        }\n      }\n    }\n    //datastep\n    define('def', 'stack pgm view source debug nesting nolist', ['inDataStep']);\n    define('def', 'if while until for do do; end end; then else cancel', ['inDataStep']);\n    define('def', 'label format _n_ _error_', ['inDataStep']);\n    define('def', 'ALTER BUFNO BUFSIZE CNTLLEV COMPRESS DLDMGACTION ENCRYPT ENCRYPTKEY EXTENDOBSCOUNTER GENMAX GENNUM INDEX LABEL OBSBUF OUTREP PW PWREQ READ REPEMPTY REPLACE REUSE ROLE SORTEDBY SPILL TOBSNO TYPE WRITE FILECLOSE FIRSTOBS IN OBS POINTOBS WHERE WHEREUP IDXNAME IDXWHERE DROP KEEP RENAME', ['inDataStep']);\n    define('def', 'filevar finfo finv fipname fipnamel fipstate first firstobs floor', ['inDataStep']);\n    define('def', 'varfmt varinfmt varlabel varlen varname varnum varray varrayx vartype verify vformat vformatd vformatdx vformatn vformatnx vformatw vformatwx vformatx vinarray vinarrayx vinformat vinformatd vinformatdx vinformatn vinformatnx vinformatw vinformatwx vinformatx vlabel vlabelx vlength vlengthx vname vnamex vnferr vtype vtypex weekday', ['inDataStep']);\n    define('def', 'zipfips zipname zipnamel zipstate', ['inDataStep']);\n    define('def', 'put putc putn', ['inDataStep']);\n    define('builtin', 'data run', ['inDataStep']);\n\n\n    //proc\n    define('def', 'data', ['inProc']);\n\n    // flow control for macros\n    define('def', '%if %end %end; %else %else; %do %do; %then', ['inMacro']);\n\n    //everywhere\n    define('builtin', 'proc run; quit; libname filename %macro %mend option options', ['ALL']);\n\n    define('def', 'footnote title libname ods', ['ALL']);\n    define('def', '%let %put %global %sysfunc %eval ', ['ALL']);\n    // automatic macro variables http://support.sas.com/documentation/cdl/en/mcrolref/61885/HTML/default/viewer.htm#a003167023.htm\n    define('variable', '&sysbuffr &syscc &syscharwidth &syscmd &sysdate &sysdate9 &sysday &sysdevic &sysdmg &sysdsn &sysencoding &sysenv &syserr &syserrortext &sysfilrc &syshostname &sysindex &sysinfo &sysjobid &syslast &syslckrc &syslibrc &syslogapplname &sysmacroname &sysmenv &sysmsg &sysncpu &sysodspath &sysparm &syspbuff &sysprocessid &sysprocessname &sysprocname &sysrc &sysscp &sysscpl &sysscpl &syssite &sysstartid &sysstartname &systcpiphostname &systime &sysuserid &sysver &sysvlong &sysvlong4 &syswarningtext', ['ALL']);\n\n    //footnote[1-9]? title[1-9]?\n\n    //options statement\n    define('def', 'source2 nosource2 page pageno pagesize', ['ALL']);\n\n    //proc and datastep\n    define('def', '_all_ _character_ _cmd_ _freq_ _i_ _infile_ _last_ _msg_ _null_ _numeric_ _temporary_ _type_ abort abs addr adjrsq airy alpha alter altlog altprint and arcos array arsin as atan attrc attrib attrn authserver autoexec awscontrol awsdef awsmenu awsmenumerge awstitle backward band base betainv between blocksize blshift bnot bor brshift bufno bufsize bxor by byerr byline byte calculated call cards cards4 catcache cbufno cdf ceil center cexist change chisq cinv class cleanup close cnonct cntllev coalesce codegen col collate collin column comamid comaux1 comaux2 comdef compbl compound compress config continue convert cos cosh cpuid create cross crosstab css curobs cv daccdb daccdbsl daccsl daccsyd dacctab dairy datalines datalines4 datejul datepart datetime day dbcslang dbcstype dclose ddm delete delimiter depdb depdbsl depsl depsyd deptab dequote descending descript design= device dflang dhms dif digamma dim dinfo display distinct dkricond dkrocond dlm dnum do dopen doptname doptnum dread drop dropnote dsname dsnferr echo else emaildlg emailid emailpw emailserver emailsys encrypt end endsas engine eof eov erf erfc error errorcheck errors exist exp fappend fclose fcol fdelete feedback fetch fetchobs fexist fget file fileclose fileexist filefmt filename fileref  fmterr fmtsearch fnonct fnote font fontalias  fopen foptname foptnum force formatted formchar formdelim formdlim forward fpoint fpos fput fread frewind frlen from fsep fuzz fwrite gaminv gamma getoption getvarc getvarn go goto group gwindow hbar hbound helpenv helploc hms honorappearance hosthelp hostprint hour hpct html hvar ibessel ibr id if index indexc indexw initcmd initstmt inner input inputc inputn inr insert int intck intnx into intrr invaliddata irr is jbessel join juldate keep kentb kurtosis label lag last lbound leave left length levels lgamma lib  library libref line linesize link list log log10 log2 logpdf logpmf logsdf lostcard lowcase lrecl ls macro macrogen maps mautosource max maxdec maxr mdy mean measures median memtype merge merror min minute missing missover mlogic mod mode model modify month mopen mort mprint mrecall msglevel msymtabmax mvarsize myy n nest netpv new news nmiss no nobatch nobs nocaps nocardimage nocenter nocharcode nocmdmac nocol nocum nodate nodbcs nodetails nodmr nodms nodmsbatch nodup nodupkey noduplicates noechoauto noequals noerrorabend noexitwindows nofullstimer noicon noimplmac noint nolist noloadlist nomiss nomlogic nomprint nomrecall nomsgcase nomstored nomultenvappl nonotes nonumber noobs noovp nopad nopercent noprint noprintinit normal norow norsasuser nosetinit  nosplash nosymbolgen note notes notitle notitles notsorted noverbose noxsync noxwait npv null number numkeys nummousekeys nway obs  on open     order ordinal otherwise out outer outp= output over ovp p(1 5 10 25 50 75 90 95 99) pad pad2  paired parm parmcards path pathdll pathname pdf peek peekc pfkey pmf point poisson poke position printer probbeta probbnml probchi probf probgam probhypr probit probnegb probnorm probsig probt procleave prt ps  pw pwreq qtr quote r ranbin rancau ranexp rangam range ranks rannor ranpoi rantbl rantri ranuni read recfm register regr remote remove rename repeat replace resolve retain return reuse reverse rewind right round rsquare rtf rtrace rtraceloc s s2 samploc sasautos sascontrol sasfrscr sasmsg sasmstore sasscript sasuser saving scan sdf second select selection separated seq serror set setcomm setot sign simple sin sinh siteinfo skewness skip sle sls sortedby sortpgm sortseq sortsize soundex  spedis splashlocation split spool sqrt start std stderr stdin stfips stimer stname stnamel stop stopover subgroup subpopn substr sum sumwgt symbol symbolgen symget symput sysget sysin sysleave sysmsg sysparm sysprint sysprintfont sysprod sysrc system t table tables tan tanh tapeclose tbufsize terminal test then timepart tinv  tnonct to today tol tooldef totper transformout translate trantab tranwrd trigamma trim trimn trunc truncover type unformatted uniform union until upcase update user usericon uss validate value var  weight when where while wincharset window work workinit workterm write wsum xsync xwait yearcutoff yes yyq  min max', ['inDataStep', 'inProc']);\n    define('operator', 'and not ', ['inDataStep', 'inProc']);\n\n    // Main function\n    function tokenize(stream, state) {\n      // Finally advance the stream\n      var ch = stream.next();\n\n      // BLOCKCOMMENT\n      if (ch === '/' && stream.eat('*')) {\n        state.continueComment = true;\n        return \"comment\";\n      } else if (state.continueComment === true) { // in comment block\n        //comment ends at the beginning of the line\n        if (ch === '*' && stream.peek() === '/') {\n          stream.next();\n          state.continueComment = false;\n        } else if (stream.skipTo('*')) { //comment is potentially later in line\n          stream.skipTo('*');\n          stream.next();\n          if (stream.eat('/'))\n            state.continueComment = false;\n        } else {\n          stream.skipToEnd();\n        }\n        return \"comment\";\n      }\n\n      if (ch == \"*\" && stream.column() == stream.indentation()) {\n        stream.skipToEnd()\n        return \"comment\"\n      }\n\n      // DoubleOperator match\n      var doubleOperator = ch + stream.peek();\n\n      if ((ch === '\"' || ch === \"'\") && !state.continueString) {\n        state.continueString = ch\n        return \"string\"\n      } else if (state.continueString) {\n        if (state.continueString == ch) {\n          state.continueString = null;\n        } else if (stream.skipTo(state.continueString)) {\n          // quote found on this line\n          stream.next();\n          state.continueString = null;\n        } else {\n          stream.skipToEnd();\n        }\n        return \"string\";\n      } else if (state.continueString !== null && stream.eol()) {\n        stream.skipTo(state.continueString) || stream.skipToEnd();\n        return \"string\";\n      } else if (/[\\d\\.]/.test(ch)) { //find numbers\n        if (ch === \".\")\n          stream.match(/^[0-9]+([eE][\\-+]?[0-9]+)?/);\n        else if (ch === \"0\")\n          stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);\n        else\n          stream.match(/^[0-9]*\\.?[0-9]*([eE][\\-+]?[0-9]+)?/);\n        return \"number\";\n      } else if (isDoubleOperatorChar.test(ch + stream.peek())) { // TWO SYMBOL TOKENS\n        stream.next();\n        return \"operator\";\n      } else if (isDoubleOperatorSym.hasOwnProperty(doubleOperator)) {\n        stream.next();\n        if (stream.peek() === ' ')\n          return isDoubleOperatorSym[doubleOperator.toLowerCase()];\n      } else if (isSingleOperatorChar.test(ch)) { // SINGLE SYMBOL TOKENS\n        return \"operator\";\n      }\n\n      // Matches one whole word -- even if the word is a character\n      var word;\n      if (stream.match(/[%&;\\w]+/, false) != null) {\n        word = ch + stream.match(/[%&;\\w]+/, true);\n        if (/&/.test(word)) return 'variable'\n      } else {\n        word = ch;\n      }\n      // the word after DATA PROC or MACRO\n      if (state.nextword) {\n        stream.match(/[\\w]+/);\n        // match memname.libname\n        if (stream.peek() === '.') stream.skipTo(' ');\n        state.nextword = false;\n        return 'variable-2';\n      }\n\n      word = word.toLowerCase()\n      // Are we in a DATA Step?\n      if (state.inDataStep) {\n        if (word === 'run;' || stream.match(/run\\s;/)) {\n          state.inDataStep = false;\n          return 'builtin';\n        }\n        // variable formats\n        if ((word) && stream.next() === '.') {\n          //either a format or libname.memname\n          if (/\\w/.test(stream.peek())) return 'variable-2';\n          else return 'variable';\n        }\n        // do we have a DATA Step keyword\n        if (word && words.hasOwnProperty(word) &&\n            (words[word].state.indexOf(\"inDataStep\") !== -1 ||\n             words[word].state.indexOf(\"ALL\") !== -1)) {\n          //backup to the start of the word\n          if (stream.start < stream.pos)\n            stream.backUp(stream.pos - stream.start);\n          //advance the length of the word and return\n          for (var i = 0; i < word.length; ++i) stream.next();\n          return words[word].style;\n        }\n      }\n      // Are we in an Proc statement?\n      if (state.inProc) {\n        if (word === 'run;' || word === 'quit;') {\n          state.inProc = false;\n          return 'builtin';\n        }\n        // do we have a proc keyword\n        if (word && words.hasOwnProperty(word) &&\n            (words[word].state.indexOf(\"inProc\") !== -1 ||\n             words[word].state.indexOf(\"ALL\") !== -1)) {\n          stream.match(/[\\w]+/);\n          return words[word].style;\n        }\n      }\n      // Are we in a Macro statement?\n      if (state.inMacro) {\n        if (word === '%mend') {\n          if (stream.peek() === ';') stream.next();\n          state.inMacro = false;\n          return 'builtin';\n        }\n        if (word && words.hasOwnProperty(word) &&\n            (words[word].state.indexOf(\"inMacro\") !== -1 ||\n             words[word].state.indexOf(\"ALL\") !== -1)) {\n          stream.match(/[\\w]+/);\n          return words[word].style;\n        }\n\n        return 'atom';\n      }\n      // Do we have Keywords specific words?\n      if (word && words.hasOwnProperty(word)) {\n        // Negates the initial next()\n        stream.backUp(1);\n        // Actually move the stream\n        stream.match(/[\\w]+/);\n        if (word === 'data' && /=/.test(stream.peek()) === false) {\n          state.inDataStep = true;\n          state.nextword = true;\n          return 'builtin';\n        }\n        if (word === 'proc') {\n          state.inProc = true;\n          state.nextword = true;\n          return 'builtin';\n        }\n        if (word === '%macro') {\n          state.inMacro = true;\n          state.nextword = true;\n          return 'builtin';\n        }\n        if (/title[1-9]/.test(word)) return 'def';\n\n        if (word === 'footnote') {\n          stream.eat(/[1-9]/);\n          return 'def';\n        }\n\n        // Returns their value as state in the prior define methods\n        if (state.inDataStep === true && words[word].state.indexOf(\"inDataStep\") !== -1)\n          return words[word].style;\n        if (state.inProc === true && words[word].state.indexOf(\"inProc\") !== -1)\n          return words[word].style;\n        if (state.inMacro === true && words[word].state.indexOf(\"inMacro\") !== -1)\n          return words[word].style;\n        if (words[word].state.indexOf(\"ALL\") !== -1)\n          return words[word].style;\n        return null;\n      }\n      // Unrecognized syntax\n      return null;\n    }\n\n    return {\n      startState: function () {\n        return {\n          inDataStep: false,\n          inProc: false,\n          inMacro: false,\n          nextword: false,\n          continueString: null,\n          continueComment: false\n        };\n      },\n      token: function (stream, state) {\n        // Strip the spaces, but regex will account for them either way\n        if (stream.eatSpace()) return null;\n        // Go through the main process\n        return tokenize(stream, state);\n      },\n\n      blockCommentStart: \"/*\",\n      blockCommentEnd: \"*/\"\n    };\n\n  });\n\n  CodeMirror.defineMIME(\"text/x-sas\", \"sas\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sass/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Sass mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"../css/css.js\"></script>\n<script src=\"sass.js\"></script>\n<style>.CodeMirror {border: 1px solid #ddd; font-size:12px; height: 400px}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Sass</a>\n  </ul>\n</div>\n\n<article>\n<h2>Sass mode</h2>\n<form><textarea id=\"code\" name=\"code\">// Variable Definitions\n\n$page-width:    800px\n$sidebar-width: 200px\n$primary-color: #eeeeee\n\n// Global Attributes\n\nbody\n  font:\n    family: sans-serif\n    size: 30em\n    weight: bold\n\n// Scoped Styles\n\n#contents\n  width: $page-width\n  #sidebar\n    float: right\n    width: $sidebar-width\n  #main\n    width: $page-width - $sidebar-width\n    background: $primary-color\n    h2\n      color: blue\n\n#footer\n  height: 200px\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers : true,\n        matchBrackets : true,\n        mode: \"sass\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-sass</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sass/sass.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../css/css\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../css/css\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"sass\", function(config) {\n  var cssMode = CodeMirror.mimeModes[\"text/css\"];\n  var propertyKeywords = cssMode.propertyKeywords || {},\n      colorKeywords = cssMode.colorKeywords || {},\n      valueKeywords = cssMode.valueKeywords || {},\n      fontProperties = cssMode.fontProperties || {};\n\n  function tokenRegexp(words) {\n    return new RegExp(\"^\" + words.join(\"|\"));\n  }\n\n  var keywords = [\"true\", \"false\", \"null\", \"auto\"];\n  var keywordsRegexp = new RegExp(\"^\" + keywords.join(\"|\"));\n\n  var operators = [\"\\\\(\", \"\\\\)\", \"=\", \">\", \"<\", \"==\", \">=\", \"<=\", \"\\\\+\", \"-\",\n                   \"\\\\!=\", \"/\", \"\\\\*\", \"%\", \"and\", \"or\", \"not\", \";\",\"\\\\{\",\"\\\\}\",\":\"];\n  var opRegexp = tokenRegexp(operators);\n\n  var pseudoElementsRegexp = /^::?[a-zA-Z_][\\w\\-]*/;\n\n  var word;\n\n  function isEndLine(stream) {\n    return !stream.peek() || stream.match(/\\s+$/, false);\n  }\n\n  function urlTokens(stream, state) {\n    var ch = stream.peek();\n\n    if (ch === \")\") {\n      stream.next();\n      state.tokenizer = tokenBase;\n      return \"operator\";\n    } else if (ch === \"(\") {\n      stream.next();\n      stream.eatSpace();\n\n      return \"operator\";\n    } else if (ch === \"'\" || ch === '\"') {\n      state.tokenizer = buildStringTokenizer(stream.next());\n      return \"string\";\n    } else {\n      state.tokenizer = buildStringTokenizer(\")\", false);\n      return \"string\";\n    }\n  }\n  function comment(indentation, multiLine) {\n    return function(stream, state) {\n      if (stream.sol() && stream.indentation() <= indentation) {\n        state.tokenizer = tokenBase;\n        return tokenBase(stream, state);\n      }\n\n      if (multiLine && stream.skipTo(\"*/\")) {\n        stream.next();\n        stream.next();\n        state.tokenizer = tokenBase;\n      } else {\n        stream.skipToEnd();\n      }\n\n      return \"comment\";\n    };\n  }\n\n  function buildStringTokenizer(quote, greedy) {\n    if (greedy == null) { greedy = true; }\n\n    function stringTokenizer(stream, state) {\n      var nextChar = stream.next();\n      var peekChar = stream.peek();\n      var previousChar = stream.string.charAt(stream.pos-2);\n\n      var endingString = ((nextChar !== \"\\\\\" && peekChar === quote) || (nextChar === quote && previousChar !== \"\\\\\"));\n\n      if (endingString) {\n        if (nextChar !== quote && greedy) { stream.next(); }\n        if (isEndLine(stream)) {\n          state.cursorHalf = 0;\n        }\n        state.tokenizer = tokenBase;\n        return \"string\";\n      } else if (nextChar === \"#\" && peekChar === \"{\") {\n        state.tokenizer = buildInterpolationTokenizer(stringTokenizer);\n        stream.next();\n        return \"operator\";\n      } else {\n        return \"string\";\n      }\n    }\n\n    return stringTokenizer;\n  }\n\n  function buildInterpolationTokenizer(currentTokenizer) {\n    return function(stream, state) {\n      if (stream.peek() === \"}\") {\n        stream.next();\n        state.tokenizer = currentTokenizer;\n        return \"operator\";\n      } else {\n        return tokenBase(stream, state);\n      }\n    };\n  }\n\n  function indent(state) {\n    if (state.indentCount == 0) {\n      state.indentCount++;\n      var lastScopeOffset = state.scopes[0].offset;\n      var currentOffset = lastScopeOffset + config.indentUnit;\n      state.scopes.unshift({ offset:currentOffset });\n    }\n  }\n\n  function dedent(state) {\n    if (state.scopes.length == 1) return;\n\n    state.scopes.shift();\n  }\n\n  function tokenBase(stream, state) {\n    var ch = stream.peek();\n\n    // Comment\n    if (stream.match(\"/*\")) {\n      state.tokenizer = comment(stream.indentation(), true);\n      return state.tokenizer(stream, state);\n    }\n    if (stream.match(\"//\")) {\n      state.tokenizer = comment(stream.indentation(), false);\n      return state.tokenizer(stream, state);\n    }\n\n    // Interpolation\n    if (stream.match(\"#{\")) {\n      state.tokenizer = buildInterpolationTokenizer(tokenBase);\n      return \"operator\";\n    }\n\n    // Strings\n    if (ch === '\"' || ch === \"'\") {\n      stream.next();\n      state.tokenizer = buildStringTokenizer(ch);\n      return \"string\";\n    }\n\n    if(!state.cursorHalf){// state.cursorHalf === 0\n    // first half i.e. before : for key-value pairs\n    // including selectors\n\n      if (ch === \"-\") {\n        if (stream.match(/^-\\w+-/)) {\n          return \"meta\";\n        }\n      }\n\n      if (ch === \".\") {\n        stream.next();\n        if (stream.match(/^[\\w-]+/)) {\n          indent(state);\n          return \"qualifier\";\n        } else if (stream.peek() === \"#\") {\n          indent(state);\n          return \"tag\";\n        }\n      }\n\n      if (ch === \"#\") {\n        stream.next();\n        // ID selectors\n        if (stream.match(/^[\\w-]+/)) {\n          indent(state);\n          return \"builtin\";\n        }\n        if (stream.peek() === \"#\") {\n          indent(state);\n          return \"tag\";\n        }\n      }\n\n      // Variables\n      if (ch === \"$\") {\n        stream.next();\n        stream.eatWhile(/[\\w-]/);\n        return \"variable-2\";\n      }\n\n      // Numbers\n      if (stream.match(/^-?[0-9\\.]+/))\n        return \"number\";\n\n      // Units\n      if (stream.match(/^(px|em|in)\\b/))\n        return \"unit\";\n\n      if (stream.match(keywordsRegexp))\n        return \"keyword\";\n\n      if (stream.match(/^url/) && stream.peek() === \"(\") {\n        state.tokenizer = urlTokens;\n        return \"atom\";\n      }\n\n      if (ch === \"=\") {\n        // Match shortcut mixin definition\n        if (stream.match(/^=[\\w-]+/)) {\n          indent(state);\n          return \"meta\";\n        }\n      }\n\n      if (ch === \"+\") {\n        // Match shortcut mixin definition\n        if (stream.match(/^\\+[\\w-]+/)){\n          return \"variable-3\";\n        }\n      }\n\n      if(ch === \"@\"){\n        if(stream.match(/@extend/)){\n          if(!stream.match(/\\s*[\\w]/))\n            dedent(state);\n        }\n      }\n\n\n      // Indent Directives\n      if (stream.match(/^@(else if|if|media|else|for|each|while|mixin|function)/)) {\n        indent(state);\n        return \"def\";\n      }\n\n      // Other Directives\n      if (ch === \"@\") {\n        stream.next();\n        stream.eatWhile(/[\\w-]/);\n        return \"def\";\n      }\n\n      if (stream.eatWhile(/[\\w-]/)){\n        if(stream.match(/ *: *[\\w-\\+\\$#!\\(\"']/,false)){\n          word = stream.current().toLowerCase();\n          var prop = state.prevProp + \"-\" + word;\n          if (propertyKeywords.hasOwnProperty(prop)) {\n            return \"property\";\n          } else if (propertyKeywords.hasOwnProperty(word)) {\n            state.prevProp = word;\n            return \"property\";\n          } else if (fontProperties.hasOwnProperty(word)) {\n            return \"property\";\n          }\n          return \"tag\";\n        }\n        else if(stream.match(/ *:/,false)){\n          indent(state);\n          state.cursorHalf = 1;\n          state.prevProp = stream.current().toLowerCase();\n          return \"property\";\n        }\n        else if(stream.match(/ *,/,false)){\n          return \"tag\";\n        }\n        else{\n          indent(state);\n          return \"tag\";\n        }\n      }\n\n      if(ch === \":\"){\n        if (stream.match(pseudoElementsRegexp)){ // could be a pseudo-element\n          return \"variable-3\";\n        }\n        stream.next();\n        state.cursorHalf=1;\n        return \"operator\";\n      }\n\n    } // cursorHalf===0 ends here\n    else{\n\n      if (ch === \"#\") {\n        stream.next();\n        // Hex numbers\n        if (stream.match(/[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/)){\n          if (isEndLine(stream)) {\n            state.cursorHalf = 0;\n          }\n          return \"number\";\n        }\n      }\n\n      // Numbers\n      if (stream.match(/^-?[0-9\\.]+/)){\n        if (isEndLine(stream)) {\n          state.cursorHalf = 0;\n        }\n        return \"number\";\n      }\n\n      // Units\n      if (stream.match(/^(px|em|in)\\b/)){\n        if (isEndLine(stream)) {\n          state.cursorHalf = 0;\n        }\n        return \"unit\";\n      }\n\n      if (stream.match(keywordsRegexp)){\n        if (isEndLine(stream)) {\n          state.cursorHalf = 0;\n        }\n        return \"keyword\";\n      }\n\n      if (stream.match(/^url/) && stream.peek() === \"(\") {\n        state.tokenizer = urlTokens;\n        if (isEndLine(stream)) {\n          state.cursorHalf = 0;\n        }\n        return \"atom\";\n      }\n\n      // Variables\n      if (ch === \"$\") {\n        stream.next();\n        stream.eatWhile(/[\\w-]/);\n        if (isEndLine(stream)) {\n          state.cursorHalf = 0;\n        }\n        return \"variable-2\";\n      }\n\n      // bang character for !important, !default, etc.\n      if (ch === \"!\") {\n        stream.next();\n        state.cursorHalf = 0;\n        return stream.match(/^[\\w]+/) ? \"keyword\": \"operator\";\n      }\n\n      if (stream.match(opRegexp)){\n        if (isEndLine(stream)) {\n          state.cursorHalf = 0;\n        }\n        return \"operator\";\n      }\n\n      // attributes\n      if (stream.eatWhile(/[\\w-]/)) {\n        if (isEndLine(stream)) {\n          state.cursorHalf = 0;\n        }\n        word = stream.current().toLowerCase();\n        if (valueKeywords.hasOwnProperty(word)) {\n          return \"atom\";\n        } else if (colorKeywords.hasOwnProperty(word)) {\n          return \"keyword\";\n        } else if (propertyKeywords.hasOwnProperty(word)) {\n          state.prevProp = stream.current().toLowerCase();\n          return \"property\";\n        } else {\n          return \"tag\";\n        }\n      }\n\n      //stream.eatSpace();\n      if (isEndLine(stream)) {\n        state.cursorHalf = 0;\n        return null;\n      }\n\n    } // else ends here\n\n    if (stream.match(opRegexp))\n      return \"operator\";\n\n    // If we haven't returned by now, we move 1 character\n    // and return an error\n    stream.next();\n    return null;\n  }\n\n  function tokenLexer(stream, state) {\n    if (stream.sol()) state.indentCount = 0;\n    var style = state.tokenizer(stream, state);\n    var current = stream.current();\n\n    if (current === \"@return\" || current === \"}\"){\n      dedent(state);\n    }\n\n    if (style !== null) {\n      var startOfToken = stream.pos - current.length;\n\n      var withCurrentIndent = startOfToken + (config.indentUnit * state.indentCount);\n\n      var newScopes = [];\n\n      for (var i = 0; i < state.scopes.length; i++) {\n        var scope = state.scopes[i];\n\n        if (scope.offset <= withCurrentIndent)\n          newScopes.push(scope);\n      }\n\n      state.scopes = newScopes;\n    }\n\n\n    return style;\n  }\n\n  return {\n    startState: function() {\n      return {\n        tokenizer: tokenBase,\n        scopes: [{offset: 0, type: \"sass\"}],\n        indentCount: 0,\n        cursorHalf: 0,  // cursor half tells us if cursor lies after (1)\n                        // or before (0) colon (well... more or less)\n        definedVars: [],\n        definedMixins: []\n      };\n    },\n    token: function(stream, state) {\n      var style = tokenLexer(stream, state);\n\n      state.lastToken = { style: style, content: stream.current() };\n\n      return style;\n    },\n\n    indent: function(state) {\n      return state.scopes[0].offset;\n    }\n  };\n}, \"css\");\n\nCodeMirror.defineMIME(\"text/x-sass\", \"sass\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sass/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"sass\");\n  // Since Sass has an indent-based syntax, is almost impossible to test correctly the indentation in all cases.\n  // So disable it for tests.\n  mode.indent = undefined;\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"comment\",\n     \"[comment // this is a comment]\",\n     \"[comment   also this is a comment]\")\n\n  MT(\"comment_multiline\",\n     \"[comment /* this is a comment]\",\n     \"[comment   also this is a comment]\")\n\n  MT(\"variable\",\n     \"[variable-2 $page-width][operator :] [number 800][unit px]\")\n\n  MT(\"global_attributes\",\n     \"[tag body]\",\n     \"  [property font][operator :]\",\n     \"    [property family][operator :] [atom sans-serif]\",\n     \"    [property size][operator :] [number 30][unit em]\",\n     \"    [property weight][operator :] [atom bold]\")\n\n  MT(\"scoped_styles\",\n     \"[builtin #contents]\",\n     \"  [property width][operator :] [variable-2 $page-width]\",\n     \"  [builtin #sidebar]\",\n     \"    [property float][operator :] [atom right]\",\n     \"    [property width][operator :] [variable-2 $sidebar-width]\",\n     \"  [builtin #main]\",\n     \"    [property width][operator :] [variable-2 $page-width] [operator -] [variable-2 $sidebar-width]\",\n     \"    [property background][operator :] [variable-2 $primary-color]\",\n     \"    [tag h2]\",\n     \"      [property color][operator :] [keyword blue]\")\n\n  // Sass allows to write the colon as first char instead of a \"separator\".\n  //   :color red\n  // Not supported\n  // MT(\"property_syntax\",\n  //    \"[qualifier .foo]\",\n  //    \"  [operator :][property color] [keyword red]\")\n\n  MT(\"import\",\n     \"[def @import] [string \\\"sass/variables\\\"]\",\n     // Probably it should parsed as above: as a string even without the \" or '\n     // \"[def @import] [string sass/baz]\"\n     \"[def @import] [tag sass][operator /][tag baz]\")\n\n  MT(\"def\",\n     \"[def @if] [variable-2 $foo] [def @else]\")\n\n  MT(\"tag_on_more_lines\",\n    \"[tag td],\",\n    \"[tag th]\",\n    \"  [property font-family][operator :] [string \\\"Arial\\\"], [atom serif]\")\n\n  MT(\"important\",\n     \"[qualifier .foo]\",\n     \"  [property text-decoration][operator :] [atom none] [keyword !important]\",\n     \"[tag h1]\",\n     \"  [property font-size][operator :] [number 2.5][unit em]\")\n\n  MT(\"selector\",\n     // SCSS doesn't highlight the :\n     // \"[tag h1]:[variable-3 before],\",\n     // \"[tag h2]:[variable-3 before]\",\n     \"[tag h1][variable-3 :before],\",\n     \"[tag h2][variable-3 :before]\",\n     \"  [property content][operator :] [string \\\"::\\\"]\")\n\n  MT(\"definition_mixin_equal\",\n     \"[variable-2 $defined-bs-type][operator :] [atom border-box] [keyword !default]\",\n     \"[meta =bs][operator (][variable-2 $bs-type][operator :] [variable-2 $defined-bs-type][operator )]\",\n     \"  [meta -webkit-][property box-sizing][operator :] [variable-2 $bs-type]\",\n     \"  [property box-sizing][operator :] [variable-2 $bs-type]\")\n\n  MT(\"definition_mixin_with_space\",\n     \"[variable-2 $defined-bs-type][operator :] [atom border-box] [keyword !default]\",\n     \"[def @mixin] [tag bs][operator (][variable-2 $bs-type][operator :] [variable-2 $defined-bs-type][operator )] \",\n     \"  [meta -moz-][property box-sizing][operator :] [variable-2 $bs-type]\",\n     \"  [property box-sizing][operator :] [variable-2 $bs-type]\")\n\n  MT(\"numbers_start_dot_include_plus\",\n     // The % is not highlighted correctly\n     // \"[meta =button-links][operator (][variable-2 $button-base][operator :] [atom darken][operator (][variable-2 $color11], [number 10][unit %][operator )][operator )]\",\n     \"[meta =button-links][operator (][variable-2 $button-base][operator :] [atom darken][operator (][variable-2 $color11], [number 10][operator %))]\",\n     \"  [property padding][operator :] [number .3][unit em] [number .6][unit em]\",\n     \"  [variable-3 +border-radius][operator (][number 8][unit px][operator )]\",\n     \"  [property background-color][operator :] [variable-2 $button-base]\")\n\n  MT(\"include\",\n     \"[qualifier .bar]\",\n     \"  [def @include] [tag border-radius][operator (][number 8][unit px][operator )]\")\n\n  MT(\"reference_parent\",\n     \"[qualifier .col]\",\n     \"  [property clear][operator :] [atom both]\",\n     // SCSS doesn't highlight the :\n     // \"  &:[variable-3 after]\",\n     \"  &[variable-3 :after]\",\n     \"    [property content][operator :] [string '']\",\n     \"    [property clear][operator :] [atom both]\")\n\n  MT(\"reference_parent_with_spaces\",\n     \"[tag section]\",\n     \"  [property border-left][operator :]  [number 20][unit px] [atom transparent] [atom solid] \",\n     \"  &[qualifier .section3]\",\n     \"    [qualifier .title]\",\n     \"      [property color][operator :] [keyword white] \",\n     \"    [qualifier .vermas]\",\n     \"      [property display][operator :] [atom none]\")\n\n  MT(\"font_face\",\n     \"[def @font-face]\",\n     \"  [property font-family][operator :] [string 'icomoon']\",\n     \"  [property src][operator :] [atom url][operator (][string fonts/icomoon.ttf][operator )]\")\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/scheme/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Scheme mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"scheme.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Scheme</a>\n  </ul>\n</div>\n\n<article>\n<h2>Scheme mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n; See if the input starts with a given symbol.\n(define (match-symbol input pattern)\n  (cond ((null? (remain input)) #f)\n\t((eqv? (car (remain input)) pattern) (r-cdr input))\n\t(else #f)))\n\n; Allow the input to start with one of a list of patterns.\n(define (match-or input pattern)\n  (cond ((null? pattern) #f)\n\t((match-pattern input (car pattern)))\n\t(else (match-or input (cdr pattern)))))\n\n; Allow a sequence of patterns.\n(define (match-seq input pattern)\n  (if (null? pattern)\n      input\n      (let ((match (match-pattern input (car pattern))))\n\t(if match (match-seq match (cdr pattern)) #f))))\n\n; Match with the pattern but no problem if it does not match.\n(define (match-opt input pattern)\n  (let ((match (match-pattern input (car pattern))))\n    (if match match input)))\n\n; Match anything (other than '()), until pattern is found. The rather\n; clumsy form of requiring an ending pattern is needed to decide where\n; the end of the match is. If none is given, this will match the rest\n; of the sentence.\n(define (match-any input pattern)\n  (cond ((null? (remain input)) #f)\n\t((null? pattern) (f-cons (remain input) (clear-remain input)))\n\t(else\n\t (let ((accum-any (collector)))\n\t   (define (match-pattern-any input pattern)\n\t     (cond ((null? (remain input)) #f)\n\t\t   (else (accum-any (car (remain input)))\n\t\t\t (cond ((match-pattern (r-cdr input) pattern))\n\t\t\t       (else (match-pattern-any (r-cdr input) pattern))))))\n\t   (let ((retval (match-pattern-any input (car pattern))))\n\t     (if retval\n\t\t (f-cons (accum-any) retval)\n\t\t #f))))))\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-scheme</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/scheme/scheme.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**\n * Author: Koh Zi Han, based on implementation by Koh Zi Chun\n */\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"scheme\", function () {\n    var BUILTIN = \"builtin\", COMMENT = \"comment\", STRING = \"string\",\n        ATOM = \"atom\", NUMBER = \"number\", BRACKET = \"bracket\";\n    var INDENT_WORD_SKIP = 2;\n\n    function makeKeywords(str) {\n        var obj = {}, words = str.split(\" \");\n        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n        return obj;\n    }\n\n    var keywords = makeKeywords(\"λ case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt #f floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? #t tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?\");\n    var indentKeys = makeKeywords(\"define let letrec let* lambda\");\n\n    function stateStack(indent, type, prev) { // represents a state stack object\n        this.indent = indent;\n        this.type = type;\n        this.prev = prev;\n    }\n\n    function pushStack(state, indent, type) {\n        state.indentStack = new stateStack(indent, type, state.indentStack);\n    }\n\n    function popStack(state) {\n        state.indentStack = state.indentStack.prev;\n    }\n\n    var binaryMatcher = new RegExp(/^(?:[-+]i|[-+][01]+#*(?:\\/[01]+#*)?i|[-+]?[01]+#*(?:\\/[01]+#*)?@[-+]?[01]+#*(?:\\/[01]+#*)?|[-+]?[01]+#*(?:\\/[01]+#*)?[-+](?:[01]+#*(?:\\/[01]+#*)?)?i|[-+]?[01]+#*(?:\\/[01]+#*)?)(?=[()\\s;\"]|$)/i);\n    var octalMatcher = new RegExp(/^(?:[-+]i|[-+][0-7]+#*(?:\\/[0-7]+#*)?i|[-+]?[0-7]+#*(?:\\/[0-7]+#*)?@[-+]?[0-7]+#*(?:\\/[0-7]+#*)?|[-+]?[0-7]+#*(?:\\/[0-7]+#*)?[-+](?:[0-7]+#*(?:\\/[0-7]+#*)?)?i|[-+]?[0-7]+#*(?:\\/[0-7]+#*)?)(?=[()\\s;\"]|$)/i);\n    var hexMatcher = new RegExp(/^(?:[-+]i|[-+][\\da-f]+#*(?:\\/[\\da-f]+#*)?i|[-+]?[\\da-f]+#*(?:\\/[\\da-f]+#*)?@[-+]?[\\da-f]+#*(?:\\/[\\da-f]+#*)?|[-+]?[\\da-f]+#*(?:\\/[\\da-f]+#*)?[-+](?:[\\da-f]+#*(?:\\/[\\da-f]+#*)?)?i|[-+]?[\\da-f]+#*(?:\\/[\\da-f]+#*)?)(?=[()\\s;\"]|$)/i);\n    var decimalMatcher = new RegExp(/^(?:[-+]i|[-+](?:(?:(?:\\d+#+\\.?#*|\\d+\\.\\d*#*|\\.\\d+#*|\\d+)(?:[esfdl][-+]?\\d+)?)|\\d+#*\\/\\d+#*)i|[-+]?(?:(?:(?:\\d+#+\\.?#*|\\d+\\.\\d*#*|\\.\\d+#*|\\d+)(?:[esfdl][-+]?\\d+)?)|\\d+#*\\/\\d+#*)@[-+]?(?:(?:(?:\\d+#+\\.?#*|\\d+\\.\\d*#*|\\.\\d+#*|\\d+)(?:[esfdl][-+]?\\d+)?)|\\d+#*\\/\\d+#*)|[-+]?(?:(?:(?:\\d+#+\\.?#*|\\d+\\.\\d*#*|\\.\\d+#*|\\d+)(?:[esfdl][-+]?\\d+)?)|\\d+#*\\/\\d+#*)[-+](?:(?:(?:\\d+#+\\.?#*|\\d+\\.\\d*#*|\\.\\d+#*|\\d+)(?:[esfdl][-+]?\\d+)?)|\\d+#*\\/\\d+#*)?i|(?:(?:(?:\\d+#+\\.?#*|\\d+\\.\\d*#*|\\.\\d+#*|\\d+)(?:[esfdl][-+]?\\d+)?)|\\d+#*\\/\\d+#*))(?=[()\\s;\"]|$)/i);\n\n    function isBinaryNumber (stream) {\n        return stream.match(binaryMatcher);\n    }\n\n    function isOctalNumber (stream) {\n        return stream.match(octalMatcher);\n    }\n\n    function isDecimalNumber (stream, backup) {\n        if (backup === true) {\n            stream.backUp(1);\n        }\n        return stream.match(decimalMatcher);\n    }\n\n    function isHexNumber (stream) {\n        return stream.match(hexMatcher);\n    }\n\n    return {\n        startState: function () {\n            return {\n                indentStack: null,\n                indentation: 0,\n                mode: false,\n                sExprComment: false,\n                sExprQuote: false\n            };\n        },\n\n        token: function (stream, state) {\n            if (state.indentStack == null && stream.sol()) {\n                // update indentation, but only if indentStack is empty\n                state.indentation = stream.indentation();\n            }\n\n            // skip spaces\n            if (stream.eatSpace()) {\n                return null;\n            }\n            var returnType = null;\n\n            switch(state.mode){\n                case \"string\": // multi-line string parsing mode\n                    var next, escaped = false;\n                    while ((next = stream.next()) != null) {\n                        if (next == \"\\\"\" && !escaped) {\n\n                            state.mode = false;\n                            break;\n                        }\n                        escaped = !escaped && next == \"\\\\\";\n                    }\n                    returnType = STRING; // continue on in scheme-string mode\n                    break;\n                case \"comment\": // comment parsing mode\n                    var next, maybeEnd = false;\n                    while ((next = stream.next()) != null) {\n                        if (next == \"#\" && maybeEnd) {\n\n                            state.mode = false;\n                            break;\n                        }\n                        maybeEnd = (next == \"|\");\n                    }\n                    returnType = COMMENT;\n                    break;\n                case \"s-expr-comment\": // s-expr commenting mode\n                    state.mode = false;\n                    if(stream.peek() == \"(\" || stream.peek() == \"[\"){\n                        // actually start scheme s-expr commenting mode\n                        state.sExprComment = 0;\n                    }else{\n                        // if not we just comment the entire of the next token\n                        stream.eatWhile(/[^\\s\\(\\)\\[\\]]/); // eat symbol atom\n                        returnType = COMMENT;\n                        break;\n                    }\n                default: // default parsing mode\n                    var ch = stream.next();\n\n                    if (ch == \"\\\"\") {\n                        state.mode = \"string\";\n                        returnType = STRING;\n\n                    } else if (ch == \"'\") {\n                        if (stream.peek() == \"(\" || stream.peek() == \"[\"){\n                            if (typeof state.sExprQuote != \"number\") {\n                                state.sExprQuote = 0;\n                            } // else already in a quoted expression\n                            returnType = ATOM;\n                        } else {\n                            stream.eatWhile(/[\\w_\\-!$%&*+\\.\\/:<=>?@\\^~]/);\n                            returnType = ATOM;\n                        }\n                    } else if (ch == '#') {\n                        if (stream.eat(\"|\")) {                    // Multi-line comment\n                            state.mode = \"comment\"; // toggle to comment mode\n                            returnType = COMMENT;\n                        } else if (stream.eat(/[tf]/i)) {            // #t/#f (atom)\n                            returnType = ATOM;\n                        } else if (stream.eat(';')) {                // S-Expr comment\n                            state.mode = \"s-expr-comment\";\n                            returnType = COMMENT;\n                        } else {\n                            var numTest = null, hasExactness = false, hasRadix = true;\n                            if (stream.eat(/[ei]/i)) {\n                                hasExactness = true;\n                            } else {\n                                stream.backUp(1);       // must be radix specifier\n                            }\n                            if (stream.match(/^#b/i)) {\n                                numTest = isBinaryNumber;\n                            } else if (stream.match(/^#o/i)) {\n                                numTest = isOctalNumber;\n                            } else if (stream.match(/^#x/i)) {\n                                numTest = isHexNumber;\n                            } else if (stream.match(/^#d/i)) {\n                                numTest = isDecimalNumber;\n                            } else if (stream.match(/^[-+0-9.]/, false)) {\n                                hasRadix = false;\n                                numTest = isDecimalNumber;\n                            // re-consume the intial # if all matches failed\n                            } else if (!hasExactness) {\n                                stream.eat('#');\n                            }\n                            if (numTest != null) {\n                                if (hasRadix && !hasExactness) {\n                                    // consume optional exactness after radix\n                                    stream.match(/^#[ei]/i);\n                                }\n                                if (numTest(stream))\n                                    returnType = NUMBER;\n                            }\n                        }\n                    } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) { // match non-prefixed number, must be decimal\n                        returnType = NUMBER;\n                    } else if (ch == \";\") { // comment\n                        stream.skipToEnd(); // rest of the line is a comment\n                        returnType = COMMENT;\n                    } else if (ch == \"(\" || ch == \"[\") {\n                      var keyWord = ''; var indentTemp = stream.column(), letter;\n                        /**\n                        Either\n                        (indent-word ..\n                        (non-indent-word ..\n                        (;something else, bracket, etc.\n                        */\n\n                        while ((letter = stream.eat(/[^\\s\\(\\[\\;\\)\\]]/)) != null) {\n                            keyWord += letter;\n                        }\n\n                        if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word\n\n                            pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);\n                        } else { // non-indent word\n                            // we continue eating the spaces\n                            stream.eatSpace();\n                            if (stream.eol() || stream.peek() == \";\") {\n                                // nothing significant after\n                                // we restart indentation 1 space after\n                                pushStack(state, indentTemp + 1, ch);\n                            } else {\n                                pushStack(state, indentTemp + stream.current().length, ch); // else we match\n                            }\n                        }\n                        stream.backUp(stream.current().length - 1); // undo all the eating\n\n                        if(typeof state.sExprComment == \"number\") state.sExprComment++;\n                        if(typeof state.sExprQuote == \"number\") state.sExprQuote++;\n\n                        returnType = BRACKET;\n                    } else if (ch == \")\" || ch == \"]\") {\n                        returnType = BRACKET;\n                        if (state.indentStack != null && state.indentStack.type == (ch == \")\" ? \"(\" : \"[\")) {\n                            popStack(state);\n\n                            if(typeof state.sExprComment == \"number\"){\n                                if(--state.sExprComment == 0){\n                                    returnType = COMMENT; // final closing bracket\n                                    state.sExprComment = false; // turn off s-expr commenting mode\n                                }\n                            }\n                            if(typeof state.sExprQuote == \"number\"){\n                                if(--state.sExprQuote == 0){\n                                    returnType = ATOM; // final closing bracket\n                                    state.sExprQuote = false; // turn off s-expr quote mode\n                                }\n                            }\n                        }\n                    } else {\n                        stream.eatWhile(/[\\w_\\-!$%&*+\\.\\/:<=>?@\\^~]/);\n\n                        if (keywords && keywords.propertyIsEnumerable(stream.current())) {\n                            returnType = BUILTIN;\n                        } else returnType = \"variable\";\n                    }\n            }\n            return (typeof state.sExprComment == \"number\") ? COMMENT : ((typeof state.sExprQuote == \"number\") ? ATOM : returnType);\n        },\n\n        indent: function (state) {\n            if (state.indentStack == null) return state.indentation;\n            return state.indentStack.indent;\n        },\n\n        closeBrackets: {pairs: \"()[]{}\\\"\\\"\"},\n        lineComment: \";;\"\n    };\n});\n\nCodeMirror.defineMIME(\"text/x-scheme\", \"scheme\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/shell/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Shell mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=stylesheet href=../../lib/codemirror.css>\n<script src=../../lib/codemirror.js></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=shell.js></script>\n<style type=text/css>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Shell</a>\n  </ul>\n</div>\n\n<article>\n<h2>Shell mode</h2>\n\n\n<textarea id=code>\n#!/bin/bash\n\n# clone the repository\ngit clone http://github.com/garden/tree\n\n# generate HTTPS credentials\ncd tree\nopenssl genrsa -aes256 -out https.key 1024\nopenssl req -new -nodes -key https.key -out https.csr\nopenssl x509 -req -days 365 -in https.csr -signkey https.key -out https.crt\ncp https.key{,.orig}\nopenssl rsa -in https.key.orig -out https.key\n\n# start the server in HTTPS mode\ncd web\nsudo node ../server.js 443 'yes' &gt;&gt; ../node.log &amp;\n\n# here is how to stop the server\nfor pid in `ps aux | grep 'node ../server.js' | awk '{print $2}'` ; do\n  sudo kill -9 $pid 2&gt; /dev/null\ndone\n\nexit 0</textarea>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById('code'), {\n    mode: 'shell',\n    lineNumbers: true,\n    matchBrackets: true\n  });\n</script>\n\n<p><strong>MIME types defined:</strong> <code>text/x-sh</code>, <code>application/x-sh</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/shell/shell.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode('shell', function() {\n\n  var words = {};\n  function define(style, dict) {\n    for(var i = 0; i < dict.length; i++) {\n      words[dict[i]] = style;\n    }\n  };\n\n  var commonAtoms = [\"true\", \"false\"];\n  var commonKeywords = [\"if\", \"then\", \"do\", \"else\", \"elif\", \"while\", \"until\", \"for\", \"in\", \"esac\", \"fi\",\n    \"fin\", \"fil\", \"done\", \"exit\", \"set\", \"unset\", \"export\", \"function\"];\n  var commonCommands = [\"ab\", \"awk\", \"bash\", \"beep\", \"cat\", \"cc\", \"cd\", \"chown\", \"chmod\", \"chroot\", \"clear\",\n    \"cp\", \"curl\", \"cut\", \"diff\", \"echo\", \"find\", \"gawk\", \"gcc\", \"get\", \"git\", \"grep\", \"hg\", \"kill\", \"killall\",\n    \"ln\", \"ls\", \"make\", \"mkdir\", \"openssl\", \"mv\", \"nc\", \"nl\", \"node\", \"npm\", \"ping\", \"ps\", \"restart\", \"rm\",\n    \"rmdir\", \"sed\", \"service\", \"sh\", \"shopt\", \"shred\", \"source\", \"sort\", \"sleep\", \"ssh\", \"start\", \"stop\",\n    \"su\", \"sudo\", \"svn\", \"tee\", \"telnet\", \"top\", \"touch\", \"vi\", \"vim\", \"wall\", \"wc\", \"wget\", \"who\", \"write\",\n    \"yes\", \"zsh\"];\n\n  CodeMirror.registerHelper(\"hintWords\", \"shell\", commonAtoms.concat(commonKeywords, commonCommands));\n\n  define('atom', commonAtoms);\n  define('keyword', commonKeywords);\n  define('builtin', commonCommands);\n\n  function tokenBase(stream, state) {\n    if (stream.eatSpace()) return null;\n\n    var sol = stream.sol();\n    var ch = stream.next();\n\n    if (ch === '\\\\') {\n      stream.next();\n      return null;\n    }\n    if (ch === '\\'' || ch === '\"' || ch === '`') {\n      state.tokens.unshift(tokenString(ch, ch === \"`\" ? \"quote\" : \"string\"));\n      return tokenize(stream, state);\n    }\n    if (ch === '#') {\n      if (sol && stream.eat('!')) {\n        stream.skipToEnd();\n        return 'meta'; // 'comment'?\n      }\n      stream.skipToEnd();\n      return 'comment';\n    }\n    if (ch === '$') {\n      state.tokens.unshift(tokenDollar);\n      return tokenize(stream, state);\n    }\n    if (ch === '+' || ch === '=') {\n      return 'operator';\n    }\n    if (ch === '-') {\n      stream.eat('-');\n      stream.eatWhile(/\\w/);\n      return 'attribute';\n    }\n    if (/\\d/.test(ch)) {\n      stream.eatWhile(/\\d/);\n      if(stream.eol() || !/\\w/.test(stream.peek())) {\n        return 'number';\n      }\n    }\n    stream.eatWhile(/[\\w-]/);\n    var cur = stream.current();\n    if (stream.peek() === '=' && /\\w+/.test(cur)) return 'def';\n    return words.hasOwnProperty(cur) ? words[cur] : null;\n  }\n\n  function tokenString(quote, style) {\n    var close = quote == \"(\" ? \")\" : quote == \"{\" ? \"}\" : quote\n    return function(stream, state) {\n      var next, escaped = false;\n      while ((next = stream.next()) != null) {\n        if (next === close && !escaped) {\n          state.tokens.shift();\n          break;\n        } else if (next === '$' && !escaped && quote !== \"'\" && stream.peek() != close) {\n          escaped = true;\n          stream.backUp(1);\n          state.tokens.unshift(tokenDollar);\n          break;\n        } else if (!escaped && quote !== close && next === quote) {\n          state.tokens.unshift(tokenString(quote, style))\n          return tokenize(stream, state)\n        } else if (!escaped && /['\"]/.test(next) && !/['\"]/.test(quote)) {\n          state.tokens.unshift(tokenStringStart(next, \"string\"));\n          stream.backUp(1);\n          break;\n        }\n        escaped = !escaped && next === '\\\\';\n      }\n      return style;\n    };\n  };\n\n  function tokenStringStart(quote, style) {\n    return function(stream, state) {\n      state.tokens[0] = tokenString(quote, style)\n      stream.next()\n      return tokenize(stream, state)\n    }\n  }\n\n  var tokenDollar = function(stream, state) {\n    if (state.tokens.length > 1) stream.eat('$');\n    var ch = stream.next()\n    if (/['\"({]/.test(ch)) {\n      state.tokens[0] = tokenString(ch, ch == \"(\" ? \"quote\" : ch == \"{\" ? \"def\" : \"string\");\n      return tokenize(stream, state);\n    }\n    if (!/\\d/.test(ch)) stream.eatWhile(/\\w/);\n    state.tokens.shift();\n    return 'def';\n  };\n\n  function tokenize(stream, state) {\n    return (state.tokens[0] || tokenBase) (stream, state);\n  };\n\n  return {\n    startState: function() {return {tokens:[]};},\n    token: function(stream, state) {\n      return tokenize(stream, state);\n    },\n    closeBrackets: \"()[]{}''\\\"\\\"``\",\n    lineComment: '#',\n    fold: \"brace\"\n  };\n});\n\nCodeMirror.defineMIME('text/x-sh', 'shell');\n// Apache uses a slightly different Media Type for Shell scripts\n// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types\nCodeMirror.defineMIME('application/x-sh', 'shell');\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/shell/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({}, \"shell\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"var\",\n     \"text [def $var] text\");\n  MT(\"varBraces\",\n     \"text[def ${var}]text\");\n  MT(\"varVar\",\n     \"text [def $a$b] text\");\n  MT(\"varBracesVarBraces\",\n     \"text[def ${a}${b}]text\");\n\n  MT(\"singleQuotedVar\",\n     \"[string 'text $var text']\");\n  MT(\"singleQuotedVarBraces\",\n     \"[string 'text ${var} text']\");\n\n  MT(\"doubleQuotedVar\",\n     '[string \"text ][def $var][string  text\"]');\n  MT(\"doubleQuotedVarBraces\",\n     '[string \"text][def ${var}][string text\"]');\n  MT(\"doubleQuotedVarPunct\",\n     '[string \"text ][def $@][string  text\"]');\n  MT(\"doubleQuotedVarVar\",\n     '[string \"][def $a$b][string \"]');\n  MT(\"doubleQuotedVarBracesVarBraces\",\n     '[string \"][def ${a}${b}][string \"]');\n\n  MT(\"notAString\",\n     \"text\\\\'text\");\n  MT(\"escapes\",\n     \"outside\\\\'\\\\\\\"\\\\`\\\\\\\\[string \\\"inside\\\\`\\\\'\\\\\\\"\\\\\\\\`\\\\$notAVar\\\"]outside\\\\$\\\\(notASubShell\\\\)\");\n\n  MT(\"subshell\",\n     \"[builtin echo] [quote $(whoami)] s log, stardate [quote `date`].\");\n  MT(\"doubleQuotedSubshell\",\n     \"[builtin echo] [string \\\"][quote $(whoami)][string 's log, stardate `date`.\\\"]\");\n\n  MT(\"hashbang\",\n     \"[meta #!/bin/bash]\");\n  MT(\"comment\",\n     \"text [comment # Blurb]\");\n\n  MT(\"numbers\",\n     \"[number 0] [number 1] [number 2]\");\n  MT(\"keywords\",\n     \"[keyword while] [atom true]; [keyword do]\",\n     \"  [builtin sleep] [number 3]\",\n     \"[keyword done]\");\n  MT(\"options\",\n     \"[builtin ls] [attribute -l] [attribute --human-readable]\");\n  MT(\"operator\",\n     \"[def var][operator =]value\");\n\n  MT(\"doubleParens\",\n     \"foo [quote $((bar))]\")\n\n  MT(\"nested braces\",\n     \"[builtin echo] [def ${A[${B}]]}]\")\n\n  MT(\"strings in parens\",\n     \"[def FOO][operator =]([quote $(<][string \\\"][def $MYDIR][string \\\"][quote /myfile grep ][string 'hello$'][quote )])\")\n\n  MT (\"string ending in dollar\",\n     '[def a][operator =][string \"xyz$\"]; [def b][operator =][string \"y\"]')\n\n  MT (\"quote ending in dollar\",\n     \"[quote $(echo a$)]\")\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sieve/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Sieve (RFC5228) mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"sieve.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Sieve (RFC5228)</a>\n  </ul>\n</div>\n\n<article>\n<h2>Sieve (RFC5228) mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n#\n# Example Sieve Filter\n# Declare any optional features or extension used by the script\n#\n\nrequire [\"fileinto\", \"reject\"];\n\n#\n# Reject any large messages (note that the four leading dots get\n# \"stuffed\" to three)\n#\nif size :over 1M\n{\n  reject text:\nPlease do not send me large attachments.\nPut your file on a server and send me the URL.\nThank you.\n.... Fred\n.\n;\n  stop;\n}\n\n#\n# Handle messages from known mailing lists\n# Move messages from IETF filter discussion list to filter folder\n#\nif header :is \"Sender\" \"owner-ietf-mta-filters@imc.org\"\n{\n  fileinto \"filter\";  # move to \"filter\" folder\n}\n#\n# Keep all messages to or from people in my company\n#\nelsif address :domain :is [\"From\", \"To\"] \"example.com\"\n{\n  keep;               # keep in \"In\" folder\n}\n\n#\n# Try and catch unsolicited email.  If a message is not to me,\n# or it contains a subject known to be spam, file it away.\n#\nelsif anyof (not address :all :contains\n               [\"To\", \"Cc\", \"Bcc\"] \"me@example.com\",\n             header :matches \"subject\"\n               [\"*make*money*fast*\", \"*university*dipl*mas*\"])\n{\n  # If message header does not contain my address,\n  # it's from a list.\n  fileinto \"spam\";   # move to \"spam\" folder\n}\nelse\n{\n  # Move all other (non-company) mail to \"personal\"\n  # folder.\n  fileinto \"personal\";\n}\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>application/sieve</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sieve/sieve.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"sieve\", function(config) {\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  var keywords = words(\"if elsif else stop require\");\n  var atoms = words(\"true false not\");\n  var indentUnit = config.indentUnit;\n\n  function tokenBase(stream, state) {\n\n    var ch = stream.next();\n    if (ch == \"/\" && stream.eat(\"*\")) {\n      state.tokenize = tokenCComment;\n      return tokenCComment(stream, state);\n    }\n\n    if (ch === '#') {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n\n    if (ch == \"\\\"\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n\n    if (ch == \"(\") {\n      state._indent.push(\"(\");\n      // add virtual angel wings so that editor behaves...\n      // ...more sane incase of broken brackets\n      state._indent.push(\"{\");\n      return null;\n    }\n\n    if (ch === \"{\") {\n      state._indent.push(\"{\");\n      return null;\n    }\n\n    if (ch == \")\")  {\n      state._indent.pop();\n      state._indent.pop();\n    }\n\n    if (ch === \"}\") {\n      state._indent.pop();\n      return null;\n    }\n\n    if (ch == \",\")\n      return null;\n\n    if (ch == \";\")\n      return null;\n\n\n    if (/[{}\\(\\),;]/.test(ch))\n      return null;\n\n    // 1*DIGIT \"K\" / \"M\" / \"G\"\n    if (/\\d/.test(ch)) {\n      stream.eatWhile(/[\\d]/);\n      stream.eat(/[KkMmGg]/);\n      return \"number\";\n    }\n\n    // \":\" (ALPHA / \"_\") *(ALPHA / DIGIT / \"_\")\n    if (ch == \":\") {\n      stream.eatWhile(/[a-zA-Z_]/);\n      stream.eatWhile(/[a-zA-Z0-9_]/);\n\n      return \"operator\";\n    }\n\n    stream.eatWhile(/\\w/);\n    var cur = stream.current();\n\n    // \"text:\" *(SP / HTAB) (hash-comment / CRLF)\n    // *(multiline-literal / multiline-dotstart)\n    // \".\" CRLF\n    if ((cur == \"text\") && stream.eat(\":\"))\n    {\n      state.tokenize = tokenMultiLineString;\n      return \"string\";\n    }\n\n    if (keywords.propertyIsEnumerable(cur))\n      return \"keyword\";\n\n    if (atoms.propertyIsEnumerable(cur))\n      return \"atom\";\n\n    return null;\n  }\n\n  function tokenMultiLineString(stream, state)\n  {\n    state._multiLineString = true;\n    // the first line is special it may contain a comment\n    if (!stream.sol()) {\n      stream.eatSpace();\n\n      if (stream.peek() == \"#\") {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n\n      stream.skipToEnd();\n      return \"string\";\n    }\n\n    if ((stream.next() == \".\")  && (stream.eol()))\n    {\n      state._multiLineString = false;\n      state.tokenize = tokenBase;\n    }\n\n    return \"string\";\n  }\n\n  function tokenCComment(stream, state) {\n    var maybeEnd = false, ch;\n    while ((ch = stream.next()) != null) {\n      if (maybeEnd && ch == \"/\") {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && !escaped)\n          break;\n        escaped = !escaped && ch == \"\\\\\";\n      }\n      if (!escaped) state.tokenize = tokenBase;\n      return \"string\";\n    };\n  }\n\n  return {\n    startState: function(base) {\n      return {tokenize: tokenBase,\n              baseIndent: base || 0,\n              _indent: []};\n    },\n\n    token: function(stream, state) {\n      if (stream.eatSpace())\n        return null;\n\n      return (state.tokenize || tokenBase)(stream, state);\n    },\n\n    indent: function(state, _textAfter) {\n      var length = state._indent.length;\n      if (_textAfter && (_textAfter[0] == \"}\"))\n        length--;\n\n      if (length <0)\n        length = 0;\n\n      return length * indentUnit;\n    },\n\n    electricChars: \"}\"\n  };\n});\n\nCodeMirror.defineMIME(\"application/sieve\", \"sieve\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/slim/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: SLIM mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/ambiance.css\">\n<script src=\"https://code.jquery.com/jquery-1.11.1.min.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.11.0/jquery-ui.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../htmlembedded/htmlembedded.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"../coffeescript/coffeescript.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../ruby/ruby.js\"></script>\n<script src=\"../markdown/markdown.js\"></script>\n<script src=\"slim.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">SLIM</a>\n  </ul>\n</div>\n\n<article>\n  <h2>SLIM mode</h2>\n  <form><textarea id=\"code\" name=\"code\">\nbody\n  table\n    - for user in users\n      td id=\"user_#{user.id}\" class=user.role\n        a href=user_action(user, :edit) Edit #{user.name}\n        a href=(path_to_user user) = user.name\nbody\n  h1(id=\"logo\") = page_logo\n  h2[id=\"tagline\" class=\"small tagline\"] = page_tagline\n\nh2[id=\"tagline\"\n   class=\"small tagline\"] = page_tagline\n\nh1 id = \"logo\" = page_logo\nh2 [ id = \"tagline\" ] = page_tagline\n\n/ comment\n  second line\n/! html comment\n   second line\n<!-- html comment -->\n<a href=\"#{'hello' if set}\">link</a>\na.slim href=\"work\" disabled=false running==:atom Text <b>bold</b>\n.clazz data-id=\"test\" == 'hello' unless quark\n | Text mode #{12}\n   Second line\n= x ||= :ruby_atom\n#menu.left\n  - @env.each do |x|\n    li: a = x\n*@dyntag attr=\"val\"\n.first *{:class => [:second, :third]} Text\n.second class=[\"text\",\"more\"]\n.third class=:text,:symbol\n\n  </textarea></form>\n  <script>\n    var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n      lineNumbers: true,\n      theme: \"ambiance\",\n      mode: \"application/x-slim\"\n    });\n    $('.CodeMirror').resizable({\n      resize: function() {\n        editor.setSize($(this).width(), $(this).height());\n        //editor.refresh();\n      }\n    });\n  </script>\n\n  <p><strong>MIME types defined:</strong> <code>application/x-slim</code>.</p>\n\n  <p>\n    <strong>Parsing/Highlighting Tests:</strong>\n    <a href=\"../../test/index.html#slim_*\">normal</a>,\n    <a href=\"../../test/index.html#verbose,slim_*\">verbose</a>.\n  </p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/slim/slim.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Slim Highlighting for CodeMirror copyright (c) HicknHack Software Gmbh\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../htmlmixed/htmlmixed\"), require(\"../ruby/ruby\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../htmlmixed/htmlmixed\", \"../ruby/ruby\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\n  CodeMirror.defineMode(\"slim\", function(config) {\n    var htmlMode = CodeMirror.getMode(config, {name: \"htmlmixed\"});\n    var rubyMode = CodeMirror.getMode(config, \"ruby\");\n    var modes = { html: htmlMode, ruby: rubyMode };\n    var embedded = {\n      ruby: \"ruby\",\n      javascript: \"javascript\",\n      css: \"text/css\",\n      sass: \"text/x-sass\",\n      scss: \"text/x-scss\",\n      less: \"text/x-less\",\n      styl: \"text/x-styl\", // no highlighting so far\n      coffee: \"coffeescript\",\n      asciidoc: \"text/x-asciidoc\",\n      markdown: \"text/x-markdown\",\n      textile: \"text/x-textile\", // no highlighting so far\n      creole: \"text/x-creole\", // no highlighting so far\n      wiki: \"text/x-wiki\", // no highlighting so far\n      mediawiki: \"text/x-mediawiki\", // no highlighting so far\n      rdoc: \"text/x-rdoc\", // no highlighting so far\n      builder: \"text/x-builder\", // no highlighting so far\n      nokogiri: \"text/x-nokogiri\", // no highlighting so far\n      erb: \"application/x-erb\"\n    };\n    var embeddedRegexp = function(map){\n      var arr = [];\n      for(var key in map) arr.push(key);\n      return new RegExp(\"^(\"+arr.join('|')+\"):\");\n    }(embedded);\n\n    var styleMap = {\n      \"commentLine\": \"comment\",\n      \"slimSwitch\": \"operator special\",\n      \"slimTag\": \"tag\",\n      \"slimId\": \"attribute def\",\n      \"slimClass\": \"attribute qualifier\",\n      \"slimAttribute\": \"attribute\",\n      \"slimSubmode\": \"keyword special\",\n      \"closeAttributeTag\": null,\n      \"slimDoctype\": null,\n      \"lineContinuation\": null\n    };\n    var closing = {\n      \"{\": \"}\",\n      \"[\": \"]\",\n      \"(\": \")\"\n    };\n\n    var nameStartChar = \"_a-zA-Z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\";\n    var nameChar = nameStartChar + \"\\\\-0-9\\xB7\\u0300-\\u036F\\u203F-\\u2040\";\n    var nameRegexp = new RegExp(\"^[:\"+nameStartChar+\"](?::[\"+nameChar+\"]|[\"+nameChar+\"]*)\");\n    var attributeNameRegexp = new RegExp(\"^[:\"+nameStartChar+\"][:\\\\.\"+nameChar+\"]*(?=\\\\s*=)\");\n    var wrappedAttributeNameRegexp = new RegExp(\"^[:\"+nameStartChar+\"][:\\\\.\"+nameChar+\"]*\");\n    var classNameRegexp = /^\\.-?[_a-zA-Z]+[\\w\\-]*/;\n    var classIdRegexp = /^#[_a-zA-Z]+[\\w\\-]*/;\n\n    function backup(pos, tokenize, style) {\n      var restore = function(stream, state) {\n        state.tokenize = tokenize;\n        if (stream.pos < pos) {\n          stream.pos = pos;\n          return style;\n        }\n        return state.tokenize(stream, state);\n      };\n      return function(stream, state) {\n        state.tokenize = restore;\n        return tokenize(stream, state);\n      };\n    }\n\n    function maybeBackup(stream, state, pat, offset, style) {\n      var cur = stream.current();\n      var idx = cur.search(pat);\n      if (idx > -1) {\n        state.tokenize = backup(stream.pos, state.tokenize, style);\n        stream.backUp(cur.length - idx - offset);\n      }\n      return style;\n    }\n\n    function continueLine(state, column) {\n      state.stack = {\n        parent: state.stack,\n        style: \"continuation\",\n        indented: column,\n        tokenize: state.line\n      };\n      state.line = state.tokenize;\n    }\n    function finishContinue(state) {\n      if (state.line == state.tokenize) {\n        state.line = state.stack.tokenize;\n        state.stack = state.stack.parent;\n      }\n    }\n\n    function lineContinuable(column, tokenize) {\n      return function(stream, state) {\n        finishContinue(state);\n        if (stream.match(/^\\\\$/)) {\n          continueLine(state, column);\n          return \"lineContinuation\";\n        }\n        var style = tokenize(stream, state);\n        if (stream.eol() && stream.current().match(/(?:^|[^\\\\])(?:\\\\\\\\)*\\\\$/)) {\n          stream.backUp(1);\n        }\n        return style;\n      };\n    }\n    function commaContinuable(column, tokenize) {\n      return function(stream, state) {\n        finishContinue(state);\n        var style = tokenize(stream, state);\n        if (stream.eol() && stream.current().match(/,$/)) {\n          continueLine(state, column);\n        }\n        return style;\n      };\n    }\n\n    function rubyInQuote(endQuote, tokenize) {\n      // TODO: add multi line support\n      return function(stream, state) {\n        var ch = stream.peek();\n        if (ch == endQuote && state.rubyState.tokenize.length == 1) {\n          // step out of ruby context as it seems to complete processing all the braces\n          stream.next();\n          state.tokenize = tokenize;\n          return \"closeAttributeTag\";\n        } else {\n          return ruby(stream, state);\n        }\n      };\n    }\n    function startRubySplat(tokenize) {\n      var rubyState;\n      var runSplat = function(stream, state) {\n        if (state.rubyState.tokenize.length == 1 && !state.rubyState.context.prev) {\n          stream.backUp(1);\n          if (stream.eatSpace()) {\n            state.rubyState = rubyState;\n            state.tokenize = tokenize;\n            return tokenize(stream, state);\n          }\n          stream.next();\n        }\n        return ruby(stream, state);\n      };\n      return function(stream, state) {\n        rubyState = state.rubyState;\n        state.rubyState = CodeMirror.startState(rubyMode);\n        state.tokenize = runSplat;\n        return ruby(stream, state);\n      };\n    }\n\n    function ruby(stream, state) {\n      return rubyMode.token(stream, state.rubyState);\n    }\n\n    function htmlLine(stream, state) {\n      if (stream.match(/^\\\\$/)) {\n        return \"lineContinuation\";\n      }\n      return html(stream, state);\n    }\n    function html(stream, state) {\n      if (stream.match(/^#\\{/)) {\n        state.tokenize = rubyInQuote(\"}\", state.tokenize);\n        return null;\n      }\n      return maybeBackup(stream, state, /[^\\\\]#\\{/, 1, htmlMode.token(stream, state.htmlState));\n    }\n\n    function startHtmlLine(lastTokenize) {\n      return function(stream, state) {\n        var style = htmlLine(stream, state);\n        if (stream.eol()) state.tokenize = lastTokenize;\n        return style;\n      };\n    }\n\n    function startHtmlMode(stream, state, offset) {\n      state.stack = {\n        parent: state.stack,\n        style: \"html\",\n        indented: stream.column() + offset, // pipe + space\n        tokenize: state.line\n      };\n      state.line = state.tokenize = html;\n      return null;\n    }\n\n    function comment(stream, state) {\n      stream.skipToEnd();\n      return state.stack.style;\n    }\n\n    function commentMode(stream, state) {\n      state.stack = {\n        parent: state.stack,\n        style: \"comment\",\n        indented: state.indented + 1,\n        tokenize: state.line\n      };\n      state.line = comment;\n      return comment(stream, state);\n    }\n\n    function attributeWrapper(stream, state) {\n      if (stream.eat(state.stack.endQuote)) {\n        state.line = state.stack.line;\n        state.tokenize = state.stack.tokenize;\n        state.stack = state.stack.parent;\n        return null;\n      }\n      if (stream.match(wrappedAttributeNameRegexp)) {\n        state.tokenize = attributeWrapperAssign;\n        return \"slimAttribute\";\n      }\n      stream.next();\n      return null;\n    }\n    function attributeWrapperAssign(stream, state) {\n      if (stream.match(/^==?/)) {\n        state.tokenize = attributeWrapperValue;\n        return null;\n      }\n      return attributeWrapper(stream, state);\n    }\n    function attributeWrapperValue(stream, state) {\n      var ch = stream.peek();\n      if (ch == '\"' || ch == \"\\'\") {\n        state.tokenize = readQuoted(ch, \"string\", true, false, attributeWrapper);\n        stream.next();\n        return state.tokenize(stream, state);\n      }\n      if (ch == '[') {\n        return startRubySplat(attributeWrapper)(stream, state);\n      }\n      if (stream.match(/^(true|false|nil)\\b/)) {\n        state.tokenize = attributeWrapper;\n        return \"keyword\";\n      }\n      return startRubySplat(attributeWrapper)(stream, state);\n    }\n\n    function startAttributeWrapperMode(state, endQuote, tokenize) {\n      state.stack = {\n        parent: state.stack,\n        style: \"wrapper\",\n        indented: state.indented + 1,\n        tokenize: tokenize,\n        line: state.line,\n        endQuote: endQuote\n      };\n      state.line = state.tokenize = attributeWrapper;\n      return null;\n    }\n\n    function sub(stream, state) {\n      if (stream.match(/^#\\{/)) {\n        state.tokenize = rubyInQuote(\"}\", state.tokenize);\n        return null;\n      }\n      var subStream = new CodeMirror.StringStream(stream.string.slice(state.stack.indented), stream.tabSize);\n      subStream.pos = stream.pos - state.stack.indented;\n      subStream.start = stream.start - state.stack.indented;\n      subStream.lastColumnPos = stream.lastColumnPos - state.stack.indented;\n      subStream.lastColumnValue = stream.lastColumnValue - state.stack.indented;\n      var style = state.subMode.token(subStream, state.subState);\n      stream.pos = subStream.pos + state.stack.indented;\n      return style;\n    }\n    function firstSub(stream, state) {\n      state.stack.indented = stream.column();\n      state.line = state.tokenize = sub;\n      return state.tokenize(stream, state);\n    }\n\n    function createMode(mode) {\n      var query = embedded[mode];\n      var spec = CodeMirror.mimeModes[query];\n      if (spec) {\n        return CodeMirror.getMode(config, spec);\n      }\n      var factory = CodeMirror.modes[query];\n      if (factory) {\n        return factory(config, {name: query});\n      }\n      return CodeMirror.getMode(config, \"null\");\n    }\n\n    function getMode(mode) {\n      if (!modes.hasOwnProperty(mode)) {\n        return modes[mode] = createMode(mode);\n      }\n      return modes[mode];\n    }\n\n    function startSubMode(mode, state) {\n      var subMode = getMode(mode);\n      var subState = CodeMirror.startState(subMode);\n\n      state.subMode = subMode;\n      state.subState = subState;\n\n      state.stack = {\n        parent: state.stack,\n        style: \"sub\",\n        indented: state.indented + 1,\n        tokenize: state.line\n      };\n      state.line = state.tokenize = firstSub;\n      return \"slimSubmode\";\n    }\n\n    function doctypeLine(stream, _state) {\n      stream.skipToEnd();\n      return \"slimDoctype\";\n    }\n\n    function startLine(stream, state) {\n      var ch = stream.peek();\n      if (ch == '<') {\n        return (state.tokenize = startHtmlLine(state.tokenize))(stream, state);\n      }\n      if (stream.match(/^[|']/)) {\n        return startHtmlMode(stream, state, 1);\n      }\n      if (stream.match(/^\\/(!|\\[\\w+])?/)) {\n        return commentMode(stream, state);\n      }\n      if (stream.match(/^(-|==?[<>]?)/)) {\n        state.tokenize = lineContinuable(stream.column(), commaContinuable(stream.column(), ruby));\n        return \"slimSwitch\";\n      }\n      if (stream.match(/^doctype\\b/)) {\n        state.tokenize = doctypeLine;\n        return \"keyword\";\n      }\n\n      var m = stream.match(embeddedRegexp);\n      if (m) {\n        return startSubMode(m[1], state);\n      }\n\n      return slimTag(stream, state);\n    }\n\n    function slim(stream, state) {\n      if (state.startOfLine) {\n        return startLine(stream, state);\n      }\n      return slimTag(stream, state);\n    }\n\n    function slimTag(stream, state) {\n      if (stream.eat('*')) {\n        state.tokenize = startRubySplat(slimTagExtras);\n        return null;\n      }\n      if (stream.match(nameRegexp)) {\n        state.tokenize = slimTagExtras;\n        return \"slimTag\";\n      }\n      return slimClass(stream, state);\n    }\n    function slimTagExtras(stream, state) {\n      if (stream.match(/^(<>?|><?)/)) {\n        state.tokenize = slimClass;\n        return null;\n      }\n      return slimClass(stream, state);\n    }\n    function slimClass(stream, state) {\n      if (stream.match(classIdRegexp)) {\n        state.tokenize = slimClass;\n        return \"slimId\";\n      }\n      if (stream.match(classNameRegexp)) {\n        state.tokenize = slimClass;\n        return \"slimClass\";\n      }\n      return slimAttribute(stream, state);\n    }\n    function slimAttribute(stream, state) {\n      if (stream.match(/^([\\[\\{\\(])/)) {\n        return startAttributeWrapperMode(state, closing[RegExp.$1], slimAttribute);\n      }\n      if (stream.match(attributeNameRegexp)) {\n        state.tokenize = slimAttributeAssign;\n        return \"slimAttribute\";\n      }\n      if (stream.peek() == '*') {\n        stream.next();\n        state.tokenize = startRubySplat(slimContent);\n        return null;\n      }\n      return slimContent(stream, state);\n    }\n    function slimAttributeAssign(stream, state) {\n      if (stream.match(/^==?/)) {\n        state.tokenize = slimAttributeValue;\n        return null;\n      }\n      // should never happen, because of forward lookup\n      return slimAttribute(stream, state);\n    }\n\n    function slimAttributeValue(stream, state) {\n      var ch = stream.peek();\n      if (ch == '\"' || ch == \"\\'\") {\n        state.tokenize = readQuoted(ch, \"string\", true, false, slimAttribute);\n        stream.next();\n        return state.tokenize(stream, state);\n      }\n      if (ch == '[') {\n        return startRubySplat(slimAttribute)(stream, state);\n      }\n      if (ch == ':') {\n        return startRubySplat(slimAttributeSymbols)(stream, state);\n      }\n      if (stream.match(/^(true|false|nil)\\b/)) {\n        state.tokenize = slimAttribute;\n        return \"keyword\";\n      }\n      return startRubySplat(slimAttribute)(stream, state);\n    }\n    function slimAttributeSymbols(stream, state) {\n      stream.backUp(1);\n      if (stream.match(/^[^\\s],(?=:)/)) {\n        state.tokenize = startRubySplat(slimAttributeSymbols);\n        return null;\n      }\n      stream.next();\n      return slimAttribute(stream, state);\n    }\n    function readQuoted(quote, style, embed, unescaped, nextTokenize) {\n      return function(stream, state) {\n        finishContinue(state);\n        var fresh = stream.current().length == 0;\n        if (stream.match(/^\\\\$/, fresh)) {\n          if (!fresh) return style;\n          continueLine(state, state.indented);\n          return \"lineContinuation\";\n        }\n        if (stream.match(/^#\\{/, fresh)) {\n          if (!fresh) return style;\n          state.tokenize = rubyInQuote(\"}\", state.tokenize);\n          return null;\n        }\n        var escaped = false, ch;\n        while ((ch = stream.next()) != null) {\n          if (ch == quote && (unescaped || !escaped)) {\n            state.tokenize = nextTokenize;\n            break;\n          }\n          if (embed && ch == \"#\" && !escaped) {\n            if (stream.eat(\"{\")) {\n              stream.backUp(2);\n              break;\n            }\n          }\n          escaped = !escaped && ch == \"\\\\\";\n        }\n        if (stream.eol() && escaped) {\n          stream.backUp(1);\n        }\n        return style;\n      };\n    }\n    function slimContent(stream, state) {\n      if (stream.match(/^==?/)) {\n        state.tokenize = ruby;\n        return \"slimSwitch\";\n      }\n      if (stream.match(/^\\/$/)) { // tag close hint\n        state.tokenize = slim;\n        return null;\n      }\n      if (stream.match(/^:/)) { // inline tag\n        state.tokenize = slimTag;\n        return \"slimSwitch\";\n      }\n      startHtmlMode(stream, state, 0);\n      return state.tokenize(stream, state);\n    }\n\n    var mode = {\n      // default to html mode\n      startState: function() {\n        var htmlState = CodeMirror.startState(htmlMode);\n        var rubyState = CodeMirror.startState(rubyMode);\n        return {\n          htmlState: htmlState,\n          rubyState: rubyState,\n          stack: null,\n          last: null,\n          tokenize: slim,\n          line: slim,\n          indented: 0\n        };\n      },\n\n      copyState: function(state) {\n        return {\n          htmlState : CodeMirror.copyState(htmlMode, state.htmlState),\n          rubyState: CodeMirror.copyState(rubyMode, state.rubyState),\n          subMode: state.subMode,\n          subState: state.subMode && CodeMirror.copyState(state.subMode, state.subState),\n          stack: state.stack,\n          last: state.last,\n          tokenize: state.tokenize,\n          line: state.line\n        };\n      },\n\n      token: function(stream, state) {\n        if (stream.sol()) {\n          state.indented = stream.indentation();\n          state.startOfLine = true;\n          state.tokenize = state.line;\n          while (state.stack && state.stack.indented > state.indented && state.last != \"slimSubmode\") {\n            state.line = state.tokenize = state.stack.tokenize;\n            state.stack = state.stack.parent;\n            state.subMode = null;\n            state.subState = null;\n          }\n        }\n        if (stream.eatSpace()) return null;\n        var style = state.tokenize(stream, state);\n        state.startOfLine = false;\n        if (style) state.last = style;\n        return styleMap.hasOwnProperty(style) ? styleMap[style] : style;\n      },\n\n      blankLine: function(state) {\n        if (state.subMode && state.subMode.blankLine) {\n          return state.subMode.blankLine(state.subState);\n        }\n      },\n\n      innerMode: function(state) {\n        if (state.subMode) return {state: state.subState, mode: state.subMode};\n        return {state: state, mode: mode};\n      }\n\n      //indent: function(state) {\n      //  return state.indented;\n      //}\n    };\n    return mode;\n  }, \"htmlmixed\", \"ruby\");\n\n  CodeMirror.defineMIME(\"text/x-slim\", \"slim\");\n  CodeMirror.defineMIME(\"application/x-slim\", \"slim\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/slim/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Slim Highlighting for CodeMirror copyright (c) HicknHack Software Gmbh\n\n(function() {\n  var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, \"slim\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  // Requires at least one media query\n  MT(\"elementName\",\n     \"[tag h1] Hey There\");\n\n  MT(\"oneElementPerLine\",\n     \"[tag h1] Hey There .h2\");\n\n  MT(\"idShortcut\",\n     \"[attribute&def #test] Hey There\");\n\n  MT(\"tagWithIdShortcuts\",\n     \"[tag h1][attribute&def #test] Hey There\");\n\n  MT(\"classShortcut\",\n     \"[attribute&qualifier .hello] Hey There\");\n\n  MT(\"tagWithIdAndClassShortcuts\",\n     \"[tag h1][attribute&def #test][attribute&qualifier .hello] Hey There\");\n\n  MT(\"docType\",\n     \"[keyword doctype] xml\");\n\n  MT(\"comment\",\n     \"[comment / Hello WORLD]\");\n\n  MT(\"notComment\",\n     \"[tag h1] This is not a / comment \");\n\n  MT(\"attributes\",\n     \"[tag a]([attribute title]=[string \\\"test\\\"]) [attribute href]=[string \\\"link\\\"]}\");\n\n  MT(\"multiLineAttributes\",\n     \"[tag a]([attribute title]=[string \\\"test\\\"]\",\n     \"  ) [attribute href]=[string \\\"link\\\"]}\");\n\n  MT(\"htmlCode\",\n     \"[tag&bracket <][tag h1][tag&bracket >]Title[tag&bracket </][tag h1][tag&bracket >]\");\n\n  MT(\"rubyBlock\",\n     \"[operator&special =][variable-2 @item]\");\n\n  MT(\"selectorRubyBlock\",\n     \"[tag a][attribute&qualifier .test][operator&special =] [variable-2 @item]\");\n\n  MT(\"nestedRubyBlock\",\n      \"[tag a]\",\n      \"  [operator&special =][variable puts] [string \\\"test\\\"]\");\n\n  MT(\"multilinePlaintext\",\n      \"[tag p]\",\n      \"  | Hello,\",\n      \"    World\");\n\n  MT(\"multilineRuby\",\n      \"[tag p]\",\n      \"  [comment /# this is a comment]\",\n      \"     [comment and this is a comment too]\",\n      \"  | Date/Time\",\n      \"  [operator&special -] [variable now] [operator =] [tag DateTime][operator .][property now]\",\n      \"  [tag strong][operator&special =] [variable now]\",\n      \"  [operator&special -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][property parse]([string \\\"December 31, 2006\\\"])\",\n      \"     [operator&special =][string \\\"Happy\\\"]\",\n      \"     [operator&special =][string \\\"Belated\\\"]\",\n      \"     [operator&special =][string \\\"Birthday\\\"]\");\n\n  MT(\"multilineComment\",\n      \"[comment /]\",\n      \"  [comment Multiline]\",\n      \"  [comment Comment]\");\n\n  MT(\"hamlAfterRubyTag\",\n    \"[attribute&qualifier .block]\",\n    \"  [tag strong][operator&special =] [variable now]\",\n    \"  [attribute&qualifier .test]\",\n    \"     [operator&special =][variable now]\",\n    \"  [attribute&qualifier .right]\");\n\n  MT(\"stretchedRuby\",\n     \"[operator&special =] [variable puts] [string \\\"Hello\\\"],\",\n     \"   [string \\\"World\\\"]\");\n\n  MT(\"interpolationInHashAttribute\",\n     \"[tag div]{[attribute id] = [string \\\"]#{[variable test]}[string _]#{[variable ting]}[string \\\"]} test\");\n\n  MT(\"interpolationInHTMLAttribute\",\n     \"[tag div]([attribute title]=[string \\\"]#{[variable test]}[string _]#{[variable ting]()}[string \\\"]) Test\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/smalltalk/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Smalltalk mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"smalltalk.js\"></script>\n<style>\n      .CodeMirror {border: 2px solid #dee; border-right-width: 10px;}\n      .CodeMirror-gutter {border: none; background: #dee;}\n      .CodeMirror-gutter pre {color: white; font-weight: bold;}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Smalltalk</a>\n  </ul>\n</div>\n\n<article>\n<h2>Smalltalk mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n\" \n    This is a test of the Smalltalk code\n\"\nSeaside.WAComponent subclass: #MyCounter [\n    | count |\n    MyCounter class &gt;&gt; canBeRoot [ ^true ]\n\n    initialize [\n        super initialize.\n        count := 0.\n    ]\n    states [ ^{ self } ]\n    renderContentOn: html [\n        html heading: count.\n        html anchor callback: [ count := count + 1 ]; with: '++'.\n        html space.\n        html anchor callback: [ count := count - 1 ]; with: '--'.\n    ]\n]\n\nMyCounter registerAsApplication: 'mycounter'\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-stsrc\",\n        indentUnit: 4\n      });\n    </script>\n\n    <p>Simple Smalltalk mode.</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-stsrc</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/smalltalk/smalltalk.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode('smalltalk', function(config) {\n\n  var specialChars = /[+\\-\\/\\\\*~<>=@%|&?!.,:;^]/;\n  var keywords = /true|false|nil|self|super|thisContext/;\n\n  var Context = function(tokenizer, parent) {\n    this.next = tokenizer;\n    this.parent = parent;\n  };\n\n  var Token = function(name, context, eos) {\n    this.name = name;\n    this.context = context;\n    this.eos = eos;\n  };\n\n  var State = function() {\n    this.context = new Context(next, null);\n    this.expectVariable = true;\n    this.indentation = 0;\n    this.userIndentationDelta = 0;\n  };\n\n  State.prototype.userIndent = function(indentation) {\n    this.userIndentationDelta = indentation > 0 ? (indentation / config.indentUnit - this.indentation) : 0;\n  };\n\n  var next = function(stream, context, state) {\n    var token = new Token(null, context, false);\n    var aChar = stream.next();\n\n    if (aChar === '\"') {\n      token = nextComment(stream, new Context(nextComment, context));\n\n    } else if (aChar === '\\'') {\n      token = nextString(stream, new Context(nextString, context));\n\n    } else if (aChar === '#') {\n      if (stream.peek() === '\\'') {\n        stream.next();\n        token = nextSymbol(stream, new Context(nextSymbol, context));\n      } else {\n        if (stream.eatWhile(/[^\\s.{}\\[\\]()]/))\n          token.name = 'string-2';\n        else\n          token.name = 'meta';\n      }\n\n    } else if (aChar === '$') {\n      if (stream.next() === '<') {\n        stream.eatWhile(/[^\\s>]/);\n        stream.next();\n      }\n      token.name = 'string-2';\n\n    } else if (aChar === '|' && state.expectVariable) {\n      token.context = new Context(nextTemporaries, context);\n\n    } else if (/[\\[\\]{}()]/.test(aChar)) {\n      token.name = 'bracket';\n      token.eos = /[\\[{(]/.test(aChar);\n\n      if (aChar === '[') {\n        state.indentation++;\n      } else if (aChar === ']') {\n        state.indentation = Math.max(0, state.indentation - 1);\n      }\n\n    } else if (specialChars.test(aChar)) {\n      stream.eatWhile(specialChars);\n      token.name = 'operator';\n      token.eos = aChar !== ';'; // ; cascaded message expression\n\n    } else if (/\\d/.test(aChar)) {\n      stream.eatWhile(/[\\w\\d]/);\n      token.name = 'number';\n\n    } else if (/[\\w_]/.test(aChar)) {\n      stream.eatWhile(/[\\w\\d_]/);\n      token.name = state.expectVariable ? (keywords.test(stream.current()) ? 'keyword' : 'variable') : null;\n\n    } else {\n      token.eos = state.expectVariable;\n    }\n\n    return token;\n  };\n\n  var nextComment = function(stream, context) {\n    stream.eatWhile(/[^\"]/);\n    return new Token('comment', stream.eat('\"') ? context.parent : context, true);\n  };\n\n  var nextString = function(stream, context) {\n    stream.eatWhile(/[^']/);\n    return new Token('string', stream.eat('\\'') ? context.parent : context, false);\n  };\n\n  var nextSymbol = function(stream, context) {\n    stream.eatWhile(/[^']/);\n    return new Token('string-2', stream.eat('\\'') ? context.parent : context, false);\n  };\n\n  var nextTemporaries = function(stream, context) {\n    var token = new Token(null, context, false);\n    var aChar = stream.next();\n\n    if (aChar === '|') {\n      token.context = context.parent;\n      token.eos = true;\n\n    } else {\n      stream.eatWhile(/[^|]/);\n      token.name = 'variable';\n    }\n\n    return token;\n  };\n\n  return {\n    startState: function() {\n      return new State;\n    },\n\n    token: function(stream, state) {\n      state.userIndent(stream.indentation());\n\n      if (stream.eatSpace()) {\n        return null;\n      }\n\n      var token = state.context.next(stream, state.context, state);\n      state.context = token.context;\n      state.expectVariable = token.eos;\n\n      return token.name;\n    },\n\n    blankLine: function(state) {\n      state.userIndent(0);\n    },\n\n    indent: function(state, textAfter) {\n      var i = state.context.next === next && textAfter && textAfter.charAt(0) === ']' ? -1 : state.userIndentationDelta;\n      return (state.indentation + i) * config.indentUnit;\n    },\n\n    electricChars: ']'\n  };\n\n});\n\nCodeMirror.defineMIME('text/x-stsrc', {name: 'smalltalk'});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/smarty/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Smarty mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"smarty.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Smarty</a>\n  </ul>\n</div>\n\n<article>\n<h2>Smarty mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n{extends file=\"parent.tpl\"}\n{include file=\"template.tpl\"}\n\n{* some example Smarty content *}\n{if isset($name) && $name == 'Blog'}\n  This is a {$var}.\n  {$integer = 451}, {$array[] = \"a\"}, {$stringvar = \"string\"}\n  {assign var='bob' value=$var.prop}\n{elseif $name == $foo}\n  {function name=menu level=0}\n    {foreach $data as $entry}\n      {if is_array($entry)}\n        - {$entry@key}\n        {menu data=$entry level=$level+1}\n      {else}\n        {$entry}\n      {/if}\n    {/foreach}\n  {/function}\n{/if}</textarea></form>\n\n<p>Mode for Smarty version 2 or 3, which allows for custom delimiter tags.</p>\n\n<p>Several configuration parameters are supported:</p>\n\n<ul>\n  <li><code>leftDelimiter</code> and <code>rightDelimiter</code>,\n  which should be strings that determine where the Smarty syntax\n  starts and ends.</li>\n  <li><code>version</code>, which should be 2 or 3.</li>\n  <li><code>baseMode</code>, which can be a mode spec\n  like <code>\"text/html\"</code> to set a different background mode.</li>\n</ul>\n\n<p><strong>MIME types defined:</strong> <code>text/x-smarty</code></p>\n\n<h3>Smarty 2, custom delimiters</h3>\n\n<form><textarea id=\"code2\" name=\"code2\">\n{--extends file=\"parent.tpl\"--}\n{--include file=\"template.tpl\"--}\n\n{--* some example Smarty content *--}\n{--if isset($name) && $name == 'Blog'--}\n  This is a {--$var--}.\n  {--$integer = 451--}, {--$array[] = \"a\"--}, {--$stringvar = \"string\"--}\n  {--assign var='bob' value=$var.prop--}\n{--elseif $name == $foo--}\n  {--function name=menu level=0--}\n    {--foreach $data as $entry--}\n      {--if is_array($entry)--}\n        - {--$entry@key--}\n        {--menu data=$entry level=$level+1--}\n      {--else--}\n        {--$entry--}\n      {--/if--}\n    {--/foreach--}\n  {--/function--}\n{--/if--}</textarea></form>\n\n<h3>Smarty 3</h3>\n\n<textarea id=\"code3\" name=\"code3\">\nNested tags {$foo={counter one=1 two={inception}}+3} are now valid in Smarty 3.\n\n<script>\nfunction test() {\n  console.log(\"Smarty 3 permits single curly braces followed by whitespace to NOT slip into Smarty mode.\");\n}\n</script>\n\n{assign var=foo value=[1,2,3]}\n{assign var=foo value=['y'=>'yellow','b'=>'blue']}\n{assign var=foo value=[1,[9,8],3]}\n\n{$foo=$bar+2} {* a comment *}\n{$foo.bar=1}  {* another comment *}\n{$foo = myfunct(($x+$y)*3)}\n{$foo = strlen($bar)}\n{$foo.bar.baz=1}, {$foo[]=1}\n\nSmarty \"dot\" syntax (note: embedded {} are used to address ambiguities):\n\n{$foo.a.b.c}      => $foo['a']['b']['c']\n{$foo.a.$b.c}     => $foo['a'][$b]['c']\n{$foo.a.{$b+4}.c} => $foo['a'][$b+4]['c']\n{$foo.a.{$b.c}}   => $foo['a'][$b['c']]\n\n{$object->method1($x)->method2($y)}</textarea>\n\n<script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n  lineNumbers: true,\n  mode: \"smarty\"\n});\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code2\"), {\n  lineNumbers: true,\n  mode: {\n    name: \"smarty\",\n    leftDelimiter: \"{--\",\n    rightDelimiter: \"--}\"\n  }\n});\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"code3\"), {\n  lineNumbers: true,\n  mode: {name: \"smarty\", version: 3, baseMode: \"text/html\"}\n});\n</script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/smarty/smarty.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**\n * Smarty 2 and 3 mode.\n */\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"smarty\", function(config, parserConf) {\n    var rightDelimiter = parserConf.rightDelimiter || \"}\";\n    var leftDelimiter = parserConf.leftDelimiter || \"{\";\n    var version = parserConf.version || 2;\n    var baseMode = CodeMirror.getMode(config, parserConf.baseMode || \"null\");\n\n    var keyFunctions = [\"debug\", \"extends\", \"function\", \"include\", \"literal\"];\n    var regs = {\n      operatorChars: /[+\\-*&%=<>!?]/,\n      validIdentifier: /[a-zA-Z0-9_]/,\n      stringChar: /['\"]/\n    };\n\n    var last;\n    function cont(style, lastType) {\n      last = lastType;\n      return style;\n    }\n\n    function chain(stream, state, parser) {\n      state.tokenize = parser;\n      return parser(stream, state);\n    }\n\n    // Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode\n    function doesNotCount(stream, pos) {\n      if (pos == null) pos = stream.pos;\n      return version === 3 && leftDelimiter == \"{\" &&\n        (pos == stream.string.length || /\\s/.test(stream.string.charAt(pos)));\n    }\n\n    function tokenTop(stream, state) {\n      var string = stream.string;\n      for (var scan = stream.pos;;) {\n        var nextMatch = string.indexOf(leftDelimiter, scan);\n        scan = nextMatch + leftDelimiter.length;\n        if (nextMatch == -1 || !doesNotCount(stream, nextMatch + leftDelimiter.length)) break;\n      }\n      if (nextMatch == stream.pos) {\n        stream.match(leftDelimiter);\n        if (stream.eat(\"*\")) {\n          return chain(stream, state, tokenBlock(\"comment\", \"*\" + rightDelimiter));\n        } else {\n          state.depth++;\n          state.tokenize = tokenSmarty;\n          last = \"startTag\";\n          return \"tag\";\n        }\n      }\n\n      if (nextMatch > -1) stream.string = string.slice(0, nextMatch);\n      var token = baseMode.token(stream, state.base);\n      if (nextMatch > -1) stream.string = string;\n      return token;\n    }\n\n    // parsing Smarty content\n    function tokenSmarty(stream, state) {\n      if (stream.match(rightDelimiter, true)) {\n        if (version === 3) {\n          state.depth--;\n          if (state.depth <= 0) {\n            state.tokenize = tokenTop;\n          }\n        } else {\n          state.tokenize = tokenTop;\n        }\n        return cont(\"tag\", null);\n      }\n\n      if (stream.match(leftDelimiter, true)) {\n        state.depth++;\n        return cont(\"tag\", \"startTag\");\n      }\n\n      var ch = stream.next();\n      if (ch == \"$\") {\n        stream.eatWhile(regs.validIdentifier);\n        return cont(\"variable-2\", \"variable\");\n      } else if (ch == \"|\") {\n        return cont(\"operator\", \"pipe\");\n      } else if (ch == \".\") {\n        return cont(\"operator\", \"property\");\n      } else if (regs.stringChar.test(ch)) {\n        state.tokenize = tokenAttribute(ch);\n        return cont(\"string\", \"string\");\n      } else if (regs.operatorChars.test(ch)) {\n        stream.eatWhile(regs.operatorChars);\n        return cont(\"operator\", \"operator\");\n      } else if (ch == \"[\" || ch == \"]\") {\n        return cont(\"bracket\", \"bracket\");\n      } else if (ch == \"(\" || ch == \")\") {\n        return cont(\"bracket\", \"operator\");\n      } else if (/\\d/.test(ch)) {\n        stream.eatWhile(/\\d/);\n        return cont(\"number\", \"number\");\n      } else {\n\n        if (state.last == \"variable\") {\n          if (ch == \"@\") {\n            stream.eatWhile(regs.validIdentifier);\n            return cont(\"property\", \"property\");\n          } else if (ch == \"|\") {\n            stream.eatWhile(regs.validIdentifier);\n            return cont(\"qualifier\", \"modifier\");\n          }\n        } else if (state.last == \"pipe\") {\n          stream.eatWhile(regs.validIdentifier);\n          return cont(\"qualifier\", \"modifier\");\n        } else if (state.last == \"whitespace\") {\n          stream.eatWhile(regs.validIdentifier);\n          return cont(\"attribute\", \"modifier\");\n        } if (state.last == \"property\") {\n          stream.eatWhile(regs.validIdentifier);\n          return cont(\"property\", null);\n        } else if (/\\s/.test(ch)) {\n          last = \"whitespace\";\n          return null;\n        }\n\n        var str = \"\";\n        if (ch != \"/\") {\n          str += ch;\n        }\n        var c = null;\n        while (c = stream.eat(regs.validIdentifier)) {\n          str += c;\n        }\n        for (var i=0, j=keyFunctions.length; i<j; i++) {\n          if (keyFunctions[i] == str) {\n            return cont(\"keyword\", \"keyword\");\n          }\n        }\n        if (/\\s/.test(ch)) {\n          return null;\n        }\n        return cont(\"tag\", \"tag\");\n      }\n    }\n\n    function tokenAttribute(quote) {\n      return function(stream, state) {\n        var prevChar = null;\n        var currChar = null;\n        while (!stream.eol()) {\n          currChar = stream.peek();\n          if (stream.next() == quote && prevChar !== '\\\\') {\n            state.tokenize = tokenSmarty;\n            break;\n          }\n          prevChar = currChar;\n        }\n        return \"string\";\n      };\n    }\n\n    function tokenBlock(style, terminator) {\n      return function(stream, state) {\n        while (!stream.eol()) {\n          if (stream.match(terminator)) {\n            state.tokenize = tokenTop;\n            break;\n          }\n          stream.next();\n        }\n        return style;\n      };\n    }\n\n    return {\n      startState: function() {\n        return {\n          base: CodeMirror.startState(baseMode),\n          tokenize: tokenTop,\n          last: null,\n          depth: 0\n        };\n      },\n      copyState: function(state) {\n        return {\n          base: CodeMirror.copyState(baseMode, state.base),\n          tokenize: state.tokenize,\n          last: state.last,\n          depth: state.depth\n        };\n      },\n      innerMode: function(state) {\n        if (state.tokenize == tokenTop)\n          return {mode: baseMode, state: state.base};\n      },\n      token: function(stream, state) {\n        var style = state.tokenize(stream, state);\n        state.last = last;\n        return style;\n      },\n      indent: function(state, text, line) {\n        if (state.tokenize == tokenTop && baseMode.indent)\n          return baseMode.indent(state.base, text, line);\n        else\n          return CodeMirror.Pass;\n      },\n      blockCommentStart: leftDelimiter + \"*\",\n      blockCommentEnd: \"*\" + rightDelimiter\n    };\n  });\n\n  CodeMirror.defineMIME(\"text/x-smarty\", \"smarty\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/solr/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Solr mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"solr.js\"></script>\n<style>\n  .CodeMirror {\n    border-top: 1px solid black;\n    border-bottom: 1px solid black;\n  }\n\n  .CodeMirror .cm-operator {\n    color: orange;\n  }\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Solr</a>\n  </ul>\n</div>\n\n<article>\n  <h2>Solr mode</h2>\n\n  <div>\n    <textarea id=\"code\" name=\"code\">author:Camus\n\ntitle:\"The Rebel\" and author:Camus\n\nphilosophy:Existentialism -author:Kierkegaard\n\nhardToSpell:Dostoevsky~\n\npublished:[194* TO 1960] and author:(Sartre or \"Simone de Beauvoir\")</textarea>\n  </div>\n\n  <script>\n    var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n      mode: 'solr',\n      lineNumbers: true\n    });\n  </script>\n\n  <p><strong>MIME types defined:</strong> <code>text/x-solr</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/solr/solr.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"solr\", function() {\n  \"use strict\";\n\n  var isStringChar = /[^\\s\\|\\!\\+\\-\\*\\?\\~\\^\\&\\:\\(\\)\\[\\]\\{\\}\\\"\\\\]/;\n  var isOperatorChar = /[\\|\\!\\+\\-\\*\\?\\~\\^\\&]/;\n  var isOperatorString = /^(OR|AND|NOT|TO)$/i;\n\n  function isNumber(word) {\n    return parseFloat(word).toString() === word;\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) break;\n        escaped = !escaped && next == \"\\\\\";\n      }\n\n      if (!escaped) state.tokenize = tokenBase;\n      return \"string\";\n    };\n  }\n\n  function tokenOperator(operator) {\n    return function(stream, state) {\n      var style = \"operator\";\n      if (operator == \"+\")\n        style += \" positive\";\n      else if (operator == \"-\")\n        style += \" negative\";\n      else if (operator == \"|\")\n        stream.eat(/\\|/);\n      else if (operator == \"&\")\n        stream.eat(/\\&/);\n      else if (operator == \"^\")\n        style += \" boost\";\n\n      state.tokenize = tokenBase;\n      return style;\n    };\n  }\n\n  function tokenWord(ch) {\n    return function(stream, state) {\n      var word = ch;\n      while ((ch = stream.peek()) && ch.match(isStringChar) != null) {\n        word += stream.next();\n      }\n\n      state.tokenize = tokenBase;\n      if (isOperatorString.test(word))\n        return \"operator\";\n      else if (isNumber(word))\n        return \"number\";\n      else if (stream.peek() == \":\")\n        return \"field\";\n      else\n        return \"string\";\n    };\n  }\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (ch == '\"')\n      state.tokenize = tokenString(ch);\n    else if (isOperatorChar.test(ch))\n      state.tokenize = tokenOperator(ch);\n    else if (isStringChar.test(ch))\n      state.tokenize = tokenWord(ch);\n\n    return (state.tokenize != tokenBase) ? state.tokenize(stream, state) : null;\n  }\n\n  return {\n    startState: function() {\n      return {\n        tokenize: tokenBase\n      };\n    },\n\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      return state.tokenize(stream, state);\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-solr\", \"solr\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/soy/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Soy (Closure Template) mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../css/css.js\"></script>\n<script src=\"soy.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Soy (Closure Template)</a>\n  </ul>\n</div>\n\n<article>\n<h2>Soy (Closure Template) mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n{namespace example}\n\n/**\n * Says hello to the world.\n */\n{template .helloWorld}\n  {@param name: string}\n  {@param? score: number}\n  Hello <b>{$name}</b>!\n  <div>\n    {if $score}\n      <em>{$score} points</em>\n    {else}\n      no score\n    {/if}\n  </div>\n{/template}\n\n{template .alertHelloWorld kind=\"js\"}\n  alert('Hello World');\n{/template}\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-soy\",\n        indentUnit: 2,\n        indentWithTabs: false\n      });\n    </script>\n\n    <p>A mode for <a href=\"https://developers.google.com/closure/templates/\">Closure Templates</a> (Soy).</p>\n    <p><strong>MIME type defined:</strong> <code>text/x-soy</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/soy/soy.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../htmlmixed/htmlmixed\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../htmlmixed/htmlmixed\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var indentingTags = [\"template\", \"literal\", \"msg\", \"fallbackmsg\", \"let\", \"if\", \"elseif\",\n                       \"else\", \"switch\", \"case\", \"default\", \"foreach\", \"ifempty\", \"for\",\n                       \"call\", \"param\", \"deltemplate\", \"delcall\", \"log\"];\n\n  CodeMirror.defineMode(\"soy\", function(config) {\n    var textMode = CodeMirror.getMode(config, \"text/plain\");\n    var modes = {\n      html: CodeMirror.getMode(config, {name: \"text/html\", multilineTagIndentFactor: 2, multilineTagIndentPastTag: false}),\n      attributes: textMode,\n      text: textMode,\n      uri: textMode,\n      trusted_resource_uri: textMode,\n      css: CodeMirror.getMode(config, \"text/css\"),\n      js: CodeMirror.getMode(config, {name: \"text/javascript\", statementIndent: 2 * config.indentUnit})\n    };\n\n    function last(array) {\n      return array[array.length - 1];\n    }\n\n    function tokenUntil(stream, state, untilRegExp) {\n      if (stream.sol()) {\n        for (var indent = 0; indent < state.indent; indent++) {\n          if (!stream.eat(/\\s/)) break;\n        }\n        if (indent) return null;\n      }\n      var oldString = stream.string;\n      var match = untilRegExp.exec(oldString.substr(stream.pos));\n      if (match) {\n        // We don't use backUp because it backs up just the position, not the state.\n        // This uses an undocumented API.\n        stream.string = oldString.substr(0, stream.pos + match.index);\n      }\n      var result = stream.hideFirstChars(state.indent, function() {\n        var localState = last(state.localStates);\n        return localState.mode.token(stream, localState.state);\n      });\n      stream.string = oldString;\n      return result;\n    }\n\n    function contains(list, element) {\n      while (list) {\n        if (list.element === element) return true;\n        list = list.next;\n      }\n      return false;\n    }\n\n    function prepend(list, element) {\n      return {\n        element: element,\n        next: list\n      };\n    }\n\n    // Reference a variable `name` in `list`.\n    // Let `loose` be truthy to ignore missing identifiers.\n    function ref(list, name, loose) {\n      return contains(list, name) ? \"variable-2\" : (loose ? \"variable\" : \"variable-2 error\");\n    }\n\n    function popscope(state) {\n      if (state.scopes) {\n        state.variables = state.scopes.element;\n        state.scopes = state.scopes.next;\n      }\n    }\n\n    return {\n      startState: function() {\n        return {\n          kind: [],\n          kindTag: [],\n          soyState: [],\n          templates: null,\n          variables: prepend(null, 'ij'),\n          scopes: null,\n          indent: 0,\n          quoteKind: null,\n          localStates: [{\n            mode: modes.html,\n            state: CodeMirror.startState(modes.html)\n          }]\n        };\n      },\n\n      copyState: function(state) {\n        return {\n          tag: state.tag, // Last seen Soy tag.\n          kind: state.kind.concat([]), // Values of kind=\"\" attributes.\n          kindTag: state.kindTag.concat([]), // Opened tags with kind=\"\" attributes.\n          soyState: state.soyState.concat([]),\n          templates: state.templates,\n          variables: state.variables,\n          scopes: state.scopes,\n          indent: state.indent, // Indentation of the following line.\n          quoteKind: state.quoteKind,\n          localStates: state.localStates.map(function(localState) {\n            return {\n              mode: localState.mode,\n              state: CodeMirror.copyState(localState.mode, localState.state)\n            };\n          })\n        };\n      },\n\n      token: function(stream, state) {\n        var match;\n\n        switch (last(state.soyState)) {\n          case \"comment\":\n            if (stream.match(/^.*?\\*\\//)) {\n              state.soyState.pop();\n            } else {\n              stream.skipToEnd();\n            }\n            if (!state.scopes) {\n              var paramRe = /@param\\??\\s+(\\S+)/g;\n              var current = stream.current();\n              for (var match; (match = paramRe.exec(current)); ) {\n                state.variables = prepend(state.variables, match[1]);\n              }\n            }\n            return \"comment\";\n\n          case \"string\":\n            var match = stream.match(/^.*?([\"']|\\\\[\\s\\S])/);\n            if (!match) {\n              stream.skipToEnd();\n            } else if (match[1] == state.quoteKind) {\n              state.quoteKind = null;\n              state.soyState.pop();\n            }\n            return \"string\";\n        }\n\n        if (!state.soyState.length || last(state.soyState) != \"literal\") {\n          if (stream.match(/^\\/\\*/)) {\n            state.soyState.push(\"comment\");\n            return \"comment\";\n          } else if (stream.match(stream.sol() ? /^\\s*\\/\\/.*/ : /^\\s+\\/\\/.*/)) {\n            return \"comment\";\n          }\n        }\n\n        switch (last(state.soyState)) {\n          case \"templ-def\":\n            if (match = stream.match(/^\\.?([\\w]+(?!\\.[\\w]+)*)/)) {\n              state.templates = prepend(state.templates, match[1]);\n              state.scopes = prepend(state.scopes, state.variables);\n              state.soyState.pop();\n              return \"def\";\n            }\n            stream.next();\n            return null;\n\n          case \"templ-ref\":\n            if (match = stream.match(/(\\.?[a-zA-Z_][a-zA-Z_0-9]+)+/)) {\n              state.soyState.pop();\n              // If the first character is '.', it can only be a local template.\n              if (match[0][0] == '.') {\n                return \"variable-2\"\n              }\n              // Otherwise\n              return \"variable\";\n            }\n            stream.next();\n            return null;\n\n          case \"namespace-def\":\n            if (match = stream.match(/^\\.?([\\w\\.]+)/)) {\n              state.soyState.pop();\n              return \"variable\";\n            }\n            stream.next();\n            return null;\n\n          case \"param-def\":\n            if (match = stream.match(/^\\w+/)) {\n              state.variables = prepend(state.variables, match[0]);\n              state.soyState.pop();\n              state.soyState.push(\"param-type\");\n              return \"def\";\n            }\n            stream.next();\n            return null;\n\n          case \"param-ref\":\n            if (match = stream.match(/^\\w+/)) {\n              state.soyState.pop();\n              return \"property\";\n            }\n            stream.next();\n            return null;\n\n          case \"param-type\":\n            if (stream.peek() == \"}\") {\n              state.soyState.pop();\n              return null;\n            }\n            if (stream.eatWhile(/^([\\w]+|[?])/)) {\n              return \"type\";\n            }\n            stream.next();\n            return null;\n\n          case \"var-def\":\n            if (match = stream.match(/^\\$([\\w]+)/)) {\n              state.variables = prepend(state.variables, match[1]);\n              state.soyState.pop();\n              return \"def\";\n            }\n            stream.next();\n            return null;\n\n          case \"tag\":\n            if (stream.match(/^\\/?}/)) {\n              if (state.tag == \"/template\" || state.tag == \"/deltemplate\") {\n                popscope(state);\n                state.variables = prepend(null, 'ij');\n                state.indent = 0;\n              } else {\n                if (state.tag == \"/for\" || state.tag == \"/foreach\") {\n                  popscope(state);\n                }\n                state.indent -= config.indentUnit *\n                    (stream.current() == \"/}\" || indentingTags.indexOf(state.tag) == -1 ? 2 : 1);\n              }\n              state.soyState.pop();\n              return \"keyword\";\n            } else if (stream.match(/^([\\w?]+)(?==)/)) {\n              if (stream.current() == \"kind\" && (match = stream.match(/^=\"([^\"]+)/, false))) {\n                var kind = match[1];\n                state.kind.push(kind);\n                state.kindTag.push(state.tag);\n                var mode = modes[kind] || modes.html;\n                var localState = last(state.localStates);\n                if (localState.mode.indent) {\n                  state.indent += localState.mode.indent(localState.state, \"\", \"\");\n                }\n                state.localStates.push({\n                  mode: mode,\n                  state: CodeMirror.startState(mode)\n                });\n              }\n              return \"attribute\";\n            } else if (match = stream.match(/([\\w]+)(?=\\()/)) {\n              return \"variable callee\";\n            } else if (match = stream.match(/^[\"']/)) {\n              state.soyState.push(\"string\");\n              state.quoteKind = match;\n              return \"string\";\n            }\n            if (stream.match(/(null|true|false)(?!\\w)/) ||\n              stream.match(/0x([0-9a-fA-F]{2,})/) ||\n              stream.match(/-?([0-9]*[.])?[0-9]+(e[0-9]*)?/)) {\n              return \"atom\";\n            }\n            if (stream.match(/(\\||[+\\-*\\/%]|[=!]=|\\?:|[<>]=?)/)) {\n              // Tokenize filter, binary, null propagator, and equality operators.\n              return \"operator\";\n            }\n            if (match = stream.match(/^\\$([\\w]+)/)) {\n              return ref(state.variables, match[1]);\n            }\n            if (match = stream.match(/^\\w+/)) {\n              return /^(?:as|and|or|not|in)$/.test(match[0]) ? \"keyword\" : null;\n            }\n            stream.next();\n            return null;\n\n          case \"literal\":\n            if (stream.match(/^(?=\\{\\/literal})/)) {\n              state.indent -= config.indentUnit;\n              state.soyState.pop();\n              return this.token(stream, state);\n            }\n            return tokenUntil(stream, state, /\\{\\/literal}/);\n        }\n\n        if (stream.match(/^\\{literal}/)) {\n          state.indent += config.indentUnit;\n          state.soyState.push(\"literal\");\n          return \"keyword\";\n\n        // A tag-keyword must be followed by whitespace, comment or a closing tag.\n        } else if (match = stream.match(/^\\{([/@\\\\]?\\w+\\??)(?=$|[\\s}]|\\/[/*])/)) {\n          if (match[1] != \"/switch\")\n            state.indent += (/^(\\/|(else|elseif|ifempty|case|fallbackmsg|default)$)/.test(match[1]) && state.tag != \"switch\" ? 1 : 2) * config.indentUnit;\n          state.tag = match[1];\n          if (state.tag == \"/\" + last(state.kindTag)) {\n            // We found the tag that opened the current kind=\"\".\n            state.kind.pop();\n            state.kindTag.pop();\n            state.localStates.pop();\n            var localState = last(state.localStates);\n            if (localState.mode.indent) {\n              state.indent -= localState.mode.indent(localState.state, \"\", \"\");\n            }\n          }\n          state.soyState.push(\"tag\");\n          if (state.tag == \"template\" || state.tag == \"deltemplate\") {\n            state.soyState.push(\"templ-def\");\n          } else if (state.tag == \"call\" || state.tag == \"delcall\") {\n            state.soyState.push(\"templ-ref\");\n          } else if (state.tag == \"let\") {\n            state.soyState.push(\"var-def\");\n          } else if (state.tag == \"for\" || state.tag == \"foreach\") {\n            state.scopes = prepend(state.scopes, state.variables);\n            state.soyState.push(\"var-def\");\n          } else if (state.tag == \"namespace\") {\n            state.soyState.push(\"namespace-def\");\n            if (!state.scopes) {\n              state.variables = prepend(null, 'ij');\n            }\n          } else if (state.tag.match(/^@(?:param\\??|inject|prop)/)) {\n            state.soyState.push(\"param-def\");\n          } else if (state.tag.match(/^(?:param)/)) {\n            state.soyState.push(\"param-ref\");\n          }\n          return \"keyword\";\n\n        // Not a tag-keyword; it's an implicit print tag.\n        } else if (stream.eat('{')) {\n          state.tag = \"print\";\n          state.indent += 2 * config.indentUnit;\n          state.soyState.push(\"tag\");\n          return \"keyword\";\n        }\n\n        return tokenUntil(stream, state, /\\{|\\s+\\/\\/|\\/\\*/);\n      },\n\n      indent: function(state, textAfter, line) {\n        var indent = state.indent, top = last(state.soyState);\n        if (top == \"comment\") return CodeMirror.Pass;\n\n        if (top == \"literal\") {\n          if (/^\\{\\/literal}/.test(textAfter)) indent -= config.indentUnit;\n        } else {\n          if (/^\\s*\\{\\/(template|deltemplate)\\b/.test(textAfter)) return 0;\n          if (/^\\{(\\/|(fallbackmsg|elseif|else|ifempty)\\b)/.test(textAfter)) indent -= config.indentUnit;\n          if (state.tag != \"switch\" && /^\\{(case|default)\\b/.test(textAfter)) indent -= config.indentUnit;\n          if (/^\\{\\/switch\\b/.test(textAfter)) indent -= config.indentUnit;\n        }\n        var localState = last(state.localStates);\n        if (indent && localState.mode.indent) {\n          indent += localState.mode.indent(localState.state, textAfter, line);\n        }\n        return indent;\n      },\n\n      innerMode: function(state) {\n        if (state.soyState.length && last(state.soyState) != \"literal\") return null;\n        else return last(state.localStates);\n      },\n\n      electricInput: /^\\s*\\{(\\/|\\/template|\\/deltemplate|\\/switch|fallbackmsg|elseif|else|case|default|ifempty|\\/literal\\})$/,\n      lineComment: \"//\",\n      blockCommentStart: \"/*\",\n      blockCommentEnd: \"*/\",\n      blockCommentContinue: \" * \",\n      useInnerComments: false,\n      fold: \"indent\"\n    };\n  }, \"htmlmixed\");\n\n  CodeMirror.registerHelper(\"wordChars\", \"soy\", /[\\w$]/);\n\n  CodeMirror.registerHelper(\"hintWords\", \"soy\", indentingTags.concat(\n      [\"delpackage\", \"namespace\", \"alias\", \"print\", \"css\", \"debugger\"]));\n\n  CodeMirror.defineMIME(\"text/x-soy\", \"soy\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/soy/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"soy\");\n  function MT(name) {test.mode(name, mode, Array.prototype.slice.call(arguments, 1));}\n\n  // Test of small keywords and words containing them.\n  MT('keywords-test',\n     '[keyword {] [keyword as] worrying [keyword and] notorious [keyword as]',\n     '    the Fandor[operator -]alias assassin, [keyword or]',\n     '    Corcand cannot fit [keyword in] [keyword }]');\n\n  MT('let-test',\n     '[keyword {template] [def .name][keyword }]',\n     '  [keyword {let] [def $name]: [string \"world\"][keyword /}]',\n     '  [tag&bracket <][tag h1][tag&bracket >]',\n     '    Hello, [keyword {][variable-2 $name][keyword }]',\n     '  [tag&bracket </][tag h1][tag&bracket >]',\n     '[keyword {/template}]',\n     '');\n\n  MT('function-test',\n     '[keyword {] [callee&variable css]([string \"MyClass\"])[keyword }]',\n     '[tag&bracket <][tag input] [attribute value]=[string \"]' +\n     '[keyword {] [callee&variable index]([variable-2&error $list])[keyword }]' +\n        '[string \"][tag&bracket />]');\n\n  MT('namespace-test',\n     '[keyword {namespace] [variable namespace][keyword }]')\n\n  MT('namespace-with-attribute-test',\n     '[keyword {namespace] [variable my.namespace.templates] ' +\n         '[attribute requirecss]=[string \"my.namespace\"][keyword }]');\n\n  MT('operators-test',\n     '[keyword {] [atom 1] [operator ==] [atom 1] [keyword }]',\n     '[keyword {] [atom 1] [operator !=] [atom 2] [keyword }]',\n     '[keyword {] [atom 2] [operator +] [atom 2] [keyword }]',\n     '[keyword {] [atom 2] [operator -] [atom 2] [keyword }]',\n     '[keyword {] [atom 2] [operator *] [atom 2] [keyword }]',\n     '[keyword {] [atom 2] [operator /] [atom 2] [keyword }]',\n     '[keyword {] [atom 2] [operator %] [atom 2] [keyword }]',\n     '[keyword {] [atom 2] [operator <=] [atom 2] [keyword }]',\n     '[keyword {] [atom 2] [operator >=] [atom 2] [keyword }]',\n     '[keyword {] [atom 3] [operator >] [atom 2] [keyword }]',\n     '[keyword {] [atom 2] [operator >] [atom 3] [keyword }]',\n     '[keyword {] [atom null] [operator ?:] [string \"\"] [keyword }]',\n     '[keyword {] [variable-2&error $variable] [operator |] safeHtml [keyword }]')\n\n  MT('primitive-test',\n     '[keyword {] [atom true] [keyword }]',\n     '[keyword {] [atom false] [keyword }]',\n     '[keyword {] truethy [keyword }]',\n     '[keyword {] falsey [keyword }]',\n     '[keyword {] [atom 42] [keyword }]',\n     '[keyword {] [atom .42] [keyword }]',\n     '[keyword {] [atom 0.42] [keyword }]',\n     '[keyword {] [atom -0.42] [keyword }]',\n     '[keyword {] [atom -.2] [keyword }]',\n     '[keyword {] [atom 6.03e23] [keyword }]',\n     '[keyword {] [atom -0.03e0] [keyword }]',\n     '[keyword {] [atom 0x1F] [keyword }]',\n     '[keyword {] [atom 0x1F00BBEA] [keyword }]');\n\n  MT('param-type-test',\n     '[keyword {@param] [def a]: ' +\n         '[type list]<[[[type a]: [type int], ' +\n         '[type b]: [type map]<[type string], ' +\n         '[type bool]>]]>][keyword }]',\n      '[keyword {@param] [def unknown]: [type ?][keyword }]',\n      '[keyword {@param] [def list]: [type list]<[type ?]>[keyword }]');\n\n  MT('undefined-var',\n     '[keyword {][variable-2&error $var]');\n\n  MT('param-scope-test',\n     '[keyword {template] [def .a][keyword }]',\n     '  [keyword {@param] [def x]: [type string][keyword }]',\n     '  [keyword {][variable-2 $x][keyword }]',\n     '[keyword {/template}]',\n     '',\n     '[keyword {template] [def .b][keyword }]',\n     '  [keyword {][variable-2&error $x][keyword }]',\n     '[keyword {/template}]',\n     '');\n\n  MT('if-variable-test',\n     '[keyword {if] [variable-2&error $showThing][keyword }]',\n     '  Yo!',\n     '[keyword {/if}]',\n     '');\n\n  MT('defined-if-variable-test',\n     '[keyword {template] [def .foo][keyword }]',\n     '  [keyword {@param?] [def showThing]: [type bool][keyword }]',\n     '  [keyword {if] [variable-2 $showThing][keyword }]',\n     '    Yo!',\n     '  [keyword {/if}]',\n     '[keyword {/template}]',\n     '');\n\n  MT('template-calls-test',\n     '[keyword {call] [variable-2 .foo][keyword /}]',\n     '[keyword {call] [variable foo][keyword /}]',\n     '[keyword {call] [variable foo][keyword }] [keyword {/call}]',\n     '[keyword {call] [variable first1.second.third_3][keyword /}]',\n     '[keyword {call] [variable first1.second.third_3] [keyword }] [keyword {/call}]',\n     '');\n\n  MT('foreach-scope-test',\n     '[keyword {@param] [def bar]: [type string][keyword }]',\n     '[keyword {foreach] [def $foo] [keyword in] [variable-2&error $foos][keyword }]',\n     '  [keyword {][variable-2 $foo][keyword }]',\n     '[keyword {/foreach}]',\n     '[keyword {][variable-2&error $foo][keyword }]',\n     '[keyword {][variable-2 $bar][keyword }]');\n\n  MT('foreach-ifempty-indent-test',\n     '[keyword {foreach] [def $foo] [keyword in] [variable-2&error $foos][keyword }]',\n     '  something',\n     '[keyword {ifempty}]',\n     '  nothing',\n     '[keyword {/foreach}]',\n     '');\n\n  MT('nested-kind-test',\n     '[keyword {template] [def .foo] [attribute kind]=[string \"html\"][keyword }]',\n     '  [tag&bracket <][tag div][tag&bracket >]',\n     '    [keyword {call] [variable-2 .bar][keyword }]',\n     '      [keyword {param] [property propertyName] [attribute kind]=[string \"js\"][keyword }]',\n     '        [keyword var] [def bar] [operator =] [number 5];',\n     '      [keyword {/param}]',\n     '    [keyword {/call}]',\n     '  [tag&bracket </][tag div][tag&bracket >]',\n     '[keyword {/template}]',\n     '');\n\n  MT('tag-starting-with-function-call-is-not-a-keyword',\n     '[keyword {][callee&variable index]([variable-2&error $foo])[keyword }]',\n     '[keyword {css] [string \"some-class\"][keyword }]',\n     '[keyword {][callee&variable css]([string \"some-class\"])[keyword }]',\n     '');\n\n  MT('allow-missing-colon-in-@param',\n     '[keyword {template] [def .foo][keyword }]',\n     '  [keyword {@param] [def showThing] [type bool][keyword }]',\n     '  [keyword {if] [variable-2 $showThing][keyword }]',\n     '    Yo!',\n     '  [keyword {/if}]',\n     '[keyword {/template}]',\n     '');\n\n  MT('single-quote-strings',\n     '[keyword {][string \"foo\"] [string \\'bar\\'][keyword }]',\n     '');\n\n  MT('literal-comments',\n     '[keyword {literal}]/* comment */ // comment[keyword {/literal}]');\n\n  MT('highlight-command-at-eol',\n     '[keyword {msg]',\n     '    [keyword }]');\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sparql/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: SPARQL mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"sparql.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">SPARQL</a>\n  </ul>\n</div>\n\n<article>\n<h2>SPARQL mode</h2>\n<form><textarea id=\"code\" name=\"code\">\nPREFIX a: &lt;http://www.w3.org/2000/10/annotation-ns#>\nPREFIX dc: &lt;http://purl.org/dc/elements/1.1/>\nPREFIX foaf: &lt;http://xmlns.com/foaf/0.1/>\nPREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#>\n\n# Comment!\n\nSELECT ?given ?family\nWHERE {\n  {\n    ?annot a:annotates &lt;http://www.w3.org/TR/rdf-sparql-query/> .\n    ?annot dc:creator ?c .\n    OPTIONAL {?c foaf:givenName ?given ;\n                 foaf:familyName ?family }\n  } UNION {\n    ?c !foaf:knows/foaf:knows? ?thing.\n    ?thing rdfs\n  } MINUS {\n    ?thing rdfs:label \"剛柔流\"@jp\n  }\n  FILTER isBlank(?c)\n}\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"application/sparql-query\",\n        matchBrackets: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>application/sparql-query</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sparql/sparql.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"sparql\", function(config) {\n  var indentUnit = config.indentUnit;\n  var curPunc;\n\n  function wordRegexp(words) {\n    return new RegExp(\"^(?:\" + words.join(\"|\") + \")$\", \"i\");\n  }\n  var ops = wordRegexp([\"str\", \"lang\", \"langmatches\", \"datatype\", \"bound\", \"sameterm\", \"isiri\", \"isuri\",\n                        \"iri\", \"uri\", \"bnode\", \"count\", \"sum\", \"min\", \"max\", \"avg\", \"sample\",\n                        \"group_concat\", \"rand\", \"abs\", \"ceil\", \"floor\", \"round\", \"concat\", \"substr\", \"strlen\",\n                        \"replace\", \"ucase\", \"lcase\", \"encode_for_uri\", \"contains\", \"strstarts\", \"strends\",\n                        \"strbefore\", \"strafter\", \"year\", \"month\", \"day\", \"hours\", \"minutes\", \"seconds\",\n                        \"timezone\", \"tz\", \"now\", \"uuid\", \"struuid\", \"md5\", \"sha1\", \"sha256\", \"sha384\",\n                        \"sha512\", \"coalesce\", \"if\", \"strlang\", \"strdt\", \"isnumeric\", \"regex\", \"exists\",\n                        \"isblank\", \"isliteral\", \"a\", \"bind\"]);\n  var keywords = wordRegexp([\"base\", \"prefix\", \"select\", \"distinct\", \"reduced\", \"construct\", \"describe\",\n                             \"ask\", \"from\", \"named\", \"where\", \"order\", \"limit\", \"offset\", \"filter\", \"optional\",\n                             \"graph\", \"by\", \"asc\", \"desc\", \"as\", \"having\", \"undef\", \"values\", \"group\",\n                             \"minus\", \"in\", \"not\", \"service\", \"silent\", \"using\", \"insert\", \"delete\", \"union\",\n                             \"true\", \"false\", \"with\",\n                             \"data\", \"copy\", \"to\", \"move\", \"add\", \"create\", \"drop\", \"clear\", \"load\"]);\n  var operatorChars = /[*+\\-<>=&|\\^\\/!\\?]/;\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    curPunc = null;\n    if (ch == \"$\" || ch == \"?\") {\n      if(ch == \"?\" && stream.match(/\\s/, false)){\n        return \"operator\";\n      }\n      stream.match(/^[\\w\\d]*/);\n      return \"variable-2\";\n    }\n    else if (ch == \"<\" && !stream.match(/^[\\s\\u00a0=]/, false)) {\n      stream.match(/^[^\\s\\u00a0>]*>?/);\n      return \"atom\";\n    }\n    else if (ch == \"\\\"\" || ch == \"'\") {\n      state.tokenize = tokenLiteral(ch);\n      return state.tokenize(stream, state);\n    }\n    else if (/[{}\\(\\),\\.;\\[\\]]/.test(ch)) {\n      curPunc = ch;\n      return \"bracket\";\n    }\n    else if (ch == \"#\") {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n    else if (operatorChars.test(ch)) {\n      stream.eatWhile(operatorChars);\n      return \"operator\";\n    }\n    else if (ch == \":\") {\n      stream.eatWhile(/[\\w\\d\\._\\-]/);\n      return \"atom\";\n    }\n    else if (ch == \"@\") {\n      stream.eatWhile(/[a-z\\d\\-]/i);\n      return \"meta\";\n    }\n    else {\n      stream.eatWhile(/[_\\w\\d]/);\n      if (stream.eat(\":\")) {\n        stream.eatWhile(/[\\w\\d_\\-]/);\n        return \"atom\";\n      }\n      var word = stream.current();\n      if (ops.test(word))\n        return \"builtin\";\n      else if (keywords.test(word))\n        return \"keyword\";\n      else\n        return \"variable\";\n    }\n  }\n\n  function tokenLiteral(quote) {\n    return function(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && !escaped) {\n          state.tokenize = tokenBase;\n          break;\n        }\n        escaped = !escaped && ch == \"\\\\\";\n      }\n      return \"string\";\n    };\n  }\n\n  function pushContext(state, type, col) {\n    state.context = {prev: state.context, indent: state.indent, col: col, type: type};\n  }\n  function popContext(state) {\n    state.indent = state.context.indent;\n    state.context = state.context.prev;\n  }\n\n  return {\n    startState: function() {\n      return {tokenize: tokenBase,\n              context: null,\n              indent: 0,\n              col: 0};\n    },\n\n    token: function(stream, state) {\n      if (stream.sol()) {\n        if (state.context && state.context.align == null) state.context.align = false;\n        state.indent = stream.indentation();\n      }\n      if (stream.eatSpace()) return null;\n      var style = state.tokenize(stream, state);\n\n      if (style != \"comment\" && state.context && state.context.align == null && state.context.type != \"pattern\") {\n        state.context.align = true;\n      }\n\n      if (curPunc == \"(\") pushContext(state, \")\", stream.column());\n      else if (curPunc == \"[\") pushContext(state, \"]\", stream.column());\n      else if (curPunc == \"{\") pushContext(state, \"}\", stream.column());\n      else if (/[\\]\\}\\)]/.test(curPunc)) {\n        while (state.context && state.context.type == \"pattern\") popContext(state);\n        if (state.context && curPunc == state.context.type) {\n          popContext(state);\n          if (curPunc == \"}\" && state.context && state.context.type == \"pattern\")\n            popContext(state);\n        }\n      }\n      else if (curPunc == \".\" && state.context && state.context.type == \"pattern\") popContext(state);\n      else if (/atom|string|variable/.test(style) && state.context) {\n        if (/[\\}\\]]/.test(state.context.type))\n          pushContext(state, \"pattern\", stream.column());\n        else if (state.context.type == \"pattern\" && !state.context.align) {\n          state.context.align = true;\n          state.context.col = stream.column();\n        }\n      }\n\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      var firstChar = textAfter && textAfter.charAt(0);\n      var context = state.context;\n      if (/[\\]\\}]/.test(firstChar))\n        while (context && context.type == \"pattern\") context = context.prev;\n\n      var closing = context && firstChar == context.type;\n      if (!context)\n        return 0;\n      else if (context.type == \"pattern\")\n        return context.col;\n      else if (context.align)\n        return context.col + (closing ? 0 : 1);\n      else\n        return context.indent + (closing ? 0 : indentUnit);\n    },\n\n    lineComment: \"#\"\n  };\n});\n\nCodeMirror.defineMIME(\"application/sparql-query\", \"sparql\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/spreadsheet/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Spreadsheet mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"spreadsheet.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Spreadsheet</a>\n  </ul>\n</div>\n\n<article>\n  <h2>Spreadsheet mode</h2>\n  <form><textarea id=\"code\" name=\"code\">=IF(A1:B2, TRUE, FALSE) / 100</textarea></form>\n\n  <script>\n    var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n      lineNumbers: true,\n      matchBrackets: true,\n      extraKeys: {\"Tab\":  \"indentAuto\"}\n    });\n  </script>\n\n  <p><strong>MIME types defined:</strong> <code>text/x-spreadsheet</code>.</p>\n  \n  <h3>The Spreadsheet Mode</h3>\n  <p> Created by <a href=\"https://github.com/robertleeplummerjr\">Robert Plummer</a></p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/spreadsheet/spreadsheet.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"spreadsheet\", function () {\n    return {\n      startState: function () {\n        return {\n          stringType: null,\n          stack: []\n        };\n      },\n      token: function (stream, state) {\n        if (!stream) return;\n\n        //check for state changes\n        if (state.stack.length === 0) {\n          //strings\n          if ((stream.peek() == '\"') || (stream.peek() == \"'\")) {\n            state.stringType = stream.peek();\n            stream.next(); // Skip quote\n            state.stack.unshift(\"string\");\n          }\n        }\n\n        //return state\n        //stack has\n        switch (state.stack[0]) {\n        case \"string\":\n          while (state.stack[0] === \"string\" && !stream.eol()) {\n            if (stream.peek() === state.stringType) {\n              stream.next(); // Skip quote\n              state.stack.shift(); // Clear flag\n            } else if (stream.peek() === \"\\\\\") {\n              stream.next();\n              stream.next();\n            } else {\n              stream.match(/^.[^\\\\\\\"\\']*/);\n            }\n          }\n          return \"string\";\n\n        case \"characterClass\":\n          while (state.stack[0] === \"characterClass\" && !stream.eol()) {\n            if (!(stream.match(/^[^\\]\\\\]+/) || stream.match(/^\\\\./)))\n              state.stack.shift();\n          }\n          return \"operator\";\n        }\n\n        var peek = stream.peek();\n\n        //no stack\n        switch (peek) {\n        case \"[\":\n          stream.next();\n          state.stack.unshift(\"characterClass\");\n          return \"bracket\";\n        case \":\":\n          stream.next();\n          return \"operator\";\n        case \"\\\\\":\n          if (stream.match(/\\\\[a-z]+/)) return \"string-2\";\n          else {\n            stream.next();\n            return \"atom\";\n          }\n        case \".\":\n        case \",\":\n        case \";\":\n        case \"*\":\n        case \"-\":\n        case \"+\":\n        case \"^\":\n        case \"<\":\n        case \"/\":\n        case \"=\":\n          stream.next();\n          return \"atom\";\n        case \"$\":\n          stream.next();\n          return \"builtin\";\n        }\n\n        if (stream.match(/\\d+/)) {\n          if (stream.match(/^\\w+/)) return \"error\";\n          return \"number\";\n        } else if (stream.match(/^[a-zA-Z_]\\w*/)) {\n          if (stream.match(/(?=[\\(.])/, false)) return \"keyword\";\n          return \"variable-2\";\n        } else if ([\"[\", \"]\", \"(\", \")\", \"{\", \"}\"].indexOf(peek) != -1) {\n          stream.next();\n          return \"bracket\";\n        } else if (!stream.eatSpace()) {\n          stream.next();\n        }\n        return null;\n      }\n    };\n  });\n\n  CodeMirror.defineMIME(\"text/x-spreadsheet\", \"spreadsheet\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sql/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: SQL Mode for CodeMirror</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\" />\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"sql.js\"></script>\n<link rel=\"stylesheet\" href=\"../../addon/hint/show-hint.css\" />\n<script src=\"../../addon/hint/show-hint.js\"></script>\n<script src=\"../../addon/hint/sql-hint.js\"></script>\n<style>\n.CodeMirror {\n    border-top: 1px solid black;\n    border-bottom: 1px solid black;\n}\n        </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">SQL Mode for CodeMirror</a>\n  </ul>\n</div>\n\n<article>\n<h2>SQL Mode for CodeMirror</h2>\n<form>\n            <textarea id=\"code\" name=\"code\">-- SQL Mode for CodeMirror\nSELECT SQL_NO_CACHE DISTINCT\n\t\t@var1 AS `val1`, @'val2', @global.'sql_mode',\n\t\t1.1 AS `float_val`, .14 AS `another_float`, 0.09e3 AS `int_with_esp`,\n\t\t0xFA5 AS `hex`, x'fa5' AS `hex2`, 0b101 AS `bin`, b'101' AS `bin2`,\n\t\tDATE '1994-01-01' AS `sql_date`, { T \"1994-01-01\" } AS `odbc_date`,\n\t\t'my string', _utf8'your string', N'her string',\n        TRUE, FALSE, UNKNOWN\n\tFROM DUAL\n\t-- space needed after '--'\n\t# 1 line comment\n\t/* multiline\n\tcomment! */\n\tLIMIT 1 OFFSET 0;\n</textarea>\n            </form>\n            <p><strong>MIME types defined:</strong>\n            <code><a href=\"?mime=text/x-sql\">text/x-sql</a></code>,\n            <code><a href=\"?mime=text/x-mysql\">text/x-mysql</a></code>,\n            <code><a href=\"?mime=text/x-mariadb\">text/x-mariadb</a></code>,\n            <code><a href=\"?mime=text/x-cassandra\">text/x-cassandra</a></code>,\n            <code><a href=\"?mime=text/x-plsql\">text/x-plsql</a></code>,\n            <code><a href=\"?mime=text/x-mssql\">text/x-mssql</a></code>,\n            <code><a href=\"?mime=text/x-hive\">text/x-hive</a></code>,\n            <code><a href=\"?mime=text/x-pgsql\">text/x-pgsql</a></code>,\n            <code><a href=\"?mime=text/x-gql\">text/x-gql</a></code>,\n            <code><a href=\"?mime=text/x-gpsql\">text/x-gpsql</a></code>.\n            <code><a href=\"?mime=text/x-esper\">text/x-esper</a></code>.\n        </p>\n<script>\nwindow.onload = function() {\n  var mime = 'text/x-mariadb';\n  // get mime type\n  if (window.location.href.indexOf('mime=') > -1) {\n    mime = window.location.href.substr(window.location.href.indexOf('mime=') + 5);\n  }\n  window.editor = CodeMirror.fromTextArea(document.getElementById('code'), {\n    mode: mime,\n    indentWithTabs: true,\n    smartIndent: true,\n    lineNumbers: true,\n    matchBrackets : true,\n    autofocus: true,\n    extraKeys: {\"Ctrl-Space\": \"autocomplete\"},\n    hintOptions: {tables: {\n      users: [\"name\", \"score\", \"birthDate\"],\n      countries: [\"name\", \"population\", \"size\"]\n    }}\n  });\n};\n</script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/sql/sql.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"sql\", function(config, parserConfig) {\n  var client         = parserConfig.client || {},\n      atoms          = parserConfig.atoms || {\"false\": true, \"true\": true, \"null\": true},\n      builtin        = parserConfig.builtin || set(defaultBuiltin),\n      keywords       = parserConfig.keywords || set(sqlKeywords),\n      operatorChars  = parserConfig.operatorChars || /^[*+\\-%<>!=&|~^\\/]/,\n      support        = parserConfig.support || {},\n      hooks          = parserConfig.hooks || {},\n      dateSQL        = parserConfig.dateSQL || {\"date\" : true, \"time\" : true, \"timestamp\" : true},\n      backslashStringEscapes = parserConfig.backslashStringEscapes !== false,\n      brackets       = parserConfig.brackets || /^[\\{}\\(\\)\\[\\]]/,\n      punctuation    = parserConfig.punctuation || /^[;.,:]/\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n\n    // call hooks from the mime type\n    if (hooks[ch]) {\n      var result = hooks[ch](stream, state);\n      if (result !== false) return result;\n    }\n\n    if (support.hexNumber &&\n      ((ch == \"0\" && stream.match(/^[xX][0-9a-fA-F]+/))\n      || (ch == \"x\" || ch == \"X\") && stream.match(/^'[0-9a-fA-F]+'/))) {\n      // hex\n      // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html\n      return \"number\";\n    } else if (support.binaryNumber &&\n      (((ch == \"b\" || ch == \"B\") && stream.match(/^'[01]+'/))\n      || (ch == \"0\" && stream.match(/^b[01]+/)))) {\n      // bitstring\n      // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html\n      return \"number\";\n    } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {\n      // numbers\n      // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html\n      stream.match(/^[0-9]*(\\.[0-9]+)?([eE][-+]?[0-9]+)?/);\n      support.decimallessFloat && stream.match(/^\\.(?!\\.)/);\n      return \"number\";\n    } else if (ch == \"?\" && (stream.eatSpace() || stream.eol() || stream.eat(\";\"))) {\n      // placeholders\n      return \"variable-3\";\n    } else if (ch == \"'\" || (ch == '\"' && support.doubleQuote)) {\n      // strings\n      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html\n      state.tokenize = tokenLiteral(ch);\n      return state.tokenize(stream, state);\n    } else if ((((support.nCharCast && (ch == \"n\" || ch == \"N\"))\n        || (support.charsetCast && ch == \"_\" && stream.match(/[a-z][a-z0-9]*/i)))\n        && (stream.peek() == \"'\" || stream.peek() == '\"'))) {\n      // charset casting: _utf8'str', N'str', n'str'\n      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html\n      return \"keyword\";\n    } else if (support.commentSlashSlash && ch == \"/\" && stream.eat(\"/\")) {\n      // 1-line comment\n      stream.skipToEnd();\n      return \"comment\";\n    } else if ((support.commentHash && ch == \"#\")\n        || (ch == \"-\" && stream.eat(\"-\") && (!support.commentSpaceRequired || stream.eat(\" \")))) {\n      // 1-line comments\n      // ref: https://kb.askmonty.org/en/comment-syntax/\n      stream.skipToEnd();\n      return \"comment\";\n    } else if (ch == \"/\" && stream.eat(\"*\")) {\n      // multi-line comments\n      // ref: https://kb.askmonty.org/en/comment-syntax/\n      state.tokenize = tokenComment(1);\n      return state.tokenize(stream, state);\n    } else if (ch == \".\") {\n      // .1 for 0.1\n      if (support.zerolessFloat && stream.match(/^(?:\\d+(?:e[+-]?\\d+)?)/i))\n        return \"number\";\n      if (stream.match(/^\\.+/))\n        return null\n      // .table_name (ODBC)\n      // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html\n      if (support.ODBCdotTable && stream.match(/^[\\w\\d_]+/))\n        return \"variable-2\";\n    } else if (operatorChars.test(ch)) {\n      // operators\n      stream.eatWhile(operatorChars);\n      return \"operator\";\n    } else if (brackets.test(ch)) {\n      // brackets\n      return \"bracket\";\n    } else if (punctuation.test(ch)) {\n      // punctuation\n      stream.eatWhile(punctuation);\n      return \"punctuation\";\n    } else if (ch == '{' &&\n        (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*\"[^\"]*\"( )*}/))) {\n      // dates (weird ODBC syntax)\n      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html\n      return \"number\";\n    } else {\n      stream.eatWhile(/^[_\\w\\d]/);\n      var word = stream.current().toLowerCase();\n      // dates (standard SQL syntax)\n      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html\n      if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+\"[^\"]*\"/)))\n        return \"number\";\n      if (atoms.hasOwnProperty(word)) return \"atom\";\n      if (builtin.hasOwnProperty(word)) return \"builtin\";\n      if (keywords.hasOwnProperty(word)) return \"keyword\";\n      if (client.hasOwnProperty(word)) return \"string-2\";\n      return null;\n    }\n  }\n\n  // 'string', with char specified in quote escaped by '\\'\n  function tokenLiteral(quote) {\n    return function(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && !escaped) {\n          state.tokenize = tokenBase;\n          break;\n        }\n        escaped = backslashStringEscapes && !escaped && ch == \"\\\\\";\n      }\n      return \"string\";\n    };\n  }\n  function tokenComment(depth) {\n    return function(stream, state) {\n      var m = stream.match(/^.*?(\\/\\*|\\*\\/)/)\n      if (!m) stream.skipToEnd()\n      else if (m[1] == \"/*\") state.tokenize = tokenComment(depth + 1)\n      else if (depth > 1) state.tokenize = tokenComment(depth - 1)\n      else state.tokenize = tokenBase\n      return \"comment\"\n    }\n  }\n\n  function pushContext(stream, state, type) {\n    state.context = {\n      prev: state.context,\n      indent: stream.indentation(),\n      col: stream.column(),\n      type: type\n    };\n  }\n\n  function popContext(state) {\n    state.indent = state.context.indent;\n    state.context = state.context.prev;\n  }\n\n  return {\n    startState: function() {\n      return {tokenize: tokenBase, context: null};\n    },\n\n    token: function(stream, state) {\n      if (stream.sol()) {\n        if (state.context && state.context.align == null)\n          state.context.align = false;\n      }\n      if (state.tokenize == tokenBase && stream.eatSpace()) return null;\n\n      var style = state.tokenize(stream, state);\n      if (style == \"comment\") return style;\n\n      if (state.context && state.context.align == null)\n        state.context.align = true;\n\n      var tok = stream.current();\n      if (tok == \"(\")\n        pushContext(stream, state, \")\");\n      else if (tok == \"[\")\n        pushContext(stream, state, \"]\");\n      else if (state.context && state.context.type == tok)\n        popContext(state);\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      var cx = state.context;\n      if (!cx) return CodeMirror.Pass;\n      var closing = textAfter.charAt(0) == cx.type;\n      if (cx.align) return cx.col + (closing ? 0 : 1);\n      else return cx.indent + (closing ? 0 : config.indentUnit);\n    },\n\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    lineComment: support.commentSlashSlash ? \"//\" : support.commentHash ? \"#\" : \"--\",\n    closeBrackets: \"()[]{}''\\\"\\\"``\"\n  };\n});\n\n  // `identifier`\n  function hookIdentifier(stream) {\n    // MySQL/MariaDB identifiers\n    // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html\n    var ch;\n    while ((ch = stream.next()) != null) {\n      if (ch == \"`\" && !stream.eat(\"`\")) return \"variable-2\";\n    }\n    stream.backUp(stream.current().length - 1);\n    return stream.eatWhile(/\\w/) ? \"variable-2\" : null;\n  }\n\n  // \"identifier\"\n  function hookIdentifierDoublequote(stream) {\n    // Standard SQL /SQLite identifiers\n    // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier\n    // ref: http://sqlite.org/lang_keywords.html\n    var ch;\n    while ((ch = stream.next()) != null) {\n      if (ch == \"\\\"\" && !stream.eat(\"\\\"\")) return \"variable-2\";\n    }\n    stream.backUp(stream.current().length - 1);\n    return stream.eatWhile(/\\w/) ? \"variable-2\" : null;\n  }\n\n  // variable token\n  function hookVar(stream) {\n    // variables\n    // @@prefix.varName @varName\n    // varName can be quoted with ` or ' or \"\n    // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html\n    if (stream.eat(\"@\")) {\n      stream.match(/^session\\./);\n      stream.match(/^local\\./);\n      stream.match(/^global\\./);\n    }\n\n    if (stream.eat(\"'\")) {\n      stream.match(/^.*'/);\n      return \"variable-2\";\n    } else if (stream.eat('\"')) {\n      stream.match(/^.*\"/);\n      return \"variable-2\";\n    } else if (stream.eat(\"`\")) {\n      stream.match(/^.*`/);\n      return \"variable-2\";\n    } else if (stream.match(/^[0-9a-zA-Z$\\.\\_]+/)) {\n      return \"variable-2\";\n    }\n    return null;\n  };\n\n  // short client keyword token\n  function hookClient(stream) {\n    // \\N means NULL\n    // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html\n    if (stream.eat(\"N\")) {\n        return \"atom\";\n    }\n    // \\g, etc\n    // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html\n    return stream.match(/^[a-zA-Z.#!?]/) ? \"variable-2\" : null;\n  }\n\n  // these keywords are used by all SQL dialects (however, a mode can still overwrite it)\n  var sqlKeywords = \"alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit \";\n\n  // turn a space-separated list into an array\n  function set(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  var defaultBuiltin = \"bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric\"\n\n  // A generic SQL Mode. It's not a standard, it just try to support what is generally supported\n  CodeMirror.defineMIME(\"text/x-sql\", {\n    name: \"sql\",\n    keywords: set(sqlKeywords + \"begin\"),\n    builtin: set(defaultBuiltin),\n    atoms: set(\"false true null unknown\"),\n    dateSQL: set(\"date time timestamp\"),\n    support: set(\"ODBCdotTable doubleQuote binaryNumber hexNumber\")\n  });\n\n  CodeMirror.defineMIME(\"text/x-mssql\", {\n    name: \"sql\",\n    client: set(\"$partition binary_checksum checksum connectionproperty context_info current_request_id error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big xact_state object_id\"),\n    keywords: set(sqlKeywords + \"begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec go if use index holdlock nolock nowait paglock readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot tablock tablockx updlock with\"),\n    builtin: set(\"bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table \"),\n    atoms: set(\"is not null like and or in left right between inner outer join all any some cross unpivot pivot exists\"),\n    operatorChars: /^[*+\\-%<>!=^\\&|\\/]/,\n    brackets: /^[\\{}\\(\\)]/,\n    punctuation: /^[;.,:/]/,\n    backslashStringEscapes: false,\n    dateSQL: set(\"date datetimeoffset datetime2 smalldatetime datetime time\"),\n    hooks: {\n      \"@\":   hookVar\n    }\n  });\n\n  CodeMirror.defineMIME(\"text/x-mysql\", {\n    name: \"sql\",\n    client: set(\"charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee\"),\n    keywords: set(sqlKeywords + \"accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat\"),\n    builtin: set(\"bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric\"),\n    atoms: set(\"false true null unknown\"),\n    operatorChars: /^[*+\\-%<>!=&|^]/,\n    dateSQL: set(\"date time timestamp\"),\n    support: set(\"ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired\"),\n    hooks: {\n      \"@\":   hookVar,\n      \"`\":   hookIdentifier,\n      \"\\\\\":  hookClient\n    }\n  });\n\n  CodeMirror.defineMIME(\"text/x-mariadb\", {\n    name: \"sql\",\n    client: set(\"charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee\"),\n    keywords: set(sqlKeywords + \"accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat\"),\n    builtin: set(\"bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric\"),\n    atoms: set(\"false true null unknown\"),\n    operatorChars: /^[*+\\-%<>!=&|^]/,\n    dateSQL: set(\"date time timestamp\"),\n    support: set(\"ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired\"),\n    hooks: {\n      \"@\":   hookVar,\n      \"`\":   hookIdentifier,\n      \"\\\\\":  hookClient\n    }\n  });\n\n  // provided by the phpLiteAdmin project - phpliteadmin.org\n  CodeMirror.defineMIME(\"text/x-sqlite\", {\n    name: \"sql\",\n    // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd\n    client: set(\"auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width\"),\n    // ref: http://sqlite.org/lang_keywords.html\n    keywords: set(sqlKeywords + \"abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without\"),\n    // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.\n    builtin: set(\"bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real\"),\n    // ref: http://sqlite.org/syntax/literal-value.html\n    atoms: set(\"null current_date current_time current_timestamp\"),\n    // ref: http://sqlite.org/lang_expr.html#binaryops\n    operatorChars: /^[*+\\-%<>!=&|/~]/,\n    // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.\n    dateSQL: set(\"date time timestamp datetime\"),\n    support: set(\"decimallessFloat zerolessFloat\"),\n    identifierQuote: \"\\\"\",  //ref: http://sqlite.org/lang_keywords.html\n    hooks: {\n      // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam\n      \"@\":   hookVar,\n      \":\":   hookVar,\n      \"?\":   hookVar,\n      \"$\":   hookVar,\n      // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html\n      \"\\\"\":   hookIdentifierDoublequote,\n      // there is also support for backtics, ref: http://sqlite.org/lang_keywords.html\n      \"`\":   hookIdentifier\n    }\n  });\n\n  // the query language used by Apache Cassandra is called CQL, but this mime type\n  // is called Cassandra to avoid confusion with Contextual Query Language\n  CodeMirror.defineMIME(\"text/x-cassandra\", {\n    name: \"sql\",\n    client: { },\n    keywords: set(\"add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime\"),\n    builtin: set(\"ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint\"),\n    atoms: set(\"false true infinity NaN\"),\n    operatorChars: /^[<>=]/,\n    dateSQL: { },\n    support: set(\"commentSlashSlash decimallessFloat\"),\n    hooks: { }\n  });\n\n  // this is based on Peter Raganitsch's 'plsql' mode\n  CodeMirror.defineMIME(\"text/x-plsql\", {\n    name:       \"sql\",\n    client:     set(\"appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap\"),\n    keywords:   set(\"abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work\"),\n    builtin:    set(\"abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml\"),\n    operatorChars: /^[*\\/+\\-%<>!=~]/,\n    dateSQL:    set(\"date time timestamp\"),\n    support:    set(\"doubleQuote nCharCast zerolessFloat binaryNumber hexNumber\")\n  });\n\n  // Created to support specific hive keywords\n  CodeMirror.defineMIME(\"text/x-hive\", {\n    name: \"sql\",\n    keywords: set(\"select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with admin authorization char compact compactions conf cube current current_date current_timestamp day decimal defined dependency directories elem_type exchange file following for grouping hour ignore inner interval jar less logical macro minute month more none noscan over owner partialscan preceding pretty principals protection reload rewrite role roles rollup rows second server sets skewed transactions truncate unbounded unset uri user values window year\"),\n    builtin: set(\"bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype key_type utctimestamp value_type varchar\"),\n    atoms: set(\"false true null unknown\"),\n    operatorChars: /^[*+\\-%<>!=]/,\n    dateSQL: set(\"date timestamp\"),\n    support: set(\"ODBCdotTable doubleQuote binaryNumber hexNumber\")\n  });\n\n  CodeMirror.defineMIME(\"text/x-pgsql\", {\n    name: \"sql\",\n    client: set(\"source\"),\n    // https://www.postgresql.org/docs/10/static/sql-keywords-appendix.html\n    keywords: set(sqlKeywords + \"a abort abs absent absolute access according action ada add admin after aggregate all allocate also always analyse analyze any are array array_agg array_max_cardinality asensitive assertion assignment asymmetric at atomic attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli binary bit_length blob blocked bom both breadth c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain characteristics characters character_length character_set_catalog character_set_name character_set_schema char_length check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column columns column_name command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constraint constraints constraint_catalog constraint_name constraint_schema constructor contains content continue control conversion convert copy corr corresponding cost covar_pop covar_samp cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datetime_interval_code datetime_interval_precision day db deallocate dec declare default defaults deferrable deferred defined definer degree delimiter delimiters dense_rank depth deref derived describe descriptor deterministic diagnostics dictionary disable discard disconnect dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain dynamic dynamic_function dynamic_function_code each element else empty enable encoding encrypted end end-exec end_frame end_partition enforced enum equals escape event every except exception exclude excluding exclusive exec execute exists exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreign fortran forward found frame_row free freeze fs full function functions fusion g general generated get gettoken global go goto grant granted greatest grouping groups handler header headline hex hierarchy hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import including increment indent index indexes indicator inherit inherits init initially inline inner inout input insensitive instance instantiable instead integrity intersect intersection invoker isnull isolation k key key_member key_type label lag language large last last_value lateral lc_collate lc_ctype lead leading leakproof least left length level lexize lextypes library like_regex link listen ln load local localtime localtimestamp location locator lock locked logged lower m map mapping match matched materialized max maxvalue max_cardinality member merge message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized nothing notify notnull nowait nth_value ntile null nullable nullif nulls number object occurrences_regex octets octet_length of off offset oids old only open operator option options ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parallel parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password percent percentile_cont percentile_disc percent_rank period permission placing plans pli policy portion position position_regex power precedes preceding prepare prepared preserve primary prior privileges procedural procedure program public publication quote range rank read reads reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict restricted result return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns revoke right role rollback rollup routine routine_catalog routine_name routine_schema row rows row_count row_number rule savepoint scale schema schema_name scope scope_catalog scope_name scope_schema scroll search second section security selective self sensitive sequence sequences serializable server server_name session session_user setof sets share show similar simple size skip snapshot some source space specific specifictype specific_name sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset subscription substring substring_regex succeeds sum symmetric sysid system system_time system_user t tables tablesample tablespace table_name temp template temporary then ties timezone_hour timezone_minute to token top_level_count trailing transaction transactions_committed transactions_rolled_back transaction_active transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted unique unknown unlink unlisten unlogged unnamed unnest until untyped upper uri usage user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of varbinary variadic var_pop var_samp verbose version versioning view views volatile when whenever whitespace width_bucket window within work wrapper write xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes loop repeat attach path depends detach zone\"),\n    // https://www.postgresql.org/docs/10/static/datatype.html\n    builtin: set(\"bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml\"),\n    atoms: set(\"false true null unknown\"),\n    operatorChars: /^[*\\/+\\-%<>!=&|^\\/#@?~]/,\n    dateSQL: set(\"date time timestamp\"),\n    support: set(\"ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast\")\n  });\n\n  // Google's SQL-like query language, GQL\n  CodeMirror.defineMIME(\"text/x-gql\", {\n    name: \"sql\",\n    keywords: set(\"ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where\"),\n    atoms: set(\"false true\"),\n    builtin: set(\"blob datetime first key __key__ string integer double boolean null\"),\n    operatorChars: /^[*+\\-%<>!=]/\n  });\n\n  // Greenplum\n  CodeMirror.defineMIME(\"text/x-gpsql\", {\n    name: \"sql\",\n    client: set(\"source\"),\n    //https://github.com/greenplum-db/gpdb/blob/master/src/include/parser/kwlist.h\n    keywords: set(\"abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone\"),\n    builtin: set(\"bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml\"),\n    atoms: set(\"false true null unknown\"),\n    operatorChars: /^[*+\\-%<>!=&|^\\/#@?~]/,\n    dateSQL: set(\"date time timestamp\"),\n    support: set(\"ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast\")\n  });\n\n  // Spark SQL\n  CodeMirror.defineMIME(\"text/x-sparksql\", {\n    name: \"sql\",\n    keywords: set(\"add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases datata dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with\"),\n    builtin: set(\"tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat\"),\n    atoms: set(\"false true null\"),\n    operatorChars: /^[*\\/+\\-%<>!=~&|^]/,\n    dateSQL: set(\"date time timestamp\"),\n    support: set(\"ODBCdotTable doubleQuote zerolessFloat\")\n  });\n\n  // Esper\n  CodeMirror.defineMIME(\"text/x-esper\", {\n    name: \"sql\",\n    client: set(\"source\"),\n    // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html\n    keywords: set(\"alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until update variable weekday when where window\"),\n    builtin: {},\n    atoms: set(\"false true null\"),\n    operatorChars: /^[*+\\-%<>!=&|^\\/#@?~]/,\n    dateSQL: set(\"time\"),\n    support: set(\"decimallessFloat zerolessFloat binaryNumber hexNumber\")\n  });\n});\n\n/*\n  How Properties of Mime Types are used by SQL Mode\n  =================================================\n\n  keywords:\n    A list of keywords you want to be highlighted.\n  builtin:\n    A list of builtin types you want to be highlighted (if you want types to be of class \"builtin\" instead of \"keyword\").\n  operatorChars:\n    All characters that must be handled as operators.\n  client:\n    Commands parsed and executed by the client (not the server).\n  support:\n    A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.\n    * ODBCdotTable: .tableName\n    * zerolessFloat: .1\n    * doubleQuote\n    * nCharCast: N'string'\n    * charsetCast: _utf8'string'\n    * commentHash: use # char for comments\n    * commentSlashSlash: use // for comments\n    * commentSpaceRequired: require a space after -- for comments\n  atoms:\n    Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:\n    UNKNOWN, INFINITY, UNDERFLOW, NaN...\n  dateSQL:\n    Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.\n*/\n"
  },
  {
    "path": "third_party/CodeMirror/mode/stex/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: sTeX mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"stex.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">sTeX</a>\n  </ul>\n</div>\n\n<article>\n<h2>sTeX mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n\\begin{module}[id=bbt-size]\n\\importmodule[balanced-binary-trees]{balanced-binary-trees}\n\\importmodule[\\KWARCslides{dmath/en/cardinality}]{cardinality}\n\n\\begin{frame}\n  \\frametitle{Size Lemma for Balanced Trees}\n  \\begin{itemize}\n  \\item\n    \\begin{assertion}[id=size-lemma,type=lemma] \n    Let $G=\\tup{V,E}$ be a \\termref[cd=binary-trees]{balanced binary tree} \n    of \\termref[cd=graph-depth,name=vertex-depth]{depth}$n>i$, then the set\n     $\\defeq{\\livar{V}i}{\\setst{\\inset{v}{V}}{\\gdepth{v} = i}}$ of\n    \\termref[cd=graphs-intro,name=node]{nodes} at \n    \\termref[cd=graph-depth,name=vertex-depth]{depth} $i$ has\n    \\termref[cd=cardinality,name=cardinality]{cardinality} $\\power2i$.\n   \\end{assertion}\n  \\item\n    \\begin{sproof}[id=size-lemma-pf,proofend=,for=size-lemma]{via induction over the depth $i$.}\n      \\begin{spfcases}{We have to consider two cases}\n        \\begin{spfcase}{$i=0$}\n          \\begin{spfstep}[display=flow]\n            then $\\livar{V}i=\\set{\\livar{v}r}$, where $\\livar{v}r$ is the root, so\n            $\\eq{\\card{\\livar{V}0},\\card{\\set{\\livar{v}r}},1,\\power20}$.\n          \\end{spfstep}\n        \\end{spfcase}\n        \\begin{spfcase}{$i>0$}\n          \\begin{spfstep}[display=flow]\n           then $\\livar{V}{i-1}$ contains $\\power2{i-1}$ vertexes \n           \\begin{justification}[method=byIH](IH)\\end{justification}\n          \\end{spfstep}\n          \\begin{spfstep}\n           By the \\begin{justification}[method=byDef]definition of a binary\n              tree\\end{justification}, each $\\inset{v}{\\livar{V}{i-1}}$ is a leaf or has\n            two children that are at depth $i$.\n          \\end{spfstep}\n          \\begin{spfstep}\n           As $G$ is \\termref[cd=balanced-binary-trees,name=balanced-binary-tree]{balanced} and $\\gdepth{G}=n>i$, $\\livar{V}{i-1}$ cannot contain\n            leaves.\n          \\end{spfstep}\n          \\begin{spfstep}[type=conclusion]\n           Thus $\\eq{\\card{\\livar{V}i},{\\atimes[cdot]{2,\\card{\\livar{V}{i-1}}}},{\\atimes[cdot]{2,\\power2{i-1}}},\\power2i}$.\n          \\end{spfstep}\n        \\end{spfcase}\n      \\end{spfcases}\n    \\end{sproof}\n  \\item \n    \\begin{assertion}[id=fbbt,type=corollary]\t\n      A fully balanced tree of depth $d$ has $\\power2{d+1}-1$ nodes.\n    \\end{assertion}\n  \\item\n      \\begin{sproof}[for=fbbt,id=fbbt-pf]{}\n        \\begin{spfstep}\n          Let $\\defeq{G}{\\tup{V,E}}$ be a fully balanced tree\n        \\end{spfstep}\n        \\begin{spfstep}\n          Then $\\card{V}=\\Sumfromto{i}1d{\\power2i}= \\power2{d+1}-1$.\n        \\end{spfstep}\n      \\end{sproof}\n    \\end{itemize}\n  \\end{frame}\n\\begin{note}\n  \\begin{omtext}[type=conclusion,for=binary-tree]\n    This shows that balanced binary trees grow in breadth very quickly, a consequence of\n    this is that they are very shallow (and this compute very fast), which is the essence of\n    the next result.\n  \\end{omtext}\n\\end{note}\n\\end{module}\n\n%%% Local Variables: \n%%% mode: LaTeX\n%%% TeX-master: \"all\"\n%%% End: \\end{document}\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p>sTeX mode supports this option:</p>\n    <d1>\n      <dt><code>inMathMode: boolean</code></dt>\n      <dd>Whether to start parsing in math mode (default: <code>false</code>).</dd>\n    </d1>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-stex</code>.</p>\n\n    <p><strong>Parsing/Highlighting Tests:</strong> <a href=\"../../test/index.html#stex_*\">normal</a>,  <a href=\"../../test/index.html#verbose,stex_*\">verbose</a>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/stex/stex.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/*\n * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de)\n * Licence: MIT\n */\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"stex\", function(_config, parserConfig) {\n    \"use strict\";\n\n    function pushCommand(state, command) {\n      state.cmdState.push(command);\n    }\n\n    function peekCommand(state) {\n      if (state.cmdState.length > 0) {\n        return state.cmdState[state.cmdState.length - 1];\n      } else {\n        return null;\n      }\n    }\n\n    function popCommand(state) {\n      var plug = state.cmdState.pop();\n      if (plug) {\n        plug.closeBracket();\n      }\n    }\n\n    // returns the non-default plugin closest to the end of the list\n    function getMostPowerful(state) {\n      var context = state.cmdState;\n      for (var i = context.length - 1; i >= 0; i--) {\n        var plug = context[i];\n        if (plug.name == \"DEFAULT\") {\n          continue;\n        }\n        return plug;\n      }\n      return { styleIdentifier: function() { return null; } };\n    }\n\n    function addPluginPattern(pluginName, cmdStyle, styles) {\n      return function () {\n        this.name = pluginName;\n        this.bracketNo = 0;\n        this.style = cmdStyle;\n        this.styles = styles;\n        this.argument = null;   // \\begin and \\end have arguments that follow. These are stored in the plugin\n\n        this.styleIdentifier = function() {\n          return this.styles[this.bracketNo - 1] || null;\n        };\n        this.openBracket = function() {\n          this.bracketNo++;\n          return \"bracket\";\n        };\n        this.closeBracket = function() {};\n      };\n    }\n\n    var plugins = {};\n\n    plugins[\"importmodule\"] = addPluginPattern(\"importmodule\", \"tag\", [\"string\", \"builtin\"]);\n    plugins[\"documentclass\"] = addPluginPattern(\"documentclass\", \"tag\", [\"\", \"atom\"]);\n    plugins[\"usepackage\"] = addPluginPattern(\"usepackage\", \"tag\", [\"atom\"]);\n    plugins[\"begin\"] = addPluginPattern(\"begin\", \"tag\", [\"atom\"]);\n    plugins[\"end\"] = addPluginPattern(\"end\", \"tag\", [\"atom\"]);\n\n    plugins[\"label\"    ] = addPluginPattern(\"label\"    , \"tag\", [\"atom\"]);\n    plugins[\"ref\"      ] = addPluginPattern(\"ref\"      , \"tag\", [\"atom\"]);\n    plugins[\"eqref\"    ] = addPluginPattern(\"eqref\"    , \"tag\", [\"atom\"]);\n    plugins[\"cite\"     ] = addPluginPattern(\"cite\"     , \"tag\", [\"atom\"]);\n    plugins[\"bibitem\"  ] = addPluginPattern(\"bibitem\"  , \"tag\", [\"atom\"]);\n    plugins[\"Bibitem\"  ] = addPluginPattern(\"Bibitem\"  , \"tag\", [\"atom\"]);\n    plugins[\"RBibitem\" ] = addPluginPattern(\"RBibitem\" , \"tag\", [\"atom\"]);\n\n    plugins[\"DEFAULT\"] = function () {\n      this.name = \"DEFAULT\";\n      this.style = \"tag\";\n\n      this.styleIdentifier = this.openBracket = this.closeBracket = function() {};\n    };\n\n    function setState(state, f) {\n      state.f = f;\n    }\n\n    // called when in a normal (no environment) context\n    function normal(source, state) {\n      var plug;\n      // Do we look like '\\command' ?  If so, attempt to apply the plugin 'command'\n      if (source.match(/^\\\\[a-zA-Z@]+/)) {\n        var cmdName = source.current().slice(1);\n        plug = plugins[cmdName] || plugins[\"DEFAULT\"];\n        plug = new plug();\n        pushCommand(state, plug);\n        setState(state, beginParams);\n        return plug.style;\n      }\n\n      // escape characters\n      if (source.match(/^\\\\[$&%#{}_]/)) {\n        return \"tag\";\n      }\n\n      // white space control characters\n      if (source.match(/^\\\\[,;!\\/\\\\]/)) {\n        return \"tag\";\n      }\n\n      // find if we're starting various math modes\n      if (source.match(\"\\\\[\")) {\n        setState(state, function(source, state){ return inMathMode(source, state, \"\\\\]\"); });\n        return \"keyword\";\n      }\n      if (source.match(\"\\\\(\")) {\n        setState(state, function(source, state){ return inMathMode(source, state, \"\\\\)\"); });\n        return \"keyword\";\n      }\n      if (source.match(\"$$\")) {\n        setState(state, function(source, state){ return inMathMode(source, state, \"$$\"); });\n        return \"keyword\";\n      }\n      if (source.match(\"$\")) {\n        setState(state, function(source, state){ return inMathMode(source, state, \"$\"); });\n        return \"keyword\";\n      }\n\n      var ch = source.next();\n      if (ch == \"%\") {\n        source.skipToEnd();\n        return \"comment\";\n      } else if (ch == '}' || ch == ']') {\n        plug = peekCommand(state);\n        if (plug) {\n          plug.closeBracket(ch);\n          setState(state, beginParams);\n        } else {\n          return \"error\";\n        }\n        return \"bracket\";\n      } else if (ch == '{' || ch == '[') {\n        plug = plugins[\"DEFAULT\"];\n        plug = new plug();\n        pushCommand(state, plug);\n        return \"bracket\";\n      } else if (/\\d/.test(ch)) {\n        source.eatWhile(/[\\w.%]/);\n        return \"atom\";\n      } else {\n        source.eatWhile(/[\\w\\-_]/);\n        plug = getMostPowerful(state);\n        if (plug.name == 'begin') {\n          plug.argument = source.current();\n        }\n        return plug.styleIdentifier();\n      }\n    }\n\n    function inMathMode(source, state, endModeSeq) {\n      if (source.eatSpace()) {\n        return null;\n      }\n      if (endModeSeq && source.match(endModeSeq)) {\n        setState(state, normal);\n        return \"keyword\";\n      }\n      if (source.match(/^\\\\[a-zA-Z@]+/)) {\n        return \"tag\";\n      }\n      if (source.match(/^[a-zA-Z]+/)) {\n        return \"variable-2\";\n      }\n      // escape characters\n      if (source.match(/^\\\\[$&%#{}_]/)) {\n        return \"tag\";\n      }\n      // white space control characters\n      if (source.match(/^\\\\[,;!\\/]/)) {\n        return \"tag\";\n      }\n      // special math-mode characters\n      if (source.match(/^[\\^_&]/)) {\n        return \"tag\";\n      }\n      // non-special characters\n      if (source.match(/^[+\\-<>|=,\\/@!*:;'\"`~#?]/)) {\n        return null;\n      }\n      if (source.match(/^(\\d+\\.\\d*|\\d*\\.\\d+|\\d+)/)) {\n        return \"number\";\n      }\n      var ch = source.next();\n      if (ch == \"{\" || ch == \"}\" || ch == \"[\" || ch == \"]\" || ch == \"(\" || ch == \")\") {\n        return \"bracket\";\n      }\n\n      if (ch == \"%\") {\n        source.skipToEnd();\n        return \"comment\";\n      }\n      return \"error\";\n    }\n\n    function beginParams(source, state) {\n      var ch = source.peek(), lastPlug;\n      if (ch == '{' || ch == '[') {\n        lastPlug = peekCommand(state);\n        lastPlug.openBracket(ch);\n        source.eat(ch);\n        setState(state, normal);\n        return \"bracket\";\n      }\n      if (/[ \\t\\r]/.test(ch)) {\n        source.eat(ch);\n        return null;\n      }\n      setState(state, normal);\n      popCommand(state);\n\n      return normal(source, state);\n    }\n\n    return {\n      startState: function() {\n        var f = parserConfig.inMathMode ? function(source, state){ return inMathMode(source, state); } : normal;\n        return {\n          cmdState: [],\n          f: f\n        };\n      },\n      copyState: function(s) {\n        return {\n          cmdState: s.cmdState.slice(),\n          f: s.f\n        };\n      },\n      token: function(stream, state) {\n        return state.f(stream, state);\n      },\n      blankLine: function(state) {\n        state.f = normal;\n        state.cmdState.length = 0;\n      },\n      lineComment: \"%\"\n    };\n  });\n\n  CodeMirror.defineMIME(\"text/x-stex\", \"stex\");\n  CodeMirror.defineMIME(\"text/x-latex\", \"stex\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/stex/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({tabSize: 4}, \"stex\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"word\",\n     \"foo\");\n\n  MT(\"twoWords\",\n     \"foo bar\");\n\n  MT(\"beginEndDocument\",\n     \"[tag \\\\begin][bracket {][atom document][bracket }]\",\n     \"[tag \\\\end][bracket {][atom document][bracket }]\");\n\n  MT(\"beginEndEquation\",\n     \"[tag \\\\begin][bracket {][atom equation][bracket }]\",\n     \"  E=mc^2\",\n     \"[tag \\\\end][bracket {][atom equation][bracket }]\");\n\n  MT(\"beginModule\",\n     \"[tag \\\\begin][bracket {][atom module][bracket }[[]]]\");\n\n  MT(\"beginModuleId\",\n     \"[tag \\\\begin][bracket {][atom module][bracket }[[]id=bbt-size[bracket ]]]\");\n\n  MT(\"importModule\",\n     \"[tag \\\\importmodule][bracket [[][string b-b-t][bracket ]]{][builtin b-b-t][bracket }]\");\n\n  MT(\"importModulePath\",\n     \"[tag \\\\importmodule][bracket [[][tag \\\\KWARCslides][bracket {][string dmath/en/cardinality][bracket }]]{][builtin card][bracket }]\");\n\n  MT(\"psForPDF\",\n     \"[tag \\\\PSforPDF][bracket [[][atom 1][bracket ]]{]#1[bracket }]\");\n\n  MT(\"comment\",\n     \"[comment % foo]\");\n\n  MT(\"tagComment\",\n     \"[tag \\\\item][comment % bar]\");\n\n  MT(\"commentTag\",\n     \" [comment % \\\\item]\");\n\n  MT(\"commentLineBreak\",\n     \"[comment %]\",\n     \"foo\");\n\n  MT(\"tagErrorCurly\",\n     \"[tag \\\\begin][error }][bracket {]\");\n\n  MT(\"tagErrorSquare\",\n     \"[tag \\\\item][error ]]][bracket {]\");\n\n  MT(\"commentCurly\",\n     \"[comment % }]\");\n\n  MT(\"tagHash\",\n     \"the [tag \\\\#] key\");\n\n  MT(\"tagNumber\",\n     \"a [tag \\\\$][atom 5] stetson\");\n\n  MT(\"tagPercent\",\n     \"[atom 100][tag \\\\%] beef\");\n\n  MT(\"tagAmpersand\",\n     \"L [tag \\\\&] N\");\n\n  MT(\"tagUnderscore\",\n     \"foo[tag \\\\_]bar\");\n\n  MT(\"tagBracketOpen\",\n     \"[tag \\\\emph][bracket {][tag \\\\{][bracket }]\");\n\n  MT(\"tagBracketClose\",\n     \"[tag \\\\emph][bracket {][tag \\\\}][bracket }]\");\n\n  MT(\"tagLetterNumber\",\n     \"section [tag \\\\S][atom 1]\");\n\n  MT(\"textTagNumber\",\n     \"para [tag \\\\P][atom 2]\");\n\n  MT(\"thinspace\",\n     \"x[tag \\\\,]y\");\n\n  MT(\"thickspace\",\n     \"x[tag \\\\;]y\");\n\n  MT(\"negativeThinspace\",\n     \"x[tag \\\\!]y\");\n\n  MT(\"periodNotSentence\",\n     \"J.\\\\ L.\\\\ is\");\n\n  MT(\"periodSentence\",\n     \"X[tag \\\\@]. The\");\n\n  MT(\"italicCorrection\",\n     \"[bracket {][tag \\\\em] If[tag \\\\/][bracket }] I\");\n\n  MT(\"tagBracket\",\n     \"[tag \\\\newcommand][bracket {][tag \\\\pop][bracket }]\");\n\n  MT(\"inlineMathTagFollowedByNumber\",\n     \"[keyword $][tag \\\\pi][number 2][keyword $]\");\n\n  MT(\"inlineMath\",\n     \"[keyword $][number 3][variable-2 x][tag ^][number 2.45]-[tag \\\\sqrt][bracket {][tag \\\\$\\\\alpha][bracket }] = [number 2][keyword $] other text\");\n\n  MT(\"inlineMathLatexStyle\",\n     \"[keyword \\\\(][number 3][variable-2 x][tag ^][number 2.45]-[tag \\\\sqrt][bracket {][tag \\\\$\\\\alpha][bracket }] = [number 2][keyword \\\\)] other text\");\n\n  MT(\"displayMath\",\n     \"More [keyword $$]\\t[variable-2 S][tag ^][variable-2 n][tag \\\\sum] [variable-2 i][keyword $$] other text\");\n\n  MT(\"displayMath environment\",\n     \"[tag \\\\begin][bracket {][atom equation][bracket }] x [tag \\\\end][bracket {][atom equation][bracket }] other text\");\n\n  MT(\"displayMath environment with label\",\n     \"[tag \\\\begin][bracket {][atom equation][bracket }][tag \\\\label][bracket {][atom eq1][bracket }] x [tag \\\\end][bracket {][atom equation][bracket }] other text~[tag \\\\ref][bracket {][atom eq1][bracket }]\");\n\n  MT(\"mathWithComment\",\n     \"[keyword $][variable-2 x] [comment % $]\",\n     \"[variable-2 y][keyword $] other text\");\n\n  MT(\"lineBreakArgument\",\n    \"[tag \\\\\\\\][bracket [[][atom 1cm][bracket ]]]\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/stylus/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Stylus mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../addon/hint/show-hint.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"stylus.js\"></script>\n<script src=\"../../addon/hint/show-hint.js\"></script>\n<script src=\"../../addon/hint/css-hint.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;} form{margin-bottom: .7em;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Stylus</a>\n  </ul>\n</div>\n\n<article>\n<h2>Stylus mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n/* Stylus mode */\n\n#id,\n.class,\narticle\n  font-family Arial, sans-serif\n\n#id,\n.class,\narticle {\n  font-family: Arial, sans-serif;\n}\n\n// Variables\nfont-size-base = 16px\nline-height-base = 1.5\nfont-family-base = \"Helvetica Neue\", Helvetica, Arial, sans-serif\ntext-color = lighten(#000, 20%)\n\nbody\n  font font-size-base/line-height-base font-family-base\n  color text-color\n\nbody {\n  font: 400 16px/1.5 \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n  color: #333;\n}\n\n// Variables\nlink-color = darken(#428bca, 6.5%)\nlink-hover-color = darken(link-color, 15%)\nlink-decoration = none\nlink-hover-decoration = false\n\n// Mixin\ntab-focus()\n  outline thin dotted\n  outline 5px auto -webkit-focus-ring-color\n  outline-offset -2px\n\na\n  color link-color\n  if link-decoration\n    text-decoration link-decoration\n  &:hover\n  &:focus\n    color link-hover-color\n    if link-hover-decoration\n      text-decoration link-hover-decoration\n  &:focus\n    tab-focus()\n\na {\n  color: #3782c4;\n  text-decoration: none;\n}\na:hover,\na:focus {\n  color: #2f6ea7;\n}\na:focus {\n  outline: thin dotted;\n  outline: 5px auto -webkit-focus-ring-color;\n  outline-offset: -2px;\n}\n</textarea>\n</form>\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    extraKeys: {\"Ctrl-Space\": \"autocomplete\"},\n    tabSize: 2\n  });\n</script>\n\n<p><strong>MIME types defined:</strong> <code>text/x-styl</code>.</p>\n<p>Created by <a href=\"https://github.com/dmitrykiselyov\">Dmitry Kiselyov</a></p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/stylus/stylus.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Stylus mode created by Dmitry Kiselyov http://git.io/AaRB\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"stylus\", function(config) {\n    var indentUnit = config.indentUnit,\n        indentUnitString = '',\n        tagKeywords = keySet(tagKeywords_),\n        tagVariablesRegexp = /^(a|b|i|s|col|em)$/i,\n        propertyKeywords = keySet(propertyKeywords_),\n        nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_),\n        valueKeywords = keySet(valueKeywords_),\n        colorKeywords = keySet(colorKeywords_),\n        documentTypes = keySet(documentTypes_),\n        documentTypesRegexp = wordRegexp(documentTypes_),\n        mediaFeatures = keySet(mediaFeatures_),\n        mediaTypes = keySet(mediaTypes_),\n        fontProperties = keySet(fontProperties_),\n        operatorsRegexp = /^\\s*([.]{2,3}|&&|\\|\\||\\*\\*|[?!=:]?=|[-+*\\/%<>]=?|\\?:|\\~)/,\n        wordOperatorKeywordsRegexp = wordRegexp(wordOperatorKeywords_),\n        blockKeywords = keySet(blockKeywords_),\n        vendorPrefixesRegexp = new RegExp(/^\\-(moz|ms|o|webkit)-/i),\n        commonAtoms = keySet(commonAtoms_),\n        firstWordMatch = \"\",\n        states = {},\n        ch,\n        style,\n        type,\n        override;\n\n    while (indentUnitString.length < indentUnit) indentUnitString += ' ';\n\n    /**\n     * Tokenizers\n     */\n    function tokenBase(stream, state) {\n      firstWordMatch = stream.string.match(/(^[\\w-]+\\s*=\\s*$)|(^\\s*[\\w-]+\\s*=\\s*[\\w-])|(^\\s*(\\.|#|@|\\$|\\&|\\[|\\d|\\+|::?|\\{|\\>|~|\\/)?\\s*[\\w-]*([a-z0-9-]|\\*|\\/\\*)(\\(|,)?)/);\n      state.context.line.firstWord = firstWordMatch ? firstWordMatch[0].replace(/^\\s*/, \"\") : \"\";\n      state.context.line.indent = stream.indentation();\n      ch = stream.peek();\n\n      // Line comment\n      if (stream.match(\"//\")) {\n        stream.skipToEnd();\n        return [\"comment\", \"comment\"];\n      }\n      // Block comment\n      if (stream.match(\"/*\")) {\n        state.tokenize = tokenCComment;\n        return tokenCComment(stream, state);\n      }\n      // String\n      if (ch == \"\\\"\" || ch == \"'\") {\n        stream.next();\n        state.tokenize = tokenString(ch);\n        return state.tokenize(stream, state);\n      }\n      // Def\n      if (ch == \"@\") {\n        stream.next();\n        stream.eatWhile(/[\\w\\\\-]/);\n        return [\"def\", stream.current()];\n      }\n      // ID selector or Hex color\n      if (ch == \"#\") {\n        stream.next();\n        // Hex color\n        if (stream.match(/^[0-9a-f]{3}([0-9a-f]([0-9a-f]{2}){0,2})?\\b/i)) {\n          return [\"atom\", \"atom\"];\n        }\n        // ID selector\n        if (stream.match(/^[a-z][\\w-]*/i)) {\n          return [\"builtin\", \"hash\"];\n        }\n      }\n      // Vendor prefixes\n      if (stream.match(vendorPrefixesRegexp)) {\n        return [\"meta\", \"vendor-prefixes\"];\n      }\n      // Numbers\n      if (stream.match(/^-?[0-9]?\\.?[0-9]/)) {\n        stream.eatWhile(/[a-z%]/i);\n        return [\"number\", \"unit\"];\n      }\n      // !important|optional\n      if (ch == \"!\") {\n        stream.next();\n        return [stream.match(/^(important|optional)/i) ? \"keyword\": \"operator\", \"important\"];\n      }\n      // Class\n      if (ch == \".\" && stream.match(/^\\.[a-z][\\w-]*/i)) {\n        return [\"qualifier\", \"qualifier\"];\n      }\n      // url url-prefix domain regexp\n      if (stream.match(documentTypesRegexp)) {\n        if (stream.peek() == \"(\") state.tokenize = tokenParenthesized;\n        return [\"property\", \"word\"];\n      }\n      // Mixins / Functions\n      if (stream.match(/^[a-z][\\w-]*\\(/i)) {\n        stream.backUp(1);\n        return [\"keyword\", \"mixin\"];\n      }\n      // Block mixins\n      if (stream.match(/^(\\+|-)[a-z][\\w-]*\\(/i)) {\n        stream.backUp(1);\n        return [\"keyword\", \"block-mixin\"];\n      }\n      // Parent Reference BEM naming\n      if (stream.string.match(/^\\s*&/) && stream.match(/^[-_]+[a-z][\\w-]*/)) {\n        return [\"qualifier\", \"qualifier\"];\n      }\n      // / Root Reference & Parent Reference\n      if (stream.match(/^(\\/|&)(-|_|:|\\.|#|[a-z])/)) {\n        stream.backUp(1);\n        return [\"variable-3\", \"reference\"];\n      }\n      if (stream.match(/^&{1}\\s*$/)) {\n        return [\"variable-3\", \"reference\"];\n      }\n      // Word operator\n      if (stream.match(wordOperatorKeywordsRegexp)) {\n        return [\"operator\", \"operator\"];\n      }\n      // Word\n      if (stream.match(/^\\$?[-_]*[a-z0-9]+[\\w-]*/i)) {\n        // Variable\n        if (stream.match(/^(\\.|\\[)[\\w-\\'\\\"\\]]+/i, false)) {\n          if (!wordIsTag(stream.current())) {\n            stream.match(/\\./);\n            return [\"variable-2\", \"variable-name\"];\n          }\n        }\n        return [\"variable-2\", \"word\"];\n      }\n      // Operators\n      if (stream.match(operatorsRegexp)) {\n        return [\"operator\", stream.current()];\n      }\n      // Delimiters\n      if (/[:;,{}\\[\\]\\(\\)]/.test(ch)) {\n        stream.next();\n        return [null, ch];\n      }\n      // Non-detected items\n      stream.next();\n      return [null, null];\n    }\n\n    /**\n     * Token comment\n     */\n    function tokenCComment(stream, state) {\n      var maybeEnd = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (maybeEnd && ch == \"/\") {\n          state.tokenize = null;\n          break;\n        }\n        maybeEnd = (ch == \"*\");\n      }\n      return [\"comment\", \"comment\"];\n    }\n\n    /**\n     * Token string\n     */\n    function tokenString(quote) {\n      return function(stream, state) {\n        var escaped = false, ch;\n        while ((ch = stream.next()) != null) {\n          if (ch == quote && !escaped) {\n            if (quote == \")\") stream.backUp(1);\n            break;\n          }\n          escaped = !escaped && ch == \"\\\\\";\n        }\n        if (ch == quote || !escaped && quote != \")\") state.tokenize = null;\n        return [\"string\", \"string\"];\n      };\n    }\n\n    /**\n     * Token parenthesized\n     */\n    function tokenParenthesized(stream, state) {\n      stream.next(); // Must be \"(\"\n      if (!stream.match(/\\s*[\\\"\\')]/, false))\n        state.tokenize = tokenString(\")\");\n      else\n        state.tokenize = null;\n      return [null, \"(\"];\n    }\n\n    /**\n     * Context management\n     */\n    function Context(type, indent, prev, line) {\n      this.type = type;\n      this.indent = indent;\n      this.prev = prev;\n      this.line = line || {firstWord: \"\", indent: 0};\n    }\n\n    function pushContext(state, stream, type, indent) {\n      indent = indent >= 0 ? indent : indentUnit;\n      state.context = new Context(type, stream.indentation() + indent, state.context);\n      return type;\n    }\n\n    function popContext(state, currentIndent) {\n      var contextIndent = state.context.indent - indentUnit;\n      currentIndent = currentIndent || false;\n      state.context = state.context.prev;\n      if (currentIndent) state.context.indent = contextIndent;\n      return state.context.type;\n    }\n\n    function pass(type, stream, state) {\n      return states[state.context.type](type, stream, state);\n    }\n\n    function popAndPass(type, stream, state, n) {\n      for (var i = n || 1; i > 0; i--)\n        state.context = state.context.prev;\n      return pass(type, stream, state);\n    }\n\n\n    /**\n     * Parser\n     */\n    function wordIsTag(word) {\n      return word.toLowerCase() in tagKeywords;\n    }\n\n    function wordIsProperty(word) {\n      word = word.toLowerCase();\n      return word in propertyKeywords || word in fontProperties;\n    }\n\n    function wordIsBlock(word) {\n      return word.toLowerCase() in blockKeywords;\n    }\n\n    function wordIsVendorPrefix(word) {\n      return word.toLowerCase().match(vendorPrefixesRegexp);\n    }\n\n    function wordAsValue(word) {\n      var wordLC = word.toLowerCase();\n      var override = \"variable-2\";\n      if (wordIsTag(word)) override = \"tag\";\n      else if (wordIsBlock(word)) override = \"block-keyword\";\n      else if (wordIsProperty(word)) override = \"property\";\n      else if (wordLC in valueKeywords || wordLC in commonAtoms) override = \"atom\";\n      else if (wordLC == \"return\" || wordLC in colorKeywords) override = \"keyword\";\n\n      // Font family\n      else if (word.match(/^[A-Z]/)) override = \"string\";\n      return override;\n    }\n\n    function typeIsBlock(type, stream) {\n      return ((endOfLine(stream) && (type == \"{\" || type == \"]\" || type == \"hash\" || type == \"qualifier\")) || type == \"block-mixin\");\n    }\n\n    function typeIsInterpolation(type, stream) {\n      return type == \"{\" && stream.match(/^\\s*\\$?[\\w-]+/i, false);\n    }\n\n    function typeIsPseudo(type, stream) {\n      return type == \":\" && stream.match(/^[a-z-]+/, false);\n    }\n\n    function startOfLine(stream) {\n      return stream.sol() || stream.string.match(new RegExp(\"^\\\\s*\" + escapeRegExp(stream.current())));\n    }\n\n    function endOfLine(stream) {\n      return stream.eol() || stream.match(/^\\s*$/, false);\n    }\n\n    function firstWordOfLine(line) {\n      var re = /^\\s*[-_]*[a-z0-9]+[\\w-]*/i;\n      var result = typeof line == \"string\" ? line.match(re) : line.string.match(re);\n      return result ? result[0].replace(/^\\s*/, \"\") : \"\";\n    }\n\n\n    /**\n     * Block\n     */\n    states.block = function(type, stream, state) {\n      if ((type == \"comment\" && startOfLine(stream)) ||\n          (type == \",\" && endOfLine(stream)) ||\n          type == \"mixin\") {\n        return pushContext(state, stream, \"block\", 0);\n      }\n      if (typeIsInterpolation(type, stream)) {\n        return pushContext(state, stream, \"interpolation\");\n      }\n      if (endOfLine(stream) && type == \"]\") {\n        if (!/^\\s*(\\.|#|:|\\[|\\*|&)/.test(stream.string) && !wordIsTag(firstWordOfLine(stream))) {\n          return pushContext(state, stream, \"block\", 0);\n        }\n      }\n      if (typeIsBlock(type, stream)) {\n        return pushContext(state, stream, \"block\");\n      }\n      if (type == \"}\" && endOfLine(stream)) {\n        return pushContext(state, stream, \"block\", 0);\n      }\n      if (type == \"variable-name\") {\n        if (stream.string.match(/^\\s?\\$[\\w-\\.\\[\\]\\'\\\"]+$/) || wordIsBlock(firstWordOfLine(stream))) {\n          return pushContext(state, stream, \"variableName\");\n        }\n        else {\n          return pushContext(state, stream, \"variableName\", 0);\n        }\n      }\n      if (type == \"=\") {\n        if (!endOfLine(stream) && !wordIsBlock(firstWordOfLine(stream))) {\n          return pushContext(state, stream, \"block\", 0);\n        }\n        return pushContext(state, stream, \"block\");\n      }\n      if (type == \"*\") {\n        if (endOfLine(stream) || stream.match(/\\s*(,|\\.|#|\\[|:|{)/,false)) {\n          override = \"tag\";\n          return pushContext(state, stream, \"block\");\n        }\n      }\n      if (typeIsPseudo(type, stream)) {\n        return pushContext(state, stream, \"pseudo\");\n      }\n      if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) {\n        return pushContext(state, stream, endOfLine(stream) ? \"block\" : \"atBlock\");\n      }\n      if (/@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) {\n        return pushContext(state, stream, \"keyframes\");\n      }\n      if (/@extends?/.test(type)) {\n        return pushContext(state, stream, \"extend\", 0);\n      }\n      if (type && type.charAt(0) == \"@\") {\n\n        // Property Lookup\n        if (stream.indentation() > 0 && wordIsProperty(stream.current().slice(1))) {\n          override = \"variable-2\";\n          return \"block\";\n        }\n        if (/(@import|@require|@charset)/.test(type)) {\n          return pushContext(state, stream, \"block\", 0);\n        }\n        return pushContext(state, stream, \"block\");\n      }\n      if (type == \"reference\" && endOfLine(stream)) {\n        return pushContext(state, stream, \"block\");\n      }\n      if (type == \"(\") {\n        return pushContext(state, stream, \"parens\");\n      }\n\n      if (type == \"vendor-prefixes\") {\n        return pushContext(state, stream, \"vendorPrefixes\");\n      }\n      if (type == \"word\") {\n        var word = stream.current();\n        override = wordAsValue(word);\n\n        if (override == \"property\") {\n          if (startOfLine(stream)) {\n            return pushContext(state, stream, \"block\", 0);\n          } else {\n            override = \"atom\";\n            return \"block\";\n          }\n        }\n\n        if (override == \"tag\") {\n\n          // tag is a css value\n          if (/embed|menu|pre|progress|sub|table/.test(word)) {\n            if (wordIsProperty(firstWordOfLine(stream))) {\n              override = \"atom\";\n              return \"block\";\n            }\n          }\n\n          // tag is an attribute\n          if (stream.string.match(new RegExp(\"\\\\[\\\\s*\" + word + \"|\" + word +\"\\\\s*\\\\]\"))) {\n            override = \"atom\";\n            return \"block\";\n          }\n\n          // tag is a variable\n          if (tagVariablesRegexp.test(word)) {\n            if ((startOfLine(stream) && stream.string.match(/=/)) ||\n                (!startOfLine(stream) &&\n                 !stream.string.match(/^(\\s*\\.|#|\\&|\\[|\\/|>|\\*)/) &&\n                 !wordIsTag(firstWordOfLine(stream)))) {\n              override = \"variable-2\";\n              if (wordIsBlock(firstWordOfLine(stream)))  return \"block\";\n              return pushContext(state, stream, \"block\", 0);\n            }\n          }\n\n          if (endOfLine(stream)) return pushContext(state, stream, \"block\");\n        }\n        if (override == \"block-keyword\") {\n          override = \"keyword\";\n\n          // Postfix conditionals\n          if (stream.current(/(if|unless)/) && !startOfLine(stream)) {\n            return \"block\";\n          }\n          return pushContext(state, stream, \"block\");\n        }\n        if (word == \"return\") return pushContext(state, stream, \"block\", 0);\n\n        // Placeholder selector\n        if (override == \"variable-2\" && stream.string.match(/^\\s?\\$[\\w-\\.\\[\\]\\'\\\"]+$/)) {\n          return pushContext(state, stream, \"block\");\n        }\n      }\n      return state.context.type;\n    };\n\n\n    /**\n     * Parens\n     */\n    states.parens = function(type, stream, state) {\n      if (type == \"(\") return pushContext(state, stream, \"parens\");\n      if (type == \")\") {\n        if (state.context.prev.type == \"parens\") {\n          return popContext(state);\n        }\n        if ((stream.string.match(/^[a-z][\\w-]*\\(/i) && endOfLine(stream)) ||\n            wordIsBlock(firstWordOfLine(stream)) ||\n            /(\\.|#|:|\\[|\\*|&|>|~|\\+|\\/)/.test(firstWordOfLine(stream)) ||\n            (!stream.string.match(/^-?[a-z][\\w-\\.\\[\\]\\'\\\"]*\\s*=/) &&\n             wordIsTag(firstWordOfLine(stream)))) {\n          return pushContext(state, stream, \"block\");\n        }\n        if (stream.string.match(/^[\\$-]?[a-z][\\w-\\.\\[\\]\\'\\\"]*\\s*=/) ||\n            stream.string.match(/^\\s*(\\(|\\)|[0-9])/) ||\n            stream.string.match(/^\\s+[a-z][\\w-]*\\(/i) ||\n            stream.string.match(/^\\s+[\\$-]?[a-z]/i)) {\n          return pushContext(state, stream, \"block\", 0);\n        }\n        if (endOfLine(stream)) return pushContext(state, stream, \"block\");\n        else return pushContext(state, stream, \"block\", 0);\n      }\n      if (type && type.charAt(0) == \"@\" && wordIsProperty(stream.current().slice(1))) {\n        override = \"variable-2\";\n      }\n      if (type == \"word\") {\n        var word = stream.current();\n        override = wordAsValue(word);\n        if (override == \"tag\" && tagVariablesRegexp.test(word)) {\n          override = \"variable-2\";\n        }\n        if (override == \"property\" || word == \"to\") override = \"atom\";\n      }\n      if (type == \"variable-name\") {\n        return pushContext(state, stream, \"variableName\");\n      }\n      if (typeIsPseudo(type, stream)) {\n        return pushContext(state, stream, \"pseudo\");\n      }\n      return state.context.type;\n    };\n\n\n    /**\n     * Vendor prefixes\n     */\n    states.vendorPrefixes = function(type, stream, state) {\n      if (type == \"word\") {\n        override = \"property\";\n        return pushContext(state, stream, \"block\", 0);\n      }\n      return popContext(state);\n    };\n\n\n    /**\n     * Pseudo\n     */\n    states.pseudo = function(type, stream, state) {\n      if (!wordIsProperty(firstWordOfLine(stream.string))) {\n        stream.match(/^[a-z-]+/);\n        override = \"variable-3\";\n        if (endOfLine(stream)) return pushContext(state, stream, \"block\");\n        return popContext(state);\n      }\n      return popAndPass(type, stream, state);\n    };\n\n\n    /**\n     * atBlock\n     */\n    states.atBlock = function(type, stream, state) {\n      if (type == \"(\") return pushContext(state, stream, \"atBlock_parens\");\n      if (typeIsBlock(type, stream)) {\n        return pushContext(state, stream, \"block\");\n      }\n      if (typeIsInterpolation(type, stream)) {\n        return pushContext(state, stream, \"interpolation\");\n      }\n      if (type == \"word\") {\n        var word = stream.current().toLowerCase();\n        if (/^(only|not|and|or)$/.test(word))\n          override = \"keyword\";\n        else if (documentTypes.hasOwnProperty(word))\n          override = \"tag\";\n        else if (mediaTypes.hasOwnProperty(word))\n          override = \"attribute\";\n        else if (mediaFeatures.hasOwnProperty(word))\n          override = \"property\";\n        else if (nonStandardPropertyKeywords.hasOwnProperty(word))\n          override = \"string-2\";\n        else override = wordAsValue(stream.current());\n        if (override == \"tag\" && endOfLine(stream)) {\n          return pushContext(state, stream, \"block\");\n        }\n      }\n      if (type == \"operator\" && /^(not|and|or)$/.test(stream.current())) {\n        override = \"keyword\";\n      }\n      return state.context.type;\n    };\n\n    states.atBlock_parens = function(type, stream, state) {\n      if (type == \"{\" || type == \"}\") return state.context.type;\n      if (type == \")\") {\n        if (endOfLine(stream)) return pushContext(state, stream, \"block\");\n        else return pushContext(state, stream, \"atBlock\");\n      }\n      if (type == \"word\") {\n        var word = stream.current().toLowerCase();\n        override = wordAsValue(word);\n        if (/^(max|min)/.test(word)) override = \"property\";\n        if (override == \"tag\") {\n          tagVariablesRegexp.test(word) ? override = \"variable-2\" : override = \"atom\";\n        }\n        return state.context.type;\n      }\n      return states.atBlock(type, stream, state);\n    };\n\n\n    /**\n     * Keyframes\n     */\n    states.keyframes = function(type, stream, state) {\n      if (stream.indentation() == \"0\" && ((type == \"}\" && startOfLine(stream)) || type == \"]\" || type == \"hash\"\n                                          || type == \"qualifier\" || wordIsTag(stream.current()))) {\n        return popAndPass(type, stream, state);\n      }\n      if (type == \"{\") return pushContext(state, stream, \"keyframes\");\n      if (type == \"}\") {\n        if (startOfLine(stream)) return popContext(state, true);\n        else return pushContext(state, stream, \"keyframes\");\n      }\n      if (type == \"unit\" && /^[0-9]+\\%$/.test(stream.current())) {\n        return pushContext(state, stream, \"keyframes\");\n      }\n      if (type == \"word\") {\n        override = wordAsValue(stream.current());\n        if (override == \"block-keyword\") {\n          override = \"keyword\";\n          return pushContext(state, stream, \"keyframes\");\n        }\n      }\n      if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) {\n        return pushContext(state, stream, endOfLine(stream) ? \"block\" : \"atBlock\");\n      }\n      if (type == \"mixin\") {\n        return pushContext(state, stream, \"block\", 0);\n      }\n      return state.context.type;\n    };\n\n\n    /**\n     * Interpolation\n     */\n    states.interpolation = function(type, stream, state) {\n      if (type == \"{\") popContext(state) && pushContext(state, stream, \"block\");\n      if (type == \"}\") {\n        if (stream.string.match(/^\\s*(\\.|#|:|\\[|\\*|&|>|~|\\+|\\/)/i) ||\n            (stream.string.match(/^\\s*[a-z]/i) && wordIsTag(firstWordOfLine(stream)))) {\n          return pushContext(state, stream, \"block\");\n        }\n        if (!stream.string.match(/^(\\{|\\s*\\&)/) ||\n            stream.match(/\\s*[\\w-]/,false)) {\n          return pushContext(state, stream, \"block\", 0);\n        }\n        return pushContext(state, stream, \"block\");\n      }\n      if (type == \"variable-name\") {\n        return pushContext(state, stream, \"variableName\", 0);\n      }\n      if (type == \"word\") {\n        override = wordAsValue(stream.current());\n        if (override == \"tag\") override = \"atom\";\n      }\n      return state.context.type;\n    };\n\n\n    /**\n     * Extend/s\n     */\n    states.extend = function(type, stream, state) {\n      if (type == \"[\" || type == \"=\") return \"extend\";\n      if (type == \"]\") return popContext(state);\n      if (type == \"word\") {\n        override = wordAsValue(stream.current());\n        return \"extend\";\n      }\n      return popContext(state);\n    };\n\n\n    /**\n     * Variable name\n     */\n    states.variableName = function(type, stream, state) {\n      if (type == \"string\" || type == \"[\" || type == \"]\" || stream.current().match(/^(\\.|\\$)/)) {\n        if (stream.current().match(/^\\.[\\w-]+/i)) override = \"variable-2\";\n        return \"variableName\";\n      }\n      return popAndPass(type, stream, state);\n    };\n\n\n    return {\n      startState: function(base) {\n        return {\n          tokenize: null,\n          state: \"block\",\n          context: new Context(\"block\", base || 0, null)\n        };\n      },\n      token: function(stream, state) {\n        if (!state.tokenize && stream.eatSpace()) return null;\n        style = (state.tokenize || tokenBase)(stream, state);\n        if (style && typeof style == \"object\") {\n          type = style[1];\n          style = style[0];\n        }\n        override = style;\n        state.state = states[state.state](type, stream, state);\n        return override;\n      },\n      indent: function(state, textAfter, line) {\n\n        var cx = state.context,\n            ch = textAfter && textAfter.charAt(0),\n            indent = cx.indent,\n            lineFirstWord = firstWordOfLine(textAfter),\n            lineIndent = line.match(/^\\s*/)[0].replace(/\\t/g, indentUnitString).length,\n            prevLineFirstWord = state.context.prev ? state.context.prev.line.firstWord : \"\",\n            prevLineIndent = state.context.prev ? state.context.prev.line.indent : lineIndent;\n\n        if (cx.prev &&\n            (ch == \"}\" && (cx.type == \"block\" || cx.type == \"atBlock\" || cx.type == \"keyframes\") ||\n             ch == \")\" && (cx.type == \"parens\" || cx.type == \"atBlock_parens\") ||\n             ch == \"{\" && (cx.type == \"at\"))) {\n          indent = cx.indent - indentUnit;\n        } else if (!(/(\\})/.test(ch))) {\n          if (/@|\\$|\\d/.test(ch) ||\n              /^\\{/.test(textAfter) ||\n/^\\s*\\/(\\/|\\*)/.test(textAfter) ||\n              /^\\s*\\/\\*/.test(prevLineFirstWord) ||\n              /^\\s*[\\w-\\.\\[\\]\\'\\\"]+\\s*(\\?|:|\\+)?=/i.test(textAfter) ||\n/^(\\+|-)?[a-z][\\w-]*\\(/i.test(textAfter) ||\n/^return/.test(textAfter) ||\n              wordIsBlock(lineFirstWord)) {\n            indent = lineIndent;\n          } else if (/(\\.|#|:|\\[|\\*|&|>|~|\\+|\\/)/.test(ch) || wordIsTag(lineFirstWord)) {\n            if (/\\,\\s*$/.test(prevLineFirstWord)) {\n              indent = prevLineIndent;\n            } else if (/^\\s+/.test(line) && (/(\\.|#|:|\\[|\\*|&|>|~|\\+|\\/)/.test(prevLineFirstWord) || wordIsTag(prevLineFirstWord))) {\n              indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit;\n            } else {\n              indent = lineIndent;\n            }\n          } else if (!/,\\s*$/.test(line) && (wordIsVendorPrefix(lineFirstWord) || wordIsProperty(lineFirstWord))) {\n            if (wordIsBlock(prevLineFirstWord)) {\n              indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit;\n            } else if (/^\\{/.test(prevLineFirstWord)) {\n              indent = lineIndent <= prevLineIndent ? lineIndent : prevLineIndent + indentUnit;\n            } else if (wordIsVendorPrefix(prevLineFirstWord) || wordIsProperty(prevLineFirstWord)) {\n              indent = lineIndent >= prevLineIndent ? prevLineIndent : lineIndent;\n            } else if (/^(\\.|#|:|\\[|\\*|&|@|\\+|\\-|>|~|\\/)/.test(prevLineFirstWord) ||\n                      /=\\s*$/.test(prevLineFirstWord) ||\n                      wordIsTag(prevLineFirstWord) ||\n                      /^\\$[\\w-\\.\\[\\]\\'\\\"]/.test(prevLineFirstWord)) {\n              indent = prevLineIndent + indentUnit;\n            } else {\n              indent = lineIndent;\n            }\n          }\n        }\n        return indent;\n      },\n      electricChars: \"}\",\n      lineComment: \"//\",\n      fold: \"indent\"\n    };\n  });\n\n  // developer.mozilla.org/en-US/docs/Web/HTML/Element\n  var tagKeywords_ = [\"a\",\"abbr\",\"address\",\"area\",\"article\",\"aside\",\"audio\", \"b\", \"base\",\"bdi\", \"bdo\",\"bgsound\",\"blockquote\",\"body\",\"br\",\"button\",\"canvas\",\"caption\",\"cite\", \"code\",\"col\",\"colgroup\",\"data\",\"datalist\",\"dd\",\"del\",\"details\",\"dfn\",\"div\", \"dl\",\"dt\",\"em\",\"embed\",\"fieldset\",\"figcaption\",\"figure\",\"footer\",\"form\",\"h1\", \"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"head\",\"header\",\"hgroup\",\"hr\",\"html\",\"i\",\"iframe\", \"img\",\"input\",\"ins\",\"kbd\",\"keygen\",\"label\",\"legend\",\"li\",\"link\",\"main\",\"map\", \"mark\",\"marquee\",\"menu\",\"menuitem\",\"meta\",\"meter\",\"nav\",\"nobr\",\"noframes\", \"noscript\",\"object\",\"ol\",\"optgroup\",\"option\",\"output\",\"p\",\"param\",\"pre\", \"progress\",\"q\",\"rp\",\"rt\",\"ruby\",\"s\",\"samp\",\"script\",\"section\",\"select\", \"small\",\"source\",\"span\",\"strong\",\"style\",\"sub\",\"summary\",\"sup\",\"table\",\"tbody\",\"td\",\"textarea\",\"tfoot\",\"th\",\"thead\",\"time\",\"tr\",\"track\", \"u\",\"ul\",\"var\",\"video\"];\n\n  // github.com/codemirror/CodeMirror/blob/master/mode/css/css.js\n  var documentTypes_ = [\"domain\", \"regexp\", \"url\", \"url-prefix\"];\n  var mediaTypes_ = [\"all\",\"aural\",\"braille\",\"handheld\",\"print\",\"projection\",\"screen\",\"tty\",\"tv\",\"embossed\"];\n  var mediaFeatures_ = [\"width\",\"min-width\",\"max-width\",\"height\",\"min-height\",\"max-height\",\"device-width\",\"min-device-width\",\"max-device-width\",\"device-height\",\"min-device-height\",\"max-device-height\",\"aspect-ratio\",\"min-aspect-ratio\",\"max-aspect-ratio\",\"device-aspect-ratio\",\"min-device-aspect-ratio\",\"max-device-aspect-ratio\",\"color\",\"min-color\",\"max-color\",\"color-index\",\"min-color-index\",\"max-color-index\",\"monochrome\",\"min-monochrome\",\"max-monochrome\",\"resolution\",\"min-resolution\",\"max-resolution\",\"scan\",\"grid\"];\n  var propertyKeywords_ = [\"align-content\",\"align-items\",\"align-self\",\"alignment-adjust\",\"alignment-baseline\",\"anchor-point\",\"animation\",\"animation-delay\",\"animation-direction\",\"animation-duration\",\"animation-fill-mode\",\"animation-iteration-count\",\"animation-name\",\"animation-play-state\",\"animation-timing-function\",\"appearance\",\"azimuth\",\"backface-visibility\",\"background\",\"background-attachment\",\"background-clip\",\"background-color\",\"background-image\",\"background-origin\",\"background-position\",\"background-repeat\",\"background-size\",\"baseline-shift\",\"binding\",\"bleed\",\"bookmark-label\",\"bookmark-level\",\"bookmark-state\",\"bookmark-target\",\"border\",\"border-bottom\",\"border-bottom-color\",\"border-bottom-left-radius\",\"border-bottom-right-radius\",\"border-bottom-style\",\"border-bottom-width\",\"border-collapse\",\"border-color\",\"border-image\",\"border-image-outset\",\"border-image-repeat\",\"border-image-slice\",\"border-image-source\",\"border-image-width\",\"border-left\",\"border-left-color\",\"border-left-style\",\"border-left-width\",\"border-radius\",\"border-right\",\"border-right-color\",\"border-right-style\",\"border-right-width\",\"border-spacing\",\"border-style\",\"border-top\",\"border-top-color\",\"border-top-left-radius\",\"border-top-right-radius\",\"border-top-style\",\"border-top-width\",\"border-width\",\"bottom\",\"box-decoration-break\",\"box-shadow\",\"box-sizing\",\"break-after\",\"break-before\",\"break-inside\",\"caption-side\",\"clear\",\"clip\",\"color\",\"color-profile\",\"column-count\",\"column-fill\",\"column-gap\",\"column-rule\",\"column-rule-color\",\"column-rule-style\",\"column-rule-width\",\"column-span\",\"column-width\",\"columns\",\"content\",\"counter-increment\",\"counter-reset\",\"crop\",\"cue\",\"cue-after\",\"cue-before\",\"cursor\",\"direction\",\"display\",\"dominant-baseline\",\"drop-initial-after-adjust\",\"drop-initial-after-align\",\"drop-initial-before-adjust\",\"drop-initial-before-align\",\"drop-initial-size\",\"drop-initial-value\",\"elevation\",\"empty-cells\",\"fit\",\"fit-position\",\"flex\",\"flex-basis\",\"flex-direction\",\"flex-flow\",\"flex-grow\",\"flex-shrink\",\"flex-wrap\",\"float\",\"float-offset\",\"flow-from\",\"flow-into\",\"font\",\"font-feature-settings\",\"font-family\",\"font-kerning\",\"font-language-override\",\"font-size\",\"font-size-adjust\",\"font-stretch\",\"font-style\",\"font-synthesis\",\"font-variant\",\"font-variant-alternates\",\"font-variant-caps\",\"font-variant-east-asian\",\"font-variant-ligatures\",\"font-variant-numeric\",\"font-variant-position\",\"font-weight\",\"grid\",\"grid-area\",\"grid-auto-columns\",\"grid-auto-flow\",\"grid-auto-position\",\"grid-auto-rows\",\"grid-column\",\"grid-column-end\",\"grid-column-start\",\"grid-row\",\"grid-row-end\",\"grid-row-start\",\"grid-template\",\"grid-template-areas\",\"grid-template-columns\",\"grid-template-rows\",\"hanging-punctuation\",\"height\",\"hyphens\",\"icon\",\"image-orientation\",\"image-rendering\",\"image-resolution\",\"inline-box-align\",\"justify-content\",\"left\",\"letter-spacing\",\"line-break\",\"line-height\",\"line-stacking\",\"line-stacking-ruby\",\"line-stacking-shift\",\"line-stacking-strategy\",\"list-style\",\"list-style-image\",\"list-style-position\",\"list-style-type\",\"margin\",\"margin-bottom\",\"margin-left\",\"margin-right\",\"margin-top\",\"marker-offset\",\"marks\",\"marquee-direction\",\"marquee-loop\",\"marquee-play-count\",\"marquee-speed\",\"marquee-style\",\"max-height\",\"max-width\",\"min-height\",\"min-width\",\"move-to\",\"nav-down\",\"nav-index\",\"nav-left\",\"nav-right\",\"nav-up\",\"object-fit\",\"object-position\",\"opacity\",\"order\",\"orphans\",\"outline\",\"outline-color\",\"outline-offset\",\"outline-style\",\"outline-width\",\"overflow\",\"overflow-style\",\"overflow-wrap\",\"overflow-x\",\"overflow-y\",\"padding\",\"padding-bottom\",\"padding-left\",\"padding-right\",\"padding-top\",\"page\",\"page-break-after\",\"page-break-before\",\"page-break-inside\",\"page-policy\",\"pause\",\"pause-after\",\"pause-before\",\"perspective\",\"perspective-origin\",\"pitch\",\"pitch-range\",\"play-during\",\"position\",\"presentation-level\",\"punctuation-trim\",\"quotes\",\"region-break-after\",\"region-break-before\",\"region-break-inside\",\"region-fragment\",\"rendering-intent\",\"resize\",\"rest\",\"rest-after\",\"rest-before\",\"richness\",\"right\",\"rotation\",\"rotation-point\",\"ruby-align\",\"ruby-overhang\",\"ruby-position\",\"ruby-span\",\"shape-image-threshold\",\"shape-inside\",\"shape-margin\",\"shape-outside\",\"size\",\"speak\",\"speak-as\",\"speak-header\",\"speak-numeral\",\"speak-punctuation\",\"speech-rate\",\"stress\",\"string-set\",\"tab-size\",\"table-layout\",\"target\",\"target-name\",\"target-new\",\"target-position\",\"text-align\",\"text-align-last\",\"text-decoration\",\"text-decoration-color\",\"text-decoration-line\",\"text-decoration-skip\",\"text-decoration-style\",\"text-emphasis\",\"text-emphasis-color\",\"text-emphasis-position\",\"text-emphasis-style\",\"text-height\",\"text-indent\",\"text-justify\",\"text-outline\",\"text-overflow\",\"text-shadow\",\"text-size-adjust\",\"text-space-collapse\",\"text-transform\",\"text-underline-position\",\"text-wrap\",\"top\",\"transform\",\"transform-origin\",\"transform-style\",\"transition\",\"transition-delay\",\"transition-duration\",\"transition-property\",\"transition-timing-function\",\"unicode-bidi\",\"vertical-align\",\"visibility\",\"voice-balance\",\"voice-duration\",\"voice-family\",\"voice-pitch\",\"voice-range\",\"voice-rate\",\"voice-stress\",\"voice-volume\",\"volume\",\"white-space\",\"widows\",\"width\",\"will-change\",\"word-break\",\"word-spacing\",\"word-wrap\",\"z-index\",\"clip-path\",\"clip-rule\",\"mask\",\"enable-background\",\"filter\",\"flood-color\",\"flood-opacity\",\"lighting-color\",\"stop-color\",\"stop-opacity\",\"pointer-events\",\"color-interpolation\",\"color-interpolation-filters\",\"color-rendering\",\"fill\",\"fill-opacity\",\"fill-rule\",\"image-rendering\",\"marker\",\"marker-end\",\"marker-mid\",\"marker-start\",\"shape-rendering\",\"stroke\",\"stroke-dasharray\",\"stroke-dashoffset\",\"stroke-linecap\",\"stroke-linejoin\",\"stroke-miterlimit\",\"stroke-opacity\",\"stroke-width\",\"text-rendering\",\"baseline-shift\",\"dominant-baseline\",\"glyph-orientation-horizontal\",\"glyph-orientation-vertical\",\"text-anchor\",\"writing-mode\",\"font-smoothing\",\"osx-font-smoothing\"];\n  var nonStandardPropertyKeywords_ = [\"scrollbar-arrow-color\",\"scrollbar-base-color\",\"scrollbar-dark-shadow-color\",\"scrollbar-face-color\",\"scrollbar-highlight-color\",\"scrollbar-shadow-color\",\"scrollbar-3d-light-color\",\"scrollbar-track-color\",\"shape-inside\",\"searchfield-cancel-button\",\"searchfield-decoration\",\"searchfield-results-button\",\"searchfield-results-decoration\",\"zoom\"];\n  var fontProperties_ = [\"font-family\",\"src\",\"unicode-range\",\"font-variant\",\"font-feature-settings\",\"font-stretch\",\"font-weight\",\"font-style\"];\n  var colorKeywords_ = [\"aliceblue\",\"antiquewhite\",\"aqua\",\"aquamarine\",\"azure\",\"beige\",\"bisque\",\"black\",\"blanchedalmond\",\"blue\",\"blueviolet\",\"brown\",\"burlywood\",\"cadetblue\",\"chartreuse\",\"chocolate\",\"coral\",\"cornflowerblue\",\"cornsilk\",\"crimson\",\"cyan\",\"darkblue\",\"darkcyan\",\"darkgoldenrod\",\"darkgray\",\"darkgreen\",\"darkkhaki\",\"darkmagenta\",\"darkolivegreen\",\"darkorange\",\"darkorchid\",\"darkred\",\"darksalmon\",\"darkseagreen\",\"darkslateblue\",\"darkslategray\",\"darkturquoise\",\"darkviolet\",\"deeppink\",\"deepskyblue\",\"dimgray\",\"dodgerblue\",\"firebrick\",\"floralwhite\",\"forestgreen\",\"fuchsia\",\"gainsboro\",\"ghostwhite\",\"gold\",\"goldenrod\",\"gray\",\"grey\",\"green\",\"greenyellow\",\"honeydew\",\"hotpink\",\"indianred\",\"indigo\",\"ivory\",\"khaki\",\"lavender\",\"lavenderblush\",\"lawngreen\",\"lemonchiffon\",\"lightblue\",\"lightcoral\",\"lightcyan\",\"lightgoldenrodyellow\",\"lightgray\",\"lightgreen\",\"lightpink\",\"lightsalmon\",\"lightseagreen\",\"lightskyblue\",\"lightslategray\",\"lightsteelblue\",\"lightyellow\",\"lime\",\"limegreen\",\"linen\",\"magenta\",\"maroon\",\"mediumaquamarine\",\"mediumblue\",\"mediumorchid\",\"mediumpurple\",\"mediumseagreen\",\"mediumslateblue\",\"mediumspringgreen\",\"mediumturquoise\",\"mediumvioletred\",\"midnightblue\",\"mintcream\",\"mistyrose\",\"moccasin\",\"navajowhite\",\"navy\",\"oldlace\",\"olive\",\"olivedrab\",\"orange\",\"orangered\",\"orchid\",\"palegoldenrod\",\"palegreen\",\"paleturquoise\",\"palevioletred\",\"papayawhip\",\"peachpuff\",\"peru\",\"pink\",\"plum\",\"powderblue\",\"purple\",\"rebeccapurple\",\"red\",\"rosybrown\",\"royalblue\",\"saddlebrown\",\"salmon\",\"sandybrown\",\"seagreen\",\"seashell\",\"sienna\",\"silver\",\"skyblue\",\"slateblue\",\"slategray\",\"snow\",\"springgreen\",\"steelblue\",\"tan\",\"teal\",\"thistle\",\"tomato\",\"turquoise\",\"violet\",\"wheat\",\"white\",\"whitesmoke\",\"yellow\",\"yellowgreen\"];\n  var valueKeywords_ = [\"above\",\"absolute\",\"activeborder\",\"additive\",\"activecaption\",\"afar\",\"after-white-space\",\"ahead\",\"alias\",\"all\",\"all-scroll\",\"alphabetic\",\"alternate\",\"always\",\"amharic\",\"amharic-abegede\",\"antialiased\",\"appworkspace\",\"arabic-indic\",\"armenian\",\"asterisks\",\"attr\",\"auto\",\"avoid\",\"avoid-column\",\"avoid-page\",\"avoid-region\",\"background\",\"backwards\",\"baseline\",\"below\",\"bidi-override\",\"binary\",\"bengali\",\"blink\",\"block\",\"block-axis\",\"bold\",\"bolder\",\"border\",\"border-box\",\"both\",\"bottom\",\"break\",\"break-all\",\"break-word\",\"bullets\",\"button\",\"button-bevel\",\"buttonface\",\"buttonhighlight\",\"buttonshadow\",\"buttontext\",\"calc\",\"cambodian\",\"capitalize\",\"caps-lock-indicator\",\"caption\",\"captiontext\",\"caret\",\"cell\",\"center\",\"checkbox\",\"circle\",\"cjk-decimal\",\"cjk-earthly-branch\",\"cjk-heavenly-stem\",\"cjk-ideographic\",\"clear\",\"clip\",\"close-quote\",\"col-resize\",\"collapse\",\"column\",\"compact\",\"condensed\",\"contain\",\"content\",\"contents\",\"content-box\",\"context-menu\",\"continuous\",\"copy\",\"counter\",\"counters\",\"cover\",\"crop\",\"cross\",\"crosshair\",\"currentcolor\",\"cursive\",\"cyclic\",\"dashed\",\"decimal\",\"decimal-leading-zero\",\"default\",\"default-button\",\"destination-atop\",\"destination-in\",\"destination-out\",\"destination-over\",\"devanagari\",\"disc\",\"discard\",\"disclosure-closed\",\"disclosure-open\",\"document\",\"dot-dash\",\"dot-dot-dash\",\"dotted\",\"double\",\"down\",\"e-resize\",\"ease\",\"ease-in\",\"ease-in-out\",\"ease-out\",\"element\",\"ellipse\",\"ellipsis\",\"embed\",\"end\",\"ethiopic\",\"ethiopic-abegede\",\"ethiopic-abegede-am-et\",\"ethiopic-abegede-gez\",\"ethiopic-abegede-ti-er\",\"ethiopic-abegede-ti-et\",\"ethiopic-halehame-aa-er\",\"ethiopic-halehame-aa-et\",\"ethiopic-halehame-am-et\",\"ethiopic-halehame-gez\",\"ethiopic-halehame-om-et\",\"ethiopic-halehame-sid-et\",\"ethiopic-halehame-so-et\",\"ethiopic-halehame-ti-er\",\"ethiopic-halehame-ti-et\",\"ethiopic-halehame-tig\",\"ethiopic-numeric\",\"ew-resize\",\"expanded\",\"extends\",\"extra-condensed\",\"extra-expanded\",\"fantasy\",\"fast\",\"fill\",\"fixed\",\"flat\",\"flex\",\"footnotes\",\"forwards\",\"from\",\"geometricPrecision\",\"georgian\",\"graytext\",\"groove\",\"gujarati\",\"gurmukhi\",\"hand\",\"hangul\",\"hangul-consonant\",\"hebrew\",\"help\",\"hidden\",\"hide\",\"higher\",\"highlight\",\"highlighttext\",\"hiragana\",\"hiragana-iroha\",\"horizontal\",\"hsl\",\"hsla\",\"icon\",\"ignore\",\"inactiveborder\",\"inactivecaption\",\"inactivecaptiontext\",\"infinite\",\"infobackground\",\"infotext\",\"inherit\",\"initial\",\"inline\",\"inline-axis\",\"inline-block\",\"inline-flex\",\"inline-table\",\"inset\",\"inside\",\"intrinsic\",\"invert\",\"italic\",\"japanese-formal\",\"japanese-informal\",\"justify\",\"kannada\",\"katakana\",\"katakana-iroha\",\"keep-all\",\"khmer\",\"korean-hangul-formal\",\"korean-hanja-formal\",\"korean-hanja-informal\",\"landscape\",\"lao\",\"large\",\"larger\",\"left\",\"level\",\"lighter\",\"line-through\",\"linear\",\"linear-gradient\",\"lines\",\"list-item\",\"listbox\",\"listitem\",\"local\",\"logical\",\"loud\",\"lower\",\"lower-alpha\",\"lower-armenian\",\"lower-greek\",\"lower-hexadecimal\",\"lower-latin\",\"lower-norwegian\",\"lower-roman\",\"lowercase\",\"ltr\",\"malayalam\",\"match\",\"matrix\",\"matrix3d\",\"media-controls-background\",\"media-current-time-display\",\"media-fullscreen-button\",\"media-mute-button\",\"media-play-button\",\"media-return-to-realtime-button\",\"media-rewind-button\",\"media-seek-back-button\",\"media-seek-forward-button\",\"media-slider\",\"media-sliderthumb\",\"media-time-remaining-display\",\"media-volume-slider\",\"media-volume-slider-container\",\"media-volume-sliderthumb\",\"medium\",\"menu\",\"menulist\",\"menulist-button\",\"menulist-text\",\"menulist-textfield\",\"menutext\",\"message-box\",\"middle\",\"min-intrinsic\",\"mix\",\"mongolian\",\"monospace\",\"move\",\"multiple\",\"myanmar\",\"n-resize\",\"narrower\",\"ne-resize\",\"nesw-resize\",\"no-close-quote\",\"no-drop\",\"no-open-quote\",\"no-repeat\",\"none\",\"normal\",\"not-allowed\",\"nowrap\",\"ns-resize\",\"numbers\",\"numeric\",\"nw-resize\",\"nwse-resize\",\"oblique\",\"octal\",\"open-quote\",\"optimizeLegibility\",\"optimizeSpeed\",\"oriya\",\"oromo\",\"outset\",\"outside\",\"outside-shape\",\"overlay\",\"overline\",\"padding\",\"padding-box\",\"painted\",\"page\",\"paused\",\"persian\",\"perspective\",\"plus-darker\",\"plus-lighter\",\"pointer\",\"polygon\",\"portrait\",\"pre\",\"pre-line\",\"pre-wrap\",\"preserve-3d\",\"progress\",\"push-button\",\"radial-gradient\",\"radio\",\"read-only\",\"read-write\",\"read-write-plaintext-only\",\"rectangle\",\"region\",\"relative\",\"repeat\",\"repeating-linear-gradient\",\"repeating-radial-gradient\",\"repeat-x\",\"repeat-y\",\"reset\",\"reverse\",\"rgb\",\"rgba\",\"ridge\",\"right\",\"rotate\",\"rotate3d\",\"rotateX\",\"rotateY\",\"rotateZ\",\"round\",\"row-resize\",\"rtl\",\"run-in\",\"running\",\"s-resize\",\"sans-serif\",\"scale\",\"scale3d\",\"scaleX\",\"scaleY\",\"scaleZ\",\"scroll\",\"scrollbar\",\"scroll-position\",\"se-resize\",\"searchfield\",\"searchfield-cancel-button\",\"searchfield-decoration\",\"searchfield-results-button\",\"searchfield-results-decoration\",\"semi-condensed\",\"semi-expanded\",\"separate\",\"serif\",\"show\",\"sidama\",\"simp-chinese-formal\",\"simp-chinese-informal\",\"single\",\"skew\",\"skewX\",\"skewY\",\"skip-white-space\",\"slide\",\"slider-horizontal\",\"slider-vertical\",\"sliderthumb-horizontal\",\"sliderthumb-vertical\",\"slow\",\"small\",\"small-caps\",\"small-caption\",\"smaller\",\"solid\",\"somali\",\"source-atop\",\"source-in\",\"source-out\",\"source-over\",\"space\",\"spell-out\",\"square\",\"square-button\",\"start\",\"static\",\"status-bar\",\"stretch\",\"stroke\",\"sub\",\"subpixel-antialiased\",\"super\",\"sw-resize\",\"symbolic\",\"symbols\",\"table\",\"table-caption\",\"table-cell\",\"table-column\",\"table-column-group\",\"table-footer-group\",\"table-header-group\",\"table-row\",\"table-row-group\",\"tamil\",\"telugu\",\"text\",\"text-bottom\",\"text-top\",\"textarea\",\"textfield\",\"thai\",\"thick\",\"thin\",\"threeddarkshadow\",\"threedface\",\"threedhighlight\",\"threedlightshadow\",\"threedshadow\",\"tibetan\",\"tigre\",\"tigrinya-er\",\"tigrinya-er-abegede\",\"tigrinya-et\",\"tigrinya-et-abegede\",\"to\",\"top\",\"trad-chinese-formal\",\"trad-chinese-informal\",\"translate\",\"translate3d\",\"translateX\",\"translateY\",\"translateZ\",\"transparent\",\"ultra-condensed\",\"ultra-expanded\",\"underline\",\"up\",\"upper-alpha\",\"upper-armenian\",\"upper-greek\",\"upper-hexadecimal\",\"upper-latin\",\"upper-norwegian\",\"upper-roman\",\"uppercase\",\"urdu\",\"url\",\"var\",\"vertical\",\"vertical-text\",\"visible\",\"visibleFill\",\"visiblePainted\",\"visibleStroke\",\"visual\",\"w-resize\",\"wait\",\"wave\",\"wider\",\"window\",\"windowframe\",\"windowtext\",\"words\",\"x-large\",\"x-small\",\"xor\",\"xx-large\",\"xx-small\",\"bicubic\",\"optimizespeed\",\"grayscale\",\"row\",\"row-reverse\",\"wrap\",\"wrap-reverse\",\"column-reverse\",\"flex-start\",\"flex-end\",\"space-between\",\"space-around\", \"unset\"];\n\n  var wordOperatorKeywords_ = [\"in\",\"and\",\"or\",\"not\",\"is not\",\"is a\",\"is\",\"isnt\",\"defined\",\"if unless\"],\n      blockKeywords_ = [\"for\",\"if\",\"else\",\"unless\", \"from\", \"to\"],\n      commonAtoms_ = [\"null\",\"true\",\"false\",\"href\",\"title\",\"type\",\"not-allowed\",\"readonly\",\"disabled\"],\n      commonDef_ = [\"@font-face\", \"@keyframes\", \"@media\", \"@viewport\", \"@page\", \"@host\", \"@supports\", \"@block\", \"@css\"];\n\n  var hintWords = tagKeywords_.concat(documentTypes_,mediaTypes_,mediaFeatures_,\n                                      propertyKeywords_,nonStandardPropertyKeywords_,\n                                      colorKeywords_,valueKeywords_,fontProperties_,\n                                      wordOperatorKeywords_,blockKeywords_,\n                                      commonAtoms_,commonDef_);\n\n  function wordRegexp(words) {\n    words = words.sort(function(a,b){return b > a;});\n    return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n  }\n\n  function keySet(array) {\n    var keys = {};\n    for (var i = 0; i < array.length; ++i) keys[array[i]] = true;\n    return keys;\n  }\n\n  function escapeRegExp(text) {\n    return text.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, \"\\\\$&\");\n  }\n\n  CodeMirror.registerHelper(\"hintWords\", \"stylus\", hintWords);\n  CodeMirror.defineMIME(\"text/x-styl\", \"stylus\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/swift/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Swift mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"./swift.js\"></script>\n<style>\n\t.CodeMirror { border: 2px inset #dee; }\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Swift</a>\n  </ul>\n</div>\n\n<article>\n<h2>Swift mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n//\n//  TipCalculatorModel.swift\n//  TipCalculator\n//\n//  Created by Main Account on 12/18/14.\n//  Copyright (c) 2014 Razeware LLC. All rights reserved.\n//\n\nimport Foundation\n\nclass TipCalculatorModel {\n\n  var total: Double\n  var taxPct: Double\n  var subtotal: Double {\n    get {\n      return total / (taxPct + 1)\n    }\n  }\n\n  init(total: Double, taxPct: Double) {\n    self.total = total\n    self.taxPct = taxPct\n  }\n\n  func calcTipWithTipPct(tipPct: Double) -> Double {\n    return subtotal * tipPct\n  }\n\n  func returnPossibleTips() -> [Int: Double] {\n\n    let possibleTipsInferred = [0.15, 0.18, 0.20]\n    let possibleTipsExplicit:[Double] = [0.15, 0.18, 0.20]\n\n    var retval = [Int: Double]()\n    for possibleTip in possibleTipsInferred {\n      let intPct = Int(possibleTip*100)\n      retval[intPct] = calcTipWithTipPct(possibleTip)\n    }\n    return retval\n\n  }\n\n  func funWithStrings() {\n    var numLines = 3\n    print(\"This is a string!\")\n    print(\"\"\"\n          This is a\n          multi-line\n          string!\n          \"\"\")\n    print(\"The preceding string had \\(numLines) lines!\")\n  }\n\n}\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-swift\"\n      });\n    </script>\n\n    <p>A simple mode for Swift</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-swift</code> (Swift code)</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/swift/swift.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Swift mode created by Michael Kaminsky https://github.com/mkaminsky11\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\")\n    mod(require(\"../../lib/codemirror\"))\n  else if (typeof define == \"function\" && define.amd)\n    define([\"../../lib/codemirror\"], mod)\n  else\n    mod(CodeMirror)\n})(function(CodeMirror) {\n  \"use strict\"\n\n  function wordSet(words) {\n    var set = {}\n    for (var i = 0; i < words.length; i++) set[words[i]] = true\n    return set\n  }\n\n  var keywords = wordSet([\"_\",\"var\",\"let\",\"class\",\"enum\",\"extension\",\"import\",\"protocol\",\"struct\",\"func\",\"typealias\",\"associatedtype\",\n                          \"open\",\"public\",\"internal\",\"fileprivate\",\"private\",\"deinit\",\"init\",\"new\",\"override\",\"self\",\"subscript\",\"super\",\n                          \"convenience\",\"dynamic\",\"final\",\"indirect\",\"lazy\",\"required\",\"static\",\"unowned\",\"unowned(safe)\",\"unowned(unsafe)\",\"weak\",\"as\",\"is\",\n                          \"break\",\"case\",\"continue\",\"default\",\"else\",\"fallthrough\",\"for\",\"guard\",\"if\",\"in\",\"repeat\",\"switch\",\"where\",\"while\",\n                          \"defer\",\"return\",\"inout\",\"mutating\",\"nonmutating\",\"catch\",\"do\",\"rethrows\",\"throw\",\"throws\",\"try\",\"didSet\",\"get\",\"set\",\"willSet\",\n                          \"assignment\",\"associativity\",\"infix\",\"left\",\"none\",\"operator\",\"postfix\",\"precedence\",\"precedencegroup\",\"prefix\",\"right\",\n                          \"Any\",\"AnyObject\",\"Type\",\"dynamicType\",\"Self\",\"Protocol\",\"__COLUMN__\",\"__FILE__\",\"__FUNCTION__\",\"__LINE__\"])\n  var definingKeywords = wordSet([\"var\",\"let\",\"class\",\"enum\",\"extension\",\"import\",\"protocol\",\"struct\",\"func\",\"typealias\",\"associatedtype\",\"for\"])\n  var atoms = wordSet([\"true\",\"false\",\"nil\",\"self\",\"super\",\"_\"])\n  var types = wordSet([\"Array\",\"Bool\",\"Character\",\"Dictionary\",\"Double\",\"Float\",\"Int\",\"Int8\",\"Int16\",\"Int32\",\"Int64\",\"Never\",\"Optional\",\"Set\",\"String\",\n                       \"UInt8\",\"UInt16\",\"UInt32\",\"UInt64\",\"Void\"])\n  var operators = \"+-/*%=|&<>~^?!\"\n  var punc = \":;,.(){}[]\"\n  var binary = /^\\-?0b[01][01_]*/\n  var octal = /^\\-?0o[0-7][0-7_]*/\n  var hexadecimal = /^\\-?0x[\\dA-Fa-f][\\dA-Fa-f_]*(?:(?:\\.[\\dA-Fa-f][\\dA-Fa-f_]*)?[Pp]\\-?\\d[\\d_]*)?/\n  var decimal = /^\\-?\\d[\\d_]*(?:\\.\\d[\\d_]*)?(?:[Ee]\\-?\\d[\\d_]*)?/\n  var identifier = /^\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1/\n  var property = /^\\.(?:\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1)/\n  var instruction = /^\\#[A-Za-z]+/\n  var attribute = /^@(?:\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1)/\n  //var regexp = /^\\/(?!\\s)(?:\\/\\/)?(?:\\\\.|[^\\/])+\\//\n\n  function tokenBase(stream, state, prev) {\n    if (stream.sol()) state.indented = stream.indentation()\n    if (stream.eatSpace()) return null\n\n    var ch = stream.peek()\n    if (ch == \"/\") {\n      if (stream.match(\"//\")) {\n        stream.skipToEnd()\n        return \"comment\"\n      }\n      if (stream.match(\"/*\")) {\n        state.tokenize.push(tokenComment)\n        return tokenComment(stream, state)\n      }\n    }\n    if (stream.match(instruction)) return \"builtin\"\n    if (stream.match(attribute)) return \"attribute\"\n    if (stream.match(binary)) return \"number\"\n    if (stream.match(octal)) return \"number\"\n    if (stream.match(hexadecimal)) return \"number\"\n    if (stream.match(decimal)) return \"number\"\n    if (stream.match(property)) return \"property\"\n    if (operators.indexOf(ch) > -1) {\n      stream.next()\n      return \"operator\"\n    }\n    if (punc.indexOf(ch) > -1) {\n      stream.next()\n      stream.match(\"..\")\n      return \"punctuation\"\n    }\n    if (ch = stream.match(/(\"{3}|\"|')/)) {\n      var tokenize = tokenString(ch[0])\n      state.tokenize.push(tokenize)\n      return tokenize(stream, state)\n    }\n\n    if (stream.match(identifier)) {\n      var ident = stream.current()\n      if (types.hasOwnProperty(ident)) return \"variable-2\"\n      if (atoms.hasOwnProperty(ident)) return \"atom\"\n      if (keywords.hasOwnProperty(ident)) {\n        if (definingKeywords.hasOwnProperty(ident))\n          state.prev = \"define\"\n        return \"keyword\"\n      }\n      if (prev == \"define\") return \"def\"\n      return \"variable\"\n    }\n\n    stream.next()\n    return null\n  }\n\n  function tokenUntilClosingParen() {\n    var depth = 0\n    return function(stream, state, prev) {\n      var inner = tokenBase(stream, state, prev)\n      if (inner == \"punctuation\") {\n        if (stream.current() == \"(\") ++depth\n        else if (stream.current() == \")\") {\n          if (depth == 0) {\n            stream.backUp(1)\n            state.tokenize.pop()\n            return state.tokenize[state.tokenize.length - 1](stream, state)\n          }\n          else --depth\n        }\n      }\n      return inner\n    }\n  }\n\n  function tokenString(quote) {\n    var singleLine = quote.length == 1\n    return function(stream, state) {\n      var ch, escaped = false\n      while (ch = stream.next()) {\n        if (escaped) {\n          if (ch == \"(\") {\n            state.tokenize.push(tokenUntilClosingParen())\n            return \"string\"\n          }\n          escaped = false\n        } else if (stream.match(quote)) {\n          state.tokenize.pop()\n          return \"string\"\n        } else {\n          escaped = ch == \"\\\\\"\n        }\n      }\n      if (singleLine) {\n        state.tokenize.pop()\n      }\n      return \"string\"\n    }\n  }\n\n  function tokenComment(stream, state) {\n    var ch\n    while (true) {\n      stream.match(/^[^/*]+/, true)\n      ch = stream.next()\n      if (!ch) break\n      if (ch === \"/\" && stream.eat(\"*\")) {\n        state.tokenize.push(tokenComment)\n      } else if (ch === \"*\" && stream.eat(\"/\")) {\n        state.tokenize.pop()\n      }\n    }\n    return \"comment\"\n  }\n\n  function Context(prev, align, indented) {\n    this.prev = prev\n    this.align = align\n    this.indented = indented\n  }\n\n  function pushContext(state, stream) {\n    var align = stream.match(/^\\s*($|\\/[\\/\\*])/, false) ? null : stream.column() + 1\n    state.context = new Context(state.context, align, state.indented)\n  }\n\n  function popContext(state) {\n    if (state.context) {\n      state.indented = state.context.indented\n      state.context = state.context.prev\n    }\n  }\n\n  CodeMirror.defineMode(\"swift\", function(config) {\n    return {\n      startState: function() {\n        return {\n          prev: null,\n          context: null,\n          indented: 0,\n          tokenize: []\n        }\n      },\n\n      token: function(stream, state) {\n        var prev = state.prev\n        state.prev = null\n        var tokenize = state.tokenize[state.tokenize.length - 1] || tokenBase\n        var style = tokenize(stream, state, prev)\n        if (!style || style == \"comment\") state.prev = prev\n        else if (!state.prev) state.prev = style\n\n        if (style == \"punctuation\") {\n          var bracket = /[\\(\\[\\{]|([\\]\\)\\}])/.exec(stream.current())\n          if (bracket) (bracket[1] ? popContext : pushContext)(state, stream)\n        }\n\n        return style\n      },\n\n      indent: function(state, textAfter) {\n        var cx = state.context\n        if (!cx) return 0\n        var closing = /^[\\]\\}\\)]/.test(textAfter)\n        if (cx.align != null) return cx.align - (closing ? 1 : 0)\n        return cx.indented + (closing ? 0 : config.indentUnit)\n      },\n\n      electricInput: /^\\s*[\\)\\}\\]]$/,\n\n      lineComment: \"//\",\n      blockCommentStart: \"/*\",\n      blockCommentEnd: \"*/\",\n      fold: \"brace\",\n      closeBrackets: \"()[]{}''\\\"\\\"``\"\n    }\n  })\n\n  CodeMirror.defineMIME(\"text/x-swift\",\"swift\")\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/swift/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"swift\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  // Ensure all number types are properly represented.\n  MT(\"numbers\",\n     \"[keyword var] [def a] [operator =] [number 17]\",\n     \"[keyword var] [def b] [operator =] [number -0.5]\",\n     \"[keyword var] [def c] [operator =] [number 0.3456e-4]\",\n     \"[keyword var] [def d] [operator =] [number 345e2]\",\n     \"[keyword var] [def e] [operator =] [number 0o7324]\",\n     \"[keyword var] [def f] [operator =] [number 0b10010]\",\n     \"[keyword var] [def g] [operator =] [number -0x35ade]\",\n     \"[keyword var] [def h] [operator =] [number 0xaea.ep-13]\",\n     \"[keyword var] [def i] [operator =] [number 0x13ep6]\");\n\n  // Variable/class/etc definition.\n  MT(\"definition\",\n     \"[keyword var] [def a] [operator =] [number 5]\",\n     \"[keyword let] [def b][punctuation :] [variable-2 Int] [operator =] [number 10]\",\n     \"[keyword class] [def C] [punctuation {] [punctuation }]\",\n     \"[keyword struct] [def D] [punctuation {] [punctuation }]\",\n     \"[keyword enum] [def E] [punctuation {] [punctuation }]\",\n     \"[keyword extension] [def F] [punctuation {] [punctuation }]\",\n     \"[keyword protocol] [def G] [punctuation {] [punctuation }]\",\n     \"[keyword func] [def h][punctuation ()] [punctuation {] [punctuation }]\",\n     \"[keyword import] [def Foundation]\",\n     \"[keyword typealias] [def NewString] [operator =] [variable-2 String]\",\n     \"[keyword associatedtype] [def I]\",\n     \"[keyword for] [def j] [keyword in] [number 0][punctuation ..][operator <][number 3] [punctuation {] [punctuation }]\");\n\n  // Strings and string interpolation.\n  MT(\"strings\",\n     \"[keyword var] [def a][punctuation :] [variable-2 String] [operator =] [string \\\"test\\\"]\",\n     \"[keyword var] [def b][punctuation :] [variable-2 String] [operator =] [string \\\"\\\\(][variable a][string )\\\"]\",\n     \"[keyword var] [def c] [operator =] [string \\\"\\\"\\\"]\",\n     \"[string multi]\",\n     \"[string line]\",\n     \"[string \\\"test\\\"]\",\n     \"[string \\\"\\\"\\\"]\");\n\n  // Comments.\n  MT(\"comments\",\n     \"[comment // This is a comment]\",\n     \"[comment /* This is another comment */]\",\n     \"[keyword var] [def a] [operator =] [number 5] [comment // Third comment]\");\n\n  // Atoms.\n  MT(\"atoms\",\n     \"[keyword class] [def FooClass] [punctuation {]\",\n     \"  [keyword let] [def fooBool][punctuation :] [variable-2 Bool][operator ?]\",\n     \"  [keyword let] [def fooInt][punctuation :] [variable-2 Int][operator ?]\",\n     \"  [keyword func] [keyword init][punctuation (][variable fooBool][punctuation :] [variable-2 Bool][punctuation ,] [variable barBool][punctuation :] [variable-2 Bool][punctuation )] [punctuation {]\",\n     \"    [atom super][property .init][punctuation ()]\",\n     \"    [atom self][property .fooBool] [operator =] [variable fooBool]\",\n     \"    [variable fooInt] [operator =] [atom nil]\",\n     \"    [keyword if] [variable barBool] [operator ==] [atom true] [punctuation {]\",\n     \"      [variable print][punctuation (][string \\\"True!\\\"][punctuation )]\",\n     \"    [punctuation }] [keyword else] [keyword if] [variable barBool] [operator ==] [atom false] [punctuation {]\",\n     \"      [keyword for] [atom _] [keyword in] [number 0][punctuation ...][number 5] [punctuation {]\",\n     \"        [variable print][punctuation (][string \\\"False!\\\"][punctuation )]\",\n     \"      [punctuation }]\",\n     \"    [punctuation }]\",\n     \"  [punctuation }]\",\n     \"[punctuation }]\");\n\n  // Types.\n  MT(\"types\",\n     \"[keyword var] [def a] [operator =] [variable-2 Array][operator <][variable-2 Int][operator >]\",\n     \"[keyword var] [def b] [operator =] [variable-2 Set][operator <][variable-2 Bool][operator >]\",\n     \"[keyword var] [def c] [operator =] [variable-2 Dictionary][operator <][variable-2 String][punctuation ,][variable-2 Character][operator >]\",\n     \"[keyword var] [def d][punctuation :] [variable-2 Int64][operator ?] [operator =] [variable-2 Optional][punctuation (][number 8][punctuation )]\",\n     \"[keyword func] [def e][punctuation ()] [operator ->] [variable-2 Void] [punctuation {]\",\n     \"  [keyword var] [def e1][punctuation :] [variable-2 Float] [operator =] [number 1.2]\",\n     \"[punctuation }]\",\n     \"[keyword func] [def f][punctuation ()] [operator ->] [variable-2 Never] [punctuation {]\",\n     \"  [keyword var] [def f1][punctuation :] [variable-2 Double] [operator =] [number 2.4]\",\n     \"[punctuation }]\");\n\n  // Operators.\n  MT(\"operators\",\n     \"[keyword var] [def a] [operator =] [number 1] [operator +] [number 2]\",\n     \"[keyword var] [def b] [operator =] [number 1] [operator -] [number 2]\",\n     \"[keyword var] [def c] [operator =] [number 1] [operator *] [number 2]\",\n     \"[keyword var] [def d] [operator =] [number 1] [operator /] [number 2]\",\n     \"[keyword var] [def e] [operator =] [number 1] [operator %] [number 2]\",\n     \"[keyword var] [def f] [operator =] [number 1] [operator |] [number 2]\",\n     \"[keyword var] [def g] [operator =] [number 1] [operator &] [number 2]\",\n     \"[keyword var] [def h] [operator =] [number 1] [operator <<] [number 2]\",\n     \"[keyword var] [def i] [operator =] [number 1] [operator >>] [number 2]\",\n     \"[keyword var] [def j] [operator =] [number 1] [operator ^] [number 2]\",\n     \"[keyword var] [def k] [operator =] [operator ~][number 1]\",\n     \"[keyword var] [def l] [operator =] [variable foo] [operator ?] [number 1] [punctuation :] [number 2]\",\n     \"[keyword var] [def m][punctuation :] [variable-2 Int] [operator =] [variable-2 Optional][punctuation (][number 8][punctuation )][operator !]\");\n\n  // Punctuation.\n  MT(\"punctuation\",\n     \"[keyword let] [def a] [operator =] [number 1][punctuation ;] [keyword let] [def b] [operator =] [number 2]\",\n     \"[keyword let] [def testArr][punctuation :] [punctuation [[][variable-2 Int][punctuation ]]] [operator =] [punctuation [[][variable a][punctuation ,] [variable b][punctuation ]]]\",\n     \"[keyword for] [def i] [keyword in] [number 0][punctuation ..][operator <][variable testArr][property .count] [punctuation {]\",\n     \"  [variable print][punctuation (][variable testArr][punctuation [[][variable i][punctuation ]])]\",\n     \"[punctuation }]\");\n\n  // Identifiers.\n  MT(\"identifiers\",\n     \"[keyword let] [def abc] [operator =] [number 1]\",\n     \"[keyword let] [def ABC] [operator =] [number 2]\",\n     \"[keyword let] [def _123] [operator =] [number 3]\",\n     \"[keyword let] [def _$1$2$3] [operator =] [number 4]\",\n     \"[keyword let] [def A1$_c32_$_] [operator =] [number 5]\",\n     \"[keyword let] [def `var`] [operator =] [punctuation [[][number 1][punctuation ,] [number 2][punctuation ,] [number 3][punctuation ]]]\",\n     \"[keyword let] [def square$] [operator =] [variable `var`][property .map] [punctuation {][variable $0] [operator *] [variable $0][punctuation }]\",\n     \"$$ [number 1][variable a] $[atom _] [variable _$] [variable __] `[variable a] [variable b]`\");\n\n  // Properties.\n  MT(\"properties\",\n     \"[variable print][punctuation (][variable foo][property .abc][punctuation )]\",\n     \"[variable print][punctuation (][variable foo][property .ABC][punctuation )]\",\n     \"[variable print][punctuation (][variable foo][property ._123][punctuation )]\",\n     \"[variable print][punctuation (][variable foo][property ._$1$2$3][punctuation )]\",\n     \"[variable print][punctuation (][variable foo][property .A1$_c32_$_][punctuation )]\",\n     \"[variable print][punctuation (][variable foo][property .`var`][punctuation )]\",\n     \"[variable print][punctuation (][variable foo][property .__][punctuation )]\");\n\n  // Instructions or other things that start with #.\n  MT(\"instructions\",\n     \"[keyword if] [builtin #available][punctuation (][variable iOS] [number 9][punctuation ,] [operator *][punctuation )] [punctuation {}]\",\n     \"[variable print][punctuation (][builtin #file][punctuation ,] [builtin #function][punctuation )]\",\n     \"[variable print][punctuation (][builtin #line][punctuation ,] [builtin #column][punctuation )]\",\n     \"[builtin #if] [atom true]\",\n     \"[keyword import] [def A]\",\n     \"[builtin #elseif] [atom false]\",\n     \"[keyword import] [def B]\",\n     \"[builtin #endif]\",\n     \"[builtin #sourceLocation][punctuation (][variable file][punctuation :] [string \\\"file.swift\\\"][punctuation ,] [variable line][punctuation :] [number 2][punctuation )]\");\n\n  // Attributes; things that start with @.\n  MT(\"attributes\",\n     \"[attribute @objc][punctuation (][variable objcFoo][punctuation :)]\",\n     \"[attribute @available][punctuation (][variable iOS][punctuation )]\");\n\n  // Property/number edge case.\n  MT(\"property_number\",\n     \"[variable print][punctuation (][variable foo][property ._123][punctuation )]\",\n     \"[variable print][punctuation (]\")\n\n  MT(\"nested_comments\",\n     \"[comment /*]\",\n     \"[comment But wait /* this is a nested comment */ for real]\",\n     \"[comment /**** let * me * show * you ****/]\",\n     \"[comment ///// let / me / show / you /////]\",\n     \"[comment */]\");\n\n  // TODO: correctly identify when multiple variables are being declared\n  // by use of a comma-separated list.\n  // TODO: correctly identify when variables are being declared in a tuple.\n  // TODO: identify protocols as types when used before an extension?\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/tcl/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Tcl mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/night.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"tcl.js\"></script>\n<script src=\"../../addon/scroll/scrollpastend.js\"></script>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Tcl</a>\n  </ul>\n</div>\n\n<article>\n<h2>Tcl mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n##############################################################################################\n##  ##     whois.tcl for eggdrop by Ford_Lawnmower irc.geekshed.net #Script-Help        ##  ##\n##############################################################################################\n## To use this script you must set channel flag +whois (ie .chanset #chan +whois)           ##\n##############################################################################################\n##      ____                __                 ###########################################  ##\n##     / __/___ _ ___ _ ___/ /____ ___   ___   ###########################################  ##\n##    / _/ / _ `// _ `// _  // __// _ \\ / _ \\  ###########################################  ##\n##   /___/ \\_, / \\_, / \\_,_//_/   \\___// .__/  ###########################################  ##\n##        /___/ /___/                 /_/      ###########################################  ##\n##                                             ###########################################  ##\n##############################################################################################\n##  ##                             Start Setup.                                         ##  ##\n##############################################################################################\nnamespace eval whois {\n## change cmdchar to the trigger you want to use                                        ##  ##\n  variable cmdchar \"!\"\n## change command to the word trigger you would like to use.                            ##  ##\n## Keep in mind, This will also change the .chanset +/-command                          ##  ##\n  variable command \"whois\"\n## change textf to the colors you want for the text.                                    ##  ##\n  variable textf \"\\017\\00304\"\n## change tagf to the colors you want for tags:                                         ##  ##\n  variable tagf \"\\017\\002\"\n## Change logo to the logo you want at the start of the line.                           ##  ##\n  variable logo \"\\017\\00304\\002\\[\\00306W\\003hois\\00304\\]\\017\"\n## Change lineout to the results you want. Valid results are channel users modes topic  ##  ##\n  variable lineout \"channel users modes topic\"\n##############################################################################################\n##  ##                           End Setup.                                              ## ##\n##############################################################################################\n  variable channel \"\"\n  setudef flag $whois::command\n  bind pub -|- [string trimleft $whois::cmdchar]${whois::command} whois::list\n  bind raw -|- \"311\" whois::311\n  bind raw -|- \"312\" whois::312\n  bind raw -|- \"319\" whois::319\n  bind raw -|- \"317\" whois::317\n  bind raw -|- \"313\" whois::multi\n  bind raw -|- \"310\" whois::multi\n  bind raw -|- \"335\" whois::multi\n  bind raw -|- \"301\" whois::301\n  bind raw -|- \"671\" whois::multi\n  bind raw -|- \"320\" whois::multi\n  bind raw -|- \"401\" whois::multi\n  bind raw -|- \"318\" whois::318\n  bind raw -|- \"307\" whois::307\n}\nproc whois::311 {from key text} {\n  if {[regexp -- {^[^\\s]+\\s(.+?)\\s(.+?)\\s(.+?)\\s\\*\\s\\:(.+)$} $text wholematch nick ident host realname]} {\n    putserv \"PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Host:${whois::textf} \\\n        $nick \\(${ident}@${host}\\) ${whois::tagf}Realname:${whois::textf} $realname\"\n  }\n}\nproc whois::multi {from key text} {\n  if {[regexp {\\:(.*)$} $text match $key]} {\n    putserv \"PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Note:${whois::textf} [subst $$key]\"\n        return 1\n  }\n}\nproc whois::312 {from key text} {\n  regexp {([^\\s]+)\\s\\:} $text match server\n  putserv \"PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Server:${whois::textf} $server\"\n}\nproc whois::319 {from key text} {\n  if {[regexp {.+\\:(.+)$} $text match channels]} {\n    putserv \"PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Channels:${whois::textf} $channels\"\n  }\n}\nproc whois::317 {from key text} {\n  if {[regexp -- {.*\\s(\\d+)\\s(\\d+)\\s\\:} $text wholematch idle signon]} {\n    putserv \"PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Connected:${whois::textf} \\\n        [ctime $signon] ${whois::tagf}Idle:${whois::textf} [duration $idle]\"\n  }\n}\nproc whois::301 {from key text} {\n  if {[regexp {^.+\\s[^\\s]+\\s\\:(.*)$} $text match awaymsg]} {\n    putserv \"PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Away:${whois::textf} $awaymsg\"\n  }\n}\nproc whois::318 {from key text} {\n  namespace eval whois {\n        variable channel \"\"\n  }\n  variable whois::channel \"\"\n}\nproc whois::307 {from key text} {\n  putserv \"PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Services:${whois::textf} Registered Nick\"\n}\nproc whois::list {nick host hand chan text} {\n  if {[lsearch -exact [channel info $chan] \"+${whois::command}\"] != -1} {\n    namespace eval whois {\n          variable channel \"\"\n        }\n    variable whois::channel $chan\n    putserv \"WHOIS $text\"\n  }\n}\nputlog \"\\002*Loaded* \\017\\00304\\002\\[\\00306W\\003hois\\00304\\]\\017 \\002by \\\nFord_Lawnmower irc.GeekShed.net #Script-Help\"\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        theme: \"night\",\n        lineNumbers: true,\n        indentUnit: 2,\n        scrollPastEnd: true,\n        mode: \"text/x-tcl\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-tcl</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/tcl/tcl.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n//tcl mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"tcl\", function() {\n  function parseWords(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n  var keywords = parseWords(\"Tcl safe after append array auto_execok auto_import auto_load \" +\n        \"auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror \" +\n        \"binary break catch cd close concat continue dde eof encoding error \" +\n        \"eval exec exit expr fblocked fconfigure fcopy file fileevent filename \" +\n        \"filename flush for foreach format gets glob global history http if \" +\n        \"incr info interp join lappend lindex linsert list llength load lrange \" +\n        \"lreplace lsearch lset lsort memory msgcat namespace open package parray \" +\n        \"pid pkg::create pkg_mkIndex proc puts pwd re_syntax read regex regexp \" +\n        \"registry regsub rename resource return scan seek set socket source split \" +\n        \"string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord \" +\n        \"tcl_wordBreakAfter tcl_startOfPreviousWord tcl_wordBreakBefore tcltest \" +\n        \"tclvars tell time trace unknown unset update uplevel upvar variable \" +\n    \"vwait\");\n    var functions = parseWords(\"if elseif else and not or eq ne in ni for foreach while switch\");\n    var isOperatorChar = /[+\\-*&%=<>!?^\\/\\|]/;\n    function chain(stream, state, f) {\n      state.tokenize = f;\n      return f(stream, state);\n    }\n    function tokenBase(stream, state) {\n      var beforeParams = state.beforeParams;\n      state.beforeParams = false;\n      var ch = stream.next();\n      if ((ch == '\"' || ch == \"'\") && state.inParams) {\n        return chain(stream, state, tokenString(ch));\n      } else if (/[\\[\\]{}\\(\\),;\\.]/.test(ch)) {\n        if (ch == \"(\" && beforeParams) state.inParams = true;\n        else if (ch == \")\") state.inParams = false;\n          return null;\n      } else if (/\\d/.test(ch)) {\n        stream.eatWhile(/[\\w\\.]/);\n        return \"number\";\n      } else if (ch == \"#\") {\n        if (stream.eat(\"*\"))\n          return chain(stream, state, tokenComment);\n        if (ch == \"#\" && stream.match(/ *\\[ *\\[/))\n          return chain(stream, state, tokenUnparsed);\n        stream.skipToEnd();\n        return \"comment\";\n      } else if (ch == '\"') {\n        stream.skipTo(/\"/);\n        return \"comment\";\n      } else if (ch == \"$\") {\n        stream.eatWhile(/[$_a-z0-9A-Z\\.{:]/);\n        stream.eatWhile(/}/);\n        state.beforeParams = true;\n        return \"builtin\";\n      } else if (isOperatorChar.test(ch)) {\n        stream.eatWhile(isOperatorChar);\n        return \"comment\";\n      } else {\n        stream.eatWhile(/[\\w\\$_{}\\xa1-\\uffff]/);\n        var word = stream.current().toLowerCase();\n        if (keywords && keywords.propertyIsEnumerable(word))\n          return \"keyword\";\n        if (functions && functions.propertyIsEnumerable(word)) {\n          state.beforeParams = true;\n          return \"keyword\";\n        }\n        return null;\n      }\n    }\n    function tokenString(quote) {\n      return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {\n          end = true;\n          break;\n        }\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end) state.tokenize = tokenBase;\n        return \"string\";\n      };\n    }\n    function tokenComment(stream, state) {\n      var maybeEnd = false, ch;\n      while (ch = stream.next()) {\n        if (ch == \"#\" && maybeEnd) {\n          state.tokenize = tokenBase;\n          break;\n        }\n        maybeEnd = (ch == \"*\");\n      }\n      return \"comment\";\n    }\n    function tokenUnparsed(stream, state) {\n      var maybeEnd = 0, ch;\n      while (ch = stream.next()) {\n        if (ch == \"#\" && maybeEnd == 2) {\n          state.tokenize = tokenBase;\n          break;\n        }\n        if (ch == \"]\")\n          maybeEnd++;\n        else if (ch != \" \")\n          maybeEnd = 0;\n      }\n      return \"meta\";\n    }\n    return {\n      startState: function() {\n        return {\n          tokenize: tokenBase,\n          beforeParams: false,\n          inParams: false\n        };\n      },\n      token: function(stream, state) {\n        if (stream.eatSpace()) return null;\n        return state.tokenize(stream, state);\n      }\n    };\n});\nCodeMirror.defineMIME(\"text/x-tcl\", \"tcl\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/textile/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Textile mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"textile.js\"></script>\n<style>.CodeMirror {background: #f8f8f8;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/marijnh/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=\"active\" href=\"#\">Textile</a>\n  </ul>\n</div>\n\n<article>\n    <h2>Textile mode</h2>\n    <form><textarea id=\"code\" name=\"code\">\nh1. Textile Mode\n\nA paragraph without formatting.\n\np. A simple Paragraph.\n\n\nh2. Phrase Modifiers\n\nHere are some simple phrase modifiers: *strong*, _emphasis_, **bold**, and __italic__.\n\nA ??citation??, -deleted text-, +inserted text+, some ^superscript^, and some ~subscript~.\n\nA %span element% and @code element@\n\nA \"link\":http://example.com, a \"link with (alt text)\":urlAlias\n\n[urlAlias]http://example.com/\n\nAn image: !http://example.com/image.png! and an image with a link: !http://example.com/image.png!:http://example.com\n\nA sentence with a footnote.[123]\n\nfn123. The footnote is defined here.\n\nRegistered(r), Trademark(tm), and Copyright(c)\n\n\nh2. Headers\n\nh1. Top level\nh2. Second level\nh3. Third level\nh4. Fourth level\nh5. Fifth level\nh6. Lowest level\n\n\nh2.  Lists\n\n* An unordered list\n** foo bar\n*** foo bar\n**** foo bar\n** foo bar\n\n# An ordered list\n## foo bar\n### foo bar\n#### foo bar\n## foo bar\n\n- definition list := description\n- another item    := foo bar\n- spanning ines   :=\n                     foo bar\n\n                     foo bar =:\n\n\nh2. Attributes\n\nLayouts and phrase modifiers can be modified with various kinds of attributes: alignment, CSS ID, CSS class names, language, padding, and CSS styles.\n\nh3. Alignment\n\ndiv<. left align\ndiv>. right align\n\nh3. CSS ID and class name\n\nYou are a %(my-id#my-classname) rad% person.\n\nh3. Language\n\np[en_CA]. Strange weather, eh?\n\nh3. Horizontal Padding\n\np(())). 2em left padding, 3em right padding\n\nh3. CSS styling\n\np{background: red}. Fire!\n\n\nh2. Table\n\n|_.              Header 1               |_.      Header 2        |\n|{background:#ddd}. Cell with background|         Normal         |\n|\\2.         Cell spanning 2 columns                             |\n|/2.         Cell spanning 2 rows       |(cell-class). one       |\n|                                                two             |\n|>.                  Right aligned cell |<. Left aligned cell    |\n\n\nh3. A table with attributes:\n\ntable(#prices).\n|Adults|$5|\n|Children|$2|\n\n\nh2. Code blocks\n\nbc.\nfunction factorial(n) {\n    if (n === 0) {\n        return 1;\n    }\n    return n * factorial(n - 1);\n}\n\npre..\n                ,,,,,,\n            o#'9MMHb':'-,o,\n         .oH\":HH$' \"' ' -*R&o,\n        dMMM*\"\"'`'      .oM\"HM?.\n       ,MMM'          \"HLbd< ?&H\\\n      .:MH .\"\\          ` MM  MM&b\n     . \"*H    -        &MMMMMMMMMH:\n     .    dboo        MMMMMMMMMMMM.\n     .   dMMMMMMb      *MMMMMMMMMP.\n     .    MMMMMMMP        *MMMMMP .\n          `#MMMMM           MM6P ,\n       '    `MMMP\"           HM*`,\n        '    :MM             .- ,\n         '.   `#?..  .       ..'\n            -.   .         .-\n              ''-.oo,oo.-''\n\n\\. _(9>\n \\==_)\n  -'=\n\nh2. Temporarily disabling textile markup\n\nnotextile. Don't __touch this!__\n\nSurround text with double-equals to disable textile inline. Example: Use ==*asterisks*== for *strong* text.\n\n\nh2. HTML\n\nSome block layouts are simply textile versions of HTML tags with the same name, like @div@, @pre@, and @p@. HTML tags can also exist on their own line:\n\n<section>\n  <h1>Title</h1>\n  <p>Hello!</p>\n</section>\n\n</textarea></form>\n    <script>\n        var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n            lineNumbers: true,\n            mode: \"text/x-textile\"\n        });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-textile</code>.</p>\n\n    <p><strong>Parsing/Highlighting Tests:</strong> <a href=\"../../test/index.html#textile_*\">normal</a>,  <a href=\"../../test/index.html#verbose,textile_*\">verbose</a>.</p>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/textile/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({tabSize: 4}, 'textile');\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT('simpleParagraphs',\n      'Some text.',\n      '',\n      'Some more text.');\n\n  /*\n   * Phrase Modifiers\n   */\n\n  MT('em',\n      'foo [em _bar_]');\n\n  MT('emBoogus',\n      'code_mirror');\n\n  MT('strong',\n      'foo [strong *bar*]');\n\n  MT('strongBogus',\n      '3 * 3 = 9');\n\n  MT('italic',\n      'foo [em __bar__]');\n\n  MT('italicBogus',\n      'code__mirror');\n\n  MT('bold',\n      'foo [strong **bar**]');\n\n  MT('boldBogus',\n      '3 ** 3 = 27');\n\n  MT('simpleLink',\n      '[link \"CodeMirror\":https://codemirror.net]');\n\n  MT('referenceLink',\n      '[link \"CodeMirror\":code_mirror]',\n      'Normal Text.',\n      '[link [[code_mirror]]https://codemirror.net]');\n\n  MT('footCite',\n      'foo bar[qualifier [[1]]]');\n\n  MT('footCiteBogus',\n      'foo bar[[1a2]]');\n\n  MT('special-characters',\n          'Registered [tag (r)], ' +\n          'Trademark [tag (tm)], and ' +\n          'Copyright [tag (c)] 2008');\n\n  MT('cite',\n      \"A book is [keyword ??The Count of Monte Cristo??] by Dumas.\");\n\n  MT('additionAndDeletion',\n      'The news networks declared [negative -Al Gore-] ' +\n        '[positive +George W. Bush+] the winner in Florida.');\n\n  MT('subAndSup',\n      'f(x, n) = log [builtin ~4~] x [builtin ^n^]');\n\n  MT('spanAndCode',\n      'A [quote %span element%] and [atom @code element@]');\n\n  MT('spanBogus',\n      'Percentage 25% is not a span.');\n\n  MT('citeBogus',\n      'Question? is not a citation.');\n\n  MT('codeBogus',\n      'user@example.com');\n\n  MT('subBogus',\n      '~username');\n\n  MT('supBogus',\n      'foo ^ bar');\n\n  MT('deletionBogus',\n      '3 - 3 = 0');\n\n  MT('additionBogus',\n      '3 + 3 = 6');\n\n  MT('image',\n      'An image: [string !http://www.example.com/image.png!]');\n\n  MT('imageWithAltText',\n      'An image: [string !http://www.example.com/image.png (Alt Text)!]');\n\n  MT('imageWithUrl',\n      'An image: [string !http://www.example.com/image.png!:http://www.example.com/]');\n\n  /*\n   * Headers\n   */\n\n  MT('h1',\n      '[header&header-1 h1. foo]');\n\n  MT('h2',\n      '[header&header-2 h2. foo]');\n\n  MT('h3',\n      '[header&header-3 h3. foo]');\n\n  MT('h4',\n      '[header&header-4 h4. foo]');\n\n  MT('h5',\n      '[header&header-5 h5. foo]');\n\n  MT('h6',\n      '[header&header-6 h6. foo]');\n\n  MT('h7Bogus',\n      'h7. foo');\n\n  MT('multipleHeaders',\n      '[header&header-1 h1. Heading 1]',\n      '',\n      'Some text.',\n      '',\n      '[header&header-2 h2. Heading 2]',\n      '',\n      'More text.');\n\n  MT('h1inline',\n      '[header&header-1 h1. foo ][header&header-1&em _bar_][header&header-1  baz]');\n\n  /*\n   * Lists\n   */\n\n  MT('ul',\n      'foo',\n      'bar',\n      '',\n      '[variable-2 * foo]',\n      '[variable-2 * bar]');\n\n  MT('ulNoBlank',\n      'foo',\n      'bar',\n      '[variable-2 * foo]',\n      '[variable-2 * bar]');\n\n  MT('ol',\n      'foo',\n      'bar',\n      '',\n      '[variable-2 # foo]',\n      '[variable-2 # bar]');\n\n  MT('olNoBlank',\n      'foo',\n      'bar',\n      '[variable-2 # foo]',\n      '[variable-2 # bar]');\n\n  MT('ulFormatting',\n      '[variable-2 * ][variable-2&em _foo_][variable-2  bar]',\n      '[variable-2 * ][variable-2&strong *][variable-2&em&strong _foo_]' +\n        '[variable-2&strong *][variable-2  bar]',\n      '[variable-2 * ][variable-2&strong *foo*][variable-2  bar]');\n\n  MT('olFormatting',\n      '[variable-2 # ][variable-2&em _foo_][variable-2  bar]',\n      '[variable-2 # ][variable-2&strong *][variable-2&em&strong _foo_]' +\n        '[variable-2&strong *][variable-2  bar]',\n      '[variable-2 # ][variable-2&strong *foo*][variable-2  bar]');\n\n  MT('ulNested',\n      '[variable-2 * foo]',\n      '[variable-3 ** bar]',\n      '[keyword *** bar]',\n      '[variable-2 **** bar]',\n      '[variable-3 ** bar]');\n\n  MT('olNested',\n      '[variable-2 # foo]',\n      '[variable-3 ## bar]',\n      '[keyword ### bar]',\n      '[variable-2 #### bar]',\n      '[variable-3 ## bar]');\n\n  MT('ulNestedWithOl',\n      '[variable-2 * foo]',\n      '[variable-3 ## bar]',\n      '[keyword *** bar]',\n      '[variable-2 #### bar]',\n      '[variable-3 ** bar]');\n\n  MT('olNestedWithUl',\n      '[variable-2 # foo]',\n      '[variable-3 ** bar]',\n      '[keyword ### bar]',\n      '[variable-2 **** bar]',\n      '[variable-3 ## bar]');\n\n  MT('definitionList',\n      '[number - coffee := Hot ][number&em _and_][number  black]',\n      '',\n      'Normal text.');\n\n  MT('definitionListSpan',\n      '[number - coffee :=]',\n      '',\n      '[number Hot ][number&em _and_][number  black =:]',\n      '',\n      'Normal text.');\n\n  MT('boo',\n      '[number - dog := woof woof]',\n      '[number - cat := meow meow]',\n      '[number - whale :=]',\n      '[number Whale noises.]',\n      '',\n      '[number Also, ][number&em _splashing_][number . =:]');\n\n  /*\n   * Attributes\n   */\n\n  MT('divWithAttribute',\n      '[punctuation div][punctuation&attribute (#my-id)][punctuation . foo bar]');\n\n  MT('divWithAttributeAnd2emRightPadding',\n      '[punctuation div][punctuation&attribute (#my-id)((][punctuation . foo bar]');\n\n  MT('divWithClassAndId',\n      '[punctuation div][punctuation&attribute (my-class#my-id)][punctuation . foo bar]');\n\n  MT('paragraphWithCss',\n      'p[attribute {color:red;}]. foo bar');\n\n  MT('paragraphNestedStyles',\n      'p. [strong *foo ][strong&em _bar_][strong *]');\n\n  MT('paragraphWithLanguage',\n      'p[attribute [[fr]]]. Parlez-vous français?');\n\n  MT('paragraphLeftAlign',\n      'p[attribute <]. Left');\n\n  MT('paragraphRightAlign',\n      'p[attribute >]. Right');\n\n  MT('paragraphRightAlign',\n      'p[attribute =]. Center');\n\n  MT('paragraphJustified',\n      'p[attribute <>]. Justified');\n\n  MT('paragraphWithLeftIndent1em',\n      'p[attribute (]. Left');\n\n  MT('paragraphWithRightIndent1em',\n      'p[attribute )]. Right');\n\n  MT('paragraphWithLeftIndent2em',\n      'p[attribute ((]. Left');\n\n  MT('paragraphWithRightIndent2em',\n      'p[attribute ))]. Right');\n\n  MT('paragraphWithLeftIndent3emRightIndent2em',\n      'p[attribute ((())]. Right');\n\n  MT('divFormatting',\n      '[punctuation div. ][punctuation&strong *foo ]' +\n        '[punctuation&strong&em _bar_][punctuation&strong *]');\n\n  MT('phraseModifierAttributes',\n      'p[attribute (my-class)]. This is a paragraph that has a class and' +\n      ' this [em _][em&attribute (#special-phrase)][em emphasized phrase_]' +\n      ' has an id.');\n\n  MT('linkWithClass',\n      '[link \"(my-class). This is a link with class\":http://redcloth.org]');\n\n  /*\n   * Layouts\n   */\n\n  MT('paragraphLayouts',\n      'p. This is one paragraph.',\n      '',\n      'p. This is another.');\n\n  MT('div',\n      '[punctuation div. foo bar]');\n\n  MT('pre',\n      '[operator pre. Text]');\n\n  MT('bq.',\n      '[bracket bq. foo bar]',\n      '',\n      'Normal text.');\n\n  MT('footnote',\n      '[variable fn123. foo ][variable&strong *bar*]');\n\n  /*\n   * Spanning Layouts\n   */\n\n  MT('bq..ThenParagraph',\n      '[bracket bq.. foo bar]',\n      '',\n      '[bracket More quote.]',\n      'p. Normal Text');\n\n  MT('bq..ThenH1',\n      '[bracket bq.. foo bar]',\n      '',\n      '[bracket More quote.]',\n      '[header&header-1 h1. Header Text]');\n\n  MT('bc..ThenParagraph',\n      '[atom bc.. # Some ruby code]',\n      '[atom obj = {foo: :bar}]',\n      '[atom puts obj]',\n      '',\n      '[atom obj[[:love]] = \"*love*\"]',\n      '[atom puts obj.love.upcase]',\n      '',\n      'p. Normal text.');\n\n  MT('fn1..ThenParagraph',\n      '[variable fn1.. foo bar]',\n      '',\n      '[variable More.]',\n      'p. Normal Text');\n\n  MT('pre..ThenParagraph',\n      '[operator pre.. foo bar]',\n      '',\n      '[operator More.]',\n      'p. Normal Text');\n\n  /*\n   * Tables\n   */\n\n  MT('table',\n      '[variable-3&operator |_. name |_. age|]',\n      '[variable-3 |][variable-3&strong *Walter*][variable-3 |   5  |]',\n      '[variable-3 |Florence|   6  |]',\n      '',\n      'p. Normal text.');\n\n  MT('tableWithAttributes',\n      '[variable-3&operator |_. name |_. age|]',\n      '[variable-3 |][variable-3&attribute /2.][variable-3  Jim |]',\n      '[variable-3 |][variable-3&attribute \\\\2{color: red}.][variable-3  Sam |]');\n\n  /*\n   * HTML\n   */\n\n  MT('html',\n      '[comment <div id=\"wrapper\">]',\n      '[comment <section id=\"introduction\">]',\n      '',\n      '[header&header-1 h1. Welcome]',\n      '',\n      '[variable-2 * Item one]',\n      '[variable-2 * Item two]',\n      '',\n      '[comment <a href=\"http://example.com\">Example</a>]',\n      '',\n      '[comment </section>]',\n      '[comment </div>]');\n\n  MT('inlineHtml',\n      'I can use HTML directly in my [comment <span class=\"youbetcha\">Textile</span>].');\n\n  /*\n   * No-Textile\n   */\n\n  MT('notextile',\n    '[string-2 notextile. *No* formatting]');\n\n  MT('notextileInline',\n      'Use [string-2 ==*asterisks*==] for [strong *strong*] text.');\n\n  MT('notextileWithPre',\n      '[operator pre. *No* formatting]');\n\n  MT('notextileWithSpanningPre',\n      '[operator pre.. *No* formatting]',\n      '',\n      '[operator *No* formatting]');\n\n  /* Only toggling phrases between non-word chars. */\n\n  MT('phrase-in-word',\n     'foo_bar_baz');\n\n  MT('phrase-non-word',\n     '[negative -x-] aaa-bbb ccc-ddd [negative -eee-] fff [negative -ggg-]');\n\n  MT('phrase-lone-dash',\n     'foo - bar - baz');\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/textile/textile.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") { // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  } else if (typeof define == \"function\" && define.amd) { // AMD\n    define([\"../../lib/codemirror\"], mod);\n  } else { // Plain browser env\n    mod(CodeMirror);\n  }\n})(function(CodeMirror) {\n  \"use strict\";\n\n  var TOKEN_STYLES = {\n    addition: \"positive\",\n    attributes: \"attribute\",\n    bold: \"strong\",\n    cite: \"keyword\",\n    code: \"atom\",\n    definitionList: \"number\",\n    deletion: \"negative\",\n    div: \"punctuation\",\n    em: \"em\",\n    footnote: \"variable\",\n    footCite: \"qualifier\",\n    header: \"header\",\n    html: \"comment\",\n    image: \"string\",\n    italic: \"em\",\n    link: \"link\",\n    linkDefinition: \"link\",\n    list1: \"variable-2\",\n    list2: \"variable-3\",\n    list3: \"keyword\",\n    notextile: \"string-2\",\n    pre: \"operator\",\n    p: \"property\",\n    quote: \"bracket\",\n    span: \"quote\",\n    specialChar: \"tag\",\n    strong: \"strong\",\n    sub: \"builtin\",\n    sup: \"builtin\",\n    table: \"variable-3\",\n    tableHeading: \"operator\"\n  };\n\n  function startNewLine(stream, state) {\n    state.mode = Modes.newLayout;\n    state.tableHeading = false;\n\n    if (state.layoutType === \"definitionList\" && state.spanningLayout &&\n        stream.match(RE(\"definitionListEnd\"), false))\n      state.spanningLayout = false;\n  }\n\n  function handlePhraseModifier(stream, state, ch) {\n    if (ch === \"_\") {\n      if (stream.eat(\"_\"))\n        return togglePhraseModifier(stream, state, \"italic\", /__/, 2);\n      else\n        return togglePhraseModifier(stream, state, \"em\", /_/, 1);\n    }\n\n    if (ch === \"*\") {\n      if (stream.eat(\"*\")) {\n        return togglePhraseModifier(stream, state, \"bold\", /\\*\\*/, 2);\n      }\n      return togglePhraseModifier(stream, state, \"strong\", /\\*/, 1);\n    }\n\n    if (ch === \"[\") {\n      if (stream.match(/\\d+\\]/)) state.footCite = true;\n      return tokenStyles(state);\n    }\n\n    if (ch === \"(\") {\n      var spec = stream.match(/^(r|tm|c)\\)/);\n      if (spec)\n        return tokenStylesWith(state, TOKEN_STYLES.specialChar);\n    }\n\n    if (ch === \"<\" && stream.match(/(\\w+)[^>]+>[^<]+<\\/\\1>/))\n      return tokenStylesWith(state, TOKEN_STYLES.html);\n\n    if (ch === \"?\" && stream.eat(\"?\"))\n      return togglePhraseModifier(stream, state, \"cite\", /\\?\\?/, 2);\n\n    if (ch === \"=\" && stream.eat(\"=\"))\n      return togglePhraseModifier(stream, state, \"notextile\", /==/, 2);\n\n    if (ch === \"-\" && !stream.eat(\"-\"))\n      return togglePhraseModifier(stream, state, \"deletion\", /-/, 1);\n\n    if (ch === \"+\")\n      return togglePhraseModifier(stream, state, \"addition\", /\\+/, 1);\n\n    if (ch === \"~\")\n      return togglePhraseModifier(stream, state, \"sub\", /~/, 1);\n\n    if (ch === \"^\")\n      return togglePhraseModifier(stream, state, \"sup\", /\\^/, 1);\n\n    if (ch === \"%\")\n      return togglePhraseModifier(stream, state, \"span\", /%/, 1);\n\n    if (ch === \"@\")\n      return togglePhraseModifier(stream, state, \"code\", /@/, 1);\n\n    if (ch === \"!\") {\n      var type = togglePhraseModifier(stream, state, \"image\", /(?:\\([^\\)]+\\))?!/, 1);\n      stream.match(/^:\\S+/); // optional Url portion\n      return type;\n    }\n    return tokenStyles(state);\n  }\n\n  function togglePhraseModifier(stream, state, phraseModifier, closeRE, openSize) {\n    var charBefore = stream.pos > openSize ? stream.string.charAt(stream.pos - openSize - 1) : null;\n    var charAfter = stream.peek();\n    if (state[phraseModifier]) {\n      if ((!charAfter || /\\W/.test(charAfter)) && charBefore && /\\S/.test(charBefore)) {\n        var type = tokenStyles(state);\n        state[phraseModifier] = false;\n        return type;\n      }\n    } else if ((!charBefore || /\\W/.test(charBefore)) && charAfter && /\\S/.test(charAfter) &&\n               stream.match(new RegExp(\"^.*\\\\S\" + closeRE.source + \"(?:\\\\W|$)\"), false)) {\n      state[phraseModifier] = true;\n      state.mode = Modes.attributes;\n    }\n    return tokenStyles(state);\n  };\n\n  function tokenStyles(state) {\n    var disabled = textileDisabled(state);\n    if (disabled) return disabled;\n\n    var styles = [];\n    if (state.layoutType) styles.push(TOKEN_STYLES[state.layoutType]);\n\n    styles = styles.concat(activeStyles(\n      state, \"addition\", \"bold\", \"cite\", \"code\", \"deletion\", \"em\", \"footCite\",\n      \"image\", \"italic\", \"link\", \"span\", \"strong\", \"sub\", \"sup\", \"table\", \"tableHeading\"));\n\n    if (state.layoutType === \"header\")\n      styles.push(TOKEN_STYLES.header + \"-\" + state.header);\n\n    return styles.length ? styles.join(\" \") : null;\n  }\n\n  function textileDisabled(state) {\n    var type = state.layoutType;\n\n    switch(type) {\n    case \"notextile\":\n    case \"code\":\n    case \"pre\":\n      return TOKEN_STYLES[type];\n    default:\n      if (state.notextile)\n        return TOKEN_STYLES.notextile + (type ? (\" \" + TOKEN_STYLES[type]) : \"\");\n      return null;\n    }\n  }\n\n  function tokenStylesWith(state, extraStyles) {\n    var disabled = textileDisabled(state);\n    if (disabled) return disabled;\n\n    var type = tokenStyles(state);\n    if (extraStyles)\n      return type ? (type + \" \" + extraStyles) : extraStyles;\n    else\n      return type;\n  }\n\n  function activeStyles(state) {\n    var styles = [];\n    for (var i = 1; i < arguments.length; ++i) {\n      if (state[arguments[i]])\n        styles.push(TOKEN_STYLES[arguments[i]]);\n    }\n    return styles;\n  }\n\n  function blankLine(state) {\n    var spanningLayout = state.spanningLayout, type = state.layoutType;\n\n    for (var key in state) if (state.hasOwnProperty(key))\n      delete state[key];\n\n    state.mode = Modes.newLayout;\n    if (spanningLayout) {\n      state.layoutType = type;\n      state.spanningLayout = true;\n    }\n  }\n\n  var REs = {\n    cache: {},\n    single: {\n      bc: \"bc\",\n      bq: \"bq\",\n      definitionList: /- .*?:=+/,\n      definitionListEnd: /.*=:\\s*$/,\n      div: \"div\",\n      drawTable: /\\|.*\\|/,\n      foot: /fn\\d+/,\n      header: /h[1-6]/,\n      html: /\\s*<(?:\\/)?(\\w+)(?:[^>]+)?>(?:[^<]+<\\/\\1>)?/,\n      link: /[^\"]+\":\\S/,\n      linkDefinition: /\\[[^\\s\\]]+\\]\\S+/,\n      list: /(?:#+|\\*+)/,\n      notextile: \"notextile\",\n      para: \"p\",\n      pre: \"pre\",\n      table: \"table\",\n      tableCellAttributes: /[\\/\\\\]\\d+/,\n      tableHeading: /\\|_\\./,\n      tableText: /[^\"_\\*\\[\\(\\?\\+~\\^%@|-]+/,\n      text: /[^!\"_=\\*\\[\\(<\\?\\+~\\^%@-]+/\n    },\n    attributes: {\n      align: /(?:<>|<|>|=)/,\n      selector: /\\([^\\(][^\\)]+\\)/,\n      lang: /\\[[^\\[\\]]+\\]/,\n      pad: /(?:\\(+|\\)+){1,2}/,\n      css: /\\{[^\\}]+\\}/\n    },\n    createRe: function(name) {\n      switch (name) {\n      case \"drawTable\":\n        return REs.makeRe(\"^\", REs.single.drawTable, \"$\");\n      case \"html\":\n        return REs.makeRe(\"^\", REs.single.html, \"(?:\", REs.single.html, \")*\", \"$\");\n      case \"linkDefinition\":\n        return REs.makeRe(\"^\", REs.single.linkDefinition, \"$\");\n      case \"listLayout\":\n        return REs.makeRe(\"^\", REs.single.list, RE(\"allAttributes\"), \"*\\\\s+\");\n      case \"tableCellAttributes\":\n        return REs.makeRe(\"^\", REs.choiceRe(REs.single.tableCellAttributes,\n                                            RE(\"allAttributes\")), \"+\\\\.\");\n      case \"type\":\n        return REs.makeRe(\"^\", RE(\"allTypes\"));\n      case \"typeLayout\":\n        return REs.makeRe(\"^\", RE(\"allTypes\"), RE(\"allAttributes\"),\n                          \"*\\\\.\\\\.?\", \"(\\\\s+|$)\");\n      case \"attributes\":\n        return REs.makeRe(\"^\", RE(\"allAttributes\"), \"+\");\n\n      case \"allTypes\":\n        return REs.choiceRe(REs.single.div, REs.single.foot,\n                            REs.single.header, REs.single.bc, REs.single.bq,\n                            REs.single.notextile, REs.single.pre, REs.single.table,\n                            REs.single.para);\n\n      case \"allAttributes\":\n        return REs.choiceRe(REs.attributes.selector, REs.attributes.css,\n                            REs.attributes.lang, REs.attributes.align, REs.attributes.pad);\n\n      default:\n        return REs.makeRe(\"^\", REs.single[name]);\n      }\n    },\n    makeRe: function() {\n      var pattern = \"\";\n      for (var i = 0; i < arguments.length; ++i) {\n        var arg = arguments[i];\n        pattern += (typeof arg === \"string\") ? arg : arg.source;\n      }\n      return new RegExp(pattern);\n    },\n    choiceRe: function() {\n      var parts = [arguments[0]];\n      for (var i = 1; i < arguments.length; ++i) {\n        parts[i * 2 - 1] = \"|\";\n        parts[i * 2] = arguments[i];\n      }\n\n      parts.unshift(\"(?:\");\n      parts.push(\")\");\n      return REs.makeRe.apply(null, parts);\n    }\n  };\n\n  function RE(name) {\n    return (REs.cache[name] || (REs.cache[name] = REs.createRe(name)));\n  }\n\n  var Modes = {\n    newLayout: function(stream, state) {\n      if (stream.match(RE(\"typeLayout\"), false)) {\n        state.spanningLayout = false;\n        return (state.mode = Modes.blockType)(stream, state);\n      }\n      var newMode;\n      if (!textileDisabled(state)) {\n        if (stream.match(RE(\"listLayout\"), false))\n          newMode = Modes.list;\n        else if (stream.match(RE(\"drawTable\"), false))\n          newMode = Modes.table;\n        else if (stream.match(RE(\"linkDefinition\"), false))\n          newMode = Modes.linkDefinition;\n        else if (stream.match(RE(\"definitionList\")))\n          newMode = Modes.definitionList;\n        else if (stream.match(RE(\"html\"), false))\n          newMode = Modes.html;\n      }\n      return (state.mode = (newMode || Modes.text))(stream, state);\n    },\n\n    blockType: function(stream, state) {\n      var match, type;\n      state.layoutType = null;\n\n      if (match = stream.match(RE(\"type\")))\n        type = match[0];\n      else\n        return (state.mode = Modes.text)(stream, state);\n\n      if (match = type.match(RE(\"header\"))) {\n        state.layoutType = \"header\";\n        state.header = parseInt(match[0][1]);\n      } else if (type.match(RE(\"bq\"))) {\n        state.layoutType = \"quote\";\n      } else if (type.match(RE(\"bc\"))) {\n        state.layoutType = \"code\";\n      } else if (type.match(RE(\"foot\"))) {\n        state.layoutType = \"footnote\";\n      } else if (type.match(RE(\"notextile\"))) {\n        state.layoutType = \"notextile\";\n      } else if (type.match(RE(\"pre\"))) {\n        state.layoutType = \"pre\";\n      } else if (type.match(RE(\"div\"))) {\n        state.layoutType = \"div\";\n      } else if (type.match(RE(\"table\"))) {\n        state.layoutType = \"table\";\n      }\n\n      state.mode = Modes.attributes;\n      return tokenStyles(state);\n    },\n\n    text: function(stream, state) {\n      if (stream.match(RE(\"text\"))) return tokenStyles(state);\n\n      var ch = stream.next();\n      if (ch === '\"')\n        return (state.mode = Modes.link)(stream, state);\n      return handlePhraseModifier(stream, state, ch);\n    },\n\n    attributes: function(stream, state) {\n      state.mode = Modes.layoutLength;\n\n      if (stream.match(RE(\"attributes\")))\n        return tokenStylesWith(state, TOKEN_STYLES.attributes);\n      else\n        return tokenStyles(state);\n    },\n\n    layoutLength: function(stream, state) {\n      if (stream.eat(\".\") && stream.eat(\".\"))\n        state.spanningLayout = true;\n\n      state.mode = Modes.text;\n      return tokenStyles(state);\n    },\n\n    list: function(stream, state) {\n      var match = stream.match(RE(\"list\"));\n      state.listDepth = match[0].length;\n      var listMod = (state.listDepth - 1) % 3;\n      if (!listMod)\n        state.layoutType = \"list1\";\n      else if (listMod === 1)\n        state.layoutType = \"list2\";\n      else\n        state.layoutType = \"list3\";\n\n      state.mode = Modes.attributes;\n      return tokenStyles(state);\n    },\n\n    link: function(stream, state) {\n      state.mode = Modes.text;\n      if (stream.match(RE(\"link\"))) {\n        stream.match(/\\S+/);\n        return tokenStylesWith(state, TOKEN_STYLES.link);\n      }\n      return tokenStyles(state);\n    },\n\n    linkDefinition: function(stream, state) {\n      stream.skipToEnd();\n      return tokenStylesWith(state, TOKEN_STYLES.linkDefinition);\n    },\n\n    definitionList: function(stream, state) {\n      stream.match(RE(\"definitionList\"));\n\n      state.layoutType = \"definitionList\";\n\n      if (stream.match(/\\s*$/))\n        state.spanningLayout = true;\n      else\n        state.mode = Modes.attributes;\n\n      return tokenStyles(state);\n    },\n\n    html: function(stream, state) {\n      stream.skipToEnd();\n      return tokenStylesWith(state, TOKEN_STYLES.html);\n    },\n\n    table: function(stream, state) {\n      state.layoutType = \"table\";\n      return (state.mode = Modes.tableCell)(stream, state);\n    },\n\n    tableCell: function(stream, state) {\n      if (stream.match(RE(\"tableHeading\")))\n        state.tableHeading = true;\n      else\n        stream.eat(\"|\");\n\n      state.mode = Modes.tableCellAttributes;\n      return tokenStyles(state);\n    },\n\n    tableCellAttributes: function(stream, state) {\n      state.mode = Modes.tableText;\n\n      if (stream.match(RE(\"tableCellAttributes\")))\n        return tokenStylesWith(state, TOKEN_STYLES.attributes);\n      else\n        return tokenStyles(state);\n    },\n\n    tableText: function(stream, state) {\n      if (stream.match(RE(\"tableText\")))\n        return tokenStyles(state);\n\n      if (stream.peek() === \"|\") { // end of cell\n        state.mode = Modes.tableCell;\n        return tokenStyles(state);\n      }\n      return handlePhraseModifier(stream, state, stream.next());\n    }\n  };\n\n  CodeMirror.defineMode(\"textile\", function() {\n    return {\n      startState: function() {\n        return { mode: Modes.newLayout };\n      },\n      token: function(stream, state) {\n        if (stream.sol()) startNewLine(stream, state);\n        return state.mode(stream, state);\n      },\n      blankLine: blankLine\n    };\n  });\n\n  CodeMirror.defineMIME(\"text/x-textile\", \"textile\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/tiddlywiki/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: TiddlyWiki mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"tiddlywiki.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"tiddlywiki.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">TiddlyWiki</a>\n  </ul>\n</div>\n\n<article>\n<h2>TiddlyWiki mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n!TiddlyWiki Formatting\n* Rendered versions can be found at: http://www.tiddlywiki.com/#Reference\n\n|!Option            | !Syntax            |\n|bold font          | ''bold''           |\n|italic type        | //italic//         |\n|underlined text    | __underlined__     |\n|strikethrough text | --strikethrough--  |\n|superscript text   | super^^script^^    |\n|subscript text     | sub~~script~~      |\n|highlighted text   | @@highlighted@@    |\n|preformatted text  | {{{preformatted}}} |\n\n!Block Elements\n<<<\n!Heading 1\n\n!!Heading 2\n\n!!!Heading 3\n\n!!!!Heading 4\n\n!!!!!Heading 5\n<<<\n\n!!Lists\n<<<\n* unordered list, level 1\n** unordered list, level 2\n*** unordered list, level 3\n\n# ordered list, level 1\n## ordered list, level 2\n### unordered list, level 3\n\n; definition list, term\n: definition list, description\n<<<\n\n!!Blockquotes\n<<<\n> blockquote, level 1\n>> blockquote, level 2\n>>> blockquote, level 3\n\n> blockquote\n<<<\n\n!!Preformatted Text\n<<<\n{{{\npreformatted (e.g. code)\n}}}\n<<<\n\n!!Code Sections\n<<<\n{{{\nText style code\n}}}\n\n//{{{\nJS styled code. TiddlyWiki mixed mode should support highlighter switching in the future.\n//}}}\n\n<!--{{{-->\nXML styled code. TiddlyWiki mixed mode should support highlighter switching in the future.\n<!--}}}-->\n<<<\n\n!!Tables\n<<<\n|CssClass|k\n|!heading column 1|!heading column 2|\n|row 1, column 1|row 1, column 2|\n|row 2, column 1|row 2, column 2|\n|>|COLSPAN|\n|ROWSPAN| ... |\n|~| ... |\n|CssProperty:value;...| ... |\n|caption|c\n\n''Annotation:''\n* The {{{>}}} marker creates a \"colspan\", causing the current cell to merge with the one to the right.\n* The {{{~}}} marker creates a \"rowspan\", causing the current cell to merge with the one above.\n<<<\n!!Images /% TODO %/\ncf. [[TiddlyWiki.com|http://www.tiddlywiki.com/#EmbeddedImages]]\n\n!Hyperlinks\n* [[WikiWords|WikiWord]] are automatically transformed to hyperlinks to the respective tiddler\n** the automatic transformation can be suppressed by preceding the respective WikiWord with a tilde ({{{~}}}): {{{~WikiWord}}}\n* [[PrettyLinks]] are enclosed in square brackets and contain the desired tiddler name: {{{[[tiddler name]]}}}\n** optionally, a custom title or description can be added, separated by a pipe character ({{{|}}}): {{{[[title|target]]}}}<br>'''N.B.:''' In this case, the target can also be any website (i.e. URL).\n\n!Custom Styling\n* {{{@@CssProperty:value;CssProperty:value;...@@}}}<br>''N.B.:'' CSS color definitions should use lowercase letters to prevent the inadvertent creation of WikiWords.\n* <html><code>{{customCssClass{...}}}</code></html>\n* raw HTML can be inserted by enclosing the respective code in HTML tags: {{{<html> ... </html>}}}\n\n!Special Markers\n* {{{<br>}}} forces a manual line break\n* {{{----}}} creates a horizontal ruler\n* [[HTML entities|http://www.tiddlywiki.com/#HtmlEntities]]\n* [[HTML entities local|HtmlEntities]]\n* {{{<<macroName>>}}} calls the respective [[macro|Macros]]\n* To hide text within a tiddler so that it is not displayed, it can be wrapped in {{{/%}}} and {{{%/}}}.<br/>This can be a useful trick for hiding drafts or annotating complex markup.\n* To prevent wiki markup from taking effect for a particular section, that section can be enclosed in three double quotes: e.g. {{{\"\"\"WikiWord\"\"\"}}}.\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: 'tiddlywiki',      \n        lineNumbers: true,\n        matchBrackets: true\n      });\n    </script>\n\n    <p>TiddlyWiki mode supports a single configuration.</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-tiddlywiki</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/tiddlywiki/tiddlywiki.css",
    "content": "span.cm-underlined {\n  text-decoration: underline;\n}\nspan.cm-strikethrough {\n  text-decoration: line-through;\n}\nspan.cm-brace {\n  color: #170;\n  font-weight: bold;\n}\nspan.cm-table {\n  color: blue;\n  font-weight: bold;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/mode/tiddlywiki/tiddlywiki.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/***\n    |''Name''|tiddlywiki.js|\n    |''Description''|Enables TiddlyWikiy syntax highlighting using CodeMirror|\n    |''Author''|PMario|\n    |''Version''|0.1.7|\n    |''Status''|''stable''|\n    |''Source''|[[GitHub|https://github.com/pmario/CodeMirror2/blob/tw-syntax/mode/tiddlywiki]]|\n    |''Documentation''|https://codemirror.tiddlyspace.com/|\n    |''License''|[[MIT License|http://www.opensource.org/licenses/mit-license.php]]|\n    |''CoreVersion''|2.5.0|\n    |''Requires''|codemirror.js|\n    |''Keywords''|syntax highlighting color code mirror codemirror|\n    ! Info\n    CoreVersion parameter is needed for TiddlyWiki only!\n***/\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"tiddlywiki\", function () {\n  // Tokenizer\n  var textwords = {};\n\n  var keywords = {\n    \"allTags\": true, \"closeAll\": true, \"list\": true,\n    \"newJournal\": true, \"newTiddler\": true,\n    \"permaview\": true, \"saveChanges\": true,\n    \"search\": true, \"slider\": true, \"tabs\": true,\n    \"tag\": true, \"tagging\": true, \"tags\": true,\n    \"tiddler\": true, \"timeline\": true,\n    \"today\": true, \"version\": true, \"option\": true,\n    \"with\": true, \"filter\": true\n  };\n\n  var isSpaceName = /[\\w_\\-]/i,\n      reHR = /^\\-\\-\\-\\-+$/,                                 // <hr>\n      reWikiCommentStart = /^\\/\\*\\*\\*$/,            // /***\n      reWikiCommentStop = /^\\*\\*\\*\\/$/,             // ***/\n      reBlockQuote = /^<<<$/,\n\n      reJsCodeStart = /^\\/\\/\\{\\{\\{$/,                       // //{{{ js block start\n      reJsCodeStop = /^\\/\\/\\}\\}\\}$/,                        // //}}} js stop\n      reXmlCodeStart = /^<!--\\{\\{\\{-->$/,           // xml block start\n      reXmlCodeStop = /^<!--\\}\\}\\}-->$/,            // xml stop\n\n      reCodeBlockStart = /^\\{\\{\\{$/,                        // {{{ TW text div block start\n      reCodeBlockStop = /^\\}\\}\\}$/,                 // }}} TW text stop\n\n      reUntilCodeStop = /.*?\\}\\}\\}/;\n\n  function chain(stream, state, f) {\n    state.tokenize = f;\n    return f(stream, state);\n  }\n\n  function tokenBase(stream, state) {\n    var sol = stream.sol(), ch = stream.peek();\n\n    state.block = false;        // indicates the start of a code block.\n\n    // check start of  blocks\n    if (sol && /[<\\/\\*{}\\-]/.test(ch)) {\n      if (stream.match(reCodeBlockStart)) {\n        state.block = true;\n        return chain(stream, state, twTokenCode);\n      }\n      if (stream.match(reBlockQuote))\n        return 'quote';\n      if (stream.match(reWikiCommentStart) || stream.match(reWikiCommentStop))\n        return 'comment';\n      if (stream.match(reJsCodeStart) || stream.match(reJsCodeStop) || stream.match(reXmlCodeStart) || stream.match(reXmlCodeStop))\n        return 'comment';\n      if (stream.match(reHR))\n        return 'hr';\n    }\n\n    stream.next();\n    if (sol && /[\\/\\*!#;:>|]/.test(ch)) {\n      if (ch == \"!\") { // tw header\n        stream.skipToEnd();\n        return \"header\";\n      }\n      if (ch == \"*\") { // tw list\n        stream.eatWhile('*');\n        return \"comment\";\n      }\n      if (ch == \"#\") { // tw numbered list\n        stream.eatWhile('#');\n        return \"comment\";\n      }\n      if (ch == \";\") { // definition list, term\n        stream.eatWhile(';');\n        return \"comment\";\n      }\n      if (ch == \":\") { // definition list, description\n        stream.eatWhile(':');\n        return \"comment\";\n      }\n      if (ch == \">\") { // single line quote\n        stream.eatWhile(\">\");\n        return \"quote\";\n      }\n      if (ch == '|')\n        return 'header';\n    }\n\n    if (ch == '{' && stream.match(/\\{\\{/))\n      return chain(stream, state, twTokenCode);\n\n    // rudimentary html:// file:// link matching. TW knows much more ...\n    if (/[hf]/i.test(ch) &&\n        /[ti]/i.test(stream.peek()) &&\n        stream.match(/\\b(ttps?|tp|ile):\\/\\/[\\-A-Z0-9+&@#\\/%?=~_|$!:,.;]*[A-Z0-9+&@#\\/%=~_|$]/i))\n      return \"link\";\n\n    // just a little string indicator, don't want to have the whole string covered\n    if (ch == '\"')\n      return 'string';\n\n    if (ch == '~')    // _no_ CamelCase indicator should be bold\n      return 'brace';\n\n    if (/[\\[\\]]/.test(ch) && stream.match(ch)) // check for [[..]]\n      return 'brace';\n\n    if (ch == \"@\") {    // check for space link. TODO fix @@...@@ highlighting\n      stream.eatWhile(isSpaceName);\n      return \"link\";\n    }\n\n    if (/\\d/.test(ch)) {        // numbers\n      stream.eatWhile(/\\d/);\n      return \"number\";\n    }\n\n    if (ch == \"/\") { // tw invisible comment\n      if (stream.eat(\"%\")) {\n        return chain(stream, state, twTokenComment);\n      } else if (stream.eat(\"/\")) { //\n        return chain(stream, state, twTokenEm);\n      }\n    }\n\n    if (ch == \"_\" && stream.eat(\"_\")) // tw underline\n        return chain(stream, state, twTokenUnderline);\n\n    // strikethrough and mdash handling\n    if (ch == \"-\" && stream.eat(\"-\")) {\n      // if strikethrough looks ugly, change CSS.\n      if (stream.peek() != ' ')\n        return chain(stream, state, twTokenStrike);\n      // mdash\n      if (stream.peek() == ' ')\n        return 'brace';\n    }\n\n    if (ch == \"'\" && stream.eat(\"'\")) // tw bold\n      return chain(stream, state, twTokenStrong);\n\n    if (ch == \"<\" && stream.eat(\"<\")) // tw macro\n      return chain(stream, state, twTokenMacro);\n\n    // core macro handling\n    stream.eatWhile(/[\\w\\$_]/);\n    return textwords.propertyIsEnumerable(stream.current()) ? \"keyword\" : null\n  }\n\n  // tw invisible comment\n  function twTokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"%\");\n    }\n    return \"comment\";\n  }\n\n  // tw strong / bold\n  function twTokenStrong(stream, state) {\n    var maybeEnd = false,\n    ch;\n    while (ch = stream.next()) {\n      if (ch == \"'\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"'\");\n    }\n    return \"strong\";\n  }\n\n  // tw code\n  function twTokenCode(stream, state) {\n    var sb = state.block;\n\n    if (sb && stream.current()) {\n      return \"comment\";\n    }\n\n    if (!sb && stream.match(reUntilCodeStop)) {\n      state.tokenize = tokenBase;\n      return \"comment\";\n    }\n\n    if (sb && stream.sol() && stream.match(reCodeBlockStop)) {\n      state.tokenize = tokenBase;\n      return \"comment\";\n    }\n\n    stream.next();\n    return \"comment\";\n  }\n\n  // tw em / italic\n  function twTokenEm(stream, state) {\n    var maybeEnd = false,\n    ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"/\");\n    }\n    return \"em\";\n  }\n\n  // tw underlined text\n  function twTokenUnderline(stream, state) {\n    var maybeEnd = false,\n    ch;\n    while (ch = stream.next()) {\n      if (ch == \"_\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"_\");\n    }\n    return \"underlined\";\n  }\n\n  // tw strike through text looks ugly\n  // change CSS if needed\n  function twTokenStrike(stream, state) {\n    var maybeEnd = false, ch;\n\n    while (ch = stream.next()) {\n      if (ch == \"-\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"-\");\n    }\n    return \"strikethrough\";\n  }\n\n  // macro\n  function twTokenMacro(stream, state) {\n    if (stream.current() == '<<') {\n      return 'macro';\n    }\n\n    var ch = stream.next();\n    if (!ch) {\n      state.tokenize = tokenBase;\n      return null;\n    }\n    if (ch == \">\") {\n      if (stream.peek() == '>') {\n        stream.next();\n        state.tokenize = tokenBase;\n        return \"macro\";\n      }\n    }\n\n    stream.eatWhile(/[\\w\\$_]/);\n    return keywords.propertyIsEnumerable(stream.current()) ? \"keyword\" : null\n  }\n\n  // Interface\n  return {\n    startState: function () {\n      return {tokenize: tokenBase};\n    },\n\n    token: function (stream, state) {\n      if (stream.eatSpace()) return null;\n      var style = state.tokenize(stream, state);\n      return style;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-tiddlywiki\", \"tiddlywiki\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/tiki/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Tiki wiki mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"tiki.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"tiki.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Tiki wiki</a>\n  </ul>\n</div>\n\n<article>\n<h2>Tiki wiki mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\nHeadings\n!Header 1\n!!Header 2\n!!!Header 3\n!!!!Header 4\n!!!!!Header 5\n!!!!!!Header 6\n\nStyling\n-=titlebar=-\n^^ Box on multi\nlines\nof content^^\n__bold__\n''italic''\n===underline===\n::center::\n--Line Through--\n\nOperators\n~np~No parse~/np~\n\nLink\n[link|desc|nocache]\n\nWiki\n((Wiki))\n((Wiki|desc))\n((Wiki|desc|timeout))\n\nTable\n||row1 col1|row1 col2|row1 col3\nrow2 col1|row2 col2|row2 col3\nrow3 col1|row3 col2|row3 col3||\n\nLists:\n*bla\n**bla-1\n++continue-bla-1\n***bla-2\n++continue-bla-1\n*bla\n+continue-bla\n#bla\n** tra-la-la\n+continue-bla\n#bla\n\nPlugin (standard):\n{PLUGIN(attr=\"my attr\")}\nPlugin Body\n{PLUGIN}\n\nPlugin (inline):\n{plugin attr=\"my attr\"}\n</textarea></div>\n\n<script>\n\tvar editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: 'tiki',      \n        lineNumbers: true\n    });\n</script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/tiki/tiki.css",
    "content": ".cm-tw-syntaxerror {\n\tcolor: #FFF;\n\tbackground-color: #900;\n}\n\n.cm-tw-deleted {\n\ttext-decoration: line-through;\n}\n\n.cm-tw-header5 {\n\tfont-weight: bold;\n}\n.cm-tw-listitem:first-child { /*Added first child to fix duplicate padding when highlighting*/\n\tpadding-left: 10px;\n}\n\n.cm-tw-box {\n\tborder-top-width: 0px !important;\n\tborder-style: solid;\n\tborder-width: 1px;\n\tborder-color: inherit;\n}\n\n.cm-tw-underline {\n\ttext-decoration: underline;\n}"
  },
  {
    "path": "third_party/CodeMirror/mode/tiki/tiki.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode('tiki', function(config) {\n  function inBlock(style, terminator, returnTokenizer) {\n    return function(stream, state) {\n      while (!stream.eol()) {\n        if (stream.match(terminator)) {\n          state.tokenize = inText;\n          break;\n        }\n        stream.next();\n      }\n\n      if (returnTokenizer) state.tokenize = returnTokenizer;\n\n      return style;\n    };\n  }\n\n  function inLine(style) {\n    return function(stream, state) {\n      while(!stream.eol()) {\n        stream.next();\n      }\n      state.tokenize = inText;\n      return style;\n    };\n  }\n\n  function inText(stream, state) {\n    function chain(parser) {\n      state.tokenize = parser;\n      return parser(stream, state);\n    }\n\n    var sol = stream.sol();\n    var ch = stream.next();\n\n    //non start of line\n    switch (ch) { //switch is generally much faster than if, so it is used here\n    case \"{\": //plugin\n      stream.eat(\"/\");\n      stream.eatSpace();\n      stream.eatWhile(/[^\\s\\u00a0=\\\"\\'\\/?(}]/);\n      state.tokenize = inPlugin;\n      return \"tag\";\n    case \"_\": //bold\n      if (stream.eat(\"_\"))\n        return chain(inBlock(\"strong\", \"__\", inText));\n      break;\n    case \"'\": //italics\n      if (stream.eat(\"'\"))\n        return chain(inBlock(\"em\", \"''\", inText));\n      break;\n    case \"(\":// Wiki Link\n      if (stream.eat(\"(\"))\n        return chain(inBlock(\"variable-2\", \"))\", inText));\n      break;\n    case \"[\":// Weblink\n      return chain(inBlock(\"variable-3\", \"]\", inText));\n      break;\n    case \"|\": //table\n      if (stream.eat(\"|\"))\n        return chain(inBlock(\"comment\", \"||\"));\n      break;\n    case \"-\":\n      if (stream.eat(\"=\")) {//titleBar\n        return chain(inBlock(\"header string\", \"=-\", inText));\n      } else if (stream.eat(\"-\")) {//deleted\n        return chain(inBlock(\"error tw-deleted\", \"--\", inText));\n      }\n      break;\n    case \"=\": //underline\n      if (stream.match(\"==\"))\n        return chain(inBlock(\"tw-underline\", \"===\", inText));\n      break;\n    case \":\":\n      if (stream.eat(\":\"))\n        return chain(inBlock(\"comment\", \"::\"));\n      break;\n    case \"^\": //box\n      return chain(inBlock(\"tw-box\", \"^\"));\n      break;\n    case \"~\": //np\n      if (stream.match(\"np~\"))\n        return chain(inBlock(\"meta\", \"~/np~\"));\n      break;\n    }\n\n    //start of line types\n    if (sol) {\n      switch (ch) {\n      case \"!\": //header at start of line\n        if (stream.match('!!!!!')) {\n          return chain(inLine(\"header string\"));\n        } else if (stream.match('!!!!')) {\n          return chain(inLine(\"header string\"));\n        } else if (stream.match('!!!')) {\n          return chain(inLine(\"header string\"));\n        } else if (stream.match('!!')) {\n          return chain(inLine(\"header string\"));\n        } else {\n          return chain(inLine(\"header string\"));\n        }\n        break;\n      case \"*\": //unordered list line item, or <li /> at start of line\n      case \"#\": //ordered list line item, or <li /> at start of line\n      case \"+\": //ordered list line item, or <li /> at start of line\n        return chain(inLine(\"tw-listitem bracket\"));\n        break;\n      }\n    }\n\n    //stream.eatWhile(/[&{]/); was eating up plugins, turned off to act less like html and more like tiki\n    return null;\n  }\n\n  var indentUnit = config.indentUnit;\n\n  // Return variables for tokenizers\n  var pluginName, type;\n  function inPlugin(stream, state) {\n    var ch = stream.next();\n    var peek = stream.peek();\n\n    if (ch == \"}\") {\n      state.tokenize = inText;\n      //type = ch == \")\" ? \"endPlugin\" : \"selfclosePlugin\"; inPlugin\n      return \"tag\";\n    } else if (ch == \"(\" || ch == \")\") {\n      return \"bracket\";\n    } else if (ch == \"=\") {\n      type = \"equals\";\n\n      if (peek == \">\") {\n        stream.next();\n        peek = stream.peek();\n      }\n\n      //here we detect values directly after equal character with no quotes\n      if (!/[\\'\\\"]/.test(peek)) {\n        state.tokenize = inAttributeNoQuote();\n      }\n      //end detect values\n\n      return \"operator\";\n    } else if (/[\\'\\\"]/.test(ch)) {\n      state.tokenize = inAttribute(ch);\n      return state.tokenize(stream, state);\n    } else {\n      stream.eatWhile(/[^\\s\\u00a0=\\\"\\'\\/?]/);\n      return \"keyword\";\n    }\n  }\n\n  function inAttribute(quote) {\n    return function(stream, state) {\n      while (!stream.eol()) {\n        if (stream.next() == quote) {\n          state.tokenize = inPlugin;\n          break;\n        }\n      }\n      return \"string\";\n    };\n  }\n\n  function inAttributeNoQuote() {\n    return function(stream, state) {\n      while (!stream.eol()) {\n        var ch = stream.next();\n        var peek = stream.peek();\n        if (ch == \" \" || ch == \",\" || /[ )}]/.test(peek)) {\n      state.tokenize = inPlugin;\n      break;\n    }\n  }\n  return \"string\";\n};\n                     }\n\nvar curState, setStyle;\nfunction pass() {\n  for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);\n}\n\nfunction cont() {\n  pass.apply(null, arguments);\n  return true;\n}\n\nfunction pushContext(pluginName, startOfLine) {\n  var noIndent = curState.context && curState.context.noIndent;\n  curState.context = {\n    prev: curState.context,\n    pluginName: pluginName,\n    indent: curState.indented,\n    startOfLine: startOfLine,\n    noIndent: noIndent\n  };\n}\n\nfunction popContext() {\n  if (curState.context) curState.context = curState.context.prev;\n}\n\nfunction element(type) {\n  if (type == \"openPlugin\") {curState.pluginName = pluginName; return cont(attributes, endplugin(curState.startOfLine));}\n  else if (type == \"closePlugin\") {\n    var err = false;\n    if (curState.context) {\n      err = curState.context.pluginName != pluginName;\n      popContext();\n    } else {\n      err = true;\n    }\n    if (err) setStyle = \"error\";\n    return cont(endcloseplugin(err));\n  }\n  else if (type == \"string\") {\n    if (!curState.context || curState.context.name != \"!cdata\") pushContext(\"!cdata\");\n    if (curState.tokenize == inText) popContext();\n    return cont();\n  }\n  else return cont();\n}\n\nfunction endplugin(startOfLine) {\n  return function(type) {\n    if (\n      type == \"selfclosePlugin\" ||\n        type == \"endPlugin\"\n    )\n      return cont();\n    if (type == \"endPlugin\") {pushContext(curState.pluginName, startOfLine); return cont();}\n    return cont();\n  };\n}\n\nfunction endcloseplugin(err) {\n  return function(type) {\n    if (err) setStyle = \"error\";\n    if (type == \"endPlugin\") return cont();\n    return pass();\n  };\n}\n\nfunction attributes(type) {\n  if (type == \"keyword\") {setStyle = \"attribute\"; return cont(attributes);}\n  if (type == \"equals\") return cont(attvalue, attributes);\n  return pass();\n}\nfunction attvalue(type) {\n  if (type == \"keyword\") {setStyle = \"string\"; return cont();}\n  if (type == \"string\") return cont(attvaluemaybe);\n  return pass();\n}\nfunction attvaluemaybe(type) {\n  if (type == \"string\") return cont(attvaluemaybe);\n  else return pass();\n}\nreturn {\n  startState: function() {\n    return {tokenize: inText, cc: [], indented: 0, startOfLine: true, pluginName: null, context: null};\n  },\n  token: function(stream, state) {\n    if (stream.sol()) {\n      state.startOfLine = true;\n      state.indented = stream.indentation();\n    }\n    if (stream.eatSpace()) return null;\n\n    setStyle = type = pluginName = null;\n    var style = state.tokenize(stream, state);\n    if ((style || type) && style != \"comment\") {\n      curState = state;\n      while (true) {\n        var comb = state.cc.pop() || element;\n        if (comb(type || style)) break;\n      }\n    }\n    state.startOfLine = false;\n    return setStyle || style;\n  },\n  indent: function(state, textAfter) {\n    var context = state.context;\n    if (context && context.noIndent) return 0;\n    if (context && /^{\\//.test(textAfter))\n        context = context.prev;\n    while (context && !context.startOfLine)\n        context = context.prev;\n    if (context) return context.indent + indentUnit;\n    else return 0;\n  },\n  electricChars: \"/\"\n};\n});\n\nCodeMirror.defineMIME(\"text/tiki\", \"tiki\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/toml/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: TOML Mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"toml.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">TOML Mode</a>\n  </ul>\n</div>\n\n<article>\n<h2>TOML Mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n# This is a TOML document. Boom.\n\ntitle = \"TOML Example\"\n\n[owner]\nname = \"Tom Preston-Werner\"\norganization = \"GitHub\"\nbio = \"GitHub Cofounder &amp; CEO\\nLikes tater tots and beer.\"\ndob = 1979-05-27T07:32:00Z # First class dates? Why not?\n\n[database]\nserver = \"192.168.1.1\"\nports = [ 8001, 8001, 8002 ]\nconnection_max = 5000\nenabled = true\n\n[servers]\n\n  # You can indent as you please. Tabs or spaces. TOML don't care.\n  [servers.alpha]\n  ip = \"10.0.0.1\"\n  dc = \"eqdc10\"\n  \n  [servers.beta]\n  ip = \"10.0.0.2\"\n  dc = \"eqdc10\"\n  \n[clients]\ndata = [ [\"gamma\", \"delta\"], [1, 2] ]\n\n# Line breaks are OK when inside arrays\nhosts = [\n  \"alpha\",\n  \"omega\"\n]\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"toml\"},\n        lineNumbers: true\n      });\n    </script>\n    <h3>The TOML Mode</h3>\n      <p> Created by Forbes Lindesay.</p>\n    <p><strong>MIME type defined:</strong> <code>text/x-toml</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/toml/toml.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"toml\", function () {\n  return {\n    startState: function () {\n      return {\n        inString: false,\n        stringType: \"\",\n        lhs: true,\n        inArray: 0\n      };\n    },\n    token: function (stream, state) {\n      //check for state changes\n      if (!state.inString && ((stream.peek() == '\"') || (stream.peek() == \"'\"))) {\n        state.stringType = stream.peek();\n        stream.next(); // Skip quote\n        state.inString = true; // Update state\n      }\n      if (stream.sol() && state.inArray === 0) {\n        state.lhs = true;\n      }\n      //return state\n      if (state.inString) {\n        while (state.inString && !stream.eol()) {\n          if (stream.peek() === state.stringType) {\n            stream.next(); // Skip quote\n            state.inString = false; // Clear flag\n          } else if (stream.peek() === '\\\\') {\n            stream.next();\n            stream.next();\n          } else {\n            stream.match(/^.[^\\\\\\\"\\']*/);\n          }\n        }\n        return state.lhs ? \"property string\" : \"string\"; // Token style\n      } else if (state.inArray && stream.peek() === ']') {\n        stream.next();\n        state.inArray--;\n        return 'bracket';\n      } else if (state.lhs && stream.peek() === '[' && stream.skipTo(']')) {\n        stream.next();//skip closing ]\n        // array of objects has an extra open & close []\n        if (stream.peek() === ']') stream.next();\n        return \"atom\";\n      } else if (stream.peek() === \"#\") {\n        stream.skipToEnd();\n        return \"comment\";\n      } else if (stream.eatSpace()) {\n        return null;\n      } else if (state.lhs && stream.eatWhile(function (c) { return c != '=' && c != ' '; })) {\n        return \"property\";\n      } else if (state.lhs && stream.peek() === \"=\") {\n        stream.next();\n        state.lhs = false;\n        return null;\n      } else if (!state.lhs && stream.match(/^\\d\\d\\d\\d[\\d\\-\\:\\.T]*Z/)) {\n        return 'atom'; //date\n      } else if (!state.lhs && (stream.match('true') || stream.match('false'))) {\n        return 'atom';\n      } else if (!state.lhs && stream.peek() === '[') {\n        state.inArray++;\n        stream.next();\n        return 'bracket';\n      } else if (!state.lhs && stream.match(/^\\-?\\d+(?:\\.\\d+)?/)) {\n        return 'number';\n      } else if (!stream.eatSpace()) {\n        stream.next();\n      }\n      return null;\n    }\n  };\n});\n\nCodeMirror.defineMIME('text/x-toml', 'toml');\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/tornado/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Tornado template mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/overlay.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"tornado.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/marijnh/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Tornado</a>\n  </ul>\n</div>\n\n<article>\n<h2>Tornado template mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n<!doctype html>\n<html>\n    <head>\n        <title>My Tornado web application</title>\n    </head>\n    <body>\n        <h1>\n            {{ title }}\n        </h1>\n        <ul class=\"my-list\">\n            {% for item in items %}\n                <li>{% item.name %}</li>\n            {% empty %}\n                <li>You have no items in your list.</li>\n            {% end %}\n        </ul>\n    </body>\n</html>\n</textarea></form>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        mode: \"tornado\",\n        indentUnit: 4,\n        indentWithTabs: true\n      });\n    </script>\n\n    <p>Mode for HTML with embedded Tornado template markup.</p>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-tornado</code></p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/tornado/tornado.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../htmlmixed/htmlmixed\"),\n        require(\"../../addon/mode/overlay\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../htmlmixed/htmlmixed\",\n            \"../../addon/mode/overlay\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"tornado:inner\", function() {\n    var keywords = [\"and\",\"as\",\"assert\",\"autoescape\",\"block\",\"break\",\"class\",\"comment\",\"context\",\n                    \"continue\",\"datetime\",\"def\",\"del\",\"elif\",\"else\",\"end\",\"escape\",\"except\",\n                    \"exec\",\"extends\",\"false\",\"finally\",\"for\",\"from\",\"global\",\"if\",\"import\",\"in\",\n                    \"include\",\"is\",\"json_encode\",\"lambda\",\"length\",\"linkify\",\"load\",\"module\",\n                    \"none\",\"not\",\"or\",\"pass\",\"print\",\"put\",\"raise\",\"raw\",\"return\",\"self\",\"set\",\n                    \"squeeze\",\"super\",\"true\",\"try\",\"url_escape\",\"while\",\"with\",\"without\",\"xhtml_escape\",\"yield\"];\n    keywords = new RegExp(\"^((\" + keywords.join(\")|(\") + \"))\\\\b\");\n\n    function tokenBase (stream, state) {\n      stream.eatWhile(/[^\\{]/);\n      var ch = stream.next();\n      if (ch == \"{\") {\n        if (ch = stream.eat(/\\{|%|#/)) {\n          state.tokenize = inTag(ch);\n          return \"tag\";\n        }\n      }\n    }\n    function inTag (close) {\n      if (close == \"{\") {\n        close = \"}\";\n      }\n      return function (stream, state) {\n        var ch = stream.next();\n        if ((ch == close) && stream.eat(\"}\")) {\n          state.tokenize = tokenBase;\n          return \"tag\";\n        }\n        if (stream.match(keywords)) {\n          return \"keyword\";\n        }\n        return close == \"#\" ? \"comment\" : \"string\";\n      };\n    }\n    return {\n      startState: function () {\n        return {tokenize: tokenBase};\n      },\n      token: function (stream, state) {\n        return state.tokenize(stream, state);\n      }\n    };\n  });\n\n  CodeMirror.defineMode(\"tornado\", function(config) {\n    var htmlBase = CodeMirror.getMode(config, \"text/html\");\n    var tornadoInner = CodeMirror.getMode(config, \"tornado:inner\");\n    return CodeMirror.overlayMode(htmlBase, tornadoInner);\n  });\n\n  CodeMirror.defineMIME(\"text/x-tornado\", \"tornado\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/troff/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: troff mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=stylesheet href=../../lib/codemirror.css>\n<script src=../../lib/codemirror.js></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=troff.js></script>\n<style type=text/css>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">troff</a>\n  </ul>\n</div>\n\n<article>\n<h2>troff</h2>\n\n\n<textarea id=code>\n'\\\" t\n.\\\"     Title: mkvextract\n.TH \"MKVEXTRACT\" \"1\" \"2015\\-02\\-28\" \"MKVToolNix 7\\&.7\\&.0\" \"User Commands\"\n.\\\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n.ie \\n(.g .ds Aq \\(aq\n.el       .ds Aq '\n.\\\" -----------------------------------------------------------------\n.nh\n.\\\" disable justification (adjust text to left margin only)\n.ad l\n.\\\" -----------------------------------------------------------------\n.SH \"NAME\"\nmkvextract \\- extract tracks from Matroska(TM) files into other files\n.SH \"SYNOPSIS\"\n.HP \\w'\\fBmkvextract\\fR\\ 'u\n\\fBmkvextract\\fR {mode} {source\\-filename} [options] [extraction\\-spec]\n.SH \"DESCRIPTION\"\n.PP\n.B mkvextract\nextracts specific parts from a\n.I Matroska(TM)\nfile to other useful formats\\&. The first argument,\n\\fBmode\\fR, tells\n\\fBmkvextract\\fR(1)\nwhat to extract\\&. Currently supported is the extraction of\ntracks,\ntags,\nattachments,\nchapters,\nCUE sheets,\ntimecodes\nand\ncues\\&. The second argument is the name of the source file\\&. It must be a\nMatroska(TM)\nfile\\&. All following arguments are options and extraction specifications; both of which depend on the selected mode\\&.\n.SS \"Common options\"\n.PP\nThe following options are available in all modes and only described once in this section\\&.\n.PP\n\\fB\\-f\\fR, \\fB\\-\\-parse\\-fully\\fR\n.RS 4\nSets the parse mode to \\*(Aqfull\\*(Aq\\&. The default mode does not parse the whole file but uses the meta seek elements for locating the required elements of a source file\\&. In 99% of all cases this is enough\\&. But for files that do not contain meta seek elements or which are damaged the user might have to use this mode\\&. A full scan of a file can take a couple of minutes while a fast scan only takes seconds\\&.\n.RE\n.PP\n\\fB\\-\\-command\\-line\\-charset\\fR \\fIcharacter\\-set\\fR\n.RS 4\nSets the character set to convert strings given on the command line from\\&. It defaults to the character set given by system\\*(Aqs current locale\\&.\n.RE\n.PP\n\\fB\\-\\-output\\-charset\\fR \\fIcharacter\\-set\\fR\n.RS 4\nSets the character set to which strings are converted that are to be output\\&. It defaults to the character set given by system\\*(Aqs current locale\\&.\n.RE\n.PP\n\\fB\\-r\\fR, \\fB\\-\\-redirect\\-output\\fR \\fIfile\\-name\\fR\n.RS 4\nWrites all messages to the file\n\\fIfile\\-name\\fR\ninstead of to the console\\&. While this can be done easily with output redirection there are cases in which this option is needed: when the terminal reinterprets the output before writing it to a file\\&. The character set set with\n\\fB\\-\\-output\\-charset\\fR\nis honored\\&.\n.RE\n.PP\n\\fB\\-\\-ui\\-language\\fR \\fIcode\\fR\n.RS 4\nForces the translations for the language\n\\fIcode\\fR\nto be used (e\\&.g\\&. \\*(Aqde_DE\\*(Aq for the German translations)\\&. It is preferable to use the environment variables\n\\fILANG\\fR,\n\\fILC_MESSAGES\\fR\nand\n\\fILC_ALL\\fR\nthough\\&. Entering \\*(Aqlist\\*(Aq as the\n\\fIcode\\fR\nwill cause\n\\fBmkvextract\\fR(1)\nto output a list of available translations\\&.\n\n.\\\" [...]\n\n.SH \"SEE ALSO\"\n.PP\n\\fBmkvmerge\\fR(1),\n\\fBmkvinfo\\fR(1),\n\\fBmkvpropedit\\fR(1),\n\\fBmmg\\fR(1)\n.SH \"WWW\"\n.PP\nThe latest version can always be found at\n\\m[blue]\\fBthe MKVToolNix homepage\\fR\\m[]\\&\\s-2\\u[1]\\d\\s+2\\&.\n.SH \"AUTHOR\"\n.PP\n\\(co \\fBMoritz Bunkus\\fR <\\&moritz@bunkus\\&.org\\&>\n.RS 4\nDeveloper\n.RE\n.SH \"NOTES\"\n.IP \" 1.\" 4\nthe MKVToolNix homepage\n.RS 4\n\\%https://www.bunkus.org/videotools/mkvtoolnix/\n.RE\n</textarea>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById('code'), {\n    mode: 'troff',\n    lineNumbers: true,\n    matchBrackets: false\n  });\n</script>\n\n<p><strong>MIME types defined:</strong> <code>troff</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/troff/troff.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\")\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd)\n    define([\"../../lib/codemirror\"], mod);\n  else\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode('troff', function() {\n\n  var words = {};\n\n  function tokenBase(stream) {\n    if (stream.eatSpace()) return null;\n\n    var sol = stream.sol();\n    var ch = stream.next();\n\n    if (ch === '\\\\') {\n      if (stream.match('fB') || stream.match('fR') || stream.match('fI') ||\n          stream.match('u')  || stream.match('d')  ||\n          stream.match('%')  || stream.match('&')) {\n        return 'string';\n      }\n      if (stream.match('m[')) {\n        stream.skipTo(']');\n        stream.next();\n        return 'string';\n      }\n      if (stream.match('s+') || stream.match('s-')) {\n        stream.eatWhile(/[\\d-]/);\n        return 'string';\n      }\n      if (stream.match('\\(') || stream.match('*\\(')) {\n        stream.eatWhile(/[\\w-]/);\n        return 'string';\n      }\n      return 'string';\n    }\n    if (sol && (ch === '.' || ch === '\\'')) {\n      if (stream.eat('\\\\') && stream.eat('\\\"')) {\n        stream.skipToEnd();\n        return 'comment';\n      }\n    }\n    if (sol && ch === '.') {\n      if (stream.match('B ') || stream.match('I ') || stream.match('R ')) {\n        return 'attribute';\n      }\n      if (stream.match('TH ') || stream.match('SH ') || stream.match('SS ') || stream.match('HP ')) {\n        stream.skipToEnd();\n        return 'quote';\n      }\n      if ((stream.match(/[A-Z]/) && stream.match(/[A-Z]/)) || (stream.match(/[a-z]/) && stream.match(/[a-z]/))) {\n        return 'attribute';\n      }\n    }\n    stream.eatWhile(/[\\w-]/);\n    var cur = stream.current();\n    return words.hasOwnProperty(cur) ? words[cur] : null;\n  }\n\n  function tokenize(stream, state) {\n    return (state.tokens[0] || tokenBase) (stream, state);\n  };\n\n  return {\n    startState: function() {return {tokens:[]};},\n    token: function(stream, state) {\n      return tokenize(stream, state);\n    }\n  };\n});\n\nCodeMirror.defineMIME('text/troff', 'troff');\nCodeMirror.defineMIME('text/x-troff', 'troff');\nCodeMirror.defineMIME('application/x-troff', 'troff');\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ttcn/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: TTCN mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"ttcn.js\"></script>\n<style>\n    .CodeMirror {\n        border-top: 1px solid black;\n        border-bottom: 1px solid black;\n    }\n</style>\n<div id=nav>\n    <a href=\"https://codemirror.net\"><h1>CodeMirror</h1>\n        <img id=logo src=\"../../doc/logo.png\">\n    </a>\n\n    <ul>\n        <li><a href=\"../../index.html\">Home</a>\n        <li><a href=\"../../doc/manual.html\">Manual</a>\n        <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n    </ul>\n    <ul>\n        <li><a href=\"../index.html\">Language modes</a>\n        <li><a class=active href=\"http://en.wikipedia.org/wiki/TTCN\">TTCN</a>\n    </ul>\n</div>\n<article>\n    <h2>TTCN example</h2>\n    <div>\n        <textarea id=\"ttcn-code\">\nmodule Templates {\n  /* import types from ASN.1 */\n  import from Types language \"ASN.1:1997\" all;\n\n  /* During the conversion phase from ASN.1 to TTCN-3 */\n  /* - the minus sign (Message-Type) within the identifiers will be replaced by underscore (Message_Type)*/\n  /* - the ASN.1 identifiers matching a TTCN-3 keyword (objid) will be postfixed with an underscore (objid_)*/\n\n  // simple types\n\n  template SenderID localObjid := objid {itu_t(0) identified_organization(4) etsi(0)};\n\n  // complex types\n\n  /* ASN.1 Message-Type mapped to TTCN-3 Message_Type */\n  template Message receiveMsg(template (present) Message_Type p_messageType) := {\n    header := p_messageType,\n    body := ?\n  }\n\n  /* ASN.1 objid mapped to TTCN-3 objid_ */\n  template Message sendInviteMsg := {\n      header := inviteType,\n      body := {\n        /* optional fields may be assigned by omit or may be ignored/skipped */\n        description := \"Invite Message\",\n        data := 'FF'O,\n        objid_ := localObjid\n      }\n  }\n\n  template Message sendAcceptMsg modifies sendInviteMsg := {\n      header := acceptType,\n      body := {\n        description := \"Accept Message\"\n      }\n    };\n\n  template Message sendErrorMsg modifies sendInviteMsg := {\n      header := errorType,\n      body := {\n        description := \"Error Message\"\n      }\n    };\n\n  template Message expectedErrorMsg := {\n      header := errorType,\n      body := ?\n    };\n\n  template Message expectedInviteMsg modifies expectedErrorMsg := {\n      header := inviteType\n    };\n\n  template Message expectedAcceptMsg modifies expectedErrorMsg := {\n      header := acceptType\n    };\n\n} with { encode \"BER:1997\" }\n        </textarea>\n    </div>\n\n    <script> \n      var ttcnEditor = CodeMirror.fromTextArea(document.getElementById(\"ttcn-code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-ttcn\"\n      });\n      ttcnEditor.setSize(600, 860);\n      var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault;\n      CodeMirror.keyMap.default[(mac ? \"Cmd\" : \"Ctrl\") + \"-Space\"] = \"autocomplete\";\n    </script>\n    <br/>\n    <p><strong>Language:</strong> Testing and Test Control Notation\n        (<a href=\"http://en.wikipedia.org/wiki/TTCN\">TTCN</a>)\n    </p>\n    <p><strong>MIME types defined:</strong> <code>text/x-ttcn,\n        text/x-ttcn3, text/x-ttcnpp</code>.</p>\n    <br/>\n    <p>The development of this mode has been sponsored by <a href=\"http://www.ericsson.com/\">Ericsson\n    </a>.</p>\n    <p>Coded by Asmelash Tsegay Gebretsadkan </p>\n</article>\n\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ttcn/ttcn.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"ttcn\", function(config, parserConfig) {\n    var indentUnit = config.indentUnit,\n        keywords = parserConfig.keywords || {},\n        builtin = parserConfig.builtin || {},\n        timerOps = parserConfig.timerOps || {},\n        portOps  = parserConfig.portOps || {},\n        configOps = parserConfig.configOps || {},\n        verdictOps = parserConfig.verdictOps || {},\n        sutOps = parserConfig.sutOps || {},\n        functionOps = parserConfig.functionOps || {},\n\n        verdictConsts = parserConfig.verdictConsts || {},\n        booleanConsts = parserConfig.booleanConsts || {},\n        otherConsts   = parserConfig.otherConsts || {},\n\n        types = parserConfig.types || {},\n        visibilityModifiers = parserConfig.visibilityModifiers || {},\n        templateMatch = parserConfig.templateMatch || {},\n        multiLineStrings = parserConfig.multiLineStrings,\n        indentStatements = parserConfig.indentStatements !== false;\n    var isOperatorChar = /[+\\-*&@=<>!\\/]/;\n    var curPunc;\n\n    function tokenBase(stream, state) {\n      var ch = stream.next();\n\n      if (ch == '\"' || ch == \"'\") {\n        state.tokenize = tokenString(ch);\n        return state.tokenize(stream, state);\n      }\n      if (/[\\[\\]{}\\(\\),;\\\\:\\?\\.]/.test(ch)) {\n        curPunc = ch;\n        return \"punctuation\";\n      }\n      if (ch == \"#\"){\n        stream.skipToEnd();\n        return \"atom preprocessor\";\n      }\n      if (ch == \"%\"){\n        stream.eatWhile(/\\b/);\n        return \"atom ttcn3Macros\";\n      }\n      if (/\\d/.test(ch)) {\n        stream.eatWhile(/[\\w\\.]/);\n        return \"number\";\n      }\n      if (ch == \"/\") {\n        if (stream.eat(\"*\")) {\n          state.tokenize = tokenComment;\n          return tokenComment(stream, state);\n        }\n        if (stream.eat(\"/\")) {\n          stream.skipToEnd();\n          return \"comment\";\n        }\n      }\n      if (isOperatorChar.test(ch)) {\n        if(ch == \"@\"){\n          if(stream.match(\"try\") || stream.match(\"catch\")\n              || stream.match(\"lazy\")){\n            return \"keyword\";\n          }\n        }\n        stream.eatWhile(isOperatorChar);\n        return \"operator\";\n      }\n      stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n      var cur = stream.current();\n\n      if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n      if (builtin.propertyIsEnumerable(cur)) return \"builtin\";\n\n      if (timerOps.propertyIsEnumerable(cur)) return \"def timerOps\";\n      if (configOps.propertyIsEnumerable(cur)) return \"def configOps\";\n      if (verdictOps.propertyIsEnumerable(cur)) return \"def verdictOps\";\n      if (portOps.propertyIsEnumerable(cur)) return \"def portOps\";\n      if (sutOps.propertyIsEnumerable(cur)) return \"def sutOps\";\n      if (functionOps.propertyIsEnumerable(cur)) return \"def functionOps\";\n\n      if (verdictConsts.propertyIsEnumerable(cur)) return \"string verdictConsts\";\n      if (booleanConsts.propertyIsEnumerable(cur)) return \"string booleanConsts\";\n      if (otherConsts.propertyIsEnumerable(cur)) return \"string otherConsts\";\n\n      if (types.propertyIsEnumerable(cur)) return \"builtin types\";\n      if (visibilityModifiers.propertyIsEnumerable(cur))\n        return \"builtin visibilityModifiers\";\n      if (templateMatch.propertyIsEnumerable(cur)) return \"atom templateMatch\";\n\n      return \"variable\";\n    }\n\n    function tokenString(quote) {\n      return function(stream, state) {\n        var escaped = false, next, end = false;\n        while ((next = stream.next()) != null) {\n          if (next == quote && !escaped){\n            var afterQuote = stream.peek();\n            //look if the character after the quote is like the B in '10100010'B\n            if (afterQuote){\n              afterQuote = afterQuote.toLowerCase();\n              if(afterQuote == \"b\" || afterQuote == \"h\" || afterQuote == \"o\")\n                stream.next();\n            }\n            end = true; break;\n          }\n          escaped = !escaped && next == \"\\\\\";\n        }\n        if (end || !(escaped || multiLineStrings))\n          state.tokenize = null;\n        return \"string\";\n      };\n    }\n\n    function tokenComment(stream, state) {\n      var maybeEnd = false, ch;\n      while (ch = stream.next()) {\n        if (ch == \"/\" && maybeEnd) {\n          state.tokenize = null;\n          break;\n        }\n        maybeEnd = (ch == \"*\");\n      }\n      return \"comment\";\n    }\n\n    function Context(indented, column, type, align, prev) {\n      this.indented = indented;\n      this.column = column;\n      this.type = type;\n      this.align = align;\n      this.prev = prev;\n    }\n\n    function pushContext(state, col, type) {\n      var indent = state.indented;\n      if (state.context && state.context.type == \"statement\")\n        indent = state.context.indented;\n      return state.context = new Context(indent, col, type, null, state.context);\n    }\n\n    function popContext(state) {\n      var t = state.context.type;\n      if (t == \")\" || t == \"]\" || t == \"}\")\n        state.indented = state.context.indented;\n      return state.context = state.context.prev;\n    }\n\n    //Interface\n    return {\n      startState: function(basecolumn) {\n        return {\n          tokenize: null,\n          context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", false),\n          indented: 0,\n          startOfLine: true\n        };\n      },\n\n      token: function(stream, state) {\n        var ctx = state.context;\n        if (stream.sol()) {\n          if (ctx.align == null) ctx.align = false;\n          state.indented = stream.indentation();\n          state.startOfLine = true;\n        }\n        if (stream.eatSpace()) return null;\n        curPunc = null;\n        var style = (state.tokenize || tokenBase)(stream, state);\n        if (style == \"comment\") return style;\n        if (ctx.align == null) ctx.align = true;\n\n        if ((curPunc == \";\" || curPunc == \":\" || curPunc == \",\")\n            && ctx.type == \"statement\"){\n          popContext(state);\n        }\n        else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n        else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n        else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n        else if (curPunc == \"}\") {\n          while (ctx.type == \"statement\") ctx = popContext(state);\n          if (ctx.type == \"}\") ctx = popContext(state);\n          while (ctx.type == \"statement\") ctx = popContext(state);\n        }\n        else if (curPunc == ctx.type) popContext(state);\n        else if (indentStatements &&\n            (((ctx.type == \"}\" || ctx.type == \"top\") && curPunc != ';') ||\n            (ctx.type == \"statement\" && curPunc == \"newstatement\")))\n          pushContext(state, stream.column(), \"statement\");\n\n        state.startOfLine = false;\n\n        return style;\n      },\n\n      electricChars: \"{}\",\n      blockCommentStart: \"/*\",\n      blockCommentEnd: \"*/\",\n      lineComment: \"//\",\n      fold: \"brace\"\n    };\n  });\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  function def(mimes, mode) {\n    if (typeof mimes == \"string\") mimes = [mimes];\n    var words = [];\n    function add(obj) {\n      if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))\n        words.push(prop);\n    }\n\n    add(mode.keywords);\n    add(mode.builtin);\n    add(mode.timerOps);\n    add(mode.portOps);\n\n    if (words.length) {\n      mode.helperType = mimes[0];\n      CodeMirror.registerHelper(\"hintWords\", mimes[0], words);\n    }\n\n    for (var i = 0; i < mimes.length; ++i)\n      CodeMirror.defineMIME(mimes[i], mode);\n  }\n\n  def([\"text/x-ttcn\", \"text/x-ttcn3\", \"text/x-ttcnpp\"], {\n    name: \"ttcn\",\n    keywords: words(\"activate address alive all alt altstep and and4b any\" +\n    \" break case component const continue control deactivate\" +\n    \" display do else encode enumerated except exception\" +\n    \" execute extends extension external for from function\" +\n    \" goto group if import in infinity inout interleave\" +\n    \" label language length log match message mixed mod\" +\n    \" modifies module modulepar mtc noblock not not4b nowait\" +\n    \" of on optional or or4b out override param pattern port\" +\n    \" procedure record recursive rem repeat return runs select\" +\n    \" self sender set signature system template testcase to\" +\n    \" type union value valueof var variant while with xor xor4b\"),\n    builtin: words(\"bit2hex bit2int bit2oct bit2str char2int char2oct encvalue\" +\n    \" decomp decvalue float2int float2str hex2bit hex2int\" +\n    \" hex2oct hex2str int2bit int2char int2float int2hex\" +\n    \" int2oct int2str int2unichar isbound ischosen ispresent\" +\n    \" isvalue lengthof log2str oct2bit oct2char oct2hex oct2int\" +\n    \" oct2str regexp replace rnd sizeof str2bit str2float\" +\n    \" str2hex str2int str2oct substr unichar2int unichar2char\" +\n    \" enum2int\"),\n    types: words(\"anytype bitstring boolean char charstring default float\" +\n    \" hexstring integer objid octetstring universal verdicttype timer\"),\n    timerOps: words(\"read running start stop timeout\"),\n    portOps: words(\"call catch check clear getcall getreply halt raise receive\" +\n    \" reply send trigger\"),\n    configOps: words(\"create connect disconnect done kill killed map unmap\"),\n    verdictOps: words(\"getverdict setverdict\"),\n    sutOps: words(\"action\"),\n    functionOps: words(\"apply derefers refers\"),\n\n    verdictConsts: words(\"error fail inconc none pass\"),\n    booleanConsts: words(\"true false\"),\n    otherConsts: words(\"null NULL omit\"),\n\n    visibilityModifiers: words(\"private public friend\"),\n    templateMatch: words(\"complement ifpresent subset superset permutation\"),\n    multiLineStrings: true\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ttcn-cfg/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: TTCN-CFG mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"ttcn-cfg.js\"></script>\n<style>\n    .CodeMirror {\n        border-top: 1px solid black;\n        border-bottom: 1px solid black;\n    }\n</style>\n<div id=nav>\n    <a href=\"https://codemirror.net\"><h1>CodeMirror</h1>\n        <img id=logo src=\"../../doc/logo.png\">\n    </a>\n\n    <ul>\n        <li><a href=\"../../index.html\">Home</a>\n        <li><a href=\"../../doc/manual.html\">Manual</a>\n        <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n    </ul>\n    <ul>\n        <li><a href=\"../index.html\">Language modes</a>\n        <li><a class=active href=\"http://en.wikipedia.org/wiki/TTCN\">TTCN-CFG</a>\n    </ul>\n</div>\n<article>\n    <h2>TTCN-CFG example</h2>\n    <div>\n        <textarea id=\"ttcn-cfg-code\">\n[MODULE_PARAMETERS]\n# This section shall contain the values of all parameters that are defined in your TTCN-3 modules.\n\n[LOGGING]\n# In this section you can specify the name of the log file and the classes of events\n# you want to log into the file or display on console (standard error).\n\nLogFile := \"logs/%e.%h-%r.%s\"\nFileMask := LOG_ALL | DEBUG | MATCHING\nConsoleMask := ERROR | WARNING | TESTCASE | STATISTICS | PORTEVENT\n\nLogSourceInfo := Yes\nAppendFile := No\nTimeStampFormat := DateTime\nLogEventTypes := Yes\nSourceInfoFormat := Single\nLogEntityName := Yes\n\n[TESTPORT_PARAMETERS]\n# In this section you can specify parameters that are passed to Test Ports.\n\n[DEFINE]\n# In this section you can create macro definitions,\n# that can be used in other configuration file sections except [INCLUDE].\n\n[INCLUDE]\n# To use configuration settings given in other configuration files,\n# the configuration files just need to be listed in this section, with their full or relative pathnames.\n\n[EXTERNAL_COMMANDS]\n# This section can define external commands (shell scripts) to be executed by the ETS\n# whenever a control part or test case is started or terminated.\n\nBeginTestCase := \"\"\nEndTestCase := \"\"\nBeginControlPart := \"\"\nEndControlPart := \"\"\n\n[EXECUTE]\n# In this section you can specify what parts of your test suite you want to execute.\n\n[GROUPS]\n# In this section you can specify groups of hosts. These groups can be used inside the\n# [COMPONENTS] section to restrict the creation of certain PTCs to a given set of hosts.\n\n[COMPONENTS]\n# This section consists of rules restricting the location of created PTCs.\n\n[MAIN_CONTROLLER]\n# The options herein control the behavior of MC.\n\nTCPPort := 0\nKillTimer := 10.0\nNumHCs := 0\nLocalAddress :=\n        </textarea>\n    </div>\n\n    <script> \n      var ttcnEditor = CodeMirror.fromTextArea(document.getElementById(\"ttcn-cfg-code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        mode: \"text/x-ttcn-cfg\"\n      });\n      ttcnEditor.setSize(600, 860);\n      var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault;\n      CodeMirror.keyMap.default[(mac ? \"Cmd\" : \"Ctrl\") + \"-Space\"] = \"autocomplete\";\n    </script>\n    <br/>\n    <p><strong>Language:</strong> Testing and Test Control Notation -\n        Configuration files\n        (<a href=\"http://en.wikipedia.org/wiki/TTCN\">TTCN-CFG</a>)\n    </p>\n    <p><strong>MIME types defined:</strong> <code>text/x-ttcn-cfg</code>.</p>\n\n    <br/>\n    <p>The development of this mode has been sponsored by <a href=\"http://www.ericsson.com/\">Ericsson\n    </a>.</p>\n    <p>Coded by Asmelash Tsegay Gebretsadkan </p>\n</article>\n\n"
  },
  {
    "path": "third_party/CodeMirror/mode/ttcn-cfg/ttcn-cfg.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"ttcn-cfg\", function(config, parserConfig) {\n    var indentUnit = config.indentUnit,\n        keywords = parserConfig.keywords || {},\n        fileNCtrlMaskOptions = parserConfig.fileNCtrlMaskOptions || {},\n        externalCommands = parserConfig.externalCommands || {},\n        multiLineStrings = parserConfig.multiLineStrings,\n        indentStatements = parserConfig.indentStatements !== false;\n    var isOperatorChar = /[\\|]/;\n    var curPunc;\n\n    function tokenBase(stream, state) {\n      var ch = stream.next();\n      if (ch == '\"' || ch == \"'\") {\n        state.tokenize = tokenString(ch);\n        return state.tokenize(stream, state);\n      }\n      if (/[:=]/.test(ch)) {\n        curPunc = ch;\n        return \"punctuation\";\n      }\n      if (ch == \"#\"){\n        stream.skipToEnd();\n        return \"comment\";\n      }\n      if (/\\d/.test(ch)) {\n        stream.eatWhile(/[\\w\\.]/);\n        return \"number\";\n      }\n      if (isOperatorChar.test(ch)) {\n        stream.eatWhile(isOperatorChar);\n        return \"operator\";\n      }\n      if (ch == \"[\"){\n        stream.eatWhile(/[\\w_\\]]/);\n        return \"number sectionTitle\";\n      }\n\n      stream.eatWhile(/[\\w\\$_]/);\n      var cur = stream.current();\n      if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n      if (fileNCtrlMaskOptions.propertyIsEnumerable(cur))\n        return \"negative fileNCtrlMaskOptions\";\n      if (externalCommands.propertyIsEnumerable(cur)) return \"negative externalCommands\";\n\n      return \"variable\";\n    }\n\n    function tokenString(quote) {\n      return function(stream, state) {\n        var escaped = false, next, end = false;\n        while ((next = stream.next()) != null) {\n          if (next == quote && !escaped){\n            var afterNext = stream.peek();\n            //look if the character if the quote is like the B in '10100010'B\n            if (afterNext){\n              afterNext = afterNext.toLowerCase();\n              if(afterNext == \"b\" || afterNext == \"h\" || afterNext == \"o\")\n                stream.next();\n            }\n            end = true; break;\n          }\n          escaped = !escaped && next == \"\\\\\";\n        }\n        if (end || !(escaped || multiLineStrings))\n          state.tokenize = null;\n        return \"string\";\n      };\n    }\n\n    function Context(indented, column, type, align, prev) {\n      this.indented = indented;\n      this.column = column;\n      this.type = type;\n      this.align = align;\n      this.prev = prev;\n    }\n    function pushContext(state, col, type) {\n      var indent = state.indented;\n      if (state.context && state.context.type == \"statement\")\n        indent = state.context.indented;\n      return state.context = new Context(indent, col, type, null, state.context);\n    }\n    function popContext(state) {\n      var t = state.context.type;\n      if (t == \")\" || t == \"]\" || t == \"}\")\n        state.indented = state.context.indented;\n      return state.context = state.context.prev;\n    }\n\n    //Interface\n    return {\n      startState: function(basecolumn) {\n        return {\n          tokenize: null,\n          context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", false),\n          indented: 0,\n          startOfLine: true\n        };\n      },\n\n      token: function(stream, state) {\n        var ctx = state.context;\n        if (stream.sol()) {\n          if (ctx.align == null) ctx.align = false;\n          state.indented = stream.indentation();\n          state.startOfLine = true;\n        }\n        if (stream.eatSpace()) return null;\n        curPunc = null;\n        var style = (state.tokenize || tokenBase)(stream, state);\n        if (style == \"comment\") return style;\n        if (ctx.align == null) ctx.align = true;\n\n        if ((curPunc == \";\" || curPunc == \":\" || curPunc == \",\")\n            && ctx.type == \"statement\"){\n          popContext(state);\n        }\n        else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n        else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n        else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n        else if (curPunc == \"}\") {\n          while (ctx.type == \"statement\") ctx = popContext(state);\n          if (ctx.type == \"}\") ctx = popContext(state);\n          while (ctx.type == \"statement\") ctx = popContext(state);\n        }\n        else if (curPunc == ctx.type) popContext(state);\n        else if (indentStatements && (((ctx.type == \"}\" || ctx.type == \"top\")\n            && curPunc != ';') || (ctx.type == \"statement\"\n            && curPunc == \"newstatement\")))\n          pushContext(state, stream.column(), \"statement\");\n        state.startOfLine = false;\n        return style;\n      },\n\n      electricChars: \"{}\",\n      lineComment: \"#\",\n      fold: \"brace\"\n    };\n  });\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i)\n      obj[words[i]] = true;\n    return obj;\n  }\n\n  CodeMirror.defineMIME(\"text/x-ttcn-cfg\", {\n    name: \"ttcn-cfg\",\n    keywords: words(\"Yes No LogFile FileMask ConsoleMask AppendFile\" +\n    \" TimeStampFormat LogEventTypes SourceInfoFormat\" +\n    \" LogEntityName LogSourceInfo DiskFullAction\" +\n    \" LogFileNumber LogFileSize MatchingHints Detailed\" +\n    \" Compact SubCategories Stack Single None Seconds\" +\n    \" DateTime Time Stop Error Retry Delete TCPPort KillTimer\" +\n    \" NumHCs UnixSocketsEnabled LocalAddress\"),\n    fileNCtrlMaskOptions: words(\"TTCN_EXECUTOR TTCN_ERROR TTCN_WARNING\" +\n    \" TTCN_PORTEVENT TTCN_TIMEROP TTCN_VERDICTOP\" +\n    \" TTCN_DEFAULTOP TTCN_TESTCASE TTCN_ACTION\" +\n    \" TTCN_USER TTCN_FUNCTION TTCN_STATISTICS\" +\n    \" TTCN_PARALLEL TTCN_MATCHING TTCN_DEBUG\" +\n    \" EXECUTOR ERROR WARNING PORTEVENT TIMEROP\" +\n    \" VERDICTOP DEFAULTOP TESTCASE ACTION USER\" +\n    \" FUNCTION STATISTICS PARALLEL MATCHING DEBUG\" +\n    \" LOG_ALL LOG_NOTHING ACTION_UNQUALIFIED\" +\n    \" DEBUG_ENCDEC DEBUG_TESTPORT\" +\n    \" DEBUG_UNQUALIFIED DEFAULTOP_ACTIVATE\" +\n    \" DEFAULTOP_DEACTIVATE DEFAULTOP_EXIT\" +\n    \" DEFAULTOP_UNQUALIFIED ERROR_UNQUALIFIED\" +\n    \" EXECUTOR_COMPONENT EXECUTOR_CONFIGDATA\" +\n    \" EXECUTOR_EXTCOMMAND EXECUTOR_LOGOPTIONS\" +\n    \" EXECUTOR_RUNTIME EXECUTOR_UNQUALIFIED\" +\n    \" FUNCTION_RND FUNCTION_UNQUALIFIED\" +\n    \" MATCHING_DONE MATCHING_MCSUCCESS\" +\n    \" MATCHING_MCUNSUCC MATCHING_MMSUCCESS\" +\n    \" MATCHING_MMUNSUCC MATCHING_PCSUCCESS\" +\n    \" MATCHING_PCUNSUCC MATCHING_PMSUCCESS\" +\n    \" MATCHING_PMUNSUCC MATCHING_PROBLEM\" +\n    \" MATCHING_TIMEOUT MATCHING_UNQUALIFIED\" +\n    \" PARALLEL_PORTCONN PARALLEL_PORTMAP\" +\n    \" PARALLEL_PTC PARALLEL_UNQUALIFIED\" +\n    \" PORTEVENT_DUALRECV PORTEVENT_DUALSEND\" +\n    \" PORTEVENT_MCRECV PORTEVENT_MCSEND\" +\n    \" PORTEVENT_MMRECV PORTEVENT_MMSEND\" +\n    \" PORTEVENT_MQUEUE PORTEVENT_PCIN\" +\n    \" PORTEVENT_PCOUT PORTEVENT_PMIN\" +\n    \" PORTEVENT_PMOUT PORTEVENT_PQUEUE\" +\n    \" PORTEVENT_STATE PORTEVENT_UNQUALIFIED\" +\n    \" STATISTICS_UNQUALIFIED STATISTICS_VERDICT\" +\n    \" TESTCASE_FINISH TESTCASE_START\" +\n    \" TESTCASE_UNQUALIFIED TIMEROP_GUARD\" +\n    \" TIMEROP_READ TIMEROP_START TIMEROP_STOP\" +\n    \" TIMEROP_TIMEOUT TIMEROP_UNQUALIFIED\" +\n    \" USER_UNQUALIFIED VERDICTOP_FINAL\" +\n    \" VERDICTOP_GETVERDICT VERDICTOP_SETVERDICT\" +\n    \" VERDICTOP_UNQUALIFIED WARNING_UNQUALIFIED\"),\n    externalCommands: words(\"BeginControlPart EndControlPart BeginTestCase\" +\n    \" EndTestCase\"),\n    multiLineStrings: true\n  });\n});"
  },
  {
    "path": "third_party/CodeMirror/mode/turtle/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Turtle mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"turtle.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Turtle</a>\n  </ul>\n</div>\n\n<article>\n<h2>Turtle mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n@prefix geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> .\n@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n\n<http://purl.org/net/bsletten> \n    a foaf:Person;\n    foaf:interest <http://www.w3.org/2000/01/sw/>;\n    foaf:based_near [\n        geo:lat \"34.0736111\" ;\n        geo:lon \"-118.3994444\"\n   ]\n\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"text/turtle\",\n        matchBrackets: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/turtle</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/turtle/turtle.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"turtle\", function(config) {\n  var indentUnit = config.indentUnit;\n  var curPunc;\n\n  function wordRegexp(words) {\n    return new RegExp(\"^(?:\" + words.join(\"|\") + \")$\", \"i\");\n  }\n  var ops = wordRegexp([]);\n  var keywords = wordRegexp([\"@prefix\", \"@base\", \"a\"]);\n  var operatorChars = /[*+\\-<>=&|]/;\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    curPunc = null;\n    if (ch == \"<\" && !stream.match(/^[\\s\\u00a0=]/, false)) {\n      stream.match(/^[^\\s\\u00a0>]*>?/);\n      return \"atom\";\n    }\n    else if (ch == \"\\\"\" || ch == \"'\") {\n      state.tokenize = tokenLiteral(ch);\n      return state.tokenize(stream, state);\n    }\n    else if (/[{}\\(\\),\\.;\\[\\]]/.test(ch)) {\n      curPunc = ch;\n      return null;\n    }\n    else if (ch == \"#\") {\n      stream.skipToEnd();\n      return \"comment\";\n    }\n    else if (operatorChars.test(ch)) {\n      stream.eatWhile(operatorChars);\n      return null;\n    }\n    else if (ch == \":\") {\n          return \"operator\";\n        } else {\n      stream.eatWhile(/[_\\w\\d]/);\n      if(stream.peek() == \":\") {\n        return \"variable-3\";\n      } else {\n             var word = stream.current();\n\n             if(keywords.test(word)) {\n                        return \"meta\";\n             }\n\n             if(ch >= \"A\" && ch <= \"Z\") {\n                    return \"comment\";\n                 } else {\n                        return \"keyword\";\n                 }\n      }\n      var word = stream.current();\n      if (ops.test(word))\n        return null;\n      else if (keywords.test(word))\n        return \"meta\";\n      else\n        return \"variable\";\n    }\n  }\n\n  function tokenLiteral(quote) {\n    return function(stream, state) {\n      var escaped = false, ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == quote && !escaped) {\n          state.tokenize = tokenBase;\n          break;\n        }\n        escaped = !escaped && ch == \"\\\\\";\n      }\n      return \"string\";\n    };\n  }\n\n  function pushContext(state, type, col) {\n    state.context = {prev: state.context, indent: state.indent, col: col, type: type};\n  }\n  function popContext(state) {\n    state.indent = state.context.indent;\n    state.context = state.context.prev;\n  }\n\n  return {\n    startState: function() {\n      return {tokenize: tokenBase,\n              context: null,\n              indent: 0,\n              col: 0};\n    },\n\n    token: function(stream, state) {\n      if (stream.sol()) {\n        if (state.context && state.context.align == null) state.context.align = false;\n        state.indent = stream.indentation();\n      }\n      if (stream.eatSpace()) return null;\n      var style = state.tokenize(stream, state);\n\n      if (style != \"comment\" && state.context && state.context.align == null && state.context.type != \"pattern\") {\n        state.context.align = true;\n      }\n\n      if (curPunc == \"(\") pushContext(state, \")\", stream.column());\n      else if (curPunc == \"[\") pushContext(state, \"]\", stream.column());\n      else if (curPunc == \"{\") pushContext(state, \"}\", stream.column());\n      else if (/[\\]\\}\\)]/.test(curPunc)) {\n        while (state.context && state.context.type == \"pattern\") popContext(state);\n        if (state.context && curPunc == state.context.type) popContext(state);\n      }\n      else if (curPunc == \".\" && state.context && state.context.type == \"pattern\") popContext(state);\n      else if (/atom|string|variable/.test(style) && state.context) {\n        if (/[\\}\\]]/.test(state.context.type))\n          pushContext(state, \"pattern\", stream.column());\n        else if (state.context.type == \"pattern\" && !state.context.align) {\n          state.context.align = true;\n          state.context.col = stream.column();\n        }\n      }\n\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      var firstChar = textAfter && textAfter.charAt(0);\n      var context = state.context;\n      if (/[\\]\\}]/.test(firstChar))\n        while (context && context.type == \"pattern\") context = context.prev;\n\n      var closing = context && firstChar == context.type;\n      if (!context)\n        return 0;\n      else if (context.type == \"pattern\")\n        return context.col;\n      else if (context.align)\n        return context.col + (closing ? 0 : 1);\n      else\n        return context.indent + (closing ? 0 : indentUnit);\n    },\n\n    lineComment: \"#\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/turtle\", \"turtle\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/twig/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Twig mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"twig.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Twig</a>\n  </ul>\n</div>\n\n<article>\n<h2>Twig mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n{% extends \"layout.twig\" %}\n{% block title %}CodeMirror: Twig mode{% endblock %}\n{# this is a comment #}\n{% block content %}\n  {% for foo in bar if foo.baz is divisible by(3) %}\n    Hello {{ foo.world }}\n  {% else %}\n    {% set msg = \"Result not found\" %}\n    {% include \"empty.twig\" with { message: msg } %}\n  {% endfor %}\n{% endblock %}\n</textarea></form>\n    <script>\n      var editor =\n      CodeMirror.fromTextArea(document.getElementById(\"code\"), {mode:\n        {name: \"twig\", htmlMode: true}});\n    </script>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/twig/twig.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"),  require(\"../../addon/mode/multiplex\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../../addon/mode/multiplex\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  CodeMirror.defineMode(\"twig:inner\", function() {\n    var keywords = [\"and\", \"as\", \"autoescape\", \"endautoescape\", \"block\", \"do\", \"endblock\", \"else\", \"elseif\", \"extends\", \"for\", \"endfor\", \"embed\", \"endembed\", \"filter\", \"endfilter\", \"flush\", \"from\", \"if\", \"endif\", \"in\", \"is\", \"include\", \"import\", \"not\", \"or\", \"set\", \"spaceless\", \"endspaceless\", \"with\", \"endwith\", \"trans\", \"endtrans\", \"blocktrans\", \"endblocktrans\", \"macro\", \"endmacro\", \"use\", \"verbatim\", \"endverbatim\"],\n        operator = /^[+\\-*&%=<>!?|~^]/,\n        sign = /^[:\\[\\(\\{]/,\n        atom = [\"true\", \"false\", \"null\", \"empty\", \"defined\", \"divisibleby\", \"divisible by\", \"even\", \"odd\", \"iterable\", \"sameas\", \"same as\"],\n        number = /^(\\d[+\\-\\*\\/])?\\d+(\\.\\d+)?/;\n\n    keywords = new RegExp(\"((\" + keywords.join(\")|(\") + \"))\\\\b\");\n    atom = new RegExp(\"((\" + atom.join(\")|(\") + \"))\\\\b\");\n\n    function tokenBase (stream, state) {\n      var ch = stream.peek();\n\n      //Comment\n      if (state.incomment) {\n        if (!stream.skipTo(\"#}\")) {\n          stream.skipToEnd();\n        } else {\n          stream.eatWhile(/\\#|}/);\n          state.incomment = false;\n        }\n        return \"comment\";\n      //Tag\n      } else if (state.intag) {\n        //After operator\n        if (state.operator) {\n          state.operator = false;\n          if (stream.match(atom)) {\n            return \"atom\";\n          }\n          if (stream.match(number)) {\n            return \"number\";\n          }\n        }\n        //After sign\n        if (state.sign) {\n          state.sign = false;\n          if (stream.match(atom)) {\n            return \"atom\";\n          }\n          if (stream.match(number)) {\n            return \"number\";\n          }\n        }\n\n        if (state.instring) {\n          if (ch == state.instring) {\n            state.instring = false;\n          }\n          stream.next();\n          return \"string\";\n        } else if (ch == \"'\" || ch == '\"') {\n          state.instring = ch;\n          stream.next();\n          return \"string\";\n        } else if (stream.match(state.intag + \"}\") || stream.eat(\"-\") && stream.match(state.intag + \"}\")) {\n          state.intag = false;\n          return \"tag\";\n        } else if (stream.match(operator)) {\n          state.operator = true;\n          return \"operator\";\n        } else if (stream.match(sign)) {\n          state.sign = true;\n        } else {\n          if (stream.eat(\" \") || stream.sol()) {\n            if (stream.match(keywords)) {\n              return \"keyword\";\n            }\n            if (stream.match(atom)) {\n              return \"atom\";\n            }\n            if (stream.match(number)) {\n              return \"number\";\n            }\n            if (stream.sol()) {\n              stream.next();\n            }\n          } else {\n            stream.next();\n          }\n\n        }\n        return \"variable\";\n      } else if (stream.eat(\"{\")) {\n        if (stream.eat(\"#\")) {\n          state.incomment = true;\n          if (!stream.skipTo(\"#}\")) {\n            stream.skipToEnd();\n          } else {\n            stream.eatWhile(/\\#|}/);\n            state.incomment = false;\n          }\n          return \"comment\";\n        //Open tag\n        } else if (ch = stream.eat(/\\{|%/)) {\n          //Cache close tag\n          state.intag = ch;\n          if (ch == \"{\") {\n            state.intag = \"}\";\n          }\n          stream.eat(\"-\");\n          return \"tag\";\n        }\n      }\n      stream.next();\n    };\n\n    return {\n      startState: function () {\n        return {};\n      },\n      token: function (stream, state) {\n        return tokenBase(stream, state);\n      }\n    };\n  });\n\n  CodeMirror.defineMode(\"twig\", function(config, parserConfig) {\n    var twigInner = CodeMirror.getMode(config, \"twig:inner\");\n    if (!parserConfig || !parserConfig.base) return twigInner;\n    return CodeMirror.multiplexingMode(\n      CodeMirror.getMode(config, parserConfig.base), {\n        open: /\\{[{#%]/, close: /[}#%]\\}/, mode: twigInner, parseDelimiters: true\n      }\n    );\n  });\n  CodeMirror.defineMIME(\"text/x-twig\", \"twig\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/vb/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: VB.NET mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link href=\"http://fonts.googleapis.com/css?family=Inconsolata\" rel=\"stylesheet\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"vb.js\"></script>\n<script src=\"../../addon/runmode/runmode.js\"></script>\n<style>\n      .CodeMirror {border: 1px solid #aaa; height:210px; height: auto;}\n      .CodeMirror-scroll { overflow-x: auto; overflow-y: hidden;}\n      .CodeMirror pre { font-family: Inconsolata; font-size: 14px}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">VB.NET</a>\n  </ul>\n</div>\n\n<article>\n<h2>VB.NET mode</h2>\n  <div id=\"edit\">\n  <textarea name=\"code\" id=\"code\" >\nClass rocket\n  Private quality as Double\n  Public Sub launch() as String\n    If quality > 0.8\n      launch = \"Successful\"\n    Else\n      launch = \"Failed\"\n    End If\n  End sub\nEnd class\n</textarea>\n  </div>\n  <p>MIME type defined: <code>text/x-vb</code>.</p>\n<script>CodeMirror.fromTextArea(document.getElementById(\"code\"))</script>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/vb/vb.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"vb\", function(conf, parserConf) {\n    var ERRORCLASS = 'error';\n\n    function wordRegexp(words) {\n        return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\", \"i\");\n    }\n\n    var singleOperators = new RegExp(\"^[\\\\+\\\\-\\\\*/%&\\\\\\\\|\\\\^~<>!]\");\n    var singleDelimiters = new RegExp('^[\\\\(\\\\)\\\\[\\\\]\\\\{\\\\}@,:`=;\\\\.]');\n    var doubleOperators = new RegExp(\"^((==)|(<>)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\\\*\\\\*))\");\n    var doubleDelimiters = new RegExp(\"^((\\\\+=)|(\\\\-=)|(\\\\*=)|(%=)|(/=)|(&=)|(\\\\|=)|(\\\\^=))\");\n    var tripleDelimiters = new RegExp(\"^((//=)|(>>=)|(<<=)|(\\\\*\\\\*=))\");\n    var identifiers = new RegExp(\"^[_A-Za-z][_A-Za-z0-9]*\");\n\n    var openingKeywords = ['class','module', 'sub','enum','select','while','if','function',  'get','set','property', 'try'];\n    var middleKeywords = ['else','elseif','case', 'catch'];\n    var endKeywords = ['next','loop'];\n\n    var operatorKeywords = ['and', 'or', 'not', 'xor', 'in'];\n    var wordOperators = wordRegexp(operatorKeywords);\n    var commonKeywords = ['as', 'dim', 'break',  'continue','optional', 'then',  'until',\n                          'goto', 'byval','byref','new','handles','property', 'return',\n                          'const','private', 'protected', 'friend', 'public', 'shared', 'static', 'true','false'];\n    var commontypes = ['integer','string','double','decimal','boolean','short','char', 'float','single'];\n\n    var keywords = wordRegexp(commonKeywords);\n    var types = wordRegexp(commontypes);\n    var stringPrefixes = '\"';\n\n    var opening = wordRegexp(openingKeywords);\n    var middle = wordRegexp(middleKeywords);\n    var closing = wordRegexp(endKeywords);\n    var doubleClosing = wordRegexp(['end']);\n    var doOpening = wordRegexp(['do']);\n\n    var indentInfo = null;\n\n    CodeMirror.registerHelper(\"hintWords\", \"vb\", openingKeywords.concat(middleKeywords).concat(endKeywords)\n                                .concat(operatorKeywords).concat(commonKeywords).concat(commontypes));\n\n    function indent(_stream, state) {\n      state.currentIndent++;\n    }\n\n    function dedent(_stream, state) {\n      state.currentIndent--;\n    }\n    // tokenizers\n    function tokenBase(stream, state) {\n        if (stream.eatSpace()) {\n            return null;\n        }\n\n        var ch = stream.peek();\n\n        // Handle Comments\n        if (ch === \"'\") {\n            stream.skipToEnd();\n            return 'comment';\n        }\n\n\n        // Handle Number Literals\n        if (stream.match(/^((&H)|(&O))?[0-9\\.a-f]/i, false)) {\n            var floatLiteral = false;\n            // Floats\n            if (stream.match(/^\\d*\\.\\d+F?/i)) { floatLiteral = true; }\n            else if (stream.match(/^\\d+\\.\\d*F?/)) { floatLiteral = true; }\n            else if (stream.match(/^\\.\\d+F?/)) { floatLiteral = true; }\n\n            if (floatLiteral) {\n                // Float literals may be \"imaginary\"\n                stream.eat(/J/i);\n                return 'number';\n            }\n            // Integers\n            var intLiteral = false;\n            // Hex\n            if (stream.match(/^&H[0-9a-f]+/i)) { intLiteral = true; }\n            // Octal\n            else if (stream.match(/^&O[0-7]+/i)) { intLiteral = true; }\n            // Decimal\n            else if (stream.match(/^[1-9]\\d*F?/)) {\n                // Decimal literals may be \"imaginary\"\n                stream.eat(/J/i);\n                // TODO - Can you have imaginary longs?\n                intLiteral = true;\n            }\n            // Zero by itself with no other piece of number.\n            else if (stream.match(/^0(?![\\dx])/i)) { intLiteral = true; }\n            if (intLiteral) {\n                // Integer literals may be \"long\"\n                stream.eat(/L/i);\n                return 'number';\n            }\n        }\n\n        // Handle Strings\n        if (stream.match(stringPrefixes)) {\n            state.tokenize = tokenStringFactory(stream.current());\n            return state.tokenize(stream, state);\n        }\n\n        // Handle operators and Delimiters\n        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {\n            return null;\n        }\n        if (stream.match(doubleOperators)\n            || stream.match(singleOperators)\n            || stream.match(wordOperators)) {\n            return 'operator';\n        }\n        if (stream.match(singleDelimiters)) {\n            return null;\n        }\n        if (stream.match(doOpening)) {\n            indent(stream,state);\n            state.doInCurrentLine = true;\n            return 'keyword';\n        }\n        if (stream.match(opening)) {\n            if (! state.doInCurrentLine)\n              indent(stream,state);\n            else\n              state.doInCurrentLine = false;\n            return 'keyword';\n        }\n        if (stream.match(middle)) {\n            return 'keyword';\n        }\n\n        if (stream.match(doubleClosing)) {\n            dedent(stream,state);\n            dedent(stream,state);\n            return 'keyword';\n        }\n        if (stream.match(closing)) {\n            dedent(stream,state);\n            return 'keyword';\n        }\n\n        if (stream.match(types)) {\n            return 'keyword';\n        }\n\n        if (stream.match(keywords)) {\n            return 'keyword';\n        }\n\n        if (stream.match(identifiers)) {\n            return 'variable';\n        }\n\n        // Handle non-detected items\n        stream.next();\n        return ERRORCLASS;\n    }\n\n    function tokenStringFactory(delimiter) {\n        var singleline = delimiter.length == 1;\n        var OUTCLASS = 'string';\n\n        return function(stream, state) {\n            while (!stream.eol()) {\n                stream.eatWhile(/[^'\"]/);\n                if (stream.match(delimiter)) {\n                    state.tokenize = tokenBase;\n                    return OUTCLASS;\n                } else {\n                    stream.eat(/['\"]/);\n                }\n            }\n            if (singleline) {\n                if (parserConf.singleLineStringErrors) {\n                    return ERRORCLASS;\n                } else {\n                    state.tokenize = tokenBase;\n                }\n            }\n            return OUTCLASS;\n        };\n    }\n\n\n    function tokenLexer(stream, state) {\n        var style = state.tokenize(stream, state);\n        var current = stream.current();\n\n        // Handle '.' connected identifiers\n        if (current === '.') {\n            style = state.tokenize(stream, state);\n            if (style === 'variable') {\n                return 'variable';\n            } else {\n                return ERRORCLASS;\n            }\n        }\n\n\n        var delimiter_index = '[({'.indexOf(current);\n        if (delimiter_index !== -1) {\n            indent(stream, state );\n        }\n        if (indentInfo === 'dedent') {\n            if (dedent(stream, state)) {\n                return ERRORCLASS;\n            }\n        }\n        delimiter_index = '])}'.indexOf(current);\n        if (delimiter_index !== -1) {\n            if (dedent(stream, state)) {\n                return ERRORCLASS;\n            }\n        }\n\n        return style;\n    }\n\n    var external = {\n        electricChars:\"dDpPtTfFeE \",\n        startState: function() {\n            return {\n              tokenize: tokenBase,\n              lastToken: null,\n              currentIndent: 0,\n              nextLineIndent: 0,\n              doInCurrentLine: false\n\n\n          };\n        },\n\n        token: function(stream, state) {\n            if (stream.sol()) {\n              state.currentIndent += state.nextLineIndent;\n              state.nextLineIndent = 0;\n              state.doInCurrentLine = 0;\n            }\n            var style = tokenLexer(stream, state);\n\n            state.lastToken = {style:style, content: stream.current()};\n\n\n\n            return style;\n        },\n\n        indent: function(state, textAfter) {\n            var trueText = textAfter.replace(/^\\s+|\\s+$/g, '') ;\n            if (trueText.match(closing) || trueText.match(doubleClosing) || trueText.match(middle)) return conf.indentUnit*(state.currentIndent-1);\n            if(state.currentIndent < 0) return 0;\n            return state.currentIndent * conf.indentUnit;\n        },\n\n        lineComment: \"'\"\n    };\n    return external;\n});\n\nCodeMirror.defineMIME(\"text/x-vb\", \"vb\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/vbscript/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: VBScript mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"vbscript.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">VBScript</a>\n  </ul>\n</div>\n\n<article>\n<h2>VBScript mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n' Pete Guhl\n' 03-04-2012\n'\n' Basic VBScript support for codemirror2\n\nConst ForReading = 1, ForWriting = 2, ForAppending = 8\n\nCall Sub020_PostBroadcastToUrbanAirship(strUserName, strPassword, intTransmitID, strResponse)\n\nIf Not IsNull(strResponse) AND Len(strResponse) = 0 Then\n\tboolTransmitOkYN = False\nElse\n\t' WScript.Echo \"Oh Happy Day! Oh Happy DAY!\"\n\tboolTransmitOkYN = True\nEnd If\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        indentUnit: 4\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/vbscript</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/vbscript/vbscript.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/*\nFor extra ASP classic objects, initialize CodeMirror instance with this option:\n    isASP: true\n\nE.G.:\n    var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        isASP: true\n      });\n*/\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"vbscript\", function(conf, parserConf) {\n    var ERRORCLASS = 'error';\n\n    function wordRegexp(words) {\n        return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\", \"i\");\n    }\n\n    var singleOperators = new RegExp(\"^[\\\\+\\\\-\\\\*/&\\\\\\\\\\\\^<>=]\");\n    var doubleOperators = new RegExp(\"^((<>)|(<=)|(>=))\");\n    var singleDelimiters = new RegExp('^[\\\\.,]');\n    var brakets = new RegExp('^[\\\\(\\\\)]');\n    var identifiers = new RegExp(\"^[A-Za-z][_A-Za-z0-9]*\");\n\n    var openingKeywords = ['class','sub','select','while','if','function', 'property', 'with', 'for'];\n    var middleKeywords = ['else','elseif','case'];\n    var endKeywords = ['next','loop','wend'];\n\n    var wordOperators = wordRegexp(['and', 'or', 'not', 'xor', 'is', 'mod', 'eqv', 'imp']);\n    var commonkeywords = ['dim', 'redim', 'then',  'until', 'randomize',\n                          'byval','byref','new','property', 'exit', 'in',\n                          'const','private', 'public',\n                          'get','set','let', 'stop', 'on error resume next', 'on error goto 0', 'option explicit', 'call', 'me'];\n\n    //This list was from: http://msdn.microsoft.com/en-us/library/f8tbc79x(v=vs.84).aspx\n    var atomWords = ['true', 'false', 'nothing', 'empty', 'null'];\n    //This list was from: http://msdn.microsoft.com/en-us/library/3ca8tfek(v=vs.84).aspx\n    var builtinFuncsWords = ['abs', 'array', 'asc', 'atn', 'cbool', 'cbyte', 'ccur', 'cdate', 'cdbl', 'chr', 'cint', 'clng', 'cos', 'csng', 'cstr', 'date', 'dateadd', 'datediff', 'datepart',\n                        'dateserial', 'datevalue', 'day', 'escape', 'eval', 'execute', 'exp', 'filter', 'formatcurrency', 'formatdatetime', 'formatnumber', 'formatpercent', 'getlocale', 'getobject',\n                        'getref', 'hex', 'hour', 'inputbox', 'instr', 'instrrev', 'int', 'fix', 'isarray', 'isdate', 'isempty', 'isnull', 'isnumeric', 'isobject', 'join', 'lbound', 'lcase', 'left',\n                        'len', 'loadpicture', 'log', 'ltrim', 'rtrim', 'trim', 'maths', 'mid', 'minute', 'month', 'monthname', 'msgbox', 'now', 'oct', 'replace', 'rgb', 'right', 'rnd', 'round',\n                        'scriptengine', 'scriptenginebuildversion', 'scriptenginemajorversion', 'scriptengineminorversion', 'second', 'setlocale', 'sgn', 'sin', 'space', 'split', 'sqr', 'strcomp',\n                        'string', 'strreverse', 'tan', 'time', 'timer', 'timeserial', 'timevalue', 'typename', 'ubound', 'ucase', 'unescape', 'vartype', 'weekday', 'weekdayname', 'year'];\n\n    //This list was from: http://msdn.microsoft.com/en-us/library/ydz4cfk3(v=vs.84).aspx\n    var builtinConsts = ['vbBlack', 'vbRed', 'vbGreen', 'vbYellow', 'vbBlue', 'vbMagenta', 'vbCyan', 'vbWhite', 'vbBinaryCompare', 'vbTextCompare',\n                         'vbSunday', 'vbMonday', 'vbTuesday', 'vbWednesday', 'vbThursday', 'vbFriday', 'vbSaturday', 'vbUseSystemDayOfWeek', 'vbFirstJan1', 'vbFirstFourDays', 'vbFirstFullWeek',\n                         'vbGeneralDate', 'vbLongDate', 'vbShortDate', 'vbLongTime', 'vbShortTime', 'vbObjectError',\n                         'vbOKOnly', 'vbOKCancel', 'vbAbortRetryIgnore', 'vbYesNoCancel', 'vbYesNo', 'vbRetryCancel', 'vbCritical', 'vbQuestion', 'vbExclamation', 'vbInformation', 'vbDefaultButton1', 'vbDefaultButton2',\n                         'vbDefaultButton3', 'vbDefaultButton4', 'vbApplicationModal', 'vbSystemModal', 'vbOK', 'vbCancel', 'vbAbort', 'vbRetry', 'vbIgnore', 'vbYes', 'vbNo',\n                         'vbCr', 'VbCrLf', 'vbFormFeed', 'vbLf', 'vbNewLine', 'vbNullChar', 'vbNullString', 'vbTab', 'vbVerticalTab', 'vbUseDefault', 'vbTrue', 'vbFalse',\n                         'vbEmpty', 'vbNull', 'vbInteger', 'vbLong', 'vbSingle', 'vbDouble', 'vbCurrency', 'vbDate', 'vbString', 'vbObject', 'vbError', 'vbBoolean', 'vbVariant', 'vbDataObject', 'vbDecimal', 'vbByte', 'vbArray'];\n    //This list was from: http://msdn.microsoft.com/en-us/library/hkc375ea(v=vs.84).aspx\n    var builtinObjsWords = ['WScript', 'err', 'debug', 'RegExp'];\n    var knownProperties = ['description', 'firstindex', 'global', 'helpcontext', 'helpfile', 'ignorecase', 'length', 'number', 'pattern', 'source', 'value', 'count'];\n    var knownMethods = ['clear', 'execute', 'raise', 'replace', 'test', 'write', 'writeline', 'close', 'open', 'state', 'eof', 'update', 'addnew', 'end', 'createobject', 'quit'];\n\n    var aspBuiltinObjsWords = ['server', 'response', 'request', 'session', 'application'];\n    var aspKnownProperties = ['buffer', 'cachecontrol', 'charset', 'contenttype', 'expires', 'expiresabsolute', 'isclientconnected', 'pics', 'status', //response\n                              'clientcertificate', 'cookies', 'form', 'querystring', 'servervariables', 'totalbytes', //request\n                              'contents', 'staticobjects', //application\n                              'codepage', 'lcid', 'sessionid', 'timeout', //session\n                              'scripttimeout']; //server\n    var aspKnownMethods = ['addheader', 'appendtolog', 'binarywrite', 'end', 'flush', 'redirect', //response\n                           'binaryread', //request\n                           'remove', 'removeall', 'lock', 'unlock', //application\n                           'abandon', //session\n                           'getlasterror', 'htmlencode', 'mappath', 'transfer', 'urlencode']; //server\n\n    var knownWords = knownMethods.concat(knownProperties);\n\n    builtinObjsWords = builtinObjsWords.concat(builtinConsts);\n\n    if (conf.isASP){\n        builtinObjsWords = builtinObjsWords.concat(aspBuiltinObjsWords);\n        knownWords = knownWords.concat(aspKnownMethods, aspKnownProperties);\n    };\n\n    var keywords = wordRegexp(commonkeywords);\n    var atoms = wordRegexp(atomWords);\n    var builtinFuncs = wordRegexp(builtinFuncsWords);\n    var builtinObjs = wordRegexp(builtinObjsWords);\n    var known = wordRegexp(knownWords);\n    var stringPrefixes = '\"';\n\n    var opening = wordRegexp(openingKeywords);\n    var middle = wordRegexp(middleKeywords);\n    var closing = wordRegexp(endKeywords);\n    var doubleClosing = wordRegexp(['end']);\n    var doOpening = wordRegexp(['do']);\n    var noIndentWords = wordRegexp(['on error resume next', 'exit']);\n    var comment = wordRegexp(['rem']);\n\n\n    function indent(_stream, state) {\n      state.currentIndent++;\n    }\n\n    function dedent(_stream, state) {\n      state.currentIndent--;\n    }\n    // tokenizers\n    function tokenBase(stream, state) {\n        if (stream.eatSpace()) {\n            return 'space';\n            //return null;\n        }\n\n        var ch = stream.peek();\n\n        // Handle Comments\n        if (ch === \"'\") {\n            stream.skipToEnd();\n            return 'comment';\n        }\n        if (stream.match(comment)){\n            stream.skipToEnd();\n            return 'comment';\n        }\n\n\n        // Handle Number Literals\n        if (stream.match(/^((&H)|(&O))?[0-9\\.]/i, false) && !stream.match(/^((&H)|(&O))?[0-9\\.]+[a-z_]/i, false)) {\n            var floatLiteral = false;\n            // Floats\n            if (stream.match(/^\\d*\\.\\d+/i)) { floatLiteral = true; }\n            else if (stream.match(/^\\d+\\.\\d*/)) { floatLiteral = true; }\n            else if (stream.match(/^\\.\\d+/)) { floatLiteral = true; }\n\n            if (floatLiteral) {\n                // Float literals may be \"imaginary\"\n                stream.eat(/J/i);\n                return 'number';\n            }\n            // Integers\n            var intLiteral = false;\n            // Hex\n            if (stream.match(/^&H[0-9a-f]+/i)) { intLiteral = true; }\n            // Octal\n            else if (stream.match(/^&O[0-7]+/i)) { intLiteral = true; }\n            // Decimal\n            else if (stream.match(/^[1-9]\\d*F?/)) {\n                // Decimal literals may be \"imaginary\"\n                stream.eat(/J/i);\n                // TODO - Can you have imaginary longs?\n                intLiteral = true;\n            }\n            // Zero by itself with no other piece of number.\n            else if (stream.match(/^0(?![\\dx])/i)) { intLiteral = true; }\n            if (intLiteral) {\n                // Integer literals may be \"long\"\n                stream.eat(/L/i);\n                return 'number';\n            }\n        }\n\n        // Handle Strings\n        if (stream.match(stringPrefixes)) {\n            state.tokenize = tokenStringFactory(stream.current());\n            return state.tokenize(stream, state);\n        }\n\n        // Handle operators and Delimiters\n        if (stream.match(doubleOperators)\n            || stream.match(singleOperators)\n            || stream.match(wordOperators)) {\n            return 'operator';\n        }\n        if (stream.match(singleDelimiters)) {\n            return null;\n        }\n\n        if (stream.match(brakets)) {\n            return \"bracket\";\n        }\n\n        if (stream.match(noIndentWords)) {\n            state.doInCurrentLine = true;\n\n            return 'keyword';\n        }\n\n        if (stream.match(doOpening)) {\n            indent(stream,state);\n            state.doInCurrentLine = true;\n\n            return 'keyword';\n        }\n        if (stream.match(opening)) {\n            if (! state.doInCurrentLine)\n              indent(stream,state);\n            else\n              state.doInCurrentLine = false;\n\n            return 'keyword';\n        }\n        if (stream.match(middle)) {\n            return 'keyword';\n        }\n\n\n        if (stream.match(doubleClosing)) {\n            dedent(stream,state);\n            dedent(stream,state);\n\n            return 'keyword';\n        }\n        if (stream.match(closing)) {\n            if (! state.doInCurrentLine)\n              dedent(stream,state);\n            else\n              state.doInCurrentLine = false;\n\n            return 'keyword';\n        }\n\n        if (stream.match(keywords)) {\n            return 'keyword';\n        }\n\n        if (stream.match(atoms)) {\n            return 'atom';\n        }\n\n        if (stream.match(known)) {\n            return 'variable-2';\n        }\n\n        if (stream.match(builtinFuncs)) {\n            return 'builtin';\n        }\n\n        if (stream.match(builtinObjs)){\n            return 'variable-2';\n        }\n\n        if (stream.match(identifiers)) {\n            return 'variable';\n        }\n\n        // Handle non-detected items\n        stream.next();\n        return ERRORCLASS;\n    }\n\n    function tokenStringFactory(delimiter) {\n        var singleline = delimiter.length == 1;\n        var OUTCLASS = 'string';\n\n        return function(stream, state) {\n            while (!stream.eol()) {\n                stream.eatWhile(/[^'\"]/);\n                if (stream.match(delimiter)) {\n                    state.tokenize = tokenBase;\n                    return OUTCLASS;\n                } else {\n                    stream.eat(/['\"]/);\n                }\n            }\n            if (singleline) {\n                if (parserConf.singleLineStringErrors) {\n                    return ERRORCLASS;\n                } else {\n                    state.tokenize = tokenBase;\n                }\n            }\n            return OUTCLASS;\n        };\n    }\n\n\n    function tokenLexer(stream, state) {\n        var style = state.tokenize(stream, state);\n        var current = stream.current();\n\n        // Handle '.' connected identifiers\n        if (current === '.') {\n            style = state.tokenize(stream, state);\n\n            current = stream.current();\n            if (style && (style.substr(0, 8) === 'variable' || style==='builtin' || style==='keyword')){//|| knownWords.indexOf(current.substring(1)) > -1) {\n                if (style === 'builtin' || style === 'keyword') style='variable';\n                if (knownWords.indexOf(current.substr(1)) > -1) style='variable-2';\n\n                return style;\n            } else {\n                return ERRORCLASS;\n            }\n        }\n\n        return style;\n    }\n\n    var external = {\n        electricChars:\"dDpPtTfFeE \",\n        startState: function() {\n            return {\n              tokenize: tokenBase,\n              lastToken: null,\n              currentIndent: 0,\n              nextLineIndent: 0,\n              doInCurrentLine: false,\n              ignoreKeyword: false\n\n\n          };\n        },\n\n        token: function(stream, state) {\n            if (stream.sol()) {\n              state.currentIndent += state.nextLineIndent;\n              state.nextLineIndent = 0;\n              state.doInCurrentLine = 0;\n            }\n            var style = tokenLexer(stream, state);\n\n            state.lastToken = {style:style, content: stream.current()};\n\n            if (style==='space') style=null;\n\n            return style;\n        },\n\n        indent: function(state, textAfter) {\n            var trueText = textAfter.replace(/^\\s+|\\s+$/g, '') ;\n            if (trueText.match(closing) || trueText.match(doubleClosing) || trueText.match(middle)) return conf.indentUnit*(state.currentIndent-1);\n            if(state.currentIndent < 0) return 0;\n            return state.currentIndent * conf.indentUnit;\n        }\n\n    };\n    return external;\n});\n\nCodeMirror.defineMIME(\"text/vbscript\", \"vbscript\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/velocity/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Velocity mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/night.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"velocity.js\"></script>\n<style>.CodeMirror {border: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Velocity</a>\n  </ul>\n</div>\n\n<article>\n<h2>Velocity mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n## Velocity Code Demo\n#*\n   based on PL/SQL mode by Peter Raganitsch, adapted to Velocity by Steve O'Hara ( http://www.pivotal-solutions.co.uk )\n   August 2011\n*#\n\n#*\n   This is a multiline comment.\n   This is the second line\n*#\n\n#[[ hello steve\n   This has invalid syntax that would normally need \"poor man's escaping\" like:\n\n   #define()\n\n   ${blah\n]]#\n\n#include( \"disclaimer.txt\" \"opinion.txt\" )\n#include( $foo $bar )\n\n#parse( \"lecorbusier.vm\" )\n#parse( $foo )\n\n#evaluate( 'string with VTL #if(true)will be displayed#end' )\n\n#define( $hello ) Hello $who #end #set( $who = \"World!\") $hello ## displays Hello World!\n\n#foreach( $customer in $customerList )\n\n    $foreach.count $customer.Name\n\n    #if( $foo == ${bar})\n        it's true!\n        #break\n    #{else}\n        it's not!\n        #stop\n    #end\n\n    #if ($foreach.parent.hasNext)\n        $velocityCount\n    #end\n#end\n\n$someObject.getValues(\"this is a string split\n        across lines\")\n\n$someObject(\"This plus $something in the middle\").method(7567).property\n\n#set($something = \"Parseable string with '$quotes'!\")\n\n#macro( tablerows $color $somelist )\n    #foreach( $something in $somelist )\n        <tr><td bgcolor=$color>$something</td></tr>\n        <tr><td bgcolor=$color>$bodyContent</td></tr>\n    #end\n#end\n\n#tablerows(\"red\" [\"dadsdf\",\"dsa\"])\n#@tablerows(\"red\" [\"dadsdf\",\"dsa\"]) some body content #end\n\n   Variable reference: #set( $monkey = $bill )\n   String literal: #set( $monkey.Friend = 'monica' )\n   Property reference: #set( $monkey.Blame = $whitehouse.Leak )\n   Method reference: #set( $monkey.Plan = $spindoctor.weave($web) )\n   Number literal: #set( $monkey.Number = 123 )\n   Range operator: #set( $monkey.Numbers = [1..3] )\n   Object list: #set( $monkey.Say = [\"Not\", $my, \"fault\"] )\n   Object map: #set( $monkey.Map = {\"banana\" : \"good\", \"roast beef\" : \"bad\"})\n\nThe RHS can also be a simple arithmetic expression, such as:\nAddition: #set( $value = $foo + 1 )\n   Subtraction: #set( $value = $bar - 1 )\n   Multiplication: #set( $value = $foo * $bar )\n   Division: #set( $value = $foo / $bar )\n   Remainder: #set( $value = $foo % $bar )\n\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        theme: \"night\",\n        lineNumbers: true,\n        indentUnit: 4,\n        mode: \"text/velocity\"\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/velocity</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/velocity/velocity.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"velocity\", function() {\n    function parseWords(str) {\n        var obj = {}, words = str.split(\" \");\n        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n        return obj;\n    }\n\n    var keywords = parseWords(\"#end #else #break #stop #[[ #]] \" +\n                              \"#{end} #{else} #{break} #{stop}\");\n    var functions = parseWords(\"#if #elseif #foreach #set #include #parse #macro #define #evaluate \" +\n                               \"#{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}\");\n    var specials = parseWords(\"$foreach.count $foreach.hasNext $foreach.first $foreach.last $foreach.topmost $foreach.parent.count $foreach.parent.hasNext $foreach.parent.first $foreach.parent.last $foreach.parent $velocityCount $!bodyContent $bodyContent\");\n    var isOperatorChar = /[+\\-*&%=<>!?:\\/|]/;\n\n    function chain(stream, state, f) {\n        state.tokenize = f;\n        return f(stream, state);\n    }\n    function tokenBase(stream, state) {\n        var beforeParams = state.beforeParams;\n        state.beforeParams = false;\n        var ch = stream.next();\n        // start of unparsed string?\n        if ((ch == \"'\") && !state.inString && state.inParams) {\n            state.lastTokenWasBuiltin = false;\n            return chain(stream, state, tokenString(ch));\n        }\n        // start of parsed string?\n        else if ((ch == '\"')) {\n            state.lastTokenWasBuiltin = false;\n            if (state.inString) {\n                state.inString = false;\n                return \"string\";\n            }\n            else if (state.inParams)\n                return chain(stream, state, tokenString(ch));\n        }\n        // is it one of the special signs []{}().,;? Seperator?\n        else if (/[\\[\\]{}\\(\\),;\\.]/.test(ch)) {\n            if (ch == \"(\" && beforeParams)\n                state.inParams = true;\n            else if (ch == \")\") {\n                state.inParams = false;\n                state.lastTokenWasBuiltin = true;\n            }\n            return null;\n        }\n        // start of a number value?\n        else if (/\\d/.test(ch)) {\n            state.lastTokenWasBuiltin = false;\n            stream.eatWhile(/[\\w\\.]/);\n            return \"number\";\n        }\n        // multi line comment?\n        else if (ch == \"#\" && stream.eat(\"*\")) {\n            state.lastTokenWasBuiltin = false;\n            return chain(stream, state, tokenComment);\n        }\n        // unparsed content?\n        else if (ch == \"#\" && stream.match(/ *\\[ *\\[/)) {\n            state.lastTokenWasBuiltin = false;\n            return chain(stream, state, tokenUnparsed);\n        }\n        // single line comment?\n        else if (ch == \"#\" && stream.eat(\"#\")) {\n            state.lastTokenWasBuiltin = false;\n            stream.skipToEnd();\n            return \"comment\";\n        }\n        // variable?\n        else if (ch == \"$\") {\n            stream.eatWhile(/[\\w\\d\\$_\\.{}-]/);\n            // is it one of the specials?\n            if (specials && specials.propertyIsEnumerable(stream.current())) {\n                return \"keyword\";\n            }\n            else {\n                state.lastTokenWasBuiltin = true;\n                state.beforeParams = true;\n                return \"builtin\";\n            }\n        }\n        // is it a operator?\n        else if (isOperatorChar.test(ch)) {\n            state.lastTokenWasBuiltin = false;\n            stream.eatWhile(isOperatorChar);\n            return \"operator\";\n        }\n        else {\n            // get the whole word\n            stream.eatWhile(/[\\w\\$_{}@]/);\n            var word = stream.current();\n            // is it one of the listed keywords?\n            if (keywords && keywords.propertyIsEnumerable(word))\n                return \"keyword\";\n            // is it one of the listed functions?\n            if (functions && functions.propertyIsEnumerable(word) ||\n                    (stream.current().match(/^#@?[a-z0-9_]+ *$/i) && stream.peek()==\"(\") &&\n                     !(functions && functions.propertyIsEnumerable(word.toLowerCase()))) {\n                state.beforeParams = true;\n                state.lastTokenWasBuiltin = false;\n                return \"keyword\";\n            }\n            if (state.inString) {\n                state.lastTokenWasBuiltin = false;\n                return \"string\";\n            }\n            if (stream.pos > word.length && stream.string.charAt(stream.pos-word.length-1)==\".\" && state.lastTokenWasBuiltin)\n                return \"builtin\";\n            // default: just a \"word\"\n            state.lastTokenWasBuiltin = false;\n            return null;\n        }\n    }\n\n    function tokenString(quote) {\n        return function(stream, state) {\n            var escaped = false, next, end = false;\n            while ((next = stream.next()) != null) {\n                if ((next == quote) && !escaped) {\n                    end = true;\n                    break;\n                }\n                if (quote=='\"' && stream.peek() == '$' && !escaped) {\n                    state.inString = true;\n                    end = true;\n                    break;\n                }\n                escaped = !escaped && next == \"\\\\\";\n            }\n            if (end) state.tokenize = tokenBase;\n            return \"string\";\n        };\n    }\n\n    function tokenComment(stream, state) {\n        var maybeEnd = false, ch;\n        while (ch = stream.next()) {\n            if (ch == \"#\" && maybeEnd) {\n                state.tokenize = tokenBase;\n                break;\n            }\n            maybeEnd = (ch == \"*\");\n        }\n        return \"comment\";\n    }\n\n    function tokenUnparsed(stream, state) {\n        var maybeEnd = 0, ch;\n        while (ch = stream.next()) {\n            if (ch == \"#\" && maybeEnd == 2) {\n                state.tokenize = tokenBase;\n                break;\n            }\n            if (ch == \"]\")\n                maybeEnd++;\n            else if (ch != \" \")\n                maybeEnd = 0;\n        }\n        return \"meta\";\n    }\n    // Interface\n\n    return {\n        startState: function() {\n            return {\n                tokenize: tokenBase,\n                beforeParams: false,\n                inParams: false,\n                inString: false,\n                lastTokenWasBuiltin: false\n            };\n        },\n\n        token: function(stream, state) {\n            if (stream.eatSpace()) return null;\n            return state.tokenize(stream, state);\n        },\n        blockCommentStart: \"#*\",\n        blockCommentEnd: \"*#\",\n        lineComment: \"##\",\n        fold: \"velocity\"\n    };\n});\n\nCodeMirror.defineMIME(\"text/velocity\", \"velocity\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/verilog/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Verilog/SystemVerilog mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"verilog.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Verilog/SystemVerilog</a>\n  </ul>\n</div>\n\n<article>\n<h2>SystemVerilog mode</h2>\n\n<div><textarea id=\"code\" name=\"code\">\n// Literals\n1'b0\n1'bx\n1'bz\n16'hDC78\n'hdeadbeef\n'b0011xxzz\n1234\n32'd5678\n3.4e6\n-128.7\n\n// Macro definition\n`define BUS_WIDTH = 8;\n\n// Module definition\nmodule block(\n  input                   clk,\n  input                   rst_n,\n  input  [`BUS_WIDTH-1:0] data_in,\n  output [`BUS_WIDTH-1:0] data_out\n);\n  \n  always @(posedge clk or negedge rst_n) begin\n\n    if (~rst_n) begin\n      data_out <= 8'b0;\n    end else begin\n      data_out <= data_in;\n    end\n    \n    if (~rst_n)\n      data_out <= 8'b0;\n    else\n      data_out <= data_in;\n    \n    if (~rst_n)\n      begin\n        data_out <= 8'b0;\n      end\n    else\n      begin\n        data_out <= data_in;\n      end\n\n  end\n  \nendmodule\n\n// Class definition\nclass test;\n\n  /**\n   * Sum two integers\n   */\n  function int sum(int a, int b);\n    int result = a + b;\n    string msg = $sformatf(\"%d + %d = %d\", a, b, result);\n    $display(msg);\n    return result;\n  endfunction\n  \n  task delay(int num_cycles);\n    repeat(num_cycles) #1;\n  endtask\n  \nendclass\n\n</textarea></div>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    matchBrackets: true,\n    mode: {\n      name: \"verilog\",\n      noIndentKeywords: [\"package\"]\n    }\n  });\n</script>\n\n<p>\nSyntax highlighting and indentation for the Verilog and SystemVerilog languages (IEEE 1800).\n<h2>Configuration options:</h2>\n  <ul>\n    <li><strong>noIndentKeywords</strong> - List of keywords which should not cause indentation to increase. E.g. [\"package\", \"module\"]. Default: None</li>\n  </ul>\n</p>\n\n<p><strong>MIME types defined:</strong> <code>text/x-verilog</code> and <code>text/x-systemverilog</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/verilog/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 4}, \"verilog\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"binary_literals\",\n     \"[number 1'b0]\",\n     \"[number 1'b1]\",\n     \"[number 1'bx]\",\n     \"[number 1'bz]\",\n     \"[number 1'bX]\",\n     \"[number 1'bZ]\",\n     \"[number 1'B0]\",\n     \"[number 1'B1]\",\n     \"[number 1'Bx]\",\n     \"[number 1'Bz]\",\n     \"[number 1'BX]\",\n     \"[number 1'BZ]\",\n     \"[number 1'b0]\",\n     \"[number 1'b1]\",\n     \"[number 2'b01]\",\n     \"[number 2'bxz]\",\n     \"[number 2'b11]\",\n     \"[number 2'b10]\",\n     \"[number 2'b1Z]\",\n     \"[number 12'b0101_0101_0101]\",\n     \"[number 1'b 0]\",\n     \"[number 'b0101]\"\n  );\n\n  MT(\"octal_literals\",\n     \"[number 3'o7]\",\n     \"[number 3'O7]\",\n     \"[number 3'so7]\",\n     \"[number 3'SO7]\"\n  );\n\n  MT(\"decimal_literals\",\n     \"[number 0]\",\n     \"[number 1]\",\n     \"[number 7]\",\n     \"[number 123_456]\",\n     \"[number 'd33]\",\n     \"[number 8'd255]\",\n     \"[number 8'D255]\",\n     \"[number 8'sd255]\",\n     \"[number 8'SD255]\",\n     \"[number 32'd123]\",\n     \"[number 32 'd123]\",\n     \"[number 32 'd 123]\"\n  );\n\n  MT(\"hex_literals\",\n     \"[number 4'h0]\",\n     \"[number 4'ha]\",\n     \"[number 4'hF]\",\n     \"[number 4'hx]\",\n     \"[number 4'hz]\",\n     \"[number 4'hX]\",\n     \"[number 4'hZ]\",\n     \"[number 32'hdc78]\",\n     \"[number 32'hDC78]\",\n     \"[number 32 'hDC78]\",\n     \"[number 32'h DC78]\",\n     \"[number 32 'h DC78]\",\n     \"[number 32'h44x7]\",\n     \"[number 32'hFFF?]\"\n  );\n\n  MT(\"real_number_literals\",\n     \"[number 1.2]\",\n     \"[number 0.1]\",\n     \"[number 2394.26331]\",\n     \"[number 1.2E12]\",\n     \"[number 1.2e12]\",\n     \"[number 1.30e-2]\",\n     \"[number 0.1e-0]\",\n     \"[number 23E10]\",\n     \"[number 29E-2]\",\n     \"[number 236.123_763_e-12]\"\n  );\n\n  MT(\"operators\",\n     \"[meta ^]\"\n  );\n\n  MT(\"keywords\",\n     \"[keyword logic]\",\n     \"[keyword logic] [variable foo]\",\n     \"[keyword reg] [variable abc]\"\n  );\n\n  MT(\"variables\",\n     \"[variable _leading_underscore]\",\n     \"[variable _if]\",\n     \"[number 12] [variable foo]\",\n     \"[variable foo] [number 14]\"\n  );\n\n  MT(\"tick_defines\",\n     \"[def `FOO]\",\n     \"[def `foo]\",\n     \"[def `FOO_bar]\"\n  );\n\n  MT(\"system_calls\",\n     \"[meta $display]\",\n     \"[meta $vpi_printf]\"\n  );\n\n  MT(\"line_comment\", \"[comment // Hello world]\");\n\n  // Alignment tests\n  MT(\"align_port_map_style1\",\n     /**\n      * mod mod(.a(a),\n      *         .b(b)\n      *        );\n      */\n     \"[variable mod] [variable mod][bracket (].[variable a][bracket (][variable a][bracket )],\",\n     \"        .[variable b][bracket (][variable b][bracket )]\",\n     \"       [bracket )];\",\n     \"\"\n  );\n\n  MT(\"align_port_map_style2\",\n     /**\n      * mod mod(\n      *     .a(a),\n      *     .b(b)\n      * );\n      */\n     \"[variable mod] [variable mod][bracket (]\",\n     \"    .[variable a][bracket (][variable a][bracket )],\",\n     \"    .[variable b][bracket (][variable b][bracket )]\",\n     \"[bracket )];\",\n     \"\"\n  );\n\n  // Indentation tests\n  MT(\"indent_single_statement_if\",\n      \"[keyword if] [bracket (][variable foo][bracket )]\",\n      \"    [keyword break];\",\n      \"\"\n  );\n\n  MT(\"no_indent_after_single_line_if\",\n      \"[keyword if] [bracket (][variable foo][bracket )] [keyword break];\",\n      \"\"\n  );\n\n  MT(\"indent_after_if_begin_same_line\",\n      \"[keyword if] [bracket (][variable foo][bracket )] [keyword begin]\",\n      \"    [keyword break];\",\n      \"    [keyword break];\",\n      \"[keyword end]\",\n      \"\"\n  );\n\n  MT(\"indent_after_if_begin_next_line\",\n      \"[keyword if] [bracket (][variable foo][bracket )]\",\n      \"    [keyword begin]\",\n      \"        [keyword break];\",\n      \"        [keyword break];\",\n      \"    [keyword end]\",\n      \"\"\n  );\n\n  MT(\"indent_single_statement_if_else\",\n      \"[keyword if] [bracket (][variable foo][bracket )]\",\n      \"    [keyword break];\",\n      \"[keyword else]\",\n      \"    [keyword break];\",\n      \"\"\n  );\n\n  MT(\"indent_if_else_begin_same_line\",\n      \"[keyword if] [bracket (][variable foo][bracket )] [keyword begin]\",\n      \"    [keyword break];\",\n      \"    [keyword break];\",\n      \"[keyword end] [keyword else] [keyword begin]\",\n      \"    [keyword break];\",\n      \"    [keyword break];\",\n      \"[keyword end]\",\n      \"\"\n  );\n\n  MT(\"indent_if_else_begin_next_line\",\n      \"[keyword if] [bracket (][variable foo][bracket )]\",\n      \"    [keyword begin]\",\n      \"        [keyword break];\",\n      \"        [keyword break];\",\n      \"    [keyword end]\",\n      \"[keyword else]\",\n      \"    [keyword begin]\",\n      \"        [keyword break];\",\n      \"        [keyword break];\",\n      \"    [keyword end]\",\n      \"\"\n  );\n\n  MT(\"indent_if_nested_without_begin\",\n      \"[keyword if] [bracket (][variable foo][bracket )]\",\n      \"    [keyword if] [bracket (][variable foo][bracket )]\",\n      \"        [keyword if] [bracket (][variable foo][bracket )]\",\n      \"            [keyword break];\",\n      \"\"\n  );\n\n  MT(\"indent_case\",\n      \"[keyword case] [bracket (][variable state][bracket )]\",\n      \"    [variable FOO]:\",\n      \"        [keyword break];\",\n      \"    [variable BAR]:\",\n      \"        [keyword break];\",\n      \"[keyword endcase]\",\n      \"\"\n  );\n\n  MT(\"unindent_after_end_with_preceding_text\",\n      \"[keyword begin]\",\n      \"    [keyword break]; [keyword end]\",\n      \"\"\n  );\n\n  MT(\"export_function_one_line_does_not_indent\",\n     \"[keyword export] [string \\\"DPI-C\\\"] [keyword function] [variable helloFromSV];\",\n     \"\"\n  );\n\n  MT(\"export_task_one_line_does_not_indent\",\n     \"[keyword export] [string \\\"DPI-C\\\"] [keyword task] [variable helloFromSV];\",\n     \"\"\n  );\n\n  MT(\"export_function_two_lines_indents_properly\",\n    \"[keyword export]\",\n    \"    [string \\\"DPI-C\\\"] [keyword function] [variable helloFromSV];\",\n    \"\"\n  );\n\n  MT(\"export_task_two_lines_indents_properly\",\n    \"[keyword export]\",\n    \"    [string \\\"DPI-C\\\"] [keyword task] [variable helloFromSV];\",\n    \"\"\n  );\n\n  MT(\"import_function_one_line_does_not_indent\",\n    \"[keyword import] [string \\\"DPI-C\\\"] [keyword function] [variable helloFromC];\",\n    \"\"\n  );\n\n  MT(\"import_task_one_line_does_not_indent\",\n    \"[keyword import] [string \\\"DPI-C\\\"] [keyword task] [variable helloFromC];\",\n    \"\"\n  );\n\n  MT(\"import_package_single_line_does_not_indent\",\n    \"[keyword import] [variable p]::[variable x];\",\n    \"[keyword import] [variable p]::[variable y];\",\n    \"\"\n  );\n\n  MT(\"covergroup_with_function_indents_properly\",\n    \"[keyword covergroup] [variable cg] [keyword with] [keyword function] [variable sample][bracket (][keyword bit] [variable b][bracket )];\",\n    \"    [variable c] : [keyword coverpoint] [variable c];\",\n    \"[keyword endgroup]: [variable cg]\",\n    \"\"\n  );\n\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/verilog/verilog.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"verilog\", function(config, parserConfig) {\n\n  var indentUnit = config.indentUnit,\n      statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,\n      dontAlignCalls = parserConfig.dontAlignCalls,\n      noIndentKeywords = parserConfig.noIndentKeywords || [],\n      multiLineStrings = parserConfig.multiLineStrings,\n      hooks = parserConfig.hooks || {};\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  /**\n   * Keywords from IEEE 1800-2012\n   */\n  var keywords = words(\n    \"accept_on alias always always_comb always_ff always_latch and assert assign assume automatic before begin bind \" +\n    \"bins binsof bit break buf bufif0 bufif1 byte case casex casez cell chandle checker class clocking cmos config \" +\n    \"const constraint context continue cover covergroup coverpoint cross deassign default defparam design disable \" +\n    \"dist do edge else end endcase endchecker endclass endclocking endconfig endfunction endgenerate endgroup \" +\n    \"endinterface endmodule endpackage endprimitive endprogram endproperty endspecify endsequence endtable endtask \" +\n    \"enum event eventually expect export extends extern final first_match for force foreach forever fork forkjoin \" +\n    \"function generate genvar global highz0 highz1 if iff ifnone ignore_bins illegal_bins implements implies import \" +\n    \"incdir include initial inout input inside instance int integer interconnect interface intersect join join_any \" +\n    \"join_none large let liblist library local localparam logic longint macromodule matches medium modport module \" +\n    \"nand negedge nettype new nexttime nmos nor noshowcancelled not notif0 notif1 null or output package packed \" +\n    \"parameter pmos posedge primitive priority program property protected pull0 pull1 pulldown pullup \" +\n    \"pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos real realtime ref reg \" +\n    \"reject_on release repeat restrict return rnmos rpmos rtran rtranif0 rtranif1 s_always s_eventually s_nexttime \" +\n    \"s_until s_until_with scalared sequence shortint shortreal showcancelled signed small soft solve specify \" +\n    \"specparam static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on sync_reject_on \" +\n    \"table tagged task this throughout time timeprecision timeunit tran tranif0 tranif1 tri tri0 tri1 triand trior \" +\n    \"trireg type typedef union unique unique0 unsigned until until_with untyped use uwire var vectored virtual void \" +\n    \"wait wait_order wand weak weak0 weak1 while wildcard wire with within wor xnor xor\");\n\n  /** Operators from IEEE 1800-2012\n     unary_operator ::=\n       + | - | ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~\n     binary_operator ::=\n       + | - | * | / | % | == | != | === | !== | ==? | !=? | && | || | **\n       | < | <= | > | >= | & | | | ^ | ^~ | ~^ | >> | << | >>> | <<<\n       | -> | <->\n     inc_or_dec_operator ::= ++ | --\n     unary_module_path_operator ::=\n       ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~\n     binary_module_path_operator ::=\n       == | != | && | || | & | | | ^ | ^~ | ~^\n  */\n  var isOperatorChar = /[\\+\\-\\*\\/!~&|^%=?:]/;\n  var isBracketChar = /[\\[\\]{}()]/;\n\n  var unsignedNumber = /\\d[0-9_]*/;\n  var decimalLiteral = /\\d*\\s*'s?d\\s*\\d[0-9_]*/i;\n  var binaryLiteral = /\\d*\\s*'s?b\\s*[xz01][xz01_]*/i;\n  var octLiteral = /\\d*\\s*'s?o\\s*[xz0-7][xz0-7_]*/i;\n  var hexLiteral = /\\d*\\s*'s?h\\s*[0-9a-fxz?][0-9a-fxz?_]*/i;\n  var realLiteral = /(\\d[\\d_]*(\\.\\d[\\d_]*)?E-?[\\d_]+)|(\\d[\\d_]*\\.\\d[\\d_]*)/i;\n\n  var closingBracketOrWord = /^((\\w+)|[)}\\]])/;\n  var closingBracket = /[)}\\]]/;\n\n  var curPunc;\n  var curKeyword;\n\n  // Block openings which are closed by a matching keyword in the form of (\"end\" + keyword)\n  // E.g. \"task\" => \"endtask\"\n  var blockKeywords = words(\n    \"case checker class clocking config function generate interface module package \" +\n    \"primitive program property specify sequence table task\"\n  );\n\n  // Opening/closing pairs\n  var openClose = {};\n  for (var keyword in blockKeywords) {\n    openClose[keyword] = \"end\" + keyword;\n  }\n  openClose[\"begin\"] = \"end\";\n  openClose[\"casex\"] = \"endcase\";\n  openClose[\"casez\"] = \"endcase\";\n  openClose[\"do\"   ] = \"while\";\n  openClose[\"fork\" ] = \"join;join_any;join_none\";\n  openClose[\"covergroup\"] = \"endgroup\";\n\n  for (var i in noIndentKeywords) {\n    var keyword = noIndentKeywords[i];\n    if (openClose[keyword]) {\n      openClose[keyword] = undefined;\n    }\n  }\n\n  // Keywords which open statements that are ended with a semi-colon\n  var statementKeywords = words(\"always always_comb always_ff always_latch assert assign assume else export for foreach forever if import initial repeat while\");\n\n  function tokenBase(stream, state) {\n    var ch = stream.peek(), style;\n    if (hooks[ch] && (style = hooks[ch](stream, state)) != false) return style;\n    if (hooks.tokenBase && (style = hooks.tokenBase(stream, state)) != false)\n      return style;\n\n    if (/[,;:\\.]/.test(ch)) {\n      curPunc = stream.next();\n      return null;\n    }\n    if (isBracketChar.test(ch)) {\n      curPunc = stream.next();\n      return \"bracket\";\n    }\n    // Macros (tick-defines)\n    if (ch == '`') {\n      stream.next();\n      if (stream.eatWhile(/[\\w\\$_]/)) {\n        return \"def\";\n      } else {\n        return null;\n      }\n    }\n    // System calls\n    if (ch == '$') {\n      stream.next();\n      if (stream.eatWhile(/[\\w\\$_]/)) {\n        return \"meta\";\n      } else {\n        return null;\n      }\n    }\n    // Time literals\n    if (ch == '#') {\n      stream.next();\n      stream.eatWhile(/[\\d_.]/);\n      return \"def\";\n    }\n    // Strings\n    if (ch == '\"') {\n      stream.next();\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n    // Comments\n    if (ch == \"/\") {\n      stream.next();\n      if (stream.eat(\"*\")) {\n        state.tokenize = tokenComment;\n        return tokenComment(stream, state);\n      }\n      if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n      stream.backUp(1);\n    }\n\n    // Numeric literals\n    if (stream.match(realLiteral) ||\n        stream.match(decimalLiteral) ||\n        stream.match(binaryLiteral) ||\n        stream.match(octLiteral) ||\n        stream.match(hexLiteral) ||\n        stream.match(unsignedNumber) ||\n        stream.match(realLiteral)) {\n      return \"number\";\n    }\n\n    // Operators\n    if (stream.eatWhile(isOperatorChar)) {\n      return \"meta\";\n    }\n\n    // Keywords / plain variables\n    if (stream.eatWhile(/[\\w\\$_]/)) {\n      var cur = stream.current();\n      if (keywords[cur]) {\n        if (openClose[cur]) {\n          curPunc = \"newblock\";\n        }\n        if (statementKeywords[cur]) {\n          curPunc = \"newstatement\";\n        }\n        curKeyword = cur;\n        return \"keyword\";\n      }\n      return \"variable\";\n    }\n\n    stream.next();\n    return null;\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {end = true; break;}\n        escaped = !escaped && next == \"\\\\\";\n      }\n      if (end || !(escaped || multiLineStrings))\n        state.tokenize = tokenBase;\n      return \"string\";\n    };\n  }\n\n  function tokenComment(stream, state) {\n    var maybeEnd = false, ch;\n    while (ch = stream.next()) {\n      if (ch == \"/\" && maybeEnd) {\n        state.tokenize = tokenBase;\n        break;\n      }\n      maybeEnd = (ch == \"*\");\n    }\n    return \"comment\";\n  }\n\n  function Context(indented, column, type, align, prev) {\n    this.indented = indented;\n    this.column = column;\n    this.type = type;\n    this.align = align;\n    this.prev = prev;\n  }\n  function pushContext(state, col, type) {\n    var indent = state.indented;\n    var c = new Context(indent, col, type, null, state.context);\n    return state.context = c;\n  }\n  function popContext(state) {\n    var t = state.context.type;\n    if (t == \")\" || t == \"]\" || t == \"}\") {\n      state.indented = state.context.indented;\n    }\n    return state.context = state.context.prev;\n  }\n\n  function isClosing(text, contextClosing) {\n    if (text == contextClosing) {\n      return true;\n    } else {\n      // contextClosing may be multiple keywords separated by ;\n      var closingKeywords = contextClosing.split(\";\");\n      for (var i in closingKeywords) {\n        if (text == closingKeywords[i]) {\n          return true;\n        }\n      }\n      return false;\n    }\n  }\n\n  function buildElectricInputRegEx() {\n    // Reindentation should occur on any bracket char: {}()[]\n    // or on a match of any of the block closing keywords, at\n    // the end of a line\n    var allClosings = [];\n    for (var i in openClose) {\n      if (openClose[i]) {\n        var closings = openClose[i].split(\";\");\n        for (var j in closings) {\n          allClosings.push(closings[j]);\n        }\n      }\n    }\n    var re = new RegExp(\"[{}()\\\\[\\\\]]|(\" + allClosings.join(\"|\") + \")$\");\n    return re;\n  }\n\n  // Interface\n  return {\n\n    // Regex to force current line to reindent\n    electricInput: buildElectricInputRegEx(),\n\n    startState: function(basecolumn) {\n      var state = {\n        tokenize: null,\n        context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", false),\n        indented: 0,\n        startOfLine: true\n      };\n      if (hooks.startState) hooks.startState(state);\n      return state;\n    },\n\n    token: function(stream, state) {\n      var ctx = state.context;\n      if (stream.sol()) {\n        if (ctx.align == null) ctx.align = false;\n        state.indented = stream.indentation();\n        state.startOfLine = true;\n      }\n      if (hooks.token) {\n        // Call hook, with an optional return value of a style to override verilog styling.\n        var style = hooks.token(stream, state);\n        if (style !== undefined) {\n          return style;\n        }\n      }\n      if (stream.eatSpace()) return null;\n      curPunc = null;\n      curKeyword = null;\n      var style = (state.tokenize || tokenBase)(stream, state);\n      if (style == \"comment\" || style == \"meta\" || style == \"variable\") return style;\n      if (ctx.align == null) ctx.align = true;\n\n      if (curPunc == ctx.type) {\n        popContext(state);\n      } else if ((curPunc == \";\" && ctx.type == \"statement\") ||\n               (ctx.type && isClosing(curKeyword, ctx.type))) {\n        ctx = popContext(state);\n        while (ctx && ctx.type == \"statement\") ctx = popContext(state);\n      } else if (curPunc == \"{\") {\n        pushContext(state, stream.column(), \"}\");\n      } else if (curPunc == \"[\") {\n        pushContext(state, stream.column(), \"]\");\n      } else if (curPunc == \"(\") {\n        pushContext(state, stream.column(), \")\");\n      } else if (ctx && ctx.type == \"endcase\" && curPunc == \":\") {\n        pushContext(state, stream.column(), \"statement\");\n      } else if (curPunc == \"newstatement\") {\n        pushContext(state, stream.column(), \"statement\");\n      } else if (curPunc == \"newblock\") {\n        if (curKeyword == \"function\" && ctx && (ctx.type == \"statement\" || ctx.type == \"endgroup\")) {\n          // The 'function' keyword can appear in some other contexts where it actually does not\n          // indicate a function (import/export DPI and covergroup definitions).\n          // Do nothing in this case\n        } else if (curKeyword == \"task\" && ctx && ctx.type == \"statement\") {\n          // Same thing for task\n        } else {\n          var close = openClose[curKeyword];\n          pushContext(state, stream.column(), close);\n        }\n      }\n\n      state.startOfLine = false;\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;\n      if (hooks.indent) {\n        var fromHook = hooks.indent(state);\n        if (fromHook >= 0) return fromHook;\n      }\n      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);\n      if (ctx.type == \"statement\" && firstChar == \"}\") ctx = ctx.prev;\n      var closing = false;\n      var possibleClosing = textAfter.match(closingBracketOrWord);\n      if (possibleClosing)\n        closing = isClosing(possibleClosing[0], ctx.type);\n      if (ctx.type == \"statement\") return ctx.indented + (firstChar == \"{\" ? 0 : statementIndentUnit);\n      else if (closingBracket.test(ctx.type) && ctx.align && !dontAlignCalls) return ctx.column + (closing ? 0 : 1);\n      else if (ctx.type == \")\" && !closing) return ctx.indented + statementIndentUnit;\n      else return ctx.indented + (closing ? 0 : indentUnit);\n    },\n\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    lineComment: \"//\"\n  };\n});\n\n  CodeMirror.defineMIME(\"text/x-verilog\", {\n    name: \"verilog\"\n  });\n\n  CodeMirror.defineMIME(\"text/x-systemverilog\", {\n    name: \"verilog\"\n  });\n\n\n\n  // TL-Verilog mode.\n  // See tl-x.org for language spec.\n  // See the mode in action at makerchip.com.\n  // Contact: steve.hoover@redwoodeda.com\n\n  // TLV Identifier prefixes.\n  // Note that sign is not treated separately, so \"+/-\" versions of numeric identifiers\n  // are included.\n  var tlvIdentifierStyle = {\n    \"|\": \"link\",\n    \">\": \"property\",  // Should condition this off for > TLV 1c.\n    \"$\": \"variable\",\n    \"$$\": \"variable\",\n    \"?$\": \"qualifier\",\n    \"?*\": \"qualifier\",\n    \"-\": \"hr\",\n    \"/\": \"property\",\n    \"/-\": \"property\",\n    \"@\": \"variable-3\",\n    \"@-\": \"variable-3\",\n    \"@++\": \"variable-3\",\n    \"@+=\": \"variable-3\",\n    \"@+=-\": \"variable-3\",\n    \"@--\": \"variable-3\",\n    \"@-=\": \"variable-3\",\n    \"%+\": \"tag\",\n    \"%-\": \"tag\",\n    \"%\": \"tag\",\n    \">>\": \"tag\",\n    \"<<\": \"tag\",\n    \"<>\": \"tag\",\n    \"#\": \"tag\",  // Need to choose a style for this.\n    \"^\": \"attribute\",\n    \"^^\": \"attribute\",\n    \"^!\": \"attribute\",\n    \"*\": \"variable-2\",\n    \"**\": \"variable-2\",\n    \"\\\\\": \"keyword\",\n    \"\\\"\": \"comment\"\n  };\n\n  // Lines starting with these characters define scope (result in indentation).\n  var tlvScopePrefixChars = {\n    \"/\": \"beh-hier\",\n    \">\": \"beh-hier\",\n    \"-\": \"phys-hier\",\n    \"|\": \"pipe\",\n    \"?\": \"when\",\n    \"@\": \"stage\",\n    \"\\\\\": \"keyword\"\n  };\n  var tlvIndentUnit = 3;\n  var tlvTrackStatements = false;\n  var tlvIdentMatch = /^([~!@#\\$%\\^&\\*-\\+=\\?\\/\\\\\\|'\"<>]+)([\\d\\w_]*)/;  // Matches an identifiere.\n  // Note that ':' is excluded, because of it's use in [:].\n  var tlvFirstLevelIndentMatch = /^[! ]  /;\n  var tlvLineIndentationMatch = /^[! ] */;\n  var tlvCommentMatch = /^\\/[\\/\\*]/;\n\n\n  // Returns a style specific to the scope at the given indentation column.\n  // Type is one of: \"indent\", \"scope-ident\", \"before-scope-ident\".\n  function tlvScopeStyle(state, indentation, type) {\n    // Begin scope.\n    var depth = indentation / tlvIndentUnit;  // TODO: Pass this in instead.\n    return \"tlv-\" + state.tlvIndentationStyle[depth] + \"-\" + type;\n  }\n\n  // Return true if the next thing in the stream is an identifier with a mnemonic.\n  function tlvIdentNext(stream) {\n    var match;\n    return (match = stream.match(tlvIdentMatch, false)) && match[2].length > 0;\n  }\n\n  CodeMirror.defineMIME(\"text/x-tlv\", {\n    name: \"verilog\",\n\n    hooks: {\n\n      electricInput: false,\n\n\n      // Return undefined for verilog tokenizing, or style for TLV token (null not used).\n      // Standard CM styles are used for most formatting, but some TL-Verilog-specific highlighting\n      // can be enabled with the definition of cm-tlv-* styles, including highlighting for:\n      //   - M4 tokens\n      //   - TLV scope indentation\n      //   - Statement delimitation (enabled by tlvTrackStatements)\n      token: function(stream, state) {\n        var style = undefined;\n        var match;  // Return value of pattern matches.\n\n        // Set highlighting mode based on code region (TLV or SV).\n        if (stream.sol() && ! state.tlvInBlockComment) {\n          // Process region.\n          if (stream.peek() == '\\\\') {\n            style = \"def\";\n            stream.skipToEnd();\n            if (stream.string.match(/\\\\SV/)) {\n              state.tlvCodeActive = false;\n            } else if (stream.string.match(/\\\\TLV/)){\n              state.tlvCodeActive = true;\n            }\n          }\n          // Correct indentation in the face of a line prefix char.\n          if (state.tlvCodeActive && stream.pos == 0 &&\n              (state.indented == 0) && (match = stream.match(tlvLineIndentationMatch, false))) {\n            state.indented = match[0].length;\n          }\n\n          // Compute indentation state:\n          //   o Auto indentation on next line\n          //   o Indentation scope styles\n          var indented = state.indented;\n          var depth = indented / tlvIndentUnit;\n          if (depth <= state.tlvIndentationStyle.length) {\n            // not deeper than current scope\n\n            var blankline = stream.string.length == indented;\n            var chPos = depth * tlvIndentUnit;\n            if (chPos < stream.string.length) {\n              var bodyString = stream.string.slice(chPos);\n              var ch = bodyString[0];\n              if (tlvScopePrefixChars[ch] && ((match = bodyString.match(tlvIdentMatch)) &&\n                  tlvIdentifierStyle[match[1]])) {\n                // This line begins scope.\n                // Next line gets indented one level.\n                indented += tlvIndentUnit;\n                // Style the next level of indentation (except non-region keyword identifiers,\n                //   which are statements themselves)\n                if (!(ch == \"\\\\\" && chPos > 0)) {\n                  state.tlvIndentationStyle[depth] = tlvScopePrefixChars[ch];\n                  if (tlvTrackStatements) {state.statementComment = false;}\n                  depth++;\n                }\n              }\n            }\n            // Clear out deeper indentation levels unless line is blank.\n            if (!blankline) {\n              while (state.tlvIndentationStyle.length > depth) {\n                state.tlvIndentationStyle.pop();\n              }\n            }\n          }\n          // Set next level of indentation.\n          state.tlvNextIndent = indented;\n        }\n\n        if (state.tlvCodeActive) {\n          // Highlight as TLV.\n\n          var beginStatement = false;\n          if (tlvTrackStatements) {\n            // This starts a statement if the position is at the scope level\n            // and we're not within a statement leading comment.\n            beginStatement =\n                   (stream.peek() != \" \") &&   // not a space\n                   (style === undefined) &&    // not a region identifier\n                   !state.tlvInBlockComment && // not in block comment\n                   //!stream.match(tlvCommentMatch, false) && // not comment start\n                   (stream.column() == state.tlvIndentationStyle.length * tlvIndentUnit);  // at scope level\n            if (beginStatement) {\n              if (state.statementComment) {\n                // statement already started by comment\n                beginStatement = false;\n              }\n              state.statementComment =\n                   stream.match(tlvCommentMatch, false); // comment start\n            }\n          }\n\n          var match;\n          if (style !== undefined) {\n            // Region line.\n            style += \" \" + tlvScopeStyle(state, 0, \"scope-ident\")\n          } else if (((stream.pos / tlvIndentUnit) < state.tlvIndentationStyle.length) &&\n                     (match = stream.match(stream.sol() ? tlvFirstLevelIndentMatch : /^   /))) {\n            // Indentation\n            style = // make this style distinct from the previous one to prevent\n                    // codemirror from combining spans\n                    \"tlv-indent-\" + (((stream.pos % 2) == 0) ? \"even\" : \"odd\") +\n                    // and style it\n                    \" \" + tlvScopeStyle(state, stream.pos - tlvIndentUnit, \"indent\");\n            // Style the line prefix character.\n            if (match[0].charAt(0) == \"!\") {\n              style += \" tlv-alert-line-prefix\";\n            }\n            // Place a class before a scope identifier.\n            if (tlvIdentNext(stream)) {\n              style += \" \" + tlvScopeStyle(state, stream.pos, \"before-scope-ident\");\n            }\n          } else if (state.tlvInBlockComment) {\n            // In a block comment.\n            if (stream.match(/^.*?\\*\\//)) {\n              // Exit block comment.\n              state.tlvInBlockComment = false;\n              if (tlvTrackStatements && !stream.eol()) {\n                // Anything after comment is assumed to be real statement content.\n                state.statementComment = false;\n              }\n            } else {\n              stream.skipToEnd();\n            }\n            style = \"comment\";\n          } else if ((match = stream.match(tlvCommentMatch)) && !state.tlvInBlockComment) {\n            // Start comment.\n            if (match[0] == \"//\") {\n              // Line comment.\n              stream.skipToEnd();\n            } else {\n              // Block comment.\n              state.tlvInBlockComment = true;\n            }\n            style = \"comment\";\n          } else if (match = stream.match(tlvIdentMatch)) {\n            // looks like an identifier (or identifier prefix)\n            var prefix = match[1];\n            var mnemonic = match[2];\n            if (// is identifier prefix\n                tlvIdentifierStyle.hasOwnProperty(prefix) &&\n                // has mnemonic or we're at the end of the line (maybe it hasn't been typed yet)\n                (mnemonic.length > 0 || stream.eol())) {\n              style = tlvIdentifierStyle[prefix];\n              if (stream.column() == state.indented) {\n                // Begin scope.\n                style += \" \" + tlvScopeStyle(state, stream.column(), \"scope-ident\")\n              }\n            } else {\n              // Just swallow one character and try again.\n              // This enables subsequent identifier match with preceding symbol character, which\n              //   is legal within a statement.  (Eg, !$reset).  It also enables detection of\n              //   comment start with preceding symbols.\n              stream.backUp(stream.current().length - 1);\n              style = \"tlv-default\";\n            }\n          } else if (stream.match(/^\\t+/)) {\n            // Highlight tabs, which are illegal.\n            style = \"tlv-tab\";\n          } else if (stream.match(/^[\\[\\]{}\\(\\);\\:]+/)) {\n            // [:], (), {}, ;.\n            style = \"meta\";\n          } else if (match = stream.match(/^[mM]4([\\+_])?[\\w\\d_]*/)) {\n            // m4 pre proc\n            style = (match[1] == \"+\") ? \"tlv-m4-plus\" : \"tlv-m4\";\n          } else if (stream.match(/^ +/)){\n            // Skip over spaces.\n            if (stream.eol()) {\n              // Trailing spaces.\n              style = \"error\";\n            } else {\n              // Non-trailing spaces.\n              style = \"tlv-default\";\n            }\n          } else if (stream.match(/^[\\w\\d_]+/)) {\n            // alpha-numeric token.\n            style = \"number\";\n          } else {\n            // Eat the next char w/ no formatting.\n            stream.next();\n            style = \"tlv-default\";\n          }\n          if (beginStatement) {\n            style += \" tlv-statement\";\n          }\n        } else {\n          if (stream.match(/^[mM]4([\\w\\d_]*)/)) {\n            // m4 pre proc\n            style = \"tlv-m4\";\n          }\n        }\n        return style;\n      },\n\n      indent: function(state) {\n        return (state.tlvCodeActive == true) ? state.tlvNextIndent : -1;\n      },\n\n      startState: function(state) {\n        state.tlvIndentationStyle = [];  // Styles to use for each level of indentation.\n        state.tlvCodeActive = true;  // True when we're in a TLV region (and at beginning of file).\n        state.tlvNextIndent = -1;    // The number of spaces to autoindent the next line if tlvCodeActive.\n        state.tlvInBlockComment = false;  // True inside /**/ comment.\n        if (tlvTrackStatements) {\n          state.statementComment = false;  // True inside a statement's header comment.\n        }\n      }\n\n    }\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/vhdl/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: VHDL mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"vhdl.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">VHDL</a>\n  </ul>\n</div>\n\n<article>\n<h2>VHDL mode</h2>\n\n<div><textarea id=\"code\" name=\"code\">\nLIBRARY ieee;\nUSE ieee.std_logic_1164.ALL;\nUSE ieee.numeric_std.ALL;\n\nENTITY tb IS\nEND tb;\n\nARCHITECTURE behavior OF tb IS\n   --Inputs\n   signal a : unsigned(2 downto 0) := (others => '0');\n   signal b : unsigned(2 downto 0) := (others => '0');\n    --Outputs\n   signal a_eq_b : std_logic;\n   signal a_le_b : std_logic;\n   signal a_gt_b : std_logic;\n\n    signal i,j : integer;\n\nBEGIN\n\n    -- Instantiate the Unit Under Test (UUT)\n   uut: entity work.comparator PORT MAP (\n          a => a,\n          b => b,\n          a_eq_b => a_eq_b,\n          a_le_b => a_le_b,\n          a_gt_b => a_gt_b\n        );\n\n   -- Stimulus process\n   stim_proc: process\n   begin\n        for i in 0 to 8 loop\n            for j in 0 to 8 loop\n                a <= to_unsigned(i,3); --integer to unsigned type conversion\n                b <= to_unsigned(j,3);\n                wait for 10 ns;\n            end loop;\n        end loop;\n   end process;\n\nEND;\n</textarea></div>\n\n<script>\n  var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n    lineNumbers: true,\n    matchBrackets: true,\n    mode: {\n      name: \"vhdl\",\n    }\n  });\n</script>\n\n<p>\nSyntax highlighting and indentation for the VHDL language.\n<h2>Configuration options:</h2>\n  <ul>\n    <li><strong>atoms</strong> - List of atom words. Default: \"null\"</li>\n    <li><strong>hooks</strong> - List of meta hooks. Default: [\"`\", \"$\"]</li>\n    <li><strong>multiLineStrings</strong> - Whether multi-line strings are accepted. Default: false</li>\n  </ul>\n</p>\n\n<p><strong>MIME types defined:</strong> <code>text/x-vhdl</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/vhdl/vhdl.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Originally written by Alf Nielsen, re-written by Michael Zhou\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nfunction words(str) {\n  var obj = {}, words = str.split(\",\");\n  for (var i = 0; i < words.length; ++i) {\n    var allCaps = words[i].toUpperCase();\n    var firstCap = words[i].charAt(0).toUpperCase() + words[i].slice(1);\n    obj[words[i]] = true;\n    obj[allCaps] = true;\n    obj[firstCap] = true;\n  }\n  return obj;\n}\n\nfunction metaHook(stream) {\n  stream.eatWhile(/[\\w\\$_]/);\n  return \"meta\";\n}\n\nCodeMirror.defineMode(\"vhdl\", function(config, parserConfig) {\n  var indentUnit = config.indentUnit,\n      atoms = parserConfig.atoms || words(\"null\"),\n      hooks = parserConfig.hooks || {\"`\": metaHook, \"$\": metaHook},\n      multiLineStrings = parserConfig.multiLineStrings;\n\n  var keywords = words(\"abs,access,after,alias,all,and,architecture,array,assert,attribute,begin,block,\" +\n      \"body,buffer,bus,case,component,configuration,constant,disconnect,downto,else,elsif,end,end block,end case,\" +\n      \"end component,end for,end generate,end if,end loop,end process,end record,end units,entity,exit,file,for,\" +\n      \"function,generate,generic,generic map,group,guarded,if,impure,in,inertial,inout,is,label,library,linkage,\" +\n      \"literal,loop,map,mod,nand,new,next,nor,null,of,on,open,or,others,out,package,package body,port,port map,\" +\n      \"postponed,procedure,process,pure,range,record,register,reject,rem,report,return,rol,ror,select,severity,signal,\" +\n      \"sla,sll,sra,srl,subtype,then,to,transport,type,unaffected,units,until,use,variable,wait,when,while,with,xnor,xor\");\n\n  var blockKeywords = words(\"architecture,entity,begin,case,port,else,elsif,end,for,function,if\");\n\n  var isOperatorChar = /[&|~><!\\)\\(*#%@+\\/=?\\:;}{,\\.\\^\\-\\[\\]]/;\n  var curPunc;\n\n  function tokenBase(stream, state) {\n    var ch = stream.next();\n    if (hooks[ch]) {\n      var result = hooks[ch](stream, state);\n      if (result !== false) return result;\n    }\n    if (ch == '\"') {\n      state.tokenize = tokenString2(ch);\n      return state.tokenize(stream, state);\n    }\n    if (ch == \"'\") {\n      state.tokenize = tokenString(ch);\n      return state.tokenize(stream, state);\n    }\n    if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n      curPunc = ch;\n      return null;\n    }\n    if (/[\\d']/.test(ch)) {\n      stream.eatWhile(/[\\w\\.']/);\n      return \"number\";\n    }\n    if (ch == \"-\") {\n      if (stream.eat(\"-\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n    }\n    if (isOperatorChar.test(ch)) {\n      stream.eatWhile(isOperatorChar);\n      return \"operator\";\n    }\n    stream.eatWhile(/[\\w\\$_]/);\n    var cur = stream.current();\n    if (keywords.propertyIsEnumerable(cur.toLowerCase())) {\n      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n      return \"keyword\";\n    }\n    if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n    return \"variable\";\n  }\n\n  function tokenString(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {end = true; break;}\n        escaped = !escaped && next == \"--\";\n      }\n      if (end || !(escaped || multiLineStrings))\n        state.tokenize = tokenBase;\n      return \"string\";\n    };\n  }\n  function tokenString2(quote) {\n    return function(stream, state) {\n      var escaped = false, next, end = false;\n      while ((next = stream.next()) != null) {\n        if (next == quote && !escaped) {end = true; break;}\n        escaped = !escaped && next == \"--\";\n      }\n      if (end || !(escaped || multiLineStrings))\n        state.tokenize = tokenBase;\n      return \"string-2\";\n    };\n  }\n\n  function Context(indented, column, type, align, prev) {\n    this.indented = indented;\n    this.column = column;\n    this.type = type;\n    this.align = align;\n    this.prev = prev;\n  }\n  function pushContext(state, col, type) {\n    return state.context = new Context(state.indented, col, type, null, state.context);\n  }\n  function popContext(state) {\n    var t = state.context.type;\n    if (t == \")\" || t == \"]\" || t == \"}\")\n      state.indented = state.context.indented;\n    return state.context = state.context.prev;\n  }\n\n  // Interface\n  return {\n    startState: function(basecolumn) {\n      return {\n        tokenize: null,\n        context: new Context((basecolumn || 0) - indentUnit, 0, \"top\", false),\n        indented: 0,\n        startOfLine: true\n      };\n    },\n\n    token: function(stream, state) {\n      var ctx = state.context;\n      if (stream.sol()) {\n        if (ctx.align == null) ctx.align = false;\n        state.indented = stream.indentation();\n        state.startOfLine = true;\n      }\n      if (stream.eatSpace()) return null;\n      curPunc = null;\n      var style = (state.tokenize || tokenBase)(stream, state);\n      if (style == \"comment\" || style == \"meta\") return style;\n      if (ctx.align == null) ctx.align = true;\n\n      if ((curPunc == \";\" || curPunc == \":\") && ctx.type == \"statement\") popContext(state);\n      else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n      else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n      else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n      else if (curPunc == \"}\") {\n        while (ctx.type == \"statement\") ctx = popContext(state);\n        if (ctx.type == \"}\") ctx = popContext(state);\n        while (ctx.type == \"statement\") ctx = popContext(state);\n      }\n      else if (curPunc == ctx.type) popContext(state);\n      else if (ctx.type == \"}\" || ctx.type == \"top\" || (ctx.type == \"statement\" && curPunc == \"newstatement\"))\n        pushContext(state, stream.column(), \"statement\");\n      state.startOfLine = false;\n      return style;\n    },\n\n    indent: function(state, textAfter) {\n      if (state.tokenize != tokenBase && state.tokenize != null) return 0;\n      var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type;\n      if (ctx.type == \"statement\") return ctx.indented + (firstChar == \"{\" ? 0 : indentUnit);\n      else if (ctx.align) return ctx.column + (closing ? 0 : 1);\n      else return ctx.indented + (closing ? 0 : indentUnit);\n    },\n\n    electricChars: \"{}\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-vhdl\", \"vhdl\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/vue/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Vue.js mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/overlay.js\"></script>\n<script src=\"../../addon/mode/simple.js\"></script>\n<script src=\"../../addon/selection/selection-pointer.js\"></script>\n<script src=\"../xml/xml.js\"></script>\n<script src=\"../javascript/javascript.js\"></script>\n<script src=\"../css/css.js\"></script>\n<script src=\"../coffeescript/coffeescript.js\"></script>\n<script src=\"../sass/sass.js\"></script>\n<script src=\"../pug/pug.js\"></script>\n\n<script src=\"../handlebars/handlebars.js\"></script>\n<script src=\"../htmlmixed/htmlmixed.js\"></script>\n<script src=\"vue.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Vue.js mode</a>\n  </ul>\n</div>\n\n<article>\n<h2>Vue.js mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n<template>\n  <div class=\"sass\">Im am a {{mustache-like}} template</div>\n</template>\n\n<script lang=\"coffee\">\n  module.exports =\n    props: ['one', 'two', 'three']\n</script>\n\n<style lang=\"sass\">\n.sass\n  font-size: 18px\n</style>\n\n</textarea></form>\n    <script>\n      // Define an extended mixed-mode that understands vbscript and\n      // leaves mustache/handlebars embedded templates in html mode\n      var mixedMode = {\n        name: \"vue\"\n      };\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: mixedMode,\n        selectionPointer: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-vue</code></p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/vue/vue.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function (mod) {\n  \"use strict\";\n  if (typeof exports === \"object\" && typeof module === \"object\") {// CommonJS\n    mod(require(\"../../lib/codemirror\"),\n        require(\"../../addon/mode/overlay\"),\n        require(\"../xml/xml\"),\n        require(\"../javascript/javascript\"),\n        require(\"../coffeescript/coffeescript\"),\n        require(\"../css/css\"),\n        require(\"../sass/sass\"),\n        require(\"../stylus/stylus\"),\n        require(\"../pug/pug\"),\n        require(\"../handlebars/handlebars\"));\n  } else if (typeof define === \"function\" && define.amd) { // AMD\n    define([\"../../lib/codemirror\",\n            \"../../addon/mode/overlay\",\n            \"../xml/xml\",\n            \"../javascript/javascript\",\n            \"../coffeescript/coffeescript\",\n            \"../css/css\",\n            \"../sass/sass\",\n            \"../stylus/stylus\",\n            \"../pug/pug\",\n            \"../handlebars/handlebars\"], mod);\n  } else { // Plain browser env\n    mod(CodeMirror);\n  }\n})(function (CodeMirror) {\n  var tagLanguages = {\n    script: [\n      [\"lang\", /coffee(script)?/, \"coffeescript\"],\n      [\"type\", /^(?:text|application)\\/(?:x-)?coffee(?:script)?$/, \"coffeescript\"],\n      [\"lang\", /^babel$/, \"javascript\"],\n      [\"type\", /^text\\/babel$/, \"javascript\"],\n      [\"type\", /^text\\/ecmascript-\\d+$/, \"javascript\"]\n    ],\n    style: [\n      [\"lang\", /^stylus$/i, \"stylus\"],\n      [\"lang\", /^sass$/i, \"sass\"],\n      [\"lang\", /^less$/i, \"text/x-less\"],\n      [\"lang\", /^scss$/i, \"text/x-scss\"],\n      [\"type\", /^(text\\/)?(x-)?styl(us)?$/i, \"stylus\"],\n      [\"type\", /^text\\/sass/i, \"sass\"],\n      [\"type\", /^(text\\/)?(x-)?scss$/i, \"text/x-scss\"],\n      [\"type\", /^(text\\/)?(x-)?less$/i, \"text/x-less\"]\n    ],\n    template: [\n      [\"lang\", /^vue-template$/i, \"vue\"],\n      [\"lang\", /^pug$/i, \"pug\"],\n      [\"lang\", /^handlebars$/i, \"handlebars\"],\n      [\"type\", /^(text\\/)?(x-)?pug$/i, \"pug\"],\n      [\"type\", /^text\\/x-handlebars-template$/i, \"handlebars\"],\n      [null, null, \"vue-template\"]\n    ]\n  };\n\n  CodeMirror.defineMode(\"vue-template\", function (config, parserConfig) {\n    var mustacheOverlay = {\n      token: function (stream) {\n        if (stream.match(/^\\{\\{.*?\\}\\}/)) return \"meta mustache\";\n        while (stream.next() && !stream.match(\"{{\", false)) {}\n        return null;\n      }\n    };\n    return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || \"text/html\"), mustacheOverlay);\n  });\n\n  CodeMirror.defineMode(\"vue\", function (config) {\n    return CodeMirror.getMode(config, {name: \"htmlmixed\", tags: tagLanguages});\n  }, \"htmlmixed\", \"xml\", \"javascript\", \"coffeescript\", \"css\", \"sass\", \"stylus\", \"pug\", \"handlebars\");\n\n  CodeMirror.defineMIME(\"script/x-vue\", \"vue\");\n  CodeMirror.defineMIME(\"text/x-vue\", \"vue\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/webidl/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Web IDL mode</title>\n<meta charset=\"utf-8\">\n<link rel=\"stylesheet\" href=\"../../doc/docs.css\">\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"webidl.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n\n<div id=\"nav\">\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=\"logo\" src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=\"active\" href=\"#\">Web IDL</a>\n  </ul>\n</div>\n\n<article>\n  <h2>Web IDL mode</h2>\n\n  <div>\n<textarea id=\"code\" name=\"code\">\n[NamedConstructor=Image(optional unsigned long width, optional unsigned long height)]\ninterface HTMLImageElement : HTMLElement {\n           attribute DOMString alt;\n           attribute DOMString src;\n           attribute DOMString srcset;\n           attribute DOMString sizes;\n           attribute DOMString? crossOrigin;\n           attribute DOMString useMap;\n           attribute boolean isMap;\n           attribute unsigned long width;\n           attribute unsigned long height;\n  readonly attribute unsigned long naturalWidth;\n  readonly attribute unsigned long naturalHeight;\n  readonly attribute boolean complete;\n  readonly attribute DOMString currentSrc;\n\n  // also has obsolete members\n};\n\npartial interface HTMLImageElement {\n  attribute DOMString name;\n  attribute DOMString lowsrc;\n  attribute DOMString align;\n  attribute unsigned long hspace;\n  attribute unsigned long vspace;\n  attribute DOMString longDesc;\n\n  [TreatNullAs=EmptyString] attribute DOMString border;\n};\n</textarea>\n  </div>\n\n  <script>\n    var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n      lineNumbers: true,\n      matchBrackets: true\n    });\n  </script>\n\n  <p><strong>MIME type defined:</strong> <code>text/x-webidl</code>.</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/webidl/webidl.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nfunction wordRegexp(words) {\n  return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n};\n\nvar builtinArray = [\n  \"Clamp\",\n  \"Constructor\",\n  \"EnforceRange\",\n  \"Exposed\",\n  \"ImplicitThis\",\n  \"Global\", \"PrimaryGlobal\",\n  \"LegacyArrayClass\",\n  \"LegacyUnenumerableNamedProperties\",\n  \"LenientThis\",\n  \"NamedConstructor\",\n  \"NewObject\",\n  \"NoInterfaceObject\",\n  \"OverrideBuiltins\",\n  \"PutForwards\",\n  \"Replaceable\",\n  \"SameObject\",\n  \"TreatNonObjectAsNull\",\n  \"TreatNullAs\",\n    \"EmptyString\",\n  \"Unforgeable\",\n  \"Unscopeable\"\n];\nvar builtins = wordRegexp(builtinArray);\n\nvar typeArray = [\n  \"unsigned\", \"short\", \"long\",                  // UnsignedIntegerType\n  \"unrestricted\", \"float\", \"double\",            // UnrestrictedFloatType\n  \"boolean\", \"byte\", \"octet\",                   // Rest of PrimitiveType\n  \"Promise\",                                    // PromiseType\n  \"ArrayBuffer\", \"DataView\", \"Int8Array\", \"Int16Array\", \"Int32Array\",\n  \"Uint8Array\", \"Uint16Array\", \"Uint32Array\", \"Uint8ClampedArray\",\n  \"Float32Array\", \"Float64Array\",               // BufferRelatedType\n  \"ByteString\", \"DOMString\", \"USVString\", \"sequence\", \"object\", \"RegExp\",\n  \"Error\", \"DOMException\", \"FrozenArray\",       // Rest of NonAnyType\n  \"any\",                                        // Rest of SingleType\n  \"void\"                                        // Rest of ReturnType\n];\nvar types = wordRegexp(typeArray);\n\nvar keywordArray = [\n  \"attribute\", \"callback\", \"const\", \"deleter\", \"dictionary\", \"enum\", \"getter\",\n  \"implements\", \"inherit\", \"interface\", \"iterable\", \"legacycaller\", \"maplike\",\n  \"partial\", \"required\", \"serializer\", \"setlike\", \"setter\", \"static\",\n  \"stringifier\", \"typedef\",                     // ArgumentNameKeyword except\n                                                // \"unrestricted\"\n  \"optional\", \"readonly\", \"or\"\n];\nvar keywords = wordRegexp(keywordArray);\n\nvar atomArray = [\n  \"true\", \"false\",                              // BooleanLiteral\n  \"Infinity\", \"NaN\",                            // FloatLiteral\n  \"null\"                                        // Rest of ConstValue\n];\nvar atoms = wordRegexp(atomArray);\n\nCodeMirror.registerHelper(\"hintWords\", \"webidl\",\n    builtinArray.concat(typeArray).concat(keywordArray).concat(atomArray));\n\nvar startDefArray = [\"callback\", \"dictionary\", \"enum\", \"interface\"];\nvar startDefs = wordRegexp(startDefArray);\n\nvar endDefArray = [\"typedef\"];\nvar endDefs = wordRegexp(endDefArray);\n\nvar singleOperators = /^[:<=>?]/;\nvar integers = /^-?([1-9][0-9]*|0[Xx][0-9A-Fa-f]+|0[0-7]*)/;\nvar floats = /^-?(([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)/;\nvar identifiers = /^_?[A-Za-z][0-9A-Z_a-z-]*/;\nvar identifiersEnd = /^_?[A-Za-z][0-9A-Z_a-z-]*(?=\\s*;)/;\nvar strings = /^\"[^\"]*\"/;\nvar multilineComments = /^\\/\\*.*?\\*\\//;\nvar multilineCommentsStart = /^\\/\\*.*/;\nvar multilineCommentsEnd = /^.*?\\*\\//;\n\nfunction readToken(stream, state) {\n  // whitespace\n  if (stream.eatSpace()) return null;\n\n  // comment\n  if (state.inComment) {\n    if (stream.match(multilineCommentsEnd)) {\n      state.inComment = false;\n      return \"comment\";\n    }\n    stream.skipToEnd();\n    return \"comment\";\n  }\n  if (stream.match(\"//\")) {\n    stream.skipToEnd();\n    return \"comment\";\n  }\n  if (stream.match(multilineComments)) return \"comment\";\n  if (stream.match(multilineCommentsStart)) {\n    state.inComment = true;\n    return \"comment\";\n  }\n\n  // integer and float\n  if (stream.match(/^-?[0-9\\.]/, false)) {\n    if (stream.match(integers) || stream.match(floats)) return \"number\";\n  }\n\n  // string\n  if (stream.match(strings)) return \"string\";\n\n  // identifier\n  if (state.startDef && stream.match(identifiers)) return \"def\";\n\n  if (state.endDef && stream.match(identifiersEnd)) {\n    state.endDef = false;\n    return \"def\";\n  }\n\n  if (stream.match(keywords)) return \"keyword\";\n\n  if (stream.match(types)) {\n    var lastToken = state.lastToken;\n    var nextToken = (stream.match(/^\\s*(.+?)\\b/, false) || [])[1];\n\n    if (lastToken === \":\" || lastToken === \"implements\" ||\n        nextToken === \"implements\" || nextToken === \"=\") {\n      // Used as identifier\n      return \"builtin\";\n    } else {\n      // Used as type\n      return \"variable-3\";\n    }\n  }\n\n  if (stream.match(builtins)) return \"builtin\";\n  if (stream.match(atoms)) return \"atom\";\n  if (stream.match(identifiers)) return \"variable\";\n\n  // other\n  if (stream.match(singleOperators)) return \"operator\";\n\n  // unrecognized\n  stream.next();\n  return null;\n};\n\nCodeMirror.defineMode(\"webidl\", function() {\n  return {\n    startState: function() {\n      return {\n        // Is in multiline comment\n        inComment: false,\n        // Last non-whitespace, matched token\n        lastToken: \"\",\n        // Next token is a definition\n        startDef: false,\n        // Last token of the statement is a definition\n        endDef: false\n      };\n    },\n    token: function(stream, state) {\n      var style = readToken(stream, state);\n\n      if (style) {\n        var cur = stream.current();\n        state.lastToken = cur;\n        if (style === \"keyword\") {\n          state.startDef = startDefs.test(cur);\n          state.endDef = state.endDef || endDefs.test(cur);\n        } else {\n          state.startDef = false;\n        }\n      }\n\n      return style;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-webidl\", \"webidl\");\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/xml/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: XML mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"xml.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">XML</a>\n  </ul>\n</div>\n\n<article>\n<h2>XML mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n&lt;html style=\"color: green\"&gt;\n  &lt;!-- this is a comment --&gt;\n  &lt;head&gt;\n    &lt;title&gt;HTML Example&lt;/title&gt;\n  &lt;/head&gt;\n  &lt;body&gt;\n    The indentation tries to be &lt;em&gt;somewhat &amp;quot;do what\n    I mean&amp;quot;&lt;/em&gt;... but might not match your style.\n  &lt;/body&gt;\n&lt;/html&gt;\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: \"text/html\",\n        lineNumbers: true\n      });\n    </script>\n    <p>The XML mode supports these configuration parameters:</p>\n    <dl>\n      <dt><code>htmlMode (boolean)</code></dt>\n      <dd>This switches the mode to parse HTML instead of XML. This\n      means attributes do not have to be quoted, and some elements\n      (such as <code>br</code>) do not require a closing tag.</dd>\n      <dt><code>matchClosing (boolean)</code></dt>\n      <dd>Controls whether the mode checks that close tags match the\n      corresponding opening tag, and highlights mismatches as errors.\n      Defaults to true.</dd>\n      <dt><code>alignCDATA (boolean)</code></dt>\n      <dd>Setting this to true will force the opening tag of CDATA\n      blocks to not be indented.</dd>\n    </dl>\n\n    <p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/html</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/xml/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var mode = CodeMirror.getMode({indentUnit: 2}, \"xml\"), mname = \"xml\";\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), mname); }\n\n  MT(\"matching\",\n     \"[tag&bracket <][tag top][tag&bracket >]\",\n     \"  text\",\n     \"  [tag&bracket <][tag inner][tag&bracket />]\",\n     \"[tag&bracket </][tag top][tag&bracket >]\");\n\n  MT(\"nonmatching\",\n     \"[tag&bracket <][tag top][tag&bracket >]\",\n     \"  [tag&bracket <][tag inner][tag&bracket />]\",\n     \"  [tag&bracket </][tag&error tip][tag&bracket&error >]\");\n\n  MT(\"doctype\",\n     \"[meta <!doctype foobar>]\",\n     \"[tag&bracket <][tag top][tag&bracket />]\");\n\n  MT(\"cdata\",\n     \"[tag&bracket <][tag top][tag&bracket >]\",\n     \"  [atom <![CDATA[foo]\",\n     \"[atom barbazguh]]]]>]\",\n     \"[tag&bracket </][tag top][tag&bracket >]\");\n\n  // HTML tests\n  mode = CodeMirror.getMode({indentUnit: 2}, \"text/html\");\n\n  MT(\"selfclose\",\n     \"[tag&bracket <][tag html][tag&bracket >]\",\n     \"  [tag&bracket <][tag link] [attribute rel]=[string stylesheet] [attribute href]=[string \\\"/foobar\\\"][tag&bracket >]\",\n     \"[tag&bracket </][tag html][tag&bracket >]\");\n\n  MT(\"list\",\n     \"[tag&bracket <][tag ol][tag&bracket >]\",\n     \"  [tag&bracket <][tag li][tag&bracket >]one\",\n     \"  [tag&bracket <][tag li][tag&bracket >]two\",\n     \"[tag&bracket </][tag ol][tag&bracket >]\");\n\n  MT(\"valueless\",\n     \"[tag&bracket <][tag input] [attribute type]=[string checkbox] [attribute checked][tag&bracket />]\");\n\n  MT(\"pThenArticle\",\n     \"[tag&bracket <][tag p][tag&bracket >]\",\n     \"  foo\",\n     \"[tag&bracket <][tag article][tag&bracket >]bar\");\n\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/xml/xml.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nvar htmlConfig = {\n  autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,\n                    'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,\n                    'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,\n                    'track': true, 'wbr': true, 'menuitem': true},\n  implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,\n                     'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,\n                     'th': true, 'tr': true},\n  contextGrabbers: {\n    'dd': {'dd': true, 'dt': true},\n    'dt': {'dd': true, 'dt': true},\n    'li': {'li': true},\n    'option': {'option': true, 'optgroup': true},\n    'optgroup': {'optgroup': true},\n    'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,\n          'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,\n          'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,\n          'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,\n          'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},\n    'rp': {'rp': true, 'rt': true},\n    'rt': {'rp': true, 'rt': true},\n    'tbody': {'tbody': true, 'tfoot': true},\n    'td': {'td': true, 'th': true},\n    'tfoot': {'tbody': true},\n    'th': {'td': true, 'th': true},\n    'thead': {'tbody': true, 'tfoot': true},\n    'tr': {'tr': true}\n  },\n  doNotIndent: {\"pre\": true},\n  allowUnquoted: true,\n  allowMissing: true,\n  caseFold: true\n}\n\nvar xmlConfig = {\n  autoSelfClosers: {},\n  implicitlyClosed: {},\n  contextGrabbers: {},\n  doNotIndent: {},\n  allowUnquoted: false,\n  allowMissing: false,\n  allowMissingTagName: false,\n  caseFold: false\n}\n\nCodeMirror.defineMode(\"xml\", function(editorConf, config_) {\n  var indentUnit = editorConf.indentUnit\n  var config = {}\n  var defaults = config_.htmlMode ? htmlConfig : xmlConfig\n  for (var prop in defaults) config[prop] = defaults[prop]\n  for (var prop in config_) config[prop] = config_[prop]\n\n  // Return variables for tokenizers\n  var type, setStyle;\n\n  function inText(stream, state) {\n    function chain(parser) {\n      state.tokenize = parser;\n      return parser(stream, state);\n    }\n\n    var ch = stream.next();\n    if (ch == \"<\") {\n      if (stream.eat(\"!\")) {\n        if (stream.eat(\"[\")) {\n          if (stream.match(\"CDATA[\")) return chain(inBlock(\"atom\", \"]]>\"));\n          else return null;\n        } else if (stream.match(\"--\")) {\n          return chain(inBlock(\"comment\", \"-->\"));\n        } else if (stream.match(\"DOCTYPE\", true, true)) {\n          stream.eatWhile(/[\\w\\._\\-]/);\n          return chain(doctype(1));\n        } else {\n          return null;\n        }\n      } else if (stream.eat(\"?\")) {\n        stream.eatWhile(/[\\w\\._\\-]/);\n        state.tokenize = inBlock(\"meta\", \"?>\");\n        return \"meta\";\n      } else {\n        type = stream.eat(\"/\") ? \"closeTag\" : \"openTag\";\n        state.tokenize = inTag;\n        return \"tag bracket\";\n      }\n    } else if (ch == \"&\") {\n      var ok;\n      if (stream.eat(\"#\")) {\n        if (stream.eat(\"x\")) {\n          ok = stream.eatWhile(/[a-fA-F\\d]/) && stream.eat(\";\");\n        } else {\n          ok = stream.eatWhile(/[\\d]/) && stream.eat(\";\");\n        }\n      } else {\n        ok = stream.eatWhile(/[\\w\\.\\-:]/) && stream.eat(\";\");\n      }\n      return ok ? \"atom\" : \"error\";\n    } else {\n      stream.eatWhile(/[^&<]/);\n      return null;\n    }\n  }\n  inText.isInText = true;\n\n  function inTag(stream, state) {\n    var ch = stream.next();\n    if (ch == \">\" || (ch == \"/\" && stream.eat(\">\"))) {\n      state.tokenize = inText;\n      type = ch == \">\" ? \"endTag\" : \"selfcloseTag\";\n      return \"tag bracket\";\n    } else if (ch == \"=\") {\n      type = \"equals\";\n      return null;\n    } else if (ch == \"<\") {\n      state.tokenize = inText;\n      state.state = baseState;\n      state.tagName = state.tagStart = null;\n      var next = state.tokenize(stream, state);\n      return next ? next + \" tag error\" : \"tag error\";\n    } else if (/[\\'\\\"]/.test(ch)) {\n      state.tokenize = inAttribute(ch);\n      state.stringStartCol = stream.column();\n      return state.tokenize(stream, state);\n    } else {\n      stream.match(/^[^\\s\\u00a0=<>\\\"\\']*[^\\s\\u00a0=<>\\\"\\'\\/]/);\n      return \"word\";\n    }\n  }\n\n  function inAttribute(quote) {\n    var closure = function(stream, state) {\n      while (!stream.eol()) {\n        if (stream.next() == quote) {\n          state.tokenize = inTag;\n          break;\n        }\n      }\n      return \"string\";\n    };\n    closure.isInAttribute = true;\n    return closure;\n  }\n\n  function inBlock(style, terminator) {\n    return function(stream, state) {\n      while (!stream.eol()) {\n        if (stream.match(terminator)) {\n          state.tokenize = inText;\n          break;\n        }\n        stream.next();\n      }\n      return style;\n    }\n  }\n\n  function doctype(depth) {\n    return function(stream, state) {\n      var ch;\n      while ((ch = stream.next()) != null) {\n        if (ch == \"<\") {\n          state.tokenize = doctype(depth + 1);\n          return state.tokenize(stream, state);\n        } else if (ch == \">\") {\n          if (depth == 1) {\n            state.tokenize = inText;\n            break;\n          } else {\n            state.tokenize = doctype(depth - 1);\n            return state.tokenize(stream, state);\n          }\n        }\n      }\n      return \"meta\";\n    };\n  }\n\n  function Context(state, tagName, startOfLine) {\n    this.prev = state.context;\n    this.tagName = tagName;\n    this.indent = state.indented;\n    this.startOfLine = startOfLine;\n    if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))\n      this.noIndent = true;\n  }\n  function popContext(state) {\n    if (state.context) state.context = state.context.prev;\n  }\n  function maybePopContext(state, nextTagName) {\n    var parentTagName;\n    while (true) {\n      if (!state.context) {\n        return;\n      }\n      parentTagName = state.context.tagName;\n      if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||\n          !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {\n        return;\n      }\n      popContext(state);\n    }\n  }\n\n  function baseState(type, stream, state) {\n    if (type == \"openTag\") {\n      state.tagStart = stream.column();\n      return tagNameState;\n    } else if (type == \"closeTag\") {\n      return closeTagNameState;\n    } else {\n      return baseState;\n    }\n  }\n  function tagNameState(type, stream, state) {\n    if (type == \"word\") {\n      state.tagName = stream.current();\n      setStyle = \"tag\";\n      return attrState;\n    } else if (config.allowMissingTagName && type == \"endTag\") {\n      setStyle = \"tag bracket\";\n      return attrState(type, stream, state);\n    } else {\n      setStyle = \"error\";\n      return tagNameState;\n    }\n  }\n  function closeTagNameState(type, stream, state) {\n    if (type == \"word\") {\n      var tagName = stream.current();\n      if (state.context && state.context.tagName != tagName &&\n          config.implicitlyClosed.hasOwnProperty(state.context.tagName))\n        popContext(state);\n      if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {\n        setStyle = \"tag\";\n        return closeState;\n      } else {\n        setStyle = \"tag error\";\n        return closeStateErr;\n      }\n    } else if (config.allowMissingTagName && type == \"endTag\") {\n      setStyle = \"tag bracket\";\n      return closeState(type, stream, state);\n    } else {\n      setStyle = \"error\";\n      return closeStateErr;\n    }\n  }\n\n  function closeState(type, _stream, state) {\n    if (type != \"endTag\") {\n      setStyle = \"error\";\n      return closeState;\n    }\n    popContext(state);\n    return baseState;\n  }\n  function closeStateErr(type, stream, state) {\n    setStyle = \"error\";\n    return closeState(type, stream, state);\n  }\n\n  function attrState(type, _stream, state) {\n    if (type == \"word\") {\n      setStyle = \"attribute\";\n      return attrEqState;\n    } else if (type == \"endTag\" || type == \"selfcloseTag\") {\n      var tagName = state.tagName, tagStart = state.tagStart;\n      state.tagName = state.tagStart = null;\n      if (type == \"selfcloseTag\" ||\n          config.autoSelfClosers.hasOwnProperty(tagName)) {\n        maybePopContext(state, tagName);\n      } else {\n        maybePopContext(state, tagName);\n        state.context = new Context(state, tagName, tagStart == state.indented);\n      }\n      return baseState;\n    }\n    setStyle = \"error\";\n    return attrState;\n  }\n  function attrEqState(type, stream, state) {\n    if (type == \"equals\") return attrValueState;\n    if (!config.allowMissing) setStyle = \"error\";\n    return attrState(type, stream, state);\n  }\n  function attrValueState(type, stream, state) {\n    if (type == \"string\") return attrContinuedState;\n    if (type == \"word\" && config.allowUnquoted) {setStyle = \"string\"; return attrState;}\n    setStyle = \"error\";\n    return attrState(type, stream, state);\n  }\n  function attrContinuedState(type, stream, state) {\n    if (type == \"string\") return attrContinuedState;\n    return attrState(type, stream, state);\n  }\n\n  return {\n    startState: function(baseIndent) {\n      var state = {tokenize: inText,\n                   state: baseState,\n                   indented: baseIndent || 0,\n                   tagName: null, tagStart: null,\n                   context: null}\n      if (baseIndent != null) state.baseIndent = baseIndent\n      return state\n    },\n\n    token: function(stream, state) {\n      if (!state.tagName && stream.sol())\n        state.indented = stream.indentation();\n\n      if (stream.eatSpace()) return null;\n      type = null;\n      var style = state.tokenize(stream, state);\n      if ((style || type) && style != \"comment\") {\n        setStyle = null;\n        state.state = state.state(type || style, stream, state);\n        if (setStyle)\n          style = setStyle == \"error\" ? style + \" error\" : setStyle;\n      }\n      return style;\n    },\n\n    indent: function(state, textAfter, fullLine) {\n      var context = state.context;\n      // Indent multi-line strings (e.g. css).\n      if (state.tokenize.isInAttribute) {\n        if (state.tagStart == state.indented)\n          return state.stringStartCol + 1;\n        else\n          return state.indented + indentUnit;\n      }\n      if (context && context.noIndent) return CodeMirror.Pass;\n      if (state.tokenize != inTag && state.tokenize != inText)\n        return fullLine ? fullLine.match(/^(\\s*)/)[0].length : 0;\n      // Indent the starts of attribute names.\n      if (state.tagName) {\n        if (config.multilineTagIndentPastTag !== false)\n          return state.tagStart + state.tagName.length + 2;\n        else\n          return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);\n      }\n      if (config.alignCDATA && /<!\\[CDATA\\[/.test(textAfter)) return 0;\n      var tagAfter = textAfter && /^<(\\/)?([\\w_:\\.-]*)/.exec(textAfter);\n      if (tagAfter && tagAfter[1]) { // Closing tag spotted\n        while (context) {\n          if (context.tagName == tagAfter[2]) {\n            context = context.prev;\n            break;\n          } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {\n            context = context.prev;\n          } else {\n            break;\n          }\n        }\n      } else if (tagAfter) { // Opening tag spotted\n        while (context) {\n          var grabbers = config.contextGrabbers[context.tagName];\n          if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))\n            context = context.prev;\n          else\n            break;\n        }\n      }\n      while (context && context.prev && !context.startOfLine)\n        context = context.prev;\n      if (context) return context.indent + indentUnit;\n      else return state.baseIndent || 0;\n    },\n\n    electricInput: /<\\/[\\s\\w:]+>$/,\n    blockCommentStart: \"<!--\",\n    blockCommentEnd: \"-->\",\n\n    configuration: config.htmlMode ? \"html\" : \"xml\",\n    helperType: config.htmlMode ? \"html\" : \"xml\",\n\n    skipAttribute: function(state) {\n      if (state.state == attrValueState)\n        state.state = attrState\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/xml\", \"xml\");\nCodeMirror.defineMIME(\"application/xml\", \"xml\");\nif (!CodeMirror.mimeModes.hasOwnProperty(\"text/html\"))\n  CodeMirror.defineMIME(\"text/html\", {name: \"xml\", htmlMode: true});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/xquery/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: XQuery mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"../../theme/xq-dark.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"xquery.js\"></script>\n<style>\n\t.CodeMirror {\n\t  border-top: 1px solid black; border-bottom: 1px solid black;\n\t  height:400px;\n\t}\n    </style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">XQuery</a>\n  </ul>\n</div>\n\n<article>\n<h2>XQuery mode</h2>\n \n \n<div class=\"cm-s-default\"> \n\t<textarea id=\"code\" name=\"code\"> \nxquery version &quot;1.0-ml&quot;;\n(: this is\n : a \n   \"comment\" :)\nlet $let := &lt;x attr=&quot;value&quot;&gt;&quot;test&quot;&lt;func&gt;function() $var {function()} {$var}&lt;/func&gt;&lt;/x&gt;\nlet $joe:=1\nreturn element element {\n\tattribute attribute { 1 },\n\telement test { &#39;a&#39; }, \n\tattribute foo { &quot;bar&quot; },\n\tfn:doc()[ foo/@bar eq $let ],\n\t//x }    \n \n(: a more 'evil' test :)\n(: Modified Blakeley example (: with nested comment :) ... :)\ndeclare private function local:declare() {()};\ndeclare private function local:private() {()};\ndeclare private function local:function() {()};\ndeclare private function local:local() {()};\nlet $let := &lt;let&gt;let $let := &quot;let&quot;&lt;/let&gt;\nreturn element element {\n\tattribute attribute { try { xdmp:version() } catch($e) { xdmp:log($e) } },\n\tattribute fn:doc { &quot;bar&quot; castable as xs:string },\n\telement text { text { &quot;text&quot; } },\n\tfn:doc()[ child::eq/(@bar | attribute::attribute) eq $let ],\n\t//fn:doc\n}\n\n\n\nxquery version &quot;1.0-ml&quot;;\n\n(: Copyright 2006-2010 Mark Logic Corporation. :)\n\n(:\n : Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);\n : you may not use this file except in compliance with the License.\n : You may obtain a copy of the License at\n :\n :     http://www.apache.org/licenses/LICENSE-2.0\n :\n : Unless required by applicable law or agreed to in writing, software\n : distributed under the License is distributed on an &quot;AS IS&quot; BASIS,\n : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n : See the License for the specific language governing permissions and\n : limitations under the License.\n :)\n\nmodule namespace json = &quot;http://marklogic.com/json&quot;;\ndeclare default function namespace &quot;http://www.w3.org/2005/xpath-functions&quot;;\n\n(: Need to backslash escape any double quotes, backslashes, and newlines :)\ndeclare function json:escape($s as xs:string) as xs:string {\n  let $s := replace($s, &quot;\\\\&quot;, &quot;\\\\\\\\&quot;)\n  let $s := replace($s, &quot;&quot;&quot;&quot;, &quot;\\\\&quot;&quot;&quot;)\n  let $s := replace($s, codepoints-to-string((13, 10)), &quot;\\\\n&quot;)\n  let $s := replace($s, codepoints-to-string(13), &quot;\\\\n&quot;)\n  let $s := replace($s, codepoints-to-string(10), &quot;\\\\n&quot;)\n  return $s\n};\n\ndeclare function json:atomize($x as element()) as xs:string {\n  if (count($x/node()) = 0) then 'null'\n  else if ($x/@type = &quot;number&quot;) then\n    let $castable := $x castable as xs:float or\n                     $x castable as xs:double or\n                     $x castable as xs:decimal\n    return\n    if ($castable) then xs:string($x)\n    else error(concat(&quot;Not a number: &quot;, xdmp:describe($x)))\n  else if ($x/@type = &quot;boolean&quot;) then\n    let $castable := $x castable as xs:boolean\n    return\n    if ($castable) then xs:string(xs:boolean($x))\n    else error(concat(&quot;Not a boolean: &quot;, xdmp:describe($x)))\n  else concat('&quot;', json:escape($x), '&quot;')\n};\n\n(: Print the thing that comes after the colon :)\ndeclare function json:print-value($x as element()) as xs:string {\n  if (count($x/*) = 0) then\n    json:atomize($x)\n  else if ($x/@quote = &quot;true&quot;) then\n    concat('&quot;', json:escape(xdmp:quote($x/node())), '&quot;')\n  else\n    string-join(('{',\n      string-join(for $i in $x/* return json:print-name-value($i), &quot;,&quot;),\n    '}'), &quot;&quot;)\n};\n\n(: Print the name and value both :)\ndeclare function json:print-name-value($x as element()) as xs:string? {\n  let $name := name($x)\n  let $first-in-array :=\n    count($x/preceding-sibling::*[name(.) = $name]) = 0 and\n    (count($x/following-sibling::*[name(.) = $name]) &gt; 0 or $x/@array = &quot;true&quot;)\n  let $later-in-array := count($x/preceding-sibling::*[name(.) = $name]) &gt; 0\n  return\n\n  if ($later-in-array) then\n    ()  (: I was handled previously :)\n  else if ($first-in-array) then\n    string-join(('&quot;', json:escape($name), '&quot;:[',\n      string-join((for $i in ($x, $x/following-sibling::*[name(.) = $name]) return json:print-value($i)), &quot;,&quot;),\n    ']'), &quot;&quot;)\n   else\n     string-join(('&quot;', json:escape($name), '&quot;:', json:print-value($x)), &quot;&quot;)\n};\n\n(:~\n  Transforms an XML element into a JSON string representation.  See http://json.org.\n  &lt;p/&gt;\n  Sample usage:\n  &lt;pre&gt;\n    xquery version &quot;1.0-ml&quot;;\n    import module namespace json=&quot;http://marklogic.com/json&quot; at &quot;json.xqy&quot;;\n    json:serialize(&amp;lt;foo&amp;gt;&amp;lt;bar&amp;gt;kid&amp;lt;/bar&amp;gt;&amp;lt;/foo&amp;gt;)\n  &lt;/pre&gt;\n  Sample transformations:\n  &lt;pre&gt;\n  &amp;lt;e/&amp;gt; becomes {&quot;e&quot;:null}\n  &amp;lt;e&amp;gt;text&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;text&quot;}\n  &amp;lt;e&amp;gt;quote &quot; escaping&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;quote \\&quot; escaping&quot;}\n  &amp;lt;e&amp;gt;backslash \\ escaping&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;backslash \\\\ escaping&quot;}\n  &amp;lt;e&amp;gt;&amp;lt;a&amp;gt;text1&amp;lt;/a&amp;gt;&amp;lt;b&amp;gt;text2&amp;lt;/b&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:&quot;text1&quot;,&quot;b&quot;:&quot;text2&quot;}}\n  &amp;lt;e&amp;gt;&amp;lt;a&amp;gt;text1&amp;lt;/a&amp;gt;&amp;lt;a&amp;gt;text2&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:[&quot;text1&quot;,&quot;text2&quot;]}}\n  &amp;lt;e&amp;gt;&amp;lt;a array=&quot;true&quot;&amp;gt;text1&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:[&quot;text1&quot;]}}\n  &amp;lt;e&amp;gt;&amp;lt;a type=&quot;boolean&quot;&amp;gt;false&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:false}}\n  &amp;lt;e&amp;gt;&amp;lt;a type=&quot;number&quot;&amp;gt;123.5&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:123.5}}\n  &amp;lt;e quote=&quot;true&quot;&amp;gt;&amp;lt;div attrib=&quot;value&quot;/&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;&amp;lt;div attrib=\\&quot;value\\&quot;/&amp;gt;&quot;}\n  &lt;/pre&gt;\n  &lt;p/&gt;\n  Namespace URIs are ignored.  Namespace prefixes are included in the JSON name.\n  &lt;p/&gt;\n  Attributes are ignored, except for the special attribute @array=&quot;true&quot; that\n  indicates the JSON serialization should write the node, even if single, as an\n  array, and the attribute @type that can be set to &quot;boolean&quot; or &quot;number&quot; to\n  dictate the value should be written as that type (unquoted).  There's also\n  an @quote attribute that when set to true writes the inner content as text\n  rather than as structured JSON, useful for sending some XHTML over the\n  wire.\n  &lt;p/&gt;\n  Text nodes within mixed content are ignored.\n\n  @param $x Element node to convert\n  @return String holding JSON serialized representation of $x\n\n  @author Jason Hunter\n  @version 1.0.1\n  \n  Ported to xquery 1.0-ml; double escaped backslashes in json:escape\n:)\ndeclare function json:serialize($x as element())  as xs:string {\n  string-join(('{', json:print-name-value($x), '}'), &quot;&quot;)\n};\n  </textarea> \n</div> \n \n    <script> \n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true,\n        matchBrackets: true,\n        theme: \"xq-dark\"\n      });\n    </script> \n \n    <p><strong>MIME types defined:</strong> <code>application/xquery</code>.</p> \n \n    <p>Development of the CodeMirror XQuery mode was sponsored by \n      <a href=\"http://marklogic.com\">MarkLogic</a> and developed by \n      <a href=\"https://twitter.com/mbrevoort\">Mike Brevoort</a>.\n    </p>\n \n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/xquery/test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Don't take these too seriously -- the expected results appear to be\n// based on the results of actual runs without any serious manual\n// verification. If a change you made causes them to fail, the test is\n// as likely to wrong as the code.\n\n(function() {\n  var mode = CodeMirror.getMode({tabSize: 4}, \"xquery\");\n  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }\n\n  MT(\"eviltest\",\n     \"[keyword xquery] [keyword version] [variable &quot;1][keyword .][atom 0][keyword -][variable ml&quot;][def&variable ;]      [comment (: this is       : a          \\\"comment\\\" :)]\",\n     \"      [keyword let] [variable $let] [keyword :=] [variable &lt;x] [variable attr][keyword =][variable &quot;value&quot;&gt;&quot;test&quot;&lt;func&gt][def&variable ;function]() [variable $var] {[keyword function]()} {[variable $var]}[variable &lt;][keyword /][variable func&gt;&lt;][keyword /][variable x&gt;]\",\n     \"      [keyword let] [variable $joe][keyword :=][atom 1]\",\n     \"      [keyword return] [keyword element] [variable element] {\",\n     \"          [keyword attribute] [variable attribute] { [atom 1] },\",\n     \"          [keyword element] [variable test] { [variable &#39;a&#39;] },           [keyword attribute] [variable foo] { [variable &quot;bar&quot;] },\",\n     \"          [def&variable fn:doc]()[[ [variable foo][keyword /][variable @bar] [keyword eq] [variable $let] ]],\",\n     \"          [keyword //][variable x] }                 [comment (: a more 'evil' test :)]\",\n     \"      [comment (: Modified Blakeley example (: with nested comment :) ... :)]\",\n     \"      [keyword declare] [variable private] [keyword function] [def&variable local:declare]() {()}[variable ;]\",\n     \"      [keyword declare] [variable private] [keyword function] [def&variable local:private]() {()}[variable ;]\",\n     \"      [keyword declare] [variable private] [keyword function] [def&variable local:function]() {()}[variable ;]\",\n     \"      [keyword declare] [variable private] [keyword function] [def&variable local:local]() {()}[variable ;]\",\n     \"      [keyword let] [variable $let] [keyword :=] [variable &lt;let&gt;let] [variable $let] [keyword :=] [variable &quot;let&quot;&lt;][keyword /let][variable &gt;]\",\n     \"      [keyword return] [keyword element] [variable element] {\",\n     \"          [keyword attribute] [variable attribute] { [keyword try] { [def&variable xdmp:version]() } [keyword catch]([variable $e]) { [def&variable xdmp:log]([variable $e]) } },\",\n     \"          [keyword attribute] [variable fn:doc] { [variable &quot;bar&quot;] [keyword castable] [keyword as] [atom xs:string] },\",\n     \"          [keyword element] [variable text] { [keyword text] { [variable &quot;text&quot;] } },\",\n     \"          [def&variable fn:doc]()[[ [qualifier child::][variable eq][keyword /]([variable @bar] [keyword |] [qualifier attribute::][variable attribute]) [keyword eq] [variable $let] ]],\",\n     \"          [keyword //][variable fn:doc]\",\n     \"      }\");\n\n  MT(\"testEmptySequenceKeyword\",\n     \"[string \\\"foo\\\"] [keyword instance] [keyword of] [keyword empty-sequence]()\");\n\n  MT(\"testMultiAttr\",\n     \"[tag <p ][attribute a1]=[string \\\"foo\\\"] [attribute a2]=[string \\\"bar\\\"][tag >][variable hello] [variable world][tag </p>]\");\n\n  MT(\"test namespaced variable\",\n     \"[keyword declare] [keyword namespace] [variable e] [keyword =] [string \\\"http://example.com/ANamespace\\\"][variable ;declare] [keyword variable] [variable $e:exampleComThisVarIsNotRecognized] [keyword as] [keyword element]([keyword *]) [variable external;]\");\n\n  MT(\"test EQName variable\",\n     \"[keyword declare] [keyword variable] [variable $\\\"http://www.example.com/ns/my\\\":var] [keyword :=] [atom 12][variable ;]\",\n     \"[tag <out>]{[variable $\\\"http://www.example.com/ns/my\\\":var]}[tag </out>]\");\n\n  MT(\"test EQName function\",\n     \"[keyword declare] [keyword function] [def&variable \\\"http://www.example.com/ns/my\\\":fn] ([variable $a] [keyword as] [atom xs:integer]) [keyword as] [atom xs:integer] {\",\n     \"   [variable $a] [keyword +] [atom 2]\",\n     \"}[variable ;]\",\n     \"[tag <out>]{[def&variable \\\"http://www.example.com/ns/my\\\":fn]([atom 12])}[tag </out>]\");\n\n  MT(\"test EQName function with single quotes\",\n     \"[keyword declare] [keyword function] [def&variable 'http://www.example.com/ns/my':fn] ([variable $a] [keyword as] [atom xs:integer]) [keyword as] [atom xs:integer] {\",\n     \"   [variable $a] [keyword +] [atom 2]\",\n     \"}[variable ;]\",\n     \"[tag <out>]{[def&variable 'http://www.example.com/ns/my':fn]([atom 12])}[tag </out>]\");\n\n  MT(\"testProcessingInstructions\",\n     \"[def&variable data]([comment&meta <?target content?>]) [keyword instance] [keyword of] [atom xs:string]\");\n\n  MT(\"testQuoteEscapeDouble\",\n     \"[keyword let] [variable $rootfolder] [keyword :=] [string \\\"c:\\\\builds\\\\winnt\\\\HEAD\\\\qa\\\\scripts\\\\\\\"]\",\n     \"[keyword let] [variable $keysfolder] [keyword :=] [def&variable concat]([variable $rootfolder], [string \\\"keys\\\\\\\"])\");\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/mode/xquery/xquery.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"xquery\", function() {\n\n  // The keywords object is set to the result of this self executing\n  // function. Each keyword is a property of the keywords object whose\n  // value is {type: atype, style: astyle}\n  var keywords = function(){\n    // convenience functions used to build keywords object\n    function kw(type) {return {type: type, style: \"keyword\"};}\n    var operator = kw(\"operator\")\n      , atom = {type: \"atom\", style: \"atom\"}\n      , punctuation = {type: \"punctuation\", style: null}\n      , qualifier = {type: \"axis_specifier\", style: \"qualifier\"};\n\n    // kwObj is what is return from this function at the end\n    var kwObj = {\n      ',': punctuation\n    };\n\n    // a list of 'basic' keywords. For each add a property to kwObj with the value of\n    // {type: basic[i], style: \"keyword\"} e.g. 'after' --> {type: \"after\", style: \"keyword\"}\n    var basic = ['after', 'all', 'allowing', 'ancestor', 'ancestor-or-self', 'any', 'array', 'as',\n    'ascending', 'at', 'attribute', 'base-uri', 'before', 'boundary-space', 'by', 'case', 'cast',\n    'castable', 'catch', 'child', 'collation', 'comment', 'construction', 'contains', 'content',\n    'context', 'copy', 'copy-namespaces', 'count', 'decimal-format', 'declare', 'default', 'delete',\n    'descendant', 'descendant-or-self', 'descending', 'diacritics', 'different', 'distance',\n    'document', 'document-node', 'element', 'else', 'empty', 'empty-sequence', 'encoding', 'end',\n    'entire', 'every', 'exactly', 'except', 'external', 'first', 'following', 'following-sibling',\n    'for', 'from', 'ftand', 'ftnot', 'ft-option', 'ftor', 'function', 'fuzzy', 'greatest', 'group',\n    'if', 'import', 'in', 'inherit', 'insensitive', 'insert', 'instance', 'intersect', 'into',\n    'invoke', 'is', 'item', 'language', 'last', 'lax', 'least', 'let', 'levels', 'lowercase', 'map',\n    'modify', 'module', 'most', 'namespace', 'next', 'no', 'node', 'nodes', 'no-inherit',\n    'no-preserve', 'not', 'occurs', 'of', 'only', 'option', 'order', 'ordered', 'ordering',\n    'paragraph', 'paragraphs', 'parent', 'phrase', 'preceding', 'preceding-sibling', 'preserve',\n    'previous', 'processing-instruction', 'relationship', 'rename', 'replace', 'return',\n    'revalidation', 'same', 'satisfies', 'schema', 'schema-attribute', 'schema-element', 'score',\n    'self', 'sensitive', 'sentence', 'sentences', 'sequence', 'skip', 'sliding', 'some', 'stable',\n    'start', 'stemming', 'stop', 'strict', 'strip', 'switch', 'text', 'then', 'thesaurus', 'times',\n    'to', 'transform', 'treat', 'try', 'tumbling', 'type', 'typeswitch', 'union', 'unordered',\n    'update', 'updating', 'uppercase', 'using', 'validate', 'value', 'variable', 'version',\n    'weight', 'when', 'where', 'wildcards', 'window', 'with', 'without', 'word', 'words', 'xquery'];\n    for(var i=0, l=basic.length; i < l; i++) { kwObj[basic[i]] = kw(basic[i]);};\n\n    // a list of types. For each add a property to kwObj with the value of\n    // {type: \"atom\", style: \"atom\"}\n    var types = ['xs:anyAtomicType', 'xs:anySimpleType', 'xs:anyType', 'xs:anyURI',\n    'xs:base64Binary', 'xs:boolean', 'xs:byte', 'xs:date', 'xs:dateTime', 'xs:dateTimeStamp',\n    'xs:dayTimeDuration', 'xs:decimal', 'xs:double', 'xs:duration', 'xs:ENTITIES', 'xs:ENTITY',\n    'xs:float', 'xs:gDay', 'xs:gMonth', 'xs:gMonthDay', 'xs:gYear', 'xs:gYearMonth', 'xs:hexBinary',\n    'xs:ID', 'xs:IDREF', 'xs:IDREFS', 'xs:int', 'xs:integer', 'xs:item', 'xs:java', 'xs:language',\n    'xs:long', 'xs:Name', 'xs:NCName', 'xs:negativeInteger', 'xs:NMTOKEN', 'xs:NMTOKENS',\n    'xs:nonNegativeInteger', 'xs:nonPositiveInteger', 'xs:normalizedString', 'xs:NOTATION',\n    'xs:numeric', 'xs:positiveInteger', 'xs:precisionDecimal', 'xs:QName', 'xs:short', 'xs:string',\n    'xs:time', 'xs:token', 'xs:unsignedByte', 'xs:unsignedInt', 'xs:unsignedLong',\n    'xs:unsignedShort', 'xs:untyped', 'xs:untypedAtomic', 'xs:yearMonthDuration'];\n    for(var i=0, l=types.length; i < l; i++) { kwObj[types[i]] = atom;};\n\n    // each operator will add a property to kwObj with value of {type: \"operator\", style: \"keyword\"}\n    var operators = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', ':=', '=', '>', '>=', '<', '<=', '.', '|', '?', 'and', 'or', 'div', 'idiv', 'mod', '*', '/', '+', '-'];\n    for(var i=0, l=operators.length; i < l; i++) { kwObj[operators[i]] = operator;};\n\n    // each axis_specifiers will add a property to kwObj with value of {type: \"axis_specifier\", style: \"qualifier\"}\n    var axis_specifiers = [\"self::\", \"attribute::\", \"child::\", \"descendant::\", \"descendant-or-self::\", \"parent::\",\n    \"ancestor::\", \"ancestor-or-self::\", \"following::\", \"preceding::\", \"following-sibling::\", \"preceding-sibling::\"];\n    for(var i=0, l=axis_specifiers.length; i < l; i++) { kwObj[axis_specifiers[i]] = qualifier; };\n\n    return kwObj;\n  }();\n\n  function chain(stream, state, f) {\n    state.tokenize = f;\n    return f(stream, state);\n  }\n\n  // the primary mode tokenizer\n  function tokenBase(stream, state) {\n    var ch = stream.next(),\n        mightBeFunction = false,\n        isEQName = isEQNameAhead(stream);\n\n    // an XML tag (if not in some sub, chained tokenizer)\n    if (ch == \"<\") {\n      if(stream.match(\"!--\", true))\n        return chain(stream, state, tokenXMLComment);\n\n      if(stream.match(\"![CDATA\", false)) {\n        state.tokenize = tokenCDATA;\n        return \"tag\";\n      }\n\n      if(stream.match(\"?\", false)) {\n        return chain(stream, state, tokenPreProcessing);\n      }\n\n      var isclose = stream.eat(\"/\");\n      stream.eatSpace();\n      var tagName = \"\", c;\n      while ((c = stream.eat(/[^\\s\\u00a0=<>\\\"\\'\\/?]/))) tagName += c;\n\n      return chain(stream, state, tokenTag(tagName, isclose));\n    }\n    // start code block\n    else if(ch == \"{\") {\n      pushStateStack(state, { type: \"codeblock\"});\n      return null;\n    }\n    // end code block\n    else if(ch == \"}\") {\n      popStateStack(state);\n      return null;\n    }\n    // if we're in an XML block\n    else if(isInXmlBlock(state)) {\n      if(ch == \">\")\n        return \"tag\";\n      else if(ch == \"/\" && stream.eat(\">\")) {\n        popStateStack(state);\n        return \"tag\";\n      }\n      else\n        return \"variable\";\n    }\n    // if a number\n    else if (/\\d/.test(ch)) {\n      stream.match(/^\\d*(?:\\.\\d*)?(?:E[+\\-]?\\d+)?/);\n      return \"atom\";\n    }\n    // comment start\n    else if (ch === \"(\" && stream.eat(\":\")) {\n      pushStateStack(state, { type: \"comment\"});\n      return chain(stream, state, tokenComment);\n    }\n    // quoted string\n    else if (!isEQName && (ch === '\"' || ch === \"'\"))\n      return chain(stream, state, tokenString(ch));\n    // variable\n    else if(ch === \"$\") {\n      return chain(stream, state, tokenVariable);\n    }\n    // assignment\n    else if(ch ===\":\" && stream.eat(\"=\")) {\n      return \"keyword\";\n    }\n    // open paren\n    else if(ch === \"(\") {\n      pushStateStack(state, { type: \"paren\"});\n      return null;\n    }\n    // close paren\n    else if(ch === \")\") {\n      popStateStack(state);\n      return null;\n    }\n    // open paren\n    else if(ch === \"[\") {\n      pushStateStack(state, { type: \"bracket\"});\n      return null;\n    }\n    // close paren\n    else if(ch === \"]\") {\n      popStateStack(state);\n      return null;\n    }\n    else {\n      var known = keywords.propertyIsEnumerable(ch) && keywords[ch];\n\n      // if there's a EQName ahead, consume the rest of the string portion, it's likely a function\n      if(isEQName && ch === '\\\"') while(stream.next() !== '\"'){}\n      if(isEQName && ch === '\\'') while(stream.next() !== '\\''){}\n\n      // gobble up a word if the character is not known\n      if(!known) stream.eatWhile(/[\\w\\$_-]/);\n\n      // gobble a colon in the case that is a lib func type call fn:doc\n      var foundColon = stream.eat(\":\");\n\n      // if there's not a second colon, gobble another word. Otherwise, it's probably an axis specifier\n      // which should get matched as a keyword\n      if(!stream.eat(\":\") && foundColon) {\n        stream.eatWhile(/[\\w\\$_-]/);\n      }\n      // if the next non whitespace character is an open paren, this is probably a function (if not a keyword of other sort)\n      if(stream.match(/^[ \\t]*\\(/, false)) {\n        mightBeFunction = true;\n      }\n      // is the word a keyword?\n      var word = stream.current();\n      known = keywords.propertyIsEnumerable(word) && keywords[word];\n\n      // if we think it's a function call but not yet known,\n      // set style to variable for now for lack of something better\n      if(mightBeFunction && !known) known = {type: \"function_call\", style: \"variable def\"};\n\n      // if the previous word was element, attribute, axis specifier, this word should be the name of that\n      if(isInXmlConstructor(state)) {\n        popStateStack(state);\n        return \"variable\";\n      }\n      // as previously checked, if the word is element,attribute, axis specifier, call it an \"xmlconstructor\" and\n      // push the stack so we know to look for it on the next word\n      if(word == \"element\" || word == \"attribute\" || known.type == \"axis_specifier\") pushStateStack(state, {type: \"xmlconstructor\"});\n\n      // if the word is known, return the details of that else just call this a generic 'word'\n      return known ? known.style : \"variable\";\n    }\n  }\n\n  // handle comments, including nested\n  function tokenComment(stream, state) {\n    var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;\n    while (ch = stream.next()) {\n      if (ch == \")\" && maybeEnd) {\n        if(nestedCount > 0)\n          nestedCount--;\n        else {\n          popStateStack(state);\n          break;\n        }\n      }\n      else if(ch == \":\" && maybeNested) {\n        nestedCount++;\n      }\n      maybeEnd = (ch == \":\");\n      maybeNested = (ch == \"(\");\n    }\n\n    return \"comment\";\n  }\n\n  // tokenizer for string literals\n  // optionally pass a tokenizer function to set state.tokenize back to when finished\n  function tokenString(quote, f) {\n    return function(stream, state) {\n      var ch;\n\n      if(isInString(state) && stream.current() == quote) {\n        popStateStack(state);\n        if(f) state.tokenize = f;\n        return \"string\";\n      }\n\n      pushStateStack(state, { type: \"string\", name: quote, tokenize: tokenString(quote, f) });\n\n      // if we're in a string and in an XML block, allow an embedded code block\n      if(stream.match(\"{\", false) && isInXmlAttributeBlock(state)) {\n        state.tokenize = tokenBase;\n        return \"string\";\n      }\n\n\n      while (ch = stream.next()) {\n        if (ch ==  quote) {\n          popStateStack(state);\n          if(f) state.tokenize = f;\n          break;\n        }\n        else {\n          // if we're in a string and in an XML block, allow an embedded code block in an attribute\n          if(stream.match(\"{\", false) && isInXmlAttributeBlock(state)) {\n            state.tokenize = tokenBase;\n            return \"string\";\n          }\n\n        }\n      }\n\n      return \"string\";\n    };\n  }\n\n  // tokenizer for variables\n  function tokenVariable(stream, state) {\n    var isVariableChar = /[\\w\\$_-]/;\n\n    // a variable may start with a quoted EQName so if the next character is quote, consume to the next quote\n    if(stream.eat(\"\\\"\")) {\n      while(stream.next() !== '\\\"'){};\n      stream.eat(\":\");\n    } else {\n      stream.eatWhile(isVariableChar);\n      if(!stream.match(\":=\", false)) stream.eat(\":\");\n    }\n    stream.eatWhile(isVariableChar);\n    state.tokenize = tokenBase;\n    return \"variable\";\n  }\n\n  // tokenizer for XML tags\n  function tokenTag(name, isclose) {\n    return function(stream, state) {\n      stream.eatSpace();\n      if(isclose && stream.eat(\">\")) {\n        popStateStack(state);\n        state.tokenize = tokenBase;\n        return \"tag\";\n      }\n      // self closing tag without attributes?\n      if(!stream.eat(\"/\"))\n        pushStateStack(state, { type: \"tag\", name: name, tokenize: tokenBase});\n      if(!stream.eat(\">\")) {\n        state.tokenize = tokenAttribute;\n        return \"tag\";\n      }\n      else {\n        state.tokenize = tokenBase;\n      }\n      return \"tag\";\n    };\n  }\n\n  // tokenizer for XML attributes\n  function tokenAttribute(stream, state) {\n    var ch = stream.next();\n\n    if(ch == \"/\" && stream.eat(\">\")) {\n      if(isInXmlAttributeBlock(state)) popStateStack(state);\n      if(isInXmlBlock(state)) popStateStack(state);\n      return \"tag\";\n    }\n    if(ch == \">\") {\n      if(isInXmlAttributeBlock(state)) popStateStack(state);\n      return \"tag\";\n    }\n    if(ch == \"=\")\n      return null;\n    // quoted string\n    if (ch == '\"' || ch == \"'\")\n      return chain(stream, state, tokenString(ch, tokenAttribute));\n\n    if(!isInXmlAttributeBlock(state))\n      pushStateStack(state, { type: \"attribute\", tokenize: tokenAttribute});\n\n    stream.eat(/[a-zA-Z_:]/);\n    stream.eatWhile(/[-a-zA-Z0-9_:.]/);\n    stream.eatSpace();\n\n    // the case where the attribute has not value and the tag was closed\n    if(stream.match(\">\", false) || stream.match(\"/\", false)) {\n      popStateStack(state);\n      state.tokenize = tokenBase;\n    }\n\n    return \"attribute\";\n  }\n\n  // handle comments, including nested\n  function tokenXMLComment(stream, state) {\n    var ch;\n    while (ch = stream.next()) {\n      if (ch == \"-\" && stream.match(\"->\", true)) {\n        state.tokenize = tokenBase;\n        return \"comment\";\n      }\n    }\n  }\n\n\n  // handle CDATA\n  function tokenCDATA(stream, state) {\n    var ch;\n    while (ch = stream.next()) {\n      if (ch == \"]\" && stream.match(\"]\", true)) {\n        state.tokenize = tokenBase;\n        return \"comment\";\n      }\n    }\n  }\n\n  // handle preprocessing instructions\n  function tokenPreProcessing(stream, state) {\n    var ch;\n    while (ch = stream.next()) {\n      if (ch == \"?\" && stream.match(\">\", true)) {\n        state.tokenize = tokenBase;\n        return \"comment meta\";\n      }\n    }\n  }\n\n\n  // functions to test the current context of the state\n  function isInXmlBlock(state) { return isIn(state, \"tag\"); }\n  function isInXmlAttributeBlock(state) { return isIn(state, \"attribute\"); }\n  function isInXmlConstructor(state) { return isIn(state, \"xmlconstructor\"); }\n  function isInString(state) { return isIn(state, \"string\"); }\n\n  function isEQNameAhead(stream) {\n    // assume we've already eaten a quote (\")\n    if(stream.current() === '\"')\n      return stream.match(/^[^\\\"]+\\\"\\:/, false);\n    else if(stream.current() === '\\'')\n      return stream.match(/^[^\\\"]+\\'\\:/, false);\n    else\n      return false;\n  }\n\n  function isIn(state, type) {\n    return (state.stack.length && state.stack[state.stack.length - 1].type == type);\n  }\n\n  function pushStateStack(state, newState) {\n    state.stack.push(newState);\n  }\n\n  function popStateStack(state) {\n    state.stack.pop();\n    var reinstateTokenize = state.stack.length && state.stack[state.stack.length-1].tokenize;\n    state.tokenize = reinstateTokenize || tokenBase;\n  }\n\n  // the interface for the mode API\n  return {\n    startState: function() {\n      return {\n        tokenize: tokenBase,\n        cc: [],\n        stack: []\n      };\n    },\n\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      var style = state.tokenize(stream, state);\n      return style;\n    },\n\n    blockCommentStart: \"(:\",\n    blockCommentEnd: \":)\"\n\n  };\n\n});\n\nCodeMirror.defineMIME(\"application/xquery\", \"xquery\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/yacas/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: yacas mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=stylesheet href=../../lib/codemirror.css>\n<script src=../../lib/codemirror.js></script>\n<script src=../../addon/edit/matchbrackets.js></script>\n<script src=yacas.js></script>\n<style type=text/css>\n  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}\n</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">yacas</a>\n  </ul>\n</div>\n\n<article>\n<h2>yacas mode</h2>\n\n\n<textarea id=\"yacasCode\">\n// example yacas code\nGraph(edges_IsList) <-- [\n    Local(v, e, f, t);\n\n    vertices := {};\n\n    ForEach (e, edges) [\n        If (IsList(e), e := Head(e));\n        {f, t} := Tail(Listify(e));\n\n        DestructiveAppend(vertices, f);\n        DestructiveAppend(vertices, t);\n    ];\n\n    Graph(RemoveDuplicates(vertices), edges);\n];\n\n10 # IsGraph(Graph(vertices_IsList, edges_IsList)) <-- True;\n20 # IsGraph(_x) <-- False;\n\nEdges(Graph(vertices_IsList, edges_IsList)) <-- edges;\nVertices(Graph(vertices_IsList, edges_IsList)) <-- vertices;\n\nAdjacencyList(g_IsGraph) <-- [\n    Local(l, vertices, edges, e, op, f, t);\n\n    l := Association'Create();\n\n    vertices := Vertices(g);\n    ForEach (v, vertices)\n        Association'Set(l, v, {});\n\n    edges := Edges(g);\n\n    ForEach(e, edges) [\n        If (IsList(e), e := Head(e));\n        {op, f, t} := Listify(e);\n        DestructiveAppend(Association'Get(l, f), t);\n        If (String(op) = \"<->\", DestructiveAppend(Association'Get(l, t), f));\n    ];\n\n    l;\n];\n</textarea>\n\n<script>\n  var yacasEditor = CodeMirror.fromTextArea(document.getElementById('yacasCode'), {\n    mode: 'text/x-yacas',\n    lineNumbers: true,\n    matchBrackets: true\n  });\n</script>\n\n<p><strong>MIME types defined:</strong> <code>text/x-yacas</code> (yacas).</p>\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/yacas/yacas.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// Yacas mode copyright (c) 2015 by Grzegorz Mazur\n// Loosely based on mathematica mode by Calin Barbat\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode('yacas', function(_config, _parserConfig) {\n\n  function words(str) {\n    var obj = {}, words = str.split(\" \");\n    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n    return obj;\n  }\n\n  var bodiedOps = words(\"Assert BackQuote D Defun Deriv For ForEach FromFile \" +\n                        \"FromString Function Integrate InverseTaylor Limit \" +\n                        \"LocalSymbols Macro MacroRule MacroRulePattern \" +\n                        \"NIntegrate Rule RulePattern Subst TD TExplicitSum \" +\n                        \"TSum Taylor Taylor1 Taylor2 Taylor3 ToFile \" +\n                        \"ToStdout ToString TraceRule Until While\");\n\n  // patterns\n  var pFloatForm  = \"(?:(?:\\\\.\\\\d+|\\\\d+\\\\.\\\\d*|\\\\d+)(?:[eE][+-]?\\\\d+)?)\";\n  var pIdentifier = \"(?:[a-zA-Z\\\\$'][a-zA-Z0-9\\\\$']*)\";\n\n  // regular expressions\n  var reFloatForm    = new RegExp(pFloatForm);\n  var reIdentifier   = new RegExp(pIdentifier);\n  var rePattern      = new RegExp(pIdentifier + \"?_\" + pIdentifier);\n  var reFunctionLike = new RegExp(pIdentifier + \"\\\\s*\\\\(\");\n\n  function tokenBase(stream, state) {\n    var ch;\n\n    // get next character\n    ch = stream.next();\n\n    // string\n    if (ch === '\"') {\n      state.tokenize = tokenString;\n      return state.tokenize(stream, state);\n    }\n\n    // comment\n    if (ch === '/') {\n      if (stream.eat('*')) {\n        state.tokenize = tokenComment;\n        return state.tokenize(stream, state);\n      }\n      if (stream.eat(\"/\")) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n    }\n\n    // go back one character\n    stream.backUp(1);\n\n    // update scope info\n    var m = stream.match(/^(\\w+)\\s*\\(/, false);\n    if (m !== null && bodiedOps.hasOwnProperty(m[1]))\n      state.scopes.push('bodied');\n\n    var scope = currentScope(state);\n\n    if (scope === 'bodied' && ch === '[')\n      state.scopes.pop();\n\n    if (ch === '[' || ch === '{' || ch === '(')\n      state.scopes.push(ch);\n\n    scope = currentScope(state);\n\n    if (scope === '[' && ch === ']' ||\n        scope === '{' && ch === '}' ||\n        scope === '(' && ch === ')')\n      state.scopes.pop();\n\n    if (ch === ';') {\n      while (scope === 'bodied') {\n        state.scopes.pop();\n        scope = currentScope(state);\n      }\n    }\n\n    // look for ordered rules\n    if (stream.match(/\\d+ *#/, true, false)) {\n      return 'qualifier';\n    }\n\n    // look for numbers\n    if (stream.match(reFloatForm, true, false)) {\n      return 'number';\n    }\n\n    // look for placeholders\n    if (stream.match(rePattern, true, false)) {\n      return 'variable-3';\n    }\n\n    // match all braces separately\n    if (stream.match(/(?:\\[|\\]|{|}|\\(|\\))/, true, false)) {\n      return 'bracket';\n    }\n\n    // literals looking like function calls\n    if (stream.match(reFunctionLike, true, false)) {\n      stream.backUp(1);\n      return 'variable';\n    }\n\n    // all other identifiers\n    if (stream.match(reIdentifier, true, false)) {\n      return 'variable-2';\n    }\n\n    // operators; note that operators like @@ or /; are matched separately for each symbol.\n    if (stream.match(/(?:\\\\|\\+|\\-|\\*|\\/|,|;|\\.|:|@|~|=|>|<|&|\\||_|`|'|\\^|\\?|!|%|#)/, true, false)) {\n      return 'operator';\n    }\n\n    // everything else is an error\n    return 'error';\n  }\n\n  function tokenString(stream, state) {\n    var next, end = false, escaped = false;\n    while ((next = stream.next()) != null) {\n      if (next === '\"' && !escaped) {\n        end = true;\n        break;\n      }\n      escaped = !escaped && next === '\\\\';\n    }\n    if (end && !escaped) {\n      state.tokenize = tokenBase;\n    }\n    return 'string';\n  };\n\n  function tokenComment(stream, state) {\n    var prev, next;\n    while((next = stream.next()) != null) {\n      if (prev === '*' && next === '/') {\n        state.tokenize = tokenBase;\n        break;\n      }\n      prev = next;\n    }\n    return 'comment';\n  }\n\n  function currentScope(state) {\n    var scope = null;\n    if (state.scopes.length > 0)\n      scope = state.scopes[state.scopes.length - 1];\n    return scope;\n  }\n\n  return {\n    startState: function() {\n      return {\n        tokenize: tokenBase,\n        scopes: []\n      };\n    },\n    token: function(stream, state) {\n      if (stream.eatSpace()) return null;\n      return state.tokenize(stream, state);\n    },\n    indent: function(state, textAfter) {\n      if (state.tokenize !== tokenBase && state.tokenize !== null)\n        return CodeMirror.Pass;\n\n      var delta = 0;\n      if (textAfter === ']' || textAfter === '];' ||\n          textAfter === '}' || textAfter === '};' ||\n          textAfter === ');')\n        delta = -1;\n\n      return (state.scopes.length + delta) * _config.indentUnit;\n    },\n    electricChars: \"{}[]();\",\n    blockCommentStart: \"/*\",\n    blockCommentEnd: \"*/\",\n    lineComment: \"//\"\n  };\n});\n\nCodeMirror.defineMIME('text/x-yacas', {\n  name: 'yacas'\n});\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/yaml/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: YAML mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"yaml.js\"></script>\n<style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">YAML</a>\n  </ul>\n</div>\n\n<article>\n<h2>YAML mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n--- # Favorite movies\n- Casablanca\n- North by Northwest\n- The Man Who Wasn't There\n--- # Shopping list\n[milk, pumpkin pie, eggs, juice]\n--- # Indented Blocks, common in YAML data files, use indentation and new lines to separate the key: value pairs\n  name: John Smith\n  age: 33\n--- # Inline Blocks, common in YAML data streams, use commas to separate the key: value pairs between braces\n{name: John Smith, age: 33}\n---\nreceipt:     Oz-Ware Purchase Invoice\ndate:        2007-08-06\ncustomer:\n    given:   Dorothy\n    family:  Gale\n\nitems:\n    - part_no:   A4786\n      descrip:   Water Bucket (Filled)\n      price:     1.47\n      quantity:  4\n\n    - part_no:   E1628\n      descrip:   High Heeled \"Ruby\" Slippers\n      size:       8\n      price:     100.27\n      quantity:  1\n\nbill-to:  &id001\n    street: |\n            123 Tornado Alley\n            Suite 16\n    city:   East Centerville\n    state:  KS\n\nship-to:  *id001\n\nspecialDelivery:  >\n    Follow the Yellow Brick\n    Road to the Emerald City.\n    Pay no attention to the\n    man behind the curtain.\n...\n</textarea></form>\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {});\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-yaml</code>.</p>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/yaml/yaml.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"yaml\", function() {\n\n  var cons = ['true', 'false', 'on', 'off', 'yes', 'no'];\n  var keywordRegex = new RegExp(\"\\\\b((\"+cons.join(\")|(\")+\"))$\", 'i');\n\n  return {\n    token: function(stream, state) {\n      var ch = stream.peek();\n      var esc = state.escaped;\n      state.escaped = false;\n      /* comments */\n      if (ch == \"#\" && (stream.pos == 0 || /\\s/.test(stream.string.charAt(stream.pos - 1)))) {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n\n      if (stream.match(/^('([^']|\\\\.)*'?|\"([^\"]|\\\\.)*\"?)/))\n        return \"string\";\n\n      if (state.literal && stream.indentation() > state.keyCol) {\n        stream.skipToEnd(); return \"string\";\n      } else if (state.literal) { state.literal = false; }\n      if (stream.sol()) {\n        state.keyCol = 0;\n        state.pair = false;\n        state.pairStart = false;\n        /* document start */\n        if(stream.match(/---/)) { return \"def\"; }\n        /* document end */\n        if (stream.match(/\\.\\.\\./)) { return \"def\"; }\n        /* array list item */\n        if (stream.match(/\\s*-\\s+/)) { return 'meta'; }\n      }\n      /* inline pairs/lists */\n      if (stream.match(/^(\\{|\\}|\\[|\\])/)) {\n        if (ch == '{')\n          state.inlinePairs++;\n        else if (ch == '}')\n          state.inlinePairs--;\n        else if (ch == '[')\n          state.inlineList++;\n        else\n          state.inlineList--;\n        return 'meta';\n      }\n\n      /* list seperator */\n      if (state.inlineList > 0 && !esc && ch == ',') {\n        stream.next();\n        return 'meta';\n      }\n      /* pairs seperator */\n      if (state.inlinePairs > 0 && !esc && ch == ',') {\n        state.keyCol = 0;\n        state.pair = false;\n        state.pairStart = false;\n        stream.next();\n        return 'meta';\n      }\n\n      /* start of value of a pair */\n      if (state.pairStart) {\n        /* block literals */\n        if (stream.match(/^\\s*(\\||\\>)\\s*/)) { state.literal = true; return 'meta'; };\n        /* references */\n        if (stream.match(/^\\s*(\\&|\\*)[a-z0-9\\._-]+\\b/i)) { return 'variable-2'; }\n        /* numbers */\n        if (state.inlinePairs == 0 && stream.match(/^\\s*-?[0-9\\.\\,]+\\s?$/)) { return 'number'; }\n        if (state.inlinePairs > 0 && stream.match(/^\\s*-?[0-9\\.\\,]+\\s?(?=(,|}))/)) { return 'number'; }\n        /* keywords */\n        if (stream.match(keywordRegex)) { return 'keyword'; }\n      }\n\n      /* pairs (associative arrays) -> key */\n      if (!state.pair && stream.match(/^\\s*(?:[,\\[\\]{}&*!|>'\"%@`][^\\s'\":]|[^,\\[\\]{}#&*!|>'\"%@`])[^#]*?(?=\\s*:($|\\s))/)) {\n        state.pair = true;\n        state.keyCol = stream.indentation();\n        return \"atom\";\n      }\n      if (state.pair && stream.match(/^:\\s*/)) { state.pairStart = true; return 'meta'; }\n\n      /* nothing found, continue */\n      state.pairStart = false;\n      state.escaped = (ch == '\\\\');\n      stream.next();\n      return null;\n    },\n    startState: function() {\n      return {\n        pair: false,\n        pairStart: false,\n        keyCol: 0,\n        inlinePairs: 0,\n        inlineList: 0,\n        literal: false,\n        escaped: false\n      };\n    },\n    lineComment: \"#\",\n    fold: \"indent\"\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-yaml\", \"yaml\");\nCodeMirror.defineMIME(\"text/yaml\", \"yaml\");\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/yaml-frontmatter/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: YAML front matter mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/mode/overlay.js\"></script>\n<script src=\"../markdown/markdown.js\"></script>\n<script src=\"../gfm/gfm.js\"></script>\n<script src=\"../yaml/yaml.js\"></script>\n<script src=\"yaml-frontmatter.js\"></script>\n<style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">YAML-Frontmatter</a>\n  </ul>\n</div>\n\n<article>\n<h2>YAML front matter mode</h2>\n<form><textarea id=\"code\" name=\"code\">\n---\nreceipt:     Oz-Ware Purchase Invoice\ndate:        2007-08-06\ncustomer:\n    given:   Dorothy\n    family:  Gale\n\nitems:\n    - part_no:   A4786\n      descrip:   Water Bucket (Filled)\n      price:     1.47\n      quantity:  4\n\n    - part_no:   E1628\n      descrip:   High Heeled \"Ruby\" Slippers\n      size:       8\n      price:     100.27\n      quantity:  1\n\nbill-to:  &id001\n    street: |\n            123 Tornado Alley\n            Suite 16\n    city:   East Centerville\n    state:  KS\n\nship-to:  *id001\n\nspecialDelivery:  >\n    Follow the Yellow Brick\n    Road to the Emerald City.\n    Pay no attention to the\n    man behind the curtain.\n---\n\nGitHub Flavored Markdown\n========================\n\nEverything from markdown plus GFM features:\n\n## URL autolinking\n\nUnderscores_are_allowed_between_words.\n\n## Strikethrough text\n\nGFM adds syntax to strikethrough text, which is missing from standard Markdown.\n\n~~Mistaken text.~~\n~~**works with other formatting**~~\n\n~~spans across\nlines~~\n\n## Fenced code blocks (and syntax highlighting)\n\n```javascript\nfor (var i = 0; i &lt; items.length; i++) {\n    console.log(items[i], i); // log them\n}\n```\n\n## Task Lists\n\n- [ ] Incomplete task list item\n- [x] **Completed** task list item\n\n## A bit of GitHub spice\n\n* SHA: be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2\n* User@SHA ref: mojombo@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2\n* User/Project@SHA: mojombo/god@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2\n* \\#Num: #1\n* User/#Num: mojombo#1\n* User/Project#Num: mojombo/god#1\n\nSee http://github.github.com/github-flavored-markdown/.\n</textarea></form>\n\n<p>Defines a mode that parses\na <a href=\"http://jekyllrb.com/docs/frontmatter/\">YAML frontmatter</a>\nat the start of a file, switching to a base mode at the end of that.\nTakes a mode configuration option <code>base</code> to configure the\nbase mode, which defaults to <code>\"gfm\"</code>.</p>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {mode: \"yaml-frontmatter\"});\n    </script>\n\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/yaml-frontmatter/yaml-frontmatter.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function (mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"), require(\"../yaml/yaml\"))\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\", \"../yaml/yaml\"], mod)\n  else // Plain browser env\n    mod(CodeMirror)\n})(function (CodeMirror) {\n\n  var START = 0, FRONTMATTER = 1, BODY = 2\n\n  // a mixed mode for Markdown text with an optional YAML front matter\n  CodeMirror.defineMode(\"yaml-frontmatter\", function (config, parserConfig) {\n    var yamlMode = CodeMirror.getMode(config, \"yaml\")\n    var innerMode = CodeMirror.getMode(config, parserConfig && parserConfig.base || \"gfm\")\n\n    function curMode(state) {\n      return state.state == BODY ? innerMode : yamlMode\n    }\n\n    return {\n      startState: function () {\n        return {\n          state: START,\n          inner: CodeMirror.startState(yamlMode)\n        }\n      },\n      copyState: function (state) {\n        return {\n          state: state.state,\n          inner: CodeMirror.copyState(curMode(state), state.inner)\n        }\n      },\n      token: function (stream, state) {\n        if (state.state == START) {\n          if (stream.match(/---/, false)) {\n            state.state = FRONTMATTER\n            return yamlMode.token(stream, state.inner)\n          } else {\n            state.state = BODY\n            state.inner = CodeMirror.startState(innerMode)\n            return innerMode.token(stream, state.inner)\n          }\n        } else if (state.state == FRONTMATTER) {\n          var end = stream.sol() && stream.match(/---/, false)\n          var style = yamlMode.token(stream, state.inner)\n          if (end) {\n            state.state = BODY\n            state.inner = CodeMirror.startState(innerMode)\n          }\n          return style\n        } else {\n          return innerMode.token(stream, state.inner)\n        }\n      },\n      innerMode: function (state) {\n        return {mode: curMode(state), state: state.inner}\n      },\n      blankLine: function (state) {\n        var mode = curMode(state)\n        if (mode.blankLine) return mode.blankLine(state.inner)\n      }\n    }\n  })\n});\n"
  },
  {
    "path": "third_party/CodeMirror/mode/z80/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Z80 assembly mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"z80.js\"></script>\n<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Z80 assembly</a>\n  </ul>\n</div>\n\n<article>\n<h2>Z80 assembly mode</h2>\n\n\n<div><textarea id=\"code\" name=\"code\">\n#include    \"ti83plus.inc\"\n#define     progStart   $9D95\n    .org progStart-2\n    .db $BB,$6D\n\n    bcall(_ClrLCDFull)\n    ld hl,0\n    ld (CurCol),hl\n    ld hl,Message\n    bcall(_PutS) ; Displays the string\n    bcall(_NewLine)\n    ret\nMessage:\n    .db \"Hello world!\",0\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        lineNumbers: true\n      });\n    </script>\n\n    <p><strong>MIME types defined:</strong> <code>text/x-z80</code>, <code>text/x-ez80</code>.</p>\n  </article>\n"
  },
  {
    "path": "third_party/CodeMirror/mode/z80/z80.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n  mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n  define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n  mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode('z80', function(_config, parserConfig) {\n  var ez80 = parserConfig.ez80;\n  var keywords1, keywords2;\n  if (ez80) {\n    keywords1 = /^(exx?|(ld|cp)([di]r?)?|[lp]ea|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|[de]i|halt|im|in([di]mr?|ir?|irx|2r?)|ot(dmr?|[id]rx|imr?)|out(0?|[di]r?|[di]2r?)|tst(io)?|slp)(\\.([sl]?i)?[sl])?\\b/i;\n    keywords2 = /^(((call|j[pr]|rst|ret[in]?)(\\.([sl]?i)?[sl])?)|(rs|st)mix)\\b/i;\n  } else {\n    keywords1 = /^(exx?|(ld|cp|in)([di]r?)?|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|rst|[de]i|halt|im|ot[di]r|out[di]?)\\b/i;\n    keywords2 = /^(call|j[pr]|ret[in]?|b_?(call|jump))\\b/i;\n  }\n\n  var variables1 = /^(af?|bc?|c|de?|e|hl?|l|i[xy]?|r|sp)\\b/i;\n  var variables2 = /^(n?[zc]|p[oe]?|m)\\b/i;\n  var errors = /^([hl][xy]|i[xy][hl]|slia|sll)\\b/i;\n  var numbers = /^([\\da-f]+h|[0-7]+o|[01]+b|\\d+d?)\\b/i;\n\n  return {\n    startState: function() {\n      return {\n        context: 0\n      };\n    },\n    token: function(stream, state) {\n      if (!stream.column())\n        state.context = 0;\n\n      if (stream.eatSpace())\n        return null;\n\n      var w;\n\n      if (stream.eatWhile(/\\w/)) {\n        if (ez80 && stream.eat('.')) {\n          stream.eatWhile(/\\w/);\n        }\n        w = stream.current();\n\n        if (stream.indentation()) {\n          if ((state.context == 1 || state.context == 4) && variables1.test(w)) {\n            state.context = 4;\n            return 'var2';\n          }\n\n          if (state.context == 2 && variables2.test(w)) {\n            state.context = 4;\n            return 'var3';\n          }\n\n          if (keywords1.test(w)) {\n            state.context = 1;\n            return 'keyword';\n          } else if (keywords2.test(w)) {\n            state.context = 2;\n            return 'keyword';\n          } else if (state.context == 4 && numbers.test(w)) {\n            return 'number';\n          }\n\n          if (errors.test(w))\n            return 'error';\n        } else if (stream.match(numbers)) {\n          return 'number';\n        } else {\n          return null;\n        }\n      } else if (stream.eat(';')) {\n        stream.skipToEnd();\n        return 'comment';\n      } else if (stream.eat('\"')) {\n        while (w = stream.next()) {\n          if (w == '\"')\n            break;\n\n          if (w == '\\\\')\n            stream.next();\n        }\n        return 'string';\n      } else if (stream.eat('\\'')) {\n        if (stream.match(/\\\\?.'/))\n          return 'number';\n      } else if (stream.eat('.') || stream.sol() && stream.eat('#')) {\n        state.context = 5;\n\n        if (stream.eatWhile(/\\w/))\n          return 'def';\n      } else if (stream.eat('$')) {\n        if (stream.eatWhile(/[\\da-f]/i))\n          return 'number';\n      } else if (stream.eat('%')) {\n        if (stream.eatWhile(/[01]/))\n          return 'number';\n      } else {\n        stream.next();\n      }\n      return null;\n    }\n  };\n});\n\nCodeMirror.defineMIME(\"text/x-z80\", \"z80\");\nCodeMirror.defineMIME(\"text/x-ez80\", { name: \"z80\", ez80: true });\n\n});\n"
  },
  {
    "path": "third_party/CodeMirror/package.json",
    "content": "{\n  \"name\": \"codemirror\",\n  \"version\": \"5.43.0\",\n  \"main\": \"lib/codemirror.js\",\n  \"style\": \"lib/codemirror.css\",\n  \"author\": {\n    \"name\": \"Marijn Haverbeke\",\n    \"email\": \"marijnh@gmail.com\",\n    \"url\": \"http://marijnhaverbeke.nl\"\n  },\n  \"description\": \"Full-featured in-browser code editor\",\n  \"license\": \"MIT\",\n  \"directories\": {\n    \"lib\": \"./lib\"\n  },\n  \"scripts\": {\n    \"build\": \"rollup -c\",\n    \"watch\": \"rollup -w -c\",\n    \"prepare\": \"npm run-script build\",\n    \"test\": \"node ./test/run.js\",\n    \"lint\": \"bin/lint\"\n  },\n  \"devDependencies\": {\n    \"blint\": \"^1\",\n    \"node-static\": \"0.7.11\",\n    \"phantomjs-prebuilt\": \"^2.1.12\",\n    \"rollup\": \"^0.66.2\",\n    \"rollup-plugin-buble\": \"^0.19.2\",\n    \"rollup-watch\": \"^4.3.1\"\n  },\n  \"bugs\": \"http://github.com/codemirror/CodeMirror/issues\",\n  \"keywords\": [\n    \"JavaScript\",\n    \"CodeMirror\",\n    \"Editor\"\n  ],\n  \"homepage\": \"https://codemirror.net\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/codemirror/CodeMirror.git\"\n  },\n  \"jspm\": {\n    \"directories\": {},\n    \"dependencies\": {},\n    \"devDependencies\": {}\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/rollup.config.js",
    "content": "import buble from 'rollup-plugin-buble';\n\nexport default {\n  input: \"src/codemirror.js\",\n  output: {\n    banner: `// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// This is CodeMirror (https://codemirror.net), a code editor\n// implemented in JavaScript on top of the browser's DOM.\n//\n// You can find some technical background for some of the code below\n// at http://marijnhaverbeke.nl/blog/#cm-internals .\n`,\n    format: \"umd\",\n    file: \"lib/codemirror.js\",\n    name: \"CodeMirror\"\n  },\n  plugins: [ buble({namedFunctionExpressions: false}) ]\n};\n"
  },
  {
    "path": "third_party/CodeMirror/src/codemirror.js",
    "content": "import { CodeMirror } from \"./edit/main.js\"\n\nexport default CodeMirror\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/Display.js",
    "content": "import { gecko, ie, ie_version, mobile, webkit } from \"../util/browser.js\"\nimport { elt, eltP } from \"../util/dom.js\"\nimport { scrollerGap } from \"../util/misc.js\"\n\n// The display handles the DOM integration, both for input reading\n// and content drawing. It holds references to DOM nodes and\n// display-related state.\n\nexport function Display(place, doc, input) {\n  let d = this\n  this.input = input\n\n  // Covers bottom-right square when both scrollbars are present.\n  d.scrollbarFiller = elt(\"div\", null, \"CodeMirror-scrollbar-filler\")\n  d.scrollbarFiller.setAttribute(\"cm-not-content\", \"true\")\n  // Covers bottom of gutter when coverGutterNextToScrollbar is on\n  // and h scrollbar is present.\n  d.gutterFiller = elt(\"div\", null, \"CodeMirror-gutter-filler\")\n  d.gutterFiller.setAttribute(\"cm-not-content\", \"true\")\n  // Will contain the actual code, positioned to cover the viewport.\n  d.lineDiv = eltP(\"div\", null, \"CodeMirror-code\")\n  // Elements are added to these to represent selection and cursors.\n  d.selectionDiv = elt(\"div\", null, null, \"position: relative; z-index: 1\")\n  d.cursorDiv = elt(\"div\", null, \"CodeMirror-cursors\")\n  // A visibility: hidden element used to find the size of things.\n  d.measure = elt(\"div\", null, \"CodeMirror-measure\")\n  // When lines outside of the viewport are measured, they are drawn in this.\n  d.lineMeasure = elt(\"div\", null, \"CodeMirror-measure\")\n  // Wraps everything that needs to exist inside the vertically-padded coordinate system\n  d.lineSpace = eltP(\"div\", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],\n                    null, \"position: relative; outline: none\")\n  let lines = eltP(\"div\", [d.lineSpace], \"CodeMirror-lines\")\n  // Moved around its parent to cover visible view.\n  d.mover = elt(\"div\", [lines], null, \"position: relative\")\n  // Set to the height of the document, allowing scrolling.\n  d.sizer = elt(\"div\", [d.mover], \"CodeMirror-sizer\")\n  d.sizerWidth = null\n  // Behavior of elts with overflow: auto and padding is\n  // inconsistent across browsers. This is used to ensure the\n  // scrollable area is big enough.\n  d.heightForcer = elt(\"div\", null, null, \"position: absolute; height: \" + scrollerGap + \"px; width: 1px;\")\n  // Will contain the gutters, if any.\n  d.gutters = elt(\"div\", null, \"CodeMirror-gutters\")\n  d.lineGutter = null\n  // Actual scrollable element.\n  d.scroller = elt(\"div\", [d.sizer, d.heightForcer, d.gutters], \"CodeMirror-scroll\")\n  d.scroller.setAttribute(\"tabIndex\", \"-1\")\n  // The element in which the editor lives.\n  d.wrapper = elt(\"div\", [d.scrollbarFiller, d.gutterFiller, d.scroller], \"CodeMirror\")\n\n  // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)\n  if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }\n  if (!webkit && !(gecko && mobile)) d.scroller.draggable = true\n\n  if (place) {\n    if (place.appendChild) place.appendChild(d.wrapper)\n    else place(d.wrapper)\n  }\n\n  // Current rendered range (may be bigger than the view window).\n  d.viewFrom = d.viewTo = doc.first\n  d.reportedViewFrom = d.reportedViewTo = doc.first\n  // Information about the rendered lines.\n  d.view = []\n  d.renderedView = null\n  // Holds info about a single rendered line when it was rendered\n  // for measurement, while not in view.\n  d.externalMeasured = null\n  // Empty space (in pixels) above the view\n  d.viewOffset = 0\n  d.lastWrapHeight = d.lastWrapWidth = 0\n  d.updateLineNumbers = null\n\n  d.nativeBarWidth = d.barHeight = d.barWidth = 0\n  d.scrollbarsClipped = false\n\n  // Used to only resize the line number gutter when necessary (when\n  // the amount of lines crosses a boundary that makes its width change)\n  d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null\n  // Set to true when a non-horizontal-scrolling line widget is\n  // added. As an optimization, line widget aligning is skipped when\n  // this is false.\n  d.alignWidgets = false\n\n  d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null\n\n  // Tracks the maximum line length so that the horizontal scrollbar\n  // can be kept static when scrolling.\n  d.maxLine = null\n  d.maxLineLength = 0\n  d.maxLineChanged = false\n\n  // Used for measuring wheel scrolling granularity\n  d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null\n\n  // True when shift is held down.\n  d.shift = false\n\n  // Used to track whether anything happened since the context menu\n  // was opened.\n  d.selForContextMenu = null\n\n  d.activeTouch = null\n\n  input.init(d)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/focus.js",
    "content": "import { restartBlink } from \"./selection.js\"\nimport { webkit } from \"../util/browser.js\"\nimport { addClass, rmClass } from \"../util/dom.js\"\nimport { signal } from \"../util/event.js\"\n\nexport function ensureFocus(cm) {\n  if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }\n}\n\nexport function delayBlurEvent(cm) {\n  cm.state.delayingBlurEvent = true\n  setTimeout(() => { if (cm.state.delayingBlurEvent) {\n    cm.state.delayingBlurEvent = false\n    onBlur(cm)\n  } }, 100)\n}\n\nexport function onFocus(cm, e) {\n  if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false\n\n  if (cm.options.readOnly == \"nocursor\") return\n  if (!cm.state.focused) {\n    signal(cm, \"focus\", cm, e)\n    cm.state.focused = true\n    addClass(cm.display.wrapper, \"CodeMirror-focused\")\n    // This test prevents this from firing when a context\n    // menu is closed (since the input reset would kill the\n    // select-all detection hack)\n    if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {\n      cm.display.input.reset()\n      if (webkit) setTimeout(() => cm.display.input.reset(true), 20) // Issue #1730\n    }\n    cm.display.input.receivedFocus()\n  }\n  restartBlink(cm)\n}\nexport function onBlur(cm, e) {\n  if (cm.state.delayingBlurEvent) return\n\n  if (cm.state.focused) {\n    signal(cm, \"blur\", cm, e)\n    cm.state.focused = false\n    rmClass(cm.display.wrapper, \"CodeMirror-focused\")\n  }\n  clearInterval(cm.display.blinker)\n  setTimeout(() => { if (!cm.state.focused) cm.display.shift = false }, 150)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/gutters.js",
    "content": "import { elt, removeChildren } from \"../util/dom.js\"\nimport { indexOf } from \"../util/misc.js\"\n\nimport { updateGutterSpace } from \"./update_display.js\"\n\n// Rebuild the gutter elements, ensure the margin to the left of the\n// code matches their width.\nexport function updateGutters(cm) {\n  let gutters = cm.display.gutters, specs = cm.options.gutters\n  removeChildren(gutters)\n  let i = 0\n  for (; i < specs.length; ++i) {\n    let gutterClass = specs[i]\n    let gElt = gutters.appendChild(elt(\"div\", null, \"CodeMirror-gutter \" + gutterClass))\n    if (gutterClass == \"CodeMirror-linenumbers\") {\n      cm.display.lineGutter = gElt\n      gElt.style.width = (cm.display.lineNumWidth || 1) + \"px\"\n    }\n  }\n  gutters.style.display = i ? \"\" : \"none\"\n  updateGutterSpace(cm)\n}\n\n// Make sure the gutters options contains the element\n// \"CodeMirror-linenumbers\" when the lineNumbers option is true.\nexport function setGuttersForLineNumbers(options) {\n  let found = indexOf(options.gutters, \"CodeMirror-linenumbers\")\n  if (found == -1 && options.lineNumbers) {\n    options.gutters = options.gutters.concat([\"CodeMirror-linenumbers\"])\n  } else if (found > -1 && !options.lineNumbers) {\n    options.gutters = options.gutters.slice(0)\n    options.gutters.splice(found, 1)\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/highlight_worker.js",
    "content": "import { getContextBefore, highlightLine, processLine } from \"../line/highlight.js\"\nimport { copyState } from \"../modes.js\"\nimport { bind } from \"../util/misc.js\"\n\nimport { runInOp } from \"./operations.js\"\nimport { regLineChange } from \"./view_tracking.js\"\n\n// HIGHLIGHT WORKER\n\nexport function startWorker(cm, time) {\n  if (cm.doc.highlightFrontier < cm.display.viewTo)\n    cm.state.highlight.set(time, bind(highlightWorker, cm))\n}\n\nfunction highlightWorker(cm) {\n  let doc = cm.doc\n  if (doc.highlightFrontier >= cm.display.viewTo) return\n  let end = +new Date + cm.options.workTime\n  let context = getContextBefore(cm, doc.highlightFrontier)\n  let changedLines = []\n\n  doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), line => {\n    if (context.line >= cm.display.viewFrom) { // Visible\n      let oldStyles = line.styles\n      let resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null\n      let highlighted = highlightLine(cm, line, context, true)\n      if (resetState) context.state = resetState\n      line.styles = highlighted.styles\n      let oldCls = line.styleClasses, newCls = highlighted.classes\n      if (newCls) line.styleClasses = newCls\n      else if (oldCls) line.styleClasses = null\n      let ischange = !oldStyles || oldStyles.length != line.styles.length ||\n        oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)\n      for (let i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]\n      if (ischange) changedLines.push(context.line)\n      line.stateAfter = context.save()\n      context.nextLine()\n    } else {\n      if (line.text.length <= cm.options.maxHighlightLength)\n        processLine(cm, line.text, context)\n      line.stateAfter = context.line % 5 == 0 ? context.save() : null\n      context.nextLine()\n    }\n    if (+new Date > end) {\n      startWorker(cm, cm.options.workDelay)\n      return true\n    }\n  })\n  doc.highlightFrontier = context.line\n  doc.modeFrontier = Math.max(doc.modeFrontier, context.line)\n  if (changedLines.length) runInOp(cm, () => {\n    for (let i = 0; i < changedLines.length; i++)\n      regLineChange(cm, changedLines[i], \"text\")\n  })\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/line_numbers.js",
    "content": "import { lineNumberFor } from \"../line/utils_line.js\"\nimport { compensateForHScroll } from \"../measurement/position_measurement.js\"\nimport { elt } from \"../util/dom.js\"\n\nimport { updateGutterSpace } from \"./update_display.js\"\n\n// Re-align line numbers and gutter marks to compensate for\n// horizontal scrolling.\nexport function alignHorizontally(cm) {\n  let display = cm.display, view = display.view\n  if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return\n  let comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft\n  let gutterW = display.gutters.offsetWidth, left = comp + \"px\"\n  for (let i = 0; i < view.length; i++) if (!view[i].hidden) {\n    if (cm.options.fixedGutter) {\n      if (view[i].gutter)\n        view[i].gutter.style.left = left\n      if (view[i].gutterBackground)\n        view[i].gutterBackground.style.left = left\n    }\n    let align = view[i].alignable\n    if (align) for (let j = 0; j < align.length; j++)\n      align[j].style.left = left\n  }\n  if (cm.options.fixedGutter)\n    display.gutters.style.left = (comp + gutterW) + \"px\"\n}\n\n// Used to ensure that the line number gutter is still the right\n// size for the current document size. Returns true when an update\n// is needed.\nexport function maybeUpdateLineNumberWidth(cm) {\n  if (!cm.options.lineNumbers) return false\n  let doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display\n  if (last.length != display.lineNumChars) {\n    let test = display.measure.appendChild(elt(\"div\", [elt(\"div\", last)],\n                                               \"CodeMirror-linenumber CodeMirror-gutter-elt\"))\n    let innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW\n    display.lineGutter.style.width = \"\"\n    display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1\n    display.lineNumWidth = display.lineNumInnerWidth + padding\n    display.lineNumChars = display.lineNumInnerWidth ? last.length : -1\n    display.lineGutter.style.width = display.lineNumWidth + \"px\"\n    updateGutterSpace(cm)\n    return true\n  }\n  return false\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/mode_state.js",
    "content": "import { getMode } from \"../modes.js\"\n\nimport { startWorker } from \"./highlight_worker.js\"\nimport { regChange } from \"./view_tracking.js\"\n\n// Used to get the editor into a consistent state again when options change.\n\nexport function loadMode(cm) {\n  cm.doc.mode = getMode(cm.options, cm.doc.modeOption)\n  resetModeState(cm)\n}\n\nexport function resetModeState(cm) {\n  cm.doc.iter(line => {\n    if (line.stateAfter) line.stateAfter = null\n    if (line.styles) line.styles = null\n  })\n  cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first\n  startWorker(cm, 100)\n  cm.state.modeGen++\n  if (cm.curOp) regChange(cm)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/operations.js",
    "content": "import { clipPos } from \"../line/pos.js\"\nimport { findMaxLine } from \"../line/spans.js\"\nimport { displayWidth, measureChar, scrollGap } from \"../measurement/position_measurement.js\"\nimport { signal } from \"../util/event.js\"\nimport { activeElt } from \"../util/dom.js\"\nimport { finishOperation, pushOperation } from \"../util/operation_group.js\"\n\nimport { ensureFocus } from \"./focus.js\"\nimport { measureForScrollbars, updateScrollbars } from \"./scrollbars.js\"\nimport { restartBlink } from \"./selection.js\"\nimport { maybeScrollWindow, scrollPosIntoView, setScrollLeft, setScrollTop } from \"./scrolling.js\"\nimport { DisplayUpdate, maybeClipScrollbars, postUpdateDisplay, setDocumentHeight, updateDisplayIfNeeded } from \"./update_display.js\"\nimport { updateHeightsInViewport } from \"./update_lines.js\"\n\n// Operations are used to wrap a series of changes to the editor\n// state in such a way that each change won't have to update the\n// cursor and display (which would be awkward, slow, and\n// error-prone). Instead, display updates are batched and then all\n// combined and executed at once.\n\nlet nextOpId = 0\n// Start a new operation.\nexport function startOperation(cm) {\n  cm.curOp = {\n    cm: cm,\n    viewChanged: false,      // Flag that indicates that lines might need to be redrawn\n    startHeight: cm.doc.height, // Used to detect need to update scrollbar\n    forceUpdate: false,      // Used to force a redraw\n    updateInput: 0,       // Whether to reset the input textarea\n    typing: false,           // Whether this reset should be careful to leave existing text (for compositing)\n    changeObjs: null,        // Accumulated changes, for firing change events\n    cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on\n    cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already\n    selectionChanged: false, // Whether the selection needs to be redrawn\n    updateMaxLine: false,    // Set when the widest line needs to be determined anew\n    scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet\n    scrollToPos: null,       // Used to scroll to a specific position\n    focus: false,\n    id: ++nextOpId           // Unique ID\n  }\n  pushOperation(cm.curOp)\n}\n\n// Finish an operation, updating the display and signalling delayed events\nexport function endOperation(cm) {\n  let op = cm.curOp\n  if (op) finishOperation(op, group => {\n    for (let i = 0; i < group.ops.length; i++)\n      group.ops[i].cm.curOp = null\n    endOperations(group)\n  })\n}\n\n// The DOM updates done when an operation finishes are batched so\n// that the minimum number of relayouts are required.\nfunction endOperations(group) {\n  let ops = group.ops\n  for (let i = 0; i < ops.length; i++) // Read DOM\n    endOperation_R1(ops[i])\n  for (let i = 0; i < ops.length; i++) // Write DOM (maybe)\n    endOperation_W1(ops[i])\n  for (let i = 0; i < ops.length; i++) // Read DOM\n    endOperation_R2(ops[i])\n  for (let i = 0; i < ops.length; i++) // Write DOM (maybe)\n    endOperation_W2(ops[i])\n  for (let i = 0; i < ops.length; i++) // Read DOM\n    endOperation_finish(ops[i])\n}\n\nfunction endOperation_R1(op) {\n  let cm = op.cm, display = cm.display\n  maybeClipScrollbars(cm)\n  if (op.updateMaxLine) findMaxLine(cm)\n\n  op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||\n    op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||\n                       op.scrollToPos.to.line >= display.viewTo) ||\n    display.maxLineChanged && cm.options.lineWrapping\n  op.update = op.mustUpdate &&\n    new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)\n}\n\nfunction endOperation_W1(op) {\n  op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)\n}\n\nfunction endOperation_R2(op) {\n  let cm = op.cm, display = cm.display\n  if (op.updatedDisplay) updateHeightsInViewport(cm)\n\n  op.barMeasure = measureForScrollbars(cm)\n\n  // If the max line changed since it was last measured, measure it,\n  // and ensure the document's width matches it.\n  // updateDisplay_W2 will use these properties to do the actual resizing\n  if (display.maxLineChanged && !cm.options.lineWrapping) {\n    op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3\n    cm.display.sizerWidth = op.adjustWidthTo\n    op.barMeasure.scrollWidth =\n      Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)\n    op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))\n  }\n\n  if (op.updatedDisplay || op.selectionChanged)\n    op.preparedSelection = display.input.prepareSelection()\n}\n\nfunction endOperation_W2(op) {\n  let cm = op.cm\n\n  if (op.adjustWidthTo != null) {\n    cm.display.sizer.style.minWidth = op.adjustWidthTo + \"px\"\n    if (op.maxScrollLeft < cm.doc.scrollLeft)\n      setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true)\n    cm.display.maxLineChanged = false\n  }\n\n  let takeFocus = op.focus && op.focus == activeElt()\n  if (op.preparedSelection)\n    cm.display.input.showSelection(op.preparedSelection, takeFocus)\n  if (op.updatedDisplay || op.startHeight != cm.doc.height)\n    updateScrollbars(cm, op.barMeasure)\n  if (op.updatedDisplay)\n    setDocumentHeight(cm, op.barMeasure)\n\n  if (op.selectionChanged) restartBlink(cm)\n\n  if (cm.state.focused && op.updateInput)\n    cm.display.input.reset(op.typing)\n  if (takeFocus) ensureFocus(op.cm)\n}\n\nfunction endOperation_finish(op) {\n  let cm = op.cm, display = cm.display, doc = cm.doc\n\n  if (op.updatedDisplay) postUpdateDisplay(cm, op.update)\n\n  // Abort mouse wheel delta measurement, when scrolling explicitly\n  if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))\n    display.wheelStartX = display.wheelStartY = null\n\n  // Propagate the scroll position to the actual DOM scroller\n  if (op.scrollTop != null) setScrollTop(cm, op.scrollTop, op.forceScroll)\n\n  if (op.scrollLeft != null) setScrollLeft(cm, op.scrollLeft, true, true)\n  // If we need to scroll a specific position into view, do so.\n  if (op.scrollToPos) {\n    let rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),\n                                 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)\n    maybeScrollWindow(cm, rect)\n  }\n\n  // Fire events for markers that are hidden/unidden by editing or\n  // undoing\n  let hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers\n  if (hidden) for (let i = 0; i < hidden.length; ++i)\n    if (!hidden[i].lines.length) signal(hidden[i], \"hide\")\n  if (unhidden) for (let i = 0; i < unhidden.length; ++i)\n    if (unhidden[i].lines.length) signal(unhidden[i], \"unhide\")\n\n  if (display.wrapper.offsetHeight)\n    doc.scrollTop = cm.display.scroller.scrollTop\n\n  // Fire change events, and delayed event handlers\n  if (op.changeObjs)\n    signal(cm, \"changes\", cm, op.changeObjs)\n  if (op.update)\n    op.update.finish()\n}\n\n// Run the given function in an operation\nexport function runInOp(cm, f) {\n  if (cm.curOp) return f()\n  startOperation(cm)\n  try { return f() }\n  finally { endOperation(cm) }\n}\n// Wraps a function in an operation. Returns the wrapped function.\nexport function operation(cm, f) {\n  return function() {\n    if (cm.curOp) return f.apply(cm, arguments)\n    startOperation(cm)\n    try { return f.apply(cm, arguments) }\n    finally { endOperation(cm) }\n  }\n}\n// Used to add methods to editor and doc instances, wrapping them in\n// operations.\nexport function methodOp(f) {\n  return function() {\n    if (this.curOp) return f.apply(this, arguments)\n    startOperation(this)\n    try { return f.apply(this, arguments) }\n    finally { endOperation(this) }\n  }\n}\nexport function docMethodOp(f) {\n  return function() {\n    let cm = this.cm\n    if (!cm || cm.curOp) return f.apply(this, arguments)\n    startOperation(cm)\n    try { return f.apply(this, arguments) }\n    finally { endOperation(cm) }\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/scroll_events.js",
    "content": "import { chrome, gecko, ie, mac, presto, safari, webkit } from \"../util/browser.js\"\nimport { e_preventDefault } from \"../util/event.js\"\n\nimport { updateDisplaySimple } from \"./update_display.js\"\nimport { setScrollLeft, updateScrollTop } from \"./scrolling.js\"\n\n// Since the delta values reported on mouse wheel events are\n// unstandardized between browsers and even browser versions, and\n// generally horribly unpredictable, this code starts by measuring\n// the scroll effect that the first few mouse wheel events have,\n// and, from that, detects the way it can convert deltas to pixel\n// offsets afterwards.\n//\n// The reason we want to know the amount a wheel event will scroll\n// is that it gives us a chance to update the display before the\n// actual scrolling happens, reducing flickering.\n\nlet wheelSamples = 0, wheelPixelsPerUnit = null\n// Fill in a browser-detected starting value on browsers where we\n// know one. These don't have to be accurate -- the result of them\n// being wrong would just be a slight flicker on the first wheel\n// scroll (if it is large enough).\nif (ie) wheelPixelsPerUnit = -.53\nelse if (gecko) wheelPixelsPerUnit = 15\nelse if (chrome) wheelPixelsPerUnit = -.7\nelse if (safari) wheelPixelsPerUnit = -1/3\n\nfunction wheelEventDelta(e) {\n  let dx = e.wheelDeltaX, dy = e.wheelDeltaY\n  if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail\n  if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail\n  else if (dy == null) dy = e.wheelDelta\n  return {x: dx, y: dy}\n}\nexport function wheelEventPixels(e) {\n  let delta = wheelEventDelta(e)\n  delta.x *= wheelPixelsPerUnit\n  delta.y *= wheelPixelsPerUnit\n  return delta\n}\n\nexport function onScrollWheel(cm, e) {\n  let delta = wheelEventDelta(e), dx = delta.x, dy = delta.y\n\n  let display = cm.display, scroll = display.scroller\n  // Quit if there's nothing to scroll here\n  let canScrollX = scroll.scrollWidth > scroll.clientWidth\n  let canScrollY = scroll.scrollHeight > scroll.clientHeight\n  if (!(dx && canScrollX || dy && canScrollY)) return\n\n  // Webkit browsers on OS X abort momentum scrolls when the target\n  // of the scroll event is removed from the scrollable element.\n  // This hack (see related code in patchDisplay) makes sure the\n  // element is kept around.\n  if (dy && mac && webkit) {\n    outer: for (let cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {\n      for (let i = 0; i < view.length; i++) {\n        if (view[i].node == cur) {\n          cm.display.currentWheelTarget = cur\n          break outer\n        }\n      }\n    }\n  }\n\n  // On some browsers, horizontal scrolling will cause redraws to\n  // happen before the gutter has been realigned, causing it to\n  // wriggle around in a most unseemly way. When we have an\n  // estimated pixels/delta value, we just handle horizontal\n  // scrolling entirely here. It'll be slightly off from native, but\n  // better than glitching out.\n  if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {\n    if (dy && canScrollY)\n      updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit))\n    setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit))\n    // Only prevent default scrolling if vertical scrolling is\n    // actually possible. Otherwise, it causes vertical scroll\n    // jitter on OSX trackpads when deltaX is small and deltaY\n    // is large (issue #3579)\n    if (!dy || (dy && canScrollY))\n      e_preventDefault(e)\n    display.wheelStartX = null // Abort measurement, if in progress\n    return\n  }\n\n  // 'Project' the visible viewport to cover the area that is being\n  // scrolled into view (if we know enough to estimate it).\n  if (dy && wheelPixelsPerUnit != null) {\n    let pixels = dy * wheelPixelsPerUnit\n    let top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight\n    if (pixels < 0) top = Math.max(0, top + pixels - 50)\n    else bot = Math.min(cm.doc.height, bot + pixels + 50)\n    updateDisplaySimple(cm, {top: top, bottom: bot})\n  }\n\n  if (wheelSamples < 20) {\n    if (display.wheelStartX == null) {\n      display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop\n      display.wheelDX = dx; display.wheelDY = dy\n      setTimeout(() => {\n        if (display.wheelStartX == null) return\n        let movedX = scroll.scrollLeft - display.wheelStartX\n        let movedY = scroll.scrollTop - display.wheelStartY\n        let sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||\n          (movedX && display.wheelDX && movedX / display.wheelDX)\n        display.wheelStartX = display.wheelStartY = null\n        if (!sample) return\n        wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)\n        ++wheelSamples\n      }, 200)\n    } else {\n      display.wheelDX += dx; display.wheelDY += dy\n    }\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/scrollbars.js",
    "content": "import { addClass, elt, rmClass } from \"../util/dom.js\"\nimport { on } from \"../util/event.js\"\nimport { scrollGap, paddingVert } from \"../measurement/position_measurement.js\"\nimport { ie, ie_version, mac, mac_geMountainLion } from \"../util/browser.js\"\nimport { updateHeightsInViewport } from \"./update_lines.js\"\nimport { Delayed } from \"../util/misc.js\"\n\nimport { setScrollLeft, updateScrollTop } from \"./scrolling.js\"\n\n// SCROLLBARS\n\n// Prepare DOM reads needed to update the scrollbars. Done in one\n// shot to minimize update/measure roundtrips.\nexport function measureForScrollbars(cm) {\n  let d = cm.display, gutterW = d.gutters.offsetWidth\n  let docH = Math.round(cm.doc.height + paddingVert(cm.display))\n  return {\n    clientHeight: d.scroller.clientHeight,\n    viewHeight: d.wrapper.clientHeight,\n    scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,\n    viewWidth: d.wrapper.clientWidth,\n    barLeft: cm.options.fixedGutter ? gutterW : 0,\n    docHeight: docH,\n    scrollHeight: docH + scrollGap(cm) + d.barHeight,\n    nativeBarWidth: d.nativeBarWidth,\n    gutterWidth: gutterW\n  }\n}\n\nclass NativeScrollbars {\n  constructor(place, scroll, cm) {\n    this.cm = cm\n    let vert = this.vert = elt(\"div\", [elt(\"div\", null, null, \"min-width: 1px\")], \"CodeMirror-vscrollbar\")\n    let horiz = this.horiz = elt(\"div\", [elt(\"div\", null, null, \"height: 100%; min-height: 1px\")], \"CodeMirror-hscrollbar\")\n    vert.tabIndex = horiz.tabIndex = -1\n    place(vert); place(horiz)\n\n    on(vert, \"scroll\", () => {\n      if (vert.clientHeight) scroll(vert.scrollTop, \"vertical\")\n    })\n    on(horiz, \"scroll\", () => {\n      if (horiz.clientWidth) scroll(horiz.scrollLeft, \"horizontal\")\n    })\n\n    this.checkedZeroWidth = false\n    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).\n    if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = \"18px\"\n  }\n\n  update(measure) {\n    let needsH = measure.scrollWidth > measure.clientWidth + 1\n    let needsV = measure.scrollHeight > measure.clientHeight + 1\n    let sWidth = measure.nativeBarWidth\n\n    if (needsV) {\n      this.vert.style.display = \"block\"\n      this.vert.style.bottom = needsH ? sWidth + \"px\" : \"0\"\n      let totalHeight = measure.viewHeight - (needsH ? sWidth : 0)\n      // A bug in IE8 can cause this value to be negative, so guard it.\n      this.vert.firstChild.style.height =\n        Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + \"px\"\n    } else {\n      this.vert.style.display = \"\"\n      this.vert.firstChild.style.height = \"0\"\n    }\n\n    if (needsH) {\n      this.horiz.style.display = \"block\"\n      this.horiz.style.right = needsV ? sWidth + \"px\" : \"0\"\n      this.horiz.style.left = measure.barLeft + \"px\"\n      let totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)\n      this.horiz.firstChild.style.width =\n        Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + \"px\"\n    } else {\n      this.horiz.style.display = \"\"\n      this.horiz.firstChild.style.width = \"0\"\n    }\n\n    if (!this.checkedZeroWidth && measure.clientHeight > 0) {\n      if (sWidth == 0) this.zeroWidthHack()\n      this.checkedZeroWidth = true\n    }\n\n    return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}\n  }\n\n  setScrollLeft(pos) {\n    if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos\n    if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz, \"horiz\")\n  }\n\n  setScrollTop(pos) {\n    if (this.vert.scrollTop != pos) this.vert.scrollTop = pos\n    if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert, \"vert\")\n  }\n\n  zeroWidthHack() {\n    let w = mac && !mac_geMountainLion ? \"12px\" : \"18px\"\n    this.horiz.style.height = this.vert.style.width = w\n    this.horiz.style.pointerEvents = this.vert.style.pointerEvents = \"none\"\n    this.disableHoriz = new Delayed\n    this.disableVert = new Delayed\n  }\n\n  enableZeroWidthBar(bar, delay, type) {\n    bar.style.pointerEvents = \"auto\"\n    function maybeDisable() {\n      // To find out whether the scrollbar is still visible, we\n      // check whether the element under the pixel in the bottom\n      // right corner of the scrollbar box is the scrollbar box\n      // itself (when the bar is still visible) or its filler child\n      // (when the bar is hidden). If it is still visible, we keep\n      // it enabled, if it's hidden, we disable pointer events.\n      let box = bar.getBoundingClientRect()\n      let elt = type == \"vert\" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)\n          : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1)\n      if (elt != bar) bar.style.pointerEvents = \"none\"\n      else delay.set(1000, maybeDisable)\n    }\n    delay.set(1000, maybeDisable)\n  }\n\n  clear() {\n    let parent = this.horiz.parentNode\n    parent.removeChild(this.horiz)\n    parent.removeChild(this.vert)\n  }\n}\n\nclass NullScrollbars {\n  update() { return {bottom: 0, right: 0} }\n  setScrollLeft() {}\n  setScrollTop() {}\n  clear() {}\n}\n\nexport function updateScrollbars(cm, measure) {\n  if (!measure) measure = measureForScrollbars(cm)\n  let startWidth = cm.display.barWidth, startHeight = cm.display.barHeight\n  updateScrollbarsInner(cm, measure)\n  for (let i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {\n    if (startWidth != cm.display.barWidth && cm.options.lineWrapping)\n      updateHeightsInViewport(cm)\n    updateScrollbarsInner(cm, measureForScrollbars(cm))\n    startWidth = cm.display.barWidth; startHeight = cm.display.barHeight\n  }\n}\n\n// Re-synchronize the fake scrollbars with the actual size of the\n// content.\nfunction updateScrollbarsInner(cm, measure) {\n  let d = cm.display\n  let sizes = d.scrollbars.update(measure)\n\n  d.sizer.style.paddingRight = (d.barWidth = sizes.right) + \"px\"\n  d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + \"px\"\n  d.heightForcer.style.borderBottom = sizes.bottom + \"px solid transparent\"\n\n  if (sizes.right && sizes.bottom) {\n    d.scrollbarFiller.style.display = \"block\"\n    d.scrollbarFiller.style.height = sizes.bottom + \"px\"\n    d.scrollbarFiller.style.width = sizes.right + \"px\"\n  } else d.scrollbarFiller.style.display = \"\"\n  if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {\n    d.gutterFiller.style.display = \"block\"\n    d.gutterFiller.style.height = sizes.bottom + \"px\"\n    d.gutterFiller.style.width = measure.gutterWidth + \"px\"\n  } else d.gutterFiller.style.display = \"\"\n}\n\nexport let scrollbarModel = {\"native\": NativeScrollbars, \"null\": NullScrollbars}\n\nexport function initScrollbars(cm) {\n  if (cm.display.scrollbars) {\n    cm.display.scrollbars.clear()\n    if (cm.display.scrollbars.addClass)\n      rmClass(cm.display.wrapper, cm.display.scrollbars.addClass)\n  }\n\n  cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](node => {\n    cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)\n    // Prevent clicks in the scrollbars from killing focus\n    on(node, \"mousedown\", () => {\n      if (cm.state.focused) setTimeout(() => cm.display.input.focus(), 0)\n    })\n    node.setAttribute(\"cm-not-content\", \"true\")\n  }, (pos, axis) => {\n    if (axis == \"horizontal\") setScrollLeft(cm, pos)\n    else updateScrollTop(cm, pos)\n  }, cm)\n  if (cm.display.scrollbars.addClass)\n    addClass(cm.display.wrapper, cm.display.scrollbars.addClass)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/scrolling.js",
    "content": "import { Pos } from \"../line/pos.js\"\nimport { cursorCoords, displayHeight, displayWidth, estimateCoords, paddingTop, paddingVert, scrollGap, textHeight } from \"../measurement/position_measurement.js\"\nimport { gecko, phantom } from \"../util/browser.js\"\nimport { elt } from \"../util/dom.js\"\nimport { signalDOMEvent } from \"../util/event.js\"\n\nimport { startWorker } from \"./highlight_worker.js\"\nimport { alignHorizontally } from \"./line_numbers.js\"\nimport { updateDisplaySimple } from \"./update_display.js\"\n\n// SCROLLING THINGS INTO VIEW\n\n// If an editor sits on the top or bottom of the window, partially\n// scrolled out of view, this ensures that the cursor is visible.\nexport function maybeScrollWindow(cm, rect) {\n  if (signalDOMEvent(cm, \"scrollCursorIntoView\")) return\n\n  let display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null\n  if (rect.top + box.top < 0) doScroll = true\n  else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false\n  if (doScroll != null && !phantom) {\n    let scrollNode = elt(\"div\", \"\\u200b\", null, `position: absolute;\n                         top: ${rect.top - display.viewOffset - paddingTop(cm.display)}px;\n                         height: ${rect.bottom - rect.top + scrollGap(cm) + display.barHeight}px;\n                         left: ${rect.left}px; width: ${Math.max(2, rect.right - rect.left)}px;`)\n    cm.display.lineSpace.appendChild(scrollNode)\n    scrollNode.scrollIntoView(doScroll)\n    cm.display.lineSpace.removeChild(scrollNode)\n  }\n}\n\n// Scroll a given position into view (immediately), verifying that\n// it actually became visible (as line heights are accurately\n// measured, the position of something may 'drift' during drawing).\nexport function scrollPosIntoView(cm, pos, end, margin) {\n  if (margin == null) margin = 0\n  let rect\n  if (!cm.options.lineWrapping && pos == end) {\n    // Set pos and end to the cursor positions around the character pos sticks to\n    // If pos.sticky == \"before\", that is around pos.ch - 1, otherwise around pos.ch\n    // If pos == Pos(_, 0, \"before\"), pos and end are unchanged\n    pos = pos.ch ? Pos(pos.line, pos.sticky == \"before\" ? pos.ch - 1 : pos.ch, \"after\") : pos\n    end = pos.sticky == \"before\" ? Pos(pos.line, pos.ch + 1, \"before\") : pos\n  }\n  for (let limit = 0; limit < 5; limit++) {\n    let changed = false\n    let coords = cursorCoords(cm, pos)\n    let endCoords = !end || end == pos ? coords : cursorCoords(cm, end)\n    rect = {left: Math.min(coords.left, endCoords.left),\n            top: Math.min(coords.top, endCoords.top) - margin,\n            right: Math.max(coords.left, endCoords.left),\n            bottom: Math.max(coords.bottom, endCoords.bottom) + margin}\n    let scrollPos = calculateScrollPos(cm, rect)\n    let startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft\n    if (scrollPos.scrollTop != null) {\n      updateScrollTop(cm, scrollPos.scrollTop)\n      if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true\n    }\n    if (scrollPos.scrollLeft != null) {\n      setScrollLeft(cm, scrollPos.scrollLeft)\n      if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true\n    }\n    if (!changed) break\n  }\n  return rect\n}\n\n// Scroll a given set of coordinates into view (immediately).\nexport function scrollIntoView(cm, rect) {\n  let scrollPos = calculateScrollPos(cm, rect)\n  if (scrollPos.scrollTop != null) updateScrollTop(cm, scrollPos.scrollTop)\n  if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft)\n}\n\n// Calculate a new scroll position needed to scroll the given\n// rectangle into view. Returns an object with scrollTop and\n// scrollLeft properties. When these are undefined, the\n// vertical/horizontal position does not need to be adjusted.\nfunction calculateScrollPos(cm, rect) {\n  let display = cm.display, snapMargin = textHeight(cm.display)\n  if (rect.top < 0) rect.top = 0\n  let screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop\n  let screen = displayHeight(cm), result = {}\n  if (rect.bottom - rect.top > screen) rect.bottom = rect.top + screen\n  let docBottom = cm.doc.height + paddingVert(display)\n  let atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin\n  if (rect.top < screentop) {\n    result.scrollTop = atTop ? 0 : rect.top\n  } else if (rect.bottom > screentop + screen) {\n    let newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen)\n    if (newTop != screentop) result.scrollTop = newTop\n  }\n\n  let screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft\n  let screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)\n  let tooWide = rect.right - rect.left > screenw\n  if (tooWide) rect.right = rect.left + screenw\n  if (rect.left < 10)\n    result.scrollLeft = 0\n  else if (rect.left < screenleft)\n    result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10))\n  else if (rect.right > screenw + screenleft - 3)\n    result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw\n  return result\n}\n\n// Store a relative adjustment to the scroll position in the current\n// operation (to be applied when the operation finishes).\nexport function addToScrollTop(cm, top) {\n  if (top == null) return\n  resolveScrollToPos(cm)\n  cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top\n}\n\n// Make sure that at the end of the operation the current cursor is\n// shown.\nexport function ensureCursorVisible(cm) {\n  resolveScrollToPos(cm)\n  let cur = cm.getCursor()\n  cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}\n}\n\nexport function scrollToCoords(cm, x, y) {\n  if (x != null || y != null) resolveScrollToPos(cm)\n  if (x != null) cm.curOp.scrollLeft = x\n  if (y != null) cm.curOp.scrollTop = y\n}\n\nexport function scrollToRange(cm, range) {\n  resolveScrollToPos(cm)\n  cm.curOp.scrollToPos = range\n}\n\n// When an operation has its scrollToPos property set, and another\n// scroll action is applied before the end of the operation, this\n// 'simulates' scrolling that position into view in a cheap way, so\n// that the effect of intermediate scroll commands is not ignored.\nfunction resolveScrollToPos(cm) {\n  let range = cm.curOp.scrollToPos\n  if (range) {\n    cm.curOp.scrollToPos = null\n    let from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to)\n    scrollToCoordsRange(cm, from, to, range.margin)\n  }\n}\n\nexport function scrollToCoordsRange(cm, from, to, margin) {\n  let sPos = calculateScrollPos(cm, {\n    left: Math.min(from.left, to.left),\n    top: Math.min(from.top, to.top) - margin,\n    right: Math.max(from.right, to.right),\n    bottom: Math.max(from.bottom, to.bottom) + margin\n  })\n  scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop)\n}\n\n// Sync the scrollable area and scrollbars, ensure the viewport\n// covers the visible area.\nexport function updateScrollTop(cm, val) {\n  if (Math.abs(cm.doc.scrollTop - val) < 2) return\n  if (!gecko) updateDisplaySimple(cm, {top: val})\n  setScrollTop(cm, val, true)\n  if (gecko) updateDisplaySimple(cm)\n  startWorker(cm, 100)\n}\n\nexport function setScrollTop(cm, val, forceScroll) {\n  val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)\n  if (cm.display.scroller.scrollTop == val && !forceScroll) return\n  cm.doc.scrollTop = val\n  cm.display.scrollbars.setScrollTop(val)\n  if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val\n}\n\n// Sync scroller and scrollbar, ensure the gutter elements are\n// aligned.\nexport function setScrollLeft(cm, val, isScroller, forceScroll) {\n  val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)\n  if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) return\n  cm.doc.scrollLeft = val\n  alignHorizontally(cm)\n  if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val\n  cm.display.scrollbars.setScrollLeft(val)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/selection.js",
    "content": "import { Pos } from \"../line/pos.js\"\nimport { visualLine } from \"../line/spans.js\"\nimport { getLine } from \"../line/utils_line.js\"\nimport { charCoords, cursorCoords, displayWidth, paddingH, wrappedLineExtentChar } from \"../measurement/position_measurement.js\"\nimport { getOrder, iterateBidiSections } from \"../util/bidi.js\"\nimport { elt } from \"../util/dom.js\"\n\nexport function updateSelection(cm) {\n  cm.display.input.showSelection(cm.display.input.prepareSelection())\n}\n\nexport function prepareSelection(cm, primary = true) {\n  let doc = cm.doc, result = {}\n  let curFragment = result.cursors = document.createDocumentFragment()\n  let selFragment = result.selection = document.createDocumentFragment()\n\n  for (let i = 0; i < doc.sel.ranges.length; i++) {\n    if (!primary && i == doc.sel.primIndex) continue\n    let range = doc.sel.ranges[i]\n    if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue\n    let collapsed = range.empty()\n    if (collapsed || cm.options.showCursorWhenSelecting)\n      drawSelectionCursor(cm, range.head, curFragment)\n    if (!collapsed)\n      drawSelectionRange(cm, range, selFragment)\n  }\n  return result\n}\n\n// Draws a cursor for the given range\nexport function drawSelectionCursor(cm, head, output) {\n  let pos = cursorCoords(cm, head, \"div\", null, null, !cm.options.singleCursorHeightPerLine)\n\n  let cursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor\"))\n  cursor.style.left = pos.left + \"px\"\n  cursor.style.top = pos.top + \"px\"\n  cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + \"px\"\n\n  if (pos.other) {\n    // Secondary cursor, shown when on a 'jump' in bi-directional text\n    let otherCursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor CodeMirror-secondarycursor\"))\n    otherCursor.style.display = \"\"\n    otherCursor.style.left = pos.other.left + \"px\"\n    otherCursor.style.top = pos.other.top + \"px\"\n    otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + \"px\"\n  }\n}\n\nfunction cmpCoords(a, b) { return a.top - b.top || a.left - b.left }\n\n// Draws the given range as a highlighted selection\nfunction drawSelectionRange(cm, range, output) {\n  let display = cm.display, doc = cm.doc\n  let fragment = document.createDocumentFragment()\n  let padding = paddingH(cm.display), leftSide = padding.left\n  let rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right\n  let docLTR = doc.direction == \"ltr\"\n\n  function add(left, top, width, bottom) {\n    if (top < 0) top = 0\n    top = Math.round(top)\n    bottom = Math.round(bottom)\n    fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", `position: absolute; left: ${left}px;\n                             top: ${top}px; width: ${width == null ? rightSide - left : width}px;\n                             height: ${bottom - top}px`))\n  }\n\n  function drawForLine(line, fromArg, toArg) {\n    let lineObj = getLine(doc, line)\n    let lineLen = lineObj.text.length\n    let start, end\n    function coords(ch, bias) {\n      return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n    }\n\n    function wrapX(pos, dir, side) {\n      let extent = wrappedLineExtentChar(cm, lineObj, null, pos)\n      let prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\"\n      let ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1)\n      return coords(ch, prop)[prop]\n    }\n\n    let order = getOrder(lineObj, doc.direction)\n    iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, (from, to, dir, i) => {\n      let ltr = dir == \"ltr\"\n      let fromPos = coords(from, ltr ? \"left\" : \"right\")\n      let toPos = coords(to - 1, ltr ? \"right\" : \"left\")\n\n      let openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen\n      let first = i == 0, last = !order || i == order.length - 1\n      if (toPos.top - fromPos.top <= 3) { // Single line\n        let openLeft = (docLTR ? openStart : openEnd) && first\n        let openRight = (docLTR ? openEnd : openStart) && last\n        let left = openLeft ? leftSide : (ltr ? fromPos : toPos).left\n        let right = openRight ? rightSide : (ltr ? toPos : fromPos).right\n        add(left, fromPos.top, right - left, fromPos.bottom)\n      } else { // Multiple lines\n        let topLeft, topRight, botLeft, botRight\n        if (ltr) {\n          topLeft = docLTR && openStart && first ? leftSide : fromPos.left\n          topRight = docLTR ? rightSide : wrapX(from, dir, \"before\")\n          botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\")\n          botRight = docLTR && openEnd && last ? rightSide : toPos.right\n        } else {\n          topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\")\n          topRight = !docLTR && openStart && first ? rightSide : fromPos.right\n          botLeft = !docLTR && openEnd && last ? leftSide : toPos.left\n          botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\")\n        }\n        add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom)\n        if (fromPos.bottom < toPos.top) add(leftSide, fromPos.bottom, null, toPos.top)\n        add(botLeft, toPos.top, botRight - botLeft, toPos.bottom)\n      }\n\n      if (!start || cmpCoords(fromPos, start) < 0) start = fromPos\n      if (cmpCoords(toPos, start) < 0) start = toPos\n      if (!end || cmpCoords(fromPos, end) < 0) end = fromPos\n      if (cmpCoords(toPos, end) < 0) end = toPos\n    })\n    return {start: start, end: end}\n  }\n\n  let sFrom = range.from(), sTo = range.to()\n  if (sFrom.line == sTo.line) {\n    drawForLine(sFrom.line, sFrom.ch, sTo.ch)\n  } else {\n    let fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line)\n    let singleVLine = visualLine(fromLine) == visualLine(toLine)\n    let leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end\n    let rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start\n    if (singleVLine) {\n      if (leftEnd.top < rightStart.top - 2) {\n        add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)\n        add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)\n      } else {\n        add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)\n      }\n    }\n    if (leftEnd.bottom < rightStart.top)\n      add(leftSide, leftEnd.bottom, null, rightStart.top)\n  }\n\n  output.appendChild(fragment)\n}\n\n// Cursor-blinking\nexport function restartBlink(cm) {\n  if (!cm.state.focused) return\n  let display = cm.display\n  clearInterval(display.blinker)\n  let on = true\n  display.cursorDiv.style.visibility = \"\"\n  if (cm.options.cursorBlinkRate > 0)\n    display.blinker = setInterval(() => display.cursorDiv.style.visibility = (on = !on) ? \"\" : \"hidden\",\n      cm.options.cursorBlinkRate)\n  else if (cm.options.cursorBlinkRate < 0)\n    display.cursorDiv.style.visibility = \"hidden\"\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/update_display.js",
    "content": "import { sawCollapsedSpans } from \"../line/saw_special_spans.js\"\nimport { heightAtLine, visualLineEndNo, visualLineNo } from \"../line/spans.js\"\nimport { getLine, lineNumberFor } from \"../line/utils_line.js\"\nimport { displayHeight, displayWidth, getDimensions, paddingVert, scrollGap } from \"../measurement/position_measurement.js\"\nimport { mac, webkit } from \"../util/browser.js\"\nimport { activeElt, removeChildren, contains } from \"../util/dom.js\"\nimport { hasHandler, signal } from \"../util/event.js\"\nimport { indexOf } from \"../util/misc.js\"\n\nimport { buildLineElement, updateLineForChanges } from \"./update_line.js\"\nimport { startWorker } from \"./highlight_worker.js\"\nimport { maybeUpdateLineNumberWidth } from \"./line_numbers.js\"\nimport { measureForScrollbars, updateScrollbars } from \"./scrollbars.js\"\nimport { updateSelection } from \"./selection.js\"\nimport { updateHeightsInViewport, visibleLines } from \"./update_lines.js\"\nimport { adjustView, countDirtyView, resetView } from \"./view_tracking.js\"\n\n// DISPLAY DRAWING\n\nexport class DisplayUpdate {\n  constructor(cm, viewport, force) {\n    let display = cm.display\n\n    this.viewport = viewport\n    // Store some values that we'll need later (but don't want to force a relayout for)\n    this.visible = visibleLines(display, cm.doc, viewport)\n    this.editorIsHidden = !display.wrapper.offsetWidth\n    this.wrapperHeight = display.wrapper.clientHeight\n    this.wrapperWidth = display.wrapper.clientWidth\n    this.oldDisplayWidth = displayWidth(cm)\n    this.force = force\n    this.dims = getDimensions(cm)\n    this.events = []\n  }\n\n  signal(emitter, type) {\n    if (hasHandler(emitter, type))\n      this.events.push(arguments)\n  }\n  finish() {\n    for (let i = 0; i < this.events.length; i++)\n      signal.apply(null, this.events[i])\n  }\n}\n\nexport function maybeClipScrollbars(cm) {\n  let display = cm.display\n  if (!display.scrollbarsClipped && display.scroller.offsetWidth) {\n    display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth\n    display.heightForcer.style.height = scrollGap(cm) + \"px\"\n    display.sizer.style.marginBottom = -display.nativeBarWidth + \"px\"\n    display.sizer.style.borderRightWidth = scrollGap(cm) + \"px\"\n    display.scrollbarsClipped = true\n  }\n}\n\nfunction selectionSnapshot(cm) {\n  if (cm.hasFocus()) return null\n  let active = activeElt()\n  if (!active || !contains(cm.display.lineDiv, active)) return null\n  let result = {activeElt: active}\n  if (window.getSelection) {\n    let sel = window.getSelection()\n    if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {\n      result.anchorNode = sel.anchorNode\n      result.anchorOffset = sel.anchorOffset\n      result.focusNode = sel.focusNode\n      result.focusOffset = sel.focusOffset\n    }\n  }\n  return result\n}\n\nfunction restoreSelection(snapshot) {\n  if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) return\n  snapshot.activeElt.focus()\n  if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {\n    let sel = window.getSelection(), range = document.createRange()\n    range.setEnd(snapshot.anchorNode, snapshot.anchorOffset)\n    range.collapse(false)\n    sel.removeAllRanges()\n    sel.addRange(range)\n    sel.extend(snapshot.focusNode, snapshot.focusOffset)\n  }\n}\n\n// Does the actual updating of the line display. Bails out\n// (returning false) when there is nothing to be done and forced is\n// false.\nexport function updateDisplayIfNeeded(cm, update) {\n  let display = cm.display, doc = cm.doc\n\n  if (update.editorIsHidden) {\n    resetView(cm)\n    return false\n  }\n\n  // Bail out if the visible area is already rendered and nothing changed.\n  if (!update.force &&\n      update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&\n      (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&\n      display.renderedView == display.view && countDirtyView(cm) == 0)\n    return false\n\n  if (maybeUpdateLineNumberWidth(cm)) {\n    resetView(cm)\n    update.dims = getDimensions(cm)\n  }\n\n  // Compute a suitable new viewport (from & to)\n  let end = doc.first + doc.size\n  let from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first)\n  let to = Math.min(end, update.visible.to + cm.options.viewportMargin)\n  if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom)\n  if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo)\n  if (sawCollapsedSpans) {\n    from = visualLineNo(cm.doc, from)\n    to = visualLineEndNo(cm.doc, to)\n  }\n\n  let different = from != display.viewFrom || to != display.viewTo ||\n    display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth\n  adjustView(cm, from, to)\n\n  display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom))\n  // Position the mover div to align with the current scroll position\n  cm.display.mover.style.top = display.viewOffset + \"px\"\n\n  let toUpdate = countDirtyView(cm)\n  if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&\n      (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))\n    return false\n\n  // For big changes, we hide the enclosing element during the\n  // update, since that speeds up the operations on most browsers.\n  let selSnapshot = selectionSnapshot(cm)\n  if (toUpdate > 4) display.lineDiv.style.display = \"none\"\n  patchDisplay(cm, display.updateLineNumbers, update.dims)\n  if (toUpdate > 4) display.lineDiv.style.display = \"\"\n  display.renderedView = display.view\n  // There might have been a widget with a focused element that got\n  // hidden or updated, if so re-focus it.\n  restoreSelection(selSnapshot)\n\n  // Prevent selection and cursors from interfering with the scroll\n  // width and height.\n  removeChildren(display.cursorDiv)\n  removeChildren(display.selectionDiv)\n  display.gutters.style.height = display.sizer.style.minHeight = 0\n\n  if (different) {\n    display.lastWrapHeight = update.wrapperHeight\n    display.lastWrapWidth = update.wrapperWidth\n    startWorker(cm, 400)\n  }\n\n  display.updateLineNumbers = null\n\n  return true\n}\n\nexport function postUpdateDisplay(cm, update) {\n  let viewport = update.viewport\n\n  for (let first = true;; first = false) {\n    if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {\n      // Clip forced viewport to actual scrollable area.\n      if (viewport && viewport.top != null)\n        viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}\n      // Updated line heights might result in the drawn area not\n      // actually covering the viewport. Keep looping until it does.\n      update.visible = visibleLines(cm.display, cm.doc, viewport)\n      if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)\n        break\n    }\n    if (!updateDisplayIfNeeded(cm, update)) break\n    updateHeightsInViewport(cm)\n    let barMeasure = measureForScrollbars(cm)\n    updateSelection(cm)\n    updateScrollbars(cm, barMeasure)\n    setDocumentHeight(cm, barMeasure)\n    update.force = false\n  }\n\n  update.signal(cm, \"update\", cm)\n  if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {\n    update.signal(cm, \"viewportChange\", cm, cm.display.viewFrom, cm.display.viewTo)\n    cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo\n  }\n}\n\nexport function updateDisplaySimple(cm, viewport) {\n  let update = new DisplayUpdate(cm, viewport)\n  if (updateDisplayIfNeeded(cm, update)) {\n    updateHeightsInViewport(cm)\n    postUpdateDisplay(cm, update)\n    let barMeasure = measureForScrollbars(cm)\n    updateSelection(cm)\n    updateScrollbars(cm, barMeasure)\n    setDocumentHeight(cm, barMeasure)\n    update.finish()\n  }\n}\n\n// Sync the actual display DOM structure with display.view, removing\n// nodes for lines that are no longer in view, and creating the ones\n// that are not there yet, and updating the ones that are out of\n// date.\nfunction patchDisplay(cm, updateNumbersFrom, dims) {\n  let display = cm.display, lineNumbers = cm.options.lineNumbers\n  let container = display.lineDiv, cur = container.firstChild\n\n  function rm(node) {\n    let next = node.nextSibling\n    // Works around a throw-scroll bug in OS X Webkit\n    if (webkit && mac && cm.display.currentWheelTarget == node)\n      node.style.display = \"none\"\n    else\n      node.parentNode.removeChild(node)\n    return next\n  }\n\n  let view = display.view, lineN = display.viewFrom\n  // Loop over the elements in the view, syncing cur (the DOM nodes\n  // in display.lineDiv) with the view as we go.\n  for (let i = 0; i < view.length; i++) {\n    let lineView = view[i]\n    if (lineView.hidden) {\n    } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet\n      let node = buildLineElement(cm, lineView, lineN, dims)\n      container.insertBefore(node, cur)\n    } else { // Already drawn\n      while (cur != lineView.node) cur = rm(cur)\n      let updateNumber = lineNumbers && updateNumbersFrom != null &&\n        updateNumbersFrom <= lineN && lineView.lineNumber\n      if (lineView.changes) {\n        if (indexOf(lineView.changes, \"gutter\") > -1) updateNumber = false\n        updateLineForChanges(cm, lineView, lineN, dims)\n      }\n      if (updateNumber) {\n        removeChildren(lineView.lineNumber)\n        lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))\n      }\n      cur = lineView.node.nextSibling\n    }\n    lineN += lineView.size\n  }\n  while (cur) cur = rm(cur)\n}\n\nexport function updateGutterSpace(cm) {\n  let width = cm.display.gutters.offsetWidth\n  cm.display.sizer.style.marginLeft = width + \"px\"\n}\n\nexport function setDocumentHeight(cm, measure) {\n  cm.display.sizer.style.minHeight = measure.docHeight + \"px\"\n  cm.display.heightForcer.style.top = measure.docHeight + \"px\"\n  cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + \"px\"\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/update_line.js",
    "content": "import { buildLineContent } from \"../line/line_data.js\"\nimport { lineNumberFor } from \"../line/utils_line.js\"\nimport { ie, ie_version } from \"../util/browser.js\"\nimport { elt } from \"../util/dom.js\"\nimport { signalLater } from \"../util/operation_group.js\"\n\n// When an aspect of a line changes, a string is added to\n// lineView.changes. This updates the relevant part of the line's\n// DOM structure.\nexport function updateLineForChanges(cm, lineView, lineN, dims) {\n  for (let j = 0; j < lineView.changes.length; j++) {\n    let type = lineView.changes[j]\n    if (type == \"text\") updateLineText(cm, lineView)\n    else if (type == \"gutter\") updateLineGutter(cm, lineView, lineN, dims)\n    else if (type == \"class\") updateLineClasses(cm, lineView)\n    else if (type == \"widget\") updateLineWidgets(cm, lineView, dims)\n  }\n  lineView.changes = null\n}\n\n// Lines with gutter elements, widgets or a background class need to\n// be wrapped, and have the extra elements added to the wrapper div\nfunction ensureLineWrapped(lineView) {\n  if (lineView.node == lineView.text) {\n    lineView.node = elt(\"div\", null, null, \"position: relative\")\n    if (lineView.text.parentNode)\n      lineView.text.parentNode.replaceChild(lineView.node, lineView.text)\n    lineView.node.appendChild(lineView.text)\n    if (ie && ie_version < 8) lineView.node.style.zIndex = 2\n  }\n  return lineView.node\n}\n\nfunction updateLineBackground(cm, lineView) {\n  let cls = lineView.bgClass ? lineView.bgClass + \" \" + (lineView.line.bgClass || \"\") : lineView.line.bgClass\n  if (cls) cls += \" CodeMirror-linebackground\"\n  if (lineView.background) {\n    if (cls) lineView.background.className = cls\n    else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null }\n  } else if (cls) {\n    let wrap = ensureLineWrapped(lineView)\n    lineView.background = wrap.insertBefore(elt(\"div\", null, cls), wrap.firstChild)\n    cm.display.input.setUneditable(lineView.background)\n  }\n}\n\n// Wrapper around buildLineContent which will reuse the structure\n// in display.externalMeasured when possible.\nfunction getLineContent(cm, lineView) {\n  let ext = cm.display.externalMeasured\n  if (ext && ext.line == lineView.line) {\n    cm.display.externalMeasured = null\n    lineView.measure = ext.measure\n    return ext.built\n  }\n  return buildLineContent(cm, lineView)\n}\n\n// Redraw the line's text. Interacts with the background and text\n// classes because the mode may output tokens that influence these\n// classes.\nfunction updateLineText(cm, lineView) {\n  let cls = lineView.text.className\n  let built = getLineContent(cm, lineView)\n  if (lineView.text == lineView.node) lineView.node = built.pre\n  lineView.text.parentNode.replaceChild(built.pre, lineView.text)\n  lineView.text = built.pre\n  if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {\n    lineView.bgClass = built.bgClass\n    lineView.textClass = built.textClass\n    updateLineClasses(cm, lineView)\n  } else if (cls) {\n    lineView.text.className = cls\n  }\n}\n\nfunction updateLineClasses(cm, lineView) {\n  updateLineBackground(cm, lineView)\n  if (lineView.line.wrapClass)\n    ensureLineWrapped(lineView).className = lineView.line.wrapClass\n  else if (lineView.node != lineView.text)\n    lineView.node.className = \"\"\n  let textClass = lineView.textClass ? lineView.textClass + \" \" + (lineView.line.textClass || \"\") : lineView.line.textClass\n  lineView.text.className = textClass || \"\"\n}\n\nfunction updateLineGutter(cm, lineView, lineN, dims) {\n  if (lineView.gutter) {\n    lineView.node.removeChild(lineView.gutter)\n    lineView.gutter = null\n  }\n  if (lineView.gutterBackground) {\n    lineView.node.removeChild(lineView.gutterBackground)\n    lineView.gutterBackground = null\n  }\n  if (lineView.line.gutterClass) {\n    let wrap = ensureLineWrapped(lineView)\n    lineView.gutterBackground = elt(\"div\", null, \"CodeMirror-gutter-background \" + lineView.line.gutterClass,\n                                    `left: ${cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth}px; width: ${dims.gutterTotalWidth}px`)\n    cm.display.input.setUneditable(lineView.gutterBackground)\n    wrap.insertBefore(lineView.gutterBackground, lineView.text)\n  }\n  let markers = lineView.line.gutterMarkers\n  if (cm.options.lineNumbers || markers) {\n    let wrap = ensureLineWrapped(lineView)\n    let gutterWrap = lineView.gutter = elt(\"div\", null, \"CodeMirror-gutter-wrapper\", `left: ${cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth}px`)\n    cm.display.input.setUneditable(gutterWrap)\n    wrap.insertBefore(gutterWrap, lineView.text)\n    if (lineView.line.gutterClass)\n      gutterWrap.className += \" \" + lineView.line.gutterClass\n    if (cm.options.lineNumbers && (!markers || !markers[\"CodeMirror-linenumbers\"]))\n      lineView.lineNumber = gutterWrap.appendChild(\n        elt(\"div\", lineNumberFor(cm.options, lineN),\n            \"CodeMirror-linenumber CodeMirror-gutter-elt\",\n            `left: ${dims.gutterLeft[\"CodeMirror-linenumbers\"]}px; width: ${cm.display.lineNumInnerWidth}px`))\n    if (markers) for (let k = 0; k < cm.options.gutters.length; ++k) {\n      let id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]\n      if (found)\n        gutterWrap.appendChild(elt(\"div\", [found], \"CodeMirror-gutter-elt\",\n                                   `left: ${dims.gutterLeft[id]}px; width: ${dims.gutterWidth[id]}px`))\n    }\n  }\n}\n\nfunction updateLineWidgets(cm, lineView, dims) {\n  if (lineView.alignable) lineView.alignable = null\n  for (let node = lineView.node.firstChild, next; node; node = next) {\n    next = node.nextSibling\n    if (node.className == \"CodeMirror-linewidget\")\n      lineView.node.removeChild(node)\n  }\n  insertLineWidgets(cm, lineView, dims)\n}\n\n// Build a line's DOM representation from scratch\nexport function buildLineElement(cm, lineView, lineN, dims) {\n  let built = getLineContent(cm, lineView)\n  lineView.text = lineView.node = built.pre\n  if (built.bgClass) lineView.bgClass = built.bgClass\n  if (built.textClass) lineView.textClass = built.textClass\n\n  updateLineClasses(cm, lineView)\n  updateLineGutter(cm, lineView, lineN, dims)\n  insertLineWidgets(cm, lineView, dims)\n  return lineView.node\n}\n\n// A lineView may contain multiple logical lines (when merged by\n// collapsed spans). The widgets for all of them need to be drawn.\nfunction insertLineWidgets(cm, lineView, dims) {\n  insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)\n  if (lineView.rest) for (let i = 0; i < lineView.rest.length; i++)\n    insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false)\n}\n\nfunction insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {\n  if (!line.widgets) return\n  let wrap = ensureLineWrapped(lineView)\n  for (let i = 0, ws = line.widgets; i < ws.length; ++i) {\n    let widget = ws[i], node = elt(\"div\", [widget.node], \"CodeMirror-linewidget\")\n    if (!widget.handleMouseEvents) node.setAttribute(\"cm-ignore-events\", \"true\")\n    positionLineWidget(widget, node, lineView, dims)\n    cm.display.input.setUneditable(node)\n    if (allowAbove && widget.above)\n      wrap.insertBefore(node, lineView.gutter || lineView.text)\n    else\n      wrap.appendChild(node)\n    signalLater(widget, \"redraw\")\n  }\n}\n\nfunction positionLineWidget(widget, node, lineView, dims) {\n  if (widget.noHScroll) {\n    ;(lineView.alignable || (lineView.alignable = [])).push(node)\n    let width = dims.wrapperWidth\n    node.style.left = dims.fixedPos + \"px\"\n    if (!widget.coverGutter) {\n      width -= dims.gutterTotalWidth\n      node.style.paddingLeft = dims.gutterTotalWidth + \"px\"\n    }\n    node.style.width = width + \"px\"\n  }\n  if (widget.coverGutter) {\n    node.style.zIndex = 5\n    node.style.position = \"relative\"\n    if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + \"px\"\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/update_lines.js",
    "content": "import { heightAtLine } from \"../line/spans.js\"\nimport { getLine, lineAtHeight, updateLineHeight } from \"../line/utils_line.js\"\nimport { paddingTop, textHeight, charWidth } from \"../measurement/position_measurement.js\"\nimport { ie, ie_version } from \"../util/browser.js\"\n\n// Read the actual heights of the rendered lines, and update their\n// stored heights to match.\nexport function updateHeightsInViewport(cm) {\n  let display = cm.display\n  let prevBottom = display.lineDiv.offsetTop\n  for (let i = 0; i < display.view.length; i++) {\n    let cur = display.view[i], wrapping = cm.options.lineWrapping\n    let height, width = 0\n    if (cur.hidden) continue\n    if (ie && ie_version < 8) {\n      let bot = cur.node.offsetTop + cur.node.offsetHeight\n      height = bot - prevBottom\n      prevBottom = bot\n    } else {\n      let box = cur.node.getBoundingClientRect()\n      height = box.bottom - box.top\n      // Check that lines don't extend past the right of the current\n      // editor width\n      if (!wrapping && cur.text.firstChild)\n        width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1\n    }\n    let diff = cur.line.height - height\n    if (height < 2) height = textHeight(display)\n    if (diff > .005 || diff < -.005) {\n      updateLineHeight(cur.line, height)\n      updateWidgetHeight(cur.line)\n      if (cur.rest) for (let j = 0; j < cur.rest.length; j++)\n        updateWidgetHeight(cur.rest[j])\n    }\n    if (width > cm.display.sizerWidth) {\n      let chWidth = Math.ceil(width / charWidth(cm.display))\n      if (chWidth > cm.display.maxLineLength) {\n        cm.display.maxLineLength = chWidth\n        cm.display.maxLine = cur.line\n        cm.display.maxLineChanged = true\n      }\n    }\n  }\n}\n\n// Read and store the height of line widgets associated with the\n// given line.\nfunction updateWidgetHeight(line) {\n  if (line.widgets) for (let i = 0; i < line.widgets.length; ++i) {\n    let w = line.widgets[i], parent = w.node.parentNode\n    if (parent) w.height = parent.offsetHeight\n  }\n}\n\n// Compute the lines that are visible in a given viewport (defaults\n// the the current scroll position). viewport may contain top,\n// height, and ensure (see op.scrollToPos) properties.\nexport function visibleLines(display, doc, viewport) {\n  let top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop\n  top = Math.floor(top - paddingTop(display))\n  let bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight\n\n  let from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom)\n  // Ensure is a {from: {line, ch}, to: {line, ch}} object, and\n  // forces those lines into the viewport (if possible).\n  if (viewport && viewport.ensure) {\n    let ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line\n    if (ensureFrom < from) {\n      from = ensureFrom\n      to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)\n    } else if (Math.min(ensureTo, doc.lastLine()) >= to) {\n      from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)\n      to = ensureTo\n    }\n  }\n  return {from: from, to: Math.max(to, from + 1)}\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/display/view_tracking.js",
    "content": "import { buildViewArray } from \"../line/line_data.js\"\nimport { sawCollapsedSpans } from \"../line/saw_special_spans.js\"\nimport { visualLineEndNo, visualLineNo } from \"../line/spans.js\"\nimport { findViewIndex } from \"../measurement/position_measurement.js\"\nimport { indexOf } from \"../util/misc.js\"\n\n// Updates the display.view data structure for a given change to the\n// document. From and to are in pre-change coordinates. Lendiff is\n// the amount of lines added or subtracted by the change. This is\n// used for changes that span multiple lines, or change the way\n// lines are divided into visual lines. regLineChange (below)\n// registers single-line changes.\nexport function regChange(cm, from, to, lendiff) {\n  if (from == null) from = cm.doc.first\n  if (to == null) to = cm.doc.first + cm.doc.size\n  if (!lendiff) lendiff = 0\n\n  let display = cm.display\n  if (lendiff && to < display.viewTo &&\n      (display.updateLineNumbers == null || display.updateLineNumbers > from))\n    display.updateLineNumbers = from\n\n  cm.curOp.viewChanged = true\n\n  if (from >= display.viewTo) { // Change after\n    if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)\n      resetView(cm)\n  } else if (to <= display.viewFrom) { // Change before\n    if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {\n      resetView(cm)\n    } else {\n      display.viewFrom += lendiff\n      display.viewTo += lendiff\n    }\n  } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap\n    resetView(cm)\n  } else if (from <= display.viewFrom) { // Top overlap\n    let cut = viewCuttingPoint(cm, to, to + lendiff, 1)\n    if (cut) {\n      display.view = display.view.slice(cut.index)\n      display.viewFrom = cut.lineN\n      display.viewTo += lendiff\n    } else {\n      resetView(cm)\n    }\n  } else if (to >= display.viewTo) { // Bottom overlap\n    let cut = viewCuttingPoint(cm, from, from, -1)\n    if (cut) {\n      display.view = display.view.slice(0, cut.index)\n      display.viewTo = cut.lineN\n    } else {\n      resetView(cm)\n    }\n  } else { // Gap in the middle\n    let cutTop = viewCuttingPoint(cm, from, from, -1)\n    let cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)\n    if (cutTop && cutBot) {\n      display.view = display.view.slice(0, cutTop.index)\n        .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))\n        .concat(display.view.slice(cutBot.index))\n      display.viewTo += lendiff\n    } else {\n      resetView(cm)\n    }\n  }\n\n  let ext = display.externalMeasured\n  if (ext) {\n    if (to < ext.lineN)\n      ext.lineN += lendiff\n    else if (from < ext.lineN + ext.size)\n      display.externalMeasured = null\n  }\n}\n\n// Register a change to a single line. Type must be one of \"text\",\n// \"gutter\", \"class\", \"widget\"\nexport function regLineChange(cm, line, type) {\n  cm.curOp.viewChanged = true\n  let display = cm.display, ext = cm.display.externalMeasured\n  if (ext && line >= ext.lineN && line < ext.lineN + ext.size)\n    display.externalMeasured = null\n\n  if (line < display.viewFrom || line >= display.viewTo) return\n  let lineView = display.view[findViewIndex(cm, line)]\n  if (lineView.node == null) return\n  let arr = lineView.changes || (lineView.changes = [])\n  if (indexOf(arr, type) == -1) arr.push(type)\n}\n\n// Clear the view.\nexport function resetView(cm) {\n  cm.display.viewFrom = cm.display.viewTo = cm.doc.first\n  cm.display.view = []\n  cm.display.viewOffset = 0\n}\n\nfunction viewCuttingPoint(cm, oldN, newN, dir) {\n  let index = findViewIndex(cm, oldN), diff, view = cm.display.view\n  if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)\n    return {index: index, lineN: newN}\n  let n = cm.display.viewFrom\n  for (let i = 0; i < index; i++)\n    n += view[i].size\n  if (n != oldN) {\n    if (dir > 0) {\n      if (index == view.length - 1) return null\n      diff = (n + view[index].size) - oldN\n      index++\n    } else {\n      diff = n - oldN\n    }\n    oldN += diff; newN += diff\n  }\n  while (visualLineNo(cm.doc, newN) != newN) {\n    if (index == (dir < 0 ? 0 : view.length - 1)) return null\n    newN += dir * view[index - (dir < 0 ? 1 : 0)].size\n    index += dir\n  }\n  return {index: index, lineN: newN}\n}\n\n// Force the view to cover a given range, adding empty view element\n// or clipping off existing ones as needed.\nexport function adjustView(cm, from, to) {\n  let display = cm.display, view = display.view\n  if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {\n    display.view = buildViewArray(cm, from, to)\n    display.viewFrom = from\n  } else {\n    if (display.viewFrom > from)\n      display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view)\n    else if (display.viewFrom < from)\n      display.view = display.view.slice(findViewIndex(cm, from))\n    display.viewFrom = from\n    if (display.viewTo < to)\n      display.view = display.view.concat(buildViewArray(cm, display.viewTo, to))\n    else if (display.viewTo > to)\n      display.view = display.view.slice(0, findViewIndex(cm, to))\n  }\n  display.viewTo = to\n}\n\n// Count the number of lines in the view whose DOM representation is\n// out of date (or nonexistent).\nexport function countDirtyView(cm) {\n  let view = cm.display.view, dirty = 0\n  for (let i = 0; i < view.length; i++) {\n    let lineView = view[i]\n    if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty\n  }\n  return dirty\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/CodeMirror.js",
    "content": "import { Display } from \"../display/Display.js\"\nimport { onFocus, onBlur } from \"../display/focus.js\"\nimport { setGuttersForLineNumbers, updateGutters } from \"../display/gutters.js\"\nimport { maybeUpdateLineNumberWidth } from \"../display/line_numbers.js\"\nimport { endOperation, operation, startOperation } from \"../display/operations.js\"\nimport { initScrollbars } from \"../display/scrollbars.js\"\nimport { onScrollWheel } from \"../display/scroll_events.js\"\nimport { setScrollLeft, updateScrollTop } from \"../display/scrolling.js\"\nimport { clipPos, Pos } from \"../line/pos.js\"\nimport { posFromMouse } from \"../measurement/position_measurement.js\"\nimport { eventInWidget } from \"../measurement/widgets.js\"\nimport Doc from \"../model/Doc.js\"\nimport { attachDoc } from \"../model/document_data.js\"\nimport { Range } from \"../model/selection.js\"\nimport { extendSelection } from \"../model/selection_updates.js\"\nimport { ie, ie_version, mobile, webkit } from \"../util/browser.js\"\nimport { e_preventDefault, e_stop, on, signal, signalDOMEvent } from \"../util/event.js\"\nimport { bind, copyObj, Delayed } from \"../util/misc.js\"\n\nimport { clearDragCursor, onDragOver, onDragStart, onDrop } from \"./drop_events.js\"\nimport { ensureGlobalHandlers } from \"./global_events.js\"\nimport { onKeyDown, onKeyPress, onKeyUp } from \"./key_events.js\"\nimport { clickInGutter, onContextMenu, onMouseDown } from \"./mouse_events.js\"\nimport { themeChanged } from \"./utils.js\"\nimport { defaults, optionHandlers, Init } from \"./options.js\"\n\n// A CodeMirror instance represents an editor. This is the object\n// that user code is usually dealing with.\n\nexport function CodeMirror(place, options) {\n  if (!(this instanceof CodeMirror)) return new CodeMirror(place, options)\n\n  this.options = options = options ? copyObj(options) : {}\n  // Determine effective options based on given values and defaults.\n  copyObj(defaults, options, false)\n  setGuttersForLineNumbers(options)\n\n  let doc = options.value\n  if (typeof doc == \"string\") doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction)\n  else if (options.mode) doc.modeOption = options.mode\n  this.doc = doc\n\n  let input = new CodeMirror.inputStyles[options.inputStyle](this)\n  let display = this.display = new Display(place, doc, input)\n  display.wrapper.CodeMirror = this\n  updateGutters(this)\n  themeChanged(this)\n  if (options.lineWrapping)\n    this.display.wrapper.className += \" CodeMirror-wrap\"\n  initScrollbars(this)\n\n  this.state = {\n    keyMaps: [],  // stores maps added by addKeyMap\n    overlays: [], // highlighting overlays, as added by addOverlay\n    modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info\n    overwrite: false,\n    delayingBlurEvent: false,\n    focused: false,\n    suppressEdits: false, // used to disable editing during key handlers when in readOnly mode\n    pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll\n    selectingText: false,\n    draggingText: false,\n    highlight: new Delayed(), // stores highlight worker timeout\n    keySeq: null,  // Unfinished key sequence\n    specialChars: null\n  }\n\n  if (options.autofocus && !mobile) display.input.focus()\n\n  // Override magic textarea content restore that IE sometimes does\n  // on our hidden textarea on reload\n  if (ie && ie_version < 11) setTimeout(() => this.display.input.reset(true), 20)\n\n  registerEventHandlers(this)\n  ensureGlobalHandlers()\n\n  startOperation(this)\n  this.curOp.forceUpdate = true\n  attachDoc(this, doc)\n\n  if ((options.autofocus && !mobile) || this.hasFocus())\n    setTimeout(bind(onFocus, this), 20)\n  else\n    onBlur(this)\n\n  for (let opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))\n    optionHandlers[opt](this, options[opt], Init)\n  maybeUpdateLineNumberWidth(this)\n  if (options.finishInit) options.finishInit(this)\n  for (let i = 0; i < initHooks.length; ++i) initHooks[i](this)\n  endOperation(this)\n  // Suppress optimizelegibility in Webkit, since it breaks text\n  // measuring on line wrapping boundaries.\n  if (webkit && options.lineWrapping &&\n      getComputedStyle(display.lineDiv).textRendering == \"optimizelegibility\")\n    display.lineDiv.style.textRendering = \"auto\"\n}\n\n// The default configuration options.\nCodeMirror.defaults = defaults\n// Functions to run when options are changed.\nCodeMirror.optionHandlers = optionHandlers\n\nexport default CodeMirror\n\n// Attach the necessary event handlers when initializing the editor\nfunction registerEventHandlers(cm) {\n  let d = cm.display\n  on(d.scroller, \"mousedown\", operation(cm, onMouseDown))\n  // Older IE's will not fire a second mousedown for a double click\n  if (ie && ie_version < 11)\n    on(d.scroller, \"dblclick\", operation(cm, e => {\n      if (signalDOMEvent(cm, e)) return\n      let pos = posFromMouse(cm, e)\n      if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return\n      e_preventDefault(e)\n      let word = cm.findWordAt(pos)\n      extendSelection(cm.doc, word.anchor, word.head)\n    }))\n  else\n    on(d.scroller, \"dblclick\", e => signalDOMEvent(cm, e) || e_preventDefault(e))\n  // Some browsers fire contextmenu *after* opening the menu, at\n  // which point we can't mess with it anymore. Context menu is\n  // handled in onMouseDown for these browsers.\n  on(d.scroller, \"contextmenu\", e => onContextMenu(cm, e))\n\n  // Used to suppress mouse event handling when a touch happens\n  let touchFinished, prevTouch = {end: 0}\n  function finishTouch() {\n    if (d.activeTouch) {\n      touchFinished = setTimeout(() => d.activeTouch = null, 1000)\n      prevTouch = d.activeTouch\n      prevTouch.end = +new Date\n    }\n  }\n  function isMouseLikeTouchEvent(e) {\n    if (e.touches.length != 1) return false\n    let touch = e.touches[0]\n    return touch.radiusX <= 1 && touch.radiusY <= 1\n  }\n  function farAway(touch, other) {\n    if (other.left == null) return true\n    let dx = other.left - touch.left, dy = other.top - touch.top\n    return dx * dx + dy * dy > 20 * 20\n  }\n  on(d.scroller, \"touchstart\", e => {\n    if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {\n      d.input.ensurePolled()\n      clearTimeout(touchFinished)\n      let now = +new Date\n      d.activeTouch = {start: now, moved: false,\n                       prev: now - prevTouch.end <= 300 ? prevTouch : null}\n      if (e.touches.length == 1) {\n        d.activeTouch.left = e.touches[0].pageX\n        d.activeTouch.top = e.touches[0].pageY\n      }\n    }\n  })\n  on(d.scroller, \"touchmove\", () => {\n    if (d.activeTouch) d.activeTouch.moved = true\n  })\n  on(d.scroller, \"touchend\", e => {\n    let touch = d.activeTouch\n    if (touch && !eventInWidget(d, e) && touch.left != null &&\n        !touch.moved && new Date - touch.start < 300) {\n      let pos = cm.coordsChar(d.activeTouch, \"page\"), range\n      if (!touch.prev || farAway(touch, touch.prev)) // Single tap\n        range = new Range(pos, pos)\n      else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap\n        range = cm.findWordAt(pos)\n      else // Triple tap\n        range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)))\n      cm.setSelection(range.anchor, range.head)\n      cm.focus()\n      e_preventDefault(e)\n    }\n    finishTouch()\n  })\n  on(d.scroller, \"touchcancel\", finishTouch)\n\n  // Sync scrolling between fake scrollbars and real scrollable\n  // area, ensure viewport is updated when scrolling.\n  on(d.scroller, \"scroll\", () => {\n    if (d.scroller.clientHeight) {\n      updateScrollTop(cm, d.scroller.scrollTop)\n      setScrollLeft(cm, d.scroller.scrollLeft, true)\n      signal(cm, \"scroll\", cm)\n    }\n  })\n\n  // Listen to wheel events in order to try and update the viewport on time.\n  on(d.scroller, \"mousewheel\", e => onScrollWheel(cm, e))\n  on(d.scroller, \"DOMMouseScroll\", e => onScrollWheel(cm, e))\n\n  // Prevent wrapper from ever scrolling\n  on(d.wrapper, \"scroll\", () => d.wrapper.scrollTop = d.wrapper.scrollLeft = 0)\n\n  d.dragFunctions = {\n    enter: e => {if (!signalDOMEvent(cm, e)) e_stop(e)},\n    over: e => {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }},\n    start: e => onDragStart(cm, e),\n    drop: operation(cm, onDrop),\n    leave: e => {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }}\n  }\n\n  let inp = d.input.getField()\n  on(inp, \"keyup\", e => onKeyUp.call(cm, e))\n  on(inp, \"keydown\", operation(cm, onKeyDown))\n  on(inp, \"keypress\", operation(cm, onKeyPress))\n  on(inp, \"focus\", e => onFocus(cm, e))\n  on(inp, \"blur\", e => onBlur(cm, e))\n}\n\nlet initHooks = []\nCodeMirror.defineInitHook = f => initHooks.push(f)\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/commands.js",
    "content": "import { deleteNearSelection } from \"./deleteNearSelection.js\"\nimport { runInOp } from \"../display/operations.js\"\nimport { ensureCursorVisible } from \"../display/scrolling.js\"\nimport { endOfLine } from \"../input/movement.js\"\nimport { clipPos, Pos } from \"../line/pos.js\"\nimport { visualLine, visualLineEnd } from \"../line/spans.js\"\nimport { getLine, lineNo } from \"../line/utils_line.js\"\nimport { Range } from \"../model/selection.js\"\nimport { selectAll } from \"../model/selection_updates.js\"\nimport { countColumn, sel_dontScroll, sel_move, spaceStr } from \"../util/misc.js\"\nimport { getOrder } from \"../util/bidi.js\"\n\n// Commands are parameter-less actions that can be performed on an\n// editor, mostly used for keybindings.\nexport let commands = {\n  selectAll: selectAll,\n  singleSelection: cm => cm.setSelection(cm.getCursor(\"anchor\"), cm.getCursor(\"head\"), sel_dontScroll),\n  killLine: cm => deleteNearSelection(cm, range => {\n    if (range.empty()) {\n      let len = getLine(cm.doc, range.head.line).text.length\n      if (range.head.ch == len && range.head.line < cm.lastLine())\n        return {from: range.head, to: Pos(range.head.line + 1, 0)}\n      else\n        return {from: range.head, to: Pos(range.head.line, len)}\n    } else {\n      return {from: range.from(), to: range.to()}\n    }\n  }),\n  deleteLine: cm => deleteNearSelection(cm, range => ({\n    from: Pos(range.from().line, 0),\n    to: clipPos(cm.doc, Pos(range.to().line + 1, 0))\n  })),\n  delLineLeft: cm => deleteNearSelection(cm, range => ({\n    from: Pos(range.from().line, 0), to: range.from()\n  })),\n  delWrappedLineLeft: cm => deleteNearSelection(cm, range => {\n    let top = cm.charCoords(range.head, \"div\").top + 5\n    let leftPos = cm.coordsChar({left: 0, top: top}, \"div\")\n    return {from: leftPos, to: range.from()}\n  }),\n  delWrappedLineRight: cm => deleteNearSelection(cm, range => {\n    let top = cm.charCoords(range.head, \"div\").top + 5\n    let rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\")\n    return {from: range.from(), to: rightPos }\n  }),\n  undo: cm => cm.undo(),\n  redo: cm => cm.redo(),\n  undoSelection: cm => cm.undoSelection(),\n  redoSelection: cm => cm.redoSelection(),\n  goDocStart: cm => cm.extendSelection(Pos(cm.firstLine(), 0)),\n  goDocEnd: cm => cm.extendSelection(Pos(cm.lastLine())),\n  goLineStart: cm => cm.extendSelectionsBy(range => lineStart(cm, range.head.line),\n    {origin: \"+move\", bias: 1}\n  ),\n  goLineStartSmart: cm => cm.extendSelectionsBy(range => lineStartSmart(cm, range.head),\n    {origin: \"+move\", bias: 1}\n  ),\n  goLineEnd: cm => cm.extendSelectionsBy(range => lineEnd(cm, range.head.line),\n    {origin: \"+move\", bias: -1}\n  ),\n  goLineRight: cm => cm.extendSelectionsBy(range => {\n    let top = cm.cursorCoords(range.head, \"div\").top + 5\n    return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\")\n  }, sel_move),\n  goLineLeft: cm => cm.extendSelectionsBy(range => {\n    let top = cm.cursorCoords(range.head, \"div\").top + 5\n    return cm.coordsChar({left: 0, top: top}, \"div\")\n  }, sel_move),\n  goLineLeftSmart: cm => cm.extendSelectionsBy(range => {\n    let top = cm.cursorCoords(range.head, \"div\").top + 5\n    let pos = cm.coordsChar({left: 0, top: top}, \"div\")\n    if (pos.ch < cm.getLine(pos.line).search(/\\S/)) return lineStartSmart(cm, range.head)\n    return pos\n  }, sel_move),\n  goLineUp: cm => cm.moveV(-1, \"line\"),\n  goLineDown: cm => cm.moveV(1, \"line\"),\n  goPageUp: cm => cm.moveV(-1, \"page\"),\n  goPageDown: cm => cm.moveV(1, \"page\"),\n  goCharLeft: cm => cm.moveH(-1, \"char\"),\n  goCharRight: cm => cm.moveH(1, \"char\"),\n  goColumnLeft: cm => cm.moveH(-1, \"column\"),\n  goColumnRight: cm => cm.moveH(1, \"column\"),\n  goWordLeft: cm => cm.moveH(-1, \"word\"),\n  goGroupRight: cm => cm.moveH(1, \"group\"),\n  goGroupLeft: cm => cm.moveH(-1, \"group\"),\n  goWordRight: cm => cm.moveH(1, \"word\"),\n  delCharBefore: cm => cm.deleteH(-1, \"char\"),\n  delCharAfter: cm => cm.deleteH(1, \"char\"),\n  delWordBefore: cm => cm.deleteH(-1, \"word\"),\n  delWordAfter: cm => cm.deleteH(1, \"word\"),\n  delGroupBefore: cm => cm.deleteH(-1, \"group\"),\n  delGroupAfter: cm => cm.deleteH(1, \"group\"),\n  indentAuto: cm => cm.indentSelection(\"smart\"),\n  indentMore: cm => cm.indentSelection(\"add\"),\n  indentLess: cm => cm.indentSelection(\"subtract\"),\n  insertTab: cm => cm.replaceSelection(\"\\t\"),\n  insertSoftTab: cm => {\n    let spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize\n    for (let i = 0; i < ranges.length; i++) {\n      let pos = ranges[i].from()\n      let col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)\n      spaces.push(spaceStr(tabSize - col % tabSize))\n    }\n    cm.replaceSelections(spaces)\n  },\n  defaultTab: cm => {\n    if (cm.somethingSelected()) cm.indentSelection(\"add\")\n    else cm.execCommand(\"insertTab\")\n  },\n  // Swap the two chars left and right of each selection's head.\n  // Move cursor behind the two swapped characters afterwards.\n  //\n  // Doesn't consider line feeds a character.\n  // Doesn't scan more than one line above to find a character.\n  // Doesn't do anything on an empty line.\n  // Doesn't do anything with non-empty selections.\n  transposeChars: cm => runInOp(cm, () => {\n    let ranges = cm.listSelections(), newSel = []\n    for (let i = 0; i < ranges.length; i++) {\n      if (!ranges[i].empty()) continue\n      let cur = ranges[i].head, line = getLine(cm.doc, cur.line).text\n      if (line) {\n        if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1)\n        if (cur.ch > 0) {\n          cur = new Pos(cur.line, cur.ch + 1)\n          cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),\n                          Pos(cur.line, cur.ch - 2), cur, \"+transpose\")\n        } else if (cur.line > cm.doc.first) {\n          let prev = getLine(cm.doc, cur.line - 1).text\n          if (prev) {\n            cur = new Pos(cur.line, 1)\n            cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +\n                            prev.charAt(prev.length - 1),\n                            Pos(cur.line - 1, prev.length - 1), cur, \"+transpose\")\n          }\n        }\n      }\n      newSel.push(new Range(cur, cur))\n    }\n    cm.setSelections(newSel)\n  }),\n  newlineAndIndent: cm => runInOp(cm, () => {\n    let sels = cm.listSelections()\n    for (let i = sels.length - 1; i >= 0; i--)\n      cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, \"+input\")\n    sels = cm.listSelections()\n    for (let i = 0; i < sels.length; i++)\n      cm.indentLine(sels[i].from().line, null, true)\n    ensureCursorVisible(cm)\n  }),\n  openLine: cm => cm.replaceSelection(\"\\n\", \"start\"),\n  toggleOverwrite: cm => cm.toggleOverwrite()\n}\n\n\nfunction lineStart(cm, lineN) {\n  let line = getLine(cm.doc, lineN)\n  let visual = visualLine(line)\n  if (visual != line) lineN = lineNo(visual)\n  return endOfLine(true, cm, visual, lineN, 1)\n}\nfunction lineEnd(cm, lineN) {\n  let line = getLine(cm.doc, lineN)\n  let visual = visualLineEnd(line)\n  if (visual != line) lineN = lineNo(visual)\n  return endOfLine(true, cm, line, lineN, -1)\n}\nfunction lineStartSmart(cm, pos) {\n  let start = lineStart(cm, pos.line)\n  let line = getLine(cm.doc, start.line)\n  let order = getOrder(line, cm.doc.direction)\n  if (!order || order[0].level == 0) {\n    let firstNonWS = Math.max(0, line.text.search(/\\S/))\n    let inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch\n    return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)\n  }\n  return start\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/deleteNearSelection.js",
    "content": "import { runInOp } from \"../display/operations.js\"\nimport { ensureCursorVisible } from \"../display/scrolling.js\"\nimport { cmp } from \"../line/pos.js\"\nimport { replaceRange } from \"../model/changes.js\"\nimport { lst } from \"../util/misc.js\"\n\n// Helper for deleting text near the selection(s), used to implement\n// backspace, delete, and similar functionality.\nexport function deleteNearSelection(cm, compute) {\n  let ranges = cm.doc.sel.ranges, kill = []\n  // Build up a set of ranges to kill first, merging overlapping\n  // ranges.\n  for (let i = 0; i < ranges.length; i++) {\n    let toKill = compute(ranges[i])\n    while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {\n      let replaced = kill.pop()\n      if (cmp(replaced.from, toKill.from) < 0) {\n        toKill.from = replaced.from\n        break\n      }\n    }\n    kill.push(toKill)\n  }\n  // Next, remove those actual ranges.\n  runInOp(cm, () => {\n    for (let i = kill.length - 1; i >= 0; i--)\n      replaceRange(cm.doc, \"\", kill[i].from, kill[i].to, \"+delete\")\n    ensureCursorVisible(cm)\n  })\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/drop_events.js",
    "content": "import { drawSelectionCursor } from \"../display/selection.js\"\nimport { operation } from \"../display/operations.js\"\nimport { clipPos } from \"../line/pos.js\"\nimport { posFromMouse } from \"../measurement/position_measurement.js\"\nimport { eventInWidget } from \"../measurement/widgets.js\"\nimport { makeChange, replaceRange } from \"../model/changes.js\"\nimport { changeEnd } from \"../model/change_measurement.js\"\nimport { simpleSelection } from \"../model/selection.js\"\nimport { setSelectionNoUndo, setSelectionReplaceHistory } from \"../model/selection_updates.js\"\nimport { ie, presto, safari } from \"../util/browser.js\"\nimport { elt, removeChildrenAndAdd } from \"../util/dom.js\"\nimport { e_preventDefault, e_stop, signalDOMEvent } from \"../util/event.js\"\nimport { indexOf } from \"../util/misc.js\"\n\n// Kludge to work around strange IE behavior where it'll sometimes\n// re-fire a series of drag-related events right after the drop (#1551)\nlet lastDrop = 0\n\nexport function onDrop(e) {\n  let cm = this\n  clearDragCursor(cm)\n  if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))\n    return\n  e_preventDefault(e)\n  if (ie) lastDrop = +new Date\n  let pos = posFromMouse(cm, e, true), files = e.dataTransfer.files\n  if (!pos || cm.isReadOnly()) return\n  // Might be a file drop, in which case we simply extract the text\n  // and insert it.\n  if (files && files.length && window.FileReader && window.File) {\n    let n = files.length, text = Array(n), read = 0\n    let loadFile = (file, i) => {\n      if (cm.options.allowDropFileTypes &&\n          indexOf(cm.options.allowDropFileTypes, file.type) == -1)\n        return\n\n      let reader = new FileReader\n      reader.onload = operation(cm, () => {\n        let content = reader.result\n        if (/[\\x00-\\x08\\x0e-\\x1f]{2}/.test(content)) content = \"\"\n        text[i] = content\n        if (++read == n) {\n          pos = clipPos(cm.doc, pos)\n          let change = {from: pos, to: pos,\n                        text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),\n                        origin: \"paste\"}\n          makeChange(cm.doc, change)\n          setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))\n        }\n      })\n      reader.readAsText(file)\n    }\n    for (let i = 0; i < n; ++i) loadFile(files[i], i)\n  } else { // Normal drop\n    // Don't do a replace if the drop happened inside of the selected text.\n    if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {\n      cm.state.draggingText(e)\n      // Ensure the editor is re-focused\n      setTimeout(() => cm.display.input.focus(), 20)\n      return\n    }\n    try {\n      let text = e.dataTransfer.getData(\"Text\")\n      if (text) {\n        let selected\n        if (cm.state.draggingText && !cm.state.draggingText.copy)\n          selected = cm.listSelections()\n        setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))\n        if (selected) for (let i = 0; i < selected.length; ++i)\n          replaceRange(cm.doc, \"\", selected[i].anchor, selected[i].head, \"drag\")\n        cm.replaceSelection(text, \"around\", \"paste\")\n        cm.display.input.focus()\n      }\n    }\n    catch(e){}\n  }\n}\n\nexport function onDragStart(cm, e) {\n  if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }\n  if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return\n\n  e.dataTransfer.setData(\"Text\", cm.getSelection())\n  e.dataTransfer.effectAllowed = \"copyMove\"\n\n  // Use dummy image instead of default browsers image.\n  // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.\n  if (e.dataTransfer.setDragImage && !safari) {\n    let img = elt(\"img\", null, null, \"position: fixed; left: 0; top: 0;\")\n    img.src = \"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\"\n    if (presto) {\n      img.width = img.height = 1\n      cm.display.wrapper.appendChild(img)\n      // Force a relayout, or Opera won't use our image for some obscure reason\n      img._top = img.offsetTop\n    }\n    e.dataTransfer.setDragImage(img, 0, 0)\n    if (presto) img.parentNode.removeChild(img)\n  }\n}\n\nexport function onDragOver(cm, e) {\n  let pos = posFromMouse(cm, e)\n  if (!pos) return\n  let frag = document.createDocumentFragment()\n  drawSelectionCursor(cm, pos, frag)\n  if (!cm.display.dragCursor) {\n    cm.display.dragCursor = elt(\"div\", null, \"CodeMirror-cursors CodeMirror-dragcursors\")\n    cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)\n  }\n  removeChildrenAndAdd(cm.display.dragCursor, frag)\n}\n\nexport function clearDragCursor(cm) {\n  if (cm.display.dragCursor) {\n    cm.display.lineSpace.removeChild(cm.display.dragCursor)\n    cm.display.dragCursor = null\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/fromTextArea.js",
    "content": "import { CodeMirror } from \"./CodeMirror.js\"\nimport { activeElt } from \"../util/dom.js\"\nimport { off, on } from \"../util/event.js\"\nimport { copyObj } from \"../util/misc.js\"\n\nexport function fromTextArea(textarea, options) {\n  options = options ? copyObj(options) : {}\n  options.value = textarea.value\n  if (!options.tabindex && textarea.tabIndex)\n    options.tabindex = textarea.tabIndex\n  if (!options.placeholder && textarea.placeholder)\n    options.placeholder = textarea.placeholder\n  // Set autofocus to true if this textarea is focused, or if it has\n  // autofocus and no other element is focused.\n  if (options.autofocus == null) {\n    let hasFocus = activeElt()\n    options.autofocus = hasFocus == textarea ||\n      textarea.getAttribute(\"autofocus\") != null && hasFocus == document.body\n  }\n\n  function save() {textarea.value = cm.getValue()}\n\n  let realSubmit\n  if (textarea.form) {\n    on(textarea.form, \"submit\", save)\n    // Deplorable hack to make the submit method do the right thing.\n    if (!options.leaveSubmitMethodAlone) {\n      let form = textarea.form\n      realSubmit = form.submit\n      try {\n        let wrappedSubmit = form.submit = () => {\n          save()\n          form.submit = realSubmit\n          form.submit()\n          form.submit = wrappedSubmit\n        }\n      } catch(e) {}\n    }\n  }\n\n  options.finishInit = cm => {\n    cm.save = save\n    cm.getTextArea = () => textarea\n    cm.toTextArea = () => {\n      cm.toTextArea = isNaN // Prevent this from being ran twice\n      save()\n      textarea.parentNode.removeChild(cm.getWrapperElement())\n      textarea.style.display = \"\"\n      if (textarea.form) {\n        off(textarea.form, \"submit\", save)\n        if (typeof textarea.form.submit == \"function\")\n          textarea.form.submit = realSubmit\n      }\n    }\n  }\n\n  textarea.style.display = \"none\"\n  let cm = CodeMirror(node => textarea.parentNode.insertBefore(node, textarea.nextSibling),\n    options)\n  return cm\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/global_events.js",
    "content": "import { onBlur } from \"../display/focus.js\"\nimport { on } from \"../util/event.js\"\n\n// These must be handled carefully, because naively registering a\n// handler for each editor will cause the editors to never be\n// garbage collected.\n\nfunction forEachCodeMirror(f) {\n  if (!document.getElementsByClassName) return\n  let byClass = document.getElementsByClassName(\"CodeMirror\"), editors = []\n  for (let i = 0; i < byClass.length; i++) {\n    let cm = byClass[i].CodeMirror\n    if (cm) editors.push(cm)\n  }\n  if (editors.length) editors[0].operation(() => {\n    for (let i = 0; i < editors.length; i++) f(editors[i])\n  })\n}\n\nlet globalsRegistered = false\nexport function ensureGlobalHandlers() {\n  if (globalsRegistered) return\n  registerGlobalHandlers()\n  globalsRegistered = true\n}\nfunction registerGlobalHandlers() {\n  // When the window resizes, we need to refresh active editors.\n  let resizeTimer\n  on(window, \"resize\", () => {\n    if (resizeTimer == null) resizeTimer = setTimeout(() => {\n      resizeTimer = null\n      forEachCodeMirror(onResize)\n    }, 100)\n  })\n  // When the window loses focus, we want to show the editor as blurred\n  on(window, \"blur\", () => forEachCodeMirror(onBlur))\n}\n// Called when the window resizes\nfunction onResize(cm) {\n  let d = cm.display\n  // Might be a text scaling operation, clear size caches.\n  d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null\n  d.scrollbarsClipped = false\n  cm.setSize()\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/key_events.js",
    "content": "import { signalLater } from \"../util/operation_group.js\"\nimport { restartBlink } from \"../display/selection.js\"\nimport { isModifierKey, keyName, lookupKey } from \"../input/keymap.js\"\nimport { eventInWidget } from \"../measurement/widgets.js\"\nimport { ie, ie_version, mac, presto } from \"../util/browser.js\"\nimport { activeElt, addClass, rmClass } from \"../util/dom.js\"\nimport { e_preventDefault, off, on, signalDOMEvent } from \"../util/event.js\"\nimport { hasCopyEvent } from \"../util/feature_detection.js\"\nimport { Delayed, Pass } from \"../util/misc.js\"\n\nimport { commands } from \"./commands.js\"\n\n// Run a handler that was bound to a key.\nfunction doHandleBinding(cm, bound, dropShift) {\n  if (typeof bound == \"string\") {\n    bound = commands[bound]\n    if (!bound) return false\n  }\n  // Ensure previous input has been read, so that the handler sees a\n  // consistent view of the document\n  cm.display.input.ensurePolled()\n  let prevShift = cm.display.shift, done = false\n  try {\n    if (cm.isReadOnly()) cm.state.suppressEdits = true\n    if (dropShift) cm.display.shift = false\n    done = bound(cm) != Pass\n  } finally {\n    cm.display.shift = prevShift\n    cm.state.suppressEdits = false\n  }\n  return done\n}\n\nfunction lookupKeyForEditor(cm, name, handle) {\n  for (let i = 0; i < cm.state.keyMaps.length; i++) {\n    let result = lookupKey(name, cm.state.keyMaps[i], handle, cm)\n    if (result) return result\n  }\n  return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))\n    || lookupKey(name, cm.options.keyMap, handle, cm)\n}\n\n// Note that, despite the name, this function is also used to check\n// for bound mouse clicks.\n\nlet stopSeq = new Delayed\n\nexport function dispatchKey(cm, name, e, handle) {\n  let seq = cm.state.keySeq\n  if (seq) {\n    if (isModifierKey(name)) return \"handled\"\n    if (/\\'$/.test(name))\n      cm.state.keySeq = null\n    else\n      stopSeq.set(50, () => {\n        if (cm.state.keySeq == seq) {\n          cm.state.keySeq = null\n          cm.display.input.reset()\n        }\n      })\n    if (dispatchKeyInner(cm, seq + \" \" + name, e, handle)) return true\n  }\n  return dispatchKeyInner(cm, name, e, handle)\n}\n\nfunction dispatchKeyInner(cm, name, e, handle) {\n  let result = lookupKeyForEditor(cm, name, handle)\n\n  if (result == \"multi\")\n    cm.state.keySeq = name\n  if (result == \"handled\")\n    signalLater(cm, \"keyHandled\", cm, name, e)\n\n  if (result == \"handled\" || result == \"multi\") {\n    e_preventDefault(e)\n    restartBlink(cm)\n  }\n\n  return !!result\n}\n\n// Handle a key from the keydown event.\nfunction handleKeyBinding(cm, e) {\n  let name = keyName(e, true)\n  if (!name) return false\n\n  if (e.shiftKey && !cm.state.keySeq) {\n    // First try to resolve full name (including 'Shift-'). Failing\n    // that, see if there is a cursor-motion command (starting with\n    // 'go') bound to the keyname without 'Shift-'.\n    return dispatchKey(cm, \"Shift-\" + name, e, b => doHandleBinding(cm, b, true))\n        || dispatchKey(cm, name, e, b => {\n             if (typeof b == \"string\" ? /^go[A-Z]/.test(b) : b.motion)\n               return doHandleBinding(cm, b)\n           })\n  } else {\n    return dispatchKey(cm, name, e, b => doHandleBinding(cm, b))\n  }\n}\n\n// Handle a key from the keypress event\nfunction handleCharBinding(cm, e, ch) {\n  return dispatchKey(cm, \"'\" + ch + \"'\", e, b => doHandleBinding(cm, b, true))\n}\n\nlet lastStoppedKey = null\nexport function onKeyDown(e) {\n  let cm = this\n  cm.curOp.focus = activeElt()\n  if (signalDOMEvent(cm, e)) return\n  // IE does strange things with escape.\n  if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false\n  let code = e.keyCode\n  cm.display.shift = code == 16 || e.shiftKey\n  let handled = handleKeyBinding(cm, e)\n  if (presto) {\n    lastStoppedKey = handled ? code : null\n    // Opera has no cut event... we try to at least catch the key combo\n    if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))\n      cm.replaceSelection(\"\", null, \"cut\")\n  }\n\n  // Turn mouse into crosshair when Alt is held on Mac.\n  if (code == 18 && !/\\bCodeMirror-crosshair\\b/.test(cm.display.lineDiv.className))\n    showCrossHair(cm)\n}\n\nfunction showCrossHair(cm) {\n  let lineDiv = cm.display.lineDiv\n  addClass(lineDiv, \"CodeMirror-crosshair\")\n\n  function up(e) {\n    if (e.keyCode == 18 || !e.altKey) {\n      rmClass(lineDiv, \"CodeMirror-crosshair\")\n      off(document, \"keyup\", up)\n      off(document, \"mouseover\", up)\n    }\n  }\n  on(document, \"keyup\", up)\n  on(document, \"mouseover\", up)\n}\n\nexport function onKeyUp(e) {\n  if (e.keyCode == 16) this.doc.sel.shift = false\n  signalDOMEvent(this, e)\n}\n\nexport function onKeyPress(e) {\n  let cm = this\n  if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return\n  let keyCode = e.keyCode, charCode = e.charCode\n  if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}\n  if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return\n  let ch = String.fromCharCode(charCode == null ? keyCode : charCode)\n  // Some browsers fire keypress events for backspace\n  if (ch == \"\\x08\") return\n  if (handleCharBinding(cm, e, ch)) return\n  cm.display.input.onKeyPress(e)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/legacy.js",
    "content": "import { scrollbarModel } from \"../display/scrollbars.js\"\nimport { wheelEventPixels } from \"../display/scroll_events.js\"\nimport { keyMap, keyName, isModifierKey, lookupKey, normalizeKeyMap } from \"../input/keymap.js\"\nimport { keyNames } from \"../input/keynames.js\"\nimport { Line } from \"../line/line_data.js\"\nimport { cmp, Pos } from \"../line/pos.js\"\nimport { changeEnd } from \"../model/change_measurement.js\"\nimport Doc from \"../model/Doc.js\"\nimport { LineWidget } from \"../model/line_widget.js\"\nimport { SharedTextMarker, TextMarker } from \"../model/mark_text.js\"\nimport { copyState, extendMode, getMode, innerMode, mimeModes, modeExtensions, modes, resolveMode, startState } from \"../modes.js\"\nimport { addClass, contains, rmClass } from \"../util/dom.js\"\nimport { e_preventDefault, e_stop, e_stopPropagation, off, on, signal } from \"../util/event.js\"\nimport { splitLinesAuto } from \"../util/feature_detection.js\"\nimport { countColumn, findColumn, isWordCharBasic, Pass } from \"../util/misc.js\"\nimport StringStream from \"../util/StringStream.js\"\n\nimport { commands } from \"./commands.js\"\n\nexport function addLegacyProps(CodeMirror) {\n  CodeMirror.off = off\n  CodeMirror.on = on\n  CodeMirror.wheelEventPixels = wheelEventPixels\n  CodeMirror.Doc = Doc\n  CodeMirror.splitLines = splitLinesAuto\n  CodeMirror.countColumn = countColumn\n  CodeMirror.findColumn = findColumn\n  CodeMirror.isWordChar = isWordCharBasic\n  CodeMirror.Pass = Pass\n  CodeMirror.signal = signal\n  CodeMirror.Line = Line\n  CodeMirror.changeEnd = changeEnd\n  CodeMirror.scrollbarModel = scrollbarModel\n  CodeMirror.Pos = Pos\n  CodeMirror.cmpPos = cmp\n  CodeMirror.modes = modes\n  CodeMirror.mimeModes = mimeModes\n  CodeMirror.resolveMode = resolveMode\n  CodeMirror.getMode = getMode\n  CodeMirror.modeExtensions = modeExtensions\n  CodeMirror.extendMode = extendMode\n  CodeMirror.copyState = copyState\n  CodeMirror.startState = startState\n  CodeMirror.innerMode = innerMode\n  CodeMirror.commands = commands\n  CodeMirror.keyMap = keyMap\n  CodeMirror.keyName = keyName\n  CodeMirror.isModifierKey = isModifierKey\n  CodeMirror.lookupKey = lookupKey\n  CodeMirror.normalizeKeyMap = normalizeKeyMap\n  CodeMirror.StringStream = StringStream\n  CodeMirror.SharedTextMarker = SharedTextMarker\n  CodeMirror.TextMarker = TextMarker\n  CodeMirror.LineWidget = LineWidget\n  CodeMirror.e_preventDefault = e_preventDefault\n  CodeMirror.e_stopPropagation = e_stopPropagation\n  CodeMirror.e_stop = e_stop\n  CodeMirror.addClass = addClass\n  CodeMirror.contains = contains\n  CodeMirror.rmClass = rmClass\n  CodeMirror.keyNames = keyNames\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/main.js",
    "content": "// EDITOR CONSTRUCTOR\n\nimport { CodeMirror } from \"./CodeMirror.js\"\nexport { CodeMirror } from \"./CodeMirror.js\"\n\nimport { eventMixin } from \"../util/event.js\"\nimport { indexOf } from \"../util/misc.js\"\n\nimport { defineOptions } from \"./options.js\"\n\ndefineOptions(CodeMirror)\n\nimport addEditorMethods from \"./methods.js\"\n\naddEditorMethods(CodeMirror)\n\nimport Doc from \"../model/Doc.js\"\n\n// Set up methods on CodeMirror's prototype to redirect to the editor's document.\nlet dontDelegate = \"iter insert remove copy getEditor constructor\".split(\" \")\nfor (let prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)\n  CodeMirror.prototype[prop] = (function(method) {\n    return function() {return method.apply(this.doc, arguments)}\n  })(Doc.prototype[prop])\n\neventMixin(Doc)\n\n// INPUT HANDLING\n\nimport ContentEditableInput from \"../input/ContentEditableInput.js\"\nimport TextareaInput from \"../input/TextareaInput.js\"\nCodeMirror.inputStyles = {\"textarea\": TextareaInput, \"contenteditable\": ContentEditableInput}\n\n// MODE DEFINITION AND QUERYING\n\nimport { defineMIME, defineMode } from \"../modes.js\"\n\n// Extra arguments are stored as the mode's dependencies, which is\n// used by (legacy) mechanisms like loadmode.js to automatically\n// load a mode. (Preferred mechanism is the require/define calls.)\nCodeMirror.defineMode = function(name/*, mode, …*/) {\n  if (!CodeMirror.defaults.mode && name != \"null\") CodeMirror.defaults.mode = name\n  defineMode.apply(this, arguments)\n}\n\nCodeMirror.defineMIME = defineMIME\n\n// Minimal default mode.\nCodeMirror.defineMode(\"null\", () => ({token: stream => stream.skipToEnd()}))\nCodeMirror.defineMIME(\"text/plain\", \"null\")\n\n// EXTENSIONS\n\nCodeMirror.defineExtension = (name, func) => {\n  CodeMirror.prototype[name] = func\n}\nCodeMirror.defineDocExtension = (name, func) => {\n  Doc.prototype[name] = func\n}\n\nimport { fromTextArea } from \"./fromTextArea.js\"\n\nCodeMirror.fromTextArea = fromTextArea\n\nimport { addLegacyProps } from \"./legacy.js\"\n\naddLegacyProps(CodeMirror)\n\nCodeMirror.version = \"5.43.0\"\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/methods.js",
    "content": "import { deleteNearSelection } from \"./deleteNearSelection.js\"\nimport { commands } from \"./commands.js\"\nimport { attachDoc } from \"../model/document_data.js\"\nimport { activeElt, addClass, rmClass } from \"../util/dom.js\"\nimport { eventMixin, signal } from \"../util/event.js\"\nimport { getLineStyles, getContextBefore, takeToken } from \"../line/highlight.js\"\nimport { indentLine } from \"../input/indent.js\"\nimport { triggerElectric } from \"../input/input.js\"\nimport { onKeyDown, onKeyPress, onKeyUp } from \"./key_events.js\"\nimport { onMouseDown } from \"./mouse_events.js\"\nimport { getKeyMap } from \"../input/keymap.js\"\nimport { endOfLine, moveLogically, moveVisually } from \"../input/movement.js\"\nimport { endOperation, methodOp, operation, runInOp, startOperation } from \"../display/operations.js\"\nimport { clipLine, clipPos, equalCursorPos, Pos } from \"../line/pos.js\"\nimport { charCoords, charWidth, clearCaches, clearLineMeasurementCache, coordsChar, cursorCoords, displayHeight, displayWidth, estimateLineHeights, fromCoordSystem, intoCoordSystem, scrollGap, textHeight } from \"../measurement/position_measurement.js\"\nimport { Range } from \"../model/selection.js\"\nimport { replaceOneSelection, skipAtomic } from \"../model/selection_updates.js\"\nimport { addToScrollTop, ensureCursorVisible, scrollIntoView, scrollToCoords, scrollToCoordsRange, scrollToRange } from \"../display/scrolling.js\"\nimport { heightAtLine } from \"../line/spans.js\"\nimport { updateGutterSpace } from \"../display/update_display.js\"\nimport { indexOf, insertSorted, isWordChar, sel_dontScroll, sel_move } from \"../util/misc.js\"\nimport { signalLater } from \"../util/operation_group.js\"\nimport { getLine, isLine, lineAtHeight } from \"../line/utils_line.js\"\nimport { regChange, regLineChange } from \"../display/view_tracking.js\"\n\n// The publicly visible API. Note that methodOp(f) means\n// 'wrap f in an operation, performed on its `this` parameter'.\n\n// This is not the complete set of editor methods. Most of the\n// methods defined on the Doc type are also injected into\n// CodeMirror.prototype, for backwards compatibility and\n// convenience.\n\nexport default function(CodeMirror) {\n  let optionHandlers = CodeMirror.optionHandlers\n\n  let helpers = CodeMirror.helpers = {}\n\n  CodeMirror.prototype = {\n    constructor: CodeMirror,\n    focus: function(){window.focus(); this.display.input.focus()},\n\n    setOption: function(option, value) {\n      let options = this.options, old = options[option]\n      if (options[option] == value && option != \"mode\") return\n      options[option] = value\n      if (optionHandlers.hasOwnProperty(option))\n        operation(this, optionHandlers[option])(this, value, old)\n      signal(this, \"optionChange\", this, option)\n    },\n\n    getOption: function(option) {return this.options[option]},\n    getDoc: function() {return this.doc},\n\n    addKeyMap: function(map, bottom) {\n      this.state.keyMaps[bottom ? \"push\" : \"unshift\"](getKeyMap(map))\n    },\n    removeKeyMap: function(map) {\n      let maps = this.state.keyMaps\n      for (let i = 0; i < maps.length; ++i)\n        if (maps[i] == map || maps[i].name == map) {\n          maps.splice(i, 1)\n          return true\n        }\n    },\n\n    addOverlay: methodOp(function(spec, options) {\n      let mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)\n      if (mode.startState) throw new Error(\"Overlays may not be stateful.\")\n      insertSorted(this.state.overlays,\n                   {mode: mode, modeSpec: spec, opaque: options && options.opaque,\n                    priority: (options && options.priority) || 0},\n                   overlay => overlay.priority)\n      this.state.modeGen++\n      regChange(this)\n    }),\n    removeOverlay: methodOp(function(spec) {\n      let overlays = this.state.overlays\n      for (let i = 0; i < overlays.length; ++i) {\n        let cur = overlays[i].modeSpec\n        if (cur == spec || typeof spec == \"string\" && cur.name == spec) {\n          overlays.splice(i, 1)\n          this.state.modeGen++\n          regChange(this)\n          return\n        }\n      }\n    }),\n\n    indentLine: methodOp(function(n, dir, aggressive) {\n      if (typeof dir != \"string\" && typeof dir != \"number\") {\n        if (dir == null) dir = this.options.smartIndent ? \"smart\" : \"prev\"\n        else dir = dir ? \"add\" : \"subtract\"\n      }\n      if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive)\n    }),\n    indentSelection: methodOp(function(how) {\n      let ranges = this.doc.sel.ranges, end = -1\n      for (let i = 0; i < ranges.length; i++) {\n        let range = ranges[i]\n        if (!range.empty()) {\n          let from = range.from(), to = range.to()\n          let start = Math.max(end, from.line)\n          end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1\n          for (let j = start; j < end; ++j)\n            indentLine(this, j, how)\n          let newRanges = this.doc.sel.ranges\n          if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)\n            replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll)\n        } else if (range.head.line > end) {\n          indentLine(this, range.head.line, how, true)\n          end = range.head.line\n          if (i == this.doc.sel.primIndex) ensureCursorVisible(this)\n        }\n      }\n    }),\n\n    // Fetch the parser token for a given character. Useful for hacks\n    // that want to inspect the mode state (say, for completion).\n    getTokenAt: function(pos, precise) {\n      return takeToken(this, pos, precise)\n    },\n\n    getLineTokens: function(line, precise) {\n      return takeToken(this, Pos(line), precise, true)\n    },\n\n    getTokenTypeAt: function(pos) {\n      pos = clipPos(this.doc, pos)\n      let styles = getLineStyles(this, getLine(this.doc, pos.line))\n      let before = 0, after = (styles.length - 1) / 2, ch = pos.ch\n      let type\n      if (ch == 0) type = styles[2]\n      else for (;;) {\n        let mid = (before + after) >> 1\n        if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid\n        else if (styles[mid * 2 + 1] < ch) before = mid + 1\n        else { type = styles[mid * 2 + 2]; break }\n      }\n      let cut = type ? type.indexOf(\"overlay \") : -1\n      return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)\n    },\n\n    getModeAt: function(pos) {\n      let mode = this.doc.mode\n      if (!mode.innerMode) return mode\n      return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode\n    },\n\n    getHelper: function(pos, type) {\n      return this.getHelpers(pos, type)[0]\n    },\n\n    getHelpers: function(pos, type) {\n      let found = []\n      if (!helpers.hasOwnProperty(type)) return found\n      let help = helpers[type], mode = this.getModeAt(pos)\n      if (typeof mode[type] == \"string\") {\n        if (help[mode[type]]) found.push(help[mode[type]])\n      } else if (mode[type]) {\n        for (let i = 0; i < mode[type].length; i++) {\n          let val = help[mode[type][i]]\n          if (val) found.push(val)\n        }\n      } else if (mode.helperType && help[mode.helperType]) {\n        found.push(help[mode.helperType])\n      } else if (help[mode.name]) {\n        found.push(help[mode.name])\n      }\n      for (let i = 0; i < help._global.length; i++) {\n        let cur = help._global[i]\n        if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)\n          found.push(cur.val)\n      }\n      return found\n    },\n\n    getStateAfter: function(line, precise) {\n      let doc = this.doc\n      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)\n      return getContextBefore(this, line + 1, precise).state\n    },\n\n    cursorCoords: function(start, mode) {\n      let pos, range = this.doc.sel.primary()\n      if (start == null) pos = range.head\n      else if (typeof start == \"object\") pos = clipPos(this.doc, start)\n      else pos = start ? range.from() : range.to()\n      return cursorCoords(this, pos, mode || \"page\")\n    },\n\n    charCoords: function(pos, mode) {\n      return charCoords(this, clipPos(this.doc, pos), mode || \"page\")\n    },\n\n    coordsChar: function(coords, mode) {\n      coords = fromCoordSystem(this, coords, mode || \"page\")\n      return coordsChar(this, coords.left, coords.top)\n    },\n\n    lineAtHeight: function(height, mode) {\n      height = fromCoordSystem(this, {top: height, left: 0}, mode || \"page\").top\n      return lineAtHeight(this.doc, height + this.display.viewOffset)\n    },\n    heightAtLine: function(line, mode, includeWidgets) {\n      let end = false, lineObj\n      if (typeof line == \"number\") {\n        let last = this.doc.first + this.doc.size - 1\n        if (line < this.doc.first) line = this.doc.first\n        else if (line > last) { line = last; end = true }\n        lineObj = getLine(this.doc, line)\n      } else {\n        lineObj = line\n      }\n      return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || \"page\", includeWidgets || end).top +\n        (end ? this.doc.height - heightAtLine(lineObj) : 0)\n    },\n\n    defaultTextHeight: function() { return textHeight(this.display) },\n    defaultCharWidth: function() { return charWidth(this.display) },\n\n    getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},\n\n    addWidget: function(pos, node, scroll, vert, horiz) {\n      let display = this.display\n      pos = cursorCoords(this, clipPos(this.doc, pos))\n      let top = pos.bottom, left = pos.left\n      node.style.position = \"absolute\"\n      node.setAttribute(\"cm-ignore-events\", \"true\")\n      this.display.input.setUneditable(node)\n      display.sizer.appendChild(node)\n      if (vert == \"over\") {\n        top = pos.top\n      } else if (vert == \"above\" || vert == \"near\") {\n        let vspace = Math.max(display.wrapper.clientHeight, this.doc.height),\n        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)\n        // Default to positioning above (if specified and possible); otherwise default to positioning below\n        if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)\n          top = pos.top - node.offsetHeight\n        else if (pos.bottom + node.offsetHeight <= vspace)\n          top = pos.bottom\n        if (left + node.offsetWidth > hspace)\n          left = hspace - node.offsetWidth\n      }\n      node.style.top = top + \"px\"\n      node.style.left = node.style.right = \"\"\n      if (horiz == \"right\") {\n        left = display.sizer.clientWidth - node.offsetWidth\n        node.style.right = \"0px\"\n      } else {\n        if (horiz == \"left\") left = 0\n        else if (horiz == \"middle\") left = (display.sizer.clientWidth - node.offsetWidth) / 2\n        node.style.left = left + \"px\"\n      }\n      if (scroll)\n        scrollIntoView(this, {left, top, right: left + node.offsetWidth, bottom: top + node.offsetHeight})\n    },\n\n    triggerOnKeyDown: methodOp(onKeyDown),\n    triggerOnKeyPress: methodOp(onKeyPress),\n    triggerOnKeyUp: onKeyUp,\n    triggerOnMouseDown: methodOp(onMouseDown),\n\n    execCommand: function(cmd) {\n      if (commands.hasOwnProperty(cmd))\n        return commands[cmd].call(null, this)\n    },\n\n    triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),\n\n    findPosH: function(from, amount, unit, visually) {\n      let dir = 1\n      if (amount < 0) { dir = -1; amount = -amount }\n      let cur = clipPos(this.doc, from)\n      for (let i = 0; i < amount; ++i) {\n        cur = findPosH(this.doc, cur, dir, unit, visually)\n        if (cur.hitSide) break\n      }\n      return cur\n    },\n\n    moveH: methodOp(function(dir, unit) {\n      this.extendSelectionsBy(range => {\n        if (this.display.shift || this.doc.extend || range.empty())\n          return findPosH(this.doc, range.head, dir, unit, this.options.rtlMoveVisually)\n        else\n          return dir < 0 ? range.from() : range.to()\n      }, sel_move)\n    }),\n\n    deleteH: methodOp(function(dir, unit) {\n      let sel = this.doc.sel, doc = this.doc\n      if (sel.somethingSelected())\n        doc.replaceSelection(\"\", null, \"+delete\")\n      else\n        deleteNearSelection(this, range => {\n          let other = findPosH(doc, range.head, dir, unit, false)\n          return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}\n        })\n    }),\n\n    findPosV: function(from, amount, unit, goalColumn) {\n      let dir = 1, x = goalColumn\n      if (amount < 0) { dir = -1; amount = -amount }\n      let cur = clipPos(this.doc, from)\n      for (let i = 0; i < amount; ++i) {\n        let coords = cursorCoords(this, cur, \"div\")\n        if (x == null) x = coords.left\n        else coords.left = x\n        cur = findPosV(this, coords, dir, unit)\n        if (cur.hitSide) break\n      }\n      return cur\n    },\n\n    moveV: methodOp(function(dir, unit) {\n      let doc = this.doc, goals = []\n      let collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()\n      doc.extendSelectionsBy(range => {\n        if (collapse)\n          return dir < 0 ? range.from() : range.to()\n        let headPos = cursorCoords(this, range.head, \"div\")\n        if (range.goalColumn != null) headPos.left = range.goalColumn\n        goals.push(headPos.left)\n        let pos = findPosV(this, headPos, dir, unit)\n        if (unit == \"page\" && range == doc.sel.primary())\n          addToScrollTop(this, charCoords(this, pos, \"div\").top - headPos.top)\n        return pos\n      }, sel_move)\n      if (goals.length) for (let i = 0; i < doc.sel.ranges.length; i++)\n        doc.sel.ranges[i].goalColumn = goals[i]\n    }),\n\n    // Find the word at the given position (as returned by coordsChar).\n    findWordAt: function(pos) {\n      let doc = this.doc, line = getLine(doc, pos.line).text\n      let start = pos.ch, end = pos.ch\n      if (line) {\n        let helper = this.getHelper(pos, \"wordChars\")\n        if ((pos.sticky == \"before\" || end == line.length) && start) --start; else ++end\n        let startChar = line.charAt(start)\n        let check = isWordChar(startChar, helper)\n          ? ch => isWordChar(ch, helper)\n          : /\\s/.test(startChar) ? ch => /\\s/.test(ch)\n          : ch => (!/\\s/.test(ch) && !isWordChar(ch))\n        while (start > 0 && check(line.charAt(start - 1))) --start\n        while (end < line.length && check(line.charAt(end))) ++end\n      }\n      return new Range(Pos(pos.line, start), Pos(pos.line, end))\n    },\n\n    toggleOverwrite: function(value) {\n      if (value != null && value == this.state.overwrite) return\n      if (this.state.overwrite = !this.state.overwrite)\n        addClass(this.display.cursorDiv, \"CodeMirror-overwrite\")\n      else\n        rmClass(this.display.cursorDiv, \"CodeMirror-overwrite\")\n\n      signal(this, \"overwriteToggle\", this, this.state.overwrite)\n    },\n    hasFocus: function() { return this.display.input.getField() == activeElt() },\n    isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },\n\n    scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y) }),\n    getScrollInfo: function() {\n      let scroller = this.display.scroller\n      return {left: scroller.scrollLeft, top: scroller.scrollTop,\n              height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,\n              width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,\n              clientHeight: displayHeight(this), clientWidth: displayWidth(this)}\n    },\n\n    scrollIntoView: methodOp(function(range, margin) {\n      if (range == null) {\n        range = {from: this.doc.sel.primary().head, to: null}\n        if (margin == null) margin = this.options.cursorScrollMargin\n      } else if (typeof range == \"number\") {\n        range = {from: Pos(range, 0), to: null}\n      } else if (range.from == null) {\n        range = {from: range, to: null}\n      }\n      if (!range.to) range.to = range.from\n      range.margin = margin || 0\n\n      if (range.from.line != null) {\n        scrollToRange(this, range)\n      } else {\n        scrollToCoordsRange(this, range.from, range.to, range.margin)\n      }\n    }),\n\n    setSize: methodOp(function(width, height) {\n      let interpret = val => typeof val == \"number\" || /^\\d+$/.test(String(val)) ? val + \"px\" : val\n      if (width != null) this.display.wrapper.style.width = interpret(width)\n      if (height != null) this.display.wrapper.style.height = interpret(height)\n      if (this.options.lineWrapping) clearLineMeasurementCache(this)\n      let lineNo = this.display.viewFrom\n      this.doc.iter(lineNo, this.display.viewTo, line => {\n        if (line.widgets) for (let i = 0; i < line.widgets.length; i++)\n          if (line.widgets[i].noHScroll) { regLineChange(this, lineNo, \"widget\"); break }\n        ++lineNo\n      })\n      this.curOp.forceUpdate = true\n      signal(this, \"refresh\", this)\n    }),\n\n    operation: function(f){return runInOp(this, f)},\n    startOperation: function(){return startOperation(this)},\n    endOperation: function(){return endOperation(this)},\n\n    refresh: methodOp(function() {\n      let oldHeight = this.display.cachedTextHeight\n      regChange(this)\n      this.curOp.forceUpdate = true\n      clearCaches(this)\n      scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop)\n      updateGutterSpace(this)\n      if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)\n        estimateLineHeights(this)\n      signal(this, \"refresh\", this)\n    }),\n\n    swapDoc: methodOp(function(doc) {\n      let old = this.doc\n      old.cm = null\n      attachDoc(this, doc)\n      clearCaches(this)\n      this.display.input.reset()\n      scrollToCoords(this, doc.scrollLeft, doc.scrollTop)\n      this.curOp.forceScroll = true\n      signalLater(this, \"swapDoc\", this, old)\n      return old\n    }),\n\n    phrase: function(phraseText) {\n      let phrases = this.options.phrases\n      return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText\n    },\n\n    getInputField: function(){return this.display.input.getField()},\n    getWrapperElement: function(){return this.display.wrapper},\n    getScrollerElement: function(){return this.display.scroller},\n    getGutterElement: function(){return this.display.gutters}\n  }\n  eventMixin(CodeMirror)\n\n  CodeMirror.registerHelper = function(type, name, value) {\n    if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}\n    helpers[type][name] = value\n  }\n  CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {\n    CodeMirror.registerHelper(type, name, value)\n    helpers[type]._global.push({pred: predicate, val: value})\n  }\n}\n\n// Used for horizontal relative motion. Dir is -1 or 1 (left or\n// right), unit can be \"char\", \"column\" (like char, but doesn't\n// cross line boundaries), \"word\" (across next word), or \"group\" (to\n// the start of next group of word or non-word-non-whitespace\n// chars). The visually param controls whether, in right-to-left\n// text, direction 1 means to move towards the next index in the\n// string, or towards the character to the right of the current\n// position. The resulting position will have a hitSide=true\n// property if it reached the end of the document.\nfunction findPosH(doc, pos, dir, unit, visually) {\n  let oldPos = pos\n  let origDir = dir\n  let lineObj = getLine(doc, pos.line)\n  function findNextLine() {\n    let l = pos.line + dir\n    if (l < doc.first || l >= doc.first + doc.size) return false\n    pos = new Pos(l, pos.ch, pos.sticky)\n    return lineObj = getLine(doc, l)\n  }\n  function moveOnce(boundToLine) {\n    let next\n    if (visually) {\n      next = moveVisually(doc.cm, lineObj, pos, dir)\n    } else {\n      next = moveLogically(lineObj, pos, dir)\n    }\n    if (next == null) {\n      if (!boundToLine && findNextLine())\n        pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir)\n      else\n        return false\n    } else {\n      pos = next\n    }\n    return true\n  }\n\n  if (unit == \"char\") {\n    moveOnce()\n  } else if (unit == \"column\") {\n    moveOnce(true)\n  } else if (unit == \"word\" || unit == \"group\") {\n    let sawType = null, group = unit == \"group\"\n    let helper = doc.cm && doc.cm.getHelper(pos, \"wordChars\")\n    for (let first = true;; first = false) {\n      if (dir < 0 && !moveOnce(!first)) break\n      let cur = lineObj.text.charAt(pos.ch) || \"\\n\"\n      let type = isWordChar(cur, helper) ? \"w\"\n        : group && cur == \"\\n\" ? \"n\"\n        : !group || /\\s/.test(cur) ? null\n        : \"p\"\n      if (group && !first && !type) type = \"s\"\n      if (sawType && sawType != type) {\n        if (dir < 0) {dir = 1; moveOnce(); pos.sticky = \"after\"}\n        break\n      }\n\n      if (type) sawType = type\n      if (dir > 0 && !moveOnce(!first)) break\n    }\n  }\n  let result = skipAtomic(doc, pos, oldPos, origDir, true)\n  if (equalCursorPos(oldPos, result)) result.hitSide = true\n  return result\n}\n\n// For relative vertical movement. Dir may be -1 or 1. Unit can be\n// \"page\" or \"line\". The resulting position will have a hitSide=true\n// property if it reached the end of the document.\nfunction findPosV(cm, pos, dir, unit) {\n  let doc = cm.doc, x = pos.left, y\n  if (unit == \"page\") {\n    let pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)\n    let moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3)\n    y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount\n\n  } else if (unit == \"line\") {\n    y = dir > 0 ? pos.bottom + 3 : pos.top - 3\n  }\n  let target\n  for (;;) {\n    target = coordsChar(cm, x, y)\n    if (!target.outside) break\n    if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }\n    y += dir * 5\n  }\n  return target\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/mouse_events.js",
    "content": "import { delayBlurEvent, ensureFocus } from \"../display/focus.js\"\nimport { operation } from \"../display/operations.js\"\nimport { visibleLines } from \"../display/update_lines.js\"\nimport { clipPos, cmp, maxPos, minPos, Pos } from \"../line/pos.js\"\nimport { getLine, lineAtHeight } from \"../line/utils_line.js\"\nimport { posFromMouse } from \"../measurement/position_measurement.js\"\nimport { eventInWidget } from \"../measurement/widgets.js\"\nimport { normalizeSelection, Range, Selection } from \"../model/selection.js\"\nimport { extendRange, extendSelection, replaceOneSelection, setSelection } from \"../model/selection_updates.js\"\nimport { captureRightClick, chromeOS, ie, ie_version, mac, webkit } from \"../util/browser.js\"\nimport { getOrder, getBidiPartAt } from \"../util/bidi.js\"\nimport { activeElt } from \"../util/dom.js\"\nimport { e_button, e_defaultPrevented, e_preventDefault, e_target, hasHandler, off, on, signal, signalDOMEvent } from \"../util/event.js\"\nimport { dragAndDrop } from \"../util/feature_detection.js\"\nimport { bind, countColumn, findColumn, sel_mouse } from \"../util/misc.js\"\nimport { addModifierNames } from \"../input/keymap.js\"\nimport { Pass } from \"../util/misc.js\"\n\nimport { dispatchKey } from \"./key_events.js\"\nimport { commands } from \"./commands.js\"\n\nconst DOUBLECLICK_DELAY = 400\n\nclass PastClick {\n  constructor(time, pos, button) {\n    this.time = time\n    this.pos = pos\n    this.button = button\n  }\n\n  compare(time, pos, button) {\n    return this.time + DOUBLECLICK_DELAY > time &&\n      cmp(pos, this.pos) == 0 && button == this.button\n  }\n}\n\nlet lastClick, lastDoubleClick\nfunction clickRepeat(pos, button) {\n  let now = +new Date\n  if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {\n    lastClick = lastDoubleClick = null\n    return \"triple\"\n  } else if (lastClick && lastClick.compare(now, pos, button)) {\n    lastDoubleClick = new PastClick(now, pos, button)\n    lastClick = null\n    return \"double\"\n  } else {\n    lastClick = new PastClick(now, pos, button)\n    lastDoubleClick = null\n    return \"single\"\n  }\n}\n\n// A mouse down can be a single click, double click, triple click,\n// start of selection drag, start of text drag, new cursor\n// (ctrl-click), rectangle drag (alt-drag), or xwin\n// middle-click-paste. Or it might be a click on something we should\n// not interfere with, such as a scrollbar or widget.\nexport function onMouseDown(e) {\n  let cm = this, display = cm.display\n  if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return\n  display.input.ensurePolled()\n  display.shift = e.shiftKey\n\n  if (eventInWidget(display, e)) {\n    if (!webkit) {\n      // Briefly turn off draggability, to allow widgets to do\n      // normal dragging things.\n      display.scroller.draggable = false\n      setTimeout(() => display.scroller.draggable = true, 100)\n    }\n    return\n  }\n  if (clickInGutter(cm, e)) return\n  let pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : \"single\"\n  window.focus()\n\n  // #3261: make sure, that we're not starting a second selection\n  if (button == 1 && cm.state.selectingText)\n    cm.state.selectingText(e)\n\n  if (pos && handleMappedButton(cm, button, pos, repeat, e)) return\n\n  if (button == 1) {\n    if (pos) leftButtonDown(cm, pos, repeat, e)\n    else if (e_target(e) == display.scroller) e_preventDefault(e)\n  } else if (button == 2) {\n    if (pos) extendSelection(cm.doc, pos)\n    setTimeout(() => display.input.focus(), 20)\n  } else if (button == 3) {\n    if (captureRightClick) cm.display.input.onContextMenu(e)\n    else delayBlurEvent(cm)\n  }\n}\n\nfunction handleMappedButton(cm, button, pos, repeat, event) {\n  let name = \"Click\"\n  if (repeat == \"double\") name = \"Double\" + name\n  else if (repeat == \"triple\") name = \"Triple\" + name\n  name = (button == 1 ? \"Left\" : button == 2 ? \"Middle\" : \"Right\") + name\n\n  return dispatchKey(cm,  addModifierNames(name, event), event, bound => {\n    if (typeof bound == \"string\") bound = commands[bound]\n    if (!bound) return false\n    let done = false\n    try {\n      if (cm.isReadOnly()) cm.state.suppressEdits = true\n      done = bound(cm, pos) != Pass\n    } finally {\n      cm.state.suppressEdits = false\n    }\n    return done\n  })\n}\n\nfunction configureMouse(cm, repeat, event) {\n  let option = cm.getOption(\"configureMouse\")\n  let value = option ? option(cm, repeat, event) : {}\n  if (value.unit == null) {\n    let rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey\n    value.unit = rect ? \"rectangle\" : repeat == \"single\" ? \"char\" : repeat == \"double\" ? \"word\" : \"line\"\n  }\n  if (value.extend == null || cm.doc.extend) value.extend = cm.doc.extend || event.shiftKey\n  if (value.addNew == null) value.addNew = mac ? event.metaKey : event.ctrlKey\n  if (value.moveOnDrag == null) value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey)\n  return value\n}\n\nfunction leftButtonDown(cm, pos, repeat, event) {\n  if (ie) setTimeout(bind(ensureFocus, cm), 0)\n  else cm.curOp.focus = activeElt()\n\n  let behavior = configureMouse(cm, repeat, event)\n\n  let sel = cm.doc.sel, contained\n  if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&\n      repeat == \"single\" && (contained = sel.contains(pos)) > -1 &&\n      (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&\n      (cmp(contained.to(), pos) > 0 || pos.xRel < 0))\n    leftButtonStartDrag(cm, event, pos, behavior)\n  else\n    leftButtonSelect(cm, event, pos, behavior)\n}\n\n// Start a text drag. When it ends, see if any dragging actually\n// happen, and treat as a click if it didn't.\nfunction leftButtonStartDrag(cm, event, pos, behavior) {\n  let display = cm.display, moved = false\n  let dragEnd = operation(cm, e => {\n    if (webkit) display.scroller.draggable = false\n    cm.state.draggingText = false\n    off(display.wrapper.ownerDocument, \"mouseup\", dragEnd)\n    off(display.wrapper.ownerDocument, \"mousemove\", mouseMove)\n    off(display.scroller, \"dragstart\", dragStart)\n    off(display.scroller, \"drop\", dragEnd)\n    if (!moved) {\n      e_preventDefault(e)\n      if (!behavior.addNew)\n        extendSelection(cm.doc, pos, null, null, behavior.extend)\n      // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)\n      if (webkit || ie && ie_version == 9)\n        setTimeout(() => {display.wrapper.ownerDocument.body.focus(); display.input.focus()}, 20)\n      else\n        display.input.focus()\n    }\n  })\n  let mouseMove = function(e2) {\n    moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10\n  }\n  let dragStart = () => moved = true\n  // Let the drag handler handle this.\n  if (webkit) display.scroller.draggable = true\n  cm.state.draggingText = dragEnd\n  dragEnd.copy = !behavior.moveOnDrag\n  // IE's approach to draggable\n  if (display.scroller.dragDrop) display.scroller.dragDrop()\n  on(display.wrapper.ownerDocument, \"mouseup\", dragEnd)\n  on(display.wrapper.ownerDocument, \"mousemove\", mouseMove)\n  on(display.scroller, \"dragstart\", dragStart)\n  on(display.scroller, \"drop\", dragEnd)\n\n  delayBlurEvent(cm)\n  setTimeout(() => display.input.focus(), 20)\n}\n\nfunction rangeForUnit(cm, pos, unit) {\n  if (unit == \"char\") return new Range(pos, pos)\n  if (unit == \"word\") return cm.findWordAt(pos)\n  if (unit == \"line\") return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)))\n  let result = unit(cm, pos)\n  return new Range(result.from, result.to)\n}\n\n// Normal selection, as opposed to text dragging.\nfunction leftButtonSelect(cm, event, start, behavior) {\n  let display = cm.display, doc = cm.doc\n  e_preventDefault(event)\n\n  let ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges\n  if (behavior.addNew && !behavior.extend) {\n    ourIndex = doc.sel.contains(start)\n    if (ourIndex > -1)\n      ourRange = ranges[ourIndex]\n    else\n      ourRange = new Range(start, start)\n  } else {\n    ourRange = doc.sel.primary()\n    ourIndex = doc.sel.primIndex\n  }\n\n  if (behavior.unit == \"rectangle\") {\n    if (!behavior.addNew) ourRange = new Range(start, start)\n    start = posFromMouse(cm, event, true, true)\n    ourIndex = -1\n  } else {\n    let range = rangeForUnit(cm, start, behavior.unit)\n    if (behavior.extend)\n      ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend)\n    else\n      ourRange = range\n  }\n\n  if (!behavior.addNew) {\n    ourIndex = 0\n    setSelection(doc, new Selection([ourRange], 0), sel_mouse)\n    startSel = doc.sel\n  } else if (ourIndex == -1) {\n    ourIndex = ranges.length\n    setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),\n                 {scroll: false, origin: \"*mouse\"})\n  } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == \"char\" && !behavior.extend) {\n    setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),\n                 {scroll: false, origin: \"*mouse\"})\n    startSel = doc.sel\n  } else {\n    replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)\n  }\n\n  let lastPos = start\n  function extendTo(pos) {\n    if (cmp(lastPos, pos) == 0) return\n    lastPos = pos\n\n    if (behavior.unit == \"rectangle\") {\n      let ranges = [], tabSize = cm.options.tabSize\n      let startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)\n      let posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)\n      let left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)\n      for (let line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));\n           line <= end; line++) {\n        let text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)\n        if (left == right)\n          ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)))\n        else if (text.length > leftPos)\n          ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))))\n      }\n      if (!ranges.length) ranges.push(new Range(start, start))\n      setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),\n                   {origin: \"*mouse\", scroll: false})\n      cm.scrollIntoView(pos)\n    } else {\n      let oldRange = ourRange\n      let range = rangeForUnit(cm, pos, behavior.unit)\n      let anchor = oldRange.anchor, head\n      if (cmp(range.anchor, anchor) > 0) {\n        head = range.head\n        anchor = minPos(oldRange.from(), range.anchor)\n      } else {\n        head = range.anchor\n        anchor = maxPos(oldRange.to(), range.head)\n      }\n      let ranges = startSel.ranges.slice(0)\n      ranges[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head))\n      setSelection(doc, normalizeSelection(cm, ranges, ourIndex), sel_mouse)\n    }\n  }\n\n  let editorSize = display.wrapper.getBoundingClientRect()\n  // Used to ensure timeout re-tries don't fire when another extend\n  // happened in the meantime (clearTimeout isn't reliable -- at\n  // least on Chrome, the timeouts still happen even when cleared,\n  // if the clear happens after their scheduled firing time).\n  let counter = 0\n\n  function extend(e) {\n    let curCount = ++counter\n    let cur = posFromMouse(cm, e, true, behavior.unit == \"rectangle\")\n    if (!cur) return\n    if (cmp(cur, lastPos) != 0) {\n      cm.curOp.focus = activeElt()\n      extendTo(cur)\n      let visible = visibleLines(display, doc)\n      if (cur.line >= visible.to || cur.line < visible.from)\n        setTimeout(operation(cm, () => {if (counter == curCount) extend(e)}), 150)\n    } else {\n      let outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0\n      if (outside) setTimeout(operation(cm, () => {\n        if (counter != curCount) return\n        display.scroller.scrollTop += outside\n        extend(e)\n      }), 50)\n    }\n  }\n\n  function done(e) {\n    cm.state.selectingText = false\n    counter = Infinity\n    e_preventDefault(e)\n    display.input.focus()\n    off(display.wrapper.ownerDocument, \"mousemove\", move)\n    off(display.wrapper.ownerDocument, \"mouseup\", up)\n    doc.history.lastSelOrigin = null\n  }\n\n  let move = operation(cm, e => {\n    if (e.buttons === 0 || !e_button(e)) done(e)\n    else extend(e)\n  })\n  let up = operation(cm, done)\n  cm.state.selectingText = up\n  on(display.wrapper.ownerDocument, \"mousemove\", move)\n  on(display.wrapper.ownerDocument, \"mouseup\", up)\n}\n\n// Used when mouse-selecting to adjust the anchor to the proper side\n// of a bidi jump depending on the visual position of the head.\nfunction bidiSimplify(cm, range) {\n  let {anchor, head} = range, anchorLine = getLine(cm.doc, anchor.line)\n  if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) return range\n  let order = getOrder(anchorLine)\n  if (!order) return range\n  let index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]\n  if (part.from != anchor.ch && part.to != anchor.ch) return range\n  let boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1)\n  if (boundary == 0 || boundary == order.length) return range\n\n  // Compute the relative visual position of the head compared to the\n  // anchor (<0 is to the left, >0 to the right)\n  let leftSide\n  if (head.line != anchor.line) {\n    leftSide = (head.line - anchor.line) * (cm.doc.direction == \"ltr\" ? 1 : -1) > 0\n  } else {\n    let headIndex = getBidiPartAt(order, head.ch, head.sticky)\n    let dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1)\n    if (headIndex == boundary - 1 || headIndex == boundary)\n      leftSide = dir < 0\n    else\n      leftSide = dir > 0\n  }\n\n  let usePart = order[boundary + (leftSide ? -1 : 0)]\n  let from = leftSide == (usePart.level == 1)\n  let ch = from ? usePart.from : usePart.to, sticky = from ? \"after\" : \"before\"\n  return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)\n}\n\n\n// Determines whether an event happened in the gutter, and fires the\n// handlers for the corresponding event.\nfunction gutterEvent(cm, e, type, prevent) {\n  let mX, mY\n  if (e.touches) {\n    mX = e.touches[0].clientX\n    mY = e.touches[0].clientY\n  } else {\n    try { mX = e.clientX; mY = e.clientY }\n    catch(e) { return false }\n  }\n  if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false\n  if (prevent) e_preventDefault(e)\n\n  let display = cm.display\n  let lineBox = display.lineDiv.getBoundingClientRect()\n\n  if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e)\n  mY -= lineBox.top - display.viewOffset\n\n  for (let i = 0; i < cm.options.gutters.length; ++i) {\n    let g = display.gutters.childNodes[i]\n    if (g && g.getBoundingClientRect().right >= mX) {\n      let line = lineAtHeight(cm.doc, mY)\n      let gutter = cm.options.gutters[i]\n      signal(cm, type, cm, line, gutter, e)\n      return e_defaultPrevented(e)\n    }\n  }\n}\n\nexport function clickInGutter(cm, e) {\n  return gutterEvent(cm, e, \"gutterClick\", true)\n}\n\n// CONTEXT MENU HANDLING\n\n// To make the context menu work, we need to briefly unhide the\n// textarea (making it as unobtrusive as possible) to let the\n// right-click take effect on it.\nexport function onContextMenu(cm, e) {\n  if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return\n  if (signalDOMEvent(cm, e, \"contextmenu\")) return\n  if (!captureRightClick) cm.display.input.onContextMenu(e)\n}\n\nfunction contextMenuInGutter(cm, e) {\n  if (!hasHandler(cm, \"gutterContextMenu\")) return false\n  return gutterEvent(cm, e, \"gutterContextMenu\", false)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/options.js",
    "content": "import { onBlur } from \"../display/focus.js\"\nimport { setGuttersForLineNumbers, updateGutters } from \"../display/gutters.js\"\nimport { alignHorizontally } from \"../display/line_numbers.js\"\nimport { loadMode, resetModeState } from \"../display/mode_state.js\"\nimport { initScrollbars, updateScrollbars } from \"../display/scrollbars.js\"\nimport { updateSelection } from \"../display/selection.js\"\nimport { regChange } from \"../display/view_tracking.js\"\nimport { getKeyMap } from \"../input/keymap.js\"\nimport { defaultSpecialCharPlaceholder } from \"../line/line_data.js\"\nimport { Pos } from \"../line/pos.js\"\nimport { findMaxLine } from \"../line/spans.js\"\nimport { clearCaches, compensateForHScroll, estimateLineHeights } from \"../measurement/position_measurement.js\"\nimport { replaceRange } from \"../model/changes.js\"\nimport { mobile, windows } from \"../util/browser.js\"\nimport { addClass, rmClass } from \"../util/dom.js\"\nimport { off, on } from \"../util/event.js\"\n\nimport { themeChanged } from \"./utils.js\"\n\nexport let Init = {toString: function(){return \"CodeMirror.Init\"}}\n\nexport let defaults = {}\nexport let optionHandlers = {}\n\nexport function defineOptions(CodeMirror) {\n  let optionHandlers = CodeMirror.optionHandlers\n\n  function option(name, deflt, handle, notOnInit) {\n    CodeMirror.defaults[name] = deflt\n    if (handle) optionHandlers[name] =\n      notOnInit ? (cm, val, old) => {if (old != Init) handle(cm, val, old)} : handle\n  }\n\n  CodeMirror.defineOption = option\n\n  // Passed to option handlers when there is no old value.\n  CodeMirror.Init = Init\n\n  // These two are, on init, called from the constructor because they\n  // have to be initialized before the editor can start at all.\n  option(\"value\", \"\", (cm, val) => cm.setValue(val), true)\n  option(\"mode\", null, (cm, val) => {\n    cm.doc.modeOption = val\n    loadMode(cm)\n  }, true)\n\n  option(\"indentUnit\", 2, loadMode, true)\n  option(\"indentWithTabs\", false)\n  option(\"smartIndent\", true)\n  option(\"tabSize\", 4, cm => {\n    resetModeState(cm)\n    clearCaches(cm)\n    regChange(cm)\n  }, true)\n\n  option(\"lineSeparator\", null, (cm, val) => {\n    cm.doc.lineSep = val\n    if (!val) return\n    let newBreaks = [], lineNo = cm.doc.first\n    cm.doc.iter(line => {\n      for (let pos = 0;;) {\n        let found = line.text.indexOf(val, pos)\n        if (found == -1) break\n        pos = found + val.length\n        newBreaks.push(Pos(lineNo, found))\n      }\n      lineNo++\n    })\n    for (let i = newBreaks.length - 1; i >= 0; i--)\n      replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))\n  })\n  option(\"specialChars\", /[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u061c\\u200b-\\u200f\\u2028\\u2029\\ufeff]/g, (cm, val, old) => {\n    cm.state.specialChars = new RegExp(val.source + (val.test(\"\\t\") ? \"\" : \"|\\t\"), \"g\")\n    if (old != Init) cm.refresh()\n  })\n  option(\"specialCharPlaceholder\", defaultSpecialCharPlaceholder, cm => cm.refresh(), true)\n  option(\"electricChars\", true)\n  option(\"inputStyle\", mobile ? \"contenteditable\" : \"textarea\", () => {\n    throw new Error(\"inputStyle can not (yet) be changed in a running editor\") // FIXME\n  }, true)\n  option(\"spellcheck\", false, (cm, val) => cm.getInputField().spellcheck = val, true)\n  option(\"autocorrect\", false, (cm, val) => cm.getInputField().autocorrect = val, true)\n  option(\"autocapitalize\", false, (cm, val) => cm.getInputField().autocapitalize = val, true)\n  option(\"rtlMoveVisually\", !windows)\n  option(\"wholeLineUpdateBefore\", true)\n\n  option(\"theme\", \"default\", cm => {\n    themeChanged(cm)\n    guttersChanged(cm)\n  }, true)\n  option(\"keyMap\", \"default\", (cm, val, old) => {\n    let next = getKeyMap(val)\n    let prev = old != Init && getKeyMap(old)\n    if (prev && prev.detach) prev.detach(cm, next)\n    if (next.attach) next.attach(cm, prev || null)\n  })\n  option(\"extraKeys\", null)\n  option(\"configureMouse\", null)\n\n  option(\"lineWrapping\", false, wrappingChanged, true)\n  option(\"gutters\", [], cm => {\n    setGuttersForLineNumbers(cm.options)\n    guttersChanged(cm)\n  }, true)\n  option(\"fixedGutter\", true, (cm, val) => {\n    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + \"px\" : \"0\"\n    cm.refresh()\n  }, true)\n  option(\"coverGutterNextToScrollbar\", false, cm => updateScrollbars(cm), true)\n  option(\"scrollbarStyle\", \"native\", cm => {\n    initScrollbars(cm)\n    updateScrollbars(cm)\n    cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)\n    cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)\n  }, true)\n  option(\"lineNumbers\", false, cm => {\n    setGuttersForLineNumbers(cm.options)\n    guttersChanged(cm)\n  }, true)\n  option(\"firstLineNumber\", 1, guttersChanged, true)\n  option(\"lineNumberFormatter\", integer => integer, guttersChanged, true)\n  option(\"showCursorWhenSelecting\", false, updateSelection, true)\n\n  option(\"resetSelectionOnContextMenu\", true)\n  option(\"lineWiseCopyCut\", true)\n  option(\"pasteLinesPerSelection\", true)\n  option(\"selectionsMayTouch\", false)\n\n  option(\"readOnly\", false, (cm, val) => {\n    if (val == \"nocursor\") {\n      onBlur(cm)\n      cm.display.input.blur()\n    }\n    cm.display.input.readOnlyChanged(val)\n  })\n  option(\"disableInput\", false, (cm, val) => {if (!val) cm.display.input.reset()}, true)\n  option(\"dragDrop\", true, dragDropChanged)\n  option(\"allowDropFileTypes\", null)\n\n  option(\"cursorBlinkRate\", 530)\n  option(\"cursorScrollMargin\", 0)\n  option(\"cursorHeight\", 1, updateSelection, true)\n  option(\"singleCursorHeightPerLine\", true, updateSelection, true)\n  option(\"workTime\", 100)\n  option(\"workDelay\", 100)\n  option(\"flattenSpans\", true, resetModeState, true)\n  option(\"addModeClass\", false, resetModeState, true)\n  option(\"pollInterval\", 100)\n  option(\"undoDepth\", 200, (cm, val) => cm.doc.history.undoDepth = val)\n  option(\"historyEventDelay\", 1250)\n  option(\"viewportMargin\", 10, cm => cm.refresh(), true)\n  option(\"maxHighlightLength\", 10000, resetModeState, true)\n  option(\"moveInputWithCursor\", true, (cm, val) => {\n    if (!val) cm.display.input.resetPosition()\n  })\n\n  option(\"tabindex\", null, (cm, val) => cm.display.input.getField().tabIndex = val || \"\")\n  option(\"autofocus\", null)\n  option(\"direction\", \"ltr\", (cm, val) => cm.doc.setDirection(val), true)\n  option(\"phrases\", null)\n}\n\nfunction guttersChanged(cm) {\n  updateGutters(cm)\n  regChange(cm)\n  alignHorizontally(cm)\n}\n\nfunction dragDropChanged(cm, value, old) {\n  let wasOn = old && old != Init\n  if (!value != !wasOn) {\n    let funcs = cm.display.dragFunctions\n    let toggle = value ? on : off\n    toggle(cm.display.scroller, \"dragstart\", funcs.start)\n    toggle(cm.display.scroller, \"dragenter\", funcs.enter)\n    toggle(cm.display.scroller, \"dragover\", funcs.over)\n    toggle(cm.display.scroller, \"dragleave\", funcs.leave)\n    toggle(cm.display.scroller, \"drop\", funcs.drop)\n  }\n}\n\nfunction wrappingChanged(cm) {\n  if (cm.options.lineWrapping) {\n    addClass(cm.display.wrapper, \"CodeMirror-wrap\")\n    cm.display.sizer.style.minWidth = \"\"\n    cm.display.sizerWidth = null\n  } else {\n    rmClass(cm.display.wrapper, \"CodeMirror-wrap\")\n    findMaxLine(cm)\n  }\n  estimateLineHeights(cm)\n  regChange(cm)\n  clearCaches(cm)\n  setTimeout(() => updateScrollbars(cm), 100)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/edit/utils.js",
    "content": "import { clearCaches } from \"../measurement/position_measurement.js\"\n\nexport function themeChanged(cm) {\n  cm.display.wrapper.className = cm.display.wrapper.className.replace(/\\s*cm-s-\\S+/g, \"\") +\n    cm.options.theme.replace(/(^|\\s)\\s*/g, \" cm-s-\")\n  clearCaches(cm)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/input/ContentEditableInput.js",
    "content": "import { operation, runInOp } from \"../display/operations.js\"\nimport { prepareSelection } from \"../display/selection.js\"\nimport { regChange } from \"../display/view_tracking.js\"\nimport { applyTextInput, copyableRanges, disableBrowserMagic, handlePaste, hiddenTextarea, lastCopied, setLastCopied } from \"./input.js\"\nimport { cmp, maxPos, minPos, Pos } from \"../line/pos.js\"\nimport { getBetween, getLine, lineNo } from \"../line/utils_line.js\"\nimport { findViewForLine, findViewIndex, mapFromLineView, nodeAndOffsetInLineMap } from \"../measurement/position_measurement.js\"\nimport { replaceRange } from \"../model/changes.js\"\nimport { simpleSelection } from \"../model/selection.js\"\nimport { setSelection } from \"../model/selection_updates.js\"\nimport { getBidiPartAt, getOrder } from \"../util/bidi.js\"\nimport { android, chrome, gecko, ie_version } from \"../util/browser.js\"\nimport { contains, range, removeChildrenAndAdd, selectInput } from \"../util/dom.js\"\nimport { on, signalDOMEvent } from \"../util/event.js\"\nimport { Delayed, lst, sel_dontScroll } from \"../util/misc.js\"\n\n// CONTENTEDITABLE INPUT STYLE\n\nexport default class ContentEditableInput {\n  constructor(cm) {\n    this.cm = cm\n    this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null\n    this.polling = new Delayed()\n    this.composing = null\n    this.gracePeriod = false\n    this.readDOMTimeout = null\n  }\n\n  init(display) {\n    let input = this, cm = input.cm\n    let div = input.div = display.lineDiv\n    disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize)\n\n    on(div, \"paste\", e => {\n      if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return\n      // IE doesn't fire input events, so we schedule a read for the pasted content in this way\n      if (ie_version <= 11) setTimeout(operation(cm, () => this.updateFromDOM()), 20)\n    })\n\n    on(div, \"compositionstart\", e => {\n      this.composing = {data: e.data, done: false}\n    })\n    on(div, \"compositionupdate\", e => {\n      if (!this.composing) this.composing = {data: e.data, done: false}\n    })\n    on(div, \"compositionend\", e => {\n      if (this.composing) {\n        if (e.data != this.composing.data) this.readFromDOMSoon()\n        this.composing.done = true\n      }\n    })\n\n    on(div, \"touchstart\", () => input.forceCompositionEnd())\n\n    on(div, \"input\", () => {\n      if (!this.composing) this.readFromDOMSoon()\n    })\n\n    function onCopyCut(e) {\n      if (signalDOMEvent(cm, e)) return\n      if (cm.somethingSelected()) {\n        setLastCopied({lineWise: false, text: cm.getSelections()})\n        if (e.type == \"cut\") cm.replaceSelection(\"\", null, \"cut\")\n      } else if (!cm.options.lineWiseCopyCut) {\n        return\n      } else {\n        let ranges = copyableRanges(cm)\n        setLastCopied({lineWise: true, text: ranges.text})\n        if (e.type == \"cut\") {\n          cm.operation(() => {\n            cm.setSelections(ranges.ranges, 0, sel_dontScroll)\n            cm.replaceSelection(\"\", null, \"cut\")\n          })\n        }\n      }\n      if (e.clipboardData) {\n        e.clipboardData.clearData()\n        let content = lastCopied.text.join(\"\\n\")\n        // iOS exposes the clipboard API, but seems to discard content inserted into it\n        e.clipboardData.setData(\"Text\", content)\n        if (e.clipboardData.getData(\"Text\") == content) {\n          e.preventDefault()\n          return\n        }\n      }\n      // Old-fashioned briefly-focus-a-textarea hack\n      let kludge = hiddenTextarea(), te = kludge.firstChild\n      cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)\n      te.value = lastCopied.text.join(\"\\n\")\n      let hadFocus = document.activeElement\n      selectInput(te)\n      setTimeout(() => {\n        cm.display.lineSpace.removeChild(kludge)\n        hadFocus.focus()\n        if (hadFocus == div) input.showPrimarySelection()\n      }, 50)\n    }\n    on(div, \"copy\", onCopyCut)\n    on(div, \"cut\", onCopyCut)\n  }\n\n  prepareSelection() {\n    let result = prepareSelection(this.cm, false)\n    result.focus = this.cm.state.focused\n    return result\n  }\n\n  showSelection(info, takeFocus) {\n    if (!info || !this.cm.display.view.length) return\n    if (info.focus || takeFocus) this.showPrimarySelection()\n    this.showMultipleSelections(info)\n  }\n\n  getSelection() {\n    return this.cm.display.wrapper.ownerDocument.getSelection()\n  }\n\n  showPrimarySelection() {\n    let sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary()\n    let from = prim.from(), to = prim.to()\n\n    if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {\n      sel.removeAllRanges()\n      return\n    }\n\n    let curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)\n    let curFocus = domToPos(cm, sel.focusNode, sel.focusOffset)\n    if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&\n        cmp(minPos(curAnchor, curFocus), from) == 0 &&\n        cmp(maxPos(curAnchor, curFocus), to) == 0)\n      return\n\n    let view = cm.display.view\n    let start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||\n        {node: view[0].measure.map[2], offset: 0}\n    let end = to.line < cm.display.viewTo && posToDOM(cm, to)\n    if (!end) {\n      let measure = view[view.length - 1].measure\n      let map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map\n      end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}\n    }\n\n    if (!start || !end) {\n      sel.removeAllRanges()\n      return\n    }\n\n    let old = sel.rangeCount && sel.getRangeAt(0), rng\n    try { rng = range(start.node, start.offset, end.offset, end.node) }\n    catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible\n    if (rng) {\n      if (!gecko && cm.state.focused) {\n        sel.collapse(start.node, start.offset)\n        if (!rng.collapsed) {\n          sel.removeAllRanges()\n          sel.addRange(rng)\n        }\n      } else {\n        sel.removeAllRanges()\n        sel.addRange(rng)\n      }\n      if (old && sel.anchorNode == null) sel.addRange(old)\n      else if (gecko) this.startGracePeriod()\n    }\n    this.rememberSelection()\n  }\n\n  startGracePeriod() {\n    clearTimeout(this.gracePeriod)\n    this.gracePeriod = setTimeout(() => {\n      this.gracePeriod = false\n      if (this.selectionChanged())\n        this.cm.operation(() => this.cm.curOp.selectionChanged = true)\n    }, 20)\n  }\n\n  showMultipleSelections(info) {\n    removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)\n    removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)\n  }\n\n  rememberSelection() {\n    let sel = this.getSelection()\n    this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset\n    this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset\n  }\n\n  selectionInEditor() {\n    let sel = this.getSelection()\n    if (!sel.rangeCount) return false\n    let node = sel.getRangeAt(0).commonAncestorContainer\n    return contains(this.div, node)\n  }\n\n  focus() {\n    if (this.cm.options.readOnly != \"nocursor\") {\n      if (!this.selectionInEditor())\n        this.showSelection(this.prepareSelection(), true)\n      this.div.focus()\n    }\n  }\n  blur() { this.div.blur() }\n  getField() { return this.div }\n\n  supportsTouch() { return true }\n\n  receivedFocus() {\n    let input = this\n    if (this.selectionInEditor())\n      this.pollSelection()\n    else\n      runInOp(this.cm, () => input.cm.curOp.selectionChanged = true)\n\n    function poll() {\n      if (input.cm.state.focused) {\n        input.pollSelection()\n        input.polling.set(input.cm.options.pollInterval, poll)\n      }\n    }\n    this.polling.set(this.cm.options.pollInterval, poll)\n  }\n\n  selectionChanged() {\n    let sel = this.getSelection()\n    return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||\n      sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset\n  }\n\n  pollSelection() {\n    if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) return\n    let sel = this.getSelection(), cm = this.cm\n    // On Android Chrome (version 56, at least), backspacing into an\n    // uneditable block element will put the cursor in that element,\n    // and then, because it's not editable, hide the virtual keyboard.\n    // Because Android doesn't allow us to actually detect backspace\n    // presses in a sane way, this code checks for when that happens\n    // and simulates a backspace press in this case.\n    if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {\n      this.cm.triggerOnKeyDown({type: \"keydown\", keyCode: 8, preventDefault: Math.abs})\n      this.blur()\n      this.focus()\n      return\n    }\n    if (this.composing) return\n    this.rememberSelection()\n    let anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)\n    let head = domToPos(cm, sel.focusNode, sel.focusOffset)\n    if (anchor && head) runInOp(cm, () => {\n      setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)\n      if (anchor.bad || head.bad) cm.curOp.selectionChanged = true\n    })\n  }\n\n  pollContent() {\n    if (this.readDOMTimeout != null) {\n      clearTimeout(this.readDOMTimeout)\n      this.readDOMTimeout = null\n    }\n\n    let cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()\n    let from = sel.from(), to = sel.to()\n    if (from.ch == 0 && from.line > cm.firstLine())\n      from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length)\n    if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())\n      to = Pos(to.line + 1, 0)\n    if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false\n\n    let fromIndex, fromLine, fromNode\n    if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {\n      fromLine = lineNo(display.view[0].line)\n      fromNode = display.view[0].node\n    } else {\n      fromLine = lineNo(display.view[fromIndex].line)\n      fromNode = display.view[fromIndex - 1].node.nextSibling\n    }\n    let toIndex = findViewIndex(cm, to.line)\n    let toLine, toNode\n    if (toIndex == display.view.length - 1) {\n      toLine = display.viewTo - 1\n      toNode = display.lineDiv.lastChild\n    } else {\n      toLine = lineNo(display.view[toIndex + 1].line) - 1\n      toNode = display.view[toIndex + 1].node.previousSibling\n    }\n\n    if (!fromNode) return false\n    let newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))\n    let oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))\n    while (newText.length > 1 && oldText.length > 1) {\n      if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }\n      else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }\n      else break\n    }\n\n    let cutFront = 0, cutEnd = 0\n    let newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)\n    while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))\n      ++cutFront\n    let newBot = lst(newText), oldBot = lst(oldText)\n    let maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),\n                             oldBot.length - (oldText.length == 1 ? cutFront : 0))\n    while (cutEnd < maxCutEnd &&\n           newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))\n      ++cutEnd\n    // Try to move start of change to start of selection if ambiguous\n    if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {\n      while (cutFront && cutFront > from.ch &&\n             newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {\n        cutFront--\n        cutEnd++\n      }\n    }\n\n    newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\\u200b+/, \"\")\n    newText[0] = newText[0].slice(cutFront).replace(/\\u200b+$/, \"\")\n\n    let chFrom = Pos(fromLine, cutFront)\n    let chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)\n    if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {\n      replaceRange(cm.doc, newText, chFrom, chTo, \"+input\")\n      return true\n    }\n  }\n\n  ensurePolled() {\n    this.forceCompositionEnd()\n  }\n  reset() {\n    this.forceCompositionEnd()\n  }\n  forceCompositionEnd() {\n    if (!this.composing) return\n    clearTimeout(this.readDOMTimeout)\n    this.composing = null\n    this.updateFromDOM()\n    this.div.blur()\n    this.div.focus()\n  }\n  readFromDOMSoon() {\n    if (this.readDOMTimeout != null) return\n    this.readDOMTimeout = setTimeout(() => {\n      this.readDOMTimeout = null\n      if (this.composing) {\n        if (this.composing.done) this.composing = null\n        else return\n      }\n      this.updateFromDOM()\n    }, 80)\n  }\n\n  updateFromDOM() {\n    if (this.cm.isReadOnly() || !this.pollContent())\n      runInOp(this.cm, () => regChange(this.cm))\n  }\n\n  setUneditable(node) {\n    node.contentEditable = \"false\"\n  }\n\n  onKeyPress(e) {\n    if (e.charCode == 0 || this.composing) return\n    e.preventDefault()\n    if (!this.cm.isReadOnly())\n      operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0)\n  }\n\n  readOnlyChanged(val) {\n    this.div.contentEditable = String(val != \"nocursor\")\n  }\n\n  onContextMenu() {}\n  resetPosition() {}\n}\n\nContentEditableInput.prototype.needsContentAttribute = true\n\nfunction posToDOM(cm, pos) {\n  let view = findViewForLine(cm, pos.line)\n  if (!view || view.hidden) return null\n  let line = getLine(cm.doc, pos.line)\n  let info = mapFromLineView(view, line, pos.line)\n\n  let order = getOrder(line, cm.doc.direction), side = \"left\"\n  if (order) {\n    let partPos = getBidiPartAt(order, pos.ch)\n    side = partPos % 2 ? \"right\" : \"left\"\n  }\n  let result = nodeAndOffsetInLineMap(info.map, pos.ch, side)\n  result.offset = result.collapse == \"right\" ? result.end : result.start\n  return result\n}\n\nfunction isInGutter(node) {\n  for (let scan = node; scan; scan = scan.parentNode)\n    if (/CodeMirror-gutter-wrapper/.test(scan.className)) return true\n  return false\n}\n\nfunction badPos(pos, bad) { if (bad) pos.bad = true; return pos }\n\nfunction domTextBetween(cm, from, to, fromLine, toLine) {\n  let text = \"\", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false\n  function recognizeMarker(id) { return marker => marker.id == id }\n  function close() {\n    if (closing) {\n      text += lineSep\n      if (extraLinebreak) text += lineSep\n      closing = extraLinebreak = false\n    }\n  }\n  function addText(str) {\n    if (str) {\n      close()\n      text += str\n    }\n  }\n  function walk(node) {\n    if (node.nodeType == 1) {\n      let cmText = node.getAttribute(\"cm-text\")\n      if (cmText) {\n        addText(cmText)\n        return\n      }\n      let markerID = node.getAttribute(\"cm-marker\"), range\n      if (markerID) {\n        let found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))\n        if (found.length && (range = found[0].find(0)))\n          addText(getBetween(cm.doc, range.from, range.to).join(lineSep))\n        return\n      }\n      if (node.getAttribute(\"contenteditable\") == \"false\") return\n      let isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName)\n      if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) return\n\n      if (isBlock) close()\n      for (let i = 0; i < node.childNodes.length; i++)\n        walk(node.childNodes[i])\n\n      if (/^(pre|p)$/i.test(node.nodeName)) extraLinebreak = true\n      if (isBlock) closing = true\n    } else if (node.nodeType == 3) {\n      addText(node.nodeValue.replace(/\\u200b/g, \"\").replace(/\\u00a0/g, \" \"))\n    }\n  }\n  for (;;) {\n    walk(from)\n    if (from == to) break\n    from = from.nextSibling\n    extraLinebreak = false\n  }\n  return text\n}\n\nfunction domToPos(cm, node, offset) {\n  let lineNode\n  if (node == cm.display.lineDiv) {\n    lineNode = cm.display.lineDiv.childNodes[offset]\n    if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true)\n    node = null; offset = 0\n  } else {\n    for (lineNode = node;; lineNode = lineNode.parentNode) {\n      if (!lineNode || lineNode == cm.display.lineDiv) return null\n      if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break\n    }\n  }\n  for (let i = 0; i < cm.display.view.length; i++) {\n    let lineView = cm.display.view[i]\n    if (lineView.node == lineNode)\n      return locateNodeInLineView(lineView, node, offset)\n  }\n}\n\nfunction locateNodeInLineView(lineView, node, offset) {\n  let wrapper = lineView.text.firstChild, bad = false\n  if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true)\n  if (node == wrapper) {\n    bad = true\n    node = wrapper.childNodes[offset]\n    offset = 0\n    if (!node) {\n      let line = lineView.rest ? lst(lineView.rest) : lineView.line\n      return badPos(Pos(lineNo(line), line.text.length), bad)\n    }\n  }\n\n  let textNode = node.nodeType == 3 ? node : null, topNode = node\n  if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {\n    textNode = node.firstChild\n    if (offset) offset = textNode.nodeValue.length\n  }\n  while (topNode.parentNode != wrapper) topNode = topNode.parentNode\n  let measure = lineView.measure, maps = measure.maps\n\n  function find(textNode, topNode, offset) {\n    for (let i = -1; i < (maps ? maps.length : 0); i++) {\n      let map = i < 0 ? measure.map : maps[i]\n      for (let j = 0; j < map.length; j += 3) {\n        let curNode = map[j + 2]\n        if (curNode == textNode || curNode == topNode) {\n          let line = lineNo(i < 0 ? lineView.line : lineView.rest[i])\n          let ch = map[j] + offset\n          if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]\n          return Pos(line, ch)\n        }\n      }\n    }\n  }\n  let found = find(textNode, topNode, offset)\n  if (found) return badPos(found, bad)\n\n  // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems\n  for (let after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {\n    found = find(after, after.firstChild, 0)\n    if (found)\n      return badPos(Pos(found.line, found.ch - dist), bad)\n    else\n      dist += after.textContent.length\n  }\n  for (let before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {\n    found = find(before, before.firstChild, -1)\n    if (found)\n      return badPos(Pos(found.line, found.ch + dist), bad)\n    else\n      dist += before.textContent.length\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/input/TextareaInput.js",
    "content": "import { operation, runInOp } from \"../display/operations.js\"\nimport { prepareSelection } from \"../display/selection.js\"\nimport { applyTextInput, copyableRanges, handlePaste, hiddenTextarea, setLastCopied } from \"./input.js\"\nimport { cursorCoords, posFromMouse } from \"../measurement/position_measurement.js\"\nimport { eventInWidget } from \"../measurement/widgets.js\"\nimport { simpleSelection } from \"../model/selection.js\"\nimport { selectAll, setSelection } from \"../model/selection_updates.js\"\nimport { captureRightClick, ie, ie_version, ios, mac, mobile, presto, webkit } from \"../util/browser.js\"\nimport { activeElt, removeChildrenAndAdd, selectInput } from \"../util/dom.js\"\nimport { e_preventDefault, e_stop, off, on, signalDOMEvent } from \"../util/event.js\"\nimport { hasSelection } from \"../util/feature_detection.js\"\nimport { Delayed, sel_dontScroll } from \"../util/misc.js\"\n\n// TEXTAREA INPUT STYLE\n\nexport default class TextareaInput {\n  constructor(cm) {\n    this.cm = cm\n    // See input.poll and input.reset\n    this.prevInput = \"\"\n\n    // Flag that indicates whether we expect input to appear real soon\n    // now (after some event like 'keypress' or 'input') and are\n    // polling intensively.\n    this.pollingFast = false\n    // Self-resetting timeout for the poller\n    this.polling = new Delayed()\n    // Used to work around IE issue with selection being forgotten when focus moves away from textarea\n    this.hasSelection = false\n    this.composing = null\n  }\n\n  init(display) {\n    let input = this, cm = this.cm\n    this.createField(display)\n    const te = this.textarea\n\n    display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild)\n\n    // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)\n    if (ios) te.style.width = \"0px\"\n\n    on(te, \"input\", () => {\n      if (ie && ie_version >= 9 && this.hasSelection) this.hasSelection = null\n      input.poll()\n    })\n\n    on(te, \"paste\", e => {\n      if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return\n\n      cm.state.pasteIncoming = true\n      input.fastPoll()\n    })\n\n    function prepareCopyCut(e) {\n      if (signalDOMEvent(cm, e)) return\n      if (cm.somethingSelected()) {\n        setLastCopied({lineWise: false, text: cm.getSelections()})\n      } else if (!cm.options.lineWiseCopyCut) {\n        return\n      } else {\n        let ranges = copyableRanges(cm)\n        setLastCopied({lineWise: true, text: ranges.text})\n        if (e.type == \"cut\") {\n          cm.setSelections(ranges.ranges, null, sel_dontScroll)\n        } else {\n          input.prevInput = \"\"\n          te.value = ranges.text.join(\"\\n\")\n          selectInput(te)\n        }\n      }\n      if (e.type == \"cut\") cm.state.cutIncoming = true\n    }\n    on(te, \"cut\", prepareCopyCut)\n    on(te, \"copy\", prepareCopyCut)\n\n    on(display.scroller, \"paste\", e => {\n      if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return\n      cm.state.pasteIncoming = true\n      input.focus()\n    })\n\n    // Prevent normal selection in the editor (we handle our own)\n    on(display.lineSpace, \"selectstart\", e => {\n      if (!eventInWidget(display, e)) e_preventDefault(e)\n    })\n\n    on(te, \"compositionstart\", () => {\n      let start = cm.getCursor(\"from\")\n      if (input.composing) input.composing.range.clear()\n      input.composing = {\n        start: start,\n        range: cm.markText(start, cm.getCursor(\"to\"), {className: \"CodeMirror-composing\"})\n      }\n    })\n    on(te, \"compositionend\", () => {\n      if (input.composing) {\n        input.poll()\n        input.composing.range.clear()\n        input.composing = null\n      }\n    })\n  }\n\n  createField(_display) {\n    // Wraps and hides input textarea\n    this.wrapper = hiddenTextarea()\n    // The semihidden textarea that is focused when the editor is\n    // focused, and receives input.\n    this.textarea = this.wrapper.firstChild\n  }\n\n  prepareSelection() {\n    // Redraw the selection and/or cursor\n    let cm = this.cm, display = cm.display, doc = cm.doc\n    let result = prepareSelection(cm)\n\n    // Move the hidden textarea near the cursor to prevent scrolling artifacts\n    if (cm.options.moveInputWithCursor) {\n      let headPos = cursorCoords(cm, doc.sel.primary().head, \"div\")\n      let wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect()\n      result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,\n                                          headPos.top + lineOff.top - wrapOff.top))\n      result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,\n                                           headPos.left + lineOff.left - wrapOff.left))\n    }\n\n    return result\n  }\n\n  showSelection(drawn) {\n    let cm = this.cm, display = cm.display\n    removeChildrenAndAdd(display.cursorDiv, drawn.cursors)\n    removeChildrenAndAdd(display.selectionDiv, drawn.selection)\n    if (drawn.teTop != null) {\n      this.wrapper.style.top = drawn.teTop + \"px\"\n      this.wrapper.style.left = drawn.teLeft + \"px\"\n    }\n  }\n\n  // Reset the input to correspond to the selection (or to be empty,\n  // when not typing and nothing is selected)\n  reset(typing) {\n    if (this.contextMenuPending || this.composing) return\n    let cm = this.cm\n    if (cm.somethingSelected()) {\n      this.prevInput = \"\"\n      let content = cm.getSelection()\n      this.textarea.value = content\n      if (cm.state.focused) selectInput(this.textarea)\n      if (ie && ie_version >= 9) this.hasSelection = content\n    } else if (!typing) {\n      this.prevInput = this.textarea.value = \"\"\n      if (ie && ie_version >= 9) this.hasSelection = null\n    }\n  }\n\n  getField() { return this.textarea }\n\n  supportsTouch() { return false }\n\n  focus() {\n    if (this.cm.options.readOnly != \"nocursor\" && (!mobile || activeElt() != this.textarea)) {\n      try { this.textarea.focus() }\n      catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM\n    }\n  }\n\n  blur() { this.textarea.blur() }\n\n  resetPosition() {\n    this.wrapper.style.top = this.wrapper.style.left = 0\n  }\n\n  receivedFocus() { this.slowPoll() }\n\n  // Poll for input changes, using the normal rate of polling. This\n  // runs as long as the editor is focused.\n  slowPoll() {\n    if (this.pollingFast) return\n    this.polling.set(this.cm.options.pollInterval, () => {\n      this.poll()\n      if (this.cm.state.focused) this.slowPoll()\n    })\n  }\n\n  // When an event has just come in that is likely to add or change\n  // something in the input textarea, we poll faster, to ensure that\n  // the change appears on the screen quickly.\n  fastPoll() {\n    let missed = false, input = this\n    input.pollingFast = true\n    function p() {\n      let changed = input.poll()\n      if (!changed && !missed) {missed = true; input.polling.set(60, p)}\n      else {input.pollingFast = false; input.slowPoll()}\n    }\n    input.polling.set(20, p)\n  }\n\n  // Read input from the textarea, and update the document to match.\n  // When something is selected, it is present in the textarea, and\n  // selected (unless it is huge, in which case a placeholder is\n  // used). When nothing is selected, the cursor sits after previously\n  // seen text (can be empty), which is stored in prevInput (we must\n  // not reset the textarea when typing, because that breaks IME).\n  poll() {\n    let cm = this.cm, input = this.textarea, prevInput = this.prevInput\n    // Since this is called a *lot*, try to bail out as cheaply as\n    // possible when it is clear that nothing happened. hasSelection\n    // will be the case when there is a lot of text in the textarea,\n    // in which case reading its value would be expensive.\n    if (this.contextMenuPending || !cm.state.focused ||\n        (hasSelection(input) && !prevInput && !this.composing) ||\n        cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)\n      return false\n\n    let text = input.value\n    // If nothing changed, bail.\n    if (text == prevInput && !cm.somethingSelected()) return false\n    // Work around nonsensical selection resetting in IE9/10, and\n    // inexplicable appearance of private area unicode characters on\n    // some key combos in Mac (#2689).\n    if (ie && ie_version >= 9 && this.hasSelection === text ||\n        mac && /[\\uf700-\\uf7ff]/.test(text)) {\n      cm.display.input.reset()\n      return false\n    }\n\n    if (cm.doc.sel == cm.display.selForContextMenu) {\n      let first = text.charCodeAt(0)\n      if (first == 0x200b && !prevInput) prevInput = \"\\u200b\"\n      if (first == 0x21da) { this.reset(); return this.cm.execCommand(\"undo\") }\n    }\n    // Find the part of the input that is actually new\n    let same = 0, l = Math.min(prevInput.length, text.length)\n    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same\n\n    runInOp(cm, () => {\n      applyTextInput(cm, text.slice(same), prevInput.length - same,\n                     null, this.composing ? \"*compose\" : null)\n\n      // Don't leave long text in the textarea, since it makes further polling slow\n      if (text.length > 1000 || text.indexOf(\"\\n\") > -1) input.value = this.prevInput = \"\"\n      else this.prevInput = text\n\n      if (this.composing) {\n        this.composing.range.clear()\n        this.composing.range = cm.markText(this.composing.start, cm.getCursor(\"to\"),\n                                           {className: \"CodeMirror-composing\"})\n      }\n    })\n    return true\n  }\n\n  ensurePolled() {\n    if (this.pollingFast && this.poll()) this.pollingFast = false\n  }\n\n  onKeyPress() {\n    if (ie && ie_version >= 9) this.hasSelection = null\n    this.fastPoll()\n  }\n\n  onContextMenu(e) {\n    let input = this, cm = input.cm, display = cm.display, te = input.textarea\n    if (input.contextMenuPending) input.contextMenuPending()\n    let pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop\n    if (!pos || presto) return // Opera is difficult.\n\n    // Reset the current text selection only if the click is done outside of the selection\n    // and 'resetSelectionOnContextMenu' option is true.\n    let reset = cm.options.resetSelectionOnContextMenu\n    if (reset && cm.doc.sel.contains(pos) == -1)\n      operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll)\n\n    let oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText\n    let wrapperBox = input.wrapper.offsetParent.getBoundingClientRect()\n    input.wrapper.style.cssText = \"position: static\"\n    te.style.cssText = `position: absolute; width: 30px; height: 30px;\n      top: ${e.clientY - wrapperBox.top - 5}px; left: ${e.clientX - wrapperBox.left - 5}px;\n      z-index: 1000; background: ${ie ? \"rgba(255, 255, 255, .05)\" : \"transparent\"};\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);`\n    let oldScrollY\n    if (webkit) oldScrollY = window.scrollY // Work around Chrome issue (#2712)\n    display.input.focus()\n    if (webkit) window.scrollTo(null, oldScrollY)\n    display.input.reset()\n    // Adds \"Select all\" to context menu in FF\n    if (!cm.somethingSelected()) te.value = input.prevInput = \" \"\n    input.contextMenuPending = rehide\n    display.selForContextMenu = cm.doc.sel\n    clearTimeout(display.detectingSelectAll)\n\n    // Select-all will be greyed out if there's nothing to select, so\n    // this adds a zero-width space so that we can later check whether\n    // it got selected.\n    function prepareSelectAllHack() {\n      if (te.selectionStart != null) {\n        let selected = cm.somethingSelected()\n        let extval = \"\\u200b\" + (selected ? te.value : \"\")\n        te.value = \"\\u21da\" // Used to catch context-menu undo\n        te.value = extval\n        input.prevInput = selected ? \"\" : \"\\u200b\"\n        te.selectionStart = 1; te.selectionEnd = extval.length\n        // Re-set this, in case some other handler touched the\n        // selection in the meantime.\n        display.selForContextMenu = cm.doc.sel\n      }\n    }\n    function rehide() {\n      if (input.contextMenuPending != rehide) return\n      input.contextMenuPending = false\n      input.wrapper.style.cssText = oldWrapperCSS\n      te.style.cssText = oldCSS\n      if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos)\n\n      // Try to detect the user choosing select-all\n      if (te.selectionStart != null) {\n        if (!ie || (ie && ie_version < 9)) prepareSelectAllHack()\n        let i = 0, poll = () => {\n          if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&\n              te.selectionEnd > 0 && input.prevInput == \"\\u200b\") {\n            operation(cm, selectAll)(cm)\n          } else if (i++ < 10) {\n            display.detectingSelectAll = setTimeout(poll, 500)\n          } else {\n            display.selForContextMenu = null\n            display.input.reset()\n          }\n        }\n        display.detectingSelectAll = setTimeout(poll, 200)\n      }\n    }\n\n    if (ie && ie_version >= 9) prepareSelectAllHack()\n    if (captureRightClick) {\n      e_stop(e)\n      let mouseup = () => {\n        off(window, \"mouseup\", mouseup)\n        setTimeout(rehide, 20)\n      }\n      on(window, \"mouseup\", mouseup)\n    } else {\n      setTimeout(rehide, 50)\n    }\n  }\n\n  readOnlyChanged(val) {\n    if (!val) this.reset()\n    this.textarea.disabled = val == \"nocursor\"\n  }\n\n  setUneditable() {}\n}\n\nTextareaInput.prototype.needsContentAttribute = false\n"
  },
  {
    "path": "third_party/CodeMirror/src/input/indent.js",
    "content": "import { getContextBefore } from \"../line/highlight.js\"\nimport { Pos } from \"../line/pos.js\"\nimport { getLine } from \"../line/utils_line.js\"\nimport { replaceRange } from \"../model/changes.js\"\nimport { Range } from \"../model/selection.js\"\nimport { replaceOneSelection } from \"../model/selection_updates.js\"\nimport { countColumn, Pass, spaceStr } from \"../util/misc.js\"\n\n// Indent the given line. The how parameter can be \"smart\",\n// \"add\"/null, \"subtract\", or \"prev\". When aggressive is false\n// (typically set to true for forced single-line indents), empty\n// lines are not indented, and places where the mode returns Pass\n// are left alone.\nexport function indentLine(cm, n, how, aggressive) {\n  let doc = cm.doc, state\n  if (how == null) how = \"add\"\n  if (how == \"smart\") {\n    // Fall back to \"prev\" when the mode doesn't have an indentation\n    // method.\n    if (!doc.mode.indent) how = \"prev\"\n    else state = getContextBefore(cm, n).state\n  }\n\n  let tabSize = cm.options.tabSize\n  let line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)\n  if (line.stateAfter) line.stateAfter = null\n  let curSpaceString = line.text.match(/^\\s*/)[0], indentation\n  if (!aggressive && !/\\S/.test(line.text)) {\n    indentation = 0\n    how = \"not\"\n  } else if (how == \"smart\") {\n    indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)\n    if (indentation == Pass || indentation > 150) {\n      if (!aggressive) return\n      how = \"prev\"\n    }\n  }\n  if (how == \"prev\") {\n    if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize)\n    else indentation = 0\n  } else if (how == \"add\") {\n    indentation = curSpace + cm.options.indentUnit\n  } else if (how == \"subtract\") {\n    indentation = curSpace - cm.options.indentUnit\n  } else if (typeof how == \"number\") {\n    indentation = curSpace + how\n  }\n  indentation = Math.max(0, indentation)\n\n  let indentString = \"\", pos = 0\n  if (cm.options.indentWithTabs)\n    for (let i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += \"\\t\"}\n  if (pos < indentation) indentString += spaceStr(indentation - pos)\n\n  if (indentString != curSpaceString) {\n    replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), \"+input\")\n    line.stateAfter = null\n    return true\n  } else {\n    // Ensure that, if the cursor was in the whitespace at the start\n    // of the line, it is moved to the end of that space.\n    for (let i = 0; i < doc.sel.ranges.length; i++) {\n      let range = doc.sel.ranges[i]\n      if (range.head.line == n && range.head.ch < curSpaceString.length) {\n        let pos = Pos(n, curSpaceString.length)\n        replaceOneSelection(doc, i, new Range(pos, pos))\n        break\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/input/input.js",
    "content": "import { runInOp } from \"../display/operations.js\"\nimport { ensureCursorVisible } from \"../display/scrolling.js\"\nimport { Pos } from \"../line/pos.js\"\nimport { getLine } from \"../line/utils_line.js\"\nimport { makeChange } from \"../model/changes.js\"\nimport { ios, webkit } from \"../util/browser.js\"\nimport { elt } from \"../util/dom.js\"\nimport { lst, map } from \"../util/misc.js\"\nimport { signalLater } from \"../util/operation_group.js\"\nimport { splitLinesAuto } from \"../util/feature_detection.js\"\n\nimport { indentLine } from \"./indent.js\"\n\n// This will be set to a {lineWise: bool, text: [string]} object, so\n// that, when pasting, we know what kind of selections the copied\n// text was made out of.\nexport let lastCopied = null\n\nexport function setLastCopied(newLastCopied) {\n  lastCopied = newLastCopied\n}\n\nexport function applyTextInput(cm, inserted, deleted, sel, origin) {\n  let doc = cm.doc\n  cm.display.shift = false\n  if (!sel) sel = doc.sel\n\n  let paste = cm.state.pasteIncoming || origin == \"paste\"\n  let textLines = splitLinesAuto(inserted), multiPaste = null\n  // When pasting N lines into N selections, insert one line per selection\n  if (paste && sel.ranges.length > 1) {\n    if (lastCopied && lastCopied.text.join(\"\\n\") == inserted) {\n      if (sel.ranges.length % lastCopied.text.length == 0) {\n        multiPaste = []\n        for (let i = 0; i < lastCopied.text.length; i++)\n          multiPaste.push(doc.splitLines(lastCopied.text[i]))\n      }\n    } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {\n      multiPaste = map(textLines, l => [l])\n    }\n  }\n\n  let updateInput = cm.curOp.updateInput\n  // Normal behavior is to insert the new text into every selection\n  for (let i = sel.ranges.length - 1; i >= 0; i--) {\n    let range = sel.ranges[i]\n    let from = range.from(), to = range.to()\n    if (range.empty()) {\n      if (deleted && deleted > 0) // Handle deletion\n        from = Pos(from.line, from.ch - deleted)\n      else if (cm.state.overwrite && !paste) // Handle overwrite\n        to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length))\n      else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join(\"\\n\") == inserted)\n        from = to = Pos(from.line, 0)\n    }\n    let changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,\n                       origin: origin || (paste ? \"paste\" : cm.state.cutIncoming ? \"cut\" : \"+input\")}\n    makeChange(cm.doc, changeEvent)\n    signalLater(cm, \"inputRead\", cm, changeEvent)\n  }\n  if (inserted && !paste)\n    triggerElectric(cm, inserted)\n\n  ensureCursorVisible(cm)\n  if (cm.curOp.updateInput < 2) cm.curOp.updateInput = updateInput\n  cm.curOp.typing = true\n  cm.state.pasteIncoming = cm.state.cutIncoming = false\n}\n\nexport function handlePaste(e, cm) {\n  let pasted = e.clipboardData && e.clipboardData.getData(\"Text\")\n  if (pasted) {\n    e.preventDefault()\n    if (!cm.isReadOnly() && !cm.options.disableInput)\n      runInOp(cm, () => applyTextInput(cm, pasted, 0, null, \"paste\"))\n    return true\n  }\n}\n\nexport function triggerElectric(cm, inserted) {\n  // When an 'electric' character is inserted, immediately trigger a reindent\n  if (!cm.options.electricChars || !cm.options.smartIndent) return\n  let sel = cm.doc.sel\n\n  for (let i = sel.ranges.length - 1; i >= 0; i--) {\n    let range = sel.ranges[i]\n    if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue\n    let mode = cm.getModeAt(range.head)\n    let indented = false\n    if (mode.electricChars) {\n      for (let j = 0; j < mode.electricChars.length; j++)\n        if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {\n          indented = indentLine(cm, range.head.line, \"smart\")\n          break\n        }\n    } else if (mode.electricInput) {\n      if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))\n        indented = indentLine(cm, range.head.line, \"smart\")\n    }\n    if (indented) signalLater(cm, \"electricInput\", cm, range.head.line)\n  }\n}\n\nexport function copyableRanges(cm) {\n  let text = [], ranges = []\n  for (let i = 0; i < cm.doc.sel.ranges.length; i++) {\n    let line = cm.doc.sel.ranges[i].head.line\n    let lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}\n    ranges.push(lineRange)\n    text.push(cm.getRange(lineRange.anchor, lineRange.head))\n  }\n  return {text: text, ranges: ranges}\n}\n\nexport function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {\n  field.setAttribute(\"autocorrect\", !!autocorrect)\n  field.setAttribute(\"autocapitalize\", !!autocapitalize)\n  field.setAttribute(\"spellcheck\", !!spellcheck)\n}\n\nexport function hiddenTextarea() {\n  let te = elt(\"textarea\", null, null, \"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none\")\n  let div = elt(\"div\", [te], null, \"overflow: hidden; position: relative; width: 3px; height: 0px;\")\n  // The textarea is kept positioned near the cursor to prevent the\n  // fact that it'll be scrolled into view on input from scrolling\n  // our fake cursor out of view. On webkit, when wrap=off, paste is\n  // very slow. So make the area wide instead.\n  if (webkit) te.style.width = \"1000px\"\n  else te.setAttribute(\"wrap\", \"off\")\n  // If border: 0; -- iOS fails to open keyboard (issue #1287)\n  if (ios) te.style.border = \"1px solid black\"\n  disableBrowserMagic(te)\n  return div\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/input/keymap.js",
    "content": "import { flipCtrlCmd, mac, presto } from \"../util/browser.js\"\nimport { map } from \"../util/misc.js\"\n\nimport { keyNames } from \"./keynames.js\"\n\nexport let keyMap = {}\n\nkeyMap.basic = {\n  \"Left\": \"goCharLeft\", \"Right\": \"goCharRight\", \"Up\": \"goLineUp\", \"Down\": \"goLineDown\",\n  \"End\": \"goLineEnd\", \"Home\": \"goLineStartSmart\", \"PageUp\": \"goPageUp\", \"PageDown\": \"goPageDown\",\n  \"Delete\": \"delCharAfter\", \"Backspace\": \"delCharBefore\", \"Shift-Backspace\": \"delCharBefore\",\n  \"Tab\": \"defaultTab\", \"Shift-Tab\": \"indentAuto\",\n  \"Enter\": \"newlineAndIndent\", \"Insert\": \"toggleOverwrite\",\n  \"Esc\": \"singleSelection\"\n}\n// Note that the save and find-related commands aren't defined by\n// default. User code or addons can define them. Unknown commands\n// are simply ignored.\nkeyMap.pcDefault = {\n  \"Ctrl-A\": \"selectAll\", \"Ctrl-D\": \"deleteLine\", \"Ctrl-Z\": \"undo\", \"Shift-Ctrl-Z\": \"redo\", \"Ctrl-Y\": \"redo\",\n  \"Ctrl-Home\": \"goDocStart\", \"Ctrl-End\": \"goDocEnd\", \"Ctrl-Up\": \"goLineUp\", \"Ctrl-Down\": \"goLineDown\",\n  \"Ctrl-Left\": \"goGroupLeft\", \"Ctrl-Right\": \"goGroupRight\", \"Alt-Left\": \"goLineStart\", \"Alt-Right\": \"goLineEnd\",\n  \"Ctrl-Backspace\": \"delGroupBefore\", \"Ctrl-Delete\": \"delGroupAfter\", \"Ctrl-S\": \"save\", \"Ctrl-F\": \"find\",\n  \"Ctrl-G\": \"findNext\", \"Shift-Ctrl-G\": \"findPrev\", \"Shift-Ctrl-F\": \"replace\", \"Shift-Ctrl-R\": \"replaceAll\",\n  \"Ctrl-[\": \"indentLess\", \"Ctrl-]\": \"indentMore\",\n  \"Ctrl-U\": \"undoSelection\", \"Shift-Ctrl-U\": \"redoSelection\", \"Alt-U\": \"redoSelection\",\n  \"fallthrough\": \"basic\"\n}\n// Very basic readline/emacs-style bindings, which are standard on Mac.\nkeyMap.emacsy = {\n  \"Ctrl-F\": \"goCharRight\", \"Ctrl-B\": \"goCharLeft\", \"Ctrl-P\": \"goLineUp\", \"Ctrl-N\": \"goLineDown\",\n  \"Alt-F\": \"goWordRight\", \"Alt-B\": \"goWordLeft\", \"Ctrl-A\": \"goLineStart\", \"Ctrl-E\": \"goLineEnd\",\n  \"Ctrl-V\": \"goPageDown\", \"Shift-Ctrl-V\": \"goPageUp\", \"Ctrl-D\": \"delCharAfter\", \"Ctrl-H\": \"delCharBefore\",\n  \"Alt-D\": \"delWordAfter\", \"Alt-Backspace\": \"delWordBefore\", \"Ctrl-K\": \"killLine\", \"Ctrl-T\": \"transposeChars\",\n  \"Ctrl-O\": \"openLine\"\n}\nkeyMap.macDefault = {\n  \"Cmd-A\": \"selectAll\", \"Cmd-D\": \"deleteLine\", \"Cmd-Z\": \"undo\", \"Shift-Cmd-Z\": \"redo\", \"Cmd-Y\": \"redo\",\n  \"Cmd-Home\": \"goDocStart\", \"Cmd-Up\": \"goDocStart\", \"Cmd-End\": \"goDocEnd\", \"Cmd-Down\": \"goDocEnd\", \"Alt-Left\": \"goGroupLeft\",\n  \"Alt-Right\": \"goGroupRight\", \"Cmd-Left\": \"goLineLeft\", \"Cmd-Right\": \"goLineRight\", \"Alt-Backspace\": \"delGroupBefore\",\n  \"Ctrl-Alt-Backspace\": \"delGroupAfter\", \"Alt-Delete\": \"delGroupAfter\", \"Cmd-S\": \"save\", \"Cmd-F\": \"find\",\n  \"Cmd-G\": \"findNext\", \"Shift-Cmd-G\": \"findPrev\", \"Cmd-Alt-F\": \"replace\", \"Shift-Cmd-Alt-F\": \"replaceAll\",\n  \"Cmd-[\": \"indentLess\", \"Cmd-]\": \"indentMore\", \"Cmd-Backspace\": \"delWrappedLineLeft\", \"Cmd-Delete\": \"delWrappedLineRight\",\n  \"Cmd-U\": \"undoSelection\", \"Shift-Cmd-U\": \"redoSelection\", \"Ctrl-Up\": \"goDocStart\", \"Ctrl-Down\": \"goDocEnd\",\n  \"fallthrough\": [\"basic\", \"emacsy\"]\n}\nkeyMap[\"default\"] = mac ? keyMap.macDefault : keyMap.pcDefault\n\n// KEYMAP DISPATCH\n\nfunction normalizeKeyName(name) {\n  let parts = name.split(/-(?!$)/)\n  name = parts[parts.length - 1]\n  let alt, ctrl, shift, cmd\n  for (let i = 0; i < parts.length - 1; i++) {\n    let mod = parts[i]\n    if (/^(cmd|meta|m)$/i.test(mod)) cmd = true\n    else if (/^a(lt)?$/i.test(mod)) alt = true\n    else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true\n    else if (/^s(hift)?$/i.test(mod)) shift = true\n    else throw new Error(\"Unrecognized modifier name: \" + mod)\n  }\n  if (alt) name = \"Alt-\" + name\n  if (ctrl) name = \"Ctrl-\" + name\n  if (cmd) name = \"Cmd-\" + name\n  if (shift) name = \"Shift-\" + name\n  return name\n}\n\n// This is a kludge to keep keymaps mostly working as raw objects\n// (backwards compatibility) while at the same time support features\n// like normalization and multi-stroke key bindings. It compiles a\n// new normalized keymap, and then updates the old object to reflect\n// this.\nexport function normalizeKeyMap(keymap) {\n  let copy = {}\n  for (let keyname in keymap) if (keymap.hasOwnProperty(keyname)) {\n    let value = keymap[keyname]\n    if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue\n    if (value == \"...\") { delete keymap[keyname]; continue }\n\n    let keys = map(keyname.split(\" \"), normalizeKeyName)\n    for (let i = 0; i < keys.length; i++) {\n      let val, name\n      if (i == keys.length - 1) {\n        name = keys.join(\" \")\n        val = value\n      } else {\n        name = keys.slice(0, i + 1).join(\" \")\n        val = \"...\"\n      }\n      let prev = copy[name]\n      if (!prev) copy[name] = val\n      else if (prev != val) throw new Error(\"Inconsistent bindings for \" + name)\n    }\n    delete keymap[keyname]\n  }\n  for (let prop in copy) keymap[prop] = copy[prop]\n  return keymap\n}\n\nexport function lookupKey(key, map, handle, context) {\n  map = getKeyMap(map)\n  let found = map.call ? map.call(key, context) : map[key]\n  if (found === false) return \"nothing\"\n  if (found === \"...\") return \"multi\"\n  if (found != null && handle(found)) return \"handled\"\n\n  if (map.fallthrough) {\n    if (Object.prototype.toString.call(map.fallthrough) != \"[object Array]\")\n      return lookupKey(key, map.fallthrough, handle, context)\n    for (let i = 0; i < map.fallthrough.length; i++) {\n      let result = lookupKey(key, map.fallthrough[i], handle, context)\n      if (result) return result\n    }\n  }\n}\n\n// Modifier key presses don't count as 'real' key presses for the\n// purpose of keymap fallthrough.\nexport function isModifierKey(value) {\n  let name = typeof value == \"string\" ? value : keyNames[value.keyCode]\n  return name == \"Ctrl\" || name == \"Alt\" || name == \"Shift\" || name == \"Mod\"\n}\n\nexport function addModifierNames(name, event, noShift) {\n  let base = name\n  if (event.altKey && base != \"Alt\") name = \"Alt-\" + name\n  if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != \"Ctrl\") name = \"Ctrl-\" + name\n  if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != \"Cmd\") name = \"Cmd-\" + name\n  if (!noShift && event.shiftKey && base != \"Shift\") name = \"Shift-\" + name\n  return name\n}\n\n// Look up the name of a key as indicated by an event object.\nexport function keyName(event, noShift) {\n  if (presto && event.keyCode == 34 && event[\"char\"]) return false\n  let name = keyNames[event.keyCode]\n  if (name == null || event.altGraphKey) return false\n  // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,\n  // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)\n  if (event.keyCode == 3 && event.code) name = event.code\n  return addModifierNames(name, event, noShift)\n}\n\nexport function getKeyMap(val) {\n  return typeof val == \"string\" ? keyMap[val] : val\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/input/keynames.js",
    "content": "export let keyNames = {\n  3: \"Pause\", 8: \"Backspace\", 9: \"Tab\", 13: \"Enter\", 16: \"Shift\", 17: \"Ctrl\", 18: \"Alt\",\n  19: \"Pause\", 20: \"CapsLock\", 27: \"Esc\", 32: \"Space\", 33: \"PageUp\", 34: \"PageDown\", 35: \"End\",\n  36: \"Home\", 37: \"Left\", 38: \"Up\", 39: \"Right\", 40: \"Down\", 44: \"PrintScrn\", 45: \"Insert\",\n  46: \"Delete\", 59: \";\", 61: \"=\", 91: \"Mod\", 92: \"Mod\", 93: \"Mod\",\n  106: \"*\", 107: \"=\", 109: \"-\", 110: \".\", 111: \"/\", 127: \"Delete\", 145: \"ScrollLock\",\n  173: \"-\", 186: \";\", 187: \"=\", 188: \",\", 189: \"-\", 190: \".\", 191: \"/\", 192: \"`\", 219: \"[\", 220: \"\\\\\",\n  221: \"]\", 222: \"'\", 63232: \"Up\", 63233: \"Down\", 63234: \"Left\", 63235: \"Right\", 63272: \"Delete\",\n  63273: \"Home\", 63275: \"End\", 63276: \"PageUp\", 63277: \"PageDown\", 63302: \"Insert\"\n}\n\n// Number keys\nfor (let i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i)\n// Alphabetic keys\nfor (let i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i)\n// Function keys\nfor (let i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = \"F\" + i\n"
  },
  {
    "path": "third_party/CodeMirror/src/input/movement.js",
    "content": "import { Pos } from \"../line/pos.js\"\nimport { prepareMeasureForLine, measureCharPrepared, wrappedLineExtentChar } from \"../measurement/position_measurement.js\"\nimport { getBidiPartAt, getOrder } from \"../util/bidi.js\"\nimport { findFirst, lst, skipExtendingChars } from \"../util/misc.js\"\n\nfunction moveCharLogically(line, ch, dir) {\n  let target = skipExtendingChars(line.text, ch + dir, dir)\n  return target < 0 || target > line.text.length ? null : target\n}\n\nexport function moveLogically(line, start, dir) {\n  let ch = moveCharLogically(line, start.ch, dir)\n  return ch == null ? null : new Pos(start.line, ch, dir < 0 ? \"after\" : \"before\")\n}\n\nexport function endOfLine(visually, cm, lineObj, lineNo, dir) {\n  if (visually) {\n    let order = getOrder(lineObj, cm.doc.direction)\n    if (order) {\n      let part = dir < 0 ? lst(order) : order[0]\n      let moveInStorageOrder = (dir < 0) == (part.level == 1)\n      let sticky = moveInStorageOrder ? \"after\" : \"before\"\n      let ch\n      // With a wrapped rtl chunk (possibly spanning multiple bidi parts),\n      // it could be that the last bidi part is not on the last visual line,\n      // since visual lines contain content order-consecutive chunks.\n      // Thus, in rtl, we are looking for the first (content-order) character\n      // in the rtl chunk that is on the last line (that is, the same line\n      // as the last (content-order) character).\n      if (part.level > 0 || cm.doc.direction == \"rtl\") {\n        let prep = prepareMeasureForLine(cm, lineObj)\n        ch = dir < 0 ? lineObj.text.length - 1 : 0\n        let targetTop = measureCharPrepared(cm, prep, ch).top\n        ch = findFirst(ch => measureCharPrepared(cm, prep, ch).top == targetTop, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch)\n        if (sticky == \"before\") ch = moveCharLogically(lineObj, ch, 1)\n      } else ch = dir < 0 ? part.to : part.from\n      return new Pos(lineNo, ch, sticky)\n    }\n  }\n  return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? \"before\" : \"after\")\n}\n\nexport function moveVisually(cm, line, start, dir) {\n  let bidi = getOrder(line, cm.doc.direction)\n  if (!bidi) return moveLogically(line, start, dir)\n  if (start.ch >= line.text.length) {\n    start.ch = line.text.length\n    start.sticky = \"before\"\n  } else if (start.ch <= 0) {\n    start.ch = 0\n    start.sticky = \"after\"\n  }\n  let partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]\n  if (cm.doc.direction == \"ltr\" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {\n    // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,\n    // nothing interesting happens.\n    return moveLogically(line, start, dir)\n  }\n\n  let mv = (pos, dir) => moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir)\n  let prep\n  let getWrappedLineExtent = ch => {\n    if (!cm.options.lineWrapping) return {begin: 0, end: line.text.length}\n    prep = prep || prepareMeasureForLine(cm, line)\n    return wrappedLineExtentChar(cm, line, prep, ch)\n  }\n  let wrappedLineExtent = getWrappedLineExtent(start.sticky == \"before\" ? mv(start, -1) : start.ch)\n\n  if (cm.doc.direction == \"rtl\" || part.level == 1) {\n    let moveInStorageOrder = (part.level == 1) == (dir < 0)\n    let ch = mv(start, moveInStorageOrder ? 1 : -1)\n    if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {\n      // Case 2: We move within an rtl part or in an rtl editor on the same visual line\n      let sticky = moveInStorageOrder ? \"before\" : \"after\"\n      return new Pos(start.line, ch, sticky)\n    }\n  }\n\n  // Case 3: Could not move within this bidi part in this visual line, so leave\n  // the current bidi part\n\n  let searchInVisualLine = (partPos, dir, wrappedLineExtent) => {\n    let getRes = (ch, moveInStorageOrder) => moveInStorageOrder\n      ? new Pos(start.line, mv(ch, 1), \"before\")\n      : new Pos(start.line, ch, \"after\")\n\n    for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {\n      let part = bidi[partPos]\n      let moveInStorageOrder = (dir > 0) == (part.level != 1)\n      let ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1)\n      if (part.from <= ch && ch < part.to) return getRes(ch, moveInStorageOrder)\n      ch = moveInStorageOrder ? part.from : mv(part.to, -1)\n      if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) return getRes(ch, moveInStorageOrder)\n    }\n  }\n\n  // Case 3a: Look for other bidi parts on the same visual line\n  let res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent)\n  if (res) return res\n\n  // Case 3b: Look for other bidi parts on the next visual line\n  let nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1)\n  if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {\n    res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh))\n    if (res) return res\n  }\n\n  // Case 4: Nowhere to move\n  return null\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/line/highlight.js",
    "content": "import { countColumn } from \"../util/misc.js\"\nimport { copyState, innerMode, startState } from \"../modes.js\"\nimport StringStream from \"../util/StringStream.js\"\n\nimport { getLine, lineNo } from \"./utils_line.js\"\nimport { clipPos } from \"./pos.js\"\n\nclass SavedContext {\n  constructor(state, lookAhead) {\n    this.state = state\n    this.lookAhead = lookAhead\n  }\n}\n\nclass Context {\n  constructor(doc, state, line, lookAhead) {\n    this.state = state\n    this.doc = doc\n    this.line = line\n    this.maxLookAhead = lookAhead || 0\n    this.baseTokens = null\n    this.baseTokenPos = 1\n  }\n\n  lookAhead(n) {\n    let line = this.doc.getLine(this.line + n)\n    if (line != null && n > this.maxLookAhead) this.maxLookAhead = n\n    return line\n  }\n\n  baseToken(n) {\n    if (!this.baseTokens) return null\n    while (this.baseTokens[this.baseTokenPos] <= n)\n      this.baseTokenPos += 2\n    let type = this.baseTokens[this.baseTokenPos + 1]\n    return {type: type && type.replace(/( |^)overlay .*/, \"\"),\n            size: this.baseTokens[this.baseTokenPos] - n}\n  }\n\n  nextLine() {\n    this.line++\n    if (this.maxLookAhead > 0) this.maxLookAhead--\n  }\n\n  static fromSaved(doc, saved, line) {\n    if (saved instanceof SavedContext)\n      return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead)\n    else\n      return new Context(doc, copyState(doc.mode, saved), line)\n  }\n\n  save(copy) {\n    let state = copy !== false ? copyState(this.doc.mode, this.state) : this.state\n    return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state\n  }\n}\n\n\n// Compute a style array (an array starting with a mode generation\n// -- for invalidation -- followed by pairs of end positions and\n// style strings), which is used to highlight the tokens on the\n// line.\nexport function highlightLine(cm, line, context, forceToEnd) {\n  // A styles array always starts with a number identifying the\n  // mode/overlays that it is based on (for easy invalidation).\n  let st = [cm.state.modeGen], lineClasses = {}\n  // Compute the base array of styles\n  runMode(cm, line.text, cm.doc.mode, context, (end, style) => st.push(end, style),\n          lineClasses, forceToEnd)\n  let state = context.state\n\n  // Run overlays, adjust style array.\n  for (let o = 0; o < cm.state.overlays.length; ++o) {\n    context.baseTokens = st\n    let overlay = cm.state.overlays[o], i = 1, at = 0\n    context.state = true\n    runMode(cm, line.text, overlay.mode, context, (end, style) => {\n      let start = i\n      // Ensure there's a token end at the current position, and that i points at it\n      while (at < end) {\n        let i_end = st[i]\n        if (i_end > end)\n          st.splice(i, 1, end, st[i+1], i_end)\n        i += 2\n        at = Math.min(end, i_end)\n      }\n      if (!style) return\n      if (overlay.opaque) {\n        st.splice(start, i - start, end, \"overlay \" + style)\n        i = start + 2\n      } else {\n        for (; start < i; start += 2) {\n          let cur = st[start+1]\n          st[start+1] = (cur ? cur + \" \" : \"\") + \"overlay \" + style\n        }\n      }\n    }, lineClasses)\n    context.state = state\n    context.baseTokens = null\n    context.baseTokenPos = 1\n  }\n\n  return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}\n}\n\nexport function getLineStyles(cm, line, updateFrontier) {\n  if (!line.styles || line.styles[0] != cm.state.modeGen) {\n    let context = getContextBefore(cm, lineNo(line))\n    let resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state)\n    let result = highlightLine(cm, line, context)\n    if (resetState) context.state = resetState\n    line.stateAfter = context.save(!resetState)\n    line.styles = result.styles\n    if (result.classes) line.styleClasses = result.classes\n    else if (line.styleClasses) line.styleClasses = null\n    if (updateFrontier === cm.doc.highlightFrontier)\n      cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier)\n  }\n  return line.styles\n}\n\nexport function getContextBefore(cm, n, precise) {\n  let doc = cm.doc, display = cm.display\n  if (!doc.mode.startState) return new Context(doc, true, n)\n  let start = findStartLine(cm, n, precise)\n  let saved = start > doc.first && getLine(doc, start - 1).stateAfter\n  let context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start)\n\n  doc.iter(start, n, line => {\n    processLine(cm, line.text, context)\n    let pos = context.line\n    line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null\n    context.nextLine()\n  })\n  if (precise) doc.modeFrontier = context.line\n  return context\n}\n\n// Lightweight form of highlight -- proceed over this line and\n// update state, but don't save a style array. Used for lines that\n// aren't currently visible.\nexport function processLine(cm, text, context, startAt) {\n  let mode = cm.doc.mode\n  let stream = new StringStream(text, cm.options.tabSize, context)\n  stream.start = stream.pos = startAt || 0\n  if (text == \"\") callBlankLine(mode, context.state)\n  while (!stream.eol()) {\n    readToken(mode, stream, context.state)\n    stream.start = stream.pos\n  }\n}\n\nfunction callBlankLine(mode, state) {\n  if (mode.blankLine) return mode.blankLine(state)\n  if (!mode.innerMode) return\n  let inner = innerMode(mode, state)\n  if (inner.mode.blankLine) return inner.mode.blankLine(inner.state)\n}\n\nfunction readToken(mode, stream, state, inner) {\n  for (let i = 0; i < 10; i++) {\n    if (inner) inner[0] = innerMode(mode, state).mode\n    let style = mode.token(stream, state)\n    if (stream.pos > stream.start) return style\n  }\n  throw new Error(\"Mode \" + mode.name + \" failed to advance stream.\")\n}\n\nclass Token {\n  constructor(stream, type, state) {\n    this.start = stream.start; this.end = stream.pos\n    this.string = stream.current()\n    this.type = type || null\n    this.state = state\n  }\n}\n\n// Utility for getTokenAt and getLineTokens\nexport function takeToken(cm, pos, precise, asArray) {\n  let doc = cm.doc, mode = doc.mode, style\n  pos = clipPos(doc, pos)\n  let line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise)\n  let stream = new StringStream(line.text, cm.options.tabSize, context), tokens\n  if (asArray) tokens = []\n  while ((asArray || stream.pos < pos.ch) && !stream.eol()) {\n    stream.start = stream.pos\n    style = readToken(mode, stream, context.state)\n    if (asArray) tokens.push(new Token(stream, style, copyState(doc.mode, context.state)))\n  }\n  return asArray ? tokens : new Token(stream, style, context.state)\n}\n\nfunction extractLineClasses(type, output) {\n  if (type) for (;;) {\n    let lineClass = type.match(/(?:^|\\s+)line-(background-)?(\\S+)/)\n    if (!lineClass) break\n    type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)\n    let prop = lineClass[1] ? \"bgClass\" : \"textClass\"\n    if (output[prop] == null)\n      output[prop] = lineClass[2]\n    else if (!(new RegExp(\"(?:^|\\s)\" + lineClass[2] + \"(?:$|\\s)\")).test(output[prop]))\n      output[prop] += \" \" + lineClass[2]\n  }\n  return type\n}\n\n// Run the given mode's parser over a line, calling f for each token.\nfunction runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {\n  let flattenSpans = mode.flattenSpans\n  if (flattenSpans == null) flattenSpans = cm.options.flattenSpans\n  let curStart = 0, curStyle = null\n  let stream = new StringStream(text, cm.options.tabSize, context), style\n  let inner = cm.options.addModeClass && [null]\n  if (text == \"\") extractLineClasses(callBlankLine(mode, context.state), lineClasses)\n  while (!stream.eol()) {\n    if (stream.pos > cm.options.maxHighlightLength) {\n      flattenSpans = false\n      if (forceToEnd) processLine(cm, text, context, stream.pos)\n      stream.pos = text.length\n      style = null\n    } else {\n      style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses)\n    }\n    if (inner) {\n      let mName = inner[0].name\n      if (mName) style = \"m-\" + (style ? mName + \" \" + style : mName)\n    }\n    if (!flattenSpans || curStyle != style) {\n      while (curStart < stream.start) {\n        curStart = Math.min(stream.start, curStart + 5000)\n        f(curStart, curStyle)\n      }\n      curStyle = style\n    }\n    stream.start = stream.pos\n  }\n  while (curStart < stream.pos) {\n    // Webkit seems to refuse to render text nodes longer than 57444\n    // characters, and returns inaccurate measurements in nodes\n    // starting around 5000 chars.\n    let pos = Math.min(stream.pos, curStart + 5000)\n    f(pos, curStyle)\n    curStart = pos\n  }\n}\n\n// Finds the line to start with when starting a parse. Tries to\n// find a line with a stateAfter, so that it can start with a\n// valid state. If that fails, it returns the line with the\n// smallest indentation, which tends to need the least context to\n// parse correctly.\nfunction findStartLine(cm, n, precise) {\n  let minindent, minline, doc = cm.doc\n  let lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)\n  for (let search = n; search > lim; --search) {\n    if (search <= doc.first) return doc.first\n    let line = getLine(doc, search - 1), after = line.stateAfter\n    if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))\n      return search\n    let indented = countColumn(line.text, null, cm.options.tabSize)\n    if (minline == null || minindent > indented) {\n      minline = search - 1\n      minindent = indented\n    }\n  }\n  return minline\n}\n\nexport function retreatFrontier(doc, n) {\n  doc.modeFrontier = Math.min(doc.modeFrontier, n)\n  if (doc.highlightFrontier < n - 10) return\n  let start = doc.first\n  for (let line = n - 1; line > start; line--) {\n    let saved = getLine(doc, line).stateAfter\n    // change is on 3\n    // state on line 1 looked ahead 2 -- so saw 3\n    // test 1 + 2 < 3 should cover this\n    if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {\n      start = line + 1\n      break\n    }\n  }\n  doc.highlightFrontier = Math.min(doc.highlightFrontier, start)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/line/line_data.js",
    "content": "import { getOrder } from \"../util/bidi.js\"\nimport { ie, ie_version, webkit } from \"../util/browser.js\"\nimport { elt, eltP, joinClasses } from \"../util/dom.js\"\nimport { eventMixin, signal } from \"../util/event.js\"\nimport { hasBadBidiRects, zeroWidthElement } from \"../util/feature_detection.js\"\nimport { lst, spaceStr } from \"../util/misc.js\"\n\nimport { getLineStyles } from \"./highlight.js\"\nimport { attachMarkedSpans, compareCollapsedMarkers, detachMarkedSpans, lineIsHidden, visualLineContinued } from \"./spans.js\"\nimport { getLine, lineNo, updateLineHeight } from \"./utils_line.js\"\n\n// LINE DATA STRUCTURE\n\n// Line objects. These hold state related to a line, including\n// highlighting info (the styles array).\nexport class Line {\n  constructor(text, markedSpans, estimateHeight) {\n    this.text = text\n    attachMarkedSpans(this, markedSpans)\n    this.height = estimateHeight ? estimateHeight(this) : 1\n  }\n\n  lineNo() { return lineNo(this) }\n}\neventMixin(Line)\n\n// Change the content (text, markers) of a line. Automatically\n// invalidates cached information and tries to re-estimate the\n// line's height.\nexport function updateLine(line, text, markedSpans, estimateHeight) {\n  line.text = text\n  if (line.stateAfter) line.stateAfter = null\n  if (line.styles) line.styles = null\n  if (line.order != null) line.order = null\n  detachMarkedSpans(line)\n  attachMarkedSpans(line, markedSpans)\n  let estHeight = estimateHeight ? estimateHeight(line) : 1\n  if (estHeight != line.height) updateLineHeight(line, estHeight)\n}\n\n// Detach a line from the document tree and its markers.\nexport function cleanUpLine(line) {\n  line.parent = null\n  detachMarkedSpans(line)\n}\n\n// Convert a style as returned by a mode (either null, or a string\n// containing one or more styles) to a CSS style. This is cached,\n// and also looks for line-wide styles.\nlet styleToClassCache = {}, styleToClassCacheWithMode = {}\nfunction interpretTokenStyle(style, options) {\n  if (!style || /^\\s*$/.test(style)) return null\n  let cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache\n  return cache[style] ||\n    (cache[style] = style.replace(/\\S+/g, \"cm-$&\"))\n}\n\n// Render the DOM representation of the text of a line. Also builds\n// up a 'line map', which points at the DOM nodes that represent\n// specific stretches of text, and is used by the measuring code.\n// The returned object contains the DOM node, this map, and\n// information about line-wide styles that were set by the mode.\nexport function buildLineContent(cm, lineView) {\n  // The padding-right forces the element to have a 'border', which\n  // is needed on Webkit to be able to get line-level bounding\n  // rectangles for it (in measureChar).\n  let content = eltP(\"span\", null, null, webkit ? \"padding-right: .1px\" : null)\n  let builder = {pre: eltP(\"pre\", [content], \"CodeMirror-line\"), content: content,\n                 col: 0, pos: 0, cm: cm,\n                 trailingSpace: false,\n                 splitSpaces: cm.getOption(\"lineWrapping\")}\n  lineView.measure = {}\n\n  // Iterate over the logical lines that make up this visual line.\n  for (let i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {\n    let line = i ? lineView.rest[i - 1] : lineView.line, order\n    builder.pos = 0\n    builder.addToken = buildToken\n    // Optionally wire in some hacks into the token-rendering\n    // algorithm, to deal with browser quirks.\n    if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))\n      builder.addToken = buildTokenBadBidi(builder.addToken, order)\n    builder.map = []\n    let allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)\n    insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))\n    if (line.styleClasses) {\n      if (line.styleClasses.bgClass)\n        builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || \"\")\n      if (line.styleClasses.textClass)\n        builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || \"\")\n    }\n\n    // Ensure at least a single node is present, for measuring.\n    if (builder.map.length == 0)\n      builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)))\n\n    // Store the map and a cache object for the current logical line\n    if (i == 0) {\n      lineView.measure.map = builder.map\n      lineView.measure.cache = {}\n    } else {\n      ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)\n      ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})\n    }\n  }\n\n  // See issue #2901\n  if (webkit) {\n    let last = builder.content.lastChild\n    if (/\\bcm-tab\\b/.test(last.className) || (last.querySelector && last.querySelector(\".cm-tab\")))\n      builder.content.className = \"cm-tab-wrap-hack\"\n  }\n\n  signal(cm, \"renderLine\", cm, lineView.line, builder.pre)\n  if (builder.pre.className)\n    builder.textClass = joinClasses(builder.pre.className, builder.textClass || \"\")\n\n  return builder\n}\n\nexport function defaultSpecialCharPlaceholder(ch) {\n  let token = elt(\"span\", \"\\u2022\", \"cm-invalidchar\")\n  token.title = \"\\\\u\" + ch.charCodeAt(0).toString(16)\n  token.setAttribute(\"aria-label\", token.title)\n  return token\n}\n\n// Build up the DOM representation for a single token, and add it to\n// the line map. Takes care to render special characters separately.\nfunction buildToken(builder, text, style, startStyle, endStyle, css, attributes) {\n  if (!text) return\n  let displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text\n  let special = builder.cm.state.specialChars, mustWrap = false\n  let content\n  if (!special.test(text)) {\n    builder.col += text.length\n    content = document.createTextNode(displayText)\n    builder.map.push(builder.pos, builder.pos + text.length, content)\n    if (ie && ie_version < 9) mustWrap = true\n    builder.pos += text.length\n  } else {\n    content = document.createDocumentFragment()\n    let pos = 0\n    while (true) {\n      special.lastIndex = pos\n      let m = special.exec(text)\n      let skipped = m ? m.index - pos : text.length - pos\n      if (skipped) {\n        let txt = document.createTextNode(displayText.slice(pos, pos + skipped))\n        if (ie && ie_version < 9) content.appendChild(elt(\"span\", [txt]))\n        else content.appendChild(txt)\n        builder.map.push(builder.pos, builder.pos + skipped, txt)\n        builder.col += skipped\n        builder.pos += skipped\n      }\n      if (!m) break\n      pos += skipped + 1\n      let txt\n      if (m[0] == \"\\t\") {\n        let tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize\n        txt = content.appendChild(elt(\"span\", spaceStr(tabWidth), \"cm-tab\"))\n        txt.setAttribute(\"role\", \"presentation\")\n        txt.setAttribute(\"cm-text\", \"\\t\")\n        builder.col += tabWidth\n      } else if (m[0] == \"\\r\" || m[0] == \"\\n\") {\n        txt = content.appendChild(elt(\"span\", m[0] == \"\\r\" ? \"\\u240d\" : \"\\u2424\", \"cm-invalidchar\"))\n        txt.setAttribute(\"cm-text\", m[0])\n        builder.col += 1\n      } else {\n        txt = builder.cm.options.specialCharPlaceholder(m[0])\n        txt.setAttribute(\"cm-text\", m[0])\n        if (ie && ie_version < 9) content.appendChild(elt(\"span\", [txt]))\n        else content.appendChild(txt)\n        builder.col += 1\n      }\n      builder.map.push(builder.pos, builder.pos + 1, txt)\n      builder.pos++\n    }\n  }\n  builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32\n  if (style || startStyle || endStyle || mustWrap || css) {\n    let fullStyle = style || \"\"\n    if (startStyle) fullStyle += startStyle\n    if (endStyle) fullStyle += endStyle\n    let token = elt(\"span\", [content], fullStyle, css)\n    if (attributes) {\n      for (let attr in attributes) if (attributes.hasOwnProperty(attr) && attr != \"style\" && attr != \"class\")\n        token.setAttribute(attr, attributes[attr])\n    }\n    return builder.content.appendChild(token)\n  }\n  builder.content.appendChild(content)\n}\n\n// Change some spaces to NBSP to prevent the browser from collapsing\n// trailing spaces at the end of a line when rendering text (issue #1362).\nfunction splitSpaces(text, trailingBefore) {\n  if (text.length > 1 && !/  /.test(text)) return text\n  let spaceBefore = trailingBefore, result = \"\"\n  for (let i = 0; i < text.length; i++) {\n    let ch = text.charAt(i)\n    if (ch == \" \" && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))\n      ch = \"\\u00a0\"\n    result += ch\n    spaceBefore = ch == \" \"\n  }\n  return result\n}\n\n// Work around nonsense dimensions being reported for stretches of\n// right-to-left text.\nfunction buildTokenBadBidi(inner, order) {\n  return (builder, text, style, startStyle, endStyle, css, attributes) => {\n    style = style ? style + \" cm-force-border\" : \"cm-force-border\"\n    let start = builder.pos, end = start + text.length\n    for (;;) {\n      // Find the part that overlaps with the start of this text\n      let part\n      for (let i = 0; i < order.length; i++) {\n        part = order[i]\n        if (part.to > start && part.from <= start) break\n      }\n      if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, css, attributes)\n      inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes)\n      startStyle = null\n      text = text.slice(part.to - start)\n      start = part.to\n    }\n  }\n}\n\nfunction buildCollapsedSpan(builder, size, marker, ignoreWidget) {\n  let widget = !ignoreWidget && marker.widgetNode\n  if (widget) builder.map.push(builder.pos, builder.pos + size, widget)\n  if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {\n    if (!widget)\n      widget = builder.content.appendChild(document.createElement(\"span\"))\n    widget.setAttribute(\"cm-marker\", marker.id)\n  }\n  if (widget) {\n    builder.cm.display.input.setUneditable(widget)\n    builder.content.appendChild(widget)\n  }\n  builder.pos += size\n  builder.trailingSpace = false\n}\n\n// Outputs a number of spans to make up a line, taking highlighting\n// and marked text into account.\nfunction insertLineContent(line, builder, styles) {\n  let spans = line.markedSpans, allText = line.text, at = 0\n  if (!spans) {\n    for (let i = 1; i < styles.length; i+=2)\n      builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options))\n    return\n  }\n\n  let len = allText.length, pos = 0, i = 1, text = \"\", style, css\n  let nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes\n  for (;;) {\n    if (nextChange == pos) { // Update current marker set\n      spanStyle = spanEndStyle = spanStartStyle = css = \"\"\n      attributes = null\n      collapsed = null; nextChange = Infinity\n      let foundBookmarks = [], endStyles\n      for (let j = 0; j < spans.length; ++j) {\n        let sp = spans[j], m = sp.marker\n        if (m.type == \"bookmark\" && sp.from == pos && m.widgetNode) {\n          foundBookmarks.push(m)\n        } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {\n          if (sp.to != null && sp.to != pos && nextChange > sp.to) {\n            nextChange = sp.to\n            spanEndStyle = \"\"\n          }\n          if (m.className) spanStyle += \" \" + m.className\n          if (m.css) css = (css ? css + \";\" : \"\") + m.css\n          if (m.startStyle && sp.from == pos) spanStartStyle += \" \" + m.startStyle\n          if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)\n          // support for the old title property\n          // https://github.com/codemirror/CodeMirror/pull/5673\n          if (m.title) (attributes || (attributes = {})).title = m.title\n          if (m.attributes) {\n            for (let attr in m.attributes)\n              (attributes || (attributes = {}))[attr] = m.attributes[attr]\n          }\n          if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))\n            collapsed = sp\n        } else if (sp.from > pos && nextChange > sp.from) {\n          nextChange = sp.from\n        }\n      }\n      if (endStyles) for (let j = 0; j < endStyles.length; j += 2)\n        if (endStyles[j + 1] == nextChange) spanEndStyle += \" \" + endStyles[j]\n\n      if (!collapsed || collapsed.from == pos) for (let j = 0; j < foundBookmarks.length; ++j)\n        buildCollapsedSpan(builder, 0, foundBookmarks[j])\n      if (collapsed && (collapsed.from || 0) == pos) {\n        buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,\n                           collapsed.marker, collapsed.from == null)\n        if (collapsed.to == null) return\n        if (collapsed.to == pos) collapsed = false\n      }\n    }\n    if (pos >= len) break\n\n    let upto = Math.min(len, nextChange)\n    while (true) {\n      if (text) {\n        let end = pos + text.length\n        if (!collapsed) {\n          let tokenText = end > upto ? text.slice(0, upto - pos) : text\n          builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,\n                           spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : \"\", css, attributes)\n        }\n        if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}\n        pos = end\n        spanStartStyle = \"\"\n      }\n      text = allText.slice(at, at = styles[i++])\n      style = interpretTokenStyle(styles[i++], builder.cm.options)\n    }\n  }\n}\n\n\n// These objects are used to represent the visible (currently drawn)\n// part of the document. A LineView may correspond to multiple\n// logical lines, if those are connected by collapsed ranges.\nexport function LineView(doc, line, lineN) {\n  // The starting line\n  this.line = line\n  // Continuing lines, if any\n  this.rest = visualLineContinued(line)\n  // Number of logical lines in this visual line\n  this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1\n  this.node = this.text = null\n  this.hidden = lineIsHidden(doc, line)\n}\n\n// Create a range of LineView objects for the given lines.\nexport function buildViewArray(cm, from, to) {\n  let array = [], nextPos\n  for (let pos = from; pos < to; pos = nextPos) {\n    let view = new LineView(cm.doc, getLine(cm.doc, pos), pos)\n    nextPos = pos + view.size\n    array.push(view)\n  }\n  return array\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/line/pos.js",
    "content": "import { getLine } from \"./utils_line.js\"\n\n// A Pos instance represents a position within the text.\nexport function Pos(line, ch, sticky = null) {\n  if (!(this instanceof Pos)) return new Pos(line, ch, sticky)\n  this.line = line\n  this.ch = ch\n  this.sticky = sticky\n}\n\n// Compare two positions, return 0 if they are the same, a negative\n// number when a is less, and a positive number otherwise.\nexport function cmp(a, b) { return a.line - b.line || a.ch - b.ch }\n\nexport function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }\n\nexport function copyPos(x) {return Pos(x.line, x.ch)}\nexport function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }\nexport function minPos(a, b) { return cmp(a, b) < 0 ? a : b }\n\n// Most of the external API clips given positions to make sure they\n// actually exist within the document.\nexport function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}\nexport function clipPos(doc, pos) {\n  if (pos.line < doc.first) return Pos(doc.first, 0)\n  let last = doc.first + doc.size - 1\n  if (pos.line > last) return Pos(last, getLine(doc, last).text.length)\n  return clipToLen(pos, getLine(doc, pos.line).text.length)\n}\nfunction clipToLen(pos, linelen) {\n  let ch = pos.ch\n  if (ch == null || ch > linelen) return Pos(pos.line, linelen)\n  else if (ch < 0) return Pos(pos.line, 0)\n  else return pos\n}\nexport function clipPosArray(doc, array) {\n  let out = []\n  for (let i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i])\n  return out\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/line/saw_special_spans.js",
    "content": "// Optimize some code when these features are not used.\nexport let sawReadOnlySpans = false, sawCollapsedSpans = false\n\nexport function seeReadOnlySpans() {\n  sawReadOnlySpans = true\n}\n\nexport function seeCollapsedSpans() {\n  sawCollapsedSpans = true\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/line/spans.js",
    "content": "import { indexOf, lst } from \"../util/misc.js\"\n\nimport { cmp } from \"./pos.js\"\nimport { sawCollapsedSpans } from \"./saw_special_spans.js\"\nimport { getLine, isLine, lineNo } from \"./utils_line.js\"\n\n// TEXTMARKER SPANS\n\nexport function MarkedSpan(marker, from, to) {\n  this.marker = marker\n  this.from = from; this.to = to\n}\n\n// Search an array of spans for a span matching the given marker.\nexport function getMarkedSpanFor(spans, marker) {\n  if (spans) for (let i = 0; i < spans.length; ++i) {\n    let span = spans[i]\n    if (span.marker == marker) return span\n  }\n}\n// Remove a span from an array, returning undefined if no spans are\n// left (we don't store arrays for lines without spans).\nexport function removeMarkedSpan(spans, span) {\n  let r\n  for (let i = 0; i < spans.length; ++i)\n    if (spans[i] != span) (r || (r = [])).push(spans[i])\n  return r\n}\n// Add a span to a line.\nexport function addMarkedSpan(line, span) {\n  line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]\n  span.marker.attachLine(line)\n}\n\n// Used for the algorithm that adjusts markers for a change in the\n// document. These functions cut an array of spans at a given\n// character position, returning an array of remaining chunks (or\n// undefined if nothing remains).\nfunction markedSpansBefore(old, startCh, isInsert) {\n  let nw\n  if (old) for (let i = 0; i < old.length; ++i) {\n    let span = old[i], marker = span.marker\n    let startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)\n    if (startsBefore || span.from == startCh && marker.type == \"bookmark\" && (!isInsert || !span.marker.insertLeft)) {\n      let endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)\n      ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))\n    }\n  }\n  return nw\n}\nfunction markedSpansAfter(old, endCh, isInsert) {\n  let nw\n  if (old) for (let i = 0; i < old.length; ++i) {\n    let span = old[i], marker = span.marker\n    let endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)\n    if (endsAfter || span.from == endCh && marker.type == \"bookmark\" && (!isInsert || span.marker.insertLeft)) {\n      let startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)\n      ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,\n                                            span.to == null ? null : span.to - endCh))\n    }\n  }\n  return nw\n}\n\n// Given a change object, compute the new set of marker spans that\n// cover the line in which the change took place. Removes spans\n// entirely within the change, reconnects spans belonging to the\n// same marker that appear on both sides of the change, and cuts off\n// spans partially within the change. Returns an array of span\n// arrays with one element for each line in (after) the change.\nexport function stretchSpansOverChange(doc, change) {\n  if (change.full) return null\n  let oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans\n  let oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans\n  if (!oldFirst && !oldLast) return null\n\n  let startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0\n  // Get the spans that 'stick out' on both sides\n  let first = markedSpansBefore(oldFirst, startCh, isInsert)\n  let last = markedSpansAfter(oldLast, endCh, isInsert)\n\n  // Next, merge those two ends\n  let sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0)\n  if (first) {\n    // Fix up .to properties of first\n    for (let i = 0; i < first.length; ++i) {\n      let span = first[i]\n      if (span.to == null) {\n        let found = getMarkedSpanFor(last, span.marker)\n        if (!found) span.to = startCh\n        else if (sameLine) span.to = found.to == null ? null : found.to + offset\n      }\n    }\n  }\n  if (last) {\n    // Fix up .from in last (or move them into first in case of sameLine)\n    for (let i = 0; i < last.length; ++i) {\n      let span = last[i]\n      if (span.to != null) span.to += offset\n      if (span.from == null) {\n        let found = getMarkedSpanFor(first, span.marker)\n        if (!found) {\n          span.from = offset\n          if (sameLine) (first || (first = [])).push(span)\n        }\n      } else {\n        span.from += offset\n        if (sameLine) (first || (first = [])).push(span)\n      }\n    }\n  }\n  // Make sure we didn't create any zero-length spans\n  if (first) first = clearEmptySpans(first)\n  if (last && last != first) last = clearEmptySpans(last)\n\n  let newMarkers = [first]\n  if (!sameLine) {\n    // Fill gap with whole-line-spans\n    let gap = change.text.length - 2, gapMarkers\n    if (gap > 0 && first)\n      for (let i = 0; i < first.length; ++i)\n        if (first[i].to == null)\n          (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null))\n    for (let i = 0; i < gap; ++i)\n      newMarkers.push(gapMarkers)\n    newMarkers.push(last)\n  }\n  return newMarkers\n}\n\n// Remove spans that are empty and don't have a clearWhenEmpty\n// option of false.\nfunction clearEmptySpans(spans) {\n  for (let i = 0; i < spans.length; ++i) {\n    let span = spans[i]\n    if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)\n      spans.splice(i--, 1)\n  }\n  if (!spans.length) return null\n  return spans\n}\n\n// Used to 'clip' out readOnly ranges when making a change.\nexport function removeReadOnlyRanges(doc, from, to) {\n  let markers = null\n  doc.iter(from.line, to.line + 1, line => {\n    if (line.markedSpans) for (let i = 0; i < line.markedSpans.length; ++i) {\n      let mark = line.markedSpans[i].marker\n      if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))\n        (markers || (markers = [])).push(mark)\n    }\n  })\n  if (!markers) return null\n  let parts = [{from: from, to: to}]\n  for (let i = 0; i < markers.length; ++i) {\n    let mk = markers[i], m = mk.find(0)\n    for (let j = 0; j < parts.length; ++j) {\n      let p = parts[j]\n      if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue\n      let newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)\n      if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)\n        newParts.push({from: p.from, to: m.from})\n      if (dto > 0 || !mk.inclusiveRight && !dto)\n        newParts.push({from: m.to, to: p.to})\n      parts.splice.apply(parts, newParts)\n      j += newParts.length - 3\n    }\n  }\n  return parts\n}\n\n// Connect or disconnect spans from a line.\nexport function detachMarkedSpans(line) {\n  let spans = line.markedSpans\n  if (!spans) return\n  for (let i = 0; i < spans.length; ++i)\n    spans[i].marker.detachLine(line)\n  line.markedSpans = null\n}\nexport function attachMarkedSpans(line, spans) {\n  if (!spans) return\n  for (let i = 0; i < spans.length; ++i)\n    spans[i].marker.attachLine(line)\n  line.markedSpans = spans\n}\n\n// Helpers used when computing which overlapping collapsed span\n// counts as the larger one.\nfunction extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }\nfunction extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }\n\n// Returns a number indicating which of two overlapping collapsed\n// spans is larger (and thus includes the other). Falls back to\n// comparing ids when the spans cover exactly the same range.\nexport function compareCollapsedMarkers(a, b) {\n  let lenDiff = a.lines.length - b.lines.length\n  if (lenDiff != 0) return lenDiff\n  let aPos = a.find(), bPos = b.find()\n  let fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)\n  if (fromCmp) return -fromCmp\n  let toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)\n  if (toCmp) return toCmp\n  return b.id - a.id\n}\n\n// Find out whether a line ends or starts in a collapsed span. If\n// so, return the marker for that span.\nfunction collapsedSpanAtSide(line, start) {\n  let sps = sawCollapsedSpans && line.markedSpans, found\n  if (sps) for (let sp, i = 0; i < sps.length; ++i) {\n    sp = sps[i]\n    if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&\n        (!found || compareCollapsedMarkers(found, sp.marker) < 0))\n      found = sp.marker\n  }\n  return found\n}\nexport function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }\nexport function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }\n\nexport function collapsedSpanAround(line, ch) {\n  let sps = sawCollapsedSpans && line.markedSpans, found\n  if (sps) for (let i = 0; i < sps.length; ++i) {\n    let sp = sps[i]\n    if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&\n        (!found || compareCollapsedMarkers(found, sp.marker) < 0)) found = sp.marker\n  }\n  return found\n}\n\n// Test whether there exists a collapsed span that partially\n// overlaps (covers the start or end, but not both) of a new span.\n// Such overlap is not allowed.\nexport function conflictingCollapsedRange(doc, lineNo, from, to, marker) {\n  let line = getLine(doc, lineNo)\n  let sps = sawCollapsedSpans && line.markedSpans\n  if (sps) for (let i = 0; i < sps.length; ++i) {\n    let sp = sps[i]\n    if (!sp.marker.collapsed) continue\n    let found = sp.marker.find(0)\n    let fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)\n    let toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)\n    if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue\n    if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||\n        fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))\n      return true\n  }\n}\n\n// A visual line is a line as drawn on the screen. Folding, for\n// example, can cause multiple logical lines to appear on the same\n// visual line. This finds the start of the visual line that the\n// given line is part of (usually that is the line itself).\nexport function visualLine(line) {\n  let merged\n  while (merged = collapsedSpanAtStart(line))\n    line = merged.find(-1, true).line\n  return line\n}\n\nexport function visualLineEnd(line) {\n  let merged\n  while (merged = collapsedSpanAtEnd(line))\n    line = merged.find(1, true).line\n  return line\n}\n\n// Returns an array of logical lines that continue the visual line\n// started by the argument, or undefined if there are no such lines.\nexport function visualLineContinued(line) {\n  let merged, lines\n  while (merged = collapsedSpanAtEnd(line)) {\n    line = merged.find(1, true).line\n    ;(lines || (lines = [])).push(line)\n  }\n  return lines\n}\n\n// Get the line number of the start of the visual line that the\n// given line number is part of.\nexport function visualLineNo(doc, lineN) {\n  let line = getLine(doc, lineN), vis = visualLine(line)\n  if (line == vis) return lineN\n  return lineNo(vis)\n}\n\n// Get the line number of the start of the next visual line after\n// the given line.\nexport function visualLineEndNo(doc, lineN) {\n  if (lineN > doc.lastLine()) return lineN\n  let line = getLine(doc, lineN), merged\n  if (!lineIsHidden(doc, line)) return lineN\n  while (merged = collapsedSpanAtEnd(line))\n    line = merged.find(1, true).line\n  return lineNo(line) + 1\n}\n\n// Compute whether a line is hidden. Lines count as hidden when they\n// are part of a visual line that starts with another line, or when\n// they are entirely covered by collapsed, non-widget span.\nexport function lineIsHidden(doc, line) {\n  let sps = sawCollapsedSpans && line.markedSpans\n  if (sps) for (let sp, i = 0; i < sps.length; ++i) {\n    sp = sps[i]\n    if (!sp.marker.collapsed) continue\n    if (sp.from == null) return true\n    if (sp.marker.widgetNode) continue\n    if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))\n      return true\n  }\n}\nfunction lineIsHiddenInner(doc, line, span) {\n  if (span.to == null) {\n    let end = span.marker.find(1, true)\n    return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))\n  }\n  if (span.marker.inclusiveRight && span.to == line.text.length)\n    return true\n  for (let sp, i = 0; i < line.markedSpans.length; ++i) {\n    sp = line.markedSpans[i]\n    if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&\n        (sp.to == null || sp.to != span.from) &&\n        (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&\n        lineIsHiddenInner(doc, line, sp)) return true\n  }\n}\n\n// Find the height above the given line.\nexport function heightAtLine(lineObj) {\n  lineObj = visualLine(lineObj)\n\n  let h = 0, chunk = lineObj.parent\n  for (let i = 0; i < chunk.lines.length; ++i) {\n    let line = chunk.lines[i]\n    if (line == lineObj) break\n    else h += line.height\n  }\n  for (let p = chunk.parent; p; chunk = p, p = chunk.parent) {\n    for (let i = 0; i < p.children.length; ++i) {\n      let cur = p.children[i]\n      if (cur == chunk) break\n      else h += cur.height\n    }\n  }\n  return h\n}\n\n// Compute the character length of a line, taking into account\n// collapsed ranges (see markText) that might hide parts, and join\n// other lines onto it.\nexport function lineLength(line) {\n  if (line.height == 0) return 0\n  let len = line.text.length, merged, cur = line\n  while (merged = collapsedSpanAtStart(cur)) {\n    let found = merged.find(0, true)\n    cur = found.from.line\n    len += found.from.ch - found.to.ch\n  }\n  cur = line\n  while (merged = collapsedSpanAtEnd(cur)) {\n    let found = merged.find(0, true)\n    len -= cur.text.length - found.from.ch\n    cur = found.to.line\n    len += cur.text.length - found.to.ch\n  }\n  return len\n}\n\n// Find the longest line in the document.\nexport function findMaxLine(cm) {\n  let d = cm.display, doc = cm.doc\n  d.maxLine = getLine(doc, doc.first)\n  d.maxLineLength = lineLength(d.maxLine)\n  d.maxLineChanged = true\n  doc.iter(line => {\n    let len = lineLength(line)\n    if (len > d.maxLineLength) {\n      d.maxLineLength = len\n      d.maxLine = line\n    }\n  })\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/line/utils_line.js",
    "content": "import { indexOf } from \"../util/misc.js\"\n\n// Find the line object corresponding to the given line number.\nexport function getLine(doc, n) {\n  n -= doc.first\n  if (n < 0 || n >= doc.size) throw new Error(\"There is no line \" + (n + doc.first) + \" in the document.\")\n  let chunk = doc\n  while (!chunk.lines) {\n    for (let i = 0;; ++i) {\n      let child = chunk.children[i], sz = child.chunkSize()\n      if (n < sz) { chunk = child; break }\n      n -= sz\n    }\n  }\n  return chunk.lines[n]\n}\n\n// Get the part of a document between two positions, as an array of\n// strings.\nexport function getBetween(doc, start, end) {\n  let out = [], n = start.line\n  doc.iter(start.line, end.line + 1, line => {\n    let text = line.text\n    if (n == end.line) text = text.slice(0, end.ch)\n    if (n == start.line) text = text.slice(start.ch)\n    out.push(text)\n    ++n\n  })\n  return out\n}\n// Get the lines between from and to, as array of strings.\nexport function getLines(doc, from, to) {\n  let out = []\n  doc.iter(from, to, line => { out.push(line.text) }) // iter aborts when callback returns truthy value\n  return out\n}\n\n// Update the height of a line, propagating the height change\n// upwards to parent nodes.\nexport function updateLineHeight(line, height) {\n  let diff = height - line.height\n  if (diff) for (let n = line; n; n = n.parent) n.height += diff\n}\n\n// Given a line object, find its line number by walking up through\n// its parent links.\nexport function lineNo(line) {\n  if (line.parent == null) return null\n  let cur = line.parent, no = indexOf(cur.lines, line)\n  for (let chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {\n    for (let i = 0;; ++i) {\n      if (chunk.children[i] == cur) break\n      no += chunk.children[i].chunkSize()\n    }\n  }\n  return no + cur.first\n}\n\n// Find the line at the given vertical position, using the height\n// information in the document tree.\nexport function lineAtHeight(chunk, h) {\n  let n = chunk.first\n  outer: do {\n    for (let i = 0; i < chunk.children.length; ++i) {\n      let child = chunk.children[i], ch = child.height\n      if (h < ch) { chunk = child; continue outer }\n      h -= ch\n      n += child.chunkSize()\n    }\n    return n\n  } while (!chunk.lines)\n  let i = 0\n  for (; i < chunk.lines.length; ++i) {\n    let line = chunk.lines[i], lh = line.height\n    if (h < lh) break\n    h -= lh\n  }\n  return n + i\n}\n\nexport function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}\n\nexport function lineNumberFor(options, i) {\n  return String(options.lineNumberFormatter(i + options.firstLineNumber))\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/measurement/position_measurement.js",
    "content": "import { buildLineContent, LineView } from \"../line/line_data.js\"\nimport { clipPos, Pos } from \"../line/pos.js\"\nimport { collapsedSpanAround, heightAtLine, lineIsHidden, visualLine } from \"../line/spans.js\"\nimport { getLine, lineAtHeight, lineNo, updateLineHeight } from \"../line/utils_line.js\"\nimport { bidiOther, getBidiPartAt, getOrder } from \"../util/bidi.js\"\nimport { chrome, android, ie, ie_version } from \"../util/browser.js\"\nimport { elt, removeChildren, range, removeChildrenAndAdd } from \"../util/dom.js\"\nimport { e_target } from \"../util/event.js\"\nimport { hasBadZoomedRects } from \"../util/feature_detection.js\"\nimport { countColumn, findFirst, isExtendingChar, scrollerGap, skipExtendingChars } from \"../util/misc.js\"\nimport { updateLineForChanges } from \"../display/update_line.js\"\n\nimport { widgetHeight } from \"./widgets.js\"\n\n// POSITION MEASUREMENT\n\nexport function paddingTop(display) {return display.lineSpace.offsetTop}\nexport function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}\nexport function paddingH(display) {\n  if (display.cachedPaddingH) return display.cachedPaddingH\n  let e = removeChildrenAndAdd(display.measure, elt(\"pre\", \"x\"))\n  let style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle\n  let data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}\n  if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data\n  return data\n}\n\nexport function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }\nexport function displayWidth(cm) {\n  return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth\n}\nexport function displayHeight(cm) {\n  return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight\n}\n\n// Ensure the lineView.wrapping.heights array is populated. This is\n// an array of bottom offsets for the lines that make up a drawn\n// line. When lineWrapping is on, there might be more than one\n// height.\nfunction ensureLineHeights(cm, lineView, rect) {\n  let wrapping = cm.options.lineWrapping\n  let curWidth = wrapping && displayWidth(cm)\n  if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {\n    let heights = lineView.measure.heights = []\n    if (wrapping) {\n      lineView.measure.width = curWidth\n      let rects = lineView.text.firstChild.getClientRects()\n      for (let i = 0; i < rects.length - 1; i++) {\n        let cur = rects[i], next = rects[i + 1]\n        if (Math.abs(cur.bottom - next.bottom) > 2)\n          heights.push((cur.bottom + next.top) / 2 - rect.top)\n      }\n    }\n    heights.push(rect.bottom - rect.top)\n  }\n}\n\n// Find a line map (mapping character offsets to text nodes) and a\n// measurement cache for the given line number. (A line view might\n// contain multiple lines when collapsed ranges are present.)\nexport function mapFromLineView(lineView, line, lineN) {\n  if (lineView.line == line)\n    return {map: lineView.measure.map, cache: lineView.measure.cache}\n  for (let i = 0; i < lineView.rest.length; i++)\n    if (lineView.rest[i] == line)\n      return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}\n  for (let i = 0; i < lineView.rest.length; i++)\n    if (lineNo(lineView.rest[i]) > lineN)\n      return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}\n}\n\n// Render a line into the hidden node display.externalMeasured. Used\n// when measurement is needed for a line that's not in the viewport.\nfunction updateExternalMeasurement(cm, line) {\n  line = visualLine(line)\n  let lineN = lineNo(line)\n  let view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)\n  view.lineN = lineN\n  let built = view.built = buildLineContent(cm, view)\n  view.text = built.pre\n  removeChildrenAndAdd(cm.display.lineMeasure, built.pre)\n  return view\n}\n\n// Get a {top, bottom, left, right} box (in line-local coordinates)\n// for a given character.\nexport function measureChar(cm, line, ch, bias) {\n  return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)\n}\n\n// Find a line view that corresponds to the given line number.\nexport function findViewForLine(cm, lineN) {\n  if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)\n    return cm.display.view[findViewIndex(cm, lineN)]\n  let ext = cm.display.externalMeasured\n  if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)\n    return ext\n}\n\n// Measurement can be split in two steps, the set-up work that\n// applies to the whole line, and the measurement of the actual\n// character. Functions like coordsChar, that need to do a lot of\n// measurements in a row, can thus ensure that the set-up work is\n// only done once.\nexport function prepareMeasureForLine(cm, line) {\n  let lineN = lineNo(line)\n  let view = findViewForLine(cm, lineN)\n  if (view && !view.text) {\n    view = null\n  } else if (view && view.changes) {\n    updateLineForChanges(cm, view, lineN, getDimensions(cm))\n    cm.curOp.forceUpdate = true\n  }\n  if (!view)\n    view = updateExternalMeasurement(cm, line)\n\n  let info = mapFromLineView(view, line, lineN)\n  return {\n    line: line, view: view, rect: null,\n    map: info.map, cache: info.cache, before: info.before,\n    hasHeights: false\n  }\n}\n\n// Given a prepared measurement object, measures the position of an\n// actual character (or fetches it from the cache).\nexport function measureCharPrepared(cm, prepared, ch, bias, varHeight) {\n  if (prepared.before) ch = -1\n  let key = ch + (bias || \"\"), found\n  if (prepared.cache.hasOwnProperty(key)) {\n    found = prepared.cache[key]\n  } else {\n    if (!prepared.rect)\n      prepared.rect = prepared.view.text.getBoundingClientRect()\n    if (!prepared.hasHeights) {\n      ensureLineHeights(cm, prepared.view, prepared.rect)\n      prepared.hasHeights = true\n    }\n    found = measureCharInner(cm, prepared, ch, bias)\n    if (!found.bogus) prepared.cache[key] = found\n  }\n  return {left: found.left, right: found.right,\n          top: varHeight ? found.rtop : found.top,\n          bottom: varHeight ? found.rbottom : found.bottom}\n}\n\nlet nullRect = {left: 0, right: 0, top: 0, bottom: 0}\n\nexport function nodeAndOffsetInLineMap(map, ch, bias) {\n  let node, start, end, collapse, mStart, mEnd\n  // First, search the line map for the text node corresponding to,\n  // or closest to, the target character.\n  for (let i = 0; i < map.length; i += 3) {\n    mStart = map[i]\n    mEnd = map[i + 1]\n    if (ch < mStart) {\n      start = 0; end = 1\n      collapse = \"left\"\n    } else if (ch < mEnd) {\n      start = ch - mStart\n      end = start + 1\n    } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {\n      end = mEnd - mStart\n      start = end - 1\n      if (ch >= mEnd) collapse = \"right\"\n    }\n    if (start != null) {\n      node = map[i + 2]\n      if (mStart == mEnd && bias == (node.insertLeft ? \"left\" : \"right\"))\n        collapse = bias\n      if (bias == \"left\" && start == 0)\n        while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {\n          node = map[(i -= 3) + 2]\n          collapse = \"left\"\n        }\n      if (bias == \"right\" && start == mEnd - mStart)\n        while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {\n          node = map[(i += 3) + 2]\n          collapse = \"right\"\n        }\n      break\n    }\n  }\n  return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}\n}\n\nfunction getUsefulRect(rects, bias) {\n  let rect = nullRect\n  if (bias == \"left\") for (let i = 0; i < rects.length; i++) {\n    if ((rect = rects[i]).left != rect.right) break\n  } else for (let i = rects.length - 1; i >= 0; i--) {\n    if ((rect = rects[i]).left != rect.right) break\n  }\n  return rect\n}\n\nfunction measureCharInner(cm, prepared, ch, bias) {\n  let place = nodeAndOffsetInLineMap(prepared.map, ch, bias)\n  let node = place.node, start = place.start, end = place.end, collapse = place.collapse\n\n  let rect\n  if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.\n    for (let i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned\n      while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start\n      while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end\n      if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)\n        rect = node.parentNode.getBoundingClientRect()\n      else\n        rect = getUsefulRect(range(node, start, end).getClientRects(), bias)\n      if (rect.left || rect.right || start == 0) break\n      end = start\n      start = start - 1\n      collapse = \"right\"\n    }\n    if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect)\n  } else { // If it is a widget, simply get the box for the whole widget.\n    if (start > 0) collapse = bias = \"right\"\n    let rects\n    if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)\n      rect = rects[bias == \"right\" ? rects.length - 1 : 0]\n    else\n      rect = node.getBoundingClientRect()\n  }\n  if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {\n    let rSpan = node.parentNode.getClientRects()[0]\n    if (rSpan)\n      rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}\n    else\n      rect = nullRect\n  }\n\n  let rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top\n  let mid = (rtop + rbot) / 2\n  let heights = prepared.view.measure.heights\n  let i = 0\n  for (; i < heights.length - 1; i++)\n    if (mid < heights[i]) break\n  let top = i ? heights[i - 1] : 0, bot = heights[i]\n  let result = {left: (collapse == \"right\" ? rect.right : rect.left) - prepared.rect.left,\n                right: (collapse == \"left\" ? rect.left : rect.right) - prepared.rect.left,\n                top: top, bottom: bot}\n  if (!rect.left && !rect.right) result.bogus = true\n  if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }\n\n  return result\n}\n\n// Work around problem with bounding client rects on ranges being\n// returned incorrectly when zoomed on IE10 and below.\nfunction maybeUpdateRectForZooming(measure, rect) {\n  if (!window.screen || screen.logicalXDPI == null ||\n      screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))\n    return rect\n  let scaleX = screen.logicalXDPI / screen.deviceXDPI\n  let scaleY = screen.logicalYDPI / screen.deviceYDPI\n  return {left: rect.left * scaleX, right: rect.right * scaleX,\n          top: rect.top * scaleY, bottom: rect.bottom * scaleY}\n}\n\nexport function clearLineMeasurementCacheFor(lineView) {\n  if (lineView.measure) {\n    lineView.measure.cache = {}\n    lineView.measure.heights = null\n    if (lineView.rest) for (let i = 0; i < lineView.rest.length; i++)\n      lineView.measure.caches[i] = {}\n  }\n}\n\nexport function clearLineMeasurementCache(cm) {\n  cm.display.externalMeasure = null\n  removeChildren(cm.display.lineMeasure)\n  for (let i = 0; i < cm.display.view.length; i++)\n    clearLineMeasurementCacheFor(cm.display.view[i])\n}\n\nexport function clearCaches(cm) {\n  clearLineMeasurementCache(cm)\n  cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null\n  if (!cm.options.lineWrapping) cm.display.maxLineChanged = true\n  cm.display.lineNumChars = null\n}\n\nfunction pageScrollX() {\n  // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206\n  // which causes page_Offset and bounding client rects to use\n  // different reference viewports and invalidate our calculations.\n  if (chrome && android) return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft))\n  return window.pageXOffset || (document.documentElement || document.body).scrollLeft\n}\nfunction pageScrollY() {\n  if (chrome && android) return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop))\n  return window.pageYOffset || (document.documentElement || document.body).scrollTop\n}\n\nfunction widgetTopHeight(lineObj) {\n  let height = 0\n  if (lineObj.widgets) for (let i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above)\n    height += widgetHeight(lineObj.widgets[i])\n  return height\n}\n\n// Converts a {top, bottom, left, right} box from line-local\n// coordinates into another coordinate system. Context may be one of\n// \"line\", \"div\" (display.lineDiv), \"local\"./null (editor), \"window\",\n// or \"page\".\nexport function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {\n  if (!includeWidgets) {\n    let height = widgetTopHeight(lineObj)\n    rect.top += height; rect.bottom += height\n  }\n  if (context == \"line\") return rect\n  if (!context) context = \"local\"\n  let yOff = heightAtLine(lineObj)\n  if (context == \"local\") yOff += paddingTop(cm.display)\n  else yOff -= cm.display.viewOffset\n  if (context == \"page\" || context == \"window\") {\n    let lOff = cm.display.lineSpace.getBoundingClientRect()\n    yOff += lOff.top + (context == \"window\" ? 0 : pageScrollY())\n    let xOff = lOff.left + (context == \"window\" ? 0 : pageScrollX())\n    rect.left += xOff; rect.right += xOff\n  }\n  rect.top += yOff; rect.bottom += yOff\n  return rect\n}\n\n// Coverts a box from \"div\" coords to another coordinate system.\n// Context may be \"window\", \"page\", \"div\", or \"local\"./null.\nexport function fromCoordSystem(cm, coords, context) {\n  if (context == \"div\") return coords\n  let left = coords.left, top = coords.top\n  // First move into \"page\" coordinate system\n  if (context == \"page\") {\n    left -= pageScrollX()\n    top -= pageScrollY()\n  } else if (context == \"local\" || !context) {\n    let localBox = cm.display.sizer.getBoundingClientRect()\n    left += localBox.left\n    top += localBox.top\n  }\n\n  let lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()\n  return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}\n}\n\nexport function charCoords(cm, pos, context, lineObj, bias) {\n  if (!lineObj) lineObj = getLine(cm.doc, pos.line)\n  return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)\n}\n\n// Returns a box for a given cursor position, which may have an\n// 'other' property containing the position of the secondary cursor\n// on a bidi boundary.\n// A cursor Pos(line, char, \"before\") is on the same visual line as `char - 1`\n// and after `char - 1` in writing order of `char - 1`\n// A cursor Pos(line, char, \"after\") is on the same visual line as `char`\n// and before `char` in writing order of `char`\n// Examples (upper-case letters are RTL, lower-case are LTR):\n//     Pos(0, 1, ...)\n//     before   after\n// ab     a|b     a|b\n// aB     a|B     aB|\n// Ab     |Ab     A|b\n// AB     B|A     B|A\n// Every position after the last character on a line is considered to stick\n// to the last character on the line.\nexport function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {\n  lineObj = lineObj || getLine(cm.doc, pos.line)\n  if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj)\n  function get(ch, right) {\n    let m = measureCharPrepared(cm, preparedMeasure, ch, right ? \"right\" : \"left\", varHeight)\n    if (right) m.left = m.right; else m.right = m.left\n    return intoCoordSystem(cm, lineObj, m, context)\n  }\n  let order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky\n  if (ch >= lineObj.text.length) {\n    ch = lineObj.text.length\n    sticky = \"before\"\n  } else if (ch <= 0) {\n    ch = 0\n    sticky = \"after\"\n  }\n  if (!order) return get(sticky == \"before\" ? ch - 1 : ch, sticky == \"before\")\n\n  function getBidi(ch, partPos, invert) {\n    let part = order[partPos], right = part.level == 1\n    return get(invert ? ch - 1 : ch, right != invert)\n  }\n  let partPos = getBidiPartAt(order, ch, sticky)\n  let other = bidiOther\n  let val = getBidi(ch, partPos, sticky == \"before\")\n  if (other != null) val.other = getBidi(ch, other, sticky != \"before\")\n  return val\n}\n\n// Used to cheaply estimate the coordinates for a position. Used for\n// intermediate scroll updates.\nexport function estimateCoords(cm, pos) {\n  let left = 0\n  pos = clipPos(cm.doc, pos)\n  if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch\n  let lineObj = getLine(cm.doc, pos.line)\n  let top = heightAtLine(lineObj) + paddingTop(cm.display)\n  return {left: left, right: left, top: top, bottom: top + lineObj.height}\n}\n\n// Positions returned by coordsChar contain some extra information.\n// xRel is the relative x position of the input coordinates compared\n// to the found position (so xRel > 0 means the coordinates are to\n// the right of the character position, for example). When outside\n// is true, that means the coordinates lie outside the line's\n// vertical range.\nfunction PosWithInfo(line, ch, sticky, outside, xRel) {\n  let pos = Pos(line, ch, sticky)\n  pos.xRel = xRel\n  if (outside) pos.outside = true\n  return pos\n}\n\n// Compute the character position closest to the given coordinates.\n// Input must be lineSpace-local (\"div\" coordinate system).\nexport function coordsChar(cm, x, y) {\n  let doc = cm.doc\n  y += cm.display.viewOffset\n  if (y < 0) return PosWithInfo(doc.first, 0, null, true, -1)\n  let lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1\n  if (lineN > last)\n    return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1)\n  if (x < 0) x = 0\n\n  let lineObj = getLine(doc, lineN)\n  for (;;) {\n    let found = coordsCharInner(cm, lineObj, lineN, x, y)\n    let collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0))\n    if (!collapsed) return found\n    let rangeEnd = collapsed.find(1)\n    if (rangeEnd.line == lineN) return rangeEnd\n    lineObj = getLine(doc, lineN = rangeEnd.line)\n  }\n}\n\nfunction wrappedLineExtent(cm, lineObj, preparedMeasure, y) {\n  y -= widgetTopHeight(lineObj)\n  let end = lineObj.text.length\n  let begin = findFirst(ch => measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y, end, 0)\n  end = findFirst(ch => measureCharPrepared(cm, preparedMeasure, ch).top > y, begin, end)\n  return {begin, end}\n}\n\nexport function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {\n  if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj)\n  let targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), \"line\").top\n  return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)\n}\n\n// Returns true if the given side of a box is after the given\n// coordinates, in top-to-bottom, left-to-right order.\nfunction boxIsAfter(box, x, y, left) {\n  return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x\n}\n\nfunction coordsCharInner(cm, lineObj, lineNo, x, y) {\n  // Move y into line-local coordinate space\n  y -= heightAtLine(lineObj)\n  let preparedMeasure = prepareMeasureForLine(cm, lineObj)\n  // When directly calling `measureCharPrepared`, we have to adjust\n  // for the widgets at this line.\n  let widgetHeight = widgetTopHeight(lineObj)\n  let begin = 0, end = lineObj.text.length, ltr = true\n\n  let order = getOrder(lineObj, cm.doc.direction)\n  // If the line isn't plain left-to-right text, first figure out\n  // which bidi section the coordinates fall into.\n  if (order) {\n    let part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)\n                 (cm, lineObj, lineNo, preparedMeasure, order, x, y)\n    ltr = part.level != 1\n    // The awkward -1 offsets are needed because findFirst (called\n    // on these below) will treat its first bound as inclusive,\n    // second as exclusive, but we want to actually address the\n    // characters in the part's range\n    begin = ltr ? part.from : part.to - 1\n    end = ltr ? part.to : part.from - 1\n  }\n\n  // A binary search to find the first character whose bounding box\n  // starts after the coordinates. If we run across any whose box wrap\n  // the coordinates, store that.\n  let chAround = null, boxAround = null\n  let ch = findFirst(ch => {\n    let box = measureCharPrepared(cm, preparedMeasure, ch)\n    box.top += widgetHeight; box.bottom += widgetHeight\n    if (!boxIsAfter(box, x, y, false)) return false\n    if (box.top <= y && box.left <= x) {\n      chAround = ch\n      boxAround = box\n    }\n    return true\n  }, begin, end)\n\n  let baseX, sticky, outside = false\n  // If a box around the coordinates was found, use that\n  if (boxAround) {\n    // Distinguish coordinates nearer to the left or right side of the box\n    let atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr\n    ch = chAround + (atStart ? 0 : 1)\n    sticky = atStart ? \"after\" : \"before\"\n    baseX = atLeft ? boxAround.left : boxAround.right\n  } else {\n    // (Adjust for extended bound, if necessary.)\n    if (!ltr && (ch == end || ch == begin)) ch++\n    // To determine which side to associate with, get the box to the\n    // left of the character and compare it's vertical position to the\n    // coordinates\n    sticky = ch == 0 ? \"after\" : ch == lineObj.text.length ? \"before\" :\n      (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?\n      \"after\" : \"before\"\n    // Now get accurate coordinates for this place, in order to get a\n    // base X position\n    let coords = cursorCoords(cm, Pos(lineNo, ch, sticky), \"line\", lineObj, preparedMeasure)\n    baseX = coords.left\n    outside = y < coords.top || y >= coords.bottom\n  }\n\n  ch = skipExtendingChars(lineObj.text, ch, 1)\n  return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)\n}\n\nfunction coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {\n  // Bidi parts are sorted left-to-right, and in a non-line-wrapping\n  // situation, we can take this ordering to correspond to the visual\n  // ordering. This finds the first part whose end is after the given\n  // coordinates.\n  let index = findFirst(i => {\n    let part = order[i], ltr = part.level != 1\n    return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? \"before\" : \"after\"),\n                                   \"line\", lineObj, preparedMeasure), x, y, true)\n  }, 0, order.length - 1)\n  let part = order[index]\n  // If this isn't the first part, the part's start is also after\n  // the coordinates, and the coordinates aren't on the same line as\n  // that start, move one part back.\n  if (index > 0) {\n    let ltr = part.level != 1\n    let start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? \"after\" : \"before\"),\n                             \"line\", lineObj, preparedMeasure)\n    if (boxIsAfter(start, x, y, true) && start.top > y)\n      part = order[index - 1]\n  }\n  return part\n}\n\nfunction coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {\n  // In a wrapped line, rtl text on wrapping boundaries can do things\n  // that don't correspond to the ordering in our `order` array at\n  // all, so a binary search doesn't work, and we want to return a\n  // part that only spans one line so that the binary search in\n  // coordsCharInner is safe. As such, we first find the extent of the\n  // wrapped line, and then do a flat search in which we discard any\n  // spans that aren't on the line.\n  let {begin, end} = wrappedLineExtent(cm, lineObj, preparedMeasure, y)\n  if (/\\s/.test(lineObj.text.charAt(end - 1))) end--\n  let part = null, closestDist = null\n  for (let i = 0; i < order.length; i++) {\n    let p = order[i]\n    if (p.from >= end || p.to <= begin) continue\n    let ltr = p.level != 1\n    let endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right\n    // Weigh against spans ending before this, so that they are only\n    // picked if nothing ends after\n    let dist = endX < x ? x - endX + 1e9 : endX - x\n    if (!part || closestDist > dist) {\n      part = p\n      closestDist = dist\n    }\n  }\n  if (!part) part = order[order.length - 1]\n  // Clip the part to the wrapped line.\n  if (part.from < begin) part = {from: begin, to: part.to, level: part.level}\n  if (part.to > end) part = {from: part.from, to: end, level: part.level}\n  return part\n}\n\nlet measureText\n// Compute the default text height.\nexport function textHeight(display) {\n  if (display.cachedTextHeight != null) return display.cachedTextHeight\n  if (measureText == null) {\n    measureText = elt(\"pre\")\n    // Measure a bunch of lines, for browsers that compute\n    // fractional heights.\n    for (let i = 0; i < 49; ++i) {\n      measureText.appendChild(document.createTextNode(\"x\"))\n      measureText.appendChild(elt(\"br\"))\n    }\n    measureText.appendChild(document.createTextNode(\"x\"))\n  }\n  removeChildrenAndAdd(display.measure, measureText)\n  let height = measureText.offsetHeight / 50\n  if (height > 3) display.cachedTextHeight = height\n  removeChildren(display.measure)\n  return height || 1\n}\n\n// Compute the default character width.\nexport function charWidth(display) {\n  if (display.cachedCharWidth != null) return display.cachedCharWidth\n  let anchor = elt(\"span\", \"xxxxxxxxxx\")\n  let pre = elt(\"pre\", [anchor])\n  removeChildrenAndAdd(display.measure, pre)\n  let rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10\n  if (width > 2) display.cachedCharWidth = width\n  return width || 10\n}\n\n// Do a bulk-read of the DOM positions and sizes needed to draw the\n// view, so that we don't interleave reading and writing to the DOM.\nexport function getDimensions(cm) {\n  let d = cm.display, left = {}, width = {}\n  let gutterLeft = d.gutters.clientLeft\n  for (let n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {\n    left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft\n    width[cm.options.gutters[i]] = n.clientWidth\n  }\n  return {fixedPos: compensateForHScroll(d),\n          gutterTotalWidth: d.gutters.offsetWidth,\n          gutterLeft: left,\n          gutterWidth: width,\n          wrapperWidth: d.wrapper.clientWidth}\n}\n\n// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,\n// but using getBoundingClientRect to get a sub-pixel-accurate\n// result.\nexport function compensateForHScroll(display) {\n  return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left\n}\n\n// Returns a function that estimates the height of a line, to use as\n// first approximation until the line becomes visible (and is thus\n// properly measurable).\nexport function estimateHeight(cm) {\n  let th = textHeight(cm.display), wrapping = cm.options.lineWrapping\n  let perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)\n  return line => {\n    if (lineIsHidden(cm.doc, line)) return 0\n\n    let widgetsHeight = 0\n    if (line.widgets) for (let i = 0; i < line.widgets.length; i++) {\n      if (line.widgets[i].height) widgetsHeight += line.widgets[i].height\n    }\n\n    if (wrapping)\n      return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th\n    else\n      return widgetsHeight + th\n  }\n}\n\nexport function estimateLineHeights(cm) {\n  let doc = cm.doc, est = estimateHeight(cm)\n  doc.iter(line => {\n    let estHeight = est(line)\n    if (estHeight != line.height) updateLineHeight(line, estHeight)\n  })\n}\n\n// Given a mouse event, find the corresponding position. If liberal\n// is false, it checks whether a gutter or scrollbar was clicked,\n// and returns null if it was. forRect is used by rectangular\n// selections, and tries to estimate a character position even for\n// coordinates beyond the right of the text.\nexport function posFromMouse(cm, e, liberal, forRect) {\n  let display = cm.display\n  if (!liberal && e_target(e).getAttribute(\"cm-not-content\") == \"true\") return null\n\n  let x, y, space = display.lineSpace.getBoundingClientRect()\n  // Fails unpredictably on IE[67] when mouse is dragged around quickly.\n  try { x = e.clientX - space.left; y = e.clientY - space.top }\n  catch (e) { return null }\n  let coords = coordsChar(cm, x, y), line\n  if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {\n    let colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length\n    coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))\n  }\n  return coords\n}\n\n// Find the view element corresponding to a given line. Return null\n// when the line isn't visible.\nexport function findViewIndex(cm, n) {\n  if (n >= cm.display.viewTo) return null\n  n -= cm.display.viewFrom\n  if (n < 0) return null\n  let view = cm.display.view\n  for (let i = 0; i < view.length; i++) {\n    n -= view[i].size\n    if (n < 0) return i\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/measurement/widgets.js",
    "content": "import { contains, elt, removeChildrenAndAdd } from \"../util/dom.js\"\nimport { e_target } from \"../util/event.js\"\n\nexport function widgetHeight(widget) {\n  if (widget.height != null) return widget.height\n  let cm = widget.doc.cm\n  if (!cm) return 0\n  if (!contains(document.body, widget.node)) {\n    let parentStyle = \"position: relative;\"\n    if (widget.coverGutter)\n      parentStyle += \"margin-left: -\" + cm.display.gutters.offsetWidth + \"px;\"\n    if (widget.noHScroll)\n      parentStyle += \"width: \" + cm.display.wrapper.clientWidth + \"px;\"\n    removeChildrenAndAdd(cm.display.measure, elt(\"div\", [widget.node], null, parentStyle))\n  }\n  return widget.height = widget.node.parentNode.offsetHeight\n}\n\n// Return true when the given mouse event happened in a widget\nexport function eventInWidget(display, e) {\n  for (let n = e_target(e); n != display.wrapper; n = n.parentNode) {\n    if (!n || (n.nodeType == 1 && n.getAttribute(\"cm-ignore-events\") == \"true\") ||\n        (n.parentNode == display.sizer && n != display.mover))\n      return true\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/Doc.js",
    "content": "import CodeMirror from \"../edit/CodeMirror.js\"\nimport { docMethodOp } from \"../display/operations.js\"\nimport { Line } from \"../line/line_data.js\"\nimport { clipPos, clipPosArray, Pos } from \"../line/pos.js\"\nimport { visualLine } from \"../line/spans.js\"\nimport { getBetween, getLine, getLines, isLine, lineNo } from \"../line/utils_line.js\"\nimport { classTest } from \"../util/dom.js\"\nimport { splitLinesAuto } from \"../util/feature_detection.js\"\nimport { createObj, map, isEmpty, sel_dontScroll } from \"../util/misc.js\"\nimport { ensureCursorVisible, scrollToCoords } from \"../display/scrolling.js\"\n\nimport { changeLine, makeChange, makeChangeFromHistory, replaceRange } from \"./changes.js\"\nimport { computeReplacedSel } from \"./change_measurement.js\"\nimport { BranchChunk, LeafChunk } from \"./chunk.js\"\nimport { directionChanged, linkedDocs, updateDoc } from \"./document_data.js\"\nimport { copyHistoryArray, History } from \"./history.js\"\nimport { addLineWidget } from \"./line_widget.js\"\nimport { copySharedMarkers, detachSharedMarkers, findSharedMarkers, markText } from \"./mark_text.js\"\nimport { normalizeSelection, Range, simpleSelection } from \"./selection.js\"\nimport { extendSelection, extendSelections, setSelection, setSelectionReplaceHistory, setSimpleSelection } from \"./selection_updates.js\"\n\nlet nextDocId = 0\nlet Doc = function(text, mode, firstLine, lineSep, direction) {\n  if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep, direction)\n  if (firstLine == null) firstLine = 0\n\n  BranchChunk.call(this, [new LeafChunk([new Line(\"\", null)])])\n  this.first = firstLine\n  this.scrollTop = this.scrollLeft = 0\n  this.cantEdit = false\n  this.cleanGeneration = 1\n  this.modeFrontier = this.highlightFrontier = firstLine\n  let start = Pos(firstLine, 0)\n  this.sel = simpleSelection(start)\n  this.history = new History(null)\n  this.id = ++nextDocId\n  this.modeOption = mode\n  this.lineSep = lineSep\n  this.direction = (direction == \"rtl\") ? \"rtl\" : \"ltr\"\n  this.extend = false\n\n  if (typeof text == \"string\") text = this.splitLines(text)\n  updateDoc(this, {from: start, to: start, text: text})\n  setSelection(this, simpleSelection(start), sel_dontScroll)\n}\n\nDoc.prototype = createObj(BranchChunk.prototype, {\n  constructor: Doc,\n  // Iterate over the document. Supports two forms -- with only one\n  // argument, it calls that for each line in the document. With\n  // three, it iterates over the range given by the first two (with\n  // the second being non-inclusive).\n  iter: function(from, to, op) {\n    if (op) this.iterN(from - this.first, to - from, op)\n    else this.iterN(this.first, this.first + this.size, from)\n  },\n\n  // Non-public interface for adding and removing lines.\n  insert: function(at, lines) {\n    let height = 0\n    for (let i = 0; i < lines.length; ++i) height += lines[i].height\n    this.insertInner(at - this.first, lines, height)\n  },\n  remove: function(at, n) { this.removeInner(at - this.first, n) },\n\n  // From here, the methods are part of the public interface. Most\n  // are also available from CodeMirror (editor) instances.\n\n  getValue: function(lineSep) {\n    let lines = getLines(this, this.first, this.first + this.size)\n    if (lineSep === false) return lines\n    return lines.join(lineSep || this.lineSeparator())\n  },\n  setValue: docMethodOp(function(code) {\n    let top = Pos(this.first, 0), last = this.first + this.size - 1\n    makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),\n                      text: this.splitLines(code), origin: \"setValue\", full: true}, true)\n    if (this.cm) scrollToCoords(this.cm, 0, 0)\n    setSelection(this, simpleSelection(top), sel_dontScroll)\n  }),\n  replaceRange: function(code, from, to, origin) {\n    from = clipPos(this, from)\n    to = to ? clipPos(this, to) : from\n    replaceRange(this, code, from, to, origin)\n  },\n  getRange: function(from, to, lineSep) {\n    let lines = getBetween(this, clipPos(this, from), clipPos(this, to))\n    if (lineSep === false) return lines\n    return lines.join(lineSep || this.lineSeparator())\n  },\n\n  getLine: function(line) {let l = this.getLineHandle(line); return l && l.text},\n\n  getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line)},\n  getLineNumber: function(line) {return lineNo(line)},\n\n  getLineHandleVisualStart: function(line) {\n    if (typeof line == \"number\") line = getLine(this, line)\n    return visualLine(line)\n  },\n\n  lineCount: function() {return this.size},\n  firstLine: function() {return this.first},\n  lastLine: function() {return this.first + this.size - 1},\n\n  clipPos: function(pos) {return clipPos(this, pos)},\n\n  getCursor: function(start) {\n    let range = this.sel.primary(), pos\n    if (start == null || start == \"head\") pos = range.head\n    else if (start == \"anchor\") pos = range.anchor\n    else if (start == \"end\" || start == \"to\" || start === false) pos = range.to()\n    else pos = range.from()\n    return pos\n  },\n  listSelections: function() { return this.sel.ranges },\n  somethingSelected: function() {return this.sel.somethingSelected()},\n\n  setCursor: docMethodOp(function(line, ch, options) {\n    setSimpleSelection(this, clipPos(this, typeof line == \"number\" ? Pos(line, ch || 0) : line), null, options)\n  }),\n  setSelection: docMethodOp(function(anchor, head, options) {\n    setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)\n  }),\n  extendSelection: docMethodOp(function(head, other, options) {\n    extendSelection(this, clipPos(this, head), other && clipPos(this, other), options)\n  }),\n  extendSelections: docMethodOp(function(heads, options) {\n    extendSelections(this, clipPosArray(this, heads), options)\n  }),\n  extendSelectionsBy: docMethodOp(function(f, options) {\n    let heads = map(this.sel.ranges, f)\n    extendSelections(this, clipPosArray(this, heads), options)\n  }),\n  setSelections: docMethodOp(function(ranges, primary, options) {\n    if (!ranges.length) return\n    let out = []\n    for (let i = 0; i < ranges.length; i++)\n      out[i] = new Range(clipPos(this, ranges[i].anchor),\n                         clipPos(this, ranges[i].head))\n    if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex)\n    setSelection(this, normalizeSelection(this.cm, out, primary), options)\n  }),\n  addSelection: docMethodOp(function(anchor, head, options) {\n    let ranges = this.sel.ranges.slice(0)\n    ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))\n    setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options)\n  }),\n\n  getSelection: function(lineSep) {\n    let ranges = this.sel.ranges, lines\n    for (let i = 0; i < ranges.length; i++) {\n      let sel = getBetween(this, ranges[i].from(), ranges[i].to())\n      lines = lines ? lines.concat(sel) : sel\n    }\n    if (lineSep === false) return lines\n    else return lines.join(lineSep || this.lineSeparator())\n  },\n  getSelections: function(lineSep) {\n    let parts = [], ranges = this.sel.ranges\n    for (let i = 0; i < ranges.length; i++) {\n      let sel = getBetween(this, ranges[i].from(), ranges[i].to())\n      if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator())\n      parts[i] = sel\n    }\n    return parts\n  },\n  replaceSelection: function(code, collapse, origin) {\n    let dup = []\n    for (let i = 0; i < this.sel.ranges.length; i++)\n      dup[i] = code\n    this.replaceSelections(dup, collapse, origin || \"+input\")\n  },\n  replaceSelections: docMethodOp(function(code, collapse, origin) {\n    let changes = [], sel = this.sel\n    for (let i = 0; i < sel.ranges.length; i++) {\n      let range = sel.ranges[i]\n      changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin}\n    }\n    let newSel = collapse && collapse != \"end\" && computeReplacedSel(this, changes, collapse)\n    for (let i = changes.length - 1; i >= 0; i--)\n      makeChange(this, changes[i])\n    if (newSel) setSelectionReplaceHistory(this, newSel)\n    else if (this.cm) ensureCursorVisible(this.cm)\n  }),\n  undo: docMethodOp(function() {makeChangeFromHistory(this, \"undo\")}),\n  redo: docMethodOp(function() {makeChangeFromHistory(this, \"redo\")}),\n  undoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"undo\", true)}),\n  redoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"redo\", true)}),\n\n  setExtending: function(val) {this.extend = val},\n  getExtending: function() {return this.extend},\n\n  historySize: function() {\n    let hist = this.history, done = 0, undone = 0\n    for (let i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done\n    for (let i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone\n    return {undo: done, redo: undone}\n  },\n  clearHistory: function() {this.history = new History(this.history.maxGeneration)},\n\n  markClean: function() {\n    this.cleanGeneration = this.changeGeneration(true)\n  },\n  changeGeneration: function(forceSplit) {\n    if (forceSplit)\n      this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null\n    return this.history.generation\n  },\n  isClean: function (gen) {\n    return this.history.generation == (gen || this.cleanGeneration)\n  },\n\n  getHistory: function() {\n    return {done: copyHistoryArray(this.history.done),\n            undone: copyHistoryArray(this.history.undone)}\n  },\n  setHistory: function(histData) {\n    let hist = this.history = new History(this.history.maxGeneration)\n    hist.done = copyHistoryArray(histData.done.slice(0), null, true)\n    hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)\n  },\n\n  setGutterMarker: docMethodOp(function(line, gutterID, value) {\n    return changeLine(this, line, \"gutter\", line => {\n      let markers = line.gutterMarkers || (line.gutterMarkers = {})\n      markers[gutterID] = value\n      if (!value && isEmpty(markers)) line.gutterMarkers = null\n      return true\n    })\n  }),\n\n  clearGutter: docMethodOp(function(gutterID) {\n    this.iter(line => {\n      if (line.gutterMarkers && line.gutterMarkers[gutterID]) {\n        changeLine(this, line, \"gutter\", () => {\n          line.gutterMarkers[gutterID] = null\n          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null\n          return true\n        })\n      }\n    })\n  }),\n\n  lineInfo: function(line) {\n    let n\n    if (typeof line == \"number\") {\n      if (!isLine(this, line)) return null\n      n = line\n      line = getLine(this, line)\n      if (!line) return null\n    } else {\n      n = lineNo(line)\n      if (n == null) return null\n    }\n    return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,\n            textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,\n            widgets: line.widgets}\n  },\n\n  addLineClass: docMethodOp(function(handle, where, cls) {\n    return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", line => {\n      let prop = where == \"text\" ? \"textClass\"\n               : where == \"background\" ? \"bgClass\"\n               : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\"\n      if (!line[prop]) line[prop] = cls\n      else if (classTest(cls).test(line[prop])) return false\n      else line[prop] += \" \" + cls\n      return true\n    })\n  }),\n  removeLineClass: docMethodOp(function(handle, where, cls) {\n    return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", line => {\n      let prop = where == \"text\" ? \"textClass\"\n               : where == \"background\" ? \"bgClass\"\n               : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\"\n      let cur = line[prop]\n      if (!cur) return false\n      else if (cls == null) line[prop] = null\n      else {\n        let found = cur.match(classTest(cls))\n        if (!found) return false\n        let end = found.index + found[0].length\n        line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? \"\" : \" \") + cur.slice(end) || null\n      }\n      return true\n    })\n  }),\n\n  addLineWidget: docMethodOp(function(handle, node, options) {\n    return addLineWidget(this, handle, node, options)\n  }),\n  removeLineWidget: function(widget) { widget.clear() },\n\n  markText: function(from, to, options) {\n    return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || \"range\")\n  },\n  setBookmark: function(pos, options) {\n    let realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),\n                    insertLeft: options && options.insertLeft,\n                    clearWhenEmpty: false, shared: options && options.shared,\n                    handleMouseEvents: options && options.handleMouseEvents}\n    pos = clipPos(this, pos)\n    return markText(this, pos, pos, realOpts, \"bookmark\")\n  },\n  findMarksAt: function(pos) {\n    pos = clipPos(this, pos)\n    let markers = [], spans = getLine(this, pos.line).markedSpans\n    if (spans) for (let i = 0; i < spans.length; ++i) {\n      let span = spans[i]\n      if ((span.from == null || span.from <= pos.ch) &&\n          (span.to == null || span.to >= pos.ch))\n        markers.push(span.marker.parent || span.marker)\n    }\n    return markers\n  },\n  findMarks: function(from, to, filter) {\n    from = clipPos(this, from); to = clipPos(this, to)\n    let found = [], lineNo = from.line\n    this.iter(from.line, to.line + 1, line => {\n      let spans = line.markedSpans\n      if (spans) for (let i = 0; i < spans.length; i++) {\n        let span = spans[i]\n        if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||\n              span.from == null && lineNo != from.line ||\n              span.from != null && lineNo == to.line && span.from >= to.ch) &&\n            (!filter || filter(span.marker)))\n          found.push(span.marker.parent || span.marker)\n      }\n      ++lineNo\n    })\n    return found\n  },\n  getAllMarks: function() {\n    let markers = []\n    this.iter(line => {\n      let sps = line.markedSpans\n      if (sps) for (let i = 0; i < sps.length; ++i)\n        if (sps[i].from != null) markers.push(sps[i].marker)\n    })\n    return markers\n  },\n\n  posFromIndex: function(off) {\n    let ch, lineNo = this.first, sepSize = this.lineSeparator().length\n    this.iter(line => {\n      let sz = line.text.length + sepSize\n      if (sz > off) { ch = off; return true }\n      off -= sz\n      ++lineNo\n    })\n    return clipPos(this, Pos(lineNo, ch))\n  },\n  indexFromPos: function (coords) {\n    coords = clipPos(this, coords)\n    let index = coords.ch\n    if (coords.line < this.first || coords.ch < 0) return 0\n    let sepSize = this.lineSeparator().length\n    this.iter(this.first, coords.line, line => { // iter aborts when callback returns a truthy value\n      index += line.text.length + sepSize\n    })\n    return index\n  },\n\n  copy: function(copyHistory) {\n    let doc = new Doc(getLines(this, this.first, this.first + this.size),\n                      this.modeOption, this.first, this.lineSep, this.direction)\n    doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft\n    doc.sel = this.sel\n    doc.extend = false\n    if (copyHistory) {\n      doc.history.undoDepth = this.history.undoDepth\n      doc.setHistory(this.getHistory())\n    }\n    return doc\n  },\n\n  linkedDoc: function(options) {\n    if (!options) options = {}\n    let from = this.first, to = this.first + this.size\n    if (options.from != null && options.from > from) from = options.from\n    if (options.to != null && options.to < to) to = options.to\n    let copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction)\n    if (options.sharedHist) copy.history = this.history\n    ;(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})\n    copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]\n    copySharedMarkers(copy, findSharedMarkers(this))\n    return copy\n  },\n  unlinkDoc: function(other) {\n    if (other instanceof CodeMirror) other = other.doc\n    if (this.linked) for (let i = 0; i < this.linked.length; ++i) {\n      let link = this.linked[i]\n      if (link.doc != other) continue\n      this.linked.splice(i, 1)\n      other.unlinkDoc(this)\n      detachSharedMarkers(findSharedMarkers(this))\n      break\n    }\n    // If the histories were shared, split them again\n    if (other.history == this.history) {\n      let splitIds = [other.id]\n      linkedDocs(other, doc => splitIds.push(doc.id), true)\n      other.history = new History(null)\n      other.history.done = copyHistoryArray(this.history.done, splitIds)\n      other.history.undone = copyHistoryArray(this.history.undone, splitIds)\n    }\n  },\n  iterLinkedDocs: function(f) {linkedDocs(this, f)},\n\n  getMode: function() {return this.mode},\n  getEditor: function() {return this.cm},\n\n  splitLines: function(str) {\n    if (this.lineSep) return str.split(this.lineSep)\n    return splitLinesAuto(str)\n  },\n  lineSeparator: function() { return this.lineSep || \"\\n\" },\n\n  setDirection: docMethodOp(function (dir) {\n    if (dir != \"rtl\") dir = \"ltr\"\n    if (dir == this.direction) return\n    this.direction = dir\n    this.iter(line => line.order = null)\n    if (this.cm) directionChanged(this.cm)\n  })\n})\n\n// Public alias.\nDoc.prototype.eachLine = Doc.prototype.iter\n\nexport default Doc\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/change_measurement.js",
    "content": "import { cmp, Pos } from \"../line/pos.js\"\nimport { lst } from \"../util/misc.js\"\n\nimport { normalizeSelection, Range, Selection } from \"./selection.js\"\n\n// Compute the position of the end of a change (its 'to' property\n// refers to the pre-change end).\nexport function changeEnd(change) {\n  if (!change.text) return change.to\n  return Pos(change.from.line + change.text.length - 1,\n             lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))\n}\n\n// Adjust a position to refer to the post-change position of the\n// same text, or the end of the change if the change covers it.\nfunction adjustForChange(pos, change) {\n  if (cmp(pos, change.from) < 0) return pos\n  if (cmp(pos, change.to) <= 0) return changeEnd(change)\n\n  let line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch\n  if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch\n  return Pos(line, ch)\n}\n\nexport function computeSelAfterChange(doc, change) {\n  let out = []\n  for (let i = 0; i < doc.sel.ranges.length; i++) {\n    let range = doc.sel.ranges[i]\n    out.push(new Range(adjustForChange(range.anchor, change),\n                       adjustForChange(range.head, change)))\n  }\n  return normalizeSelection(doc.cm, out, doc.sel.primIndex)\n}\n\nfunction offsetPos(pos, old, nw) {\n  if (pos.line == old.line)\n    return Pos(nw.line, pos.ch - old.ch + nw.ch)\n  else\n    return Pos(nw.line + (pos.line - old.line), pos.ch)\n}\n\n// Used by replaceSelections to allow moving the selection to the\n// start or around the replaced test. Hint may be \"start\" or \"around\".\nexport function computeReplacedSel(doc, changes, hint) {\n  let out = []\n  let oldPrev = Pos(doc.first, 0), newPrev = oldPrev\n  for (let i = 0; i < changes.length; i++) {\n    let change = changes[i]\n    let from = offsetPos(change.from, oldPrev, newPrev)\n    let to = offsetPos(changeEnd(change), oldPrev, newPrev)\n    oldPrev = change.to\n    newPrev = to\n    if (hint == \"around\") {\n      let range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0\n      out[i] = new Range(inv ? to : from, inv ? from : to)\n    } else {\n      out[i] = new Range(from, from)\n    }\n  }\n  return new Selection(out, doc.sel.primIndex)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/changes.js",
    "content": "import { retreatFrontier } from \"../line/highlight.js\"\nimport { startWorker } from \"../display/highlight_worker.js\"\nimport { operation } from \"../display/operations.js\"\nimport { regChange, regLineChange } from \"../display/view_tracking.js\"\nimport { clipLine, clipPos, cmp, Pos } from \"../line/pos.js\"\nimport { sawReadOnlySpans } from \"../line/saw_special_spans.js\"\nimport { lineLength, removeReadOnlyRanges, stretchSpansOverChange, visualLine } from \"../line/spans.js\"\nimport { getBetween, getLine, lineNo } from \"../line/utils_line.js\"\nimport { estimateHeight } from \"../measurement/position_measurement.js\"\nimport { hasHandler, signal, signalCursorActivity } from \"../util/event.js\"\nimport { indexOf, lst, map, sel_dontScroll } from \"../util/misc.js\"\nimport { signalLater } from \"../util/operation_group.js\"\n\nimport { changeEnd, computeSelAfterChange } from \"./change_measurement.js\"\nimport { isWholeLineUpdate, linkedDocs, updateDoc } from \"./document_data.js\"\nimport { addChangeToHistory, historyChangeFromChange, mergeOldSpans, pushSelectionToHistory } from \"./history.js\"\nimport { Range, Selection } from \"./selection.js\"\nimport { setSelection, setSelectionNoUndo } from \"./selection_updates.js\"\n\n// UPDATING\n\n// Allow \"beforeChange\" event handlers to influence a change\nfunction filterChange(doc, change, update) {\n  let obj = {\n    canceled: false,\n    from: change.from,\n    to: change.to,\n    text: change.text,\n    origin: change.origin,\n    cancel: () => obj.canceled = true\n  }\n  if (update) obj.update = (from, to, text, origin) => {\n    if (from) obj.from = clipPos(doc, from)\n    if (to) obj.to = clipPos(doc, to)\n    if (text) obj.text = text\n    if (origin !== undefined) obj.origin = origin\n  }\n  signal(doc, \"beforeChange\", doc, obj)\n  if (doc.cm) signal(doc.cm, \"beforeChange\", doc.cm, obj)\n\n  if (obj.canceled) {\n    if (doc.cm) doc.cm.curOp.updateInput = 2\n    return null\n  }\n  return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}\n}\n\n// Apply a change to a document, and add it to the document's\n// history, and propagating it to all linked documents.\nexport function makeChange(doc, change, ignoreReadOnly) {\n  if (doc.cm) {\n    if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly)\n    if (doc.cm.state.suppressEdits) return\n  }\n\n  if (hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\")) {\n    change = filterChange(doc, change, true)\n    if (!change) return\n  }\n\n  // Possibly split or suppress the update based on the presence\n  // of read-only spans in its range.\n  let split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)\n  if (split) {\n    for (let i = split.length - 1; i >= 0; --i)\n      makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [\"\"] : change.text, origin: change.origin})\n  } else {\n    makeChangeInner(doc, change)\n  }\n}\n\nfunction makeChangeInner(doc, change) {\n  if (change.text.length == 1 && change.text[0] == \"\" && cmp(change.from, change.to) == 0) return\n  let selAfter = computeSelAfterChange(doc, change)\n  addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)\n\n  makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))\n  let rebased = []\n\n  linkedDocs(doc, (doc, sharedHist) => {\n    if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n      rebaseHist(doc.history, change)\n      rebased.push(doc.history)\n    }\n    makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))\n  })\n}\n\n// Revert a change stored in a document's history.\nexport function makeChangeFromHistory(doc, type, allowSelectionOnly) {\n  let suppress = doc.cm && doc.cm.state.suppressEdits\n  if (suppress && !allowSelectionOnly) return\n\n  let hist = doc.history, event, selAfter = doc.sel\n  let source = type == \"undo\" ? hist.done : hist.undone, dest = type == \"undo\" ? hist.undone : hist.done\n\n  // Verify that there is a useable event (so that ctrl-z won't\n  // needlessly clear selection events)\n  let i = 0\n  for (; i < source.length; i++) {\n    event = source[i]\n    if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)\n      break\n  }\n  if (i == source.length) return\n  hist.lastOrigin = hist.lastSelOrigin = null\n\n  for (;;) {\n    event = source.pop()\n    if (event.ranges) {\n      pushSelectionToHistory(event, dest)\n      if (allowSelectionOnly && !event.equals(doc.sel)) {\n        setSelection(doc, event, {clearRedo: false})\n        return\n      }\n      selAfter = event\n    } else if (suppress) {\n      source.push(event)\n      return\n    } else break\n  }\n\n  // Build up a reverse change object to add to the opposite history\n  // stack (redo when undoing, and vice versa).\n  let antiChanges = []\n  pushSelectionToHistory(selAfter, dest)\n  dest.push({changes: antiChanges, generation: hist.generation})\n  hist.generation = event.generation || ++hist.maxGeneration\n\n  let filter = hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\")\n\n  for (let i = event.changes.length - 1; i >= 0; --i) {\n    let change = event.changes[i]\n    change.origin = type\n    if (filter && !filterChange(doc, change, false)) {\n      source.length = 0\n      return\n    }\n\n    antiChanges.push(historyChangeFromChange(doc, change))\n\n    let after = i ? computeSelAfterChange(doc, change) : lst(source)\n    makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))\n    if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)})\n    let rebased = []\n\n    // Propagate to the linked documents\n    linkedDocs(doc, (doc, sharedHist) => {\n      if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n        rebaseHist(doc.history, change)\n        rebased.push(doc.history)\n      }\n      makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))\n    })\n  }\n}\n\n// Sub-views need their line numbers shifted when text is added\n// above or below them in the parent document.\nfunction shiftDoc(doc, distance) {\n  if (distance == 0) return\n  doc.first += distance\n  doc.sel = new Selection(map(doc.sel.ranges, range => new Range(\n    Pos(range.anchor.line + distance, range.anchor.ch),\n    Pos(range.head.line + distance, range.head.ch)\n  )), doc.sel.primIndex)\n  if (doc.cm) {\n    regChange(doc.cm, doc.first, doc.first - distance, distance)\n    for (let d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)\n      regLineChange(doc.cm, l, \"gutter\")\n  }\n}\n\n// More lower-level change function, handling only a single document\n// (not linked ones).\nfunction makeChangeSingleDoc(doc, change, selAfter, spans) {\n  if (doc.cm && !doc.cm.curOp)\n    return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans)\n\n  if (change.to.line < doc.first) {\n    shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))\n    return\n  }\n  if (change.from.line > doc.lastLine()) return\n\n  // Clip the change to the size of this doc\n  if (change.from.line < doc.first) {\n    let shift = change.text.length - 1 - (doc.first - change.from.line)\n    shiftDoc(doc, shift)\n    change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),\n              text: [lst(change.text)], origin: change.origin}\n  }\n  let last = doc.lastLine()\n  if (change.to.line > last) {\n    change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),\n              text: [change.text[0]], origin: change.origin}\n  }\n\n  change.removed = getBetween(doc, change.from, change.to)\n\n  if (!selAfter) selAfter = computeSelAfterChange(doc, change)\n  if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans)\n  else updateDoc(doc, change, spans)\n  setSelectionNoUndo(doc, selAfter, sel_dontScroll)\n}\n\n// Handle the interaction of a change to a document with the editor\n// that this document is part of.\nfunction makeChangeSingleDocInEditor(cm, change, spans) {\n  let doc = cm.doc, display = cm.display, from = change.from, to = change.to\n\n  let recomputeMaxLength = false, checkWidthStart = from.line\n  if (!cm.options.lineWrapping) {\n    checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))\n    doc.iter(checkWidthStart, to.line + 1, line => {\n      if (line == display.maxLine) {\n        recomputeMaxLength = true\n        return true\n      }\n    })\n  }\n\n  if (doc.sel.contains(change.from, change.to) > -1)\n    signalCursorActivity(cm)\n\n  updateDoc(doc, change, spans, estimateHeight(cm))\n\n  if (!cm.options.lineWrapping) {\n    doc.iter(checkWidthStart, from.line + change.text.length, line => {\n      let len = lineLength(line)\n      if (len > display.maxLineLength) {\n        display.maxLine = line\n        display.maxLineLength = len\n        display.maxLineChanged = true\n        recomputeMaxLength = false\n      }\n    })\n    if (recomputeMaxLength) cm.curOp.updateMaxLine = true\n  }\n\n  retreatFrontier(doc, from.line)\n  startWorker(cm, 400)\n\n  let lendiff = change.text.length - (to.line - from.line) - 1\n  // Remember that these lines changed, for updating the display\n  if (change.full)\n    regChange(cm)\n  else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))\n    regLineChange(cm, from.line, \"text\")\n  else\n    regChange(cm, from.line, to.line + 1, lendiff)\n\n  let changesHandler = hasHandler(cm, \"changes\"), changeHandler = hasHandler(cm, \"change\")\n  if (changeHandler || changesHandler) {\n    let obj = {\n      from: from, to: to,\n      text: change.text,\n      removed: change.removed,\n      origin: change.origin\n    }\n    if (changeHandler) signalLater(cm, \"change\", cm, obj)\n    if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj)\n  }\n  cm.display.selForContextMenu = null\n}\n\nexport function replaceRange(doc, code, from, to, origin) {\n  if (!to) to = from\n  if (cmp(to, from) < 0) [from, to] = [to, from]\n  if (typeof code == \"string\") code = doc.splitLines(code)\n  makeChange(doc, {from, to, text: code, origin})\n}\n\n// Rebasing/resetting history to deal with externally-sourced changes\n\nfunction rebaseHistSelSingle(pos, from, to, diff) {\n  if (to < pos.line) {\n    pos.line += diff\n  } else if (from < pos.line) {\n    pos.line = from\n    pos.ch = 0\n  }\n}\n\n// Tries to rebase an array of history events given a change in the\n// document. If the change touches the same lines as the event, the\n// event, and everything 'behind' it, is discarded. If the change is\n// before the event, the event's positions are updated. Uses a\n// copy-on-write scheme for the positions, to avoid having to\n// reallocate them all on every rebase, but also avoid problems with\n// shared position objects being unsafely updated.\nfunction rebaseHistArray(array, from, to, diff) {\n  for (let i = 0; i < array.length; ++i) {\n    let sub = array[i], ok = true\n    if (sub.ranges) {\n      if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }\n      for (let j = 0; j < sub.ranges.length; j++) {\n        rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)\n        rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)\n      }\n      continue\n    }\n    for (let j = 0; j < sub.changes.length; ++j) {\n      let cur = sub.changes[j]\n      if (to < cur.from.line) {\n        cur.from = Pos(cur.from.line + diff, cur.from.ch)\n        cur.to = Pos(cur.to.line + diff, cur.to.ch)\n      } else if (from <= cur.to.line) {\n        ok = false\n        break\n      }\n    }\n    if (!ok) {\n      array.splice(0, i + 1)\n      i = 0\n    }\n  }\n}\n\nfunction rebaseHist(hist, change) {\n  let from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1\n  rebaseHistArray(hist.done, from, to, diff)\n  rebaseHistArray(hist.undone, from, to, diff)\n}\n\n// Utility for applying a change to a line by handle or number,\n// returning the number and optionally registering the line as\n// changed.\nexport function changeLine(doc, handle, changeType, op) {\n  let no = handle, line = handle\n  if (typeof handle == \"number\") line = getLine(doc, clipLine(doc, handle))\n  else no = lineNo(handle)\n  if (no == null) return null\n  if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType)\n  return line\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/chunk.js",
    "content": "import { cleanUpLine } from \"../line/line_data.js\"\nimport { indexOf } from \"../util/misc.js\"\nimport { signalLater } from \"../util/operation_group.js\"\n\n// The document is represented as a BTree consisting of leaves, with\n// chunk of lines in them, and branches, with up to ten leaves or\n// other branch nodes below them. The top node is always a branch\n// node, and is the document object itself (meaning it has\n// additional methods and properties).\n//\n// All nodes have parent links. The tree is used both to go from\n// line numbers to line objects, and to go from objects to numbers.\n// It also indexes by height, and is used to convert between height\n// and line object, and to find the total height of the document.\n//\n// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html\n\nexport function LeafChunk(lines) {\n  this.lines = lines\n  this.parent = null\n  let height = 0\n  for (let i = 0; i < lines.length; ++i) {\n    lines[i].parent = this\n    height += lines[i].height\n  }\n  this.height = height\n}\n\nLeafChunk.prototype = {\n  chunkSize() { return this.lines.length },\n\n  // Remove the n lines at offset 'at'.\n  removeInner(at, n) {\n    for (let i = at, e = at + n; i < e; ++i) {\n      let line = this.lines[i]\n      this.height -= line.height\n      cleanUpLine(line)\n      signalLater(line, \"delete\")\n    }\n    this.lines.splice(at, n)\n  },\n\n  // Helper used to collapse a small branch into a single leaf.\n  collapse(lines) {\n    lines.push.apply(lines, this.lines)\n  },\n\n  // Insert the given array of lines at offset 'at', count them as\n  // having the given height.\n  insertInner(at, lines, height) {\n    this.height += height\n    this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))\n    for (let i = 0; i < lines.length; ++i) lines[i].parent = this\n  },\n\n  // Used to iterate over a part of the tree.\n  iterN(at, n, op) {\n    for (let e = at + n; at < e; ++at)\n      if (op(this.lines[at])) return true\n  }\n}\n\nexport function BranchChunk(children) {\n  this.children = children\n  let size = 0, height = 0\n  for (let i = 0; i < children.length; ++i) {\n    let ch = children[i]\n    size += ch.chunkSize(); height += ch.height\n    ch.parent = this\n  }\n  this.size = size\n  this.height = height\n  this.parent = null\n}\n\nBranchChunk.prototype = {\n  chunkSize() { return this.size },\n\n  removeInner(at, n) {\n    this.size -= n\n    for (let i = 0; i < this.children.length; ++i) {\n      let child = this.children[i], sz = child.chunkSize()\n      if (at < sz) {\n        let rm = Math.min(n, sz - at), oldHeight = child.height\n        child.removeInner(at, rm)\n        this.height -= oldHeight - child.height\n        if (sz == rm) { this.children.splice(i--, 1); child.parent = null }\n        if ((n -= rm) == 0) break\n        at = 0\n      } else at -= sz\n    }\n    // If the result is smaller than 25 lines, ensure that it is a\n    // single leaf node.\n    if (this.size - n < 25 &&\n        (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {\n      let lines = []\n      this.collapse(lines)\n      this.children = [new LeafChunk(lines)]\n      this.children[0].parent = this\n    }\n  },\n\n  collapse(lines) {\n    for (let i = 0; i < this.children.length; ++i) this.children[i].collapse(lines)\n  },\n\n  insertInner(at, lines, height) {\n    this.size += lines.length\n    this.height += height\n    for (let i = 0; i < this.children.length; ++i) {\n      let child = this.children[i], sz = child.chunkSize()\n      if (at <= sz) {\n        child.insertInner(at, lines, height)\n        if (child.lines && child.lines.length > 50) {\n          // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.\n          // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.\n          let remaining = child.lines.length % 25 + 25\n          for (let pos = remaining; pos < child.lines.length;) {\n            let leaf = new LeafChunk(child.lines.slice(pos, pos += 25))\n            child.height -= leaf.height\n            this.children.splice(++i, 0, leaf)\n            leaf.parent = this\n          }\n          child.lines = child.lines.slice(0, remaining)\n          this.maybeSpill()\n        }\n        break\n      }\n      at -= sz\n    }\n  },\n\n  // When a node has grown, check whether it should be split.\n  maybeSpill() {\n    if (this.children.length <= 10) return\n    let me = this\n    do {\n      let spilled = me.children.splice(me.children.length - 5, 5)\n      let sibling = new BranchChunk(spilled)\n      if (!me.parent) { // Become the parent node\n        let copy = new BranchChunk(me.children)\n        copy.parent = me\n        me.children = [copy, sibling]\n        me = copy\n     } else {\n        me.size -= sibling.size\n        me.height -= sibling.height\n        let myIndex = indexOf(me.parent.children, me)\n        me.parent.children.splice(myIndex + 1, 0, sibling)\n      }\n      sibling.parent = me.parent\n    } while (me.children.length > 10)\n    me.parent.maybeSpill()\n  },\n\n  iterN(at, n, op) {\n    for (let i = 0; i < this.children.length; ++i) {\n      let child = this.children[i], sz = child.chunkSize()\n      if (at < sz) {\n        let used = Math.min(n, sz - at)\n        if (child.iterN(at, used, op)) return true\n        if ((n -= used) == 0) break\n        at = 0\n      } else at -= sz\n    }\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/document_data.js",
    "content": "import { loadMode } from \"../display/mode_state.js\"\nimport { runInOp } from \"../display/operations.js\"\nimport { regChange } from \"../display/view_tracking.js\"\nimport { Line, updateLine } from \"../line/line_data.js\"\nimport { findMaxLine } from \"../line/spans.js\"\nimport { getLine } from \"../line/utils_line.js\"\nimport { estimateLineHeights } from \"../measurement/position_measurement.js\"\nimport { addClass, rmClass } from \"../util/dom.js\"\nimport { lst } from \"../util/misc.js\"\nimport { signalLater } from \"../util/operation_group.js\"\n\n// DOCUMENT DATA STRUCTURE\n\n// By default, updates that start and end at the beginning of a line\n// are treated specially, in order to make the association of line\n// widgets and marker elements with the text behave more intuitive.\nexport function isWholeLineUpdate(doc, change) {\n  return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == \"\" &&\n    (!doc.cm || doc.cm.options.wholeLineUpdateBefore)\n}\n\n// Perform a change on the document data structure.\nexport function updateDoc(doc, change, markedSpans, estimateHeight) {\n  function spansFor(n) {return markedSpans ? markedSpans[n] : null}\n  function update(line, text, spans) {\n    updateLine(line, text, spans, estimateHeight)\n    signalLater(line, \"change\", line, change)\n  }\n  function linesFor(start, end) {\n    let result = []\n    for (let i = start; i < end; ++i)\n      result.push(new Line(text[i], spansFor(i), estimateHeight))\n    return result\n  }\n\n  let from = change.from, to = change.to, text = change.text\n  let firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)\n  let lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line\n\n  // Adjust the line structure\n  if (change.full) {\n    doc.insert(0, linesFor(0, text.length))\n    doc.remove(text.length, doc.size - text.length)\n  } else if (isWholeLineUpdate(doc, change)) {\n    // This is a whole-line replace. Treated specially to make\n    // sure line objects move the way they are supposed to.\n    let added = linesFor(0, text.length - 1)\n    update(lastLine, lastLine.text, lastSpans)\n    if (nlines) doc.remove(from.line, nlines)\n    if (added.length) doc.insert(from.line, added)\n  } else if (firstLine == lastLine) {\n    if (text.length == 1) {\n      update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)\n    } else {\n      let added = linesFor(1, text.length - 1)\n      added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))\n      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))\n      doc.insert(from.line + 1, added)\n    }\n  } else if (text.length == 1) {\n    update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))\n    doc.remove(from.line + 1, nlines)\n  } else {\n    update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))\n    update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)\n    let added = linesFor(1, text.length - 1)\n    if (nlines > 1) doc.remove(from.line + 1, nlines - 1)\n    doc.insert(from.line + 1, added)\n  }\n\n  signalLater(doc, \"change\", doc, change)\n}\n\n// Call f for all linked documents.\nexport function linkedDocs(doc, f, sharedHistOnly) {\n  function propagate(doc, skip, sharedHist) {\n    if (doc.linked) for (let i = 0; i < doc.linked.length; ++i) {\n      let rel = doc.linked[i]\n      if (rel.doc == skip) continue\n      let shared = sharedHist && rel.sharedHist\n      if (sharedHistOnly && !shared) continue\n      f(rel.doc, shared)\n      propagate(rel.doc, doc, shared)\n    }\n  }\n  propagate(doc, null, true)\n}\n\n// Attach a document to an editor.\nexport function attachDoc(cm, doc) {\n  if (doc.cm) throw new Error(\"This document is already in use.\")\n  cm.doc = doc\n  doc.cm = cm\n  estimateLineHeights(cm)\n  loadMode(cm)\n  setDirectionClass(cm)\n  if (!cm.options.lineWrapping) findMaxLine(cm)\n  cm.options.mode = doc.modeOption\n  regChange(cm)\n}\n\nfunction setDirectionClass(cm) {\n  ;(cm.doc.direction == \"rtl\" ? addClass : rmClass)(cm.display.lineDiv, \"CodeMirror-rtl\")\n}\n\nexport function directionChanged(cm) {\n  runInOp(cm, () => {\n    setDirectionClass(cm)\n    regChange(cm)\n  })\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/history.js",
    "content": "import { cmp, copyPos } from \"../line/pos.js\"\nimport { stretchSpansOverChange } from \"../line/spans.js\"\nimport { getBetween } from \"../line/utils_line.js\"\nimport { signal } from \"../util/event.js\"\nimport { indexOf, lst } from \"../util/misc.js\"\n\nimport { changeEnd } from \"./change_measurement.js\"\nimport { linkedDocs } from \"./document_data.js\"\nimport { Selection } from \"./selection.js\"\n\nexport function History(startGen) {\n  // Arrays of change events and selections. Doing something adds an\n  // event to done and clears undo. Undoing moves events from done\n  // to undone, redoing moves them in the other direction.\n  this.done = []; this.undone = []\n  this.undoDepth = Infinity\n  // Used to track when changes can be merged into a single undo\n  // event\n  this.lastModTime = this.lastSelTime = 0\n  this.lastOp = this.lastSelOp = null\n  this.lastOrigin = this.lastSelOrigin = null\n  // Used by the isClean() method\n  this.generation = this.maxGeneration = startGen || 1\n}\n\n// Create a history change event from an updateDoc-style change\n// object.\nexport function historyChangeFromChange(doc, change) {\n  let histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}\n  attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)\n  linkedDocs(doc, doc => attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1), true)\n  return histChange\n}\n\n// Pop all selection events off the end of a history array. Stop at\n// a change event.\nfunction clearSelectionEvents(array) {\n  while (array.length) {\n    let last = lst(array)\n    if (last.ranges) array.pop()\n    else break\n  }\n}\n\n// Find the top change event in the history. Pop off selection\n// events that are in the way.\nfunction lastChangeEvent(hist, force) {\n  if (force) {\n    clearSelectionEvents(hist.done)\n    return lst(hist.done)\n  } else if (hist.done.length && !lst(hist.done).ranges) {\n    return lst(hist.done)\n  } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {\n    hist.done.pop()\n    return lst(hist.done)\n  }\n}\n\n// Register a change in the history. Merges changes that are within\n// a single operation, or are close together with an origin that\n// allows merging (starting with \"+\") into a single event.\nexport function addChangeToHistory(doc, change, selAfter, opId) {\n  let hist = doc.history\n  hist.undone.length = 0\n  let time = +new Date, cur\n  let last\n\n  if ((hist.lastOp == opId ||\n       hist.lastOrigin == change.origin && change.origin &&\n       ((change.origin.charAt(0) == \"+\" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||\n        change.origin.charAt(0) == \"*\")) &&\n      (cur = lastChangeEvent(hist, hist.lastOp == opId))) {\n    // Merge this change into the last event\n    last = lst(cur.changes)\n    if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {\n      // Optimized case for simple insertion -- don't want to add\n      // new changesets for every character typed\n      last.to = changeEnd(change)\n    } else {\n      // Add new sub-event\n      cur.changes.push(historyChangeFromChange(doc, change))\n    }\n  } else {\n    // Can not be merged, start a new event.\n    let before = lst(hist.done)\n    if (!before || !before.ranges)\n      pushSelectionToHistory(doc.sel, hist.done)\n    cur = {changes: [historyChangeFromChange(doc, change)],\n           generation: hist.generation}\n    hist.done.push(cur)\n    while (hist.done.length > hist.undoDepth) {\n      hist.done.shift()\n      if (!hist.done[0].ranges) hist.done.shift()\n    }\n  }\n  hist.done.push(selAfter)\n  hist.generation = ++hist.maxGeneration\n  hist.lastModTime = hist.lastSelTime = time\n  hist.lastOp = hist.lastSelOp = opId\n  hist.lastOrigin = hist.lastSelOrigin = change.origin\n\n  if (!last) signal(doc, \"historyAdded\")\n}\n\nfunction selectionEventCanBeMerged(doc, origin, prev, sel) {\n  let ch = origin.charAt(0)\n  return ch == \"*\" ||\n    ch == \"+\" &&\n    prev.ranges.length == sel.ranges.length &&\n    prev.somethingSelected() == sel.somethingSelected() &&\n    new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)\n}\n\n// Called whenever the selection changes, sets the new selection as\n// the pending selection in the history, and pushes the old pending\n// selection into the 'done' array when it was significantly\n// different (in number of selected ranges, emptiness, or time).\nexport function addSelectionToHistory(doc, sel, opId, options) {\n  let hist = doc.history, origin = options && options.origin\n\n  // A new event is started when the previous origin does not match\n  // the current, or the origins don't allow matching. Origins\n  // starting with * are always merged, those starting with + are\n  // merged when similar and close together in time.\n  if (opId == hist.lastSelOp ||\n      (origin && hist.lastSelOrigin == origin &&\n       (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||\n        selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))\n    hist.done[hist.done.length - 1] = sel\n  else\n    pushSelectionToHistory(sel, hist.done)\n\n  hist.lastSelTime = +new Date\n  hist.lastSelOrigin = origin\n  hist.lastSelOp = opId\n  if (options && options.clearRedo !== false)\n    clearSelectionEvents(hist.undone)\n}\n\nexport function pushSelectionToHistory(sel, dest) {\n  let top = lst(dest)\n  if (!(top && top.ranges && top.equals(sel)))\n    dest.push(sel)\n}\n\n// Used to store marked span information in the history.\nfunction attachLocalSpans(doc, change, from, to) {\n  let existing = change[\"spans_\" + doc.id], n = 0\n  doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), line => {\n    if (line.markedSpans)\n      (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans\n    ++n\n  })\n}\n\n// When un/re-doing restores text containing marked spans, those\n// that have been explicitly cleared should not be restored.\nfunction removeClearedSpans(spans) {\n  if (!spans) return null\n  let out\n  for (let i = 0; i < spans.length; ++i) {\n    if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i) }\n    else if (out) out.push(spans[i])\n  }\n  return !out ? spans : out.length ? out : null\n}\n\n// Retrieve and filter the old marked spans stored in a change event.\nfunction getOldSpans(doc, change) {\n  let found = change[\"spans_\" + doc.id]\n  if (!found) return null\n  let nw = []\n  for (let i = 0; i < change.text.length; ++i)\n    nw.push(removeClearedSpans(found[i]))\n  return nw\n}\n\n// Used for un/re-doing changes from the history. Combines the\n// result of computing the existing spans with the set of spans that\n// existed in the history (so that deleting around a span and then\n// undoing brings back the span).\nexport function mergeOldSpans(doc, change) {\n  let old = getOldSpans(doc, change)\n  let stretched = stretchSpansOverChange(doc, change)\n  if (!old) return stretched\n  if (!stretched) return old\n\n  for (let i = 0; i < old.length; ++i) {\n    let oldCur = old[i], stretchCur = stretched[i]\n    if (oldCur && stretchCur) {\n      spans: for (let j = 0; j < stretchCur.length; ++j) {\n        let span = stretchCur[j]\n        for (let k = 0; k < oldCur.length; ++k)\n          if (oldCur[k].marker == span.marker) continue spans\n        oldCur.push(span)\n      }\n    } else if (stretchCur) {\n      old[i] = stretchCur\n    }\n  }\n  return old\n}\n\n// Used both to provide a JSON-safe object in .getHistory, and, when\n// detaching a document, to split the history in two\nexport function copyHistoryArray(events, newGroup, instantiateSel) {\n  let copy = []\n  for (let i = 0; i < events.length; ++i) {\n    let event = events[i]\n    if (event.ranges) {\n      copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)\n      continue\n    }\n    let changes = event.changes, newChanges = []\n    copy.push({changes: newChanges})\n    for (let j = 0; j < changes.length; ++j) {\n      let change = changes[j], m\n      newChanges.push({from: change.from, to: change.to, text: change.text})\n      if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\\d+)$/)) {\n        if (indexOf(newGroup, Number(m[1])) > -1) {\n          lst(newChanges)[prop] = change[prop]\n          delete change[prop]\n        }\n      }\n    }\n  }\n  return copy\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/line_widget.js",
    "content": "import { runInOp } from \"../display/operations.js\"\nimport { addToScrollTop } from \"../display/scrolling.js\"\nimport { regLineChange } from \"../display/view_tracking.js\"\nimport { heightAtLine, lineIsHidden } from \"../line/spans.js\"\nimport { lineNo, updateLineHeight } from \"../line/utils_line.js\"\nimport { widgetHeight } from \"../measurement/widgets.js\"\nimport { changeLine } from \"./changes.js\"\nimport { eventMixin } from \"../util/event.js\"\nimport { signalLater } from \"../util/operation_group.js\"\n\n// Line widgets are block elements displayed above or below a line.\n\nexport class LineWidget {\n  constructor(doc, node, options) {\n    if (options) for (let opt in options) if (options.hasOwnProperty(opt))\n      this[opt] = options[opt]\n    this.doc = doc\n    this.node = node\n  }\n\n  clear() {\n    let cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)\n    if (no == null || !ws) return\n    for (let i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1)\n    if (!ws.length) line.widgets = null\n    let height = widgetHeight(this)\n    updateLineHeight(line, Math.max(0, line.height - height))\n    if (cm) {\n      runInOp(cm, () => {\n        adjustScrollWhenAboveVisible(cm, line, -height)\n        regLineChange(cm, no, \"widget\")\n      })\n      signalLater(cm, \"lineWidgetCleared\", cm, this, no)\n    }\n  }\n\n  changed() {\n    let oldH = this.height, cm = this.doc.cm, line = this.line\n    this.height = null\n    let diff = widgetHeight(this) - oldH\n    if (!diff) return\n    if (!lineIsHidden(this.doc, line)) updateLineHeight(line, line.height + diff)\n    if (cm) {\n      runInOp(cm, () => {\n        cm.curOp.forceUpdate = true\n        adjustScrollWhenAboveVisible(cm, line, diff)\n        signalLater(cm, \"lineWidgetChanged\", cm, this, lineNo(line))\n      })\n    }\n  }\n}\neventMixin(LineWidget)\n\nfunction adjustScrollWhenAboveVisible(cm, line, diff) {\n  if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))\n    addToScrollTop(cm, diff)\n}\n\nexport function addLineWidget(doc, handle, node, options) {\n  let widget = new LineWidget(doc, node, options)\n  let cm = doc.cm\n  if (cm && widget.noHScroll) cm.display.alignWidgets = true\n  changeLine(doc, handle, \"widget\", line => {\n    let widgets = line.widgets || (line.widgets = [])\n    if (widget.insertAt == null) widgets.push(widget)\n    else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget)\n    widget.line = line\n    if (cm && !lineIsHidden(doc, line)) {\n      let aboveVisible = heightAtLine(line) < doc.scrollTop\n      updateLineHeight(line, line.height + widgetHeight(widget))\n      if (aboveVisible) addToScrollTop(cm, widget.height)\n      cm.curOp.forceUpdate = true\n    }\n    return true\n  })\n  if (cm) signalLater(cm, \"lineWidgetAdded\", cm, widget, typeof handle == \"number\" ? handle : lineNo(handle))\n  return widget\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/mark_text.js",
    "content": "import { eltP } from \"../util/dom.js\"\nimport { eventMixin, hasHandler, on } from \"../util/event.js\"\nimport { endOperation, operation, runInOp, startOperation } from \"../display/operations.js\"\nimport { clipPos, cmp, Pos } from \"../line/pos.js\"\nimport { lineNo, updateLineHeight } from \"../line/utils_line.js\"\nimport { clearLineMeasurementCacheFor, findViewForLine, textHeight } from \"../measurement/position_measurement.js\"\nimport { seeReadOnlySpans, seeCollapsedSpans } from \"../line/saw_special_spans.js\"\nimport { addMarkedSpan, conflictingCollapsedRange, getMarkedSpanFor, lineIsHidden, lineLength, MarkedSpan, removeMarkedSpan, visualLine } from \"../line/spans.js\"\nimport { copyObj, indexOf, lst } from \"../util/misc.js\"\nimport { signalLater } from \"../util/operation_group.js\"\nimport { widgetHeight } from \"../measurement/widgets.js\"\nimport { regChange, regLineChange } from \"../display/view_tracking.js\"\n\nimport { linkedDocs } from \"./document_data.js\"\nimport { addChangeToHistory } from \"./history.js\"\nimport { reCheckSelection } from \"./selection_updates.js\"\n\n// TEXTMARKERS\n\n// Created with markText and setBookmark methods. A TextMarker is a\n// handle that can be used to clear or find a marked position in the\n// document. Line objects hold arrays (markedSpans) containing\n// {from, to, marker} object pointing to such marker objects, and\n// indicating that such a marker is present on that line. Multiple\n// lines may point to the same marker when it spans across lines.\n// The spans will have null for their from/to properties when the\n// marker continues beyond the start/end of the line. Markers have\n// links back to the lines they currently touch.\n\n// Collapsed markers have unique ids, in order to be able to order\n// them, which is needed for uniquely determining an outer marker\n// when they overlap (they may nest, but not partially overlap).\nlet nextMarkerId = 0\n\nexport class TextMarker {\n  constructor(doc, type) {\n    this.lines = []\n    this.type = type\n    this.doc = doc\n    this.id = ++nextMarkerId\n  }\n\n  // Clear the marker.\n  clear() {\n    if (this.explicitlyCleared) return\n    let cm = this.doc.cm, withOp = cm && !cm.curOp\n    if (withOp) startOperation(cm)\n    if (hasHandler(this, \"clear\")) {\n      let found = this.find()\n      if (found) signalLater(this, \"clear\", found.from, found.to)\n    }\n    let min = null, max = null\n    for (let i = 0; i < this.lines.length; ++i) {\n      let line = this.lines[i]\n      let span = getMarkedSpanFor(line.markedSpans, this)\n      if (cm && !this.collapsed) regLineChange(cm, lineNo(line), \"text\")\n      else if (cm) {\n        if (span.to != null) max = lineNo(line)\n        if (span.from != null) min = lineNo(line)\n      }\n      line.markedSpans = removeMarkedSpan(line.markedSpans, span)\n      if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)\n        updateLineHeight(line, textHeight(cm.display))\n    }\n    if (cm && this.collapsed && !cm.options.lineWrapping) for (let i = 0; i < this.lines.length; ++i) {\n      let visual = visualLine(this.lines[i]), len = lineLength(visual)\n      if (len > cm.display.maxLineLength) {\n        cm.display.maxLine = visual\n        cm.display.maxLineLength = len\n        cm.display.maxLineChanged = true\n      }\n    }\n\n    if (min != null && cm && this.collapsed) regChange(cm, min, max + 1)\n    this.lines.length = 0\n    this.explicitlyCleared = true\n    if (this.atomic && this.doc.cantEdit) {\n      this.doc.cantEdit = false\n      if (cm) reCheckSelection(cm.doc)\n    }\n    if (cm) signalLater(cm, \"markerCleared\", cm, this, min, max)\n    if (withOp) endOperation(cm)\n    if (this.parent) this.parent.clear()\n  }\n\n  // Find the position of the marker in the document. Returns a {from,\n  // to} object by default. Side can be passed to get a specific side\n  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the\n  // Pos objects returned contain a line object, rather than a line\n  // number (used to prevent looking up the same line twice).\n  find(side, lineObj) {\n    if (side == null && this.type == \"bookmark\") side = 1\n    let from, to\n    for (let i = 0; i < this.lines.length; ++i) {\n      let line = this.lines[i]\n      let span = getMarkedSpanFor(line.markedSpans, this)\n      if (span.from != null) {\n        from = Pos(lineObj ? line : lineNo(line), span.from)\n        if (side == -1) return from\n      }\n      if (span.to != null) {\n        to = Pos(lineObj ? line : lineNo(line), span.to)\n        if (side == 1) return to\n      }\n    }\n    return from && {from: from, to: to}\n  }\n\n  // Signals that the marker's widget changed, and surrounding layout\n  // should be recomputed.\n  changed() {\n    let pos = this.find(-1, true), widget = this, cm = this.doc.cm\n    if (!pos || !cm) return\n    runInOp(cm, () => {\n      let line = pos.line, lineN = lineNo(pos.line)\n      let view = findViewForLine(cm, lineN)\n      if (view) {\n        clearLineMeasurementCacheFor(view)\n        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true\n      }\n      cm.curOp.updateMaxLine = true\n      if (!lineIsHidden(widget.doc, line) && widget.height != null) {\n        let oldHeight = widget.height\n        widget.height = null\n        let dHeight = widgetHeight(widget) - oldHeight\n        if (dHeight)\n          updateLineHeight(line, line.height + dHeight)\n      }\n      signalLater(cm, \"markerChanged\", cm, this)\n    })\n  }\n\n  attachLine(line) {\n    if (!this.lines.length && this.doc.cm) {\n      let op = this.doc.cm.curOp\n      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)\n        (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this)\n    }\n    this.lines.push(line)\n  }\n\n  detachLine(line) {\n    this.lines.splice(indexOf(this.lines, line), 1)\n    if (!this.lines.length && this.doc.cm) {\n      let op = this.doc.cm.curOp\n      ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)\n    }\n  }\n}\neventMixin(TextMarker)\n\n// Create a marker, wire it up to the right lines, and\nexport function markText(doc, from, to, options, type) {\n  // Shared markers (across linked documents) are handled separately\n  // (markTextShared will call out to this again, once per\n  // document).\n  if (options && options.shared) return markTextShared(doc, from, to, options, type)\n  // Ensure we are in an operation.\n  if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type)\n\n  let marker = new TextMarker(doc, type), diff = cmp(from, to)\n  if (options) copyObj(options, marker, false)\n  // Don't connect empty markers unless clearWhenEmpty is false\n  if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)\n    return marker\n  if (marker.replacedWith) {\n    // Showing up as a widget implies collapsed (widget replaces text)\n    marker.collapsed = true\n    marker.widgetNode = eltP(\"span\", [marker.replacedWith], \"CodeMirror-widget\")\n    if (!options.handleMouseEvents) marker.widgetNode.setAttribute(\"cm-ignore-events\", \"true\")\n    if (options.insertLeft) marker.widgetNode.insertLeft = true\n  }\n  if (marker.collapsed) {\n    if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||\n        from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))\n      throw new Error(\"Inserting collapsed marker partially overlapping an existing one\")\n    seeCollapsedSpans()\n  }\n\n  if (marker.addToHistory)\n    addChangeToHistory(doc, {from: from, to: to, origin: \"markText\"}, doc.sel, NaN)\n\n  let curLine = from.line, cm = doc.cm, updateMaxLine\n  doc.iter(curLine, to.line + 1, line => {\n    if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)\n      updateMaxLine = true\n    if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0)\n    addMarkedSpan(line, new MarkedSpan(marker,\n                                       curLine == from.line ? from.ch : null,\n                                       curLine == to.line ? to.ch : null))\n    ++curLine\n  })\n  // lineIsHidden depends on the presence of the spans, so needs a second pass\n  if (marker.collapsed) doc.iter(from.line, to.line + 1, line => {\n    if (lineIsHidden(doc, line)) updateLineHeight(line, 0)\n  })\n\n  if (marker.clearOnEnter) on(marker, \"beforeCursorEnter\", () => marker.clear())\n\n  if (marker.readOnly) {\n    seeReadOnlySpans()\n    if (doc.history.done.length || doc.history.undone.length)\n      doc.clearHistory()\n  }\n  if (marker.collapsed) {\n    marker.id = ++nextMarkerId\n    marker.atomic = true\n  }\n  if (cm) {\n    // Sync editor state\n    if (updateMaxLine) cm.curOp.updateMaxLine = true\n    if (marker.collapsed)\n      regChange(cm, from.line, to.line + 1)\n    else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||\n             marker.attributes || marker.title)\n      for (let i = from.line; i <= to.line; i++) regLineChange(cm, i, \"text\")\n    if (marker.atomic) reCheckSelection(cm.doc)\n    signalLater(cm, \"markerAdded\", cm, marker)\n  }\n  return marker\n}\n\n// SHARED TEXTMARKERS\n\n// A shared marker spans multiple linked documents. It is\n// implemented as a meta-marker-object controlling multiple normal\n// markers.\nexport class SharedTextMarker {\n  constructor(markers, primary) {\n    this.markers = markers\n    this.primary = primary\n    for (let i = 0; i < markers.length; ++i)\n      markers[i].parent = this\n  }\n\n  clear() {\n    if (this.explicitlyCleared) return\n    this.explicitlyCleared = true\n    for (let i = 0; i < this.markers.length; ++i)\n      this.markers[i].clear()\n    signalLater(this, \"clear\")\n  }\n\n  find(side, lineObj) {\n    return this.primary.find(side, lineObj)\n  }\n}\neventMixin(SharedTextMarker)\n\nfunction markTextShared(doc, from, to, options, type) {\n  options = copyObj(options)\n  options.shared = false\n  let markers = [markText(doc, from, to, options, type)], primary = markers[0]\n  let widget = options.widgetNode\n  linkedDocs(doc, doc => {\n    if (widget) options.widgetNode = widget.cloneNode(true)\n    markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))\n    for (let i = 0; i < doc.linked.length; ++i)\n      if (doc.linked[i].isParent) return\n    primary = lst(markers)\n  })\n  return new SharedTextMarker(markers, primary)\n}\n\nexport function findSharedMarkers(doc) {\n  return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), m => m.parent)\n}\n\nexport function copySharedMarkers(doc, markers) {\n  for (let i = 0; i < markers.length; i++) {\n    let marker = markers[i], pos = marker.find()\n    let mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to)\n    if (cmp(mFrom, mTo)) {\n      let subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)\n      marker.markers.push(subMark)\n      subMark.parent = marker\n    }\n  }\n}\n\nexport function detachSharedMarkers(markers) {\n  for (let i = 0; i < markers.length; i++) {\n    let marker = markers[i], linked = [marker.primary.doc]\n    linkedDocs(marker.primary.doc, d => linked.push(d))\n    for (let j = 0; j < marker.markers.length; j++) {\n      let subMarker = marker.markers[j]\n      if (indexOf(linked, subMarker.doc) == -1) {\n        subMarker.parent = null\n        marker.markers.splice(j--, 1)\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/selection.js",
    "content": "import { cmp, copyPos, equalCursorPos, maxPos, minPos } from \"../line/pos.js\"\nimport { indexOf } from \"../util/misc.js\"\n\n// Selection objects are immutable. A new one is created every time\n// the selection changes. A selection is one or more non-overlapping\n// (and non-touching) ranges, sorted, and an integer that indicates\n// which one is the primary selection (the one that's scrolled into\n// view, that getCursor returns, etc).\nexport class Selection {\n  constructor(ranges, primIndex) {\n    this.ranges = ranges\n    this.primIndex = primIndex\n  }\n\n  primary() { return this.ranges[this.primIndex] }\n\n  equals(other) {\n    if (other == this) return true\n    if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false\n    for (let i = 0; i < this.ranges.length; i++) {\n      let here = this.ranges[i], there = other.ranges[i]\n      if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) return false\n    }\n    return true\n  }\n\n  deepCopy() {\n    let out = []\n    for (let i = 0; i < this.ranges.length; i++)\n      out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head))\n    return new Selection(out, this.primIndex)\n  }\n\n  somethingSelected() {\n    for (let i = 0; i < this.ranges.length; i++)\n      if (!this.ranges[i].empty()) return true\n    return false\n  }\n\n  contains(pos, end) {\n    if (!end) end = pos\n    for (let i = 0; i < this.ranges.length; i++) {\n      let range = this.ranges[i]\n      if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)\n        return i\n    }\n    return -1\n  }\n}\n\nexport class Range {\n  constructor(anchor, head) {\n    this.anchor = anchor; this.head = head\n  }\n\n  from() { return minPos(this.anchor, this.head) }\n  to() { return maxPos(this.anchor, this.head) }\n  empty() { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }\n}\n\n// Take an unsorted, potentially overlapping set of ranges, and\n// build a selection out of it. 'Consumes' ranges array (modifying\n// it).\nexport function normalizeSelection(cm, ranges, primIndex) {\n  let mayTouch = cm && cm.options.selectionsMayTouch\n  let prim = ranges[primIndex]\n  ranges.sort((a, b) => cmp(a.from(), b.from()))\n  primIndex = indexOf(ranges, prim)\n  for (let i = 1; i < ranges.length; i++) {\n    let cur = ranges[i], prev = ranges[i - 1]\n    let diff = cmp(prev.to(), cur.from())\n    if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {\n      let from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to())\n      let inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head\n      if (i <= primIndex) --primIndex\n      ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))\n    }\n  }\n  return new Selection(ranges, primIndex)\n}\n\nexport function simpleSelection(anchor, head) {\n  return new Selection([new Range(anchor, head || anchor)], 0)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/model/selection_updates.js",
    "content": "import { signalLater } from \"../util/operation_group.js\"\nimport { ensureCursorVisible } from \"../display/scrolling.js\"\nimport { clipPos, cmp, Pos } from \"../line/pos.js\"\nimport { getLine } from \"../line/utils_line.js\"\nimport { hasHandler, signal, signalCursorActivity } from \"../util/event.js\"\nimport { lst, sel_dontScroll } from \"../util/misc.js\"\n\nimport { addSelectionToHistory } from \"./history.js\"\nimport { normalizeSelection, Range, Selection, simpleSelection } from \"./selection.js\"\n\n// The 'scroll' parameter given to many of these indicated whether\n// the new cursor position should be scrolled into view after\n// modifying the selection.\n\n// If shift is held or the extend flag is set, extends a range to\n// include a given position (and optionally a second position).\n// Otherwise, simply returns the range between the given positions.\n// Used for cursor motion and such.\nexport function extendRange(range, head, other, extend) {\n  if (extend) {\n    let anchor = range.anchor\n    if (other) {\n      let posBefore = cmp(head, anchor) < 0\n      if (posBefore != (cmp(other, anchor) < 0)) {\n        anchor = head\n        head = other\n      } else if (posBefore != (cmp(head, other) < 0)) {\n        head = other\n      }\n    }\n    return new Range(anchor, head)\n  } else {\n    return new Range(other || head, head)\n  }\n}\n\n// Extend the primary selection range, discard the rest.\nexport function extendSelection(doc, head, other, options, extend) {\n  if (extend == null) extend = doc.cm && (doc.cm.display.shift || doc.extend)\n  setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options)\n}\n\n// Extend all selections (pos is an array of selections with length\n// equal the number of selections)\nexport function extendSelections(doc, heads, options) {\n  let out = []\n  let extend = doc.cm && (doc.cm.display.shift || doc.extend)\n  for (let i = 0; i < doc.sel.ranges.length; i++)\n    out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend)\n  let newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex)\n  setSelection(doc, newSel, options)\n}\n\n// Updates a single range in the selection.\nexport function replaceOneSelection(doc, i, range, options) {\n  let ranges = doc.sel.ranges.slice(0)\n  ranges[i] = range\n  setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options)\n}\n\n// Reset the selection to a single range.\nexport function setSimpleSelection(doc, anchor, head, options) {\n  setSelection(doc, simpleSelection(anchor, head), options)\n}\n\n// Give beforeSelectionChange handlers a change to influence a\n// selection update.\nfunction filterSelectionChange(doc, sel, options) {\n  let obj = {\n    ranges: sel.ranges,\n    update: function(ranges) {\n      this.ranges = []\n      for (let i = 0; i < ranges.length; i++)\n        this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),\n                                   clipPos(doc, ranges[i].head))\n    },\n    origin: options && options.origin\n  }\n  signal(doc, \"beforeSelectionChange\", doc, obj)\n  if (doc.cm) signal(doc.cm, \"beforeSelectionChange\", doc.cm, obj)\n  if (obj.ranges != sel.ranges) return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1)\n  else return sel\n}\n\nexport function setSelectionReplaceHistory(doc, sel, options) {\n  let done = doc.history.done, last = lst(done)\n  if (last && last.ranges) {\n    done[done.length - 1] = sel\n    setSelectionNoUndo(doc, sel, options)\n  } else {\n    setSelection(doc, sel, options)\n  }\n}\n\n// Set a new selection.\nexport function setSelection(doc, sel, options) {\n  setSelectionNoUndo(doc, sel, options)\n  addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)\n}\n\nexport function setSelectionNoUndo(doc, sel, options) {\n  if (hasHandler(doc, \"beforeSelectionChange\") || doc.cm && hasHandler(doc.cm, \"beforeSelectionChange\"))\n    sel = filterSelectionChange(doc, sel, options)\n\n  let bias = options && options.bias ||\n    (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)\n  setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))\n\n  if (!(options && options.scroll === false) && doc.cm)\n    ensureCursorVisible(doc.cm)\n}\n\nfunction setSelectionInner(doc, sel) {\n  if (sel.equals(doc.sel)) return\n\n  doc.sel = sel\n\n  if (doc.cm) {\n    doc.cm.curOp.updateInput = 1\n    doc.cm.curOp.selectionChanged = true\n    signalCursorActivity(doc.cm)\n  }\n  signalLater(doc, \"cursorActivity\", doc)\n}\n\n// Verify that the selection does not partially select any atomic\n// marked ranges.\nexport function reCheckSelection(doc) {\n  setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false))\n}\n\n// Return a selection that does not partially select any atomic\n// ranges.\nfunction skipAtomicInSelection(doc, sel, bias, mayClear) {\n  let out\n  for (let i = 0; i < sel.ranges.length; i++) {\n    let range = sel.ranges[i]\n    let old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]\n    let newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)\n    let newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)\n    if (out || newAnchor != range.anchor || newHead != range.head) {\n      if (!out) out = sel.ranges.slice(0, i)\n      out[i] = new Range(newAnchor, newHead)\n    }\n  }\n  return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel\n}\n\nfunction skipAtomicInner(doc, pos, oldPos, dir, mayClear) {\n  let line = getLine(doc, pos.line)\n  if (line.markedSpans) for (let i = 0; i < line.markedSpans.length; ++i) {\n    let sp = line.markedSpans[i], m = sp.marker\n    if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&\n        (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {\n      if (mayClear) {\n        signal(m, \"beforeCursorEnter\")\n        if (m.explicitlyCleared) {\n          if (!line.markedSpans) break\n          else {--i; continue}\n        }\n      }\n      if (!m.atomic) continue\n\n      if (oldPos) {\n        let near = m.find(dir < 0 ? 1 : -1), diff\n        if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)\n          near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null)\n        if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))\n          return skipAtomicInner(doc, near, pos, dir, mayClear)\n      }\n\n      let far = m.find(dir < 0 ? -1 : 1)\n      if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)\n        far = movePos(doc, far, dir, far.line == pos.line ? line : null)\n      return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null\n    }\n  }\n  return pos\n}\n\n// Ensure a given position is not inside an atomic range.\nexport function skipAtomic(doc, pos, oldPos, bias, mayClear) {\n  let dir = bias || 1\n  let found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||\n      (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||\n      skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||\n      (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))\n  if (!found) {\n    doc.cantEdit = true\n    return Pos(doc.first, 0)\n  }\n  return found\n}\n\nfunction movePos(doc, pos, dir, line) {\n  if (dir < 0 && pos.ch == 0) {\n    if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1))\n    else return null\n  } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {\n    if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0)\n    else return null\n  } else {\n    return new Pos(pos.line, pos.ch + dir)\n  }\n}\n\nexport function selectAll(cm) {\n  cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/modes.js",
    "content": "import { copyObj, createObj } from \"./util/misc.js\"\n\n// Known modes, by name and by MIME\nexport let modes = {}, mimeModes = {}\n\n// Extra arguments are stored as the mode's dependencies, which is\n// used by (legacy) mechanisms like loadmode.js to automatically\n// load a mode. (Preferred mechanism is the require/define calls.)\nexport function defineMode(name, mode) {\n  if (arguments.length > 2)\n    mode.dependencies = Array.prototype.slice.call(arguments, 2)\n  modes[name] = mode\n}\n\nexport function defineMIME(mime, spec) {\n  mimeModes[mime] = spec\n}\n\n// Given a MIME type, a {name, ...options} config object, or a name\n// string, return a mode config object.\nexport function resolveMode(spec) {\n  if (typeof spec == \"string\" && mimeModes.hasOwnProperty(spec)) {\n    spec = mimeModes[spec]\n  } else if (spec && typeof spec.name == \"string\" && mimeModes.hasOwnProperty(spec.name)) {\n    let found = mimeModes[spec.name]\n    if (typeof found == \"string\") found = {name: found}\n    spec = createObj(found, spec)\n    spec.name = found.name\n  } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+xml$/.test(spec)) {\n    return resolveMode(\"application/xml\")\n  } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+json$/.test(spec)) {\n    return resolveMode(\"application/json\")\n  }\n  if (typeof spec == \"string\") return {name: spec}\n  else return spec || {name: \"null\"}\n}\n\n// Given a mode spec (anything that resolveMode accepts), find and\n// initialize an actual mode object.\nexport function getMode(options, spec) {\n  spec = resolveMode(spec)\n  let mfactory = modes[spec.name]\n  if (!mfactory) return getMode(options, \"text/plain\")\n  let modeObj = mfactory(options, spec)\n  if (modeExtensions.hasOwnProperty(spec.name)) {\n    let exts = modeExtensions[spec.name]\n    for (let prop in exts) {\n      if (!exts.hasOwnProperty(prop)) continue\n      if (modeObj.hasOwnProperty(prop)) modeObj[\"_\" + prop] = modeObj[prop]\n      modeObj[prop] = exts[prop]\n    }\n  }\n  modeObj.name = spec.name\n  if (spec.helperType) modeObj.helperType = spec.helperType\n  if (spec.modeProps) for (let prop in spec.modeProps)\n    modeObj[prop] = spec.modeProps[prop]\n\n  return modeObj\n}\n\n// This can be used to attach properties to mode objects from\n// outside the actual mode definition.\nexport let modeExtensions = {}\nexport function extendMode(mode, properties) {\n  let exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})\n  copyObj(properties, exts)\n}\n\nexport function copyState(mode, state) {\n  if (state === true) return state\n  if (mode.copyState) return mode.copyState(state)\n  let nstate = {}\n  for (let n in state) {\n    let val = state[n]\n    if (val instanceof Array) val = val.concat([])\n    nstate[n] = val\n  }\n  return nstate\n}\n\n// Given a mode and a state (for that mode), find the inner mode and\n// state at the position that the state refers to.\nexport function innerMode(mode, state) {\n  let info\n  while (mode.innerMode) {\n    info = mode.innerMode(state)\n    if (!info || info.mode == mode) break\n    state = info.state\n    mode = info.mode\n  }\n  return info || {mode: mode, state: state}\n}\n\nexport function startState(mode, a1, a2) {\n  return mode.startState ? mode.startState(a1, a2) : true\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/util/StringStream.js",
    "content": "import { countColumn } from \"./misc.js\"\n\n// STRING STREAM\n\n// Fed to the mode parsers, provides helper functions to make\n// parsers more succinct.\n\nclass StringStream {\n  constructor(string, tabSize, lineOracle) {\n    this.pos = this.start = 0\n    this.string = string\n    this.tabSize = tabSize || 8\n    this.lastColumnPos = this.lastColumnValue = 0\n    this.lineStart = 0\n    this.lineOracle = lineOracle\n  }\n\n  eol() {return this.pos >= this.string.length}\n  sol() {return this.pos == this.lineStart}\n  peek() {return this.string.charAt(this.pos) || undefined}\n  next() {\n    if (this.pos < this.string.length)\n      return this.string.charAt(this.pos++)\n  }\n  eat(match) {\n    let ch = this.string.charAt(this.pos)\n    let ok\n    if (typeof match == \"string\") ok = ch == match\n    else ok = ch && (match.test ? match.test(ch) : match(ch))\n    if (ok) {++this.pos; return ch}\n  }\n  eatWhile(match) {\n    let start = this.pos\n    while (this.eat(match)){}\n    return this.pos > start\n  }\n  eatSpace() {\n    let start = this.pos\n    while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos\n    return this.pos > start\n  }\n  skipToEnd() {this.pos = this.string.length}\n  skipTo(ch) {\n    let found = this.string.indexOf(ch, this.pos)\n    if (found > -1) {this.pos = found; return true}\n  }\n  backUp(n) {this.pos -= n}\n  column() {\n    if (this.lastColumnPos < this.start) {\n      this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)\n      this.lastColumnPos = this.start\n    }\n    return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n  }\n  indentation() {\n    return countColumn(this.string, null, this.tabSize) -\n      (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n  }\n  match(pattern, consume, caseInsensitive) {\n    if (typeof pattern == \"string\") {\n      let cased = str => caseInsensitive ? str.toLowerCase() : str\n      let substr = this.string.substr(this.pos, pattern.length)\n      if (cased(substr) == cased(pattern)) {\n        if (consume !== false) this.pos += pattern.length\n        return true\n      }\n    } else {\n      let match = this.string.slice(this.pos).match(pattern)\n      if (match && match.index > 0) return null\n      if (match && consume !== false) this.pos += match[0].length\n      return match\n    }\n  }\n  current(){return this.string.slice(this.start, this.pos)}\n  hideFirstChars(n, inner) {\n    this.lineStart += n\n    try { return inner() }\n    finally { this.lineStart -= n }\n  }\n  lookAhead(n) {\n    let oracle = this.lineOracle\n    return oracle && oracle.lookAhead(n)\n  }\n  baseToken() {\n    let oracle = this.lineOracle\n    return oracle && oracle.baseToken(this.pos)\n  }\n}\n\nexport default StringStream\n"
  },
  {
    "path": "third_party/CodeMirror/src/util/bidi.js",
    "content": "import { lst } from \"./misc.js\"\n\n// BIDI HELPERS\n\nexport function iterateBidiSections(order, from, to, f) {\n  if (!order) return f(from, to, \"ltr\", 0)\n  let found = false\n  for (let i = 0; i < order.length; ++i) {\n    let part = order[i]\n    if (part.from < to && part.to > from || from == to && part.to == from) {\n      f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? \"rtl\" : \"ltr\", i)\n      found = true\n    }\n  }\n  if (!found) f(from, to, \"ltr\")\n}\n\nexport let bidiOther = null\nexport function getBidiPartAt(order, ch, sticky) {\n  let found\n  bidiOther = null\n  for (let i = 0; i < order.length; ++i) {\n    let cur = order[i]\n    if (cur.from < ch && cur.to > ch) return i\n    if (cur.to == ch) {\n      if (cur.from != cur.to && sticky == \"before\") found = i\n      else bidiOther = i\n    }\n    if (cur.from == ch) {\n      if (cur.from != cur.to && sticky != \"before\") found = i\n      else bidiOther = i\n    }\n  }\n  return found != null ? found : bidiOther\n}\n\n// Bidirectional ordering algorithm\n// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm\n// that this (partially) implements.\n\n// One-char codes used for character types:\n// L (L):   Left-to-Right\n// R (R):   Right-to-Left\n// r (AL):  Right-to-Left Arabic\n// 1 (EN):  European Number\n// + (ES):  European Number Separator\n// % (ET):  European Number Terminator\n// n (AN):  Arabic Number\n// , (CS):  Common Number Separator\n// m (NSM): Non-Spacing Mark\n// b (BN):  Boundary Neutral\n// s (B):   Paragraph Separator\n// t (S):   Segment Separator\n// w (WS):  Whitespace\n// N (ON):  Other Neutrals\n\n// Returns null if characters are ordered as they appear\n// (left-to-right), or an array of sections ({from, to, level}\n// objects) in the order in which they occur visually.\nlet bidiOrdering = (function() {\n  // Character types for codepoints 0 to 0xff\n  let lowTypes = \"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN\"\n  // Character types for codepoints 0x600 to 0x6f9\n  let arabicTypes = \"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111\"\n  function charType(code) {\n    if (code <= 0xf7) return lowTypes.charAt(code)\n    else if (0x590 <= code && code <= 0x5f4) return \"R\"\n    else if (0x600 <= code && code <= 0x6f9) return arabicTypes.charAt(code - 0x600)\n    else if (0x6ee <= code && code <= 0x8ac) return \"r\"\n    else if (0x2000 <= code && code <= 0x200b) return \"w\"\n    else if (code == 0x200c) return \"b\"\n    else return \"L\"\n  }\n\n  let bidiRE = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/\n  let isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/\n\n  function BidiSpan(level, from, to) {\n    this.level = level\n    this.from = from; this.to = to\n  }\n\n  return function(str, direction) {\n    let outerType = direction == \"ltr\" ? \"L\" : \"R\"\n\n    if (str.length == 0 || direction == \"ltr\" && !bidiRE.test(str)) return false\n    let len = str.length, types = []\n    for (let i = 0; i < len; ++i)\n      types.push(charType(str.charCodeAt(i)))\n\n    // W1. Examine each non-spacing mark (NSM) in the level run, and\n    // change the type of the NSM to the type of the previous\n    // character. If the NSM is at the start of the level run, it will\n    // get the type of sor.\n    for (let i = 0, prev = outerType; i < len; ++i) {\n      let type = types[i]\n      if (type == \"m\") types[i] = prev\n      else prev = type\n    }\n\n    // W2. Search backwards from each instance of a European number\n    // until the first strong type (R, L, AL, or sor) is found. If an\n    // AL is found, change the type of the European number to Arabic\n    // number.\n    // W3. Change all ALs to R.\n    for (let i = 0, cur = outerType; i < len; ++i) {\n      let type = types[i]\n      if (type == \"1\" && cur == \"r\") types[i] = \"n\"\n      else if (isStrong.test(type)) { cur = type; if (type == \"r\") types[i] = \"R\" }\n    }\n\n    // W4. A single European separator between two European numbers\n    // changes to a European number. A single common separator between\n    // two numbers of the same type changes to that type.\n    for (let i = 1, prev = types[0]; i < len - 1; ++i) {\n      let type = types[i]\n      if (type == \"+\" && prev == \"1\" && types[i+1] == \"1\") types[i] = \"1\"\n      else if (type == \",\" && prev == types[i+1] &&\n               (prev == \"1\" || prev == \"n\")) types[i] = prev\n      prev = type\n    }\n\n    // W5. A sequence of European terminators adjacent to European\n    // numbers changes to all European numbers.\n    // W6. Otherwise, separators and terminators change to Other\n    // Neutral.\n    for (let i = 0; i < len; ++i) {\n      let type = types[i]\n      if (type == \",\") types[i] = \"N\"\n      else if (type == \"%\") {\n        let end\n        for (end = i + 1; end < len && types[end] == \"%\"; ++end) {}\n        let replace = (i && types[i-1] == \"!\") || (end < len && types[end] == \"1\") ? \"1\" : \"N\"\n        for (let j = i; j < end; ++j) types[j] = replace\n        i = end - 1\n      }\n    }\n\n    // W7. Search backwards from each instance of a European number\n    // until the first strong type (R, L, or sor) is found. If an L is\n    // found, then change the type of the European number to L.\n    for (let i = 0, cur = outerType; i < len; ++i) {\n      let type = types[i]\n      if (cur == \"L\" && type == \"1\") types[i] = \"L\"\n      else if (isStrong.test(type)) cur = type\n    }\n\n    // N1. A sequence of neutrals takes the direction of the\n    // surrounding strong text if the text on both sides has the same\n    // direction. European and Arabic numbers act as if they were R in\n    // terms of their influence on neutrals. Start-of-level-run (sor)\n    // and end-of-level-run (eor) are used at level run boundaries.\n    // N2. Any remaining neutrals take the embedding direction.\n    for (let i = 0; i < len; ++i) {\n      if (isNeutral.test(types[i])) {\n        let end\n        for (end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}\n        let before = (i ? types[i-1] : outerType) == \"L\"\n        let after = (end < len ? types[end] : outerType) == \"L\"\n        let replace = before == after ? (before ? \"L\" : \"R\") : outerType\n        for (let j = i; j < end; ++j) types[j] = replace\n        i = end - 1\n      }\n    }\n\n    // Here we depart from the documented algorithm, in order to avoid\n    // building up an actual levels array. Since there are only three\n    // levels (0, 1, 2) in an implementation that doesn't take\n    // explicit embedding into account, we can build up the order on\n    // the fly, without following the level-based algorithm.\n    let order = [], m\n    for (let i = 0; i < len;) {\n      if (countsAsLeft.test(types[i])) {\n        let start = i\n        for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}\n        order.push(new BidiSpan(0, start, i))\n      } else {\n        let pos = i, at = order.length\n        for (++i; i < len && types[i] != \"L\"; ++i) {}\n        for (let j = pos; j < i;) {\n          if (countsAsNum.test(types[j])) {\n            if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j))\n            let nstart = j\n            for (++j; j < i && countsAsNum.test(types[j]); ++j) {}\n            order.splice(at, 0, new BidiSpan(2, nstart, j))\n            pos = j\n          } else ++j\n        }\n        if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i))\n      }\n    }\n    if (direction == \"ltr\") {\n      if (order[0].level == 1 && (m = str.match(/^\\s+/))) {\n        order[0].from = m[0].length\n        order.unshift(new BidiSpan(0, 0, m[0].length))\n      }\n      if (lst(order).level == 1 && (m = str.match(/\\s+$/))) {\n        lst(order).to -= m[0].length\n        order.push(new BidiSpan(0, len - m[0].length, len))\n      }\n    }\n\n    return direction == \"rtl\" ? order.reverse() : order\n  }\n})()\n\n// Get the bidi ordering for the given line (and cache it). Returns\n// false for lines that are fully left-to-right, and an array of\n// BidiSpan objects otherwise.\nexport function getOrder(line, direction) {\n  let order = line.order\n  if (order == null) order = line.order = bidiOrdering(line.text, direction)\n  return order\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/util/browser.js",
    "content": "// Kludges for bugs and behavior differences that can't be feature\n// detected are enabled based on userAgent etc sniffing.\nlet userAgent = navigator.userAgent\nlet platform = navigator.platform\n\nexport let gecko = /gecko\\/\\d/i.test(userAgent)\nlet ie_upto10 = /MSIE \\d/.test(userAgent)\nlet ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(userAgent)\nlet edge = /Edge\\/(\\d+)/.exec(userAgent)\nexport let ie = ie_upto10 || ie_11up || edge\nexport let ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1])\nexport let webkit = !edge && /WebKit\\//.test(userAgent)\nlet qtwebkit = webkit && /Qt\\/\\d+\\.\\d+/.test(userAgent)\nexport let chrome = !edge && /Chrome\\//.test(userAgent)\nexport let presto = /Opera\\//.test(userAgent)\nexport let safari = /Apple Computer/.test(navigator.vendor)\nexport let mac_geMountainLion = /Mac OS X 1\\d\\D([8-9]|\\d\\d)\\D/.test(userAgent)\nexport let phantom = /PhantomJS/.test(userAgent)\n\nexport let ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\\/\\w+/.test(userAgent)\nexport let android = /Android/.test(userAgent)\n// This is woefully incomplete. Suggestions for alternative methods welcome.\nexport let mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent)\nexport let mac = ios || /Mac/.test(platform)\nexport let chromeOS = /\\bCrOS\\b/.test(userAgent)\nexport let windows = /win/i.test(platform)\n\nlet presto_version = presto && userAgent.match(/Version\\/(\\d*\\.\\d*)/)\nif (presto_version) presto_version = Number(presto_version[1])\nif (presto_version && presto_version >= 15) { presto = false; webkit = true }\n// Some browsers use the wrong event properties to signal cmd/ctrl on OS X\nexport let flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11))\nexport let captureRightClick = gecko || (ie && ie_version >= 9)\n"
  },
  {
    "path": "third_party/CodeMirror/src/util/dom.js",
    "content": "import { ie, ios } from \"./browser.js\"\n\nexport function classTest(cls) { return new RegExp(\"(^|\\\\s)\" + cls + \"(?:$|\\\\s)\\\\s*\") }\n\nexport let rmClass = function(node, cls) {\n  let current = node.className\n  let match = classTest(cls).exec(current)\n  if (match) {\n    let after = current.slice(match.index + match[0].length)\n    node.className = current.slice(0, match.index) + (after ? match[1] + after : \"\")\n  }\n}\n\nexport function removeChildren(e) {\n  for (let count = e.childNodes.length; count > 0; --count)\n    e.removeChild(e.firstChild)\n  return e\n}\n\nexport function removeChildrenAndAdd(parent, e) {\n  return removeChildren(parent).appendChild(e)\n}\n\nexport function elt(tag, content, className, style) {\n  let e = document.createElement(tag)\n  if (className) e.className = className\n  if (style) e.style.cssText = style\n  if (typeof content == \"string\") e.appendChild(document.createTextNode(content))\n  else if (content) for (let i = 0; i < content.length; ++i) e.appendChild(content[i])\n  return e\n}\n// wrapper for elt, which removes the elt from the accessibility tree\nexport function eltP(tag, content, className, style) {\n  let e = elt(tag, content, className, style)\n  e.setAttribute(\"role\", \"presentation\")\n  return e\n}\n\nexport let range\nif (document.createRange) range = function(node, start, end, endNode) {\n  let r = document.createRange()\n  r.setEnd(endNode || node, end)\n  r.setStart(node, start)\n  return r\n}\nelse range = function(node, start, end) {\n  let r = document.body.createTextRange()\n  try { r.moveToElementText(node.parentNode) }\n  catch(e) { return r }\n  r.collapse(true)\n  r.moveEnd(\"character\", end)\n  r.moveStart(\"character\", start)\n  return r\n}\n\nexport function contains(parent, child) {\n  if (child.nodeType == 3) // Android browser always returns false when child is a textnode\n    child = child.parentNode\n  if (parent.contains)\n    return parent.contains(child)\n  do {\n    if (child.nodeType == 11) child = child.host\n    if (child == parent) return true\n  } while (child = child.parentNode)\n}\n\nexport function activeElt() {\n  // IE and Edge may throw an \"Unspecified Error\" when accessing document.activeElement.\n  // IE < 10 will throw when accessed while the page is loading or in an iframe.\n  // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.\n  let activeElement\n  try {\n    activeElement = document.activeElement\n  } catch(e) {\n    activeElement = document.body || null\n  }\n  while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)\n    activeElement = activeElement.shadowRoot.activeElement\n  return activeElement\n}\n\nexport function addClass(node, cls) {\n  let current = node.className\n  if (!classTest(cls).test(current)) node.className += (current ? \" \" : \"\") + cls\n}\nexport function joinClasses(a, b) {\n  let as = a.split(\" \")\n  for (let i = 0; i < as.length; i++)\n    if (as[i] && !classTest(as[i]).test(b)) b += \" \" + as[i]\n  return b\n}\n\nexport let selectInput = function(node) { node.select() }\nif (ios) // Mobile Safari apparently has a bug where select() is broken.\n  selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length }\nelse if (ie) // Suppress mysterious IE10 errors\n  selectInput = function(node) { try { node.select() } catch(_e) {} }\n"
  },
  {
    "path": "third_party/CodeMirror/src/util/event.js",
    "content": "import { mac } from \"./browser.js\"\nimport { indexOf } from \"./misc.js\"\n\n// EVENT HANDLING\n\n// Lightweight event framework. on/off also work on DOM nodes,\n// registering native DOM handlers.\n\nconst noHandlers = []\n\nexport let on = function(emitter, type, f) {\n  if (emitter.addEventListener) {\n    emitter.addEventListener(type, f, false)\n  } else if (emitter.attachEvent) {\n    emitter.attachEvent(\"on\" + type, f)\n  } else {\n    let map = emitter._handlers || (emitter._handlers = {})\n    map[type] = (map[type] || noHandlers).concat(f)\n  }\n}\n\nexport function getHandlers(emitter, type) {\n  return emitter._handlers && emitter._handlers[type] || noHandlers\n}\n\nexport function off(emitter, type, f) {\n  if (emitter.removeEventListener) {\n    emitter.removeEventListener(type, f, false)\n  } else if (emitter.detachEvent) {\n    emitter.detachEvent(\"on\" + type, f)\n  } else {\n    let map = emitter._handlers, arr = map && map[type]\n    if (arr) {\n      let index = indexOf(arr, f)\n      if (index > -1)\n        map[type] = arr.slice(0, index).concat(arr.slice(index + 1))\n    }\n  }\n}\n\nexport function signal(emitter, type /*, values...*/) {\n  let handlers = getHandlers(emitter, type)\n  if (!handlers.length) return\n  let args = Array.prototype.slice.call(arguments, 2)\n  for (let i = 0; i < handlers.length; ++i) handlers[i].apply(null, args)\n}\n\n// The DOM events that CodeMirror handles can be overridden by\n// registering a (non-DOM) handler on the editor for the event name,\n// and preventDefault-ing the event in that handler.\nexport function signalDOMEvent(cm, e, override) {\n  if (typeof e == \"string\")\n    e = {type: e, preventDefault: function() { this.defaultPrevented = true }}\n  signal(cm, override || e.type, cm, e)\n  return e_defaultPrevented(e) || e.codemirrorIgnore\n}\n\nexport function signalCursorActivity(cm) {\n  let arr = cm._handlers && cm._handlers.cursorActivity\n  if (!arr) return\n  let set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])\n  for (let i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)\n    set.push(arr[i])\n}\n\nexport function hasHandler(emitter, type) {\n  return getHandlers(emitter, type).length > 0\n}\n\n// Add on and off methods to a constructor's prototype, to make\n// registering events on such objects more convenient.\nexport function eventMixin(ctor) {\n  ctor.prototype.on = function(type, f) {on(this, type, f)}\n  ctor.prototype.off = function(type, f) {off(this, type, f)}\n}\n\n// Due to the fact that we still support jurassic IE versions, some\n// compatibility wrappers are needed.\n\nexport function e_preventDefault(e) {\n  if (e.preventDefault) e.preventDefault()\n  else e.returnValue = false\n}\nexport function e_stopPropagation(e) {\n  if (e.stopPropagation) e.stopPropagation()\n  else e.cancelBubble = true\n}\nexport function e_defaultPrevented(e) {\n  return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false\n}\nexport function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)}\n\nexport function e_target(e) {return e.target || e.srcElement}\nexport function e_button(e) {\n  let b = e.which\n  if (b == null) {\n    if (e.button & 1) b = 1\n    else if (e.button & 2) b = 3\n    else if (e.button & 4) b = 2\n  }\n  if (mac && e.ctrlKey && b == 1) b = 3\n  return b\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/util/feature_detection.js",
    "content": "import { elt, range, removeChildren, removeChildrenAndAdd } from \"./dom.js\"\nimport { ie, ie_version } from \"./browser.js\"\n\n// Detect drag-and-drop\nexport let dragAndDrop = function() {\n  // There is *some* kind of drag-and-drop support in IE6-8, but I\n  // couldn't get it to work yet.\n  if (ie && ie_version < 9) return false\n  let div = elt('div')\n  return \"draggable\" in div || \"dragDrop\" in div\n}()\n\nlet zwspSupported\nexport function zeroWidthElement(measure) {\n  if (zwspSupported == null) {\n    let test = elt(\"span\", \"\\u200b\")\n    removeChildrenAndAdd(measure, elt(\"span\", [test, document.createTextNode(\"x\")]))\n    if (measure.firstChild.offsetHeight != 0)\n      zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8)\n  }\n  let node = zwspSupported ? elt(\"span\", \"\\u200b\") :\n    elt(\"span\", \"\\u00a0\", null, \"display: inline-block; width: 1px; margin-right: -1px\")\n  node.setAttribute(\"cm-text\", \"\")\n  return node\n}\n\n// Feature-detect IE's crummy client rect reporting for bidi text\nlet badBidiRects\nexport function hasBadBidiRects(measure) {\n  if (badBidiRects != null) return badBidiRects\n  let txt = removeChildrenAndAdd(measure, document.createTextNode(\"A\\u062eA\"))\n  let r0 = range(txt, 0, 1).getBoundingClientRect()\n  let r1 = range(txt, 1, 2).getBoundingClientRect()\n  removeChildren(measure)\n  if (!r0 || r0.left == r0.right) return false // Safari returns null in some cases (#2780)\n  return badBidiRects = (r1.right - r0.right < 3)\n}\n\n// See if \"\".split is the broken IE version, if so, provide an\n// alternative way to split lines.\nexport let splitLinesAuto = \"\\n\\nb\".split(/\\n/).length != 3 ? string => {\n  let pos = 0, result = [], l = string.length\n  while (pos <= l) {\n    let nl = string.indexOf(\"\\n\", pos)\n    if (nl == -1) nl = string.length\n    let line = string.slice(pos, string.charAt(nl - 1) == \"\\r\" ? nl - 1 : nl)\n    let rt = line.indexOf(\"\\r\")\n    if (rt != -1) {\n      result.push(line.slice(0, rt))\n      pos += rt + 1\n    } else {\n      result.push(line)\n      pos = nl + 1\n    }\n  }\n  return result\n} : string => string.split(/\\r\\n?|\\n/)\n\nexport let hasSelection = window.getSelection ? te => {\n  try { return te.selectionStart != te.selectionEnd }\n  catch(e) { return false }\n} : te => {\n  let range\n  try {range = te.ownerDocument.selection.createRange()}\n  catch(e) {}\n  if (!range || range.parentElement() != te) return false\n  return range.compareEndPoints(\"StartToEnd\", range) != 0\n}\n\nexport let hasCopyEvent = (() => {\n  let e = elt(\"div\")\n  if (\"oncopy\" in e) return true\n  e.setAttribute(\"oncopy\", \"return;\")\n  return typeof e.oncopy == \"function\"\n})()\n\nlet badZoomedRects = null\nexport function hasBadZoomedRects(measure) {\n  if (badZoomedRects != null) return badZoomedRects\n  let node = removeChildrenAndAdd(measure, elt(\"span\", \"x\"))\n  let normal = node.getBoundingClientRect()\n  let fromRange = range(node, 0, 1).getBoundingClientRect()\n  return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/util/misc.js",
    "content": "export function bind(f) {\n  let args = Array.prototype.slice.call(arguments, 1)\n  return function(){return f.apply(null, args)}\n}\n\nexport function copyObj(obj, target, overwrite) {\n  if (!target) target = {}\n  for (let prop in obj)\n    if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))\n      target[prop] = obj[prop]\n  return target\n}\n\n// Counts the column offset in a string, taking tabs into account.\n// Used mostly to find indentation.\nexport function countColumn(string, end, tabSize, startIndex, startValue) {\n  if (end == null) {\n    end = string.search(/[^\\s\\u00a0]/)\n    if (end == -1) end = string.length\n  }\n  for (let i = startIndex || 0, n = startValue || 0;;) {\n    let nextTab = string.indexOf(\"\\t\", i)\n    if (nextTab < 0 || nextTab >= end)\n      return n + (end - i)\n    n += nextTab - i\n    n += tabSize - (n % tabSize)\n    i = nextTab + 1\n  }\n}\n\nexport class Delayed {\n  constructor() {this.id = null}\n  set(ms, f) {\n    clearTimeout(this.id)\n    this.id = setTimeout(f, ms)\n  }\n}\n\nexport function indexOf(array, elt) {\n  for (let i = 0; i < array.length; ++i)\n    if (array[i] == elt) return i\n  return -1\n}\n\n// Number of pixels added to scroller and sizer to hide scrollbar\nexport let scrollerGap = 30\n\n// Returned or thrown by various protocols to signal 'I'm not\n// handling this'.\nexport let Pass = {toString: function(){return \"CodeMirror.Pass\"}}\n\n// Reused option objects for setSelection & friends\nexport let sel_dontScroll = {scroll: false}, sel_mouse = {origin: \"*mouse\"}, sel_move = {origin: \"+move\"}\n\n// The inverse of countColumn -- find the offset that corresponds to\n// a particular column.\nexport function findColumn(string, goal, tabSize) {\n  for (let pos = 0, col = 0;;) {\n    let nextTab = string.indexOf(\"\\t\", pos)\n    if (nextTab == -1) nextTab = string.length\n    let skipped = nextTab - pos\n    if (nextTab == string.length || col + skipped >= goal)\n      return pos + Math.min(skipped, goal - col)\n    col += nextTab - pos\n    col += tabSize - (col % tabSize)\n    pos = nextTab + 1\n    if (col >= goal) return pos\n  }\n}\n\nlet spaceStrs = [\"\"]\nexport function spaceStr(n) {\n  while (spaceStrs.length <= n)\n    spaceStrs.push(lst(spaceStrs) + \" \")\n  return spaceStrs[n]\n}\n\nexport function lst(arr) { return arr[arr.length-1] }\n\nexport function map(array, f) {\n  let out = []\n  for (let i = 0; i < array.length; i++) out[i] = f(array[i], i)\n  return out\n}\n\nexport function insertSorted(array, value, score) {\n  let pos = 0, priority = score(value)\n  while (pos < array.length && score(array[pos]) <= priority) pos++\n  array.splice(pos, 0, value)\n}\n\nfunction nothing() {}\n\nexport function createObj(base, props) {\n  let inst\n  if (Object.create) {\n    inst = Object.create(base)\n  } else {\n    nothing.prototype = base\n    inst = new nothing()\n  }\n  if (props) copyObj(props, inst)\n  return inst\n}\n\nlet nonASCIISingleCaseWordChar = /[\\u00df\\u0587\\u0590-\\u05f4\\u0600-\\u06ff\\u3040-\\u309f\\u30a0-\\u30ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\uac00-\\ud7af]/\nexport function isWordCharBasic(ch) {\n  return /\\w/.test(ch) || ch > \"\\x80\" &&\n    (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))\n}\nexport function isWordChar(ch, helper) {\n  if (!helper) return isWordCharBasic(ch)\n  if (helper.source.indexOf(\"\\\\w\") > -1 && isWordCharBasic(ch)) return true\n  return helper.test(ch)\n}\n\nexport function isEmpty(obj) {\n  for (let n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false\n  return true\n}\n\n// Extending unicode characters. A series of a non-extending char +\n// any number of extending chars is treated as a single unit as far\n// as editing and measuring is concerned. This is not fully correct,\n// since some scripts/fonts/browsers also treat other configurations\n// of code points as a group.\nlet extendingChars = /[\\u0300-\\u036f\\u0483-\\u0489\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u065e\\u0670\\u06d6-\\u06dc\\u06de-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07eb-\\u07f3\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0900-\\u0902\\u093c\\u0941-\\u0948\\u094d\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09bc\\u09be\\u09c1-\\u09c4\\u09cd\\u09d7\\u09e2\\u09e3\\u0a01\\u0a02\\u0a3c\\u0a41\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a70\\u0a71\\u0a75\\u0a81\\u0a82\\u0abc\\u0ac1-\\u0ac5\\u0ac7\\u0ac8\\u0acd\\u0ae2\\u0ae3\\u0b01\\u0b3c\\u0b3e\\u0b3f\\u0b41-\\u0b44\\u0b4d\\u0b56\\u0b57\\u0b62\\u0b63\\u0b82\\u0bbe\\u0bc0\\u0bcd\\u0bd7\\u0c3e-\\u0c40\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0cbc\\u0cbf\\u0cc2\\u0cc6\\u0ccc\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0d3e\\u0d41-\\u0d44\\u0d4d\\u0d57\\u0d62\\u0d63\\u0dca\\u0dcf\\u0dd2-\\u0dd4\\u0dd6\\u0ddf\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0eb1\\u0eb4-\\u0eb9\\u0ebb\\u0ebc\\u0ec8-\\u0ecd\\u0f18\\u0f19\\u0f35\\u0f37\\u0f39\\u0f71-\\u0f7e\\u0f80-\\u0f84\\u0f86\\u0f87\\u0f90-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102d-\\u1030\\u1032-\\u1037\\u1039\\u103a\\u103d\\u103e\\u1058\\u1059\\u105e-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108d\\u109d\\u135f\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b7-\\u17bd\\u17c6\\u17c9-\\u17d3\\u17dd\\u180b-\\u180d\\u18a9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193b\\u1a17\\u1a18\\u1a56\\u1a58-\\u1a5e\\u1a60\\u1a62\\u1a65-\\u1a6c\\u1a73-\\u1a7c\\u1a7f\\u1b00-\\u1b03\\u1b34\\u1b36-\\u1b3a\\u1b3c\\u1b42\\u1b6b-\\u1b73\\u1b80\\u1b81\\u1ba2-\\u1ba5\\u1ba8\\u1ba9\\u1c2c-\\u1c33\\u1c36\\u1c37\\u1cd0-\\u1cd2\\u1cd4-\\u1ce0\\u1ce2-\\u1ce8\\u1ced\\u1dc0-\\u1de6\\u1dfd-\\u1dff\\u200c\\u200d\\u20d0-\\u20f0\\u2cef-\\u2cf1\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua66f-\\ua672\\ua67c\\ua67d\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua825\\ua826\\ua8c4\\ua8e0-\\ua8f1\\ua926-\\ua92d\\ua947-\\ua951\\ua980-\\ua982\\ua9b3\\ua9b6-\\ua9b9\\ua9bc\\uaa29-\\uaa2e\\uaa31\\uaa32\\uaa35\\uaa36\\uaa43\\uaa4c\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uabe5\\uabe8\\uabed\\udc00-\\udfff\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe26\\uff9e\\uff9f]/\nexport function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }\n\n// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.\nexport function skipExtendingChars(str, pos, dir) {\n  while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) pos += dir\n  return pos\n}\n\n// Returns the value from the range [`from`; `to`] that satisfies\n// `pred` and is closest to `from`. Assumes that at least `to`\n// satisfies `pred`. Supports `from` being greater than `to`.\nexport function findFirst(pred, from, to) {\n  // At any point we are certain `to` satisfies `pred`, don't know\n  // whether `from` does.\n  let dir = from > to ? -1 : 1\n  for (;;) {\n    if (from == to) return from\n    let midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF)\n    if (mid == from) return pred(mid) ? from : to\n    if (pred(mid)) to = mid\n    else from = mid + dir\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/src/util/operation_group.js",
    "content": "import { getHandlers } from \"./event.js\"\n\nlet operationGroup = null\n\nexport function pushOperation(op) {\n  if (operationGroup) {\n    operationGroup.ops.push(op)\n  } else {\n    op.ownsGroup = operationGroup = {\n      ops: [op],\n      delayedCallbacks: []\n    }\n  }\n}\n\nfunction fireCallbacksForOps(group) {\n  // Calls delayed callbacks and cursorActivity handlers until no\n  // new ones appear\n  let callbacks = group.delayedCallbacks, i = 0\n  do {\n    for (; i < callbacks.length; i++)\n      callbacks[i].call(null)\n    for (let j = 0; j < group.ops.length; j++) {\n      let op = group.ops[j]\n      if (op.cursorActivityHandlers)\n        while (op.cursorActivityCalled < op.cursorActivityHandlers.length)\n          op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm)\n    }\n  } while (i < callbacks.length)\n}\n\nexport function finishOperation(op, endCb) {\n  let group = op.ownsGroup\n  if (!group) return\n\n  try { fireCallbacksForOps(group) }\n  finally {\n    operationGroup = null\n    endCb(group)\n  }\n}\n\nlet orphanDelayedCallbacks = null\n\n// Often, we want to signal events at a point where we are in the\n// middle of some work, but don't want the handler to start calling\n// other methods on the editor, which might be in an inconsistent\n// state or simply not expect any other events to happen.\n// signalLater looks whether there are any handlers, and schedules\n// them to be executed when the last operation ends, or, if no\n// operation is active, when a timeout fires.\nexport function signalLater(emitter, type /*, values...*/) {\n  let arr = getHandlers(emitter, type)\n  if (!arr.length) return\n  let args = Array.prototype.slice.call(arguments, 2), list\n  if (operationGroup) {\n    list = operationGroup.delayedCallbacks\n  } else if (orphanDelayedCallbacks) {\n    list = orphanDelayedCallbacks\n  } else {\n    list = orphanDelayedCallbacks = []\n    setTimeout(fireOrphanDelayed, 0)\n  }\n  for (let i = 0; i < arr.length; ++i)\n    list.push(() => arr[i].apply(null, args))\n}\n\nfunction fireOrphanDelayed() {\n  let delayed = orphanDelayedCallbacks\n  orphanDelayedCallbacks = null\n  for (let i = 0; i < delayed.length; ++i) delayed[i]()\n}\n"
  },
  {
    "path": "third_party/CodeMirror/test/comment_test.js",
    "content": "namespace = \"comment_\";\n\n(function() {\n  function test(name, mode, run, before, after) {\n    return testCM(name, function(cm) {\n      run(cm);\n      eq(cm.getValue(), after);\n    }, {value: before, mode: mode});\n  }\n\n  var simpleProg = \"function foo() {\\n  return bar;\\n}\";\n  var inlineBlock = \"foo(/* bar */ true);\";\n  var inlineBlocks = \"foo(/* bar */ true, /* baz */ false);\";\n  var multiLineInlineBlock = [\"above();\", \"foo(/* bar */ true);\", \"below();\"];\n\n  test(\"block\", \"javascript\", function(cm) {\n    cm.blockComment(Pos(0, 3), Pos(3, 0), {blockCommentLead: \" *\"});\n  }, simpleProg + \"\\n\", \"/* function foo() {\\n *   return bar;\\n * }\\n */\");\n\n  test(\"blockToggle\", \"javascript\", function(cm) {\n    cm.blockComment(Pos(0, 3), Pos(2, 0), {blockCommentLead: \" *\"});\n    cm.uncomment(Pos(0, 3), Pos(2, 0), {blockCommentLead: \" *\"});\n  }, simpleProg, simpleProg);\n\n  test(\"blockToggle2\", \"javascript\", function(cm) {\n    cm.setCursor({line: 0, ch: 7 /* inside the block comment */});\n    cm.execCommand(\"toggleComment\");\n  }, inlineBlock, \"foo(bar true);\");\n\n  // This test should work but currently fails.\n  // test(\"blockToggle3\", \"javascript\", function(cm) {\n  //   cm.setCursor({line: 0, ch: 7 /* inside the first block comment */});\n  //   cm.execCommand(\"toggleComment\");\n  // }, inlineBlocks, \"foo(bar true, /* baz */ false);\");\n\n  test(\"line\", \"javascript\", function(cm) {\n    cm.lineComment(Pos(1, 1), Pos(1, 1));\n  }, simpleProg, \"function foo() {\\n//   return bar;\\n}\");\n\n  test(\"lineToggle\", \"javascript\", function(cm) {\n    cm.lineComment(Pos(0, 0), Pos(2, 1));\n    cm.uncomment(Pos(0, 0), Pos(2, 1));\n  }, simpleProg, simpleProg);\n\n  test(\"fallbackToBlock\", \"css\", function(cm) {\n    cm.lineComment(Pos(0, 0), Pos(2, 1));\n  }, \"html {\\n  border: none;\\n}\", \"/* html {\\n  border: none;\\n} */\");\n\n  test(\"fallbackToLine\", \"ruby\", function(cm) {\n    cm.blockComment(Pos(0, 0), Pos(1));\n  }, \"def blah()\\n  return hah\\n\", \"# def blah()\\n#   return hah\\n\");\n\n  test(\"ignoreExternalBlockComments\", \"javascript\", function(cm) {\n    cm.execCommand(\"toggleComment\");\n  }, inlineBlocks, \"// \" + inlineBlocks);\n\n  test(\"ignoreExternalBlockComments2\", \"javascript\", function(cm) {\n    cm.setCursor({line: 0, ch: null /* eol */});\n    cm.execCommand(\"toggleComment\");\n  }, inlineBlocks, \"// \" + inlineBlocks);\n\n  test(\"ignoreExternalBlockCommentsMultiLineAbove\", \"javascript\", function(cm) {\n    cm.setSelection({line: 0, ch: 0}, {line: 1, ch: 1});\n    cm.execCommand(\"toggleComment\");\n  }, multiLineInlineBlock.join(\"\\n\"), [\"// \" + multiLineInlineBlock[0],\n                                       \"// \" + multiLineInlineBlock[1],\n                                       multiLineInlineBlock[2]].join(\"\\n\"));\n\n  test(\"ignoreExternalBlockCommentsMultiLineBelow\", \"javascript\", function(cm) {\n    cm.setSelection({line: 1, ch: 13 /* after end of block comment */}, {line: 2, ch: 1});\n    cm.execCommand(\"toggleComment\");\n  }, multiLineInlineBlock.join(\"\\n\"), [multiLineInlineBlock[0],\n                                       \"// \" + multiLineInlineBlock[1],\n                                       \"// \" + multiLineInlineBlock[2]].join(\"\\n\"));\n\n  test(\"commentRange\", \"javascript\", function(cm) {\n    cm.blockComment(Pos(1, 2), Pos(1, 13), {fullLines: false});\n  }, simpleProg, \"function foo() {\\n  /*return bar;*/\\n}\");\n\n  test(\"indented\", \"javascript\", function(cm) {\n    cm.lineComment(Pos(1, 0), Pos(2), {indent: true});\n  }, simpleProg, \"function foo() {\\n//   return bar;\\n// }\");\n\n  test(\"singleEmptyLine\", \"javascript\", function(cm) {\n    cm.setCursor(1);\n    cm.execCommand(\"toggleComment\");\n  }, \"a;\\n\\nb;\", \"a;\\n// \\nb;\");\n\n  test(\"dontMessWithStrings\", \"javascript\", function(cm) {\n    cm.execCommand(\"toggleComment\");\n  }, \"console.log(\\\"/*string*/\\\");\", \"// console.log(\\\"/*string*/\\\");\");\n\n  test(\"dontMessWithStrings2\", \"javascript\", function(cm) {\n    cm.execCommand(\"toggleComment\");\n  }, \"console.log(\\\"// string\\\");\", \"// console.log(\\\"// string\\\");\");\n\n  test(\"dontMessWithStrings3\", \"javascript\", function(cm) {\n    cm.execCommand(\"toggleComment\");\n  }, \"// console.log(\\\"// string\\\");\", \"console.log(\\\"// string\\\");\");\n\n  test(\"includeLastLine\", \"javascript\", function(cm) {\n    cm.execCommand(\"selectAll\")\n    cm.execCommand(\"toggleComment\")\n  }, \"// foo\\n// bar\\nbaz\", \"// // foo\\n// // bar\\n// baz\")\n\n  test(\"uncommentWithTrailingBlockEnd\", \"xml\", function(cm) {\n    cm.execCommand(\"toggleComment\")\n  }, \"<!-- foo --> -->\", \"foo -->\")\n\n  test(\"dontCommentInComment\", \"xml\", function(cm) {\n    cm.setCursor(1, 0)\n    cm.execCommand(\"toggleComment\")\n  }, \"<!-- foo\\nbar -->\", \"<!-- foo\\nbar -->\")\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/contenteditable_test.js",
    "content": "(function() {\n  \"use strict\";\n\n  namespace = \"contenteditable_\";\n  var Pos = CodeMirror.Pos\n\n  function findTextNode(dom, text) {\n    if (dom instanceof CodeMirror) dom = dom.getInputField()\n    if (dom.nodeType == 1) {\n      for (var ch = dom.firstChild; ch; ch = ch.nextSibling) {\n        var found = findTextNode(ch, text)\n        if (found) return found\n      }\n    } else if (dom.nodeType == 3 && dom.nodeValue == text) {\n      return dom\n    }\n  }\n\n  function lineElt(node) {\n    for (;;) {\n      var parent = node.parentNode\n      if (/CodeMirror-code/.test(parent.className)) return node\n      node = parent\n    }\n  }\n\n  testCM(\"insert_text\", function(cm) {\n    findTextNode(cm, \"foobar\").nodeValue = \"foo bar\"\n    cm.display.input.updateFromDOM()\n    eq(cm.getValue(), \"foo bar\")\n  }, {inputStyle: \"contenteditable\", value: \"foobar\"})\n\n  testCM(\"split_line\", function(cm) {\n    cm.setSelection(Pos(2, 3))\n    var node = findTextNode(cm, \"foobar\")\n    node.nodeValue = \"foo\"\n    var lineNode = lineElt(node)\n    lineNode.parentNode.insertBefore(document.createElement(\"pre\"), lineNode.nextSibling).textContent = \"bar\"\n    cm.display.input.updateFromDOM()\n    eq(cm.getValue(), \"one\\ntwo\\nfoo\\nbar\\nthree\\nfour\\n\")\n  }, {inputStyle: \"contenteditable\", value: \"one\\ntwo\\nfoobar\\nthree\\nfour\\n\"})\n\n  testCM(\"join_line\", function(cm) {\n    cm.setSelection(Pos(2, 3))\n    var node = findTextNode(cm, \"foo\")\n    node.nodeValue = \"foobar\"\n    var lineNode = lineElt(node)\n    lineNode.parentNode.removeChild(lineNode.nextSibling)\n    cm.display.input.updateFromDOM()\n    eq(cm.getValue(), \"one\\ntwo\\nfoobar\\nthree\\nfour\\n\")\n  }, {inputStyle: \"contenteditable\", value: \"one\\ntwo\\nfoo\\nbar\\nthree\\nfour\\n\"})\n\n  testCM(\"delete_multiple\", function(cm) {\n    cm.setSelection(Pos(1, 3), Pos(4, 0))\n    var text = findTextNode(cm, \"two\"), startLine = lineElt(text)\n    for (var i = 0; i < 3; i++)\n      startLine.parentNode.removeChild(startLine.nextSibling)\n    text.nodeValue = \"twothree\"\n    cm.display.input.updateFromDOM()\n    eq(cm.getValue(), \"one\\ntwothree\\nfour\\n\")\n  }, {inputStyle: \"contenteditable\", value: \"one\\ntwo\\nfoo\\nbar\\nthree\\nfour\\n\"})\n\n  testCM(\"ambiguous_diff_middle\", function(cm) {\n    cm.setSelection(Pos(0, 2))\n    findTextNode(cm, \"baah\").nodeValue = \"baaah\"\n    cm.display.input.updateFromDOM()\n    eqCharPos(cm.getCursor(), Pos(0, 3))\n  }, {inputStyle: \"contenteditable\", value: \"baah\"})\n\n  testCM(\"ambiguous_diff_start\", function(cm) {\n    cm.setSelection(Pos(0, 1))\n    findTextNode(cm, \"baah\").nodeValue = \"baaah\"\n    cm.display.input.updateFromDOM()\n    eqCharPos(cm.getCursor(), Pos(0, 2))\n  }, {inputStyle: \"contenteditable\", value: \"baah\"})\n\n  testCM(\"ambiguous_diff_end\", function(cm) {\n    cm.setSelection(Pos(0, 3))\n    findTextNode(cm, \"baah\").nodeValue = \"baaah\"\n    cm.display.input.updateFromDOM()\n    eqCharPos(cm.getCursor(), Pos(0, 4))\n  }, {inputStyle: \"contenteditable\", value: \"baah\"})\n\n  testCM(\"force_redraw\", function(cm) {\n    findTextNode(cm, \"foo\").parentNode.appendChild(document.createElement(\"hr\")).className = \"inserted\"\n    cm.display.input.updateFromDOM()\n    eq(byClassName(cm.getInputField(), \"inserted\").length, 0)\n  }, {inputStyle: \"contenteditable\", value: \"foo\"})\n\n  testCM(\"type_on_empty_line\", function(cm) {\n    cm.setSelection(Pos(1, 0))\n    findTextNode(cm, \"\\u200b\").nodeValue += \"hello\"\n    cm.display.input.updateFromDOM()\n    eq(cm.getValue(), \"foo\\nhello\\nbar\")\n  }, {inputStyle: \"contenteditable\", value: \"foo\\n\\nbar\"})\n\n  testCM(\"type_after_empty_line\", function(cm) {\n    cm.setSelection(Pos(2, 0))\n    findTextNode(cm, \"bar\").nodeValue = \"hellobar\"\n    cm.display.input.updateFromDOM()\n    eq(cm.getValue(), \"foo\\n\\nhellobar\")\n  }, {inputStyle: \"contenteditable\", value: \"foo\\n\\nbar\"})\n\n  testCM(\"type_before_empty_line\", function(cm) {\n    cm.setSelection(Pos(0, 3))\n    findTextNode(cm, \"foo\").nodeValue = \"foohello\"\n    cm.display.input.updateFromDOM()\n    eq(cm.getValue(), \"foohello\\n\\nbar\")\n  }, {inputStyle: \"contenteditable\", value: \"foo\\n\\nbar\"})\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/doc_test.js",
    "content": "(function() {\n  // A minilanguage for instantiating linked CodeMirror instances and Docs\n  function instantiateSpec(spec, place, opts) {\n    var names = {}, pos = 0, l = spec.length, editors = [];\n    while (spec) {\n      var m = spec.match(/^(\\w+)(\\*?)(?:='([^\\']*)'|<(~?)(\\w+)(?:\\/(\\d+)-(\\d+))?)\\s*/);\n      var name = m[1], isDoc = m[2], cur;\n      if (m[3]) {\n        cur = isDoc ? CodeMirror.Doc(m[3]) : CodeMirror(place, clone(opts, {value: m[3]}));\n      } else {\n        var other = m[5];\n        if (!names.hasOwnProperty(other)) {\n          names[other] = editors.length;\n          editors.push(CodeMirror(place, opts));\n        }\n        var doc = editors[names[other]].linkedDoc({\n          sharedHist: !m[4],\n          from: m[6] ? Number(m[6]) : null,\n          to: m[7] ? Number(m[7]) : null\n        });\n        cur = isDoc ? doc : CodeMirror(place, clone(opts, {value: doc}));\n      }\n      names[name] = editors.length;\n      editors.push(cur);\n      spec = spec.slice(m[0].length);\n    }\n    return editors;\n  }\n\n  function clone(obj, props) {\n    if (!obj) return;\n    clone.prototype = obj;\n    var inst = new clone();\n    if (props) for (var n in props) if (props.hasOwnProperty(n))\n      inst[n] = props[n];\n    return inst;\n  }\n\n  function eqAll(val) {\n    var end = arguments.length, msg = null;\n    if (typeof arguments[end-1] == \"string\")\n      msg = arguments[--end];\n    if (i == end) throw new Error(\"No editors provided to eqAll\");\n    for (var i = 1; i < end; ++i)\n      eq(arguments[i].getValue(), val, msg)\n  }\n\n  function testDoc(name, spec, run, opts, expectFail) {\n    if (!opts) opts = {};\n\n    return test(\"doc_\" + name, function() {\n      var place = document.getElementById(\"testground\");\n      var editors = instantiateSpec(spec, place, opts);\n      var successful = false;\n\n      try {\n        run.apply(null, editors);\n        successful = true;\n      } finally {\n        if (!successful || verbose) {\n          place.style.visibility = \"visible\";\n        } else {\n          for (var i = 0; i < editors.length; ++i)\n            if (editors[i] instanceof CodeMirror)\n              place.removeChild(editors[i].getWrapperElement());\n        }\n      }\n    }, expectFail);\n  }\n\n  var ie_lt8 = /MSIE [1-7]\\b/.test(navigator.userAgent);\n\n  function testBasic(a, b) {\n    eqAll(\"x\", a, b);\n    a.setValue(\"hey\");\n    eqAll(\"hey\", a, b);\n    b.setValue(\"wow\");\n    eqAll(\"wow\", a, b);\n    a.replaceRange(\"u\\nv\\nw\", Pos(0, 3));\n    b.replaceRange(\"i\", Pos(0, 4));\n    b.replaceRange(\"j\", Pos(2, 1));\n    eqAll(\"wowui\\nv\\nwj\", a, b);\n  }\n\n  testDoc(\"basic\", \"A='x' B<A\", testBasic);\n  testDoc(\"basicSeparate\", \"A='x' B<~A\", testBasic);\n\n  testDoc(\"sharedHist\", \"A='ab\\ncd\\nef' B<A\", function(a, b) {\n    a.replaceRange(\"x\", Pos(0));\n    b.replaceRange(\"y\", Pos(1));\n    a.replaceRange(\"z\", Pos(2));\n    eqAll(\"abx\\ncdy\\nefz\", a, b);\n    a.undo();\n    a.undo();\n    eqAll(\"abx\\ncd\\nef\", a, b);\n    a.redo();\n    eqAll(\"abx\\ncdy\\nef\", a, b);\n    b.redo();\n    eqAll(\"abx\\ncdy\\nefz\", a, b);\n    a.undo(); b.undo(); a.undo(); a.undo();\n    eqAll(\"ab\\ncd\\nef\", a, b);\n  }, null, ie_lt8);\n\n  testDoc(\"undoIntact\", \"A='ab\\ncd\\nef' B<~A\", function(a, b) {\n    a.replaceRange(\"x\", Pos(0));\n    b.replaceRange(\"y\", Pos(1));\n    a.replaceRange(\"z\", Pos(2));\n    a.replaceRange(\"q\", Pos(0));\n    eqAll(\"abxq\\ncdy\\nefz\", a, b);\n    a.undo();\n    a.undo();\n    eqAll(\"abx\\ncdy\\nef\", a, b);\n    b.undo();\n    eqAll(\"abx\\ncd\\nef\", a, b);\n    a.redo();\n    eqAll(\"abx\\ncd\\nefz\", a, b);\n    a.redo();\n    eqAll(\"abxq\\ncd\\nefz\", a, b);\n    a.undo(); a.undo(); a.undo(); a.undo();\n    eqAll(\"ab\\ncd\\nef\", a, b);\n    b.redo();\n    eqAll(\"ab\\ncdy\\nef\", a, b);\n  });\n\n  testDoc(\"undoConflict\", \"A='ab\\ncd\\nef' B<~A\", function(a, b) {\n    a.replaceRange(\"x\", Pos(0));\n    a.replaceRange(\"z\", Pos(2));\n    // This should clear the first undo event in a, but not the second\n    b.replaceRange(\"y\", Pos(0));\n    a.undo(); a.undo();\n    eqAll(\"abxy\\ncd\\nef\", a, b);\n    a.replaceRange(\"u\", Pos(2));\n    a.replaceRange(\"v\", Pos(0));\n    // This should clear both events in a\n    b.replaceRange(\"w\", Pos(0));\n    a.undo(); a.undo();\n    eqAll(\"abxyvw\\ncd\\nefu\", a, b);\n  });\n\n  testDoc(\"doubleRebase\", \"A='ab\\ncd\\nef\\ng' B<~A C<B\", function(a, b, c) {\n    c.replaceRange(\"u\", Pos(3));\n    a.replaceRange(\"\", Pos(0, 0), Pos(1, 0));\n    c.undo();\n    eqAll(\"cd\\nef\\ng\", a, b, c);\n  });\n\n  testDoc(\"undoUpdate\", \"A='ab\\ncd\\nef' B<~A\", function(a, b) {\n    a.replaceRange(\"x\", Pos(2));\n    b.replaceRange(\"u\\nv\\nw\\n\", Pos(0, 0));\n    a.undo();\n    eqAll(\"u\\nv\\nw\\nab\\ncd\\nef\", a, b);\n    a.redo();\n    eqAll(\"u\\nv\\nw\\nab\\ncd\\nefx\", a, b);\n    a.undo();\n    eqAll(\"u\\nv\\nw\\nab\\ncd\\nef\", a, b);\n    b.undo();\n    a.redo();\n    eqAll(\"ab\\ncd\\nefx\", a, b);\n    a.undo();\n    eqAll(\"ab\\ncd\\nef\", a, b);\n  });\n\n  testDoc(\"undoKeepRanges\", \"A='abcdefg' B<A\", function(a, b) {\n    var m = a.markText(Pos(0, 1), Pos(0, 3), {className: \"foo\"});\n    b.replaceRange(\"x\", Pos(0, 0));\n    eqCharPos(m.find().from, Pos(0, 2));\n    b.replaceRange(\"yzzy\", Pos(0, 1), Pos(0));\n    eq(m.find(), null);\n    b.undo();\n    eqCharPos(m.find().from, Pos(0, 2));\n    b.undo();\n    eqCharPos(m.find().from, Pos(0, 1));\n  });\n\n  testDoc(\"longChain\", \"A='uv' B<A C<B D<C\", function(a, b, c, d) {\n    a.replaceSelection(\"X\");\n    eqAll(\"Xuv\", a, b, c, d);\n    d.replaceRange(\"Y\", Pos(0));\n    eqAll(\"XuvY\", a, b, c, d);\n  });\n\n  testDoc(\"broadCast\", \"B<A C<A D<A E<A\", function(a, b, c, d, e) {\n    b.setValue(\"uu\");\n    eqAll(\"uu\", a, b, c, d, e);\n    a.replaceRange(\"v\", Pos(0, 1));\n    eqAll(\"uvu\", a, b, c, d, e);\n  });\n\n  // A and B share a history, C and D share a separate one\n  testDoc(\"islands\", \"A='x\\ny\\nz' B<A C<~A D<C\", function(a, b, c, d) {\n    a.replaceRange(\"u\", Pos(0));\n    d.replaceRange(\"v\", Pos(2));\n    b.undo();\n    eqAll(\"x\\ny\\nzv\", a, b, c, d);\n    c.undo();\n    eqAll(\"x\\ny\\nz\", a, b, c, d);\n    a.redo();\n    eqAll(\"xu\\ny\\nz\", a, b, c, d);\n    d.redo();\n    eqAll(\"xu\\ny\\nzv\", a, b, c, d);\n  });\n\n  testDoc(\"unlink\", \"B<A C<A D<B\", function(a, b, c, d) {\n    a.setValue(\"hi\");\n    b.unlinkDoc(a);\n    d.setValue(\"aye\");\n    eqAll(\"hi\", a, c);\n    eqAll(\"aye\", b, d);\n    a.setValue(\"oo\");\n    eqAll(\"oo\", a, c);\n    eqAll(\"aye\", b, d);\n  });\n\n  testDoc(\"bareDoc\", \"A*='foo' B*<A C<B\", function(a, b, c) {\n    is(a instanceof CodeMirror.Doc);\n    is(b instanceof CodeMirror.Doc);\n    is(c instanceof CodeMirror);\n    eqAll(\"foo\", a, b, c);\n    a.replaceRange(\"hey\", Pos(0, 0), Pos(0));\n    c.replaceRange(\"!\", Pos(0));\n    eqAll(\"hey!\", a, b, c);\n    b.unlinkDoc(a);\n    b.setValue(\"x\");\n    eqAll(\"x\", b, c);\n    eqAll(\"hey!\", a);\n  });\n\n  testDoc(\"swapDoc\", \"A='a' B*='b' C<A\", function(a, b, c) {\n    var d = a.swapDoc(b);\n    d.setValue(\"x\");\n    eqAll(\"x\", c, d);\n    eqAll(\"b\", a, b);\n  });\n\n  testDoc(\"docKeepsScroll\", \"A='x' B*='y'\", function(a, b) {\n    addDoc(a, 200, 200);\n    a.scrollIntoView(Pos(199, 200));\n    var c = a.swapDoc(b);\n    a.swapDoc(c);\n    var pos = a.getScrollInfo();\n    is(pos.left > 0, \"not at left\");\n    is(pos.top > 0, \"not at top\");\n  });\n\n  testDoc(\"copyDoc\", \"A='u'\", function(a) {\n    var copy = a.getDoc().copy(true);\n    a.setValue(\"foo\");\n    copy.setValue(\"bar\");\n    var old = a.swapDoc(copy);\n    eq(a.getValue(), \"bar\");\n    a.undo();\n    eq(a.getValue(), \"u\");\n    a.swapDoc(old);\n    eq(a.getValue(), \"foo\");\n    eq(old.historySize().undo, 1);\n    eq(old.copy(false).historySize().undo, 0);\n  });\n\n  testDoc(\"docKeepsMode\", \"A='1+1'\", function(a) {\n    var other = CodeMirror.Doc(\"hi\", \"text/x-markdown\");\n    a.setOption(\"mode\", \"text/javascript\");\n    var old = a.swapDoc(other);\n    eq(a.getOption(\"mode\"), \"text/x-markdown\");\n    eq(a.getMode().name, \"markdown\");\n    a.swapDoc(old);\n    eq(a.getOption(\"mode\"), \"text/javascript\");\n    eq(a.getMode().name, \"javascript\");\n  });\n\n  testDoc(\"subview\", \"A='1\\n2\\n3\\n4\\n5' B<~A/1-3\", function(a, b) {\n    eq(b.getValue(), \"2\\n3\");\n    eq(b.firstLine(), 1);\n    b.setCursor(Pos(4));\n    eqCharPos(b.getCursor(), Pos(2, 1));\n    a.replaceRange(\"-1\\n0\\n\", Pos(0, 0));\n    eq(b.firstLine(), 3);\n    eqCharPos(b.getCursor(), Pos(4, 1));\n    a.undo();\n    eqCharPos(b.getCursor(), Pos(2, 1));\n    b.replaceRange(\"oyoy\\n\", Pos(2, 0));\n    eq(a.getValue(), \"1\\n2\\noyoy\\n3\\n4\\n5\");\n    b.undo();\n    eq(a.getValue(), \"1\\n2\\n3\\n4\\n5\");\n  });\n\n  testDoc(\"subviewEditOnBoundary\", \"A='11\\n22\\n33\\n44\\n55' B<~A/1-4\", function(a, b) {\n    a.replaceRange(\"x\\nyy\\nz\", Pos(0, 1), Pos(2, 1));\n    eq(b.firstLine(), 2);\n    eq(b.lineCount(), 2);\n    eq(b.getValue(), \"z3\\n44\");\n    a.replaceRange(\"q\\nrr\\ns\", Pos(3, 1), Pos(4, 1));\n    eq(b.firstLine(), 2);\n    eq(b.getValue(), \"z3\\n4q\");\n    eq(a.getValue(), \"1x\\nyy\\nz3\\n4q\\nrr\\ns5\");\n    a.execCommand(\"selectAll\");\n    a.replaceSelection(\"!\");\n    eqAll(\"!\", a, b);\n  });\n\n\n  testDoc(\"sharedMarker\", \"A='ab\\ncd\\nef\\ngh' B<A C<~A/1-2\", function(a, b, c) {\n    var mark = b.markText(Pos(0, 1), Pos(3, 1),\n                          {className: \"cm-searching\", shared: true});\n    var found = a.findMarksAt(Pos(0, 2));\n    eq(found.length, 1);\n    eq(found[0], mark);\n    eq(c.findMarksAt(Pos(1, 1)).length, 1);\n    eqCharPos(mark.find().from, Pos(0, 1));\n    eqCharPos(mark.find().to, Pos(3, 1));\n    b.replaceRange(\"x\\ny\\n\", Pos(0, 0));\n    eqCharPos(mark.find().from, Pos(2, 1));\n    eqCharPos(mark.find().to, Pos(5, 1));\n    var cleared = 0;\n    CodeMirror.on(mark, \"clear\", function() {++cleared;});\n    b.operation(function(){mark.clear();});\n    eq(a.findMarksAt(Pos(3, 1)).length, 0);\n    eq(b.findMarksAt(Pos(3, 1)).length, 0);\n    eq(c.findMarksAt(Pos(3, 1)).length, 0);\n    eq(mark.find(), null);\n    eq(cleared, 1);\n  });\n\n  testDoc(\"sharedMarkerCopy\", \"A='abcde'\", function(a) {\n    var shared = a.markText(Pos(0, 1), Pos(0, 3), {shared: true});\n    var b = a.linkedDoc();\n    var found = b.findMarksAt(Pos(0, 2));\n    eq(found.length, 1);\n    eq(found[0], shared);\n    shared.clear();\n    eq(b.findMarksAt(Pos(0, 2)), 0);\n  });\n\n  testDoc(\"sharedMarkerDetach\", \"A='abcde' B<A C<B\", function(a, b, c) {\n    var shared = a.markText(Pos(0, 1), Pos(0, 3), {shared: true});\n    a.unlinkDoc(b);\n    var inB = b.findMarksAt(Pos(0, 2));\n    eq(inB.length, 1);\n    is(inB[0] != shared);\n    var inC = c.findMarksAt(Pos(0, 2));\n    eq(inC.length, 1);\n    is(inC[0] != shared);\n    inC[0].clear();\n    is(shared.find());\n  });\n\n  testDoc(\"sharedBookmark\", \"A='ab\\ncd\\nef\\ngh' B<A C<~A/1-2\", function(a, b, c) {\n    var mark = b.setBookmark(Pos(1, 1), {shared: true});\n    var found = a.findMarksAt(Pos(1, 1));\n    eq(found.length, 1);\n    eq(found[0], mark);\n    eq(c.findMarksAt(Pos(1, 1)).length, 1);\n    eqCharPos(mark.find(), Pos(1, 1));\n    b.replaceRange(\"x\\ny\\n\", Pos(0, 0));\n    eqCharPos(mark.find(), Pos(3, 1));\n    var cleared = 0;\n    CodeMirror.on(mark, \"clear\", function() {++cleared;});\n    b.operation(function() {mark.clear();});\n    eq(a.findMarks(Pos(0, 0), Pos(5)).length, 0);\n    eq(b.findMarks(Pos(0, 0), Pos(5)).length, 0);\n    eq(c.findMarks(Pos(0, 0), Pos(5)).length, 0);\n    eq(mark.find(), null);\n    eq(cleared, 1);\n  });\n\n  testDoc(\"undoInSubview\", \"A='line 0\\nline 1\\nline 2\\nline 3\\nline 4' B<A/1-4\", function(a, b) {\n    b.replaceRange(\"x\", Pos(2, 0));\n    a.undo();\n    eq(a.getValue(), \"line 0\\nline 1\\nline 2\\nline 3\\nline 4\");\n    eq(b.getValue(), \"line 1\\nline 2\\nline 3\");\n  });\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/driver.js",
    "content": "var tests = [], filters = [], allNames = [];\n\nfunction Failure(why) {this.message = why;}\nFailure.prototype.toString = function() { return this.message; };\n\nfunction indexOf(collection, elt) {\n  if (collection.indexOf) return collection.indexOf(elt);\n  for (var i = 0, e = collection.length; i < e; ++i)\n    if (collection[i] == elt) return i;\n  return -1;\n}\n\nfunction test(name, run, expectedFail) {\n  // Force unique names\n  var originalName = name;\n  var i = 2; // Second function would be NAME_2\n  while (indexOf(allNames, name) !== -1){\n    name = originalName + \"_\" + i;\n    i++;\n  }\n  allNames.push(name);\n  // Add test\n  tests.push({name: name, func: run, expectedFail: expectedFail});\n  return name;\n}\nvar namespace = \"\";\nfunction testCM(name, run, opts, expectedFail) {\n  return test(namespace + name, function() {\n    var place = document.getElementById(\"testground\"), cm = window.cm = CodeMirror(place, opts);\n    var successful = false;\n    try {\n      run(cm);\n      successful = true;\n    } finally {\n      if (!successful || verbose) {\n        place.style.visibility = \"visible\";\n      } else {\n        place.removeChild(cm.getWrapperElement());\n      }\n    }\n  }, expectedFail);\n}\n\nfunction runTests(callback) {\n  var totalTime = 0;\n  function step(i) {\n    for (;;) {\n      if (i === tests.length) {\n        running = false;\n        return callback(\"done\");\n      }\n      var test = tests[i], skip = false;\n      if (filters.length) {\n        skip = true;\n        for (var j = 0; j < filters.length; j++)\n          if (test.name.match(filters[j])) skip = false;\n      }\n      if (skip) {\n        callback(\"skipped\", test.name, message);\n        i++;\n      } else {\n        break;\n      }\n    }\n    var expFail = test.expectedFail, startTime = +new Date, threw = false;\n    try {\n      var message = test.func();\n    } catch(e) {\n      threw = true;\n      if (expFail) callback(\"expected\", test.name);\n      else if (e instanceof Failure) callback(\"fail\", test.name, e.message);\n      else {\n        var pos = /(?:\\bat |@).*?([^\\/:]+):(\\d+)/.exec(e.stack);\n        if (pos) console[\"log\"](e.stack);\n        callback(\"error\", test.name, e.toString() + (pos ? \" (\" + pos[1] + \":\" + pos[2] + \")\" : \"\"));\n      }\n    }\n    if (!threw) {\n      if (expFail) callback(\"fail\", test.name, message || \"expected failure, but passed\");\n      else callback(\"ok\", test.name, message);\n    }\n    if (!quit) { // Run next test\n      var delay = 0;\n      totalTime += (+new Date) - startTime;\n      if (totalTime > 500){\n        totalTime = 0;\n        delay = 50;\n      }\n      setTimeout(function(){step(i + 1);}, delay);\n    } else { // Quit tests\n      running = false;\n      return null;\n    }\n  }\n  step(0);\n}\n\nfunction label(str, msg) {\n  if (msg) return str + \" (\" + msg + \")\";\n  return str;\n}\nfunction eq(a, b, msg) {\n  if (a != b) throw new Failure(label(a + \" != \" + b, msg));\n}\nfunction near(a, b, margin, msg) {\n  if (Math.abs(a - b) > margin)\n    throw new Failure(label(a + \" is not close to \" + b + \" (\" + margin + \")\", msg));\n}\nfunction eqCharPos(a, b, msg) {\n  function str(p) { return \"{line:\" + p.line + \",ch:\" + p.ch + \",sticky:\" + p.sticky + \"}\"; }\n  if (a == b) return;\n  if (a == null) throw new Failure(label(\"comparing null to \" + str(b), msg));\n  if (b == null) throw new Failure(label(\"comparing \" + str(a) + \" to null\", msg));\n  if (a.line != b.line || a.ch != b.ch) throw new Failure(label(str(a) + \" != \" + str(b), msg));\n}\nfunction eqCursorPos(a, b, msg) {\n  eqCharPos(a, b, msg);\n  if (a) eq(a.sticky, b.sticky, msg ? msg + ' (sticky)' : 'sticky');\n}\nfunction is(a, msg) {\n  if (!a) throw new Failure(label(\"assertion failed\", msg));\n}\n\nfunction countTests() {\n  if (!filters.length) return tests.length;\n  var sum = 0;\n  for (var i = 0; i < tests.length; ++i) {\n    var name = tests[i].name;\n    for (var j = 0; j < filters.length; j++) {\n      if (name.match(filters[j])) {\n        ++sum;\n        break;\n      }\n    }\n  }\n  return sum;\n}\n\nfunction parseTestFilter(s) {\n  if (/_\\*$/.test(s)) return new RegExp(\"^\" + s.slice(0, s.length - 2), \"i\");\n  else return new RegExp(s, \"i\");\n}\n"
  },
  {
    "path": "third_party/CodeMirror/test/emacs_test.js",
    "content": "(function() {\n  \"use strict\";\n\n  var Pos = CodeMirror.Pos;\n  namespace = \"emacs_\";\n\n  var eventCache = {};\n  function fakeEvent(keyName) {\n    var event = eventCache[key];\n    if (event) return event;\n\n    var ctrl, shift, alt;\n    var key = keyName.replace(/\\w+-/g, function(type) {\n      if (type == \"Ctrl-\") ctrl = true;\n      else if (type == \"Alt-\") alt = true;\n      else if (type == \"Shift-\") shift = true;\n      return \"\";\n    });\n    var code;\n    for (var c in CodeMirror.keyNames)\n      if (CodeMirror.keyNames[c] == key) { code = c; break; }\n    if (code == null) throw new Error(\"Unknown key: \" + key);\n\n    return eventCache[keyName] = {\n      type: \"keydown\", keyCode: code, ctrlKey: ctrl, shiftKey: shift, altKey: alt,\n      preventDefault: function(){}, stopPropagation: function(){}\n    };\n  }\n\n  function sim(name, start /*, actions... */) {\n    var keys = Array.prototype.slice.call(arguments, 2);\n    testCM(name, function(cm) {\n      for (var i = 0; i < keys.length; ++i) {\n        var cur = keys[i];\n        if (cur instanceof Pos) cm.setCursor(cur);\n        else if (cur.call) cur(cm);\n        else cm.triggerOnKeyDown(fakeEvent(cur));\n      }\n    }, {keyMap: \"emacs\", value: start, mode: \"javascript\"});\n  }\n\n  function at(line, ch, sticky) { return function(cm) { eqCursorPos(cm.getCursor(), Pos(line, ch, sticky)); }; }\n  function txt(str) { return function(cm) { eq(cm.getValue(), str); }; }\n\n  sim(\"motionHSimple\", \"abc\", \"Ctrl-F\", \"Ctrl-F\", \"Ctrl-B\", at(0, 1, \"after\"));\n  sim(\"motionHMulti\", \"abcde\",\n      \"Ctrl-4\", \"Ctrl-F\", at(0, 4, \"before\"), \"Ctrl--\", \"Ctrl-2\", \"Ctrl-F\", at(0, 2, \"after\"),\n      \"Ctrl-5\", \"Ctrl-B\", at(0, 0, \"after\"));\n\n  sim(\"motionHWord\", \"abc. def ghi\",\n      \"Alt-F\", at(0, 3, \"before\"), \"Alt-F\", at(0, 8, \"before\"),\n      \"Ctrl-B\", \"Alt-B\", at(0, 5, \"after\"), \"Alt-B\", at(0, 0, \"after\"));\n  sim(\"motionHWordMulti\", \"abc. def ghi \",\n      \"Ctrl-3\", \"Alt-F\", at(0, 12, \"before\"), \"Ctrl-2\", \"Alt-B\", at(0, 5, \"after\"),\n      \"Ctrl--\", \"Alt-B\", at(0, 8, \"before\"));\n\n  sim(\"motionVSimple\", \"a\\nb\\nc\\n\", \"Ctrl-N\", \"Ctrl-N\", \"Ctrl-P\", at(1, 0, \"after\"));\n  sim(\"motionVMulti\", \"a\\nb\\nc\\nd\\ne\\n\",\n      \"Ctrl-2\", \"Ctrl-N\", at(2, 0, \"after\"), \"Ctrl-F\", \"Ctrl--\", \"Ctrl-N\", at(1, 1, \"before\"),\n      \"Ctrl--\", \"Ctrl-3\", \"Ctrl-P\", at(4, 1, \"before\"));\n\n  sim(\"killYank\", \"abc\\ndef\\nghi\",\n      \"Ctrl-F\", \"Ctrl-Space\", \"Ctrl-N\", \"Ctrl-N\", \"Ctrl-W\", \"Ctrl-E\", \"Ctrl-Y\",\n      txt(\"ahibc\\ndef\\ng\"));\n  sim(\"killRing\", \"abcdef\",\n      \"Ctrl-Space\", \"Ctrl-F\", \"Ctrl-W\", \"Ctrl-Space\", \"Ctrl-F\", \"Ctrl-W\",\n      \"Ctrl-Y\", \"Alt-Y\",\n      txt(\"acdef\"));\n  sim(\"copyYank\", \"abcd\",\n      \"Ctrl-Space\", \"Ctrl-E\", \"Alt-W\", \"Ctrl-Y\",\n      txt(\"abcdabcd\"));\n\n  sim(\"killLineSimple\", \"foo\\nbar\", \"Ctrl-F\", \"Ctrl-K\", txt(\"f\\nbar\"));\n  sim(\"killLineEmptyLine\", \"foo\\n  \\nbar\", \"Ctrl-N\", \"Ctrl-K\", txt(\"foo\\nbar\"));\n  sim(\"killLineMulti\", \"foo\\nbar\\nbaz\",\n      \"Ctrl-F\", \"Ctrl-F\", \"Ctrl-K\", \"Ctrl-K\", \"Ctrl-K\", \"Ctrl-A\", \"Ctrl-Y\",\n      txt(\"o\\nbarfo\\nbaz\"));\n\n  sim(\"moveByParagraph\", \"abc\\ndef\\n\\n\\nhij\\nklm\\n\\n\",\n      \"Ctrl-F\", \"Ctrl-Down\", at(2, 0), \"Ctrl-Down\", at(6, 0),\n      \"Ctrl-N\", \"Ctrl-Up\", at(3, 0), \"Ctrl-Up\", at(0, 0),\n      Pos(1, 2), \"Ctrl-Down\", at(2, 0), Pos(4, 2), \"Ctrl-Up\", at(3, 0));\n  sim(\"moveByParagraphMulti\", \"abc\\n\\ndef\\n\\nhij\\n\\nklm\",\n      \"Ctrl-U\", \"2\", \"Ctrl-Down\", at(3, 0),\n      \"Shift-Alt-.\", \"Ctrl-3\", \"Ctrl-Up\", at(1, 0));\n\n  sim(\"moveBySentence\", \"sentence one! sentence\\ntwo\\n\\nparagraph two\",\n      \"Alt-E\", at(0, 13), \"Alt-E\", at(1, 3), \"Ctrl-F\", \"Alt-A\", at(0, 13));\n\n  sim(\"moveByExpr\", \"function foo(a, b) {}\",\n      \"Ctrl-Alt-F\", at(0, 8), \"Ctrl-Alt-F\", at(0, 12), \"Ctrl-Alt-F\", at(0, 18),\n      \"Ctrl-Alt-B\", at(0, 12), \"Ctrl-Alt-B\", at(0, 9));\n  sim(\"moveByExprMulti\", \"foo bar baz bug\",\n      \"Ctrl-2\", \"Ctrl-Alt-F\", at(0, 7),\n      \"Ctrl--\", \"Ctrl-Alt-F\", at(0, 4),\n      \"Ctrl--\", \"Ctrl-2\", \"Ctrl-Alt-B\", at(0, 11));\n  sim(\"delExpr\", \"var x = [\\n  a,\\n  b\\n  c\\n];\",\n      Pos(0, 8), \"Ctrl-Alt-K\", txt(\"var x = ;\"), \"Ctrl-/\",\n      Pos(4, 1), \"Ctrl-Alt-Backspace\", txt(\"var x = ;\"));\n  sim(\"delExprMulti\", \"foo bar baz\",\n      \"Ctrl-2\", \"Ctrl-Alt-K\", txt(\" baz\"),\n      \"Ctrl-/\", \"Ctrl-E\", \"Ctrl-2\", \"Ctrl-Alt-Backspace\", txt(\"foo \"));\n\n  sim(\"justOneSpace\", \"hi      bye  \",\n      Pos(0, 4), \"Alt-Space\", txt(\"hi bye  \"),\n      Pos(0, 4), \"Alt-Space\", txt(\"hi b ye  \"),\n      \"Ctrl-A\", \"Alt-Space\", \"Ctrl-E\", \"Alt-Space\", txt(\" hi b ye \"));\n\n  sim(\"openLine\", \"foo bar\", \"Alt-F\", \"Ctrl-O\", txt(\"foo\\n bar\"))\n\n  sim(\"transposeChar\", \"abcd\\ne\",\n      \"Ctrl-F\", \"Ctrl-T\", \"Ctrl-T\", txt(\"bcad\\ne\"), at(0, 3),\n      \"Ctrl-F\", \"Ctrl-T\", \"Ctrl-T\", \"Ctrl-T\", txt(\"bcda\\ne\"), at(0, 4),\n      \"Ctrl-F\", \"Ctrl-T\", txt(\"bcde\\na\"), at(1, 1));\n\n  sim(\"manipWordCase\", \"foo BAR bAZ\",\n      \"Alt-C\", \"Alt-L\", \"Alt-U\", txt(\"Foo bar BAZ\"),\n      \"Ctrl-A\", \"Alt-U\", \"Alt-L\", \"Alt-C\", txt(\"FOO bar Baz\"));\n  sim(\"manipWordCaseMulti\", \"foo Bar bAz\",\n      \"Ctrl-2\", \"Alt-U\", txt(\"FOO BAR bAz\"),\n      \"Ctrl-A\", \"Ctrl-3\", \"Alt-C\", txt(\"Foo Bar Baz\"));\n\n  sim(\"upExpr\", \"foo {\\n  bar[];\\n  baz(blah);\\n}\",\n      Pos(2, 7), \"Ctrl-Alt-U\", at(2, 5), \"Ctrl-Alt-U\", at(0, 4));\n  sim(\"transposeExpr\", \"do foo[bar] dah\",\n      Pos(0, 6), \"Ctrl-Alt-T\", txt(\"do [bar]foo dah\"));\n\n  sim(\"clearMark\", \"abcde\", Pos(0, 2), \"Ctrl-Space\", \"Ctrl-F\", \"Ctrl-F\",\n      \"Ctrl-G\", \"Ctrl-W\", txt(\"abcde\"));\n\n  sim(\"delRegion\", \"abcde\", \"Ctrl-Space\", \"Ctrl-F\", \"Ctrl-F\", \"Delete\", txt(\"cde\"));\n  sim(\"backspaceRegion\", \"abcde\", \"Ctrl-Space\", \"Ctrl-F\", \"Ctrl-F\", \"Backspace\", txt(\"cde\"));\n\n  sim(\"backspaceDoesntAddToRing\", \"foobar\", \"Ctrl-F\", \"Ctrl-F\", \"Ctrl-F\", \"Ctrl-K\", \"Backspace\", \"Backspace\", \"Ctrl-Y\", txt(\"fbar\"));\n\n  testCM(\"save\", function(cm) {\n    var saved = false;\n    CodeMirror.commands.save = function(cm) { saved = cm.getValue(); };\n    cm.triggerOnKeyDown(fakeEvent(\"Ctrl-X\"));\n    cm.triggerOnKeyDown(fakeEvent(\"Ctrl-S\"));\n    is(saved, \"hi\");\n  }, {value: \"hi\", keyMap: \"emacs\"});\n\n  testCM(\"gotoInvalidLineFloat\", function(cm) {\n    cm.openDialog = function(_, cb) { cb(\"2.2\"); };\n    cm.triggerOnKeyDown(fakeEvent(\"Alt-G\"));\n    cm.triggerOnKeyDown(fakeEvent(\"G\"));\n  }, {value: \"1\\n2\\n3\\n4\", keyMap: \"emacs\"});\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/html-hint-test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var Pos = CodeMirror.Pos;\n\n  namespace = \"html-hint_\";\n\n  testData =[\n    {\n      name: \"html-element\",\n      value: \"<htm\",\n      list: [\"<html\"]\n    },\n    {\n      name: \"element-close\",\n      value: \"<a href='#a'>\\n</\",\n      list: [\"</a>\"]\n    },\n    {\n      name: \"linkref-attribute\",\n      value: \"<link hreflang='z\",\n      from: Pos(0,\"<link hreflang=\".length),\n      list: [\"'zh'\",\"'za'\",\"'zu'\"]\n    },\n    {\n      name: \"html-completion\",\n      value: \"<html>\\n\",\n      list: [\"<head\",\"<body\",\"</html>\"]\n    }\n  ];\n\n  function escapeHtmlList(o) {\n    return '<code>' +\n      JSON.stringify(o.list,null,2)\n      .replace(/</g, \"&lt;\")\n      .replace(/>/g, \"&gt;\") +\n      '</code>'\n  }\n\n  function test(name, spec) {\n    testCM(name, function(cm) {\n      cm.setValue(spec.value);\n      cm.setCursor(spec.cursor);\n      var completion = CodeMirror.hint.html(cm);\n      if (!deepCompare(completion.list, spec.list))\n        throw new Failure(\"Wrong completion results. Got\" +\n          escapeHtmlList(completion) +\" but expected\" +\n          escapeHtmlList(spec));\n      eqCharPos(completion.from, spec.from,'from-failed');\n      eqCharPos(completion.to, spec.to, 'to-failed');\n    }, {\n      value: spec.value,\n      mode: spec.mode || \"text/html\"\n    });\n  }\n\n  testData.forEach(function (value) {\n    // Use sane defaults\n    var lines = value.value.split(/\\n/);\n    value.to = value.pos || Pos(lines.length-1, lines[lines.length-1].length);\n    value.from = value.from || Pos(lines.length-1,0);\n    value.cursor = value.cursor || value.to;\n    var name = value.name ||value.value;\n    test(name,value)\n  });\n\n  function deepCompare(a, b) {\n    if (a === b) return true;\n    if (!(a && typeof a === \"object\") ||\n        !(b && typeof b === \"object\")) return false;\n    var array = a instanceof Array\n    if ((b instanceof Array) !== array) return false;\n    if (array) {\n      if (a.length !== b.length) return false;\n      for (var i = 0; i < a.length; i++) if (!deepCompare(a[i], b[i])) return false\n    } else {\n      for (var p in a) if (!(p in b) || !deepCompare(a[p], b[p])) return false;\n      for (var p in b) if (!(p in a)) return false\n    }\n    return true\n  }\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/index.html",
    "content": "<!doctype html>\n\n<meta charset=\"utf-8\"/>\n<title>CodeMirror: Test Suite</title>\n<link rel=stylesheet href=\"../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../lib/codemirror.css\">\n<link rel=\"stylesheet\" href=\"mode_test.css\">\n<script src=\"../doc/activebookmark.js\"></script>\n<script src=\"../lib/codemirror.js\"></script>\n<script src=\"../mode/meta.js\"></script>\n<script src=\"../addon/mode/overlay.js\"></script>\n<script src=\"../addon/mode/multiplex.js\"></script>\n<script src=\"../addon/search/searchcursor.js\"></script>\n<script src=\"../addon/dialog/dialog.js\"></script>\n<script src=\"../addon/edit/matchbrackets.js\"></script>\n<script src=\"../addon/hint/sql-hint.js\"></script>\n<script src=\"../addon/hint/xml-hint.js\"></script>\n<script src=\"../addon/hint/html-hint.js\"></script>\n<script src=\"../addon/comment/comment.js\"></script>\n<script src=\"../addon/mode/simple.js\"></script>\n<script src=\"../mode/css/css.js\"></script>\n<script src=\"../mode/clike/clike.js\"></script>\n<!-- clike must be after css or vim and sublime tests will fail -->\n<script src=\"../mode/clojure/clojure.js\"></script>\n<script src=\"../mode/cypher/cypher.js\"></script>\n<script src=\"../mode/d/d.js\"></script>\n<script src=\"../mode/dockerfile/dockerfile.js\"></script>\n<script src=\"../mode/gfm/gfm.js\"></script>\n<script src=\"../mode/haml/haml.js\"></script>\n<script src=\"../mode/htmlmixed/htmlmixed.js\"></script>\n<script src=\"../mode/javascript/javascript.js\"></script>\n<script src=\"../mode/jsx/jsx.js\"></script>\n<script src=\"../mode/markdown/markdown.js\"></script>\n<script src=\"../mode/php/php.js\"></script>\n<script src=\"../mode/python/python.js\"></script>\n<script src=\"../mode/powershell/powershell.js\"></script>\n<script src=\"../mode/ruby/ruby.js\"></script>\n<script src=\"../mode/sass/sass.js\"></script>\n<script src=\"../mode/shell/shell.js\"></script>\n<script src=\"../mode/slim/slim.js\"></script>\n<script src=\"../mode/soy/soy.js\"></script>\n<script src=\"../mode/sql/sql.js\"></script>\n<script src=\"../mode/stex/stex.js\"></script>\n<script src=\"../mode/swift/swift.js\"></script>\n<script src=\"../mode/textile/textile.js\"></script>\n<script src=\"../mode/verilog/verilog.js\"></script>\n<script src=\"../mode/xml/xml.js\"></script>\n<script src=\"../mode/xquery/xquery.js\"></script>\n<script src=\"../keymap/emacs.js\"></script>\n<script src=\"../keymap/sublime.js\"></script>\n<script src=\"../keymap/vim.js\"></script>\n<script src=\"../mode/rust/rust.js\"></script>\n<script src=\"../mode/mscgen/mscgen.js\"></script>\n<script src=\"../mode/dylan/dylan.js\"></script>\n\n<style>\n  .ok {color: #090;}\n  .fail {color: #e00;}\n  .error {color: #c90;}\n  .done {font-weight: bold;}\n  #progress {\n  background: #45d;\n  color: white;\n  text-shadow: 0 0 1px #45d, 0 0 2px #45d, 0 0 3px #45d;\n  font-weight: bold;\n  white-space: pre;\n  }\n  #testground {\n  visibility: hidden;\n  }\n  #testground.offscreen {\n  visibility: visible;\n  position: absolute;\n  left: -10000px;\n  top: -10000px;\n  }\n  .CodeMirror { border: 1px solid black; }\n</style>\n\n<div id=nav>\n  <a href=\"https://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../index.html\">Home</a>\n    <li><a href=\"../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a class=active href=\"#\">Test suite</a>\n  </ul>\n</div>\n\n<article>\n  <h2>Test Suite</h2>\n\n    <p>A limited set of programmatic sanity tests for CodeMirror.</p>\n\n    <div style=\"border: 1px solid black; padding: 1px; max-width: 700px;\">\n      <div style=\"width: 0px;\" id=progress><div style=\"padding: 3px;\">Ran <span id=\"progress_ran\">0</span><span id=\"progress_total\"> of 0</span> tests</div></div>\n    </div>\n    <p id=status>Please enable JavaScript...</p>\n    <div id=output></div>\n\n    <div id=testground></div>\n\n    <script src=\"driver.js\"></script>\n    <script src=\"test.js\"></script>\n    <script src=\"doc_test.js\"></script>\n    <script src=\"multi_test.js\"></script>\n    <script src=\"contenteditable_test.js\"></script>\n    <script src=\"scroll_test.js\"></script>\n    <script src=\"comment_test.js\"></script>\n    <script src=\"search_test.js\"></script>\n    <script src=\"mode_test.js\"></script>\n\n    <script src=\"../mode/clike/test.js\"></script>\n    <script src=\"../mode/clojure/test.js\"></script>\n    <script src=\"../mode/css/test.js\"></script>\n    <script src=\"../mode/css/gss_test.js\"></script>\n    <script src=\"../mode/css/scss_test.js\"></script>\n    <script src=\"../mode/css/less_test.js\"></script>\n    <script src=\"../mode/cypher/test.js\"></script>\n    <script src=\"../mode/d/test.js\"></script>\n    <script src=\"../mode/dockerfile/test.js\"></script>\n    <script src=\"../mode/gfm/test.js\"></script>\n    <script src=\"../mode/haml/test.js\"></script>\n    <script src=\"../mode/javascript/test.js\"></script>\n    <script src=\"../mode/jsx/test.js\"></script>\n    <script src=\"../mode/markdown/test.js\"></script>\n    <script src=\"../mode/php/test.js\"></script>\n    <script src=\"../mode/powershell/test.js\"></script>\n    <script src=\"../mode/ruby/test.js\"></script>\n    <script src=\"../mode/sass/test.js\"></script>\n    <script src=\"../mode/shell/test.js\"></script>\n    <script src=\"../mode/slim/test.js\"></script>\n    <script src=\"../mode/soy/test.js\"></script>\n    <script src=\"../mode/stex/test.js\"></script>\n    <script src=\"../mode/swift/test.js\"></script>\n    <script src=\"../mode/textile/test.js\"></script>\n    <script src=\"../mode/verilog/test.js\"></script>\n    <script src=\"../mode/xml/test.js\"></script>\n    <script src=\"../mode/xquery/test.js\"></script>\n    <script src=\"../mode/python/test.js\"></script>\n    <script src=\"../mode/rust/test.js\"></script>\n    <script src=\"../mode/mscgen/mscgen_test.js\"></script>\n    <script src=\"../mode/mscgen/xu_test.js\"></script>\n    <script src=\"../mode/mscgen/msgenny_test.js\"></script>\n    <script src=\"../mode/dylan/test.js\"></script>\n    <script src=\"../addon/mode/multiplex_test.js\"></script>\n    <script src=\"emacs_test.js\"></script>\n    <script src=\"sql-hint-test.js\"></script>\n    <script src=\"sublime_test.js\"></script>\n    <script src=\"vim_test.js\"></script>\n    <script src=\"html-hint-test.js\"></script>\n    <script>\n      window.onload = runHarness;\n      CodeMirror.on(window, 'hashchange', runHarness);\n\n      function esc(str) {\n        return str.replace(/[<&]/, function(ch) { return ch == \"<\" ? \"&lt;\" : \"&amp;\"; });\n      }\n\n      var output = document.getElementById(\"output\"),\n          progress = document.getElementById(\"progress\"),\n          progressRan = document.getElementById(\"progress_ran\").childNodes[0],\n          progressTotal = document.getElementById(\"progress_total\").childNodes[0];\n      var count = 0,\n          failed = 0,\n          skipped = 0,\n          bad = \"\",\n          running = false, // Flag that states tests are running\n          quit = false, // Flag to quit tests ASAP\n          verbose = false; // Adds message for *every* test to output\n\n      function runHarness(){\n        if (running) {\n          quit = true;\n          setStatus(\"Restarting tests...\", '', true);\n          setTimeout(function(){runHarness();}, 500);\n          return;\n        }\n        filters = [];\n        verbose = false;\n        if (window.location.hash.substr(1)){\n          var strings = window.location.hash.substr(1).split(\",\");\n          while (strings.length) {\n            var s = strings.shift();\n            if (s === \"verbose\")\n              verbose = true;\n            else\n              filters.push(parseTestFilter(decodeURIComponent(s)));\n          }\n        }\n        quit = false;\n        running = true;\n        setStatus(\"Loading tests...\");\n        count = 0;\n        failed = 0;\n        skipped = 0;\n        bad = \"\";\n        totalTests = countTests();\n        progressTotal.nodeValue = \" of \" + totalTests;\n        progressRan.nodeValue = count;\n        output.innerHTML = '';\n        document.getElementById(\"testground\").innerHTML = \"<form>\" +\n          \"<textarea id=\\\"code\\\" name=\\\"code\\\"></textarea>\" +\n          \"<input type=submit value=ok name=submit>\" +\n          \"</form>\";\n        runTests(displayTest);\n      }\n\n      function setStatus(message, className, force){\n        if (quit && !force) return;\n        if (!message) throw(\"must provide message\");\n        var status = document.getElementById(\"status\").childNodes[0];\n        status.nodeValue = message;\n        status.parentNode.className = className;\n      }\n      function addOutput(name, className, code){\n        var newOutput = document.createElement(\"dl\");\n        var newTitle = document.createElement(\"dt\");\n        newTitle.className = className;\n        newTitle.appendChild(document.createTextNode(name));\n        newOutput.appendChild(newTitle);\n        var newMessage = document.createElement(\"dd\");\n        newMessage.innerHTML = code;\n        newOutput.appendChild(newTitle);\n        newOutput.appendChild(newMessage);\n        output.appendChild(newOutput);\n      }\n      function displayTest(type, name, customMessage) {\n        var message = \"???\";\n        if (type != \"done\" && type != \"skipped\") ++count;\n        progress.style.width = (count * (progress.parentNode.clientWidth - 2) / (totalTests || 1)) + \"px\";\n        progressRan.nodeValue = count;\n        if (type == \"ok\") {\n          message = \"Test '\" + name + \"' passed\";\n          if (!verbose) customMessage = false;\n        } else if (type == \"skipped\") {\n          message = \"Test '\" + name + \"' skipped\";\n          ++skipped;\n          if (!verbose) customMessage = false;\n        } else if (type == \"expected\") {\n          message = \"Test '\" + name + \"' failed as expected\";\n          if (!verbose) customMessage = false;\n        } else if (type == \"error\" || type == \"fail\") {\n          ++failed;\n          message = \"Test '\" + name + \"' failed\";\n        } else if (type == \"done\") {\n          if (failed) {\n            type += \" fail\";\n            message = failed + \" failure\" + (failed > 1 ? \"s\" : \"\");\n          } else if (count < totalTests) {\n            failed = totalTests - count;\n            type += \" fail\";\n            message = failed + \" failure\" + (failed > 1 ? \"s\" : \"\");\n          } else {\n            type += \" ok\";\n            message = \"All passed\";\n            if (skipped) {\n              message += \" (\" + skipped + \" skipped)\";\n            }\n          }\n          progressTotal.nodeValue = '';\n          customMessage = true; // Hack to avoid adding to output\n        }\n        if (verbose && !customMessage)  customMessage = message;\n        setStatus(message, type);\n        if (customMessage && customMessage.length > 0) {\n          addOutput(name, type, customMessage);\n        }\n      }\n    </script>\n\n</article>\n"
  },
  {
    "path": "third_party/CodeMirror/test/lint.js",
    "content": "var blint = require(\"blint\");\n\n[\"mode\", \"lib\", \"addon\", \"keymap\"].forEach(function(dir) {\n  blint.checkDir(dir, {\n    browser: true,\n    allowedGlobals: [\"CodeMirror\", \"define\", \"test\", \"requirejs\"],\n    ecmaVersion: 5,\n    tabs: dir == \"lib\"\n  });\n});\n\n[\"src\"].forEach(function(dir) {\n  blint.checkDir(dir, {\n    browser: true,\n    ecmaVersion: 6,\n    semicolons: false\n  });\n});\n\nmodule.exports = {ok: blint.success()};\n"
  },
  {
    "path": "third_party/CodeMirror/test/mode_test.css",
    "content": ".mt-output .mt-token {\n  border: 1px solid #ddd;\n  white-space: pre;\n  font-family: \"Consolas\", monospace;\n  text-align: center;\n}\n\n.mt-output .mt-style {\n  font-size: x-small;\n}\n\n.mt-output .mt-state {\n  font-size: x-small;\n  vertical-align: top;\n}\n\n.mt-output .mt-state-row {\n  display: none;\n}\n\n.mt-state-unhide .mt-output .mt-state-row {\n  display: table-row;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/test/mode_test.js",
    "content": "/**\n * Helper to test CodeMirror highlighting modes. It pretty prints output of the\n * highlighter and can check against expected styles.\n *\n * Mode tests are registered by calling test.mode(testName, mode,\n * tokens), where mode is a mode object as returned by\n * CodeMirror.getMode, and tokens is an array of lines that make up\n * the test.\n *\n * These lines are strings, in which styled stretches of code are\n * enclosed in brackets `[]`, and prefixed by their style. For\n * example, `[keyword if]`. Brackets in the code itself must be\n * duplicated to prevent them from being interpreted as token\n * boundaries. For example `a[[i]]` for `a[i]`. If a token has\n * multiple styles, the styles must be separated by ampersands, for\n * example `[tag&error </hmtl>]`.\n *\n * See the test.js files in the css, markdown, gfm, and stex mode\n * directories for examples.\n */\n(function() {\n  function findSingle(str, pos, ch) {\n    for (;;) {\n      var found = str.indexOf(ch, pos);\n      if (found == -1) return null;\n      if (str.charAt(found + 1) != ch) return found;\n      pos = found + 2;\n    }\n  }\n\n  var styleName = /[\\w&-_]+/g;\n  function parseTokens(strs) {\n    var tokens = [], plain = \"\";\n    for (var i = 0; i < strs.length; ++i) {\n      if (i) plain += \"\\n\";\n      var str = strs[i], pos = 0;\n      while (pos < str.length) {\n        var style = null, text;\n        if (str.charAt(pos) == \"[\" && str.charAt(pos+1) != \"[\") {\n          styleName.lastIndex = pos + 1;\n          var m = styleName.exec(str);\n          style = m[0].replace(/&/g, \" \");\n          var textStart = pos + style.length + 2;\n          var end = findSingle(str, textStart, \"]\");\n          if (end == null) throw new Error(\"Unterminated token at \" + pos + \" in '\" + str + \"'\" + style);\n          text = str.slice(textStart, end);\n          pos = end + 1;\n        } else {\n          var end = findSingle(str, pos, \"[\");\n          if (end == null) end = str.length;\n          text = str.slice(pos, end);\n          pos = end;\n        }\n        text = text.replace(/\\[\\[|\\]\\]/g, function(s) {return s.charAt(0);});\n        tokens.push({style: style, text: text});\n        plain += text;\n      }\n    }\n    return {tokens: tokens, plain: plain};\n  }\n\n  test.mode = function(name, mode, tokens, modeName) {\n    var data = parseTokens(tokens);\n    return test((modeName || mode.name) + \"_\" + name, function() {\n      return compare(data.plain, data.tokens, mode);\n    });\n  };\n\n  function esc(str) {\n    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\").replace(/'/g, \"&#039;\");\n  }\n\n  function compare(text, expected, mode) {\n\n    var expectedOutput = [];\n    for (var i = 0; i < expected.length; ++i) {\n      var sty = expected[i].style;\n      if (sty && sty.indexOf(\" \")) sty = sty.split(' ').sort().join(' ');\n      expectedOutput.push({style: sty, text: expected[i].text});\n    }\n\n    var observedOutput = highlight(text, mode);\n\n    var s = \"\";\n    var diff = highlightOutputsDifferent(expectedOutput, observedOutput);\n    if (diff != null) {\n      s += '<div class=\"mt-test mt-fail\">';\n      s +=   '<pre>' + esc(text) + '</pre>';\n      s +=   '<div class=\"cm-s-default\">';\n      s += 'expected:';\n      s +=   prettyPrintOutputTable(expectedOutput, diff);\n      s += 'observed: [<a onclick=\"this.parentElement.className+=\\' mt-state-unhide\\'\">display states</a>]';\n      s +=   prettyPrintOutputTable(observedOutput, diff);\n      s +=   '</div>';\n      s += '</div>';\n    }\n    if (observedOutput.indentFailures) {\n      for (var i = 0; i < observedOutput.indentFailures.length; i++)\n        s += \"<div class='mt-test mt-fail'>\" + esc(observedOutput.indentFailures[i]) + \"</div>\";\n    }\n    if (s) throw new Failure(s);\n  }\n\n  function stringify(obj) {\n    function replacer(key, obj) {\n      if (typeof obj == \"function\") {\n        var m = obj.toString().match(/function\\s*[^\\s(]*/);\n        return m ? m[0] : \"function\";\n      }\n      return obj;\n    }\n    if (window.JSON && JSON.stringify)\n      return JSON.stringify(obj, replacer, 2);\n    return \"[unsupported]\";  // Fail safely if no native JSON.\n  }\n\n  function highlight(string, mode) {\n    var state = mode.startState();\n\n    var lines = string.replace(/\\r\\n/g,'\\n').split('\\n');\n    var st = [], pos = 0;\n    for (var i = 0; i < lines.length; ++i) {\n      var line = lines[i], newLine = true;\n      if (mode.indent) {\n        var ws = line.match(/^\\s*/)[0];\n        var indent = mode.indent(state, line.slice(ws.length), line);\n        if (indent != CodeMirror.Pass && indent != ws.length)\n          (st.indentFailures || (st.indentFailures = [])).push(\n            \"Indentation of line \" + (i + 1) + \" is \" + indent + \" (expected \" + ws.length + \")\");\n      }\n      var stream = new CodeMirror.StringStream(line, 4, {\n        lookAhead: function(n) { return lines[i + n] }\n      });\n      if (line == \"\" && mode.blankLine) mode.blankLine(state);\n      /* Start copied code from CodeMirror.highlight */\n      while (!stream.eol()) {\n        for (var j = 0; j < 10 && stream.start >= stream.pos; j++)\n          var compare = mode.token(stream, state);\n        if (j == 10)\n          throw new Failure(\"Failed to advance the stream.\" + stream.string + \" \" + stream.pos);\n        var substr = stream.current();\n        if (compare && compare.indexOf(\" \") > -1) compare = compare.split(' ').sort().join(' ');\n        stream.start = stream.pos;\n        if (pos && st[pos-1].style == compare && !newLine) {\n          st[pos-1].text += substr;\n        } else if (substr) {\n          st[pos++] = {style: compare, text: substr, state: stringify(state)};\n        }\n        // Give up when line is ridiculously long\n        if (stream.pos > 5000) {\n          st[pos++] = {style: null, text: this.text.slice(stream.pos)};\n          break;\n        }\n        newLine = false;\n      }\n    }\n\n    return st;\n  }\n\n  function highlightOutputsDifferent(o1, o2) {\n    var minLen = Math.min(o1.length, o2.length);\n    for (var i = 0; i < minLen; ++i)\n      if (o1[i].style != o2[i].style || o1[i].text != o2[i].text) return i;\n    if (o1.length > minLen || o2.length > minLen) return minLen;\n  }\n\n  function prettyPrintOutputTable(output, diffAt) {\n    var s = '<table class=\"mt-output\">';\n    s += '<tr>';\n    for (var i = 0; i < output.length; ++i) {\n      var style = output[i].style, val = output[i].text;\n      s +=\n      '<td class=\"mt-token\"' + (i == diffAt ? \" style='background: pink'\" : \"\") + '>' +\n        '<span class=\"cm-' + esc(String(style)) + '\">' +\n        esc(val.replace(/ /g,'\\xb7')) +  // · MIDDLE DOT\n        '</span>' +\n        '</td>';\n    }\n    s += '</tr><tr>';\n    for (var i = 0; i < output.length; ++i) {\n      s += '<td class=\"mt-style\"><span>' + (output[i].style || null) + '</span></td>';\n    }\n    if(output[0].state) {\n      s += '</tr><tr class=\"mt-state-row\" title=\"State AFTER each token\">';\n      for (var i = 0; i < output.length; ++i) {\n        s += '<td class=\"mt-state\"><pre>' + esc(output[i].state) + '</pre></td>';\n      }\n    }\n    s += '</tr></table>';\n    return s;\n  }\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/multi_test.js",
    "content": "(function() {\n  namespace = \"multi_\";\n\n  function hasSelections(cm) {\n    var sels = cm.listSelections();\n    var given = (arguments.length - 1) / 4;\n    if (sels.length != given)\n      throw new Failure(\"expected \" + given + \" selections, found \" + sels.length);\n    for (var i = 0, p = 1; i < given; i++, p += 4) {\n      var anchor = Pos(arguments[p], arguments[p + 1]);\n      var head = Pos(arguments[p + 2], arguments[p + 3]);\n      eqCharPos(sels[i].anchor, anchor, \"anchor of selection \" + i);\n      eqCharPos(sels[i].head, head, \"head of selection \" + i);\n    }\n  }\n  function hasCursors(cm) {\n    var sels = cm.listSelections();\n    var given = (arguments.length - 1) / 2;\n    if (sels.length != given)\n      throw new Failure(\"expected \" + given + \" selections, found \" + sels.length);\n    for (var i = 0, p = 1; i < given; i++, p += 2) {\n      eqCursorPos(sels[i].anchor, sels[i].head, \"something selected for \" + i);\n      var head = Pos(arguments[p], arguments[p + 1]);\n      eqCharPos(sels[i].head, head, \"selection \" + i);\n    }\n  }\n\n  testCM(\"getSelection\", function(cm) {\n    select(cm, {anchor: Pos(0, 0), head: Pos(1, 2)}, {anchor: Pos(2, 2), head: Pos(2, 0)});\n    eq(cm.getSelection(), \"1234\\n56\\n90\");\n    eq(cm.getSelection(false).join(\"|\"), \"1234|56|90\");\n    eq(cm.getSelections().join(\"|\"), \"1234\\n56|90\");\n  }, {value: \"1234\\n5678\\n90\"});\n\n  testCM(\"setSelection\", function(cm) {\n    select(cm, Pos(3, 0), Pos(0, 0), {anchor: Pos(2, 5), head: Pos(1, 0)});\n    hasSelections(cm, 0, 0, 0, 0,\n                  2, 5, 1, 0,\n                  3, 0, 3, 0);\n    cm.setSelection(Pos(1, 2), Pos(1, 1));\n    hasSelections(cm, 1, 2, 1, 1);\n    select(cm, {anchor: Pos(1, 1), head: Pos(2, 4)},\n           {anchor: Pos(0, 0), head: Pos(1, 3)},\n           Pos(3, 0), Pos(2, 2));\n    hasSelections(cm, 0, 0, 2, 4,\n                  3, 0, 3, 0);\n    cm.setSelections([{anchor: Pos(0, 1), head: Pos(0, 2)},\n                      {anchor: Pos(1, 1), head: Pos(1, 2)},\n                      {anchor: Pos(2, 1), head: Pos(2, 2)}], 1);\n    eqCharPos(cm.getCursor(\"head\"), Pos(1, 2));\n    eqCharPos(cm.getCursor(\"anchor\"), Pos(1, 1));\n    eqCharPos(cm.getCursor(\"from\"), Pos(1, 1));\n    eqCharPos(cm.getCursor(\"to\"), Pos(1, 2));\n    cm.setCursor(Pos(1, 1));\n    hasCursors(cm, 1, 1);\n  }, {value: \"abcde\\nabcde\\nabcde\\n\"});\n\n  testCM(\"somethingSelected\", function(cm) {\n    select(cm, Pos(0, 1), {anchor: Pos(0, 3), head: Pos(0, 5)});\n    eq(cm.somethingSelected(), true);\n    select(cm, Pos(0, 1), Pos(0, 3), Pos(0, 5));\n    eq(cm.somethingSelected(), false);\n  }, {value: \"123456789\"});\n\n  testCM(\"extendSelection\", function(cm) {\n    select(cm, Pos(0, 1), Pos(1, 1), Pos(2, 1));\n    cm.setExtending(true);\n    cm.extendSelections([Pos(0, 2), Pos(1, 0), Pos(2, 3)]);\n    hasSelections(cm, 0, 1, 0, 2,\n                  1, 1, 1, 0,\n                  2, 1, 2, 3);\n    cm.extendSelection(Pos(2, 4), Pos(2, 0));\n    hasSelections(cm, 2, 4, 2, 0);\n  }, {value: \"1234\\n1234\\n1234\"});\n\n  testCM(\"addSelection\", function(cm) {\n    select(cm, Pos(0, 1), Pos(1, 1));\n    cm.addSelection(Pos(0, 0), Pos(0, 4));\n    hasSelections(cm, 0, 0, 0, 4,\n                  1, 1, 1, 1);\n    cm.addSelection(Pos(2, 2));\n    hasSelections(cm, 0, 0, 0, 4,\n                  1, 1, 1, 1,\n                  2, 2, 2, 2);\n  }, {value: \"1234\\n1234\\n1234\"});\n\n  testCM(\"replaceSelection\", function(cm) {\n    var selections = [{anchor: Pos(0, 0), head: Pos(0, 1)},\n                      {anchor: Pos(0, 2), head: Pos(0, 3)},\n                      {anchor: Pos(0, 4), head: Pos(0, 5)},\n                      {anchor: Pos(2, 1), head: Pos(2, 4)},\n                      {anchor: Pos(2, 5), head: Pos(2, 6)}];\n    var val = \"123456\\n123456\\n123456\";\n    cm.setValue(val);\n    cm.setSelections(selections);\n    cm.replaceSelection(\"ab\", \"around\");\n    eq(cm.getValue(), \"ab2ab4ab6\\n123456\\n1ab5ab\");\n    hasSelections(cm, 0, 0, 0, 2,\n                  0, 3, 0, 5,\n                  0, 6, 0, 8,\n                  2, 1, 2, 3,\n                  2, 4, 2, 6);\n    cm.setValue(val);\n    cm.setSelections(selections);\n    cm.replaceSelection(\"\", \"around\");\n    eq(cm.getValue(), \"246\\n123456\\n15\");\n    hasSelections(cm, 0, 0, 0, 0,\n                  0, 1, 0, 1,\n                  0, 2, 0, 2,\n                  2, 1, 2, 1,\n                  2, 2, 2, 2);\n    cm.setValue(val);\n    cm.setSelections(selections);\n    cm.replaceSelection(\"X\\nY\\nZ\", \"around\");\n    hasSelections(cm, 0, 0, 2, 1,\n                  2, 2, 4, 1,\n                  4, 2, 6, 1,\n                  8, 1, 10, 1,\n                  10, 2, 12, 1);\n    cm.replaceSelection(\"a\", \"around\");\n    hasSelections(cm, 0, 0, 0, 1,\n                  0, 2, 0, 3,\n                  0, 4, 0, 5,\n                  2, 1, 2, 2,\n                  2, 3, 2, 4);\n    cm.replaceSelection(\"xy\", \"start\");\n    hasSelections(cm, 0, 0, 0, 0,\n                  0, 3, 0, 3,\n                  0, 6, 0, 6,\n                  2, 1, 2, 1,\n                  2, 4, 2, 4);\n    cm.replaceSelection(\"z\\nf\");\n    hasSelections(cm, 1, 1, 1, 1,\n                  2, 1, 2, 1,\n                  3, 1, 3, 1,\n                  6, 1, 6, 1,\n                  7, 1, 7, 1);\n    eq(cm.getValue(), \"z\\nfxy2z\\nfxy4z\\nfxy6\\n123456\\n1z\\nfxy5z\\nfxy\");\n  });\n\n  function select(cm) {\n    var sels = [];\n    for (var i = 1; i < arguments.length; i++) {\n      var arg = arguments[i];\n      if (arg.head) sels.push(arg);\n      else sels.push({head: arg, anchor: arg});\n    }\n    cm.setSelections(sels, sels.length - 1);\n  }\n\n  testCM(\"indentSelection\", function(cm) {\n    select(cm, Pos(0, 1), Pos(1, 1));\n    cm.indentSelection(4);\n    eq(cm.getValue(), \"    foo\\n    bar\\nbaz\");\n\n    select(cm, Pos(0, 2), Pos(0, 3), Pos(0, 4));\n    cm.indentSelection(-2);\n    eq(cm.getValue(), \"  foo\\n    bar\\nbaz\");\n\n    select(cm, {anchor: Pos(0, 0), head: Pos(1, 2)},\n           {anchor: Pos(1, 3), head: Pos(2, 0)});\n    cm.indentSelection(-2);\n    eq(cm.getValue(), \"foo\\n  bar\\nbaz\");\n  }, {value: \"foo\\nbar\\nbaz\"});\n\n  testCM(\"killLine\", function(cm) {\n    select(cm, Pos(0, 1), Pos(0, 2), Pos(1, 1));\n    cm.execCommand(\"killLine\");\n    eq(cm.getValue(), \"f\\nb\\nbaz\");\n    cm.execCommand(\"killLine\");\n    eq(cm.getValue(), \"fbbaz\");\n    cm.setValue(\"foo\\nbar\\nbaz\");\n    select(cm, Pos(0, 1), {anchor: Pos(0, 2), head: Pos(2, 1)});\n    cm.execCommand(\"killLine\");\n    eq(cm.getValue(), \"faz\");\n  }, {value: \"foo\\nbar\\nbaz\"});\n\n  testCM(\"deleteLine\", function(cm) {\n    select(cm, Pos(0, 0),\n           {head: Pos(0, 1), anchor: Pos(2, 0)},\n           Pos(4, 0));\n    cm.execCommand(\"deleteLine\");\n    eq(cm.getValue(), \"4\\n6\\n7\");\n    select(cm, Pos(2, 1));\n    cm.execCommand(\"deleteLine\");\n    eq(cm.getValue(), \"4\\n6\\n\");\n  }, {value: \"1\\n2\\n3\\n4\\n5\\n6\\n7\"});\n\n  testCM(\"deleteH\", function(cm) {\n    select(cm, Pos(0, 4), {anchor: Pos(1, 4), head: Pos(1, 5)});\n    cm.execCommand(\"delWordAfter\");\n    eq(cm.getValue(), \"foo bar baz\\nabc ef ghi\\n\");\n    cm.execCommand(\"delWordAfter\");\n    eq(cm.getValue(), \"foo  baz\\nabc  ghi\\n\");\n    cm.execCommand(\"delCharBefore\");\n    cm.execCommand(\"delCharBefore\");\n    eq(cm.getValue(), \"fo baz\\nab ghi\\n\");\n    select(cm, Pos(0, 3), Pos(0, 4), Pos(0, 5));\n    cm.execCommand(\"delWordAfter\");\n    eq(cm.getValue(), \"fo \\nab ghi\\n\");\n  }, {value: \"foo bar baz\\nabc def ghi\\n\"});\n\n  testCM(\"goLineStart\", function(cm) {\n    select(cm, Pos(0, 2), Pos(0, 3), Pos(1, 1));\n    cm.execCommand(\"goLineStart\");\n    hasCursors(cm, 0, 0, 1, 0);\n    select(cm, Pos(1, 1), Pos(0, 1));\n    cm.setExtending(true);\n    cm.execCommand(\"goLineStart\");\n    hasSelections(cm, 0, 1, 0, 0,\n                  1, 1, 1, 0);\n  }, {value: \"foo\\nbar\\nbaz\"});\n\n  testCM(\"moveV\", function(cm) {\n    select(cm, Pos(0, 2), Pos(1, 2));\n    cm.execCommand(\"goLineDown\");\n    hasCursors(cm, 1, 2, 2, 2);\n    cm.execCommand(\"goLineUp\");\n    hasCursors(cm, 0, 2, 1, 2);\n    cm.execCommand(\"goLineUp\");\n    hasCursors(cm, 0, 0, 0, 2);\n    cm.execCommand(\"goLineUp\");\n    hasCursors(cm, 0, 0);\n    select(cm, Pos(0, 2), Pos(1, 2));\n    cm.setExtending(true);\n    cm.execCommand(\"goLineDown\");\n    hasSelections(cm, 0, 2, 2, 2);\n  }, {value: \"12345\\n12345\\n12345\"});\n\n  testCM(\"moveH\", function(cm) {\n    select(cm, Pos(0, 1), Pos(0, 3), Pos(0, 5), Pos(2, 3));\n    cm.execCommand(\"goCharRight\");\n    hasCursors(cm, 0, 2, 0, 4, 1, 0, 2, 4);\n    cm.execCommand(\"goCharLeft\");\n    hasCursors(cm, 0, 1, 0, 3, 0, 5, 2, 3);\n    for (var i = 0; i < 15; i++)\n      cm.execCommand(\"goCharRight\");\n    hasCursors(cm, 2, 4, 2, 5);\n  }, {value: \"12345\\n12345\\n12345\"});\n\n  testCM(\"newlineAndIndent\", function(cm) {\n    select(cm, Pos(0, 5), Pos(1, 5));\n    cm.execCommand(\"newlineAndIndent\");\n    hasCursors(cm, 1, 2, 3, 2);\n    eq(cm.getValue(), \"x = [\\n  1];\\ny = [\\n  2];\");\n    cm.undo();\n    eq(cm.getValue(), \"x = [1];\\ny = [2];\");\n    hasCursors(cm, 0, 5, 1, 5);\n    select(cm, Pos(0, 5), Pos(0, 6));\n    cm.execCommand(\"newlineAndIndent\");\n    hasCursors(cm, 1, 2, 2, 0);\n    eq(cm.getValue(), \"x = [\\n  1\\n];\\ny = [2];\");\n  }, {value: \"x = [1];\\ny = [2];\", mode: \"javascript\"});\n\n  testCM(\"goDocStartEnd\", function(cm) {\n    select(cm, Pos(0, 1), Pos(1, 1));\n    cm.execCommand(\"goDocStart\");\n    hasCursors(cm, 0, 0);\n    select(cm, Pos(0, 1), Pos(1, 1));\n    cm.execCommand(\"goDocEnd\");\n    hasCursors(cm, 1, 3);\n    select(cm, Pos(0, 1), Pos(1, 1));\n    cm.setExtending(true);\n    cm.execCommand(\"goDocEnd\");\n    hasSelections(cm, 1, 1, 1, 3);\n  }, {value: \"abc\\ndef\"});\n\n  testCM(\"selectionHistory\", function(cm) {\n    for (var i = 0; i < 3; ++i)\n      cm.addSelection(Pos(0, i * 2), Pos(0, i * 2 + 1));\n    cm.execCommand(\"undoSelection\");\n    eq(cm.getSelection(), \"1\\n2\");\n    cm.execCommand(\"undoSelection\");\n    eq(cm.getSelection(), \"1\");\n    cm.execCommand(\"undoSelection\");\n    eq(cm.getSelection(), \"\");\n    eqCharPos(cm.getCursor(), Pos(0, 0));\n    cm.execCommand(\"redoSelection\");\n    eq(cm.getSelection(), \"1\");\n    cm.execCommand(\"redoSelection\");\n    eq(cm.getSelection(), \"1\\n2\");\n    cm.execCommand(\"redoSelection\");\n    eq(cm.getSelection(), \"1\\n2\\n3\");\n  }, {value: \"1 2 3\"});\n\n  testCM(\"selectionsMayTouch\", function(cm) {\n    select(cm, Pos(0, 0), Pos(0, 2))\n    cm.setExtending(true);\n    cm.extendSelections([Pos(0, 2), Pos(0, 4)])\n    hasSelections(cm, 0, 0, 0, 2,\n                  0, 2, 0, 4)\n    cm.extendSelections([Pos(0, 3), Pos(0, 4)])\n    hasSelections(cm, 0, 0, 0, 4)\n  }, {selectionsMayTouch: true, value: \"1234\"})\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/phantom_driver.js",
    "content": "var page = require('webpage').create();\n\npage.open(\"http://localhost:3000/test/index.html\", function (status) {\n  if (status != \"success\") {\n    console.log(\"page couldn't be loaded successfully\");\n    phantom.exit(1);\n  }\n  waitFor(function () {\n    return page.evaluate(function () {\n      var output = document.getElementById('status');\n      if (!output) { return false; }\n      return (/^(\\d+ failures?|all passed)/i).test(output.innerText);\n    });\n  }, function () {\n    var failed = page.evaluate(function () { return window.failed; });\n    var output = page.evaluate(function () {\n      return document.getElementById('output').innerText + \"\\n\" +\n        document.getElementById('status').innerText;\n    });\n    console.log(output);\n    phantom.exit(failed > 0 ? 1 : 0);\n  });\n});\n\nfunction waitFor (test, cb) {\n  if (test()) {\n    cb();\n  } else {\n    setTimeout(function () { waitFor(test, cb); }, 250);\n  }\n}\n"
  },
  {
    "path": "third_party/CodeMirror/test/run.js",
    "content": "#!/usr/bin/env node\n\nvar ok = require(\"./lint\").ok;\n\nvar files = new (require('node-static').Server)();\n\nvar server = require('http').createServer(function (req, res) {\n  req.addListener('end', function () {\n    files.serve(req, res, function (err/*, result */) {\n      if (err) {\n        console.error(err);\n        process.exit(1);\n      }\n    });\n  }).resume();\n}).addListener('error', function (err) {\n  throw err;\n}).listen(3000, function () {\n  var childProcess = require('child_process');\n  var phantomjs = require(\"phantomjs-prebuilt\");\n  var childArgs = [\n    require(\"path\").join(__dirname, 'phantom_driver.js')\n  ];\n  childProcess.execFile(phantomjs.path, childArgs, function (err, stdout, stderr) {\n    server.close();\n    console.log(stdout);\n    if (err) console.error(err);\n    if (stderr) console.error(stderr);\n    process.exit(err || stderr || !ok ? 1 : 0);\n  });\n});\n"
  },
  {
    "path": "third_party/CodeMirror/test/scroll_test.js",
    "content": "(function() {\n  \"use strict\";\n\n  namespace = \"scroll_\";\n\n  testCM(\"bars_hidden\", function(cm) {\n    for (var i = 0;; i++) {\n      var wrapBox = cm.getWrapperElement().getBoundingClientRect();\n      var scrollBox = cm.getScrollerElement().getBoundingClientRect();\n      is(wrapBox.bottom < scrollBox.bottom - 10);\n      is(wrapBox.right < scrollBox.right - 10);\n      if (i == 1) break;\n      cm.getWrapperElement().style.height = \"auto\";\n      cm.refresh();\n    }\n  });\n  \n  function barH(cm) { return byClassName(cm.getWrapperElement(), \"CodeMirror-hscrollbar\")[0]; }\n  function barV(cm) { return byClassName(cm.getWrapperElement(), \"CodeMirror-vscrollbar\")[0]; }\n\n  function displayBottom(cm, scrollbar) {\n    if (scrollbar && cm.display.scroller.offsetHeight > cm.display.scroller.clientHeight)\n      return barH(cm).getBoundingClientRect().top;\n    else\n      return cm.getWrapperElement().getBoundingClientRect().bottom - 1;\n  }\n\n  function displayRight(cm, scrollbar) {\n    if (scrollbar && cm.display.scroller.offsetWidth > cm.display.scroller.clientWidth)\n      return barV(cm).getBoundingClientRect().left;\n    else\n      return cm.getWrapperElement().getBoundingClientRect().right - 1;\n  }\n\n  function testMovedownFixed(cm, hScroll) {\n    cm.setSize(\"100px\", \"100px\");\n    if (hScroll) cm.setValue(new Array(100).join(\"x\"));\n    var bottom = displayBottom(cm, hScroll);\n    for (var i = 0; i < 30; i++) {\n      cm.replaceSelection(\"x\\n\");\n      var cursorBottom = cm.cursorCoords(null, \"window\").bottom;\n      is(cursorBottom <= bottom);\n    }\n    is(cursorBottom >= bottom - 5);\n  }\n\n  testCM(\"movedown_fixed\", function(cm) {testMovedownFixed(cm, false);});\n  testCM(\"movedown_hscroll_fixed\", function(cm) {testMovedownFixed(cm, true);});\n\n  function testMovedownResize(cm, hScroll) {\n    cm.getWrapperElement().style.height = \"auto\";\n    if (hScroll) cm.setValue(new Array(100).join(\"x\"));\n    cm.refresh();\n    for (var i = 0; i < 30; i++) {\n      cm.replaceSelection(\"x\\n\");\n      var bottom = displayBottom(cm, hScroll);\n      var cursorBottom = cm.cursorCoords(null, \"window\").bottom;\n      is(cursorBottom <= bottom);\n      is(cursorBottom >= bottom - 5);\n    }\n  }\n\n  testCM(\"movedown_resize\", function(cm) {testMovedownResize(cm, false);});\n  testCM(\"movedown_hscroll_resize\", function(cm) {testMovedownResize(cm, true);});\n\n  function testMoveright(cm, wrap, scroll) {\n    cm.setSize(\"100px\", \"100px\");\n    if (wrap) cm.setOption(\"lineWrapping\", true);\n    if (scroll) {\n      cm.setValue(\"\\n\" + new Array(100).join(\"x\\n\"));\n      cm.setCursor(Pos(0, 0));\n    }\n    var right = displayRight(cm, scroll);\n    for (var i = 0; i < 10; i++) {\n      cm.replaceSelection(\"xxxxxxxxxx\");\n      var cursorRight = cm.cursorCoords(null, \"window\").right;\n      is(cursorRight < right);\n    }\n    if (!wrap) is(cursorRight > right - 20);\n  }\n\n  testCM(\"moveright\", function(cm) {testMoveright(cm, false, false);});\n  testCM(\"moveright_wrap\", function(cm) {testMoveright(cm, true, false);});\n  testCM(\"moveright_scroll\", function(cm) {testMoveright(cm, false, true);});\n  testCM(\"moveright_scroll_wrap\", function(cm) {testMoveright(cm, true, true);});\n\n  testCM(\"suddenly_wide\", function(cm) {\n    addDoc(cm, 100, 100);\n    cm.replaceSelection(new Array(600).join(\"l \") + \"\\n\");\n    cm.execCommand(\"goLineUp\");\n    cm.execCommand(\"goLineEnd\");\n    is(barH(cm).scrollLeft > cm.getScrollerElement().scrollLeft - 1);\n  });\n\n  testCM(\"wrap_changes_height\", function(cm) {\n    var line = new Array(20).join(\"a \") + \"\\n\";\n    cm.setValue(new Array(20).join(line));\n    var box = cm.getWrapperElement().getBoundingClientRect();\n    cm.setSize(cm.cursorCoords(Pos(0), \"window\").right - box.left + 2,\n               cm.cursorCoords(Pos(19, 0), \"window\").bottom - box.top + 2);\n    cm.setCursor(Pos(19, 0));\n    cm.replaceSelection(\"\\n\");\n    is(cm.cursorCoords(null, \"window\").bottom < displayBottom(cm, false));\n  }, {lineWrapping: true});\n\n  testCM(\"height_auto_with_gutter_expect_no_scroll_after_line_delete\", function(cm) {\n    cm.setSize(null, \"auto\");\n    cm.setValue(\"x\\n\");\n    cm.execCommand(\"goDocEnd\");\n    cm.execCommand(\"delCharBefore\");\n    eq(cm.getScrollInfo().top, 0);\n    cm.scrollTo(null, 10);\n    is(cm.getScrollInfo().top < 5);\n  }, {lineNumbers: true});\n\n  testCM(\"bidi_ensureCursorVisible\", function(cm) {\n    cm.setValue(\"<dd>وضع الاستخدام. عندما لا تعطى، وهذا الافتراضي إلى الطريقة الاولى\\n\");\n    cm.execCommand(\"goLineStart\");\n    eq(cm.getScrollInfo().left, 0);\n    cm.execCommand(\"goCharRight\");\n    cm.execCommand(\"goCharRight\");\n    cm.execCommand(\"goCharRight\");\n    eqCursorPos(cm.getCursor(), Pos(0, 3, \"before\"));\n    eq(cm.getScrollInfo().left, 0);\n  }, {lineWrapping: false});\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/search_test.js",
    "content": "(function() {\n  \"use strict\";\n\n  function run(doc, query, options) {\n    var cursor = doc.getSearchCursor(query, null, options);\n    for (var i = 3; i < arguments.length; i += 4) {\n      var found = cursor.findNext();\n      is(found, \"not enough results (forward)\");\n      eqCharPos(Pos(arguments[i], arguments[i + 1]), cursor.from(), \"from, forward, \" + (i - 3) / 4);\n      eqCharPos(Pos(arguments[i + 2], arguments[i + 3]), cursor.to(), \"to, forward, \" + (i - 3) / 4);\n    }\n    is(!cursor.findNext(), \"too many matches (forward)\");\n    for (var i = arguments.length - 4; i >= 3; i -= 4) {\n      var found = cursor.findPrevious();\n      is(found, \"not enough results (backwards)\");\n      eqCharPos(Pos(arguments[i], arguments[i + 1]), cursor.from(), \"from, backwards, \" + (i - 3) / 4);\n      eqCharPos(Pos(arguments[i + 2], arguments[i + 3]), cursor.to(), \"to, backwards, \" + (i - 3) / 4);\n    }\n    is(!cursor.findPrevious(), \"too many matches (backwards)\");\n  }\n\n  function test(name, f) { window.test(\"search_\" + name, f) }\n\n  test(\"simple\", function() {\n    var doc = new CodeMirror.Doc(\"abcdefg\\nabcdefg\")\n    run(doc, \"cde\", false, 0, 2, 0, 5, 1, 2, 1, 5);\n  });\n\n  test(\"multiline\", function() {\n    var doc = new CodeMirror.Doc(\"hallo\\na\\nb\\ngoodbye\")\n    run(doc, \"llo\\na\\nb\\ngoo\", false, 0, 2, 3, 3);\n    run(doc, \"blah\\na\\nb\\nhall\", false);\n    run(doc, \"bye\\nx\\neye\", false);\n  });\n\n  test(\"regexp\", function() {\n    var doc = new CodeMirror.Doc(\"abcde\\nabcde\")\n    run(doc, /bcd/, false, 0, 1, 0, 4, 1, 1, 1, 4);\n    run(doc, /BCD/, false);\n    run(doc, /BCD/i, false, 0, 1, 0, 4, 1, 1, 1, 4);\n  });\n\n  test(\"regexpMultiline\", function() {\n    var doc = new CodeMirror.Doc(\"foo foo\\nbar\\nbaz\")\n    run(doc, /fo[^]*az/, {multiline: true}, 0, 0, 2, 3)\n    run(doc, /[oa][^u]/, {multiline: true}, 0, 1, 0, 3, 0, 5, 0, 7, 1, 1, 1, 3, 2, 1, 2, 3)\n    run(doc, /[a][^u]{2}/, {multiline: true}, 1, 1, 2, 0)\n  })\n\n  test(\"insensitive\", function() {\n    var doc = new CodeMirror.Doc(\"hallo\\nHALLO\\noink\\nhAllO\")\n    run(doc, \"All\", false, 3, 1, 3, 4);\n    run(doc, \"All\", true, 0, 1, 0, 4, 1, 1, 1, 4, 3, 1, 3, 4);\n  });\n\n  test(\"multilineInsensitive\", function() {\n    var doc = new CodeMirror.Doc(\"zie ginds komT\\nDe Stoomboot\\nuit Spanje weer aan\")\n    run(doc, \"komt\\nde stoomboot\\nuit\", false);\n    run(doc, \"komt\\nde stoomboot\\nuit\", {caseFold: true}, 0, 10, 2, 3);\n    run(doc, \"kOMt\\ndE stOOmboot\\nuiT\", {caseFold: true}, 0, 10, 2, 3);\n  });\n\n  test(\"multilineInsensitiveSlow\", function() {\n    var text = \"\"\n    for (var i = 0; i < 1000; i++) text += \"foo\\nbar\\n\"\n    var doc = new CodeMirror.Doc(\"find\\nme\\n\" + text + \"find\\nme\\n\")\n    var t0 = +new Date\n    run(doc, /find\\nme/, {multiline: true}, 0, 0, 1, 2, 2002, 0, 2003, 2)\n    is(+new Date - t0 < 100)\n  })\n\n  test(\"expandingCaseFold\", function() {\n    var doc = new CodeMirror.Doc(\"<b>İİ İİ</b>\\n<b>uu uu</b>\")\n    run(doc, \"</b>\", true, 0, 8, 0, 12, 1, 8, 1, 12);\n    run(doc, \"İİ\", true, 0, 3, 0, 5, 0, 6, 0, 8);\n  });\n\n  test(\"normalize\", function() {\n    if (!String.prototype.normalize) return\n    var doc = new CodeMirror.Doc(\"yılbaşı\\n수 있을까\\nLe taux d'humidité à London\")\n    run(doc, \"s\", false, 0, 5, 0, 6)\n    run(doc, \"이\", false, 1, 2, 1, 3)\n    run(doc, \"a\", false, 0, 4, 0, 5, 2, 4, 2, 5, 2, 19, 2, 20)\n  })\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/sql-hint-test.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function() {\n  var Pos = CodeMirror.Pos;\n\n  var simpleTables = {\n    \"users\": [\"name\", \"score\", \"birthDate\"],\n    \"xcountries\": [\"name\", \"population\", \"size\"]\n  };\n\n  var schemaTables = {\n    \"schema.users\": [\"name\", \"score\", \"birthDate\"],\n    \"schema.countries\": [\"name\", \"population\", \"size\"]\n  };\n\n  var displayTextTables = [{\n    text: \"mytable\",\n    displayText: \"mytable | The main table\",\n    columns: [{text: \"id\", displayText: \"id | Unique ID\"},\n              {text: \"name\", displayText: \"name | The name\"}]\n  }];\n\n  namespace = \"sql-hint_\";\n\n  function test(name, spec) {\n    testCM(name, function(cm) {\n      cm.setValue(spec.value);\n      cm.setCursor(spec.cursor);\n      var completion = CodeMirror.hint.sql(cm, {tables: spec.tables});\n      if (!deepCompare(completion.list, spec.list))\n        throw new Failure(\"Wrong completion results \" + JSON.stringify(completion.list) + \" vs \" + JSON.stringify(spec.list));\n      eqCharPos(completion.from, spec.from);\n      eqCharPos(completion.to, spec.to);\n    }, {\n      value: spec.value,\n      mode: spec.mode || \"text/x-mysql\"\n    });\n  }\n\n  test(\"keywords\", {\n    value: \"SEL\",\n    cursor: Pos(0, 3),\n    list: [{\"text\":\"SELECT\",\"className\":\"CodeMirror-hint-keyword\"}],\n    from: Pos(0, 0),\n    to: Pos(0, 3)\n  });\n\n  test(\"from\", {\n    value: \"SELECT * fr\",\n    cursor: Pos(0, 11),\n    list: [{\"text\":\"FROM\",\"className\":\"CodeMirror-hint-keyword\"}],\n    from: Pos(0, 9),\n    to: Pos(0, 11)\n  });\n\n  test(\"table\", {\n    value: \"SELECT xc\",\n    cursor: Pos(0, 9),\n    tables: simpleTables,\n    list: [{\"text\":\"xcountries\",\"className\":\"CodeMirror-hint-table\"}],\n    from: Pos(0, 7),\n    to: Pos(0, 9)\n  });\n\n  test(\"columns\", {\n    value: \"SELECT users.\",\n    cursor: Pos(0, 13),\n    tables: simpleTables,\n    list: [\"users.name\", \"users.score\", \"users.birthDate\"],\n    from: Pos(0, 7),\n    to: Pos(0, 13)\n  });\n\n  test(\"singlecolumn\", {\n    value: \"SELECT users.na\",\n    cursor: Pos(0, 15),\n    tables: simpleTables,\n    list: [\"users.name\"],\n    from: Pos(0, 7),\n    to: Pos(0, 15)\n  });\n\n  test(\"quoted\", {\n    value: \"SELECT `users`.`na\",\n    cursor: Pos(0, 18),\n    tables: simpleTables,\n    list: [\"`users`.`name`\"],\n    from: Pos(0, 7),\n    to: Pos(0, 18)\n  });\n\n  test(\"doublequoted\", {\n    value: \"SELECT \\\"users\\\".\\\"na\",\n    cursor: Pos(0, 18),\n    tables: simpleTables,\n    list: [\"\\\"users\\\".\\\"name\\\"\"],\n    from: Pos(0, 7),\n    to: Pos(0, 18),\n    mode: \"text/x-sqlite\"\n  });\n\n  test(\"quotedcolumn\", {\n    value: \"SELECT users.`na\",\n    cursor: Pos(0, 16),\n    tables: simpleTables,\n    list: [\"`users`.`name`\"],\n    from: Pos(0, 7),\n    to: Pos(0, 16)\n  });\n\n  test(\"doublequotedcolumn\", {\n    value: \"SELECT users.\\\"na\",\n    cursor: Pos(0, 16),\n    tables: simpleTables,\n    list: [\"\\\"users\\\".\\\"name\\\"\"],\n    from: Pos(0, 7),\n    to: Pos(0, 16),\n    mode: \"text/x-sqlite\"\n  });\n\n  test(\"schema\", {\n    value: \"SELECT schem\",\n    cursor: Pos(0, 12),\n    tables: schemaTables,\n    list: [{\"text\":\"schema.users\",\"className\":\"CodeMirror-hint-table\"},\n        {\"text\":\"schema.countries\",\"className\":\"CodeMirror-hint-table\"},\n        {\"text\":\"SCHEMA\",\"className\":\"CodeMirror-hint-keyword\"},\n        {\"text\":\"SCHEMA_NAME\",\"className\":\"CodeMirror-hint-keyword\"},\n        {\"text\":\"SCHEMAS\",\"className\":\"CodeMirror-hint-keyword\"}],\n    from: Pos(0, 7),\n    to: Pos(0, 12)\n  });\n\n  test(\"schemaquoted\", {\n    value: \"SELECT `sch\",\n    cursor: Pos(0, 11),\n    tables: schemaTables,\n    list: [\"`schema`.`users`\", \"`schema`.`countries`\"],\n    from: Pos(0, 7),\n    to: Pos(0, 11)\n  });\n\n  test(\"schemadoublequoted\", {\n    value: \"SELECT \\\"sch\",\n    cursor: Pos(0, 11),\n    tables: schemaTables,\n    list: [\"\\\"schema\\\".\\\"users\\\"\", \"\\\"schema\\\".\\\"countries\\\"\"],\n    from: Pos(0, 7),\n    to: Pos(0, 11),\n    mode: \"text/x-sqlite\"\n  });\n\n  test(\"schemacolumn\", {\n    value: \"SELECT schema.users.\",\n    cursor: Pos(0, 20),\n    tables: schemaTables,\n    list: [\"schema.users.name\",\n           \"schema.users.score\",\n           \"schema.users.birthDate\"],\n    from: Pos(0, 7),\n    to: Pos(0, 20)\n  });\n\n  test(\"schemacolumnquoted\", {\n    value: \"SELECT `schema`.`users`.\",\n    cursor: Pos(0, 24),\n    tables: schemaTables,\n    list: [\"`schema`.`users`.`name`\",\n           \"`schema`.`users`.`score`\",\n           \"`schema`.`users`.`birthDate`\"],\n    from: Pos(0, 7),\n    to: Pos(0, 24)\n  });\n\n  test(\"schemacolumndoublequoted\", {\n    value: \"SELECT \\\"schema\\\".\\\"users\\\".\",\n    cursor: Pos(0, 24),\n    tables: schemaTables,\n    list: [\"\\\"schema\\\".\\\"users\\\".\\\"name\\\"\",\n           \"\\\"schema\\\".\\\"users\\\".\\\"score\\\"\",\n           \"\\\"schema\\\".\\\"users\\\".\\\"birthDate\\\"\"],\n    from: Pos(0, 7),\n    to: Pos(0, 24),\n    mode: \"text/x-sqlite\"\n  });\n\n  test(\"displayText_table\", {\n    value: \"SELECT myt\",\n    cursor: Pos(0, 10),\n    tables: displayTextTables,\n    list: [{text: \"mytable\", displayText: \"mytable | The main table\", \"className\":\"CodeMirror-hint-table\"}],\n    from: Pos(0, 7),\n    to: Pos(0, 10)\n  });\n\n  test(\"displayText_column\", {\n    value: \"SELECT mytable.\",\n    cursor: Pos(0, 15),\n    tables: displayTextTables,\n    list: [{text: \"mytable.id\", displayText: \"id | Unique ID\"},\n           {text: \"mytable.name\", displayText: \"name | The name\"}],\n    from: Pos(0, 7),\n    to: Pos(0, 15)\n  });\n\n  test(\"alias_complete\", {\n    value: \"SELECT t. FROM users t\",\n    cursor: Pos(0, 9),\n    tables: simpleTables,\n    list: [\"t.name\", \"t.score\", \"t.birthDate\"],\n    from: Pos(0, 7),\n    to: Pos(0, 9)\n  });\n\n  test(\"alias_complete_with_displayText\", {\n    value: \"SELECT t. FROM mytable t\",\n    cursor: Pos(0, 9),\n    tables: displayTextTables,\n    list: [{text: \"t.id\", displayText: \"id | Unique ID\"},\n           {text: \"t.name\", displayText: \"name | The name\"}],\n    from: Pos(0, 7),\n    to: Pos(0, 9)\n  })\n\n  function deepCompare(a, b) {\n    if (a === b) return true\n    if (!(a && typeof a == \"object\") ||\n        !(b && typeof b == \"object\")) return false\n    var array = Array.isArray(a)\n    if (Array.isArray(b) != array) return false\n    if (array) {\n      if (a.length != b.length) return false\n      for (var i = 0; i < a.length; i++) if (!deepCompare(a[i], b[i])) return false\n    } else {\n      for (var p in a) if (!(p in b) || !deepCompare(a[p], b[p])) return false\n      for (var p in b) if (!(p in a)) return false\n    }\n    return true\n  }\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/sublime_test.js",
    "content": "(function() {\n  \"use strict\";\n  \n  var Pos = CodeMirror.Pos;\n  namespace = \"sublime_\";\n\n  function stTest(name) {\n    var actions = Array.prototype.slice.call(arguments, 1);\n    testCM(name, function(cm) {\n      for (var i = 0; i < actions.length; i++) {\n        var action = actions[i];\n        if (typeof action == \"string\" && i == 0)\n          cm.setValue(action);\n        else if (typeof action == \"string\")\n          cm.execCommand(action);\n        else if (action instanceof Pos)\n          cm.setCursor(action);\n        else\n          action(cm);\n      }\n    });\n  }\n\n  function at(line, ch, msg) {\n    return function(cm) {\n      eq(cm.listSelections().length, 1);\n      eqCursorPos(cm.getCursor(\"head\"), Pos(line, ch), msg);\n      eqCursorPos(cm.getCursor(\"anchor\"), Pos(line, ch), msg);\n    };\n  }\n\n  function val(content, msg) {\n    return function(cm) { eq(cm.getValue(), content, msg); };\n  }\n\n  function argsToRanges(args) {\n    if (args.length % 4) throw new Error(\"Wrong number of arguments for ranges.\");\n    var ranges = [];\n    for (var i = 0; i < args.length; i += 4)\n      ranges.push({anchor: Pos(args[i], args[i + 1]),\n                   head: Pos(args[i + 2], args[i + 3])});\n    return ranges;\n  }\n\n  function setSel() {\n    var ranges = argsToRanges(arguments);\n    return function(cm) { cm.setSelections(ranges, 0); };\n  }\n\n  function hasSel() {\n    var ranges = argsToRanges(arguments);\n    return function(cm) {\n      var sels = cm.listSelections();\n      if (sels.length != ranges.length)\n        throw new Failure(\"Expected \" + ranges.length + \" selections, but found \" + sels.length);\n      for (var i = 0; i < sels.length; i++) {\n        eqCharPos(sels[i].anchor, ranges[i].anchor, \"anchor \" + i);\n        eqCharPos(sels[i].head, ranges[i].head, \"head \" + i);\n      }\n    };\n  }\n\n  stTest(\"bySubword\", \"the foo_bar DooDahBah \\n a\",\n         \"goSubwordLeft\", at(0, 0),\n         \"goSubwordRight\", at(0, 3),\n         \"goSubwordRight\", at(0, 7),\n         \"goSubwordRight\", at(0, 11),\n         \"goSubwordRight\", at(0, 15),\n         \"goSubwordRight\", at(0, 18),\n         \"goSubwordRight\", at(0, 21),\n         \"goSubwordRight\", at(0, 22),\n         \"goSubwordRight\", at(1, 0),\n         \"goSubwordRight\", at(1, 2),\n         \"goSubwordRight\", at(1, 2),\n         \"goSubwordLeft\", at(1, 1),\n         \"goSubwordLeft\", at(1, 0),\n         \"goSubwordLeft\", at(0, 22),\n         \"goSubwordLeft\", at(0, 18),\n         \"goSubwordLeft\", at(0, 15),\n         \"goSubwordLeft\", at(0, 12),\n         \"goSubwordLeft\", at(0, 8),\n         \"goSubwordLeft\", at(0, 4),\n         \"goSubwordLeft\", at(0, 0));\n\n  stTest(\"splitSelectionByLine\", \"abc\\ndef\\nghi\",\n         setSel(0, 1, 2, 2),\n         \"splitSelectionByLine\",\n         hasSel(0, 1, 0, 3,\n                1, 0, 1, 3,\n                2, 0, 2, 2));\n\n  stTest(\"splitSelectionByLineMulti\", \"abc\\ndef\\nghi\\njkl\",\n         setSel(0, 1, 1, 1,\n                1, 2, 3, 2,\n                3, 3, 3, 3),\n         \"splitSelectionByLine\",\n         hasSel(0, 1, 0, 3,\n                1, 0, 1, 1,\n                1, 2, 1, 3,\n                2, 0, 2, 3,\n                3, 0, 3, 2,\n                3, 3, 3, 3));\n\n  stTest(\"selectLine\", \"abc\\ndef\\nghi\",\n         setSel(0, 1, 0, 1,\n                2, 0, 2, 1),\n         \"selectLine\",\n         hasSel(0, 0, 1, 0,\n                2, 0, 2, 3),\n         setSel(0, 1, 1, 0),\n         \"selectLine\",\n         hasSel(0, 0, 2, 0));\n\n  stTest(\"insertLineAfter\", \"abcde\\nfghijkl\\nmn\",\n         setSel(0, 1, 0, 1,\n                0, 3, 0, 3,\n                1, 2, 1, 2,\n                1, 3, 1, 5), \"insertLineAfter\",\n         hasSel(1, 0, 1, 0,\n                3, 0, 3, 0), val(\"abcde\\n\\nfghijkl\\n\\nmn\"));\n\n  stTest(\"insertLineBefore\", \"abcde\\nfghijkl\\nmn\",\n         setSel(0, 1, 0, 1,\n                0, 3, 0, 3,\n                1, 2, 1, 2,\n                1, 3, 1, 5), \"insertLineBefore\",\n         hasSel(0, 0, 0, 0,\n                2, 0, 2, 0), val(\"\\nabcde\\n\\nfghijkl\\nmn\"));\n\n  stTest(\"selectNextOccurrence\", \"a foo bar\\nfoobar foo\",\n         setSel(0, 2, 0, 5),\n         \"selectNextOccurrence\", hasSel(0, 2, 0, 5,\n                                        1, 0, 1, 3),\n         \"selectNextOccurrence\", hasSel(0, 2, 0, 5,\n                                        1, 0, 1, 3,\n                                        1, 7, 1, 10),\n         \"selectNextOccurrence\", hasSel(0, 2, 0, 5,\n                                        1, 0, 1, 3,\n                                        1, 7, 1, 10),\n         Pos(0, 3), \"selectNextOccurrence\", hasSel(0, 2, 0, 5),\n        \"selectNextOccurrence\", hasSel(0, 2, 0, 5,\n                                       1, 7, 1, 10),\n         setSel(0, 6, 0, 9),\n         \"selectNextOccurrence\", hasSel(0, 6, 0, 9,\n                                        1, 3, 1, 6));\n\n  stTest(\"selectScope\", \"foo(a) {\\n  bar[1, 2];\\n}\",\n         \"selectScope\", hasSel(0, 0, 2, 1),\n         Pos(0, 4), \"selectScope\", hasSel(0, 4, 0, 5),\n         Pos(0, 5), \"selectScope\", hasSel(0, 4, 0, 5),\n         Pos(0, 6), \"selectScope\", hasSel(0, 0, 2, 1),\n         Pos(0, 8), \"selectScope\", hasSel(0, 8, 2, 0),\n         Pos(1, 2), \"selectScope\", hasSel(0, 8, 2, 0),\n         Pos(1, 6), \"selectScope\", hasSel(1, 6, 1, 10),\n         Pos(1, 9), \"selectScope\", hasSel(1, 6, 1, 10),\n         \"selectScope\", hasSel(0, 8, 2, 0),\n         \"selectScope\", hasSel(0, 0, 2, 1));\n\n  stTest(\"goToBracket\", \"foo(a) {\\n  bar[1, 2];\\n}\",\n         Pos(0, 0), \"goToBracket\", at(0, 0),\n         Pos(0, 4), \"goToBracket\", at(0, 5), \"goToBracket\", at(0, 4),\n         Pos(0, 8), \"goToBracket\", at(2, 0), \"goToBracket\", at(0, 8),\n         Pos(1, 2), \"goToBracket\", at(2, 0),\n         Pos(1, 7), \"goToBracket\", at(1, 10), \"goToBracket\", at(1, 6));\n\n  stTest(\"swapLine\", \"1\\n2\\n3---\\n4\\n5\",\n         \"swapLineDown\", val(\"2\\n1\\n3---\\n4\\n5\"),\n         \"swapLineUp\", val(\"1\\n2\\n3---\\n4\\n5\"),\n         \"swapLineUp\", val(\"1\\n2\\n3---\\n4\\n5\"),\n         Pos(4, 1), \"swapLineDown\", val(\"1\\n2\\n3---\\n4\\n5\"),\n         setSel(0, 1, 0, 1,\n                1, 0, 2, 0,\n                2, 2, 2, 2),\n         \"swapLineDown\", val(\"4\\n1\\n2\\n3---\\n5\"),\n         hasSel(1, 1, 1, 1,\n                2, 0, 3, 0,\n                3, 2, 3, 2),\n         \"swapLineUp\", val(\"1\\n2\\n3---\\n4\\n5\"),\n         hasSel(0, 1, 0, 1,\n                1, 0, 2, 0,\n                2, 2, 2, 2));\n\n  stTest(\"swapLineEmptyBottomSel\", \"1\\n2\\n3\",\n         setSel(0, 1, 1, 0),\n         \"swapLineDown\", val(\"2\\n1\\n3\"), hasSel(1, 1, 2, 0),\n         \"swapLineUp\", val(\"1\\n2\\n3\"), hasSel(0, 1, 1, 0),\n         \"swapLineUp\", val(\"1\\n2\\n3\"), hasSel(0, 0, 0, 0));\n\n  stTest(\"swapLineUpFromEnd\", \"a\\nb\\nc\",\n         Pos(2, 1), \"swapLineUp\",\n         hasSel(1, 1, 1, 1), val(\"a\\nc\\nb\"));\n\n  stTest(\"joinLines\", \"abc\\ndef\\nghi\\njkl\",\n         \"joinLines\", val(\"abc def\\nghi\\njkl\"), at(0, 4),\n         \"undo\",\n         setSel(0, 2, 1, 1), \"joinLines\",\n         val(\"abc def ghi\\njkl\"), hasSel(0, 2, 0, 8),\n         \"undo\",\n         setSel(0, 1, 0, 1,\n                1, 1, 1, 1,\n                3, 1, 3, 1), \"joinLines\",\n         val(\"abc def ghi\\njkl\"), hasSel(0, 4, 0, 4,\n                                         0, 8, 0, 8,\n                                         1, 3, 1, 3));\n\n  stTest(\"duplicateLine\", \"abc\\ndef\\nghi\",\n         Pos(1, 0), \"duplicateLine\", val(\"abc\\ndef\\ndef\\nghi\"), at(2, 0),\n         \"undo\",\n         setSel(0, 1, 0, 1,\n                1, 1, 1, 1,\n                2, 1, 2, 1), \"duplicateLine\",\n         val(\"abc\\nabc\\ndef\\ndef\\nghi\\nghi\"), hasSel(1, 1, 1, 1,\n                                                     3, 1, 3, 1,\n                                                     5, 1, 5, 1));\n  stTest(\"duplicateLineSelection\", \"abcdef\",\n         setSel(0, 1, 0, 1,\n                0, 2, 0, 4,\n                0, 5, 0, 5),\n         \"duplicateLine\",\n         val(\"abcdef\\nabcdcdef\\nabcdcdef\"), hasSel(2, 1, 2, 1,\n                                                   2, 4, 2, 6,\n                                                   2, 7, 2, 7));\n\n  stTest(\"sortLines\", \"c\\nb\\na\\nC\\nB\\nA\",\n         \"sortLines\", val(\"A\\nB\\nC\\na\\nb\\nc\"),\n         \"undo\",\n         setSel(0, 0, 2, 0,\n                3, 0, 5, 0),\n         \"sortLines\", val(\"b\\nc\\na\\nB\\nC\\nA\"),\n         hasSel(0, 0, 2, 0,\n                3, 0, 5, 0),\n         \"undo\",\n         setSel(1, 0, 5, 0), \"sortLinesInsensitive\", val(\"c\\na\\nB\\nb\\nC\\nA\"));\n\n  stTest(\"bookmarks\", \"abc\\ndef\\nghi\\njkl\",\n         Pos(0, 1), \"toggleBookmark\",\n         setSel(1, 1, 1, 2), \"toggleBookmark\",\n         setSel(2, 1, 2, 2), \"toggleBookmark\",\n         \"nextBookmark\", hasSel(0, 1, 0, 1),\n         \"nextBookmark\", hasSel(1, 1, 1, 2),\n         \"nextBookmark\", hasSel(2, 1, 2, 2),\n         \"prevBookmark\", hasSel(1, 1, 1, 2),\n         \"prevBookmark\", hasSel(0, 1, 0, 1),\n         \"prevBookmark\", hasSel(2, 1, 2, 2),\n         \"prevBookmark\", hasSel(1, 1, 1, 2),\n         \"toggleBookmark\",\n         \"prevBookmark\", hasSel(2, 1, 2, 2),\n         \"prevBookmark\", hasSel(0, 1, 0, 1),\n         \"selectBookmarks\", hasSel(0, 1, 0, 1,\n                                   2, 1, 2, 2),\n         \"clearBookmarks\",\n         Pos(0, 0), \"selectBookmarks\", at(0, 0));\n\n  stTest(\"smartBackspace\", \"  foo\\n    bar\",\n         setSel(0, 2, 0, 2, 1, 4, 1, 4, 1, 6, 1, 6), \"smartBackspace\",\n         val(\"foo\\n  br\"))\n\n  stTest(\"upAndDowncaseAtCursor\", \"abc\\ndef  x\\nghI\",\n         setSel(0, 1, 0, 3,\n                1, 1, 1, 1,\n                1, 4, 1, 4), \"upcaseAtCursor\",\n         val(\"aBC\\nDEF  x\\nghI\"), hasSel(0, 1, 0, 3,\n                                         1, 3, 1, 3,\n                                         1, 4, 1, 4),\n         \"downcaseAtCursor\",\n         val(\"abc\\ndef  x\\nghI\"), hasSel(0, 1, 0, 3,\n                                         1, 3, 1, 3,\n                                         1, 4, 1, 4));\n\n  stTest(\"mark\", \"abc\\ndef\\nghi\",\n         Pos(1, 1), \"setSublimeMark\",\n         Pos(2, 1), \"selectToSublimeMark\", hasSel(2, 1, 1, 1),\n         Pos(0, 1), \"swapWithSublimeMark\", at(1, 1), \"swapWithSublimeMark\", at(0, 1),\n         \"deleteToSublimeMark\", val(\"aef\\nghi\"),\n         \"sublimeYank\", val(\"abc\\ndef\\nghi\"), at(1, 1));\n\n  stTest(\"findUnder\", \"foo foobar  a\",\n         \"findUnder\", hasSel(0, 4, 0, 7),\n         \"findUnder\", hasSel(0, 0, 0, 3),\n         \"findUnderPrevious\", hasSel(0, 4, 0, 7),\n         \"findUnderPrevious\", hasSel(0, 0, 0, 3),\n         Pos(0, 4), \"findUnder\", hasSel(0, 4, 0, 10),\n         Pos(0, 11), \"findUnder\", hasSel(0, 11, 0, 11));\n})();\n"
  },
  {
    "path": "third_party/CodeMirror/test/test.js",
    "content": "var Pos = CodeMirror.Pos;\n\nCodeMirror.defaults.rtlMoveVisually = true;\n\nfunction forEach(arr, f) {\n  for (var i = 0, e = arr.length; i < e; ++i) f(arr[i], i);\n}\n\nfunction addDoc(cm, width, height) {\n  var content = [], line = \"\";\n  for (var i = 0; i < width; ++i) line += \"x\";\n  for (var i = 0; i < height; ++i) content.push(line);\n  cm.setValue(content.join(\"\\n\"));\n}\n\nfunction byClassName(elt, cls) {\n  if (elt.getElementsByClassName) return elt.getElementsByClassName(cls);\n  var found = [], re = new RegExp(\"\\\\b\" + cls + \"\\\\b\");\n  function search(elt) {\n    if (elt.nodeType == 3) return;\n    if (re.test(elt.className)) found.push(elt);\n    for (var i = 0, e = elt.childNodes.length; i < e; ++i)\n      search(elt.childNodes[i]);\n  }\n  search(elt);\n  return found;\n}\n\nvar ie_lt8 = /MSIE [1-7]\\b/.test(navigator.userAgent);\nvar ie_lt9 = /MSIE [1-8]\\b/.test(navigator.userAgent);\nvar mac = /Mac/.test(navigator.platform);\nvar phantom = /PhantomJS/.test(navigator.userAgent);\nvar opera = /Opera\\/\\./.test(navigator.userAgent);\nvar opera_version = opera && navigator.userAgent.match(/Version\\/(\\d+\\.\\d+)/);\nif (opera_version) opera_version = Number(opera_version);\nvar opera_lt10 = opera && (!opera_version || opera_version < 10);\n\nnamespace = \"core_\";\n\ntest(\"core_fromTextArea\", function() {\n  var te = document.getElementById(\"code\");\n  te.value = \"CONTENT\";\n  var cm = CodeMirror.fromTextArea(te);\n  is(!te.offsetHeight);\n  eq(cm.getValue(), \"CONTENT\");\n  cm.setValue(\"foo\\nbar\");\n  eq(cm.getValue(), \"foo\\nbar\");\n  cm.save();\n  is(/^foo\\r?\\nbar$/.test(te.value));\n  cm.setValue(\"xxx\");\n  cm.toTextArea();\n  is(te.offsetHeight);\n  eq(te.value, \"xxx\");\n});\n\ntestCM(\"getRange\", function(cm) {\n  eq(cm.getLine(0), \"1234\");\n  eq(cm.getLine(1), \"5678\");\n  eq(cm.getLine(2), null);\n  eq(cm.getLine(-1), null);\n  eq(cm.getRange(Pos(0, 0), Pos(0, 3)), \"123\");\n  eq(cm.getRange(Pos(0, -1), Pos(0, 200)), \"1234\");\n  eq(cm.getRange(Pos(0, 2), Pos(1, 2)), \"34\\n56\");\n  eq(cm.getRange(Pos(1, 2), Pos(100, 0)), \"78\");\n}, {value: \"1234\\n5678\"});\n\ntestCM(\"replaceRange\", function(cm) {\n  eq(cm.getValue(), \"\");\n  cm.replaceRange(\"foo\\n\", Pos(0, 0));\n  eq(cm.getValue(), \"foo\\n\");\n  cm.replaceRange(\"a\\nb\", Pos(0, 1));\n  eq(cm.getValue(), \"fa\\nboo\\n\");\n  eq(cm.lineCount(), 3);\n  cm.replaceRange(\"xyzzy\", Pos(0, 0), Pos(1, 1));\n  eq(cm.getValue(), \"xyzzyoo\\n\");\n  cm.replaceRange(\"abc\", Pos(0, 0), Pos(10, 0));\n  eq(cm.getValue(), \"abc\");\n  eq(cm.lineCount(), 1);\n});\n\ntestCM(\"selection\", function(cm) {\n  cm.setSelection(Pos(0, 4), Pos(2, 2));\n  is(cm.somethingSelected());\n  eq(cm.getSelection(), \"11\\n222222\\n33\");\n  eqCursorPos(cm.getCursor(false), Pos(2, 2));\n  eqCursorPos(cm.getCursor(true), Pos(0, 4));\n  cm.setSelection(Pos(1, 0));\n  is(!cm.somethingSelected());\n  eq(cm.getSelection(), \"\");\n  eqCursorPos(cm.getCursor(true), Pos(1, 0));\n  cm.replaceSelection(\"abc\", \"around\");\n  eq(cm.getSelection(), \"abc\");\n  eq(cm.getValue(), \"111111\\nabc222222\\n333333\");\n  cm.replaceSelection(\"def\", \"end\");\n  eq(cm.getSelection(), \"\");\n  eqCursorPos(cm.getCursor(true), Pos(1, 3));\n  cm.setCursor(Pos(2, 1));\n  eqCursorPos(cm.getCursor(true), Pos(2, 1));\n  cm.setCursor(1, 2);\n  eqCursorPos(cm.getCursor(true), Pos(1, 2));\n}, {value: \"111111\\n222222\\n333333\"});\n\ntestCM(\"extendSelection\", function(cm) {\n  cm.setExtending(true);\n  addDoc(cm, 10, 10);\n  cm.setSelection(Pos(3, 5));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(3, 5));\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(3, 5));\n  cm.setSelection(Pos(2, 5), Pos(5, 5));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(5, 5));\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(2, 5));\n  eqCursorPos(cm.getCursor(\"start\"), Pos(2, 5));\n  eqCursorPos(cm.getCursor(\"end\"), Pos(5, 5));\n  cm.setSelection(Pos(5, 5), Pos(2, 5));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(2, 5));\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(5, 5));\n  eqCursorPos(cm.getCursor(\"start\"), Pos(2, 5));\n  eqCursorPos(cm.getCursor(\"end\"), Pos(5, 5));\n  cm.extendSelection(Pos(3, 2));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(3, 2));\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(5, 5));\n  cm.extendSelection(Pos(6, 2));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(6, 2));\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(5, 5));\n  cm.extendSelection(Pos(6, 3), Pos(6, 4));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(6, 4));\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(5, 5));\n  cm.extendSelection(Pos(0, 3), Pos(0, 4));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(0, 3));\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(5, 5));\n  cm.extendSelection(Pos(4, 5), Pos(6, 5));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(6, 5));\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(4, 5));\n  cm.setExtending(false);\n  cm.extendSelection(Pos(0, 3), Pos(0, 4));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(0, 3));\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(0, 4));\n});\n\ntestCM(\"lines\", function(cm) {\n  eq(cm.getLine(0), \"111111\");\n  eq(cm.getLine(1), \"222222\");\n  eq(cm.getLine(-1), null);\n  cm.replaceRange(\"\", Pos(1, 0), Pos(2, 0))\n  cm.replaceRange(\"abc\", Pos(1, 0), Pos(1));\n  eq(cm.getValue(), \"111111\\nabc\");\n}, {value: \"111111\\n222222\\n333333\"});\n\ntestCM(\"indent\", function(cm) {\n  cm.indentLine(1);\n  eq(cm.getLine(1), \"   blah();\");\n  cm.setOption(\"indentUnit\", 8);\n  cm.indentLine(1);\n  eq(cm.getLine(1), \"\\tblah();\");\n  cm.setOption(\"indentUnit\", 10);\n  cm.setOption(\"tabSize\", 4);\n  cm.indentLine(1);\n  eq(cm.getLine(1), \"\\t\\t  blah();\");\n}, {value: \"if (x) {\\nblah();\\n}\", indentUnit: 3, indentWithTabs: true, tabSize: 8});\n\ntestCM(\"indentByNumber\", function(cm) {\n  cm.indentLine(0, 2);\n  eq(cm.getLine(0), \"  foo\");\n  cm.indentLine(0, -200);\n  eq(cm.getLine(0), \"foo\");\n  cm.setSelection(Pos(0, 0), Pos(1, 2));\n  cm.indentSelection(3);\n  eq(cm.getValue(), \"   foo\\n   bar\\nbaz\");\n}, {value: \"foo\\nbar\\nbaz\"});\n\ntest(\"core_defaults\", function() {\n  var defsCopy = {}, defs = CodeMirror.defaults;\n  for (var opt in defs) defsCopy[opt] = defs[opt];\n  defs.indentUnit = 5;\n  defs.value = \"uu\";\n  defs.indentWithTabs = true;\n  defs.tabindex = 55;\n  var place = document.getElementById(\"testground\"), cm = CodeMirror(place);\n  try {\n    eq(cm.getOption(\"indentUnit\"), 5);\n    cm.setOption(\"indentUnit\", 10);\n    eq(defs.indentUnit, 5);\n    eq(cm.getValue(), \"uu\");\n    eq(cm.getOption(\"indentWithTabs\"), true);\n    eq(cm.getInputField().tabIndex, 55);\n  }\n  finally {\n    for (var opt in defsCopy) defs[opt] = defsCopy[opt];\n    place.removeChild(cm.getWrapperElement());\n  }\n});\n\ntestCM(\"lineInfo\", function(cm) {\n  eq(cm.lineInfo(-1), null);\n  var mark = document.createElement(\"span\");\n  var lh = cm.setGutterMarker(1, \"FOO\", mark);\n  var info = cm.lineInfo(1);\n  eq(info.text, \"222222\");\n  eq(info.gutterMarkers.FOO, mark);\n  eq(info.line, 1);\n  eq(cm.lineInfo(2).gutterMarkers, null);\n  cm.setGutterMarker(lh, \"FOO\", null);\n  eq(cm.lineInfo(1).gutterMarkers, null);\n  cm.setGutterMarker(1, \"FOO\", mark);\n  cm.setGutterMarker(0, \"FOO\", mark);\n  cm.clearGutter(\"FOO\");\n  eq(cm.lineInfo(0).gutterMarkers, null);\n  eq(cm.lineInfo(1).gutterMarkers, null);\n}, {value: \"111111\\n222222\\n333333\"});\n\ntestCM(\"coords\", function(cm) {\n  cm.setSize(null, 100);\n  addDoc(cm, 32, 200);\n  var top = cm.charCoords(Pos(0, 0));\n  var bot = cm.charCoords(Pos(200, 30));\n  is(top.left < bot.left);\n  is(top.top < bot.top);\n  is(top.top < top.bottom);\n  cm.scrollTo(null, 100);\n  var top2 = cm.charCoords(Pos(0, 0));\n  is(top.top > top2.top);\n  eq(top.left, top2.left);\n});\n\ntestCM(\"coordsChar\", function(cm) {\n  addDoc(cm, 35, 70);\n  for (var i = 0; i < 2; ++i) {\n    var sys = i ? \"local\" : \"page\";\n    for (var ch = 0; ch <= 35; ch += 5) {\n      for (var line = 0; line < 70; line += 5) {\n        cm.setCursor(line, ch);\n        var coords = cm.charCoords(Pos(line, ch), sys);\n        var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys);\n        eqCharPos(pos, Pos(line, ch));\n      }\n    }\n  }\n}, {lineNumbers: true});\n\ntestCM(\"coordsCharBidi\", function(cm) {\n  addDoc(cm, 35, 70);\n  // Put an rtl character into each line to trigger the bidi code path in coordsChar\n  cm.setValue(cm.getValue().replace(/\\bx/g, 'و'))\n  for (var i = 0; i < 2; ++i) {\n    var sys = i ? \"local\" : \"page\";\n    for (var ch = 2; ch <= 35; ch += 5) {\n      for (var line = 0; line < 70; line += 5) {\n        cm.setCursor(line, ch);\n        var coords = cm.charCoords(Pos(line, ch), sys);\n        var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys);\n        eqCharPos(pos, Pos(line, ch));\n      }\n    }\n  }\n}, {lineNumbers: true});\n\ntestCM(\"badBidiOptimization\", function(cm) {\n  var coords = cm.charCoords(Pos(0, 34))\n  eqCharPos(cm.coordsChar({left: coords.right, top: coords.top + 2}), Pos(0, 34))\n}, {value: \"----------<p class=\\\"title\\\">هل يمكنك اختيار مستوى قسط التأمين الذي ترغب بدفعه؟</p>\"})\n\ntestCM(\"posFromIndex\", function(cm) {\n  cm.setValue(\n    \"This function should\\n\" +\n    \"convert a zero based index\\n\" +\n    \"to line and ch.\"\n  );\n\n  var examples = [\n    { index: -1, line: 0, ch: 0  }, // <- Tests clipping\n    { index: 0,  line: 0, ch: 0  },\n    { index: 10, line: 0, ch: 10 },\n    { index: 39, line: 1, ch: 18 },\n    { index: 55, line: 2, ch: 7  },\n    { index: 63, line: 2, ch: 15 },\n    { index: 64, line: 2, ch: 15 }  // <- Tests clipping\n  ];\n\n  for (var i = 0; i < examples.length; i++) {\n    var example = examples[i];\n    var pos = cm.posFromIndex(example.index);\n    eq(pos.line, example.line);\n    eq(pos.ch, example.ch);\n    if (example.index >= 0 && example.index < 64)\n      eq(cm.indexFromPos(pos), example.index);\n  }\n});\n\ntestCM(\"undo\", function(cm) {\n  cm.replaceRange(\"def\", Pos(0, 0), Pos(0));\n  eq(cm.historySize().undo, 1);\n  cm.undo();\n  eq(cm.getValue(), \"abc\");\n  eq(cm.historySize().undo, 0);\n  eq(cm.historySize().redo, 1);\n  cm.redo();\n  eq(cm.getValue(), \"def\");\n  eq(cm.historySize().undo, 1);\n  eq(cm.historySize().redo, 0);\n  cm.setValue(\"1\\n\\n\\n2\");\n  cm.clearHistory();\n  eq(cm.historySize().undo, 0);\n  for (var i = 0; i < 20; ++i) {\n    cm.replaceRange(\"a\", Pos(0, 0));\n    cm.replaceRange(\"b\", Pos(3, 0));\n  }\n  eq(cm.historySize().undo, 40);\n  for (var i = 0; i < 40; ++i)\n    cm.undo();\n  eq(cm.historySize().redo, 40);\n  eq(cm.getValue(), \"1\\n\\n\\n2\");\n}, {value: \"abc\"});\n\ntestCM(\"undoDepth\", function(cm) {\n  cm.replaceRange(\"d\", Pos(0));\n  cm.replaceRange(\"e\", Pos(0));\n  cm.replaceRange(\"f\", Pos(0));\n  cm.undo(); cm.undo(); cm.undo();\n  eq(cm.getValue(), \"abcd\");\n}, {value: \"abc\", undoDepth: 4});\n\ntestCM(\"undoDoesntClearValue\", function(cm) {\n  cm.undo();\n  eq(cm.getValue(), \"x\");\n}, {value: \"x\"});\n\ntestCM(\"undoMultiLine\", function(cm) {\n  cm.operation(function() {\n    cm.replaceRange(\"x\", Pos(0, 0));\n    cm.replaceRange(\"y\", Pos(1, 0));\n  });\n  cm.undo();\n  eq(cm.getValue(), \"abc\\ndef\\nghi\");\n  cm.operation(function() {\n    cm.replaceRange(\"y\", Pos(1, 0));\n    cm.replaceRange(\"x\", Pos(0, 0));\n  });\n  cm.undo();\n  eq(cm.getValue(), \"abc\\ndef\\nghi\");\n  cm.operation(function() {\n    cm.replaceRange(\"y\", Pos(2, 0));\n    cm.replaceRange(\"x\", Pos(1, 0));\n    cm.replaceRange(\"z\", Pos(2, 0));\n  });\n  cm.undo();\n  eq(cm.getValue(), \"abc\\ndef\\nghi\", 3);\n}, {value: \"abc\\ndef\\nghi\"});\n\ntestCM(\"undoComposite\", function(cm) {\n  cm.replaceRange(\"y\", Pos(1));\n  cm.operation(function() {\n    cm.replaceRange(\"x\", Pos(0));\n    cm.replaceRange(\"z\", Pos(2));\n  });\n  eq(cm.getValue(), \"ax\\nby\\ncz\\n\");\n  cm.undo();\n  eq(cm.getValue(), \"a\\nby\\nc\\n\");\n  cm.undo();\n  eq(cm.getValue(), \"a\\nb\\nc\\n\");\n  cm.redo(); cm.redo();\n  eq(cm.getValue(), \"ax\\nby\\ncz\\n\");\n}, {value: \"a\\nb\\nc\\n\"});\n\ntestCM(\"undoSelection\", function(cm) {\n  cm.setSelection(Pos(0, 2), Pos(0, 4));\n  cm.replaceSelection(\"\");\n  cm.setCursor(Pos(1, 0));\n  cm.undo();\n  eqCursorPos(cm.getCursor(true), Pos(0, 2));\n  eqCursorPos(cm.getCursor(false), Pos(0, 4));\n  cm.setCursor(Pos(1, 0));\n  cm.redo();\n  eqCursorPos(cm.getCursor(true), Pos(0, 2));\n  eqCursorPos(cm.getCursor(false), Pos(0, 2));\n}, {value: \"abcdefgh\\n\"});\n\ntestCM(\"undoSelectionAsBefore\", function(cm) {\n  cm.replaceSelection(\"abc\", \"around\");\n  cm.undo();\n  cm.redo();\n  eq(cm.getSelection(), \"abc\");\n});\n\ntestCM(\"selectionChangeConfusesHistory\", function(cm) {\n  cm.replaceSelection(\"abc\", null, \"dontmerge\");\n  cm.operation(function() {\n    cm.setCursor(Pos(0, 0));\n    cm.replaceSelection(\"abc\", null, \"dontmerge\");\n  });\n  eq(cm.historySize().undo, 2);\n});\n\ntestCM(\"markTextSingleLine\", function(cm) {\n  forEach([{a: 0, b: 1, c: \"\", f: 2, t: 5},\n           {a: 0, b: 4, c: \"\", f: 0, t: 2},\n           {a: 1, b: 2, c: \"x\", f: 3, t: 6},\n           {a: 4, b: 5, c: \"\", f: 3, t: 5},\n           {a: 4, b: 5, c: \"xx\", f: 3, t: 7},\n           {a: 2, b: 5, c: \"\", f: 2, t: 3},\n           {a: 2, b: 5, c: \"abcd\", f: 6, t: 7},\n           {a: 2, b: 6, c: \"x\", f: null, t: null},\n           {a: 3, b: 6, c: \"\", f: null, t: null},\n           {a: 0, b: 9, c: \"hallo\", f: null, t: null},\n           {a: 4, b: 6, c: \"x\", f: 3, t: 4},\n           {a: 4, b: 8, c: \"\", f: 3, t: 4},\n           {a: 6, b: 6, c: \"a\", f: 3, t: 6},\n           {a: 8, b: 9, c: \"\", f: 3, t: 6}], function(test) {\n    cm.setValue(\"1234567890\");\n    var r = cm.markText(Pos(0, 3), Pos(0, 6), {className: \"foo\"});\n    cm.replaceRange(test.c, Pos(0, test.a), Pos(0, test.b));\n    var f = r.find();\n    eq(f && f.from.ch, test.f); eq(f && f.to.ch, test.t);\n  });\n});\n\ntestCM(\"markTextMultiLine\", function(cm) {\n  function p(v) { return v && Pos(v[0], v[1]); }\n  forEach([{a: [0, 0], b: [0, 5], c: \"\", f: [0, 0], t: [2, 5]},\n           {a: [0, 0], b: [0, 5], c: \"foo\\n\", f: [1, 0], t: [3, 5]},\n           {a: [0, 1], b: [0, 10], c: \"\", f: [0, 1], t: [2, 5]},\n           {a: [0, 5], b: [0, 6], c: \"x\", f: [0, 6], t: [2, 5]},\n           {a: [0, 0], b: [1, 0], c: \"\", f: [0, 0], t: [1, 5]},\n           {a: [0, 6], b: [2, 4], c: \"\", f: [0, 5], t: [0, 7]},\n           {a: [0, 6], b: [2, 4], c: \"aa\", f: [0, 5], t: [0, 9]},\n           {a: [1, 2], b: [1, 8], c: \"\", f: [0, 5], t: [2, 5]},\n           {a: [0, 5], b: [2, 5], c: \"xx\", f: null, t: null},\n           {a: [0, 0], b: [2, 10], c: \"x\", f: null, t: null},\n           {a: [1, 5], b: [2, 5], c: \"\", f: [0, 5], t: [1, 5]},\n           {a: [2, 0], b: [2, 3], c: \"\", f: [0, 5], t: [2, 2]},\n           {a: [2, 5], b: [3, 0], c: \"a\\nb\", f: [0, 5], t: [2, 5]},\n           {a: [2, 3], b: [3, 0], c: \"x\", f: [0, 5], t: [2, 3]},\n           {a: [1, 1], b: [1, 9], c: \"1\\n2\\n3\", f: [0, 5], t: [4, 5]}], function(test) {\n    cm.setValue(\"aaaaaaaaaa\\nbbbbbbbbbb\\ncccccccccc\\ndddddddd\\n\");\n    var r = cm.markText(Pos(0, 5), Pos(2, 5),\n                        {className: \"CodeMirror-matchingbracket\"});\n    cm.replaceRange(test.c, p(test.a), p(test.b));\n    var f = r.find();\n    eqCursorPos(f && f.from, p(test.f)); eqCursorPos(f && f.to, p(test.t));\n  });\n});\n\ntestCM(\"markTextUndo\", function(cm) {\n  var marker1, marker2, bookmark;\n  marker1 = cm.markText(Pos(0, 1), Pos(0, 3),\n                        {className: \"CodeMirror-matchingbracket\"});\n  marker2 = cm.markText(Pos(0, 0), Pos(2, 1),\n                        {className: \"CodeMirror-matchingbracket\"});\n  bookmark = cm.setBookmark(Pos(1, 5));\n  cm.operation(function(){\n    cm.replaceRange(\"foo\", Pos(0, 2));\n    cm.replaceRange(\"bar\\nbaz\\nbug\\n\", Pos(2, 0), Pos(3, 0));\n  });\n  var v1 = cm.getValue();\n  cm.setValue(\"\");\n  eq(marker1.find(), null); eq(marker2.find(), null); eq(bookmark.find(), null);\n  cm.undo();\n  eqCursorPos(bookmark.find(), Pos(1, 5), \"still there\");\n  cm.undo();\n  var m1Pos = marker1.find(), m2Pos = marker2.find();\n  eqCursorPos(m1Pos.from, Pos(0, 1)); eqCursorPos(m1Pos.to, Pos(0, 3));\n  eqCursorPos(m2Pos.from, Pos(0, 0)); eqCursorPos(m2Pos.to, Pos(2, 1));\n  eqCursorPos(bookmark.find(), Pos(1, 5));\n  cm.redo(); cm.redo();\n  eq(bookmark.find(), null);\n  cm.undo();\n  eqCursorPos(bookmark.find(), Pos(1, 5));\n  eq(cm.getValue(), v1);\n}, {value: \"1234\\n56789\\n00\\n\"});\n\ntestCM(\"markTextStayGone\", function(cm) {\n  var m1 = cm.markText(Pos(0, 0), Pos(0, 1));\n  cm.replaceRange(\"hi\", Pos(0, 2));\n  m1.clear();\n  cm.undo();\n  eq(m1.find(), null);\n}, {value: \"hello\"});\n\ntestCM(\"markTextAllowEmpty\", function(cm) {\n  var m1 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false});\n  is(m1.find());\n  cm.replaceRange(\"x\", Pos(0, 0));\n  is(m1.find());\n  cm.replaceRange(\"y\", Pos(0, 2));\n  is(m1.find());\n  cm.replaceRange(\"z\", Pos(0, 3), Pos(0, 4));\n  is(!m1.find());\n  var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false,\n                                              inclusiveLeft: true,\n                                              inclusiveRight: true});\n  cm.replaceRange(\"q\", Pos(0, 1), Pos(0, 2));\n  is(m2.find());\n  cm.replaceRange(\"\", Pos(0, 0), Pos(0, 3));\n  is(!m2.find());\n  var m3 = cm.markText(Pos(0, 1), Pos(0, 1), {clearWhenEmpty: false});\n  cm.replaceRange(\"a\", Pos(0, 3));\n  is(m3.find());\n  cm.replaceRange(\"b\", Pos(0, 1));\n  is(!m3.find());\n}, {value: \"abcde\"});\n\ntestCM(\"markTextStacked\", function(cm) {\n  var m1 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false});\n  var m2 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false});\n  cm.replaceRange(\"B\", Pos(0, 1));\n  is(m1.find() && m2.find());\n}, {value: \"A\"});\n\ntestCM(\"undoPreservesNewMarks\", function(cm) {\n  cm.markText(Pos(0, 3), Pos(0, 4));\n  cm.markText(Pos(1, 1), Pos(1, 3));\n  cm.replaceRange(\"\", Pos(0, 3), Pos(3, 1));\n  var mBefore = cm.markText(Pos(0, 0), Pos(0, 1));\n  var mAfter = cm.markText(Pos(0, 5), Pos(0, 6));\n  var mAround = cm.markText(Pos(0, 2), Pos(0, 4));\n  cm.undo();\n  eqCursorPos(mBefore.find().from, Pos(0, 0));\n  eqCursorPos(mBefore.find().to, Pos(0, 1));\n  eqCursorPos(mAfter.find().from, Pos(3, 3));\n  eqCursorPos(mAfter.find().to, Pos(3, 4));\n  eqCursorPos(mAround.find().from, Pos(0, 2));\n  eqCursorPos(mAround.find().to, Pos(3, 2));\n  var found = cm.findMarksAt(Pos(2, 2));\n  eq(found.length, 1);\n  eq(found[0], mAround);\n}, {value: \"aaaa\\nbbbb\\ncccc\\ndddd\"});\n\ntestCM(\"markClearBetween\", function(cm) {\n  cm.setValue(\"aaa\\nbbb\\nccc\\nddd\\n\");\n  cm.markText(Pos(0, 0), Pos(2));\n  cm.replaceRange(\"aaa\\nbbb\\nccc\", Pos(0, 0), Pos(2));\n  eq(cm.findMarksAt(Pos(1, 1)).length, 0);\n});\n\ntestCM(\"findMarksMiddle\", function(cm) {\n  var mark = cm.markText(Pos(1, 1), Pos(3, 1));\n  var found = cm.findMarks(Pos(2, 1), Pos(2, 2));\n  eq(found.length, 1);\n  eq(found[0], mark);\n}, {value: \"line 0\\nline 1\\nline 2\\nline 3\"});\n\ntestCM(\"deleteSpanCollapsedInclusiveLeft\", function(cm) {\n  var from = Pos(1, 0), to = Pos(1, 1);\n  var m = cm.markText(from, to, {collapsed: true, inclusiveLeft: true});\n  // Delete collapsed span.\n  cm.replaceRange(\"\", from, to);\n}, {value: \"abc\\nX\\ndef\"});\n\ntestCM(\"markTextCSS\", function(cm) {\n  function present() {\n    var spans = cm.display.lineDiv.getElementsByTagName(\"span\");\n    for (var i = 0; i < spans.length; i++)\n      if (spans[i].style.color && spans[i].textContent == \"cdef\") return true;\n  }\n  var m = cm.markText(Pos(0, 2), Pos(0, 6), {css: \"color: cyan\"});\n  is(present());\n  m.clear();\n  is(!present());\n}, {value: \"abcdefgh\"});\n\ntestCM(\"markTextWithAttributes\", function(cm) {\n  function present() {\n    var spans = cm.display.lineDiv.getElementsByTagName(\"span\");\n    for (var i = 0; i < spans.length; i++)\n      if (spans[i].getAttribute(\"label\") == \"label\" && spans[i].textContent == \"cdef\") return true;\n  }\n  var m = cm.markText(Pos(0, 2), Pos(0, 6), {attributes: {label: \"label\"}});\n  is(present());\n  m.clear();\n  is(!present());\n}, {value: \"abcdefgh\"});\n\ntestCM(\"bookmark\", function(cm) {\n  function p(v) { return v && Pos(v[0], v[1]); }\n  forEach([{a: [1, 0], b: [1, 1], c: \"\", d: [1, 4]},\n           {a: [1, 1], b: [1, 1], c: \"xx\", d: [1, 7]},\n           {a: [1, 4], b: [1, 5], c: \"ab\", d: [1, 6]},\n           {a: [1, 4], b: [1, 6], c: \"\", d: null},\n           {a: [1, 5], b: [1, 6], c: \"abc\", d: [1, 5]},\n           {a: [1, 6], b: [1, 8], c: \"\", d: [1, 5]},\n           {a: [1, 4], b: [1, 4], c: \"\\n\\n\", d: [3, 1]},\n           {bm: [1, 9], a: [1, 1], b: [1, 1], c: \"\\n\", d: [2, 8]}], function(test) {\n    cm.setValue(\"1234567890\\n1234567890\\n1234567890\");\n    var b = cm.setBookmark(p(test.bm) || Pos(1, 5));\n    cm.replaceRange(test.c, p(test.a), p(test.b));\n    eqCursorPos(b.find(), p(test.d));\n  });\n});\n\ntestCM(\"bookmarkInsertLeft\", function(cm) {\n  var br = cm.setBookmark(Pos(0, 2), {insertLeft: false});\n  var bl = cm.setBookmark(Pos(0, 2), {insertLeft: true});\n  cm.setCursor(Pos(0, 2));\n  cm.replaceSelection(\"hi\");\n  eqCursorPos(br.find(), Pos(0, 2));\n  eqCursorPos(bl.find(), Pos(0, 4));\n  cm.replaceRange(\"\", Pos(0, 4), Pos(0, 5));\n  cm.replaceRange(\"\", Pos(0, 2), Pos(0, 4));\n  cm.replaceRange(\"\", Pos(0, 1), Pos(0, 2));\n  // Verify that deleting next to bookmarks doesn't kill them\n  eqCursorPos(br.find(), Pos(0, 1));\n  eqCursorPos(bl.find(), Pos(0, 1));\n}, {value: \"abcdef\"});\n\ntestCM(\"bookmarkCursor\", function(cm) {\n  var pos01 = cm.cursorCoords(Pos(0, 1)), pos11 = cm.cursorCoords(Pos(1, 1)),\n      pos20 = cm.cursorCoords(Pos(2, 0)), pos30 = cm.cursorCoords(Pos(3, 0)),\n      pos41 = cm.cursorCoords(Pos(4, 1));\n  cm.setBookmark(Pos(0, 1), {widget: document.createTextNode(\"←\"), insertLeft: true});\n  cm.setBookmark(Pos(2, 0), {widget: document.createTextNode(\"←\"), insertLeft: true});\n  cm.setBookmark(Pos(1, 1), {widget: document.createTextNode(\"→\")});\n  cm.setBookmark(Pos(3, 0), {widget: document.createTextNode(\"→\")});\n  var new01 = cm.cursorCoords(Pos(0, 1)), new11 = cm.cursorCoords(Pos(1, 1)),\n      new20 = cm.cursorCoords(Pos(2, 0)), new30 = cm.cursorCoords(Pos(3, 0));\n  near(new01.left, pos01.left, 1);\n  near(new01.top, pos01.top, 1);\n  is(new11.left > pos11.left, \"at right, middle of line\");\n  near(new11.top == pos11.top, 1);\n  near(new20.left, pos20.left, 1);\n  near(new20.top, pos20.top, 1);\n  is(new30.left > pos30.left, \"at right, empty line\");\n  near(new30.top, pos30, 1);\n  cm.setBookmark(Pos(4, 0), {widget: document.createTextNode(\"→\")});\n  is(cm.cursorCoords(Pos(4, 1)).left > pos41.left, \"single-char bug\");\n}, {value: \"foo\\nbar\\n\\n\\nx\\ny\"});\n\ntestCM(\"multiBookmarkCursor\", function(cm) {\n  if (phantom) return;\n  var ms = [], m;\n  function add(insertLeft) {\n    for (var i = 0; i < 3; ++i) {\n      var node = document.createElement(\"span\");\n      node.innerHTML = \"X\";\n      ms.push(cm.setBookmark(Pos(0, 1), {widget: node, insertLeft: insertLeft}));\n    }\n  }\n  var base1 = cm.cursorCoords(Pos(0, 1)).left, base4 = cm.cursorCoords(Pos(0, 4)).left;\n  add(true);\n  near(base1, cm.cursorCoords(Pos(0, 1)).left, 1);\n  while (m = ms.pop()) m.clear();\n  add(false);\n  near(base4, cm.cursorCoords(Pos(0, 1)).left, 1);\n}, {value: \"abcdefg\"});\n\ntestCM(\"getAllMarks\", function(cm) {\n  addDoc(cm, 10, 10);\n  var m1 = cm.setBookmark(Pos(0, 2));\n  var m2 = cm.markText(Pos(0, 2), Pos(3, 2));\n  var m3 = cm.markText(Pos(1, 2), Pos(1, 8));\n  var m4 = cm.markText(Pos(8, 0), Pos(9, 0));\n  eq(cm.getAllMarks().length, 4);\n  m1.clear();\n  m3.clear();\n  eq(cm.getAllMarks().length, 2);\n});\n\ntestCM(\"setValueClears\", function(cm) {\n  cm.addLineClass(0, \"wrap\", \"foo\");\n  var mark = cm.markText(Pos(0, 0), Pos(1, 1), {inclusiveLeft: true, inclusiveRight: true});\n  cm.setValue(\"foo\");\n  is(!cm.lineInfo(0).wrapClass);\n  is(!mark.find());\n}, {value: \"a\\nb\"});\n\ntestCM(\"bug577\", function(cm) {\n  cm.setValue(\"a\\nb\");\n  cm.clearHistory();\n  cm.setValue(\"fooooo\");\n  cm.undo();\n});\n\ntestCM(\"scrollSnap\", function(cm) {\n  cm.setSize(100, 100);\n  addDoc(cm, 200, 200);\n  cm.setCursor(Pos(100, 180));\n  var info = cm.getScrollInfo();\n  is(info.left > 0 && info.top > 0);\n  cm.setCursor(Pos(0, 0));\n  info = cm.getScrollInfo();\n  is(info.left == 0 && info.top == 0, \"scrolled clean to top\");\n  cm.setCursor(Pos(100, 180));\n  cm.setCursor(Pos(199, 0));\n  info = cm.getScrollInfo();\n  is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, \"scrolled clean to bottom\");\n});\n\ntestCM(\"scrollIntoView\", function(cm) {\n  if (phantom) return;\n  function test(line, ch, msg) {\n    var pos = Pos(line, ch);\n    cm.scrollIntoView(pos);\n    var outer = cm.getWrapperElement().getBoundingClientRect();\n    var box = cm.charCoords(pos, \"window\");\n    is(box.left >= outer.left, msg + \" (left)\");\n    is(box.right <= outer.right, msg + \" (right)\");\n    is(box.top >= outer.top, msg + \" (top)\");\n    is(box.bottom <= outer.bottom, msg + \" (bottom)\");\n  }\n  addDoc(cm, 200, 200);\n  test(199, 199, \"bottom right\");\n  test(0, 0, \"top left\");\n  test(100, 100, \"center\");\n  test(199, 0, \"bottom left\");\n  test(0, 199, \"top right\");\n  test(100, 100, \"center again\");\n});\n\ntestCM(\"scrollBackAndForth\", function(cm) {\n  addDoc(cm, 1, 200);\n  cm.operation(function() {\n    cm.scrollIntoView(Pos(199, 0));\n    cm.scrollIntoView(Pos(4, 0));\n  });\n  is(cm.getScrollInfo().top > 0);\n});\n\ntestCM(\"selectAllNoScroll\", function(cm) {\n  addDoc(cm, 1, 200);\n  cm.execCommand(\"selectAll\");\n  eq(cm.getScrollInfo().top, 0);\n  cm.setCursor(199);\n  cm.execCommand(\"selectAll\");\n  is(cm.getScrollInfo().top > 0);\n});\n\ntestCM(\"selectionPos\", function(cm) {\n  if (phantom || cm.getOption(\"inputStyle\") != \"textarea\") return;\n  cm.setSize(100, 100);\n  addDoc(cm, 200, 100);\n  cm.setSelection(Pos(1, 100), Pos(98, 100));\n  var lineWidth = cm.charCoords(Pos(0, 200), \"local\").left;\n  var lineHeight = (cm.charCoords(Pos(99)).top - cm.charCoords(Pos(0)).top) / 100;\n  cm.scrollTo(0, 0);\n  var selElt = byClassName(cm.getWrapperElement(), \"CodeMirror-selected\");\n  var outer = cm.getWrapperElement().getBoundingClientRect();\n  var sawMiddle, sawTop, sawBottom;\n  for (var i = 0, e = selElt.length; i < e; ++i) {\n    var box = selElt[i].getBoundingClientRect();\n    var atLeft = box.left - outer.left < 30;\n    var width = box.right - box.left;\n    var atRight = box.right - outer.left > .8 * lineWidth;\n    if (atLeft && atRight) {\n      sawMiddle = true;\n      is(box.bottom - box.top > 90 * lineHeight, \"middle high\");\n      is(width > .9 * lineWidth, \"middle wide\");\n    } else {\n      is(width > .4 * lineWidth, \"top/bot wide enough\");\n      is(width < .6 * lineWidth, \"top/bot slim enough\");\n      if (atLeft) {\n        sawBottom = true;\n        is(box.top - outer.top > 96 * lineHeight, \"bot below\");\n      } else if (atRight) {\n        sawTop = true;\n        is(box.top - outer.top < 2.1 * lineHeight, \"top above\");\n      }\n    }\n  }\n  is(sawTop && sawBottom && sawMiddle, \"all parts\");\n}, null);\n\ntestCM(\"restoreHistory\", function(cm) {\n  cm.setValue(\"abc\\ndef\");\n  cm.replaceRange(\"hello\", Pos(1, 0), Pos(1));\n  cm.replaceRange(\"goop\", Pos(0, 0), Pos(0));\n  cm.undo();\n  var storedVal = cm.getValue(), storedHist = cm.getHistory();\n  if (window.JSON) storedHist = JSON.parse(JSON.stringify(storedHist));\n  eq(storedVal, \"abc\\nhello\");\n  cm.setValue(\"\");\n  cm.clearHistory();\n  eq(cm.historySize().undo, 0);\n  cm.setValue(storedVal);\n  cm.setHistory(storedHist);\n  cm.redo();\n  eq(cm.getValue(), \"goop\\nhello\");\n  cm.undo(); cm.undo();\n  eq(cm.getValue(), \"abc\\ndef\");\n});\n\ntestCM(\"doubleScrollbar\", function(cm) {\n  var dummy = document.body.appendChild(document.createElement(\"p\"));\n  dummy.style.cssText = \"height: 50px; overflow: scroll; width: 50px\";\n  var scrollbarWidth = dummy.offsetWidth + 1 - dummy.clientWidth;\n  document.body.removeChild(dummy);\n  if (scrollbarWidth < 2) return;\n  cm.setSize(null, 100);\n  addDoc(cm, 1, 300);\n  var wrap = cm.getWrapperElement();\n  is(wrap.offsetWidth - byClassName(wrap, \"CodeMirror-lines\")[0].offsetWidth <= scrollbarWidth * 1.5);\n});\n\ntestCM(\"weirdLinebreaks\", function(cm) {\n  cm.setValue(\"foo\\nbar\\rbaz\\r\\nquux\\n\\rplop\");\n  is(cm.getValue(), \"foo\\nbar\\nbaz\\nquux\\n\\nplop\");\n  is(cm.lineCount(), 6);\n  cm.setValue(\"\\n\\n\");\n  is(cm.lineCount(), 3);\n});\n\ntestCM(\"setSize\", function(cm) {\n  cm.setSize(100, 100);\n  var wrap = cm.getWrapperElement();\n  is(wrap.offsetWidth, 100);\n  is(wrap.offsetHeight, 100);\n  cm.setSize(\"100%\", \"3em\");\n  is(wrap.style.width, \"100%\");\n  is(wrap.style.height, \"3em\");\n  cm.setSize(null, 40);\n  is(wrap.style.width, \"100%\");\n  is(wrap.style.height, \"40px\");\n});\n\nfunction foldLines(cm, start, end, autoClear) {\n  return cm.markText(Pos(start, 0), Pos(end - 1), {\n    inclusiveLeft: true,\n    inclusiveRight: true,\n    collapsed: true,\n    clearOnEnter: autoClear\n  });\n}\n\ntestCM(\"collapsedLines\", function(cm) {\n  addDoc(cm, 4, 10);\n  var range = foldLines(cm, 4, 5), cleared = 0;\n  CodeMirror.on(range, \"clear\", function() {cleared++;});\n  cm.setCursor(Pos(3, 0));\n  CodeMirror.commands.goLineDown(cm);\n  eqCharPos(cm.getCursor(), Pos(5, 0));\n  cm.replaceRange(\"abcdefg\", Pos(3, 0), Pos(3));\n  cm.setCursor(Pos(3, 6));\n  CodeMirror.commands.goLineDown(cm);\n  eqCharPos(cm.getCursor(), Pos(5, 4));\n  cm.replaceRange(\"ab\", Pos(3, 0), Pos(3));\n  cm.setCursor(Pos(3, 2));\n  CodeMirror.commands.goLineDown(cm);\n  eqCharPos(cm.getCursor(), Pos(5, 2));\n  cm.operation(function() {range.clear(); range.clear();});\n  eq(cleared, 1);\n});\n\ntestCM(\"collapsedRangeCoordsChar\", function(cm) {\n  var pos_1_3 = cm.charCoords(Pos(1, 3));\n  pos_1_3.left += 2; pos_1_3.top += 2;\n  var opts = {collapsed: true, inclusiveLeft: true, inclusiveRight: true};\n  var m1 = cm.markText(Pos(0, 0), Pos(2, 0), opts);\n  eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3));\n  m1.clear();\n  var m1 = cm.markText(Pos(0, 0), Pos(1, 1), {collapsed: true, inclusiveLeft: true});\n  var m2 = cm.markText(Pos(1, 1), Pos(2, 0), {collapsed: true, inclusiveRight: true});\n  eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3));\n  m1.clear(); m2.clear();\n  var m1 = cm.markText(Pos(0, 0), Pos(1, 6), opts);\n  eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3));\n}, {value: \"123456\\nabcdef\\nghijkl\\nmnopqr\\n\"});\n\ntestCM(\"collapsedRangeBetweenLinesSelected\", function(cm) {\n  if (cm.getOption(\"inputStyle\") != \"textarea\") return;\n  var widget = document.createElement(\"span\");\n  widget.textContent = \"\\u2194\";\n  cm.markText(Pos(0, 3), Pos(1, 0), {replacedWith: widget});\n  cm.setSelection(Pos(0, 3), Pos(1, 0));\n  var selElts = byClassName(cm.getWrapperElement(), \"CodeMirror-selected\");\n  for (var i = 0, w = 0; i < selElts.length; i++)\n    w += selElts[i].offsetWidth;\n  is(w > 0);\n}, {value: \"one\\ntwo\"});\n\ntestCM(\"randomCollapsedRanges\", function(cm) {\n  addDoc(cm, 20, 500);\n  cm.operation(function() {\n    for (var i = 0; i < 200; i++) {\n      var start = Pos(Math.floor(Math.random() * 500), Math.floor(Math.random() * 20));\n      if (i % 4)\n        try { cm.markText(start, Pos(start.line + 2, 1), {collapsed: true}); }\n        catch(e) { if (!/overlapping/.test(String(e))) throw e; }\n      else\n        cm.markText(start, Pos(start.line, start.ch + 4), {\"className\": \"foo\"});\n    }\n  });\n});\n\ntestCM(\"hiddenLinesAutoUnfold\", function(cm) {\n  var range = foldLines(cm, 1, 3, true), cleared = 0;\n  CodeMirror.on(range, \"clear\", function() {cleared++;});\n  cm.setCursor(Pos(3, 0));\n  eq(cleared, 0);\n  cm.execCommand(\"goCharLeft\");\n  eq(cleared, 1);\n  range = foldLines(cm, 1, 3, true);\n  CodeMirror.on(range, \"clear\", function() {cleared++;});\n  eqCursorPos(cm.getCursor(), Pos(3, 0));\n  cm.setCursor(Pos(0, 3));\n  cm.execCommand(\"goCharRight\");\n  eq(cleared, 2);\n}, {value: \"abc\\ndef\\nghi\\njkl\"});\n\ntestCM(\"hiddenLinesSelectAll\", function(cm) {  // Issue #484\n  addDoc(cm, 4, 20);\n  foldLines(cm, 0, 10);\n  foldLines(cm, 11, 20);\n  CodeMirror.commands.selectAll(cm);\n  eqCursorPos(cm.getCursor(true), Pos(10, 0));\n  eqCursorPos(cm.getCursor(false), Pos(10, 4));\n});\n\ntestCM(\"clickFold\", function(cm) { // Issue #5392\n  cm.setValue(\"foo { bar }\")\n  var widget = document.createElement(\"span\")\n  widget.textContent = \"<>\"\n  cm.markText(Pos(0, 5), Pos(0, 10), {replacedWith: widget})\n  var after = cm.charCoords(Pos(0, 10))\n  var foundOn = cm.coordsChar({left: after.left - 1, top: after.top + 4})\n  is(foundOn.ch <= 5 || foundOn.ch >= 10, \"Position is not inside the folded range\")\n})\n\ntestCM(\"everythingFolded\", function(cm) {\n  addDoc(cm, 2, 2);\n  function enterPress() {\n    cm.triggerOnKeyDown({type: \"keydown\", keyCode: 13, preventDefault: function(){}, stopPropagation: function(){}});\n  }\n  var fold = foldLines(cm, 0, 2);\n  enterPress();\n  eq(cm.getValue(), \"xx\\nxx\");\n  fold.clear();\n  fold = foldLines(cm, 0, 2, true);\n  eq(fold.find(), null);\n  enterPress();\n  eq(cm.getValue(), \"\\nxx\\nxx\");\n});\n\ntestCM(\"structuredFold\", function(cm) {\n  if (phantom) return;\n  addDoc(cm, 4, 8);\n  var range = cm.markText(Pos(1, 2), Pos(6, 2), {\n    replacedWith: document.createTextNode(\"Q\")\n  });\n  cm.setCursor(0, 3);\n  CodeMirror.commands.goLineDown(cm);\n  eqCharPos(cm.getCursor(), Pos(6, 2));\n  CodeMirror.commands.goCharLeft(cm);\n  eqCharPos(cm.getCursor(), Pos(1, 2));\n  CodeMirror.commands.delCharAfter(cm);\n  eq(cm.getValue(), \"xxxx\\nxxxx\\nxxxx\");\n  addDoc(cm, 4, 8);\n  range = cm.markText(Pos(1, 2), Pos(6, 2), {\n    replacedWith: document.createTextNode(\"M\"),\n    clearOnEnter: true\n  });\n  var cleared = 0;\n  CodeMirror.on(range, \"clear\", function(){++cleared;});\n  cm.setCursor(0, 3);\n  CodeMirror.commands.goLineDown(cm);\n  eqCharPos(cm.getCursor(), Pos(6, 2));\n  CodeMirror.commands.goCharLeft(cm);\n  eqCharPos(cm.getCursor(), Pos(6, 1));\n  eq(cleared, 1);\n  range.clear();\n  eq(cleared, 1);\n  range = cm.markText(Pos(1, 2), Pos(6, 2), {\n    replacedWith: document.createTextNode(\"Q\"),\n    clearOnEnter: true\n  });\n  range.clear();\n  cm.setCursor(1, 2);\n  CodeMirror.commands.goCharRight(cm);\n  eqCharPos(cm.getCursor(), Pos(1, 3));\n  range = cm.markText(Pos(2, 0), Pos(4, 4), {\n    replacedWith: document.createTextNode(\"M\")\n  });\n  cm.setCursor(1, 0);\n  CodeMirror.commands.goLineDown(cm);\n  eqCharPos(cm.getCursor(), Pos(2, 0));\n}, null);\n\ntestCM(\"nestedFold\", function(cm) {\n  addDoc(cm, 10, 3);\n  function fold(ll, cl, lr, cr) {\n    return cm.markText(Pos(ll, cl), Pos(lr, cr), {collapsed: true});\n  }\n  var inner1 = fold(0, 6, 1, 3), inner2 = fold(0, 2, 1, 8), outer = fold(0, 1, 2, 3), inner0 = fold(0, 5, 0, 6);\n  cm.setCursor(0, 1);\n  CodeMirror.commands.goCharRight(cm);\n  eqCursorPos(cm.getCursor(), Pos(2, 3));\n  inner0.clear();\n  CodeMirror.commands.goCharLeft(cm);\n  eqCursorPos(cm.getCursor(), Pos(0, 1));\n  outer.clear();\n  CodeMirror.commands.goCharRight(cm);\n  eqCursorPos(cm.getCursor(), Pos(0, 2, \"before\"));\n  CodeMirror.commands.goCharRight(cm);\n  eqCursorPos(cm.getCursor(), Pos(1, 8));\n  inner2.clear();\n  CodeMirror.commands.goCharLeft(cm);\n  eqCursorPos(cm.getCursor(), Pos(1, 7, \"after\"));\n  cm.setCursor(0, 5);\n  CodeMirror.commands.goCharRight(cm);\n  eqCursorPos(cm.getCursor(), Pos(0, 6, \"before\"));\n  CodeMirror.commands.goCharRight(cm);\n  eqCursorPos(cm.getCursor(), Pos(1, 3));\n});\n\ntestCM(\"badNestedFold\", function(cm) {\n  addDoc(cm, 4, 4);\n  cm.markText(Pos(0, 2), Pos(3, 2), {collapsed: true});\n  var caught;\n  try {cm.markText(Pos(0, 1), Pos(0, 3), {collapsed: true});}\n  catch(e) {caught = e;}\n  is(caught instanceof Error, \"no error\");\n  is(/overlap/i.test(caught.message), \"wrong error\");\n});\n\ntestCM(\"nestedFoldOnSide\", function(cm) {\n  var m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true, inclusiveRight: true});\n  var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true});\n  cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}).clear();\n  try { cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true, inclusiveLeft: true}); }\n  catch(e) { var caught = e; }\n  is(caught && /overlap/i.test(caught.message));\n  var m3 = cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true});\n  var m4 = cm.markText(Pos(2, 0), Pos(2, 1), {collapse: true, inclusiveRight: true});\n  m1.clear(); m4.clear();\n  m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true});\n  cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}).clear();\n  try { cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true, inclusiveRight: true}); }\n  catch(e) { var caught = e; }\n  is(caught && /overlap/i.test(caught.message));\n}, {value: \"ab\\ncd\\ef\"});\n\ntestCM(\"editInFold\", function(cm) {\n  addDoc(cm, 4, 6);\n  var m = cm.markText(Pos(1, 2), Pos(3, 2), {collapsed: true});\n  cm.replaceRange(\"\", Pos(0, 0), Pos(1, 3));\n  cm.replaceRange(\"\", Pos(2, 1), Pos(3, 3));\n  cm.replaceRange(\"a\\nb\\nc\\nd\", Pos(0, 1), Pos(1, 0));\n  cm.cursorCoords(Pos(0, 0));\n});\n\ntestCM(\"wrappingInlineWidget\", function(cm) {\n  cm.setSize(\"11em\");\n  var w = document.createElement(\"span\");\n  w.style.color = \"red\";\n  w.innerHTML = \"one two three four\";\n  cm.markText(Pos(0, 6), Pos(0, 9), {replacedWith: w});\n  var cur0 = cm.cursorCoords(Pos(0, 0)), cur1 = cm.cursorCoords(Pos(0, 10));\n  is(cur0.top < cur1.top);\n  is(cur0.bottom < cur1.bottom);\n  var curL = cm.cursorCoords(Pos(0, 6)), curR = cm.cursorCoords(Pos(0, 9));\n  eq(curL.top, cur0.top);\n  eq(curL.bottom, cur0.bottom);\n  eq(curR.top, cur1.top);\n  eq(curR.bottom, cur1.bottom);\n  cm.replaceRange(\"\", Pos(0, 9), Pos(0));\n  curR = cm.cursorCoords(Pos(0, 9));\n  if (phantom) return;\n  eq(curR.top, cur1.top);\n  eq(curR.bottom, cur1.bottom);\n}, {value: \"1 2 3 xxx 4\", lineWrapping: true});\n\ntestCM(\"showEmptyWidgetSpan\", function(cm) {\n  var marker = cm.markText(Pos(0, 2), Pos(0, 2), {\n    clearWhenEmpty: false,\n    replacedWith: document.createTextNode(\"X\")\n  });\n  var text = cm.display.view[0].text;\n  eq(text.textContent || text.innerText, \"abXc\");\n}, {value: \"abc\"});\n\ntestCM(\"changedInlineWidget\", function(cm) {\n  cm.setSize(\"10em\");\n  var w = document.createElement(\"span\");\n  w.innerHTML = \"x\";\n  var m = cm.markText(Pos(0, 4), Pos(0, 5), {replacedWith: w});\n  w.innerHTML = \"and now the widget is really really long all of a sudden and a scrollbar is needed\";\n  m.changed();\n  var hScroll = byClassName(cm.getWrapperElement(), \"CodeMirror-hscrollbar\")[0];\n  is(hScroll.scrollWidth > hScroll.clientWidth);\n}, {value: \"hello there\"});\n\ntestCM(\"changedBookmark\", function(cm) {\n  cm.setSize(\"10em\");\n  var w = document.createElement(\"span\");\n  w.innerHTML = \"x\";\n  var m = cm.setBookmark(Pos(0, 4), {widget: w});\n  w.innerHTML = \"and now the widget is really really long all of a sudden and a scrollbar is needed\";\n  m.changed();\n  var hScroll = byClassName(cm.getWrapperElement(), \"CodeMirror-hscrollbar\")[0];\n  is(hScroll.scrollWidth > hScroll.clientWidth);\n}, {value: \"abcdefg\"});\n\ntestCM(\"inlineWidget\", function(cm) {\n  var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode(\"uu\")});\n  cm.setCursor(0, 2);\n  CodeMirror.commands.goLineDown(cm);\n  eqCharPos(cm.getCursor(), Pos(1, 4));\n  cm.setCursor(0, 2);\n  cm.replaceSelection(\"hi\");\n  eqCharPos(w.find(), Pos(0, 2));\n  cm.setCursor(0, 1);\n  cm.replaceSelection(\"ay\");\n  eqCharPos(w.find(), Pos(0, 4));\n  eq(cm.getLine(0), \"uayuhiuu\");\n}, {value: \"uuuu\\nuuuuuu\"});\n\ntestCM(\"wrappingAndResizing\", function(cm) {\n  cm.setSize(null, \"auto\");\n  cm.setOption(\"lineWrapping\", true);\n  var wrap = cm.getWrapperElement(), h0 = wrap.offsetHeight;\n  var doc = \"xxx xxx xxx xxx xxx\";\n  cm.setValue(doc);\n  for (var step = 10, w = cm.charCoords(Pos(0, 18), \"div\").right;; w += step) {\n    cm.setSize(w);\n    if (wrap.offsetHeight <= h0 * (opera_lt10 ? 1.2 : 1.5)) {\n      if (step == 10) { w -= 10; step = 1; }\n      else break;\n    }\n  }\n  // Ensure that putting the cursor at the end of the maximally long\n  // line doesn't cause wrapping to happen.\n  cm.setCursor(Pos(0, doc.length));\n  eq(wrap.offsetHeight, h0);\n  cm.replaceSelection(\"x\");\n  is(wrap.offsetHeight > h0, \"wrapping happens\");\n  // Now add a max-height and, in a document consisting of\n  // almost-wrapped lines, go over it so that a scrollbar appears.\n  cm.setValue(doc + \"\\n\" + doc + \"\\n\");\n  cm.getScrollerElement().style.maxHeight = \"100px\";\n  cm.replaceRange(\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n!\\n\", Pos(2, 0));\n  forEach([Pos(0, doc.length), Pos(0, doc.length - 1),\n           Pos(0, 0), Pos(1, doc.length), Pos(1, doc.length - 1)],\n          function(pos) {\n    var coords = cm.charCoords(pos);\n    eqCharPos(pos, cm.coordsChar({left: coords.left + 2, top: coords.top + 5}));\n  });\n}, null, ie_lt8);\n\ntestCM(\"measureEndOfLine\", function(cm) {\n  if (phantom) return;\n  cm.setSize(null, \"auto\");\n  var inner = byClassName(cm.getWrapperElement(), \"CodeMirror-lines\")[0].firstChild;\n  var lh = inner.offsetHeight;\n  for (var step = 10, w = cm.charCoords(Pos(0, 7), \"div\").right;; w += step) {\n    cm.setSize(w);\n    if (inner.offsetHeight < 2.5 * lh) {\n      if (step == 10) { w -= 10; step = 1; }\n      else break;\n    }\n  }\n  cm.setValue(cm.getValue() + \"\\n\\n\");\n  var endPos = cm.charCoords(Pos(0, 18), \"local\");\n  is(endPos.top > lh * .8, \"not at top\");\n  is(endPos.left > w - 20, \"at right\");\n  endPos = cm.charCoords(Pos(0, 18));\n  eqCursorPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), Pos(0, 18, \"before\"));\n\n  var wrapPos = cm.cursorCoords(Pos(0, 9, \"before\"));\n  is(wrapPos.top < endPos.top, \"wrapPos is actually in first line\");\n  eqCursorPos(cm.coordsChar({left: wrapPos.left + 10, top: wrapPos.top}), Pos(0, 9, \"before\"));\n}, {mode: \"text/html\", value: \"<!-- foo barrr -->\", lineWrapping: true}, ie_lt8 || opera_lt10);\n\ntestCM(\"measureWrappedEndOfLine\", function(cm) {\n  if (phantom) return;\n  cm.setSize(null, \"auto\");\n  var inner = byClassName(cm.getWrapperElement(), \"CodeMirror-lines\")[0].firstChild;\n  var lh = inner.offsetHeight;\n  for (var step = 10, w = cm.charCoords(Pos(0, 7), \"div\").right;; w += step) {\n    cm.setSize(w);\n    if (inner.offsetHeight < 2.5 * lh) {\n      if (step == 10) { w -= 10; step = 1; }\n      else break;\n    }\n  }\n  for (var i = 0; i < 3; ++i) {\n    var endPos = cm.charCoords(Pos(0, 12)); // Next-to-last since last would wrap (#1862)\n    endPos.left += w; // Add width of editor just to be sure that we are behind last character\n    eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, \"before\"));\n    endPos.left += w * 100;\n    eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, \"before\"));\n    cm.setValue(\"0123456789abcابجابجابجابج\");\n    if (i == 1) {\n      var node = document.createElement(\"div\");\n      node.innerHTML = \"hi\"; node.style.height = \"30px\";\n      cm.addLineWidget(0, node, {above: true});\n    }\n  }\n}, {mode: \"text/html\", value: \"0123456789abcde0123456789\", lineWrapping: true}, ie_lt8 || opera_lt10);\n\ntestCM(\"measureEndOfLineBidi\", function(cm) {\n  eqCursorPos(cm.coordsChar({left: 5000, top: cm.charCoords(Pos(0, 0)).top}), Pos(0, 8, \"after\"))\n}, {value: \"إإإإuuuuإإإإ\"})\n\ntestCM(\"measureWrappedBidiLevel2\", function(cm) {\n  cm.setSize(cm.charCoords(Pos(0, 6), \"editor\").right + 60)\n  var c9 = cm.charCoords(Pos(0, 9))\n  eqCharPos(cm.coordsChar({left: c9.right - 1, top: c9.top + 1}), Pos(0, 9))\n}, {value: \"foobar إإ إإ إإ إإ 555 بببببب\", lineWrapping: true})\n\ntestCM(\"measureWrappedBeginOfLine\", function(cm) {\n  if (phantom) return;\n  cm.setSize(null, \"auto\");\n  var inner = byClassName(cm.getWrapperElement(), \"CodeMirror-lines\")[0].firstChild;\n  var lh = inner.offsetHeight;\n  for (var step = 10, w = cm.charCoords(Pos(0, 7), \"div\").right;; w += step) {\n    cm.setSize(w);\n    if (inner.offsetHeight < 2.5 * lh) {\n      if (step == 10) { w -= 10; step = 1; }\n      else break;\n    }\n  }\n  var beginOfSecondLine = Pos(0, 13, \"after\");\n  for (var i = 0; i < 2; ++i) {\n    var beginPos = cm.charCoords(Pos(0, 0));\n    beginPos.left -= w;\n    eqCursorPos(cm.coordsChar(beginPos), Pos(0, 0, \"after\"));\n    beginPos = cm.cursorCoords(beginOfSecondLine);\n    beginPos.left = 0;\n    eqCursorPos(cm.coordsChar(beginPos), beginOfSecondLine);\n    cm.setValue(\"0123456789abcابجابجابجابج\");\n    beginOfSecondLine = Pos(0, 25, \"before\");\n  }\n}, {mode: \"text/html\", value: \"0123456789abcde0123456789\", lineWrapping: true});\n\ntestCM(\"scrollVerticallyAndHorizontally\", function(cm) {\n  if (cm.getOption(\"inputStyle\") != \"textarea\") return;\n  cm.setSize(100, 100);\n  addDoc(cm, 40, 40);\n  cm.setCursor(39);\n  var wrap = cm.getWrapperElement(), bar = byClassName(wrap, \"CodeMirror-vscrollbar\")[0];\n  is(bar.offsetHeight < wrap.offsetHeight, \"vertical scrollbar limited by horizontal one\");\n  var cursorBox = byClassName(wrap, \"CodeMirror-cursor\")[0].getBoundingClientRect();\n  var editorBox = wrap.getBoundingClientRect();\n  is(cursorBox.bottom < editorBox.top + cm.getScrollerElement().clientHeight,\n     \"bottom line visible\");\n}, {lineNumbers: true});\n\ntestCM(\"moveVstuck\", function(cm) {\n  var lines = byClassName(cm.getWrapperElement(), \"CodeMirror-lines\")[0].firstChild, h0 = lines.offsetHeight;\n  var val = \"fooooooooooooooooooooooooo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar\\n\";\n  cm.setValue(val);\n  for (var w = cm.charCoords(Pos(0, 26), \"div\").right * 2.8;; w += 5) {\n    cm.setSize(w);\n    if (lines.offsetHeight <= 3.5 * h0) break;\n  }\n  cm.setCursor(Pos(0, val.length - 1));\n  cm.moveV(-1, \"line\");\n  eqCursorPos(cm.getCursor(), Pos(0, 27, \"before\"));\n  is(cm.cursorCoords(null, \"local\").top < h0, \"cursor is in first visual line\");\n}, {lineWrapping: true}, ie_lt8 || opera_lt10);\n\ntestCM(\"collapseOnMove\", function(cm) {\n  cm.setSelection(Pos(0, 1), Pos(2, 4));\n  cm.execCommand(\"goLineUp\");\n  is(!cm.somethingSelected());\n  eqCharPos(cm.getCursor(), Pos(0, 1));\n  cm.setSelection(Pos(0, 1), Pos(2, 4));\n  cm.execCommand(\"goPageDown\");\n  is(!cm.somethingSelected());\n  eqCharPos(cm.getCursor(), Pos(2, 4));\n  cm.execCommand(\"goLineUp\");\n  cm.execCommand(\"goLineUp\");\n  eqCharPos(cm.getCursor(), Pos(0, 4));\n  cm.setSelection(Pos(0, 1), Pos(2, 4));\n  cm.execCommand(\"goCharLeft\");\n  is(!cm.somethingSelected());\n  eqCharPos(cm.getCursor(), Pos(0, 1));\n}, {value: \"aaaaa\\nb\\nccccc\"});\n\ntestCM(\"clickTab\", function(cm) {\n  var p0 = cm.charCoords(Pos(0, 0));\n  eqCharPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), Pos(0, 0));\n  eqCharPos(cm.coordsChar({left: p0.right - 5, top: p0.top + 5}), Pos(0, 1));\n}, {value: \"\\t\\n\\n\", lineWrapping: true, tabSize: 8});\n\ntestCM(\"verticalScroll\", function(cm) {\n  cm.setSize(100, 200);\n  cm.setValue(\"foo\\nbar\\nbaz\\n\");\n  var sc = cm.getScrollerElement(), baseWidth = sc.scrollWidth;\n  cm.replaceRange(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah\", Pos(0, 0), Pos(0));\n  is(sc.scrollWidth > baseWidth, \"scrollbar present\");\n  cm.replaceRange(\"foo\", Pos(0, 0), Pos(0));\n  if (!phantom) eq(sc.scrollWidth, baseWidth, \"scrollbar gone\");\n  cm.replaceRange(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah\", Pos(0, 0), Pos(0));\n  cm.replaceRange(\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh\", Pos(1, 0), Pos(1));\n  is(sc.scrollWidth > baseWidth, \"present again\");\n  var curWidth = sc.scrollWidth;\n  cm.replaceRange(\"foo\", Pos(0, 0), Pos(0));\n  is(sc.scrollWidth < curWidth, \"scrollbar smaller\");\n  is(sc.scrollWidth > baseWidth, \"but still present\");\n});\n\ntestCM(\"extraKeys\", function(cm) {\n  var outcome;\n  function fakeKey(expected, code, props) {\n    if (typeof code == \"string\") code = code.charCodeAt(0);\n    var e = {type: \"keydown\", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}};\n    if (props) for (var n in props) e[n] = props[n];\n    outcome = null;\n    cm.triggerOnKeyDown(e);\n    eq(outcome, expected);\n  }\n  CodeMirror.commands.testCommand = function() {outcome = \"tc\";};\n  CodeMirror.commands.goTestCommand = function() {outcome = \"gtc\";};\n  cm.setOption(\"extraKeys\", {\"Shift-X\": function() {outcome = \"sx\";},\n                             \"X\": function() {outcome = \"x\";},\n                             \"Ctrl-Alt-U\": function() {outcome = \"cau\";},\n                             \"End\": \"testCommand\",\n                             \"Home\": \"goTestCommand\",\n                             \"Tab\": false});\n  fakeKey(null, \"U\");\n  fakeKey(\"cau\", \"U\", {ctrlKey: true, altKey: true});\n  fakeKey(null, \"U\", {shiftKey: true, ctrlKey: true, altKey: true});\n  fakeKey(\"x\", \"X\");\n  fakeKey(\"sx\", \"X\", {shiftKey: true});\n  fakeKey(\"tc\", 35);\n  fakeKey(null, 35, {shiftKey: true});\n  fakeKey(\"gtc\", 36);\n  fakeKey(\"gtc\", 36, {shiftKey: true});\n  fakeKey(null, 9);\n}, null, window.opera && mac);\n\ntestCM(\"wordMovementCommands\", function(cm) {\n  cm.execCommand(\"goWordLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n  cm.execCommand(\"goWordRight\"); cm.execCommand(\"goWordRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 7, \"before\"));\n  cm.execCommand(\"goWordLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 5, \"after\"));\n  cm.execCommand(\"goWordRight\"); cm.execCommand(\"goWordRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 12, \"before\"));\n  cm.execCommand(\"goWordLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 9, \"after\"));\n  cm.execCommand(\"goWordRight\"); cm.execCommand(\"goWordRight\"); cm.execCommand(\"goWordRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 24, \"before\"));\n  cm.execCommand(\"goWordRight\"); cm.execCommand(\"goWordRight\");\n  eqCursorPos(cm.getCursor(), Pos(1, 9, \"before\"));\n  cm.execCommand(\"goWordRight\");\n  eqCursorPos(cm.getCursor(), Pos(1, 13, \"before\"));\n  cm.execCommand(\"goWordRight\"); cm.execCommand(\"goWordRight\");\n  eqCharPos(cm.getCursor(), Pos(2, 0));\n}, {value: \"this is (the) firstline.\\na foo12\\u00e9\\u00f8\\u00d7bar\\n\"});\n\ntestCM(\"groupMovementCommands\", function(cm) {\n  cm.execCommand(\"goGroupLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n  cm.execCommand(\"goGroupRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 4, \"before\"));\n  cm.execCommand(\"goGroupRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 7, \"before\"));\n  cm.execCommand(\"goGroupRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 10, \"before\"));\n  cm.execCommand(\"goGroupLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 7, \"after\"));\n  cm.execCommand(\"goGroupRight\"); cm.execCommand(\"goGroupRight\"); cm.execCommand(\"goGroupRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 15, \"before\"));\n  cm.setCursor(Pos(0, 17));\n  cm.execCommand(\"goGroupLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 16, \"after\"));\n  cm.execCommand(\"goGroupLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 14, \"after\"));\n  cm.execCommand(\"goGroupRight\"); cm.execCommand(\"goGroupRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 20, \"before\"));\n  cm.execCommand(\"goGroupRight\");\n  eqCursorPos(cm.getCursor(), Pos(1, 0, \"after\"));\n  cm.execCommand(\"goGroupRight\");\n  eqCursorPos(cm.getCursor(), Pos(1, 2, \"before\"));\n  cm.execCommand(\"goGroupRight\");\n  eqCursorPos(cm.getCursor(), Pos(1, 5, \"before\"));\n  cm.execCommand(\"goGroupLeft\"); cm.execCommand(\"goGroupLeft\");\n  eqCursorPos(cm.getCursor(), Pos(1, 0, \"after\"));\n  cm.execCommand(\"goGroupLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 20, \"after\"));\n  cm.execCommand(\"goGroupLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 16, \"after\"));\n}, {value: \"booo ba---quux. ffff\\n  abc d\"});\n\ntestCM(\"groupsAndWhitespace\", function(cm) {\n  var positions = [Pos(0, 0), Pos(0, 2), Pos(0, 5), Pos(0, 9), Pos(0, 11),\n                   Pos(1, 0), Pos(1, 2), Pos(1, 5)];\n  for (var i = 1; i < positions.length; i++) {\n    cm.execCommand(\"goGroupRight\");\n    eqCharPos(cm.getCursor(), positions[i]);\n  }\n  for (var i = positions.length - 2; i >= 0; i--) {\n    cm.execCommand(\"goGroupLeft\");\n    eqCharPos(cm.getCursor(), i == 2 ? Pos(0, 6, \"before\") : positions[i]);\n  }\n}, {value: \"  foo +++  \\n  bar\"});\n\ntestCM(\"charMovementCommands\", function(cm) {\n  cm.execCommand(\"goCharLeft\"); cm.execCommand(\"goColumnLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n  cm.execCommand(\"goCharRight\"); cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 2, \"before\"));\n  cm.setCursor(Pos(1, 0));\n  cm.execCommand(\"goColumnLeft\");\n  eqCursorPos(cm.getCursor(), Pos(1, 0));\n  cm.execCommand(\"goCharLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 5, \"before\"));\n  cm.execCommand(\"goColumnRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 5, \"before\"));\n  cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(1, 0, \"after\"));\n  cm.execCommand(\"goLineEnd\");\n  eqCursorPos(cm.getCursor(), Pos(1, 5, \"before\"));\n  cm.execCommand(\"goLineStartSmart\");\n  eqCursorPos(cm.getCursor(), Pos(1, 1, \"after\"));\n  cm.execCommand(\"goLineStartSmart\");\n  eqCursorPos(cm.getCursor(), Pos(1, 0, \"after\"));\n  cm.setCursor(Pos(2, 0));\n  cm.execCommand(\"goCharRight\"); cm.execCommand(\"goColumnRight\");\n  eqCursorPos(cm.getCursor(), Pos(2, 0));\n}, {value: \"line1\\n ine2\\n\"});\n\ntestCM(\"verticalMovementCommands\", function(cm) {\n  cm.execCommand(\"goLineUp\");\n  eqCharPos(cm.getCursor(), Pos(0, 0));\n  cm.execCommand(\"goLineDown\");\n  if (!phantom) // This fails in PhantomJS, though not in a real Webkit\n    eqCharPos(cm.getCursor(), Pos(1, 0));\n  cm.setCursor(Pos(1, 12));\n  cm.execCommand(\"goLineDown\");\n  eqCharPos(cm.getCursor(), Pos(2, 5));\n  cm.execCommand(\"goLineDown\");\n  eqCharPos(cm.getCursor(), Pos(3, 0));\n  cm.execCommand(\"goLineUp\");\n  eqCharPos(cm.getCursor(), Pos(2, 5));\n  cm.execCommand(\"goLineUp\");\n  eqCharPos(cm.getCursor(), Pos(1, 12));\n  cm.execCommand(\"goPageDown\");\n  eqCharPos(cm.getCursor(), Pos(5, 0));\n  cm.execCommand(\"goPageDown\"); cm.execCommand(\"goLineDown\");\n  eqCharPos(cm.getCursor(), Pos(5, 0));\n  cm.execCommand(\"goPageUp\");\n  eqCharPos(cm.getCursor(), Pos(0, 0));\n}, {value: \"line1\\nlong long line2\\nline3\\n\\nline5\\n\"});\n\ntestCM(\"verticalMovementCommandsWrapping\", function(cm) {\n  cm.setSize(120);\n  cm.setCursor(Pos(0, 5));\n  cm.execCommand(\"goLineDown\");\n  eq(cm.getCursor().line, 0);\n  is(cm.getCursor().ch > 5, \"moved beyond wrap\");\n  for (var i = 0; ; ++i) {\n    is(i < 20, \"no endless loop\");\n    cm.execCommand(\"goLineDown\");\n    var cur = cm.getCursor();\n    if (cur.line == 1) eq(cur.ch, 5);\n    if (cur.line == 2) { eq(cur.ch, 1); break; }\n  }\n}, {value: \"a very long line that wraps around somehow so that we can test cursor movement\\nshortone\\nk\",\n    lineWrapping: true});\n\ntestCM(\"verticalMovementCommandsSingleLine\", function(cm) {\n  cm.display.wrapper.style.height = \"auto\";\n  cm.refresh();\n  cm.execCommand(\"goLineUp\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n  cm.execCommand(\"goLineDown\");\n  eqCursorPos(cm.getCursor(), Pos(0, 11));\n  cm.setCursor(Pos(0, 5));\n  cm.execCommand(\"goLineDown\");\n  eqCursorPos(cm.getCursor(), Pos(0, 11));\n  cm.execCommand(\"goLineDown\");\n  eqCursorPos(cm.getCursor(), Pos(0, 11));\n  cm.execCommand(\"goLineUp\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n  cm.execCommand(\"goLineUp\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n  cm.execCommand(\"goPageDown\");\n  eqCursorPos(cm.getCursor(), Pos(0, 11));\n  cm.execCommand(\"goPageDown\"); cm.execCommand(\"goLineDown\");\n  eqCursorPos(cm.getCursor(), Pos(0, 11));\n  cm.execCommand(\"goPageUp\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n  cm.setCursor(Pos(0, 5));\n  cm.execCommand(\"goPageUp\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n  cm.setCursor(Pos(0, 5));\n  cm.execCommand(\"goPageDown\");\n  eqCursorPos(cm.getCursor(), Pos(0, 11));\n}, {value: \"single line\"});\n\n\ntestCM(\"rtlMovement\", function(cm) {\n  if (cm.getOption(\"inputStyle\") != \"textarea\") return;\n  forEach([\"خحج\", \"خحabcخحج\", \"abخحخحجcd\", \"abخde\", \"abخح2342خ1حج\", \"خ1ح2خح3حxج\",\n           \"خحcd\", \"1خحcd\", \"abcdeح1ج\", \"خمرحبها مها!\", \"foobarر\", \"خ ة ق\",\n           \"<img src=\\\"/בדיקה3.jpg\\\">\", \"يتم السحب في 05 فبراير 2014\"], function(line) {\n    cm.setValue(line + \"\\n\"); cm.execCommand(\"goLineStart\");\n    var cursors = byClassName(cm.getWrapperElement(), \"CodeMirror-cursors\")[0];\n    var cursor = cursors.firstChild;\n    var prevX = cursor.offsetLeft, prevY = cursor.offsetTop;\n    for (var i = 0; i <= line.length; ++i) {\n      cm.execCommand(\"goCharRight\");\n      cursor = cursors.firstChild;\n      if (i == line.length) is(cursor.offsetTop > prevY, \"next line\");\n      else is(cursor.offsetLeft > prevX, \"moved right\");\n      prevX = cursor.offsetLeft; prevY = cursor.offsetTop;\n    }\n    cm.setCursor(0, 0); cm.execCommand(\"goLineEnd\");\n    prevX = cursors.firstChild.offsetLeft;\n    for (var i = 0; i < line.length; ++i) {\n      cm.execCommand(\"goCharLeft\");\n      cursor = cursors.firstChild;\n      is(cursor.offsetLeft < prevX, \"moved left\");\n      prevX = cursor.offsetLeft;\n    }\n  });\n}, null, ie_lt9);\n\n// Verify that updating a line clears its bidi ordering\ntestCM(\"bidiUpdate\", function(cm) {\n  cm.setCursor(Pos(0, 2, \"before\"));\n  cm.replaceSelection(\"خحج\", \"start\");\n  cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 6, \"before\"));\n}, {value: \"abcd\\n\"});\n\ntestCM(\"movebyTextUnit\", function(cm) {\n  cm.setValue(\"בְּרֵאשִ\\nééé́\\n\");\n  cm.execCommand(\"goLineStart\");\n  for (var i = 0; i < 4; ++i) cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0, \"after\"));\n  cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(1, 0, \"after\"));\n  cm.execCommand(\"goCharRight\");\n  cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(1, 4, \"before\"));\n  cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(1, 7, \"before\"));\n});\n\ntestCM(\"lineChangeEvents\", function(cm) {\n  addDoc(cm, 3, 5);\n  var log = [], want = [\"ch 0\", \"ch 1\", \"del 2\", \"ch 0\", \"ch 0\", \"del 1\", \"del 3\", \"del 4\"];\n  for (var i = 0; i < 5; ++i) {\n    CodeMirror.on(cm.getLineHandle(i), \"delete\", function(i) {\n      return function() {log.push(\"del \" + i);};\n    }(i));\n    CodeMirror.on(cm.getLineHandle(i), \"change\", function(i) {\n      return function() {log.push(\"ch \" + i);};\n    }(i));\n  }\n  cm.replaceRange(\"x\", Pos(0, 1));\n  cm.replaceRange(\"xy\", Pos(1, 1), Pos(2));\n  cm.replaceRange(\"foo\\nbar\", Pos(0, 1));\n  cm.replaceRange(\"\", Pos(0, 0), Pos(cm.lineCount()));\n  eq(log.length, want.length, \"same length\");\n  for (var i = 0; i < log.length; ++i)\n    eq(log[i], want[i]);\n});\n\ntestCM(\"scrollEntirelyToRight\", function(cm) {\n  if (phantom || cm.getOption(\"inputStyle\") != \"textarea\") return;\n  addDoc(cm, 500, 2);\n  cm.setCursor(Pos(0, 500));\n  var wrap = cm.getWrapperElement(), cur = byClassName(wrap, \"CodeMirror-cursor\")[0];\n  is(wrap.getBoundingClientRect().right > cur.getBoundingClientRect().left);\n});\n\ntestCM(\"lineWidgets\", function(cm) {\n  addDoc(cm, 500, 3);\n  var last = cm.charCoords(Pos(2, 0));\n  var node = document.createElement(\"div\");\n  node.innerHTML = \"hi\";\n  var widget = cm.addLineWidget(1, node);\n  is(last.top < cm.charCoords(Pos(2, 0)).top, \"took up space\");\n  cm.setCursor(Pos(1, 1));\n  cm.execCommand(\"goLineDown\");\n  eqCharPos(cm.getCursor(), Pos(2, 1));\n  cm.execCommand(\"goLineUp\");\n  eqCharPos(cm.getCursor(), Pos(1, 1));\n});\n\ntestCM(\"lineWidgetFocus\", function(cm) {\n  var place = document.getElementById(\"testground\");\n  place.className = \"offscreen\";\n  try {\n    addDoc(cm, 500, 10);\n    var node = document.createElement(\"input\");\n    var widget = cm.addLineWidget(1, node);\n    node.focus();\n    eq(document.activeElement, node);\n    cm.replaceRange(\"new stuff\", Pos(1, 0));\n    eq(document.activeElement, node);\n  } finally {\n    place.className = \"\";\n  }\n});\n\ntestCM(\"lineWidgetCautiousRedraw\", function(cm) {\n  var node = document.createElement(\"div\");\n  node.innerHTML = \"hahah\";\n  var w = cm.addLineWidget(0, node);\n  var redrawn = false;\n  w.on(\"redraw\", function() { redrawn = true; });\n  cm.replaceSelection(\"0\");\n  is(!redrawn);\n}, {value: \"123\\n456\"});\n\n\nvar knownScrollbarWidth;\nfunction scrollbarWidth(measure) {\n  if (knownScrollbarWidth != null) return knownScrollbarWidth;\n  var div = document.createElement('div');\n  div.style.cssText = \"width: 50px; height: 50px; overflow-x: scroll\";\n  document.body.appendChild(div);\n  knownScrollbarWidth = div.offsetHeight - div.clientHeight;\n  document.body.removeChild(div);\n  return knownScrollbarWidth || 0;\n}\n\ntestCM(\"lineWidgetChanged\", function(cm) {\n  addDoc(cm, 2, 300);\n  var halfScrollbarWidth = scrollbarWidth(cm.display.measure)/2;\n  cm.setOption('lineNumbers', true);\n  cm.setSize(600, cm.defaultTextHeight() * 50);\n  cm.scrollTo(null, cm.heightAtLine(125, \"local\"));\n\n  var expectedWidgetHeight = 60;\n  var expectedLinesInWidget = 3;\n  function w() {\n    var node = document.createElement(\"div\");\n    // we use these children with just under half width of the line to check measurements are made with correct width\n    // when placed in the measure div.\n    // If the widget is measured at a width much narrower than it is displayed at, the underHalf children will span two lines and break the test.\n    // If the widget is measured at a width much wider than it is displayed at, the overHalf children will combine and break the test.\n    // Note that this test only checks widgets where coverGutter is true, because these require extra styling to get the width right.\n    // It may also be worthwhile to check this for non-coverGutter widgets.\n    // Visually:\n    // Good:\n    // | ------------- display width ------------- |\n    // | ------- widget-width when measured ------ |\n    // | | -- under-half -- | | -- under-half -- | |\n    // | | --- over-half --- |                     |\n    // | | --- over-half --- |                     |\n    // Height: measured as 3 lines, same as it will be when actually displayed\n\n    // Bad (too narrow):\n    // | ------------- display width ------------- |\n    // | ------ widget-width when measured ----- |  < -- uh oh\n    // | | -- under-half -- |                    |\n    // | | -- under-half -- |                    |  < -- when measured, shoved to next line\n    // | | --- over-half --- |                   |\n    // | | --- over-half --- |                   |\n    // Height: measured as 4 lines, more than expected . Will be displayed as 3 lines!\n\n    // Bad (too wide):\n    // | ------------- display width ------------- |\n    // | -------- widget-width when measured ------- | < -- uh oh\n    // | | -- under-half -- | | -- under-half -- |   |\n    // | | --- over-half --- | | --- over-half --- | | < -- when measured, combined on one line\n    // Height: measured as 2 lines, less than expected. Will be displayed as 3 lines!\n\n    var barelyUnderHalfWidthHtml = '<div style=\"display: inline-block; height: 1px; width: '+(285 - halfScrollbarWidth)+'px;\"></div>';\n    var barelyOverHalfWidthHtml = '<div style=\"display: inline-block; height: 1px; width: '+(305 - halfScrollbarWidth)+'px;\"></div>';\n    node.innerHTML = new Array(3).join(barelyUnderHalfWidthHtml) + new Array(3).join(barelyOverHalfWidthHtml);\n    node.style.cssText = \"background: yellow;font-size:0;line-height: \" + (expectedWidgetHeight/expectedLinesInWidget) + \"px;\";\n    return node;\n  }\n  var info0 = cm.getScrollInfo();\n  var w0 = cm.addLineWidget(0, w(), { coverGutter: true });\n  var w150 = cm.addLineWidget(150, w(), { coverGutter: true });\n  var w300 = cm.addLineWidget(300, w(), { coverGutter: true });\n  var info1 = cm.getScrollInfo();\n  eq(info0.height + (3 * expectedWidgetHeight), info1.height);\n  eq(info0.top + expectedWidgetHeight, info1.top);\n  expectedWidgetHeight = 12;\n  w0.node.style.lineHeight = w150.node.style.lineHeight = w300.node.style.lineHeight = (expectedWidgetHeight/expectedLinesInWidget) + \"px\";\n  w0.changed(); w150.changed(); w300.changed();\n  var info2 = cm.getScrollInfo();\n  eq(info0.height + (3 * expectedWidgetHeight), info2.height);\n  eq(info0.top + expectedWidgetHeight, info2.top);\n});\n\ntestCM(\"lineWidgetIssue5486\", function(cm) {\n  // [prepare]\n  // 2nd line is combined to 1st line due to markText\n  // 2nd line has a lineWidget below\n\n  cm.setValue(\"Lorem\\nIpsue\\nDollar\")\n\n  var el = document.createElement('div')\n  el.style.height='50px'\n  el.textContent = '[[LINE WIDGET]]'\n  \n  var lineWidget = cm.addLineWidget(1, el, {\n    above: false,\n    coverGutter: false,\n    noHScroll: false,\n    showIfHidden: false,\n  })\n  \n  var marker = document.createElement('span')\n  marker.textContent = '[--]'\n  \n  cm.markText({line:0, ch: 1}, {line:1, ch: 4}, {\n    replacedWith: marker\n  })\n\n  // before resizing the lineWidget, measure 3rd line position\n\n  var measure_1 = Math.round(cm.charCoords({line:2, ch:0}).top)\n  \n  // resize lineWidget, height + 50 px\n\n  el.style.height='100px'\n  el.textContent += \"\\nlineWidget size changed.\\nTry moving cursor to line 3?\"\n  \n  lineWidget.changed()\n\n  // re-measure 3rd line position\n  var measure_2 = Math.round(cm.charCoords({line:2, ch:0}).top)\n  eq(measure_2, measure_1 + 50)\n\n  // (extra test)\n  //\n  // add char to the right of the folded marker\n  // and re-measure 3rd line position\n\n  cm.replaceRange('-', {line:1, ch: 5})\n  var measure_3 = Math.round(cm.charCoords({line:2, ch:0}).top)\n  eq(measure_3, measure_2)\n});\n\ntestCM(\"getLineNumber\", function(cm) {\n  addDoc(cm, 2, 20);\n  var h1 = cm.getLineHandle(1);\n  eq(cm.getLineNumber(h1), 1);\n  cm.replaceRange(\"hi\\nbye\\n\", Pos(0, 0));\n  eq(cm.getLineNumber(h1), 3);\n  cm.setValue(\"\");\n  eq(cm.getLineNumber(h1), null);\n});\n\ntestCM(\"jumpTheGap\", function(cm) {\n  if (phantom) return;\n  var longLine = \"abcdef ghiklmnop qrstuvw xyz \";\n  longLine += longLine; longLine += longLine; longLine += longLine;\n  cm.replaceRange(longLine, Pos(2, 0), Pos(2));\n  cm.setSize(\"200px\", null);\n  cm.getWrapperElement().style.lineHeight = 2;\n  cm.refresh();\n  cm.setCursor(Pos(0, 1));\n  cm.execCommand(\"goLineDown\");\n  eqCharPos(cm.getCursor(), Pos(1, 1));\n  cm.execCommand(\"goLineDown\");\n  eqCharPos(cm.getCursor(), Pos(2, 1));\n  cm.execCommand(\"goLineDown\");\n  eq(cm.getCursor().line, 2);\n  is(cm.getCursor().ch > 1);\n  cm.execCommand(\"goLineUp\");\n  eqCharPos(cm.getCursor(), Pos(2, 1));\n  cm.execCommand(\"goLineUp\");\n  eqCharPos(cm.getCursor(), Pos(1, 1));\n  var node = document.createElement(\"div\");\n  node.innerHTML = \"hi\"; node.style.height = \"30px\";\n  cm.addLineWidget(0, node);\n  cm.addLineWidget(1, node.cloneNode(true), {above: true});\n  cm.setCursor(Pos(0, 2));\n  cm.execCommand(\"goLineDown\");\n  eqCharPos(cm.getCursor(), Pos(1, 2));\n  cm.execCommand(\"goLineUp\");\n  eqCharPos(cm.getCursor(), Pos(0, 2));\n}, {lineWrapping: true, value: \"abc\\ndef\\nghi\\njkl\\n\"});\n\ntestCM(\"addLineClass\", function(cm) {\n  function cls(line, text, bg, wrap, gutter) {\n    var i = cm.lineInfo(line);\n    eq(i.textClass, text);\n    eq(i.bgClass, bg);\n    eq(i.wrapClass, wrap);\n    if (typeof i.handle.gutterClass !== 'undefined') {\n        eq(i.handle.gutterClass, gutter);\n    }\n  }\n  cm.addLineClass(0, \"text\", \"foo\");\n  cm.addLineClass(0, \"text\", \"bar\");\n  cm.addLineClass(1, \"background\", \"baz\");\n  cm.addLineClass(1, \"wrap\", \"foo\");\n  cm.addLineClass(1, \"gutter\", \"gutter-class\");\n  cls(0, \"foo bar\", null, null, null);\n  cls(1, null, \"baz\", \"foo\", \"gutter-class\");\n  var lines = cm.display.lineDiv;\n  eq(byClassName(lines, \"foo\").length, 2);\n  eq(byClassName(lines, \"bar\").length, 1);\n  eq(byClassName(lines, \"baz\").length, 1);\n  eq(byClassName(lines, \"gutter-class\").length, 2); // Gutter classes are reflected in 2 nodes\n  cm.removeLineClass(0, \"text\", \"foo\");\n  cls(0, \"bar\", null, null, null);\n  cm.removeLineClass(0, \"text\", \"foo\");\n  cls(0, \"bar\", null, null, null);\n  cm.removeLineClass(0, \"text\", \"bar\");\n  cls(0, null, null, null);\n\n  cm.addLineClass(1, \"wrap\", \"quux\");\n  cls(1, null, \"baz\", \"foo quux\", \"gutter-class\");\n  cm.removeLineClass(1, \"wrap\");\n  cls(1, null, \"baz\", null, \"gutter-class\");\n  cm.removeLineClass(1, \"gutter\", \"gutter-class\");\n  eq(byClassName(lines, \"gutter-class\").length, 0);\n  cls(1, null, \"baz\", null, null);\n\n  cm.addLineClass(1, \"gutter\", \"gutter-class\");\n  cls(1, null, \"baz\", null, \"gutter-class\");\n  cm.removeLineClass(1, \"gutter\", \"gutter-class\");\n  cls(1, null, \"baz\", null, null);\n\n}, {value: \"hohoho\\n\", lineNumbers: true});\n\ntestCM(\"atomicMarker\", function(cm) {\n  addDoc(cm, 10, 10);\n  function atom(ll, cl, lr, cr, li, ri) {\n    return cm.markText(Pos(ll, cl), Pos(lr, cr),\n                       {atomic: true, inclusiveLeft: li, inclusiveRight: ri});\n  }\n  var m = atom(0, 1, 0, 5);\n  cm.setCursor(Pos(0, 1));\n  cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(0, 5));\n  cm.execCommand(\"goCharLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 1));\n  m.clear();\n  m = atom(0, 0, 0, 5, true);\n  eqCursorPos(cm.getCursor(), Pos(0, 5), \"pushed out\");\n  cm.execCommand(\"goCharLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 5));\n  m.clear();\n  m = atom(8, 4, 9, 10, false, true);\n  cm.setCursor(Pos(9, 8));\n  eqCursorPos(cm.getCursor(), Pos(8, 4), \"set\");\n  cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(8, 4), \"char right\");\n  cm.execCommand(\"goLineDown\");\n  eqCursorPos(cm.getCursor(), Pos(8, 4), \"line down\");\n  cm.execCommand(\"goCharLeft\");\n  eqCursorPos(cm.getCursor(), Pos(8, 3, \"after\"));\n  m.clear();\n  m = atom(1, 1, 3, 8);\n  cm.setCursor(Pos(0, 0));\n  cm.setCursor(Pos(2, 0));\n  eqCursorPos(cm.getCursor(), Pos(3, 8));\n  cm.execCommand(\"goCharLeft\");\n  eqCursorPos(cm.getCursor(), Pos(1, 1));\n  cm.execCommand(\"goCharRight\");\n  eqCursorPos(cm.getCursor(), Pos(3, 8));\n  cm.execCommand(\"goLineUp\");\n  eqCursorPos(cm.getCursor(), Pos(1, 1));\n  cm.execCommand(\"goLineDown\");\n  eqCursorPos(cm.getCursor(), Pos(3, 8));\n  cm.execCommand(\"delCharBefore\");\n  eq(cm.getValue().length, 80, \"del chunk\");\n  m = atom(3, 0, 5, 5);\n  cm.setCursor(Pos(3, 0));\n  cm.execCommand(\"delWordAfter\");\n  eq(cm.getValue().length, 53, \"del chunk\");\n});\n\ntestCM(\"selectionBias\", function(cm) {\n  cm.markText(Pos(0, 1), Pos(0, 3), {atomic: true});\n  cm.setCursor(Pos(0, 2));\n  eqCursorPos(cm.getCursor(), Pos(0, 1));\n  cm.setCursor(Pos(0, 2));\n  eqCursorPos(cm.getCursor(), Pos(0, 3));\n  cm.setCursor(Pos(0, 2));\n  eqCursorPos(cm.getCursor(), Pos(0, 1));\n  cm.setCursor(Pos(0, 2), null, {bias: -1});\n  eqCursorPos(cm.getCursor(), Pos(0, 1));\n  cm.setCursor(Pos(0, 4));\n  cm.setCursor(Pos(0, 2), null, {bias: 1});\n  eqCursorPos(cm.getCursor(), Pos(0, 3));\n}, {value: \"12345\"});\n\ntestCM(\"selectionHomeEnd\", function(cm) {\n  cm.markText(Pos(1, 0), Pos(1, 1), {atomic: true, inclusiveLeft: true});\n  cm.markText(Pos(1, 3), Pos(1, 4), {atomic: true, inclusiveRight: true});\n  cm.setCursor(Pos(1, 2));\n  cm.execCommand(\"goLineStart\");\n  eqCursorPos(cm.getCursor(), Pos(1, 1));\n  cm.execCommand(\"goLineEnd\");\n  eqCursorPos(cm.getCursor(), Pos(1, 3));\n}, {value: \"ab\\ncdef\\ngh\"});\n\ntestCM(\"readOnlyMarker\", function(cm) {\n  function mark(ll, cl, lr, cr, at) {\n    return cm.markText(Pos(ll, cl), Pos(lr, cr),\n                       {readOnly: true, atomic: at});\n  }\n  var m = mark(0, 1, 0, 4);\n  cm.setCursor(Pos(0, 2));\n  cm.replaceSelection(\"hi\", \"end\");\n  eqCursorPos(cm.getCursor(), Pos(0, 2));\n  eq(cm.getLine(0), \"abcde\");\n  cm.execCommand(\"selectAll\");\n  cm.replaceSelection(\"oops\", \"around\");\n  eq(cm.getValue(), \"oopsbcd\");\n  cm.undo();\n  eqCursorPos(m.find().from, Pos(0, 1));\n  eqCursorPos(m.find().to, Pos(0, 4));\n  m.clear();\n  cm.setCursor(Pos(0, 2));\n  cm.replaceSelection(\"hi\", \"around\");\n  eq(cm.getLine(0), \"abhicde\");\n  eqCursorPos(cm.getCursor(), Pos(0, 4));\n  m = mark(0, 2, 2, 2, true);\n  cm.setSelection(Pos(1, 1), Pos(2, 4));\n  cm.replaceSelection(\"t\", \"end\");\n  eqCursorPos(cm.getCursor(), Pos(2, 3));\n  eq(cm.getLine(2), \"klto\");\n  cm.execCommand(\"goCharLeft\");\n  cm.execCommand(\"goCharLeft\");\n  eqCursorPos(cm.getCursor(), Pos(0, 2));\n  cm.setSelection(Pos(0, 1), Pos(0, 3));\n  cm.replaceSelection(\"xx\", \"around\");\n  eqCursorPos(cm.getCursor(), Pos(0, 3));\n  eq(cm.getLine(0), \"axxhicde\");\n}, {value: \"abcde\\nfghij\\nklmno\\n\"});\n\ntestCM(\"dirtyBit\", function(cm) {\n  eq(cm.isClean(), true);\n  cm.replaceSelection(\"boo\", null, \"test\");\n  eq(cm.isClean(), false);\n  cm.undo();\n  eq(cm.isClean(), true);\n  cm.replaceSelection(\"boo\", null, \"test\");\n  cm.replaceSelection(\"baz\", null, \"test\");\n  cm.undo();\n  eq(cm.isClean(), false);\n  cm.markClean();\n  eq(cm.isClean(), true);\n  cm.undo();\n  eq(cm.isClean(), false);\n  cm.redo();\n  eq(cm.isClean(), true);\n});\n\ntestCM(\"changeGeneration\", function(cm) {\n  cm.replaceSelection(\"x\");\n  var softGen = cm.changeGeneration();\n  cm.replaceSelection(\"x\");\n  cm.undo();\n  eq(cm.getValue(), \"\");\n  is(!cm.isClean(softGen));\n  cm.replaceSelection(\"x\");\n  var hardGen = cm.changeGeneration(true);\n  cm.replaceSelection(\"x\");\n  cm.undo();\n  eq(cm.getValue(), \"x\");\n  is(cm.isClean(hardGen));\n});\n\ntestCM(\"addKeyMap\", function(cm) {\n  function sendKey(code) {\n    cm.triggerOnKeyDown({type: \"keydown\", keyCode: code,\n                         preventDefault: function(){}, stopPropagation: function(){}});\n  }\n\n  sendKey(39);\n  eqCursorPos(cm.getCursor(), Pos(0, 1, \"before\"));\n  var test = 0;\n  var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }}\n  cm.addKeyMap(map1);\n  sendKey(39);\n  eqCursorPos(cm.getCursor(), Pos(0, 1, \"before\"));\n  eq(test, 1);\n  cm.addKeyMap(map2, true);\n  sendKey(39);\n  eq(test, 2);\n  cm.removeKeyMap(map1);\n  sendKey(39);\n  eq(test, 12);\n  cm.removeKeyMap(map2);\n  sendKey(39);\n  eq(test, 12);\n  eqCursorPos(cm.getCursor(), Pos(0, 2, \"before\"));\n  cm.addKeyMap({Right: function() { test = 55; }, name: \"mymap\"});\n  sendKey(39);\n  eq(test, 55);\n  cm.removeKeyMap(\"mymap\");\n  sendKey(39);\n  eqCursorPos(cm.getCursor(), Pos(0, 3, \"before\"));\n}, {value: \"abc\"});\n\nfunction mouseDown(cm, button, pos, mods) {\n  var coords = cm.charCoords(pos, \"window\")\n  var event = {type: \"mousedown\",\n               preventDefault: Math.min,\n               which: button,\n               target: cm.display.lineDiv,\n               clientX: coords.left, clientY: coords.top}\n  if (mods) for (var prop in mods) event[prop] = mods[prop]\n  cm.triggerOnMouseDown(event)\n}\n\ntestCM(\"mouseBinding\", function(cm) {\n  var fired = []\n  cm.addKeyMap({\n    \"Shift-LeftClick\": function(_cm, pos) {\n      eqCharPos(pos, Pos(1, 2))\n      fired.push(\"a\")\n    },\n    \"Shift-LeftDoubleClick\": function() { fired.push(\"b\") },\n    \"Shift-LeftTripleClick\": function() { fired.push(\"c\") }\n  })\n\n  function send(button, mods) { mouseDown(cm, button, Pos(1, 2), mods) }\n  send(1, {shiftKey: true})\n  send(1, {shiftKey: true})\n  send(1, {shiftKey: true})\n  send(1, {})\n  send(2, {ctrlKey: true})\n  send(2, {ctrlKey: true})\n  eq(fired.join(\" \"), \"a b c\")\n}, {value: \"foo\\nbar\\nbaz\"})\n\ntestCM(\"configureMouse\", function(cm) {\n  cm.setOption(\"configureMouse\", function() { return {unit: \"word\"} })\n  mouseDown(cm, 1, Pos(0, 5))\n  eqCharPos(cm.getCursor(\"from\"), Pos(0, 4))\n  eqCharPos(cm.getCursor(\"to\"), Pos(0, 7))\n  cm.setOption(\"configureMouse\", function() { return {extend: true} })\n  mouseDown(cm, 1, Pos(0, 0))\n  eqCharPos(cm.getCursor(\"from\"), Pos(0, 0))\n  eqCharPos(cm.getCursor(\"to\"), Pos(0, 4))\n}, {value: \"foo bar baz\"})\n\ntestCM(\"findPosH\", function(cm) {\n  forEach([{from: Pos(0, 0), to: Pos(0, 1, \"before\"), by: 1},\n           {from: Pos(0, 0), to: Pos(0, 0), by: -1, hitSide: true},\n           {from: Pos(0, 0), to: Pos(0, 4, \"before\"), by: 1, unit: \"word\"},\n           {from: Pos(0, 0), to: Pos(0, 8, \"before\"), by: 2, unit: \"word\"},\n           {from: Pos(0, 0), to: Pos(2, 0, \"after\"), by: 20, unit: \"word\", hitSide: true},\n           {from: Pos(0, 7), to: Pos(0, 5, \"after\"), by: -1, unit: \"word\"},\n           {from: Pos(0, 4), to: Pos(0, 8, \"before\"), by: 1, unit: \"word\"},\n           {from: Pos(1, 0), to: Pos(1, 18, \"before\"), by: 3, unit: \"word\"},\n           {from: Pos(1, 22), to: Pos(1, 5, \"after\"), by: -3, unit: \"word\"},\n           {from: Pos(1, 15), to: Pos(1, 10, \"after\"), by: -5},\n           {from: Pos(1, 15), to: Pos(1, 10, \"after\"), by: -5, unit: \"column\"},\n           {from: Pos(1, 15), to: Pos(1, 0, \"after\"), by: -50, unit: \"column\", hitSide: true},\n           {from: Pos(1, 15), to: Pos(1, 24, \"before\"), by: 50, unit: \"column\", hitSide: true},\n           {from: Pos(1, 15), to: Pos(2, 0, \"after\"), by: 50, hitSide: true}], function(t) {\n    var r = cm.findPosH(t.from, t.by, t.unit || \"char\");\n    eqCursorPos(r, t.to);\n    eq(!!r.hitSide, !!t.hitSide);\n  });\n}, {value: \"line one\\nline two.something.other\\n\"});\n\ntestCM(\"beforeChange\", function(cm) {\n  cm.on(\"beforeChange\", function(cm, change) {\n    var text = [];\n    for (var i = 0; i < change.text.length; ++i)\n      text.push(change.text[i].replace(/\\s/g, \"_\"));\n    change.update(null, null, text);\n  });\n  cm.setValue(\"hello, i am a\\nnew document\\n\");\n  eq(cm.getValue(), \"hello,_i_am_a\\nnew_document\\n\");\n  CodeMirror.on(cm.getDoc(), \"beforeChange\", function(doc, change) {\n    if (change.from.line == 0) change.cancel();\n  });\n  cm.setValue(\"oops\"); // Canceled\n  eq(cm.getValue(), \"hello,_i_am_a\\nnew_document\\n\");\n  cm.replaceRange(\"hey hey hey\", Pos(1, 0), Pos(2, 0));\n  eq(cm.getValue(), \"hello,_i_am_a\\nhey_hey_hey\");\n}, {value: \"abcdefghijk\"});\n\ntestCM(\"beforeChangeUndo\", function(cm) {\n  cm.replaceRange(\"hi\", Pos(0, 0), Pos(0));\n  cm.replaceRange(\"bye\", Pos(0, 0), Pos(0));\n  eq(cm.historySize().undo, 2);\n  cm.on(\"beforeChange\", function(cm, change) {\n    is(!change.update);\n    change.cancel();\n  });\n  cm.undo();\n  eq(cm.historySize().undo, 0);\n  eq(cm.getValue(), \"bye\\ntwo\");\n}, {value: \"one\\ntwo\"});\n\ntestCM(\"beforeSelectionChange\", function(cm) {\n  function notAtEnd(cm, pos) {\n    var len = cm.getLine(pos.line).length;\n    if (!len || pos.ch == len) return Pos(pos.line, pos.ch - 1);\n    return pos;\n  }\n  cm.on(\"beforeSelectionChange\", function(cm, obj) {\n    obj.update([{anchor: notAtEnd(cm, obj.ranges[0].anchor),\n                 head: notAtEnd(cm, obj.ranges[0].head)}]);\n  });\n\n  addDoc(cm, 10, 10);\n  cm.execCommand(\"goLineEnd\");\n  eqCursorPos(cm.getCursor(), Pos(0, 9));\n  cm.execCommand(\"selectAll\");\n  eqCursorPos(cm.getCursor(\"start\"), Pos(0, 0));\n  eqCursorPos(cm.getCursor(\"end\"), Pos(9, 9));\n});\n\ntestCM(\"change_removedText\", function(cm) {\n  cm.setValue(\"abc\\ndef\");\n\n  var removedText = [];\n  cm.on(\"change\", function(cm, change) {\n    removedText.push(change.removed);\n  });\n\n  cm.operation(function() {\n    cm.replaceRange(\"xyz\", Pos(0, 0), Pos(1,1));\n    cm.replaceRange(\"123\", Pos(0,0));\n  });\n\n  eq(removedText.length, 2);\n  eq(removedText[0].join(\"\\n\"), \"abc\\nd\");\n  eq(removedText[1].join(\"\\n\"), \"\");\n\n  var removedText = [];\n  cm.undo();\n  eq(removedText.length, 2);\n  eq(removedText[0].join(\"\\n\"), \"123\");\n  eq(removedText[1].join(\"\\n\"), \"xyz\");\n\n  var removedText = [];\n  cm.redo();\n  eq(removedText.length, 2);\n  eq(removedText[0].join(\"\\n\"), \"abc\\nd\");\n  eq(removedText[1].join(\"\\n\"), \"\");\n});\n\ntestCM(\"lineStyleFromMode\", function(cm) {\n  CodeMirror.defineMode(\"test_mode\", function() {\n    return {token: function(stream) {\n      if (stream.match(/^\\[[^\\]]*\\]/)) return \"  line-brackets  \";\n      if (stream.match(/^\\([^\\)]*\\)/)) return \"  line-background-parens  \";\n      if (stream.match(/^<[^>]*>/)) return \"  span  line-line  line-background-bg  \";\n      stream.match(/^\\s+|^\\S+/);\n    }};\n  });\n  cm.setOption(\"mode\", \"test_mode\");\n  var bracketElts = byClassName(cm.getWrapperElement(), \"brackets\");\n  eq(bracketElts.length, 1, \"brackets count\");\n  eq(bracketElts[0].nodeName, \"PRE\");\n  is(!/brackets.*brackets/.test(bracketElts[0].className));\n  var parenElts = byClassName(cm.getWrapperElement(), \"parens\");\n  eq(parenElts.length, 1, \"parens count\");\n  eq(parenElts[0].nodeName, \"DIV\");\n  is(!/parens.*parens/.test(parenElts[0].className));\n  eq(parenElts[0].parentElement.nodeName, \"DIV\");\n\n  is(byClassName(cm.getWrapperElement(), \"bg\").length > 0);\n  is(byClassName(cm.getWrapperElement(), \"line\").length > 0);\n  var spanElts = byClassName(cm.getWrapperElement(), \"cm-span\");\n  eq(spanElts.length, 2);\n  is(/^\\s*cm-span\\s*$/.test(spanElts[0].className));\n}, {value: \"line1: [br] [br]\\nline2: (par) (par)\\nline3: <tag> <tag>\"});\n\ntestCM(\"lineStyleFromBlankLine\", function(cm) {\n  CodeMirror.defineMode(\"lineStyleFromBlankLine_mode\", function() {\n    return {token: function(stream) { stream.skipToEnd(); return \"comment\"; },\n            blankLine: function() { return \"line-blank\"; }};\n  });\n  cm.setOption(\"mode\", \"lineStyleFromBlankLine_mode\");\n  var blankElts = byClassName(cm.getWrapperElement(), \"blank\");\n  eq(blankElts.length, 1);\n  eq(blankElts[0].nodeName, \"PRE\");\n  cm.replaceRange(\"x\", Pos(1, 0));\n  blankElts = byClassName(cm.getWrapperElement(), \"blank\");\n  eq(blankElts.length, 0);\n}, {value: \"foo\\n\\nbar\"});\n\nCodeMirror.registerHelper(\"xxx\", \"a\", \"A\");\nCodeMirror.registerHelper(\"xxx\", \"b\", \"B\");\nCodeMirror.defineMode(\"yyy\", function() {\n  return {\n    token: function(stream) { stream.skipToEnd(); },\n    xxx: [\"a\", \"b\", \"q\"]\n  };\n});\nCodeMirror.registerGlobalHelper(\"xxx\", \"c\", function(m) { return m.enableC; }, \"C\");\n\ntestCM(\"helpers\", function(cm) {\n  cm.setOption(\"mode\", \"yyy\");\n  eq(cm.getHelpers(Pos(0, 0), \"xxx\").join(\"/\"), \"A/B\");\n  cm.setOption(\"mode\", {name: \"yyy\", modeProps: {xxx: \"b\", enableC: true}});\n  eq(cm.getHelpers(Pos(0, 0), \"xxx\").join(\"/\"), \"B/C\");\n  cm.setOption(\"mode\", \"javascript\");\n  eq(cm.getHelpers(Pos(0, 0), \"xxx\").join(\"/\"), \"\");\n});\n\ntestCM(\"selectionHistory\", function(cm) {\n  for (var i = 0; i < 3; i++) {\n    cm.setExtending(true);\n    cm.execCommand(\"goCharRight\");\n    cm.setExtending(false);\n    cm.execCommand(\"goCharRight\");\n    cm.execCommand(\"goCharRight\");\n  }\n  cm.execCommand(\"undoSelection\");\n  eq(cm.getSelection(), \"c\");\n  cm.execCommand(\"undoSelection\");\n  eq(cm.getSelection(), \"\");\n  eqCursorPos(cm.getCursor(), Pos(0, 4, \"before\"));\n  cm.execCommand(\"undoSelection\");\n  eq(cm.getSelection(), \"b\");\n  cm.execCommand(\"redoSelection\");\n  eq(cm.getSelection(), \"\");\n  eqCursorPos(cm.getCursor(), Pos(0, 4, \"before\"));\n  cm.execCommand(\"redoSelection\");\n  eq(cm.getSelection(), \"c\");\n  cm.execCommand(\"redoSelection\");\n  eq(cm.getSelection(), \"\");\n  eqCursorPos(cm.getCursor(), Pos(0, 6, \"before\"));\n}, {value: \"a b c d\"});\n\ntestCM(\"selectionChangeReducesRedo\", function(cm) {\n  cm.replaceSelection(\"X\");\n  cm.execCommand(\"goCharRight\");\n  cm.undoSelection();\n  cm.execCommand(\"selectAll\");\n  cm.undoSelection();\n  eq(cm.getValue(), \"Xabc\");\n  eqCursorPos(cm.getCursor(), Pos(0, 1));\n  cm.undoSelection();\n  eq(cm.getValue(), \"abc\");\n}, {value: \"abc\"});\n\ntestCM(\"selectionHistoryNonOverlapping\", function(cm) {\n  cm.setSelection(Pos(0, 0), Pos(0, 1));\n  cm.setSelection(Pos(0, 2), Pos(0, 3));\n  cm.execCommand(\"undoSelection\");\n  eqCursorPos(cm.getCursor(\"anchor\"), Pos(0, 0));\n  eqCursorPos(cm.getCursor(\"head\"), Pos(0, 1));\n}, {value: \"1234\"});\n\ntestCM(\"cursorMotionSplitsHistory\", function(cm) {\n  cm.replaceSelection(\"a\");\n  cm.execCommand(\"goCharRight\");\n  cm.replaceSelection(\"b\");\n  cm.replaceSelection(\"c\");\n  cm.undo();\n  eq(cm.getValue(), \"a1234\");\n  eqCursorPos(cm.getCursor(), Pos(0, 2, \"before\"));\n  cm.undo();\n  eq(cm.getValue(), \"1234\");\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n}, {value: \"1234\"});\n\ntestCM(\"selChangeInOperationDoesNotSplit\", function(cm) {\n  for (var i = 0; i < 4; i++) {\n    cm.operation(function() {\n      cm.replaceSelection(\"x\");\n      cm.setCursor(Pos(0, cm.getCursor().ch - 1));\n    });\n  }\n  eqCursorPos(cm.getCursor(), Pos(0, 0));\n  eq(cm.getValue(), \"xxxxa\");\n  cm.undo();\n  eq(cm.getValue(), \"a\");\n}, {value: \"a\"});\n\ntestCM(\"alwaysMergeSelEventWithChangeOrigin\", function(cm) {\n  cm.replaceSelection(\"U\", null, \"foo\");\n  cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: \"foo\"});\n  cm.undoSelection();\n  eq(cm.getValue(), \"a\");\n  cm.replaceSelection(\"V\", null, \"foo\");\n  cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: \"bar\"});\n  cm.undoSelection();\n  eq(cm.getValue(), \"Va\");\n}, {value: \"a\"});\n\ntestCM(\"getTokenAt\", function(cm) {\n  var tokPlus = cm.getTokenAt(Pos(0, 2));\n  eq(tokPlus.type, \"operator\");\n  eq(tokPlus.string, \"+\");\n  var toks = cm.getLineTokens(0);\n  eq(toks.length, 3);\n  forEach([[\"number\", \"1\"], [\"operator\", \"+\"], [\"number\", \"2\"]], function(expect, i) {\n    eq(toks[i].type, expect[0]);\n    eq(toks[i].string, expect[1]);\n  });\n}, {value: \"1+2\", mode: \"javascript\"});\n\ntestCM(\"getTokenTypeAt\", function(cm) {\n  eq(cm.getTokenTypeAt(Pos(0, 0)), \"number\");\n  eq(cm.getTokenTypeAt(Pos(0, 6)), \"string\");\n  cm.addOverlay({\n    token: function(stream) {\n      if (stream.match(\"foo\")) return \"foo\";\n      else stream.next();\n    }\n  });\n  eq(byClassName(cm.getWrapperElement(), \"cm-foo\").length, 1);\n  eq(cm.getTokenTypeAt(Pos(0, 6)), \"string\");\n}, {value: \"1 + 'foo'\", mode: \"javascript\"});\n\ntestCM(\"addOverlay\", function(cm) {\n  cm.addOverlay({\n    token: function(stream) {\n      var base = stream.baseToken()\n      if (!/comment/.test(base.type) && stream.match(/\\d+/)) return \"x\"\n      stream.next()\n    }\n  })\n  var x = byClassName(cm.getWrapperElement(), \"cm-x\")\n  is(x.length, 1)\n  is(x[0].textContent, \"233\")\n  cm.replaceRange(\"\", Pos(0, 4), Pos(0, 6))\n  is(byClassName(cm.getWrapperElement(), \"cm-x\").length, 2)\n}, {value: \"foo /* 100 */\\nbar + 233;\\nbaz\", mode: \"javascript\"})\n\ntestCM(\"resizeLineWidget\", function(cm) {\n  addDoc(cm, 200, 3);\n  var widget = document.createElement(\"pre\");\n  widget.innerHTML = \"imwidget\";\n  widget.style.background = \"yellow\";\n  cm.addLineWidget(1, widget, {noHScroll: true});\n  cm.setSize(40);\n  is(widget.parentNode.offsetWidth < 42);\n});\n\ntestCM(\"combinedOperations\", function(cm) {\n  var place = document.getElementById(\"testground\");\n  var other = CodeMirror(place, {value: \"123\"});\n  try {\n    cm.operation(function() {\n      cm.addLineClass(0, \"wrap\", \"foo\");\n      other.addLineClass(0, \"wrap\", \"foo\");\n    });\n    eq(byClassName(cm.getWrapperElement(), \"foo\").length, 1);\n    eq(byClassName(other.getWrapperElement(), \"foo\").length, 1);\n    cm.operation(function() {\n      cm.removeLineClass(0, \"wrap\", \"foo\");\n      other.removeLineClass(0, \"wrap\", \"foo\");\n    });\n    eq(byClassName(cm.getWrapperElement(), \"foo\").length, 0);\n    eq(byClassName(other.getWrapperElement(), \"foo\").length, 0);\n  } finally {\n    place.removeChild(other.getWrapperElement());\n  }\n}, {value: \"abc\"});\n\ntestCM(\"eventOrder\", function(cm) {\n  var seen = [];\n  cm.on(\"change\", function() {\n    if (!seen.length) cm.replaceSelection(\".\");\n    seen.push(\"change\");\n  });\n  cm.on(\"cursorActivity\", function() {\n    cm.replaceSelection(\"!\");\n    seen.push(\"activity\");\n  });\n  cm.replaceSelection(\"/\");\n  eq(seen.join(\",\"), \"change,change,activity,change\");\n});\n\ntestCM(\"splitSpaces_nonspecial\", function(cm) {\n  eq(byClassName(cm.getWrapperElement(), \"cm-invalidchar\").length, 0);\n}, {\n  specialChars: /[\\u00a0]/,\n  value: \"spaces ->            <- between\"\n});\n\ntest(\"core_rmClass\", function() {\n  var node = document.createElement(\"div\");\n  node.className = \"foo-bar baz-quux yadda\";\n  CodeMirror.rmClass(node, \"quux\");\n  eq(node.className, \"foo-bar baz-quux yadda\");\n  CodeMirror.rmClass(node, \"baz-quux\");\n  eq(node.className, \"foo-bar yadda\");\n  CodeMirror.rmClass(node, \"yadda\");\n  eq(node.className, \"foo-bar\");\n  CodeMirror.rmClass(node, \"foo-bar\");\n  eq(node.className, \"\");\n  node.className = \" foo \";\n  CodeMirror.rmClass(node, \"foo\");\n  eq(node.className, \"\");\n});\n\ntest(\"core_addClass\", function() {\n  var node = document.createElement(\"div\");\n  CodeMirror.addClass(node, \"a\");\n  eq(node.className, \"a\");\n  CodeMirror.addClass(node, \"a\");\n  eq(node.className, \"a\");\n  CodeMirror.addClass(node, \"b\");\n  eq(node.className, \"a b\");\n  CodeMirror.addClass(node, \"a\");\n  CodeMirror.addClass(node, \"b\");\n  eq(node.className, \"a b\");\n});\n\ntestCM(\"lineSeparator\", function(cm) {\n  eq(cm.lineCount(), 3);\n  eq(cm.getLine(1), \"bar\\r\");\n  eq(cm.getLine(2), \"baz\\rquux\");\n  cm.setOption(\"lineSeparator\", \"\\r\");\n  eq(cm.lineCount(), 5);\n  eq(cm.getLine(4), \"quux\");\n  eq(cm.getValue(), \"foo\\rbar\\r\\rbaz\\rquux\");\n  eq(cm.getValue(\"\\n\"), \"foo\\nbar\\n\\nbaz\\nquux\");\n  cm.setOption(\"lineSeparator\", null);\n  cm.setValue(\"foo\\nbar\\r\\nbaz\\rquux\");\n  eq(cm.lineCount(), 4);\n}, {value: \"foo\\nbar\\r\\nbaz\\rquux\",\n    lineSeparator: \"\\n\"});\n\nvar extendingChars = /[\\u0300-\\u036f\\u0483-\\u0489\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u065e\\u0670\\u06d6-\\u06dc\\u06de-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07eb-\\u07f3\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0900-\\u0902\\u093c\\u0941-\\u0948\\u094d\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09bc\\u09be\\u09c1-\\u09c4\\u09cd\\u09d7\\u09e2\\u09e3\\u0a01\\u0a02\\u0a3c\\u0a41\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a70\\u0a71\\u0a75\\u0a81\\u0a82\\u0abc\\u0ac1-\\u0ac5\\u0ac7\\u0ac8\\u0acd\\u0ae2\\u0ae3\\u0b01\\u0b3c\\u0b3e\\u0b3f\\u0b41-\\u0b44\\u0b4d\\u0b56\\u0b57\\u0b62\\u0b63\\u0b82\\u0bbe\\u0bc0\\u0bcd\\u0bd7\\u0c3e-\\u0c40\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0cbc\\u0cbf\\u0cc2\\u0cc6\\u0ccc\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0d3e\\u0d41-\\u0d44\\u0d4d\\u0d57\\u0d62\\u0d63\\u0dca\\u0dcf\\u0dd2-\\u0dd4\\u0dd6\\u0ddf\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0eb1\\u0eb4-\\u0eb9\\u0ebb\\u0ebc\\u0ec8-\\u0ecd\\u0f18\\u0f19\\u0f35\\u0f37\\u0f39\\u0f71-\\u0f7e\\u0f80-\\u0f84\\u0f86\\u0f87\\u0f90-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102d-\\u1030\\u1032-\\u1037\\u1039\\u103a\\u103d\\u103e\\u1058\\u1059\\u105e-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108d\\u109d\\u135f\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b7-\\u17bd\\u17c6\\u17c9-\\u17d3\\u17dd\\u180b-\\u180d\\u18a9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193b\\u1a17\\u1a18\\u1a56\\u1a58-\\u1a5e\\u1a60\\u1a62\\u1a65-\\u1a6c\\u1a73-\\u1a7c\\u1a7f\\u1b00-\\u1b03\\u1b34\\u1b36-\\u1b3a\\u1b3c\\u1b42\\u1b6b-\\u1b73\\u1b80\\u1b81\\u1ba2-\\u1ba5\\u1ba8\\u1ba9\\u1c2c-\\u1c33\\u1c36\\u1c37\\u1cd0-\\u1cd2\\u1cd4-\\u1ce0\\u1ce2-\\u1ce8\\u1ced\\u1dc0-\\u1de6\\u1dfd-\\u1dff\\u200c\\u200d\\u20d0-\\u20f0\\u2cef-\\u2cf1\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua66f-\\ua672\\ua67c\\ua67d\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua825\\ua826\\ua8c4\\ua8e0-\\ua8f1\\ua926-\\ua92d\\ua947-\\ua951\\ua980-\\ua982\\ua9b3\\ua9b6-\\ua9b9\\ua9bc\\uaa29-\\uaa2e\\uaa31\\uaa32\\uaa35\\uaa36\\uaa43\\uaa4c\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uabe5\\uabe8\\uabed\\udc00-\\udfff\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe26\\uff9e\\uff9f]/\nvar getChar = function (noExtending) { var res; do {res = String.fromCharCode(Math.floor(Math.random()*0x8ac)); } while ([0x90].indexOf(res.charCodeAt(0)) != -1 || (noExtending && extendingChars.test(res))); return res }\nvar getString = function (n) { var res = getChar(true); while (--n > 0) res += getChar(); return res }\n\nfunction makeItWrapAfter(cm, pos) {\n  var firstLineTop = cm.cursorCoords(Pos(0, 0)).top;\n  for(var w = 0, posTop; posTop != firstLineTop; ++w) {\n    cm.setSize(w);\n    posTop = cm.charCoords(pos).top;\n  }\n}\n\nfunction countIf(arr, f) {\n  var result = 0\n  for (var i = 0; i < arr.length; i++) if (f[arr[i]]) result++\n  return result\n}\n\nfunction testMoveBidi(str) {\n  testCM(\"move_bidi_\" + str, function(cm) {\n    if (cm.getOption(\"inputStyle\") != \"textarea\" || !cm.getOption(\"rtlMoveVisually\")) return;\n    cm.getScrollerElement().style.fontFamily = \"monospace\";\n    makeItWrapAfter(cm, Pos(0, 5));\n\n    var steps = str.length - countIf(str.split(\"\"), function(ch) { return extendingChars.test(ch) });\n    var lineBreaks = {}\n    lineBreaks[6 - countIf(str.substr(0, 5).split(\"\"), function(ch) { return extendingChars.test(ch) })] = 'w';\n    if (str.indexOf(\"\\n\") != -1) {\n      lineBreaks[steps - 2] = 'n';\n    }\n\n    // Make sure we are at the visual beginning of the first line\n    cm.execCommand(\"goLineStart\");\n\n    var prevCoords = cm.cursorCoords(), coords;\n    for(var i = 0; i < steps; ++i) {\n      cm.execCommand(\"goCharRight\");\n      coords = cm.cursorCoords();\n      if ((i >= 10 && i <= 12) && !lineBreaks[i] && coords.left < prevCoords.left && coords.top > prevCoords.top) {\n        // The first line wraps twice\n        lineBreaks[i] = 'w';\n      }\n      if (!lineBreaks[i]) {\n        is(coords.left > prevCoords.left, \"In step \" + i + \", cursor didn't move right\");\n        eq(coords.top, prevCoords.top, \"In step \" + i + \", cursor moved out of line\");\n      } else {\n        is(coords.left < prevCoords.left, i);\n        is(coords.top > prevCoords.top, i);\n      }\n      prevCoords = coords;\n    }\n\n    cm.execCommand(\"goCharRight\");\n    coords = cm.cursorCoords();\n    eq(coords.left, prevCoords.left, \"Moving \" + steps + \" steps right didn't reach the end\");\n    eq(coords.top, prevCoords.top, \"Moving \" + steps + \" steps right didn't reach the end\");\n\n    for(i = steps - 1; i >= 0; --i) {\n      cm.execCommand(\"goCharLeft\");\n      coords = cm.cursorCoords();\n      if (!(lineBreaks[i] == 'n' || lineBreaks[i + 1] == 'w')) {\n        is(coords.left < prevCoords.left, \"In step \" + i + \", cursor didn't move left\");\n        eq(coords.top, prevCoords.top, \"In step \" + i + \", cursor is not at the same line anymore\");\n      } else {\n        is(coords.left > prevCoords.left, i);\n        is(coords.top < prevCoords.top, i);\n      }\n      prevCoords = coords;\n    }\n\n    cm.execCommand(\"goCharLeft\");\n    coords = cm.cursorCoords();\n    eq(coords.left, prevCoords.left, \"Moving \" + steps + \" steps left didn't reach the beginning\");\n    eq(coords.top, prevCoords.top, \"Moving \" + steps + \" steps left didn't reach the beginning\");\n  }, {value: str, lineWrapping: true})\n};\n\nfunction testMoveEndBidi(str) {\n  testCM(\"move_end_bidi_\" + str, function(cm) {\n    cm.getScrollerElement().style.fontFamily = \"monospace\";\n    makeItWrapAfter(cm, Pos(0, 5));\n\n    cm.execCommand(\"goLineStart\");\n    var pos = cm.doc.getCursor();\n    cm.execCommand(\"goCharLeft\");\n    eqCursorPos(pos, cm.doc.getCursor());\n\n    cm.execCommand(\"goLineEnd\");\n    pos = cm.doc.getCursor();\n    cm.execCommand(\"goColumnRight\");\n    eqCursorPos(pos, cm.doc.getCursor());\n  }, {value: str, lineWrapping: true})\n};\n\nvar bidiTests = [];\n\n// We don't correctly implement L1 UBA\n// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331501\n// and https://bugs.chromium.org/p/chromium/issues/detail?id=673405\n/*\nbidiTests.push(\"Say ا ب جabj\\nS\");\nbidiTests.push(\"Sayyy ا ا ب ج\");\n*/\n\nif (!phantom) {\n  bidiTests.push(\"Όȝǝڪȉۥ״ۺ׆ɀҩۏ\\nҳ\");\n  bidiTests.push(\"ŌӰтقȤ؁ƥ؅٣ĎȺ١\\nϚ\");\n  bidiTests.push(\"ٻоҤѕѽΩ־؉ïίքǳ\\nٵ\");\n  bidiTests.push(\"؅؁ĆՕƿɁǞϮؠȩóć\\nď\");\n  bidiTests.push(\"RŨďңŪzϢŎƏԖڇڦ\\nӈ\");\n  bidiTests.push(\"ό׊۷٢ԜһОצЉيčǟ\\nѩ\");\n  bidiTests.push(\"ۑÚҳҕڬġڹհяųKV\\nr\");\n  bidiTests.push(\"źڻғúہ4ם1Ƞc1a\\nԁ\");\n  bidiTests.push(\"ҒȨҟփƞ٦ԓȦڰғâƥ\\nڤ\");\n  bidiTests.push(\"ϖسՉȏŧΔԛǆĎӟیڡ\\nέ\");\n  bidiTests.push(\"۹ؼL۵ĺȧКԙػא7״\\nم\");\n  bidiTests.push(\"ن (ي)\\u2009أقواس\"); // thin space to throw off Firefox 51's broken white-space compressing behavior\n}\n\nbidiTests.push(\"քմѧǮßپüŢҍҞўڳ\\nӧ\");\n\n//bidiTests.push(\"Count ١ ٢ ٣ ٤\");\n//bidiTests.push(\"ӣאƦϰ؊ȓېÛوը٬ز\\nϪ\");\n//bidiTests.push(\"ҾճٳџIՖӻ٥׭֐؜ڏ\\nێ\");\n//bidiTests.push(\"ҬÓФ؜ڂį٦Ͽɓڐͳٵ\\nՈ\");\n//bidiTests.push(\"aѴNĳȻهˇ҃ڱӧǻֵ\\na\");\n//bidiTests.push(\" a٧ا٢ ب جa\\nS\");\n\nfor (var i = 0; i < bidiTests.length; ++i) {\n  testMoveBidi(bidiTests[i]);\n  testMoveEndBidi(bidiTests[i]);\n}\n\n/*\nfor (var i = 0; i < 5; ++i) {\n  testMoveBidi(getString(12) + \"\\n\" + getString(1));\n}\n*/\n\nfunction testCoordsWrappedBidi(str) {\n  testCM(\"coords_wrapped_bidi_\" + str, function(cm) {\n    cm.getScrollerElement().style.fontFamily = \"monospace\";\n    makeItWrapAfter(cm, Pos(0, 5));\n\n    // Make sure we are at the visual beginning of the first line\n    var pos = Pos(0, 0), lastPos;\n    cm.doc.setCursor(pos);\n    do {\n      lastPos = pos;\n      cm.execCommand(\"goCharLeft\");\n      pos = cm.doc.getCursor();\n    } while (pos != lastPos)\n\n    var top = cm.charCoords(Pos(0, 0)).top, lastTop;\n    for (var i = 1; i < str.length; ++i) {\n      lastTop = top;\n      top = cm.charCoords(Pos(0, i)).top;\n      is(top >= lastTop);\n    }\n  }, {value: str, lineWrapping: true})\n};\n\ntestCoordsWrappedBidi(\"Count ١ ٢ ٣ ٤\");\n/*\nfor (var i = 0; i < 5; ++i) {\n  testCoordsWrappedBidi(getString(50));\n}\n*/\n\ntestCM(\"rtl_wrapped_selection\", function(cm) {\n  cm.setSelection(Pos(0, 10), Pos(0, 190))\n  is(byClassName(cm.getWrapperElement(), \"CodeMirror-selected\").length >= 3)\n}, {value: new Array(10).join(\" فتي تم تضمينها فتي تم\"), lineWrapping: true})\n\ntestCM(\"bidi_wrapped_selection\", function(cm) {\n  if (phantom) return\n  cm.setSize(cm.charCoords(Pos(0, 10), \"editor\").left)\n  cm.setSelection(Pos(0, 37), Pos(0, 80))\n  var blocks = byClassName(cm.getWrapperElement(), \"CodeMirror-selected\")\n  is(blocks.length >= 2)\n  is(blocks.length <= 3)\n  var boxTop = blocks[0].getBoundingClientRect(), boxBot = blocks[blocks.length - 1].getBoundingClientRect()\n  is(boxTop.left > cm.charCoords(Pos(0, 1)).right)\n  is(boxBot.right < cm.charCoords(Pos(0, cm.getLine(0).length - 2)).left)\n}, {value: \"<p>مفتي11 تم تضمينهفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تا فت10ي ت</p>\", lineWrapping: true})\n\ntestCM(\"delete_wrapped\", function(cm) {\n  makeItWrapAfter(cm, Pos(0, 2));\n  cm.doc.setCursor(Pos(0, 3, \"after\"));\n  cm.deleteH(-1, \"char\");\n  eq(cm.getLine(0), \"1245\");\n}, {value: \"12345\", lineWrapping: true})\n\ntestCM(\"issue_4878\", function(cm) {\n  if (phantom) return\n  cm.setCursor(Pos(1, 12, \"after\"));\n  cm.moveH(-1, \"char\");\n  eqCursorPos(cm.getCursor(), Pos(0, 113, \"before\"));\n}, {value: \"  في تطبيق السمات مرة واحدة https://github.com/codemirror/CodeMirror/issues/4878#issuecomment-330550964على سبيل المثال <code>\\\"foo bar\\\"</code>\\n\" +\n\"  سيتم تعيين\", direction: \"rtl\", lineWrapping: true});\n\nCodeMirror.defineMode(\"lookahead_mode\", function() {\n  // Colors text as atom if the line two lines down has an x in it\n  return {\n    token: function(stream) {\n      stream.skipToEnd()\n      return /x/.test(stream.lookAhead(2)) ? \"atom\" : null\n    }\n  }\n})\n\ntestCM(\"mode_lookahead\", function(cm) {\n  eq(cm.getTokenAt(Pos(0, 1)).type, \"atom\")\n  eq(cm.getTokenAt(Pos(1, 1)).type, \"atom\")\n  eq(cm.getTokenAt(Pos(2, 1)).type, null)\n  cm.replaceRange(\"\\n\", Pos(2, 0))\n  eq(cm.getTokenAt(Pos(0, 1)).type, null)\n  eq(cm.getTokenAt(Pos(1, 1)).type, \"atom\")\n}, {value: \"foo\\na\\nx\\nx\\n\", mode: \"lookahead_mode\"})\n"
  },
  {
    "path": "third_party/CodeMirror/test/vim_test.js",
    "content": "var Pos = CodeMirror.Pos;\nCodeMirror.Vim.suppressErrorLogging = true;\n\nvar code = '' +\n' wOrd1 (#%\\n' +\n' word3] \\n' +\n'aopop pop 0 1 2 3 4\\n' +\n' (a) [b] {c} \\n' +\n'int getchar(void) {\\n' +\n'  static char buf[BUFSIZ];\\n' +\n'  static char *bufp = buf;\\n' +\n'  if (n == 0) {  /* buffer is empty */\\n' +\n'    n = read(0, buf, sizeof buf);\\n' +\n'    bufp = buf;\\n' +\n'  }\\n' +\n'\\n' +\n'  return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\\n' +\n' \\n' +\n'}\\n';\n\nvar lines = (function() {\n  lineText = code.split('\\n');\n  var ret = [];\n  for (var i = 0; i < lineText.length; i++) {\n    ret[i] = {\n      line: i,\n      length: lineText[i].length,\n      lineText: lineText[i],\n      textStart: /^\\s*/.exec(lineText[i])[0].length\n    };\n  }\n  return ret;\n})();\nvar endOfDocument = makeCursor(lines.length - 1,\n    lines[lines.length - 1].length);\nvar wordLine = lines[0];\nvar bigWordLine = lines[1];\nvar charLine = lines[2];\nvar bracesLine = lines[3];\nvar seekBraceLine = lines[4];\n\nvar word1 = {\n  start: new Pos(wordLine.line, 1),\n  end: new Pos(wordLine.line, 5)\n};\nvar word2 = {\n  start: new Pos(wordLine.line, word1.end.ch + 2),\n  end: new Pos(wordLine.line, word1.end.ch + 4)\n};\nvar word3 = {\n  start: new Pos(bigWordLine.line, 1),\n  end: new Pos(bigWordLine.line, 5)\n};\nvar bigWord1 = word1;\nvar bigWord2 = word2;\nvar bigWord3 = {\n  start: new Pos(bigWordLine.line, 1),\n  end: new Pos(bigWordLine.line, 7)\n};\nvar bigWord4 = {\n  start: new Pos(bigWordLine.line, bigWord1.end.ch + 3),\n  end: new Pos(bigWordLine.line, bigWord1.end.ch + 7)\n};\n\nvar oChars = [ new Pos(charLine.line, 1),\n    new Pos(charLine.line, 3),\n    new Pos(charLine.line, 7) ];\nvar pChars = [ new Pos(charLine.line, 2),\n    new Pos(charLine.line, 4),\n    new Pos(charLine.line, 6),\n    new Pos(charLine.line, 8) ];\nvar numChars = [ new Pos(charLine.line, 10),\n    new Pos(charLine.line, 12),\n    new Pos(charLine.line, 14),\n    new Pos(charLine.line, 16),\n    new Pos(charLine.line, 18)];\nvar parens1 = {\n  start: new Pos(bracesLine.line, 1),\n  end: new Pos(bracesLine.line, 3)\n};\nvar squares1 = {\n  start: new Pos(bracesLine.line, 5),\n  end: new Pos(bracesLine.line, 7)\n};\nvar curlys1 = {\n  start: new Pos(bracesLine.line, 9),\n  end: new Pos(bracesLine.line, 11)\n};\nvar seekOutside = {\n  start: new Pos(seekBraceLine.line, 1),\n  end: new Pos(seekBraceLine.line, 16)\n};\nvar seekInside = {\n  start: new Pos(seekBraceLine.line, 14),\n  end: new Pos(seekBraceLine.line, 11)\n};\n\nfunction copyCursor(cur) {\n  return new Pos(cur.line, cur.ch);\n}\n\nfunction forEach(arr, func) {\n  for (var i = 0; i < arr.length; i++) {\n    func(arr[i], i, arr);\n  }\n}\n\nfunction testVim(name, run, opts, expectedFail) {\n  var vimOpts = {\n    lineNumbers: true,\n    vimMode: true,\n    showCursorWhenSelecting: true,\n    value: code\n  };\n  for (var prop in opts) {\n    if (opts.hasOwnProperty(prop)) {\n      vimOpts[prop] = opts[prop];\n    }\n  }\n  return test('vim_' + name, function() {\n    var place = document.getElementById(\"testground\");\n    var cm = CodeMirror(place, vimOpts);\n    var vim = CodeMirror.Vim.maybeInitVimState_(cm);\n\n    function doKeysFn(cm) {\n      return function(args) {\n        if (args instanceof Array) {\n          arguments = args;\n        }\n        for (var i = 0; i < arguments.length; i++) {\n          var result = CodeMirror.Vim.handleKey(cm, arguments[i]);\n          if (!result && cm.state.vim.insertMode) {\n            cm.replaceSelections(fillArray(arguments[i], cm.listSelections().length));\n          }\n        }\n      }\n    }\n    function doInsertModeKeysFn(cm) {\n      return function(args) {\n        if (args instanceof Array) { arguments = args; }\n        function executeHandler(handler) {\n          if (typeof handler == 'string') {\n            CodeMirror.commands[handler](cm);\n          } else {\n            handler(cm);\n          }\n          return true;\n        }\n        for (var i = 0; i < arguments.length; i++) {\n          var key = arguments[i];\n          // Find key in keymap and handle.\n          var handled = CodeMirror.lookupKey(key, cm.getOption('keyMap'), executeHandler, cm);\n          // Record for insert mode.\n          if (handled == \"handled\" && cm.state.vim.insertMode && arguments[i] != 'Esc') {\n            var lastChange = CodeMirror.Vim.getVimGlobalState_().macroModeState.lastInsertModeChanges;\n            if (lastChange && (key.indexOf('Delete') != -1 || key.indexOf('Backspace') != -1)) {\n              lastChange.changes.push(new CodeMirror.Vim.InsertModeKey(key));\n            }\n          }\n        }\n      }\n    }\n    function doExFn(cm) {\n      return function(command) {\n        cm.openDialog = helpers.fakeOpenDialog(command);\n        helpers.doKeys(':');\n      }\n    }\n    function assertCursorAtFn(cm) {\n      return function(line, ch) {\n        var pos;\n        if (ch == null && typeof line.line == 'number') {\n          pos = line;\n        } else {\n          pos = makeCursor(line, ch);\n        }\n        eqCursorPos(cm.getCursor(), pos);\n      }\n    }\n    function fakeOpenDialog(result) {\n      return function(text, callback) {\n        return callback(result);\n      }\n    }\n    function fakeOpenNotification(matcher) {\n      return function(text) {\n        matcher(text);\n      }\n    }\n    var helpers = {\n      doKeys: doKeysFn(cm),\n      // Warning: Only emulates keymap events, not character insertions. Use\n      // replaceRange to simulate character insertions.\n      // Keys are in CodeMirror format, NOT vim format.\n      doInsertModeKeys: doInsertModeKeysFn(cm),\n      doEx: doExFn(cm),\n      assertCursorAt: assertCursorAtFn(cm),\n      fakeOpenDialog: fakeOpenDialog,\n      fakeOpenNotification: fakeOpenNotification,\n      getRegisterController: function() {\n        return CodeMirror.Vim.getRegisterController();\n      }\n    }\n    CodeMirror.Vim.resetVimGlobalState_();\n    var successful = false;\n    var savedOpenNotification = cm.openNotification;\n    var savedOpenDialog = cm.openDialog;\n    try {\n      run(cm, vim, helpers);\n      successful = true;\n    } finally {\n      cm.openNotification = savedOpenNotification;\n      cm.openDialog = savedOpenDialog;\n      if (!successful || verbose) {\n        place.style.visibility = \"visible\";\n      } else {\n        place.removeChild(cm.getWrapperElement());\n      }\n    }\n  }, expectedFail);\n};\ntestVim('qq@q', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'q', 'l', 'l', 'q');\n  helpers.assertCursorAt(0,2);\n  helpers.doKeys('@', 'q');\n  helpers.assertCursorAt(0,4);\n}, { value: '            '});\ntestVim('@@', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'q', 'l', 'l', 'q');\n  helpers.assertCursorAt(0,2);\n  helpers.doKeys('@', 'q');\n  helpers.assertCursorAt(0,4);\n  helpers.doKeys('@', '@');\n  helpers.assertCursorAt(0,6);\n}, { value: '            '});\nvar jumplistScene = ''+\n  'word\\n'+\n  '(word)\\n'+\n  '{word\\n'+\n  'word.\\n'+\n  '\\n'+\n  'word search\\n'+\n  '}word\\n'+\n  'word\\n'+\n  'word\\n';\nfunction testJumplist(name, keys, endPos, startPos, dialog) {\n  endPos = makeCursor(endPos[0], endPos[1]);\n  startPos = makeCursor(startPos[0], startPos[1]);\n  testVim(name, function(cm, vim, helpers) {\n    CodeMirror.Vim.resetVimGlobalState_();\n    if(dialog)cm.openDialog = helpers.fakeOpenDialog('word');\n    cm.setCursor(startPos);\n    helpers.doKeys.apply(null, keys);\n    helpers.assertCursorAt(endPos);\n  }, {value: jumplistScene});\n}\ntestJumplist('jumplist_H', ['H', '<C-o>'], [5,2], [5,2]);\ntestJumplist('jumplist_M', ['M', '<C-o>'], [2,2], [2,2]);\ntestJumplist('jumplist_L', ['L', '<C-o>'], [2,2], [2,2]);\ntestJumplist('jumplist_[[', ['[', '[', '<C-o>'], [5,2], [5,2]);\ntestJumplist('jumplist_]]', [']', ']', '<C-o>'], [2,2], [2,2]);\ntestJumplist('jumplist_G', ['G', '<C-o>'], [5,2], [5,2]);\ntestJumplist('jumplist_gg', ['g', 'g', '<C-o>'], [5,2], [5,2]);\ntestJumplist('jumplist_%', ['%', '<C-o>'], [1,5], [1,5]);\ntestJumplist('jumplist_{', ['{', '<C-o>'], [1,5], [1,5]);\ntestJumplist('jumplist_}', ['}', '<C-o>'], [1,5], [1,5]);\ntestJumplist('jumplist_\\'', ['m', 'a', 'h', '\\'', 'a', 'h', '<C-i>'], [1,0], [1,5]);\ntestJumplist('jumplist_`', ['m', 'a', 'h', '`', 'a', 'h', '<C-i>'], [1,5], [1,5]);\ntestJumplist('jumplist_*_cachedCursor', ['*', '<C-o>'], [1,3], [1,3]);\ntestJumplist('jumplist_#_cachedCursor', ['#', '<C-o>'], [1,3], [1,3]);\ntestJumplist('jumplist_n', ['#', 'n', '<C-o>'], [1,1], [2,3]);\ntestJumplist('jumplist_N', ['#', 'N', '<C-o>'], [1,1], [2,3]);\ntestJumplist('jumplist_repeat_<c-o>', ['*', '*', '*', '3', '<C-o>'], [2,3], [2,3]);\ntestJumplist('jumplist_repeat_<c-i>', ['*', '*', '*', '3', '<C-o>', '2', '<C-i>'], [5,0], [2,3]);\ntestJumplist('jumplist_repeated_motion', ['3', '*', '<C-o>'], [2,3], [2,3]);\ntestJumplist('jumplist_/', ['/', '<C-o>'], [2,3], [2,3], 'dialog');\ntestJumplist('jumplist_?', ['?', '<C-o>'], [2,3], [2,3], 'dialog');\ntestJumplist('jumplist_skip_deleted_mark<c-o>',\n             ['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-o>', '<C-o>'],\n             [0,2], [0,2]);\ntestJumplist('jumplist_skip_deleted_mark<c-i>',\n             ['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-i>', '<C-i>'],\n             [1,0], [0,2]);\n\n/**\n * @param name Name of the test\n * @param keys An array of keys or a string with a single key to simulate.\n * @param endPos The expected end position of the cursor.\n * @param startPos The position the cursor should start at, defaults to 0, 0.\n */\nfunction testMotion(name, keys, endPos, startPos) {\n  testVim(name, function(cm, vim, helpers) {\n    if (!startPos) {\n      startPos = new Pos(0, 0);\n    }\n    cm.setCursor(startPos);\n    helpers.doKeys(keys);\n    helpers.assertCursorAt(endPos);\n  });\n}\n\nfunction makeCursor(line, ch) {\n  return new Pos(line, ch);\n}\n\nfunction offsetCursor(cur, offsetLine, offsetCh) {\n  return new Pos(cur.line + offsetLine, cur.ch + offsetCh);\n}\n\n// Motion tests\ntestMotion('|', '|', makeCursor(0, 0), makeCursor(0,4));\ntestMotion('|_repeat', ['3', '|'], makeCursor(0, 2), makeCursor(0,4));\ntestMotion('h', 'h', makeCursor(0, 0), word1.start);\ntestMotion('h_repeat', ['3', 'h'], offsetCursor(word1.end, 0, -3), word1.end);\ntestMotion('l', 'l', makeCursor(0, 1));\ntestMotion('l_repeat', ['2', 'l'], makeCursor(0, 2));\ntestMotion('j', 'j', offsetCursor(word1.end, 1, 0), word1.end);\ntestMotion('j_repeat', ['2', 'j'], offsetCursor(word1.end, 2, 0), word1.end);\ntestMotion('j_repeat_clip', ['1000', 'j'], endOfDocument);\ntestMotion('k', 'k', offsetCursor(word3.end, -1, 0), word3.end);\ntestMotion('k_repeat', ['2', 'k'], makeCursor(0, 4), makeCursor(2, 4));\ntestMotion('k_repeat_clip', ['1000', 'k'], makeCursor(0, 4), makeCursor(2, 4));\ntestMotion('w', 'w', word1.start);\ntestMotion('w_multiple_newlines_no_space', 'w', makeCursor(12, 2), makeCursor(11, 2));\ntestMotion('w_multiple_newlines_with_space', 'w', makeCursor(14, 0), makeCursor(12, 51));\ntestMotion('w_repeat', ['2', 'w'], word2.start);\ntestMotion('w_wrap', ['w'], word3.start, word2.start);\ntestMotion('w_endOfDocument', 'w', endOfDocument, endOfDocument);\ntestMotion('w_start_to_end', ['1000', 'w'], endOfDocument, makeCursor(0, 0));\ntestMotion('W', 'W', bigWord1.start);\ntestMotion('W_repeat', ['2', 'W'], bigWord3.start, bigWord1.start);\ntestMotion('e', 'e', word1.end);\ntestMotion('e_repeat', ['2', 'e'], word2.end);\ntestMotion('e_wrap', 'e', word3.end, word2.end);\ntestMotion('e_endOfDocument', 'e', endOfDocument, endOfDocument);\ntestMotion('e_start_to_end', ['1000', 'e'], endOfDocument, makeCursor(0, 0));\ntestMotion('b', 'b', word3.start, word3.end);\ntestMotion('b_repeat', ['2', 'b'], word2.start, word3.end);\ntestMotion('b_wrap', 'b', word2.start, word3.start);\ntestMotion('b_startOfDocument', 'b', makeCursor(0, 0), makeCursor(0, 0));\ntestMotion('b_end_to_start', ['1000', 'b'], makeCursor(0, 0), endOfDocument);\ntestMotion('ge', ['g', 'e'], word2.end, word3.end);\ntestMotion('ge_repeat', ['2', 'g', 'e'], word1.end, word3.start);\ntestMotion('ge_wrap', ['g', 'e'], word2.end, word3.start);\ntestMotion('ge_startOfDocument', ['g', 'e'], makeCursor(0, 0),\n    makeCursor(0, 0));\ntestMotion('ge_end_to_start', ['1000', 'g', 'e'], makeCursor(0, 0), endOfDocument);\ntestMotion('gg', ['g', 'g'], makeCursor(lines[0].line, lines[0].textStart),\n    makeCursor(3, 1));\ntestMotion('gg_repeat', ['3', 'g', 'g'],\n    makeCursor(lines[2].line, lines[2].textStart));\ntestMotion('G', 'G',\n    makeCursor(lines[lines.length - 1].line, lines[lines.length - 1].textStart),\n    makeCursor(3, 1));\ntestMotion('G_repeat', ['3', 'G'], makeCursor(lines[2].line,\n    lines[2].textStart));\n// TODO: Make the test code long enough to test Ctrl-F and Ctrl-B.\ntestMotion('0', '0', makeCursor(0, 0), makeCursor(0, 8));\ntestMotion('^', '^', makeCursor(0, lines[0].textStart), makeCursor(0, 8));\ntestMotion('+', '+', makeCursor(1, lines[1].textStart), makeCursor(0, 8));\ntestMotion('-', '-', makeCursor(0, lines[0].textStart), makeCursor(1, 4));\ntestMotion('_', ['6','_'], makeCursor(5, lines[5].textStart), makeCursor(0, 8));\ntestMotion('$', '$', makeCursor(0, lines[0].length - 1), makeCursor(0, 1));\ntestMotion('$_repeat', ['2', '$'], makeCursor(1, lines[1].length - 1),\n    makeCursor(0, 3));\ntestMotion('f', ['f', 'p'], pChars[0], makeCursor(charLine.line, 0));\ntestMotion('f_repeat', ['2', 'f', 'p'], pChars[2], pChars[0]);\ntestMotion('f_num', ['f', '2'], numChars[2], makeCursor(charLine.line, 0));\ntestMotion('t', ['t','p'], offsetCursor(pChars[0], 0, -1),\n    makeCursor(charLine.line, 0));\ntestMotion('t_repeat', ['2', 't', 'p'], offsetCursor(pChars[2], 0, -1),\n    pChars[0]);\ntestMotion('F', ['F', 'p'], pChars[0], pChars[1]);\ntestMotion('F_repeat', ['2', 'F', 'p'], pChars[0], pChars[2]);\ntestMotion('T', ['T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[1]);\ntestMotion('T_repeat', ['2', 'T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[2]);\ntestMotion('%_parens', ['%'], parens1.end, parens1.start);\ntestMotion('%_squares', ['%'], squares1.end, squares1.start);\ntestMotion('%_braces', ['%'], curlys1.end, curlys1.start);\ntestMotion('%_seek_outside', ['%'], seekOutside.end, seekOutside.start);\ntestMotion('%_seek_inside', ['%'], seekInside.end, seekInside.start);\ntestVim('%_seek_skip', function(cm, vim, helpers) {\n  cm.setCursor(0,0);\n  helpers.doKeys(['%']);\n  helpers.assertCursorAt(0,9);\n}, {value:'01234\"(\"()'});\ntestVim('%_skip_string', function(cm, vim, helpers) {\n  cm.setCursor(0,0);\n  helpers.doKeys(['%']);\n  helpers.assertCursorAt(0,4);\n  cm.setCursor(0,2);\n  helpers.doKeys(['%']);\n  helpers.assertCursorAt(0,0);\n}, {value:'(\")\")'});\ntestVim('%_skip_comment', function(cm, vim, helpers) {\n  cm.setCursor(0,0);\n  helpers.doKeys(['%']);\n  helpers.assertCursorAt(0,6);\n  cm.setCursor(0,3);\n  helpers.doKeys(['%']);\n  helpers.assertCursorAt(0,0);\n}, {value:'(/*)*/)'});\n// Make sure that moving down after going to the end of a line always leaves you\n// at the end of a line, but preserves the offset in other cases\ntestVim('Changing lines after Eol operation', function(cm, vim, helpers) {\n  cm.setCursor(0,0);\n  helpers.doKeys(['$']);\n  helpers.doKeys(['j']);\n  // After moving to Eol and then down, we should be at Eol of line 2\n  helpers.assertCursorAt(new Pos(1, lines[1].length - 1));\n  helpers.doKeys(['j']);\n  // After moving down, we should be at Eol of line 3\n  helpers.assertCursorAt(new Pos(2, lines[2].length - 1));\n  helpers.doKeys(['h']);\n  helpers.doKeys(['j']);\n  // After moving back one space and then down, since line 4 is shorter than line 2, we should\n  // be at Eol of line 2 - 1\n  helpers.assertCursorAt(new Pos(3, lines[3].length - 1));\n  helpers.doKeys(['j']);\n  helpers.doKeys(['j']);\n  // After moving down again, since line 3 has enough characters, we should be back to the\n  // same place we were at on line 1\n  helpers.assertCursorAt(new Pos(5, lines[2].length - 2));\n});\n//making sure gj and gk recover from clipping\ntestVim('gj_gk_clipping', function(cm,vim,helpers){\n  cm.setCursor(0, 1);\n  helpers.doKeys('g','j','g','j');\n  helpers.assertCursorAt(2, 1);\n  helpers.doKeys('g','k','g','k');\n  helpers.assertCursorAt(0, 1);\n},{value: 'line 1\\n\\nline 2'});\n//testing a mix of j/k and gj/gk\ntestVim('j_k_and_gj_gk', function(cm,vim,helpers){\n  cm.setSize(120);\n  cm.setCursor(0, 0);\n  //go to the last character on the first line\n  helpers.doKeys('$');\n  //move up/down on the column within the wrapped line\n  //side-effect: cursor is not locked to eol anymore\n  helpers.doKeys('g','k');\n  var cur=cm.getCursor();\n  eq(cur.line,0);\n  is((cur.ch<176),'gk didn\\'t move cursor back (1)');\n  helpers.doKeys('g','j');\n  helpers.assertCursorAt(0, 176);\n  //should move to character 177 on line 2 (j/k preserve character index within line)\n  helpers.doKeys('j');\n  //due to different line wrapping, the cursor can be on a different screen-x now\n  //gj and gk preserve screen-x on movement, much like moveV\n  helpers.doKeys('3','g','k');\n  cur=cm.getCursor();\n  eq(cur.line,1);\n  is((cur.ch<176),'gk didn\\'t move cursor back (2)');\n  helpers.doKeys('g','j','2','g','j');\n  //should return to the same character-index\n  helpers.doKeys('k');\n  helpers.assertCursorAt(0, 176);\n},{ lineWrapping:true, value: 'This line is intentially long to test movement of gj and gk over wrapped lines. I will start on the end of this line, then make a step up and back to set the origin for j and k.\\nThis line is supposed to be even longer than the previous. I will jump here and make another wiggle with gj and gk, before I jump back to the line above. Both wiggles should not change my cursor\\'s target character but both j/k and gj/gk change each other\\'s reference position.'});\ntestVim('gj_gk', function(cm, vim, helpers) {\n  if (phantom) return;\n  cm.setSize(120);\n  // Test top of document edge case.\n  cm.setCursor(0, 4);\n  helpers.doKeys('g', 'j');\n  helpers.doKeys('10', 'g', 'k');\n  helpers.assertCursorAt(0, 4);\n\n  // Test moving down preserves column position.\n  helpers.doKeys('g', 'j');\n  var pos1 = cm.getCursor();\n  var expectedPos2 = new Pos(0, (pos1.ch - 4) * 2 + 4);\n  helpers.doKeys('g', 'j');\n  helpers.assertCursorAt(expectedPos2);\n\n  // Move to the last character\n  cm.setCursor(0, 0);\n  // Move left to reset HSPos\n  helpers.doKeys('h');\n  // Test bottom of document edge case.\n  helpers.doKeys('100', 'g', 'j');\n  var endingPos = cm.getCursor();\n  is(endingPos != 0, 'gj should not be on wrapped line 0');\n  var topLeftCharCoords = cm.charCoords(makeCursor(0, 0));\n  var endingCharCoords = cm.charCoords(endingPos);\n  is(topLeftCharCoords.left == endingCharCoords.left, 'gj should end up on column 0');\n},{ lineNumbers: false, lineWrapping:true, value: 'Thislineisintentionallylongtotestmovementofgjandgkoverwrappedlines.' });\ntestVim('}', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('}');\n  helpers.assertCursorAt(1, 0);\n  cm.setCursor(0, 0);\n  helpers.doKeys('2', '}');\n  helpers.assertCursorAt(4, 0);\n  cm.setCursor(0, 0);\n  helpers.doKeys('6', '}');\n  helpers.assertCursorAt(5, 0);\n}, { value: 'a\\n\\nb\\nc\\n\\nd' });\ntestVim('{', function(cm, vim, helpers) {\n  cm.setCursor(5, 0);\n  helpers.doKeys('{');\n  helpers.assertCursorAt(4, 0);\n  cm.setCursor(5, 0);\n  helpers.doKeys('2', '{');\n  helpers.assertCursorAt(1, 0);\n  cm.setCursor(5, 0);\n  helpers.doKeys('6', '{');\n  helpers.assertCursorAt(0, 0);\n}, { value: 'a\\n\\nb\\nc\\n\\nd' });\ntestVim('(', function(cm, vim, helpers) {\n  cm.setCursor(6, 23);\n  helpers.doKeys('(');\n  helpers.assertCursorAt(6, 14);\n  helpers.doKeys('2', '(');\n  helpers.assertCursorAt(5, 0);\n  helpers.doKeys('(');\n  helpers.assertCursorAt(4, 0);\n  helpers.doKeys('(');\n  helpers.assertCursorAt(3, 0);\n  helpers.doKeys('(');\n  helpers.assertCursorAt(2, 0);\n  helpers.doKeys('(');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('(');\n  helpers.assertCursorAt(0, 0);\n}, { value: 'sentence1.\\n\\n\\nsentence2\\n\\nsentence3. sentence4\\n   sentence5? sentence6!' });\ntestVim(')', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('2', ')');\n  helpers.assertCursorAt(3, 0);\n  helpers.doKeys(')');\n  helpers.assertCursorAt(4, 0);\n  helpers.doKeys(')');\n  helpers.assertCursorAt(5, 0);\n  helpers.doKeys(')');\n  helpers.assertCursorAt(5, 11);\n  helpers.doKeys(')');\n  helpers.assertCursorAt(6, 14);\n  helpers.doKeys(')');\n  helpers.assertCursorAt(6, 23);\n  helpers.doKeys(')');\n  helpers.assertCursorAt(6, 23);\n}, { value: 'sentence1.\\n\\n\\nsentence2\\n\\nsentence3. sentence4\\n   sentence5? sentence6!' });\ntestVim('paragraph_motions', function(cm, vim, helpers) {\n  cm.setCursor(10, 0);\n  helpers.doKeys('{');\n  helpers.assertCursorAt(4, 0);\n  helpers.doKeys('{');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('2', '}');\n  helpers.assertCursorAt(7, 0);\n  helpers.doKeys('2', '}');\n  helpers.assertCursorAt(16, 0);\n\n  cm.setCursor(9, 0);\n  helpers.doKeys('}');\n  helpers.assertCursorAt(14, 0);\n\n  cm.setCursor(6, 0);\n  helpers.doKeys('}');\n  helpers.assertCursorAt(7, 0);\n\n  // ip inside empty space\n  cm.setCursor(10, 0);\n  helpers.doKeys('v', 'i', 'p');\n  eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));\n  eqCursorPos(Pos(12, 0), cm.getCursor('head'));\n  helpers.doKeys('i', 'p');\n  eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));\n  eqCursorPos(Pos(13, 1), cm.getCursor('head'));\n  helpers.doKeys('2', 'i', 'p');\n  eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));\n  eqCursorPos(Pos(16, 1), cm.getCursor('head'));\n\n  // should switch to visualLine mode\n  cm.setCursor(14, 0);\n  helpers.doKeys('<Esc>', 'v', 'i', 'p');\n  helpers.assertCursorAt(14, 0);\n\n  cm.setCursor(14, 0);\n  helpers.doKeys('<Esc>', 'V', 'i', 'p');\n  eqCursorPos(Pos(16, 1), cm.getCursor('head'));\n\n  // ap inside empty space\n  cm.setCursor(10, 0);\n  helpers.doKeys('<Esc>', 'v', 'a', 'p');\n  eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));\n  eqCursorPos(Pos(13, 1), cm.getCursor('head'));\n  helpers.doKeys('a', 'p');\n  eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));\n  eqCursorPos(Pos(16, 1), cm.getCursor('head'));\n\n  cm.setCursor(13, 0);\n  helpers.doKeys('v', 'a', 'p');\n  eqCursorPos(Pos(13, 0), cm.getCursor('anchor'));\n  eqCursorPos(Pos(14, 0), cm.getCursor('head'));\n\n  cm.setCursor(16, 0);\n  helpers.doKeys('v', 'a', 'p');\n  eqCursorPos(Pos(14, 0), cm.getCursor('anchor'));\n  eqCursorPos(Pos(16, 1), cm.getCursor('head'));\n\n  cm.setCursor(0, 0);\n  helpers.doKeys('v', 'a', 'p');\n  eqCursorPos(Pos(0, 0), cm.getCursor('anchor'));\n  eqCursorPos(Pos(4, 0), cm.getCursor('head'));\n\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'i', 'p');\n  var register = helpers.getRegisterController().getRegister();\n  eq('a\\na\\n', register.toString());\n  is(register.linewise);\n  helpers.doKeys('3', 'j', 'p');\n  helpers.doKeys('y', 'i', 'p');\n  is(register.linewise);\n  eq('b\\na\\na\\nc\\n', register.toString());\n}, { value: 'a\\na\\n\\n\\n\\nb\\nc\\n\\n\\n\\n\\n\\n\\nd\\n\\ne\\nf' });\n\n// Operator tests\ntestVim('dl', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 0);\n  cm.setCursor(curStart);\n  helpers.doKeys('d', 'l');\n  eq('word1 ', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(' ', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n}, { value: ' word1 ' });\ntestVim('dl_eol', function(cm, vim, helpers) {\n  cm.setCursor(0, 6);\n  helpers.doKeys('d', 'l');\n  eq(' word1', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(' ', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 5);\n}, { value: ' word1 ' });\ntestVim('dl_repeat', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 0);\n  cm.setCursor(curStart);\n  helpers.doKeys('2', 'd', 'l');\n  eq('ord1 ', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(' w', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n}, { value: ' word1 ' });\ntestVim('dh', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 3);\n  cm.setCursor(curStart);\n  helpers.doKeys('d', 'h');\n  eq(' wrd1 ', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('o', register.toString());\n  is(!register.linewise);\n  eqCursorPos(offsetCursor(curStart, 0 , -1), cm.getCursor());\n}, { value: ' word1 ' });\ntestVim('dj', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 3);\n  cm.setCursor(curStart);\n  helpers.doKeys('d', 'j');\n  eq(' word3', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(' word1\\nword2\\n', register.toString());\n  is(register.linewise);\n  helpers.assertCursorAt(0, 1);\n}, { value: ' word1\\nword2\\n word3' });\ntestVim('dj_end_of_document', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 3);\n  cm.setCursor(curStart);\n  helpers.doKeys('d', 'j');\n  eq('', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(' word1 \\n', register.toString());\n  is(register.linewise);\n  helpers.assertCursorAt(0, 0);\n}, { value: ' word1 ' });\ntestVim('dk', function(cm, vim, helpers) {\n  var curStart = makeCursor(1, 3);\n  cm.setCursor(curStart);\n  helpers.doKeys('d', 'k');\n  eq(' word3', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(' word1\\nword2\\n', register.toString());\n  is(register.linewise);\n  helpers.assertCursorAt(0, 1);\n}, { value: ' word1\\nword2\\n word3' });\ntestVim('dk_start_of_document', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 3);\n  cm.setCursor(curStart);\n  helpers.doKeys('d', 'k');\n  eq('', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(' word1 \\n', register.toString());\n  is(register.linewise);\n  helpers.assertCursorAt(0, 0);\n}, { value: ' word1 ' });\ntestVim('dw_space', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 0);\n  cm.setCursor(curStart);\n  helpers.doKeys('d', 'w');\n  eq('word1 ', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(' ', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n}, { value: ' word1 ' });\ntestVim('dw_word', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 1);\n  cm.setCursor(curStart);\n  helpers.doKeys('d', 'w');\n  eq(' word2', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word1 ', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n}, { value: ' word1 word2' });\ntestVim('dw_unicode_word', function(cm, vim, helpers) {\n  helpers.doKeys('d', 'w');\n  eq(cm.getValue().length, 10);\n  helpers.doKeys('d', 'w');\n  eq(cm.getValue().length, 6);\n  helpers.doKeys('d', 'w');\n  eq(cm.getValue().length, 5);\n  helpers.doKeys('d', 'e');\n  eq(cm.getValue().length, 2);\n}, { value: '  \\u0562\\u0561\\u0580\\u0587\\xbbe\\xb5g  ' });\ntestVim('dw_only_word', function(cm, vim, helpers) {\n  // Test that if there is only 1 word left, dw deletes till the end of the\n  // line.\n  cm.setCursor(0, 1);\n  helpers.doKeys('d', 'w');\n  eq(' ', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word1 ', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 0);\n}, { value: ' word1 ' });\ntestVim('dw_eol', function(cm, vim, helpers) {\n  // Assert that dw does not delete the newline if last word to delete is at end\n  // of line.\n  cm.setCursor(0, 1);\n  helpers.doKeys('d', 'w');\n  eq(' \\nword2', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word1', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 0);\n}, { value: ' word1\\nword2' });\ntestVim('dw_eol_with_multiple_newlines', function(cm, vim, helpers) {\n  // Assert that dw does not delete the newline if last word to delete is at end\n  // of line and it is followed by multiple newlines.\n  cm.setCursor(0, 1);\n  helpers.doKeys('d', 'w');\n  eq(' \\n\\nword2', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word1', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 0);\n}, { value: ' word1\\n\\nword2' });\ntestVim('dw_empty_line_followed_by_whitespace', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'w');\n  eq('  \\nword', cm.getValue());\n}, { value: '\\n  \\nword' });\ntestVim('dw_empty_line_followed_by_word', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'w');\n  eq('word', cm.getValue());\n}, { value: '\\nword' });\ntestVim('dw_empty_line_followed_by_empty_line', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'w');\n  eq('\\n', cm.getValue());\n}, { value: '\\n\\n' });\ntestVim('dw_whitespace_followed_by_whitespace', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'w');\n  eq('\\n   \\n', cm.getValue());\n}, { value: '  \\n   \\n' });\ntestVim('dw_whitespace_followed_by_empty_line', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'w');\n  eq('\\n\\n', cm.getValue());\n}, { value: '  \\n\\n' });\ntestVim('dw_word_whitespace_word', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'w');\n  eq('\\n   \\nword2', cm.getValue());\n}, { value: 'word1\\n   \\nword2'})\ntestVim('dw_end_of_document', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('d', 'w');\n  eq('\\nab', cm.getValue());\n}, { value: '\\nabc' });\ntestVim('dw_repeat', function(cm, vim, helpers) {\n  // Assert that dw does delete newline if it should go to the next line, and\n  // that repeat works properly.\n  cm.setCursor(0, 1);\n  helpers.doKeys('d', '2', 'w');\n  eq(' ', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word1\\nword2', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 0);\n}, { value: ' word1\\nword2' });\ntestVim('de_word_start_and_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'e');\n  eq('\\n\\n', cm.getValue());\n}, { value: 'word\\n\\n' });\ntestVim('de_word_end_and_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  helpers.doKeys('d', 'e');\n  eq('wor', cm.getValue());\n}, { value: 'word\\n\\n\\n' });\ntestVim('de_whitespace_and_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'e');\n  eq('', cm.getValue());\n}, { value: '   \\n\\n\\n' });\ntestVim('de_end_of_document', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('d', 'e');\n  eq('\\nab', cm.getValue());\n}, { value: '\\nabc' });\ntestVim('db_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('d', 'b');\n  eq('\\n\\n', cm.getValue());\n}, { value: '\\n\\n\\n' });\ntestVim('db_word_start_and_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('d', 'b');\n  eq('\\nword', cm.getValue());\n}, { value: '\\n\\nword' });\ntestVim('db_word_end_and_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(2, 3);\n  helpers.doKeys('d', 'b');\n  eq('\\n\\nd', cm.getValue());\n}, { value: '\\n\\nword' });\ntestVim('db_whitespace_and_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('d', 'b');\n  eq('', cm.getValue());\n}, { value: '\\n   \\n' });\ntestVim('db_start_of_document', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'b');\n  eq('abc\\n', cm.getValue());\n}, { value: 'abc\\n' });\ntestVim('dge_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(1, 0);\n  helpers.doKeys('d', 'g', 'e');\n  // Note: In real VIM the result should be '', but it's not quite consistent,\n  // since 2 newlines are deleted. But in the similar case of word\\n\\n, only\n  // 1 newline is deleted. We'll diverge from VIM's behavior since it's much\n  // easier this way.\n  eq('\\n', cm.getValue());\n}, { value: '\\n\\n' });\ntestVim('dge_word_and_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(1, 0);\n  helpers.doKeys('d', 'g', 'e');\n  eq('wor\\n', cm.getValue());\n}, { value: 'word\\n\\n'});\ntestVim('dge_whitespace_and_empty_lines', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('d', 'g', 'e');\n  eq('', cm.getValue());\n}, { value: '\\n  \\n' });\ntestVim('dge_start_of_document', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', 'g', 'e');\n  eq('bc\\n', cm.getValue());\n}, { value: 'abc\\n' });\ntestVim('d_inclusive', function(cm, vim, helpers) {\n  // Assert that when inclusive is set, the character the cursor is on gets\n  // deleted too.\n  var curStart = makeCursor(0, 1);\n  cm.setCursor(curStart);\n  helpers.doKeys('d', 'e');\n  eq('  ', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word1', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n}, { value: ' word1 ' });\ntestVim('d_reverse', function(cm, vim, helpers) {\n  // Test that deleting in reverse works.\n  cm.setCursor(1, 0);\n  helpers.doKeys('d', 'b');\n  eq(' word2 ', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word1\\n', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 1);\n}, { value: ' word1\\nword2 ' });\ntestVim('dd', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  var expectedBuffer = cm.getRange(new Pos(0, 0),\n    new Pos(1, 0));\n  var expectedLineCount = cm.lineCount() - 1;\n  helpers.doKeys('d', 'd');\n  eq(expectedLineCount, cm.lineCount());\n  var register = helpers.getRegisterController().getRegister();\n  eq(expectedBuffer, register.toString());\n  is(register.linewise);\n  helpers.assertCursorAt(0, lines[1].textStart);\n});\ntestVim('dd_prefix_repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  var expectedBuffer = cm.getRange(new Pos(0, 0),\n    new Pos(2, 0));\n  var expectedLineCount = cm.lineCount() - 2;\n  helpers.doKeys('2', 'd', 'd');\n  eq(expectedLineCount, cm.lineCount());\n  var register = helpers.getRegisterController().getRegister();\n  eq(expectedBuffer, register.toString());\n  is(register.linewise);\n  helpers.assertCursorAt(0, lines[2].textStart);\n});\ntestVim('dd_motion_repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  var expectedBuffer = cm.getRange(new Pos(0, 0),\n    new Pos(2, 0));\n  var expectedLineCount = cm.lineCount() - 2;\n  helpers.doKeys('d', '2', 'd');\n  eq(expectedLineCount, cm.lineCount());\n  var register = helpers.getRegisterController().getRegister();\n  eq(expectedBuffer, register.toString());\n  is(register.linewise);\n  helpers.assertCursorAt(0, lines[2].textStart);\n});\ntestVim('dd_multiply_repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  var expectedBuffer = cm.getRange(new Pos(0, 0),\n    new Pos(6, 0));\n  var expectedLineCount = cm.lineCount() - 6;\n  helpers.doKeys('2', 'd', '3', 'd');\n  eq(expectedLineCount, cm.lineCount());\n  var register = helpers.getRegisterController().getRegister();\n  eq(expectedBuffer, register.toString());\n  is(register.linewise);\n  helpers.assertCursorAt(0, lines[6].textStart);\n});\ntestVim('dd_lastline', function(cm, vim, helpers) {\n  cm.setCursor(cm.lineCount(), 0);\n  var expectedLineCount = cm.lineCount() - 1;\n  helpers.doKeys('d', 'd');\n  eq(expectedLineCount, cm.lineCount());\n  helpers.assertCursorAt(cm.lineCount() - 1, 0);\n});\ntestVim('dd_only_line', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  var expectedRegister = cm.getValue() + \"\\n\";\n  helpers.doKeys('d','d');\n  eq(1, cm.lineCount());\n  eq('', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(expectedRegister, register.toString());\n}, { value: \"thisistheonlyline\" });\n// Yank commands should behave the exact same as d commands, expect that nothing\n// gets deleted.\ntestVim('yw_repeat', function(cm, vim, helpers) {\n  // Assert that yw does yank newline if it should go to the next line, and\n  // that repeat works properly.\n  var curStart = makeCursor(0, 1);\n  cm.setCursor(curStart);\n  helpers.doKeys('y', '2', 'w');\n  eq(' word1\\nword2', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word1\\nword2', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n}, { value: ' word1\\nword2' });\ntestVim('yy_multiply_repeat', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 3);\n  cm.setCursor(curStart);\n  var expectedBuffer = cm.getRange(new Pos(0, 0),\n    new Pos(6, 0));\n  var expectedLineCount = cm.lineCount();\n  helpers.doKeys('2', 'y', '3', 'y');\n  eq(expectedLineCount, cm.lineCount());\n  var register = helpers.getRegisterController().getRegister();\n  eq(expectedBuffer, register.toString());\n  is(register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n});\ntestVim('2dd_blank_P', function(cm, vim, helpers) {\n  helpers.doKeys('2', 'd', 'd', 'P');\n  eq('\\na\\n\\n', cm.getValue());\n}, { value: '\\na\\n\\n' });\n// Change commands behave like d commands except that it also enters insert\n// mode. In addition, when the change is linewise, an additional newline is\n// inserted so that insert mode starts on that line.\ntestVim('cw', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('c', '2', 'w');\n  eq(' word3', cm.getValue());\n  helpers.assertCursorAt(0, 0);\n}, { value: 'word1 word2 word3'});\ntestVim('cw_repeat', function(cm, vim, helpers) {\n  // Assert that cw does delete newline if it should go to the next line, and\n  // that repeat works properly.\n  var curStart = makeCursor(0, 1);\n  cm.setCursor(curStart);\n  helpers.doKeys('c', '2', 'w');\n  eq(' ', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word1\\nword2', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n  eq('vim-insert', cm.getOption('keyMap'));\n}, { value: ' word1\\nword2' });\ntestVim('cc_multiply_repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  var expectedBuffer = cm.getRange(new Pos(0, 0),\n    new Pos(6, 0));\n  var expectedLineCount = cm.lineCount() - 5;\n  helpers.doKeys('2', 'c', '3', 'c');\n  eq(expectedLineCount, cm.lineCount());\n  var register = helpers.getRegisterController().getRegister();\n  eq(expectedBuffer, register.toString());\n  is(register.linewise);\n  eq('vim-insert', cm.getOption('keyMap'));\n});\ntestVim('ct', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('c', 't', 'w');\n  eq('  word1  word3', cm.getValue());\n  helpers.doKeys('<Esc>', 'c', '|');\n  eq(' word3', cm.getValue());\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('<Esc>', '2', 'u', 'w', 'h');\n  helpers.doKeys('c', '2', 'g', 'e');\n  eq('  wordword3', cm.getValue());\n}, { value: '  word1  word2  word3'});\ntestVim('cc_should_not_append_to_document', function(cm, vim, helpers) {\n  var expectedLineCount = cm.lineCount();\n  cm.setCursor(cm.lastLine(), 0);\n  helpers.doKeys('c', 'c');\n  eq(expectedLineCount, cm.lineCount());\n});\nfunction fillArray(val, times) {\n  var arr = [];\n  for (var i = 0; i < times; i++) {\n    arr.push(val);\n  }\n  return arr;\n}\ntestVim('c_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 'c');\n  var replacement = fillArray('hello', 3);\n  cm.replaceSelections(replacement);\n  eq('1hello\\n5hello\\nahellofg', cm.getValue());\n  helpers.doKeys('<Esc>');\n  cm.setCursor(2, 3);\n  helpers.doKeys('<C-v>', '2', 'k', 'h', 'C');\n  replacement = fillArray('world', 3);\n  cm.replaceSelections(replacement);\n  eq('1hworld\\n5hworld\\nahworld', cm.getValue());\n}, {value: '1234\\n5678\\nabcdefg'});\ntestVim('c_visual_block_replay', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('<C-v>', '2', 'j', 'l', 'c');\n  var replacement = fillArray('fo', 3);\n  cm.replaceSelections(replacement);\n  eq('1fo4\\n5fo8\\nafodefg', cm.getValue());\n  helpers.doKeys('<Esc>');\n  cm.setCursor(0, 0);\n  helpers.doKeys('.');\n  eq('foo4\\nfoo8\\nfoodefg', cm.getValue());\n}, {value: '1234\\n5678\\nabcdefg'});\n\ntestVim('d_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 'd');\n  eq('1\\n5\\nafg', cm.getValue());\n}, {value: '1234\\n5678\\nabcdefg'});\ntestVim('D_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('<C-v>', '2', 'j', 'l', 'D');\n  eq('1\\n5\\na', cm.getValue());\n}, {value: '1234\\n5678\\nabcdefg'});\n\ntestVim('s_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 's');\n  var replacement = fillArray('hello{', 3);\n  cm.replaceSelections(replacement);\n  eq('1hello{\\n5hello{\\nahello{fg\\n', cm.getValue());\n  helpers.doKeys('<Esc>');\n  cm.setCursor(2, 3);\n  helpers.doKeys('<C-v>', '1', 'k', 'h', 'S');\n  replacement = fillArray('world', 1);\n  cm.replaceSelections(replacement);\n  eq('1hello{\\n  world\\n', cm.getValue());\n}, {value: '1234\\n5678\\nabcdefg\\n'});\n\n// Swapcase commands edit in place and do not modify registers.\ntestVim('g~w_repeat', function(cm, vim, helpers) {\n  // Assert that dw does delete newline if it should go to the next line, and\n  // that repeat works properly.\n  var curStart = makeCursor(0, 1);\n  cm.setCursor(curStart);\n  helpers.doKeys('g', '~', '2', 'w');\n  eq(' WORD1\\nWORD2', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n}, { value: ' word1\\nword2' });\ntestVim('g~g~', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 3);\n  cm.setCursor(curStart);\n  var expectedLineCount = cm.lineCount();\n  var expectedValue = cm.getValue().toUpperCase();\n  helpers.doKeys('2', 'g', '~', '3', 'g', '~');\n  eq(expectedValue, cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n}, { value: ' word1\\nword2\\nword3\\nword4\\nword5\\nword6' });\ntestVim('gu_and_gU', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 7);\n  var value = cm.getValue();\n  cm.setCursor(curStart);\n  helpers.doKeys('2', 'g', 'U', 'w');\n  eq(cm.getValue(), 'wa wb xX WC wd');\n  eqCursorPos(curStart, cm.getCursor());\n  helpers.doKeys('2', 'g', 'u', 'w');\n  eq(cm.getValue(), value);\n\n  helpers.doKeys('2', 'g', 'U', 'B');\n  eq(cm.getValue(), 'wa WB Xx wc wd');\n  eqCursorPos(makeCursor(0, 3), cm.getCursor());\n\n  cm.setCursor(makeCursor(0, 4));\n  helpers.doKeys('g', 'u', 'i', 'w');\n  eq(cm.getValue(), 'wa wb Xx wc wd');\n  eqCursorPos(makeCursor(0, 3), cm.getCursor());\n\n  // TODO: support gUgU guu\n  // eqCursorPos(makeCursor(0, 0), cm.getCursor());\n\n  var register = helpers.getRegisterController().getRegister();\n  eq('', register.toString());\n  is(!register.linewise);\n}, { value: 'wa wb xx wc wd' });\ntestVim('visual_block_~', function(cm, vim, helpers) {\n  cm.setCursor(1, 1);\n  helpers.doKeys('<C-v>', 'l', 'l', 'j', '~');\n  helpers.assertCursorAt(1, 1);\n  eq('hello\\nwoRLd\\naBCDe', cm.getValue());\n  cm.setCursor(2, 0);\n  helpers.doKeys('v', 'l', 'l', '~');\n  helpers.assertCursorAt(2, 0);\n  eq('hello\\nwoRLd\\nAbcDe', cm.getValue());\n},{value: 'hello\\nwOrld\\nabcde' });\ntestVim('._swapCase_visualBlock', function(cm, vim, helpers) {\n  helpers.doKeys('<C-v>', 'j', 'j', 'l', '~');\n  cm.setCursor(0, 3);\n  helpers.doKeys('.');\n  eq('HelLO\\nWorLd\\nAbcdE', cm.getValue());\n},{value: 'hEllo\\nwOrlD\\naBcDe' });\ntestVim('._delete_visualBlock', function(cm, vim, helpers) {\n  helpers.doKeys('<C-v>', 'j', 'x');\n  eq('ive\\ne\\nsome\\nsugar', cm.getValue());\n  helpers.doKeys('.');\n  eq('ve\\n\\nsome\\nsugar', cm.getValue());\n  helpers.doKeys('j', 'j', '.');\n  eq('ve\\n\\nome\\nugar', cm.getValue());\n  helpers.doKeys('u', '<C-r>', '.');\n  eq('ve\\n\\nme\\ngar', cm.getValue());\n},{value: 'give\\nme\\nsome\\nsugar' });\ntestVim('>{motion}', function(cm, vim, helpers) {\n  cm.setCursor(1, 3);\n  var expectedLineCount = cm.lineCount();\n  var expectedValue = '   word1\\n  word2\\nword3 ';\n  helpers.doKeys('>', 'k');\n  eq(expectedValue, cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 3);\n}, { value: ' word1\\nword2\\nword3 ', indentUnit: 2 });\ntestVim('>>', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  var expectedLineCount = cm.lineCount();\n  var expectedValue = '   word1\\n  word2\\nword3 ';\n  helpers.doKeys('2', '>', '>');\n  eq(expectedValue, cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 3);\n}, { value: ' word1\\nword2\\nword3 ', indentUnit: 2 });\ntestVim('<{motion}', function(cm, vim, helpers) {\n  cm.setCursor(1, 3);\n  var expectedLineCount = cm.lineCount();\n  var expectedValue = ' word1\\nword2\\nword3 ';\n  helpers.doKeys('<', 'k');\n  eq(expectedValue, cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 1);\n}, { value: '   word1\\n  word2\\nword3 ', indentUnit: 2 });\ntestVim('<<', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  var expectedLineCount = cm.lineCount();\n  var expectedValue = ' word1\\nword2\\nword3 ';\n  helpers.doKeys('2', '<', '<');\n  eq(expectedValue, cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 1);\n}, { value: '   word1\\n  word2\\nword3 ', indentUnit: 2 });\ntestVim('=', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  helpers.doKeys('<C-v>', 'j', 'j');\n  var expectedValue = 'word1\\nword2\\nword3';\n  helpers.doKeys('=');\n  eq(expectedValue, cm.getValue());\n}, { value: '   word1\\n  word2\\n  word3', indentUnit: 2 });\n\n// Edit tests\nfunction testEdit(name, before, pos, edit, after) {\n  return testVim(name, function(cm, vim, helpers) {\n             var ch = before.search(pos)\n             var line = before.substring(0, ch).split('\\n').length - 1;\n             if (line) {\n               ch = before.substring(0, ch).split('\\n').pop().length;\n             }\n             cm.setCursor(line, ch);\n             helpers.doKeys.apply(this, edit.split(''));\n             eq(after, cm.getValue());\n           }, {value: before});\n}\n\n// These Delete tests effectively cover word-wise Change, Visual & Yank.\n// Tabs are used as differentiated whitespace to catch edge cases.\n// Normal word:\ntestEdit('diw_mid_spc', 'foo \\tbAr\\t baz', /A/, 'diw', 'foo \\t\\t baz');\ntestEdit('daw_mid_spc', 'foo \\tbAr\\t baz', /A/, 'daw', 'foo \\tbaz');\ntestEdit('diw_mid_punct', 'foo \\tbAr.\\t baz', /A/, 'diw', 'foo \\t.\\t baz');\ntestEdit('daw_mid_punct', 'foo \\tbAr.\\t baz', /A/, 'daw', 'foo.\\t baz');\ntestEdit('diw_mid_punct2', 'foo \\t,bAr.\\t baz', /A/, 'diw', 'foo \\t,.\\t baz');\ntestEdit('daw_mid_punct2', 'foo \\t,bAr.\\t baz', /A/, 'daw', 'foo \\t,.\\t baz');\ntestEdit('diw_start_spc', 'bAr \\tbaz', /A/, 'diw', ' \\tbaz');\ntestEdit('daw_start_spc', 'bAr \\tbaz', /A/, 'daw', 'baz');\ntestEdit('diw_start_punct', 'bAr. \\tbaz', /A/, 'diw', '. \\tbaz');\ntestEdit('daw_start_punct', 'bAr. \\tbaz', /A/, 'daw', '. \\tbaz');\ntestEdit('diw_end_spc', 'foo \\tbAr', /A/, 'diw', 'foo \\t');\ntestEdit('daw_end_spc', 'foo \\tbAr', /A/, 'daw', 'foo');\ntestEdit('diw_end_punct', 'foo \\tbAr.', /A/, 'diw', 'foo \\t.');\ntestEdit('daw_end_punct', 'foo \\tbAr.', /A/, 'daw', 'foo.');\n// Big word:\ntestEdit('diW_mid_spc', 'foo \\tbAr\\t baz', /A/, 'diW', 'foo \\t\\t baz');\ntestEdit('daW_mid_spc', 'foo \\tbAr\\t baz', /A/, 'daW', 'foo \\tbaz');\ntestEdit('diW_mid_punct', 'foo \\tbAr.\\t baz', /A/, 'diW', 'foo \\t\\t baz');\ntestEdit('daW_mid_punct', 'foo \\tbAr.\\t baz', /A/, 'daW', 'foo \\tbaz');\ntestEdit('diW_mid_punct2', 'foo \\t,bAr.\\t baz', /A/, 'diW', 'foo \\t\\t baz');\ntestEdit('daW_mid_punct2', 'foo \\t,bAr.\\t baz', /A/, 'daW', 'foo \\tbaz');\ntestEdit('diW_start_spc', 'bAr\\t baz', /A/, 'diW', '\\t baz');\ntestEdit('daW_start_spc', 'bAr\\t baz', /A/, 'daW', 'baz');\ntestEdit('diW_start_punct', 'bAr.\\t baz', /A/, 'diW', '\\t baz');\ntestEdit('daW_start_punct', 'bAr.\\t baz', /A/, 'daW', 'baz');\ntestEdit('diW_end_spc', 'foo \\tbAr', /A/, 'diW', 'foo \\t');\ntestEdit('daW_end_spc', 'foo \\tbAr', /A/, 'daW', 'foo');\ntestEdit('diW_end_punct', 'foo \\tbAr.', /A/, 'diW', 'foo \\t');\ntestEdit('daW_end_punct', 'foo \\tbAr.', /A/, 'daW', 'foo');\n// Deleting text objects\n//    Open and close on same line\ntestEdit('di(_open_spc', 'foo (bAr) baz', /\\(/, 'di(', 'foo () baz');\ntestEdit('di)_open_spc', 'foo (bAr) baz', /\\(/, 'di)', 'foo () baz');\ntestEdit('dib_open_spc', 'foo (bAr) baz', /\\(/, 'dib', 'foo () baz');\ntestEdit('da(_open_spc', 'foo (bAr) baz', /\\(/, 'da(', 'foo  baz');\ntestEdit('da)_open_spc', 'foo (bAr) baz', /\\(/, 'da)', 'foo  baz');\n\ntestEdit('di(_middle_spc', 'foo (bAr) baz', /A/, 'di(', 'foo () baz');\ntestEdit('di)_middle_spc', 'foo (bAr) baz', /A/, 'di)', 'foo () baz');\ntestEdit('da(_middle_spc', 'foo (bAr) baz', /A/, 'da(', 'foo  baz');\ntestEdit('da)_middle_spc', 'foo (bAr) baz', /A/, 'da)', 'foo  baz');\n\ntestEdit('di(_close_spc', 'foo (bAr) baz', /\\)/, 'di(', 'foo () baz');\ntestEdit('di)_close_spc', 'foo (bAr) baz', /\\)/, 'di)', 'foo () baz');\ntestEdit('da(_close_spc', 'foo (bAr) baz', /\\)/, 'da(', 'foo  baz');\ntestEdit('da)_close_spc', 'foo (bAr) baz', /\\)/, 'da)', 'foo  baz');\n\n//  delete around and inner b.\ntestEdit('dab_on_(_should_delete_around_()block', 'o( in(abc) )', /\\(a/, 'dab', 'o( in )');\n\n//  delete around and inner B.\ntestEdit('daB_on_{_should_delete_around_{}block', 'o{ in{abc} }', /{a/, 'daB', 'o{ in }');\ntestEdit('diB_on_{_should_delete_inner_{}block', 'o{ in{abc} }', /{a/, 'diB', 'o{ in{} }');\n\ntestEdit('da{_on_{_should_delete_inner_block', 'o{ in{abc} }', /{a/, 'da{', 'o{ in }');\ntestEdit('di[_on_(_should_not_delete', 'foo (bAr) baz', /\\(/, 'di[', 'foo (bAr) baz');\ntestEdit('di[_on_)_should_not_delete', 'foo (bAr) baz', /\\)/, 'di[', 'foo (bAr) baz');\ntestEdit('da[_on_(_should_not_delete', 'foo (bAr) baz', /\\(/, 'da[', 'foo (bAr) baz');\ntestEdit('da[_on_)_should_not_delete', 'foo (bAr) baz', /\\)/, 'da[', 'foo (bAr) baz');\ntestMotion('di(_outside_should_stay', ['d', 'i', '('], new Pos(0, 0), new Pos(0, 0));\n\n//  Open and close on different lines, equally indented\ntestEdit('di{_middle_spc', 'a{\\n\\tbar\\n}b', /r/, 'di{', 'a{}b');\ntestEdit('di}_middle_spc', 'a{\\n\\tbar\\n}b', /r/, 'di}', 'a{}b');\ntestEdit('da{_middle_spc', 'a{\\n\\tbar\\n}b', /r/, 'da{', 'ab');\ntestEdit('da}_middle_spc', 'a{\\n\\tbar\\n}b', /r/, 'da}', 'ab');\ntestEdit('daB_middle_spc', 'a{\\n\\tbar\\n}b', /r/, 'daB', 'ab');\n\n// open and close on diff lines, open indented less than close\ntestEdit('di{_middle_spc', 'a{\\n\\tbar\\n\\t}b', /r/, 'di{', 'a{}b');\ntestEdit('di}_middle_spc', 'a{\\n\\tbar\\n\\t}b', /r/, 'di}', 'a{}b');\ntestEdit('da{_middle_spc', 'a{\\n\\tbar\\n\\t}b', /r/, 'da{', 'ab');\ntestEdit('da}_middle_spc', 'a{\\n\\tbar\\n\\t}b', /r/, 'da}', 'ab');\n\n// open and close on diff lines, open indented more than close\ntestEdit('di[_middle_spc', 'a\\t[\\n\\tbar\\n]b', /r/, 'di[', 'a\\t[]b');\ntestEdit('di]_middle_spc', 'a\\t[\\n\\tbar\\n]b', /r/, 'di]', 'a\\t[]b');\ntestEdit('da[_middle_spc', 'a\\t[\\n\\tbar\\n]b', /r/, 'da[', 'a\\tb');\ntestEdit('da]_middle_spc', 'a\\t[\\n\\tbar\\n]b', /r/, 'da]', 'a\\tb');\n\n// open and close on diff lines, open indented more than close\ntestEdit('di<_middle_spc', 'a\\t<\\n\\tbar\\n>b', /r/, 'di<', 'a\\t<>b');\ntestEdit('di>_middle_spc', 'a\\t<\\n\\tbar\\n>b', /r/, 'di>', 'a\\t<>b');\ntestEdit('da<_middle_spc', 'a\\t<\\n\\tbar\\n>b', /r/, 'da<', 'a\\tb');\ntestEdit('da>_middle_spc', 'a\\t<\\n\\tbar\\n>b', /r/, 'da>', 'a\\tb');\n\nfunction testSelection(name, before, pos, keys, sel) {\n  return testVim(name, function(cm, vim, helpers) {\n             var ch = before.search(pos)\n             var line = before.substring(0, ch).split('\\n').length - 1;\n             if (line) {\n               ch = before.substring(0, ch).split('\\n').pop().length;\n             }\n             cm.setCursor(line, ch);\n             helpers.doKeys.apply(this, keys.split(''));\n             eq(sel, cm.getSelection());\n           }, {value: before});\n}\ntestSelection('viw_middle_spc', 'foo \\tbAr\\t baz', /A/, 'viw', 'bAr');\ntestSelection('vaw_middle_spc', 'foo \\tbAr\\t baz', /A/, 'vaw', 'bAr\\t ');\ntestSelection('viw_middle_punct', 'foo \\tbAr,\\t baz', /A/, 'viw', 'bAr');\ntestSelection('vaW_middle_punct', 'foo \\tbAr,\\t baz', /A/, 'vaW', 'bAr,\\t ');\ntestSelection('viw_start_spc', 'foo \\tbAr\\t baz', /b/, 'viw', 'bAr');\ntestSelection('viw_end_spc', 'foo \\tbAr\\t baz', /r/, 'viw', 'bAr');\ntestSelection('viw_eol', 'foo \\tbAr', /r/, 'viw', 'bAr');\ntestSelection('vi{_middle_spc', 'a{\\n\\tbar\\n\\t}b', /r/, 'vi{', '\\n\\tbar\\n\\t');\ntestSelection('va{_middle_spc', 'a{\\n\\tbar\\n\\t}b', /r/, 'va{', '{\\n\\tbar\\n\\t}');\n\ntestVim('mouse_select', function(cm, vim, helpers) {\n  cm.setSelection(Pos(0, 2), Pos(0, 4), {origin: '*mouse'});\n  is(cm.state.vim.visualMode);\n  is(!cm.state.vim.visualLine);\n  is(!cm.state.vim.visualBlock);\n  helpers.doKeys('<Esc>');\n  is(!cm.somethingSelected());\n  helpers.doKeys('g', 'v');\n  eq('cd', cm.getSelection());\n}, {value: 'abcdef'});\n\n// Operator-motion tests\ntestVim('D', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  helpers.doKeys('D');\n  eq(' wo\\nword2\\n word3', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('rd1', register.toString());\n  is(!register.linewise);\n  helpers.assertCursorAt(0, 2);\n}, { value: ' word1\\nword2\\n word3' });\ntestVim('C', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 3);\n  cm.setCursor(curStart);\n  helpers.doKeys('C');\n  eq(' wo\\nword2\\n word3', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('rd1', register.toString());\n  is(!register.linewise);\n  eqCursorPos(curStart, cm.getCursor());\n  eq('vim-insert', cm.getOption('keyMap'));\n}, { value: ' word1\\nword2\\n word3' });\ntestVim('Y', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 3);\n  cm.setCursor(curStart);\n  helpers.doKeys('Y');\n  eq(' word1\\nword2\\n word3', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq(' word1\\n', register.toString());\n  is(register.linewise);\n  helpers.assertCursorAt(0, 3);\n}, { value: ' word1\\nword2\\n word3' });\ntestVim('~', function(cm, vim, helpers) {\n  helpers.doKeys('3', '~');\n  eq('ABCdefg', cm.getValue());\n  helpers.assertCursorAt(0, 3);\n}, { value: 'abcdefg' });\n\n// Action tests\ntestVim('ctrl-a', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-a>');\n  eq('-9', cm.getValue());\n  helpers.assertCursorAt(0, 1);\n  helpers.doKeys('2','<C-a>');\n  eq('-7', cm.getValue());\n}, {value: '-10'});\ntestVim('ctrl-x', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-x>');\n  eq('-1', cm.getValue());\n  helpers.assertCursorAt(0, 1);\n  helpers.doKeys('2','<C-x>');\n  eq('-3', cm.getValue());\n}, {value: '0'});\ntestVim('<C-x>/<C-a> search forward', function(cm, vim, helpers) {\n  forEach(['<C-x>', '<C-a>'], function(key) {\n    cm.setCursor(0, 0);\n    helpers.doKeys(key);\n    helpers.assertCursorAt(0, 5);\n    helpers.doKeys('l');\n    helpers.doKeys(key);\n    helpers.assertCursorAt(0, 10);\n    cm.setCursor(0, 11);\n    helpers.doKeys(key);\n    helpers.assertCursorAt(0, 11);\n  });\n}, {value: '__jmp1 jmp2 jmp'});\ntestVim('insert_ctrl_w', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 10);\n  cm.setCursor(curStart);\n  helpers.doKeys('a');\n  helpers.doKeys('<C-w>');\n  eq('word1/', cm.getValue());\n  var register = helpers.getRegisterController().getRegister();\n  eq('word2', register.toString());\n  is(!register.linewise);\n  var curEnd = makeCursor(0, 6);\n  eqCursorPos(curEnd, cm.getCursor());\n  eq('vim-insert', cm.getOption('keyMap'));\n}, { value: 'word1/word2' });\ntestVim('normal_ctrl_w', function(cm, vim, helpers) {\n  var curStart = makeCursor(0, 3);\n  cm.setCursor(curStart);\n  helpers.doKeys('<C-w>');\n  eq('word', cm.getValue());\n  var curEnd = makeCursor(0, 3);\n  helpers.assertCursorAt(0,3);\n  eqCursorPos(curEnd, cm.getCursor());\n  eq('vim', cm.getOption('keyMap'));\n}, {value: 'word'});\ntestVim('a', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('a');\n  helpers.assertCursorAt(0, 2);\n  eq('vim-insert', cm.getOption('keyMap'));\n});\ntestVim('a_eol', function(cm, vim, helpers) {\n  cm.setCursor(0, lines[0].length - 1);\n  helpers.doKeys('a');\n  helpers.assertCursorAt(0, lines[0].length);\n  eq('vim-insert', cm.getOption('keyMap'));\n});\ntestVim('A_endOfSelectedArea', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('v', 'j', 'l');\n  helpers.doKeys('A');\n  helpers.assertCursorAt(1, 2);\n  eq('vim-insert', cm.getOption('keyMap'));\n}, {value: 'foo\\nbar'});\ntestVim('i', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('i');\n  helpers.assertCursorAt(0, 1);\n  eq('vim-insert', cm.getOption('keyMap'));\n});\ntestVim('i_repeat', function(cm, vim, helpers) {\n  helpers.doKeys('3', 'i');\n  cm.replaceRange('test', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  eq('testtesttest', cm.getValue());\n  helpers.assertCursorAt(0, 11);\n}, { value: '' });\ntestVim('i_repeat_delete', function(cm, vim, helpers) {\n  cm.setCursor(0, 4);\n  helpers.doKeys('2', 'i');\n  cm.replaceRange('z', cm.getCursor());\n  helpers.doInsertModeKeys('Backspace', 'Backspace');\n  helpers.doKeys('<Esc>');\n  eq('abe', cm.getValue());\n  helpers.assertCursorAt(0, 1);\n}, { value: 'abcde' });\ntestVim('insert', function(cm, vim, helpers) {\n  helpers.doKeys('i');\n  eq('vim-insert', cm.getOption('keyMap'));\n  eq(false, cm.state.overwrite);\n  helpers.doKeys('<Ins>');\n  eq('vim-replace', cm.getOption('keyMap'));\n  eq(true, cm.state.overwrite);\n  helpers.doKeys('<Ins>');\n  eq('vim-insert', cm.getOption('keyMap'));\n  eq(false, cm.state.overwrite);\n});\ntestVim('i_backspace', function(cm, vim, helpers) {\n  cm.setCursor(0, 10);\n  helpers.doKeys('i');\n  helpers.doInsertModeKeys('Backspace');\n  helpers.assertCursorAt(0, 9);\n  eq('012345678', cm.getValue());\n}, { value: '0123456789'});\ntestVim('i_overwrite_backspace', function(cm, vim, helpers) {\n  cm.setCursor(0, 10);\n  helpers.doKeys('i');\n  helpers.doKeys('<Ins>');\n  helpers.doInsertModeKeys('Backspace');\n  helpers.assertCursorAt(Pos(0, 9, \"after\"));\n  eq('0123456789', cm.getValue());\n}, { value: '0123456789'});\ntestVim('A', function(cm, vim, helpers) {\n  helpers.doKeys('A');\n  helpers.assertCursorAt(0, lines[0].length);\n  eq('vim-insert', cm.getOption('keyMap'));\n});\ntestVim('A_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'A');\n  var replacement = new Array(cm.listSelections().length+1).join('hello ').split(' ');\n  replacement.pop();\n  cm.replaceSelections(replacement);\n  eq('testhello\\nmehello\\npleahellose', cm.getValue());\n  helpers.doKeys('<Esc>');\n  cm.setCursor(0, 0);\n  helpers.doKeys('.');\n  // TODO this doesn't work yet\n  // eq('teshellothello\\nme hello hello\\nplehelloahellose', cm.getValue());\n}, {value: 'test\\nme\\nplease'});\ntestVim('I', function(cm, vim, helpers) {\n  cm.setCursor(0, 4);\n  helpers.doKeys('I');\n  helpers.assertCursorAt(0, lines[0].textStart);\n  eq('vim-insert', cm.getOption('keyMap'));\n});\ntestVim('I_repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('3', 'I');\n  cm.replaceRange('test', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  eq('testtesttestblah', cm.getValue());\n  helpers.assertCursorAt(0, 11);\n}, { value: 'blah' });\ntestVim('I_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'I');\n  var replacement = new Array(cm.listSelections().length+1).join('hello ').split(' ');\n  replacement.pop();\n  cm.replaceSelections(replacement);\n  eq('hellotest\\nhellome\\nhelloplease', cm.getValue());\n}, {value: 'test\\nme\\nplease'});\ntestVim('o', function(cm, vim, helpers) {\n  cm.setCursor(0, 4);\n  helpers.doKeys('o');\n  eq('word1\\n\\nword2', cm.getValue());\n  helpers.assertCursorAt(1, 0);\n  eq('vim-insert', cm.getOption('keyMap'));\n}, { value: 'word1\\nword2' });\ntestVim('o_repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('3', 'o');\n  cm.replaceRange('test', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  eq('\\ntest\\ntest\\ntest', cm.getValue());\n  helpers.assertCursorAt(3, 3);\n}, { value: '' });\ntestVim('O', function(cm, vim, helpers) {\n  cm.setCursor(0, 4);\n  helpers.doKeys('O');\n  eq('\\nword1\\nword2', cm.getValue());\n  helpers.assertCursorAt(0, 0);\n  eq('vim-insert', cm.getOption('keyMap'));\n}, { value: 'word1\\nword2' });\ntestVim('J', function(cm, vim, helpers) {\n  cm.setCursor(0, 4);\n  helpers.doKeys('J');\n  var expectedValue = 'word1  word2\\nword3\\n word4';\n  eq(expectedValue, cm.getValue());\n  helpers.assertCursorAt(0, expectedValue.indexOf('word2') - 1);\n}, { value: 'word1 \\n    word2\\nword3\\n word4' });\ntestVim('J_repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 4);\n  helpers.doKeys('3', 'J');\n  var expectedValue = 'word1  word2 word3\\n word4';\n  eq(expectedValue, cm.getValue());\n  helpers.assertCursorAt(0, expectedValue.indexOf('word3') - 1);\n}, { value: 'word1 \\n    word2\\nword3\\n word4' });\ntestVim('p', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.getRegisterController().pushText('\"', 'yank', 'abc\\ndef', false);\n  helpers.doKeys('p');\n  eq('__abc\\ndef_', cm.getValue());\n  helpers.assertCursorAt(1, 2);\n}, { value: '___' });\ntestVim('p_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.getRegisterController().getRegister('a').setText('abc\\ndef', false);\n  helpers.doKeys('\"', 'a', 'p');\n  eq('__abc\\ndef_', cm.getValue());\n  helpers.assertCursorAt(1, 2);\n}, { value: '___' });\ntestVim('p_wrong_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.getRegisterController().getRegister('a').setText('abc\\ndef', false);\n  helpers.doKeys('p');\n  eq('___', cm.getValue());\n  helpers.assertCursorAt(0, 1);\n}, { value: '___' });\ntestVim('p_line', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.getRegisterController().pushText('\"', 'yank', '  a\\nd\\n', true);\n  helpers.doKeys('2', 'p');\n  eq('___\\n  a\\nd\\n  a\\nd', cm.getValue());\n  helpers.assertCursorAt(1, 2);\n}, { value: '___' });\ntestVim('p_lastline', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.getRegisterController().pushText('\"', 'yank', '  a\\nd', true);\n  helpers.doKeys('2', 'p');\n  eq('___\\n  a\\nd\\n  a\\nd', cm.getValue());\n  helpers.assertCursorAt(1, 2);\n}, { value: '___' });\ntestVim(']p_first_indent_is_smaller', function(cm, vim, helpers) {\n  helpers.getRegisterController().pushText('\"', 'yank', '  abc\\n    def\\n', true);\n  helpers.doKeys(']', 'p');\n  eq('  ___\\n  abc\\n    def', cm.getValue());\n}, { value: '  ___' });\ntestVim(']p_first_indent_is_larger', function(cm, vim, helpers) {\n  helpers.getRegisterController().pushText('\"', 'yank', '    abc\\n  def\\n', true);\n  helpers.doKeys(']', 'p');\n  eq('  ___\\n  abc\\ndef', cm.getValue());\n}, { value: '  ___' });\ntestVim(']p_with_tab_indents', function(cm, vim, helpers) {\n  helpers.getRegisterController().pushText('\"', 'yank', '\\t\\tabc\\n\\t\\t\\tdef\\n', true);\n  helpers.doKeys(']', 'p');\n  eq('\\t___\\n\\tabc\\n\\t\\tdef', cm.getValue());\n}, { value: '\\t___', indentWithTabs: true});\ntestVim(']p_with_spaces_translated_to_tabs', function(cm, vim, helpers) {\n  helpers.getRegisterController().pushText('\"', 'yank', '  abc\\n    def\\n', true);\n  helpers.doKeys(']', 'p');\n  eq('\\t___\\n\\tabc\\n\\t\\tdef', cm.getValue());\n}, { value: '\\t___', indentWithTabs: true, tabSize: 2 });\ntestVim('[p', function(cm, vim, helpers) {\n  helpers.getRegisterController().pushText('\"', 'yank', '  abc\\n    def\\n', true);\n  helpers.doKeys('[', 'p');\n  eq('  abc\\n    def\\n  ___', cm.getValue());\n}, { value: '  ___' });\ntestVim('P', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.getRegisterController().pushText('\"', 'yank', 'abc\\ndef', false);\n  helpers.doKeys('P');\n  eq('_abc\\ndef__', cm.getValue());\n  helpers.assertCursorAt(1, 3);\n}, { value: '___' });\ntestVim('P_line', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.getRegisterController().pushText('\"', 'yank', '  a\\nd\\n', true);\n  helpers.doKeys('2', 'P');\n  eq('  a\\nd\\n  a\\nd\\n___', cm.getValue());\n  helpers.assertCursorAt(0, 2);\n}, { value: '___' });\ntestVim('r', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('3', 'r', 'u');\n  eq('wuuuet\\nanother', cm.getValue(),'3r failed');\n  helpers.assertCursorAt(0, 3);\n  cm.setCursor(0, 4);\n  helpers.doKeys('v', 'j', 'h', 'r', '<Space>');\n  eq('wuuu  \\n    her', cm.getValue(),'Replacing selection by space-characters failed');\n  cm.setValue(\"ox\");\n  helpers.doKeys('r', '<C-c>');\n  eq('ox', cm.getValue());\n  helpers.doKeys('r', '<Del>');\n  eq('ox', cm.getValue());\n  helpers.doKeys('r', '<CR>');\n  eq('\\nx', cm.getValue());\n}, { value: 'wordet\\nanother' });\ntestVim('r_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(2, 3);\n  helpers.doKeys('<C-v>', 'k', 'k', 'h', 'h', 'r', 'l');\n  eq('1lll\\n5lll\\nalllefg', cm.getValue());\n  helpers.doKeys('<C-v>', 'l', 'j', 'r', '<Space>');\n  eq('1  l\\n5  l\\nalllefg', cm.getValue());\n  cm.setCursor(2, 0);\n  helpers.doKeys('o');\n  helpers.doKeys('<Esc>');\n  cm.replaceRange('\\t\\t', cm.getCursor());\n  helpers.doKeys('<C-v>', 'h', 'h', 'r', 'r');\n  eq('1  l\\n5  l\\nalllefg\\nrrrrrrrr', cm.getValue());\n}, {value: '1234\\n5678\\nabcdefg'});\ntestVim('R', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('R');\n  helpers.assertCursorAt(0, 1);\n  eq('vim-replace', cm.getOption('keyMap'));\n  is(cm.state.overwrite, 'Setting overwrite state failed');\n});\ntestVim('mark', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 't');\n  cm.setCursor(0, 0);\n  helpers.doKeys('`', 't');\n  helpers.assertCursorAt(2, 2);\n  cm.setCursor(2, 0);\n  cm.replaceRange('   h', cm.getCursor());\n  cm.setCursor(0, 0);\n  helpers.doKeys('\\'', 't');\n  helpers.assertCursorAt(2, 3);\n});\ntestVim('mark\\'', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  cm.setCursor(0, 0);\n  helpers.doKeys('`', '\\'');\n  helpers.assertCursorAt(2, 2);\n  cm.setCursor(2, 0);\n  cm.replaceRange('   h', cm.getCursor());\n  cm.setCursor(0, 0);\n  helpers.doKeys('\\'', '\\'');\n  helpers.assertCursorAt(2, 3);\n});\ntestVim('mark.', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('O', 'testing', '<Esc>');\n  cm.setCursor(3, 3);\n  helpers.doKeys('\\'', '.');\n  helpers.assertCursorAt(0, 0);\n  cm.setCursor(4, 4);\n  helpers.doKeys('`', '.');\n  helpers.assertCursorAt(0, 6);\n});\ntestVim('jumpToMark_next', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 't');\n  cm.setCursor(0, 0);\n  helpers.doKeys(']', '`');\n  helpers.assertCursorAt(2, 2);\n  cm.setCursor(0, 0);\n  helpers.doKeys(']', '\\'');\n  helpers.assertCursorAt(2, 0);\n});\ntestVim('jumpToMark_next_repeat', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(3, 2);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(4, 2);\n  helpers.doKeys('m', 'c');\n  cm.setCursor(0, 0);\n  helpers.doKeys('2', ']', '`');\n  helpers.assertCursorAt(3, 2);\n  cm.setCursor(0, 0);\n  helpers.doKeys('2', ']', '\\'');\n  helpers.assertCursorAt(3, 1);\n});\ntestVim('jumpToMark_next_sameline', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(2, 4);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(2, 2);\n  helpers.doKeys(']', '`');\n  helpers.assertCursorAt(2, 4);\n});\ntestVim('jumpToMark_next_onlyprev', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(4, 0);\n  helpers.doKeys(']', '`');\n  helpers.assertCursorAt(4, 0);\n});\ntestVim('jumpToMark_next_nomark', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys(']', '`');\n  helpers.assertCursorAt(2, 2);\n  helpers.doKeys(']', '\\'');\n  helpers.assertCursorAt(2, 0);\n});\ntestVim('jumpToMark_next_linewise_over', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(3, 4);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(2, 1);\n  helpers.doKeys(']', '\\'');\n  helpers.assertCursorAt(3, 1);\n});\ntestVim('jumpToMark_next_action', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 't');\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', ']', '`');\n  helpers.assertCursorAt(0, 0);\n  var actual = cm.getLine(0);\n  var expected = 'pop pop 0 1 2 3 4';\n  eq(actual, expected, \"Deleting while jumping to the next mark failed.\");\n});\ntestVim('jumpToMark_next_line_action', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 't');\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', ']', '\\'');\n  helpers.assertCursorAt(0, 1);\n  var actual = cm.getLine(0);\n  var expected = ' (a) [b] {c} '\n  eq(actual, expected, \"Deleting while jumping to the next mark line failed.\");\n});\ntestVim('jumpToMark_prev', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 't');\n  cm.setCursor(4, 0);\n  helpers.doKeys('[', '`');\n  helpers.assertCursorAt(2, 2);\n  cm.setCursor(4, 0);\n  helpers.doKeys('[', '\\'');\n  helpers.assertCursorAt(2, 0);\n});\ntestVim('jumpToMark_prev_repeat', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(3, 2);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(4, 2);\n  helpers.doKeys('m', 'c');\n  cm.setCursor(5, 0);\n  helpers.doKeys('2', '[', '`');\n  helpers.assertCursorAt(3, 2);\n  cm.setCursor(5, 0);\n  helpers.doKeys('2', '[', '\\'');\n  helpers.assertCursorAt(3, 1);\n});\ntestVim('jumpToMark_prev_sameline', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(2, 4);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(2, 2);\n  helpers.doKeys('[', '`');\n  helpers.assertCursorAt(2, 0);\n});\ntestVim('jumpToMark_prev_onlynext', function(cm, vim, helpers) {\n  cm.setCursor(4, 4);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(2, 0);\n  helpers.doKeys('[', '`');\n  helpers.assertCursorAt(2, 0);\n});\ntestVim('jumpToMark_prev_nomark', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('[', '`');\n  helpers.assertCursorAt(2, 2);\n  helpers.doKeys('[', '\\'');\n  helpers.assertCursorAt(2, 0);\n});\ntestVim('jumpToMark_prev_linewise_over', function(cm, vim, helpers) {\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(3, 4);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(3, 6);\n  helpers.doKeys('[', '\\'');\n  helpers.assertCursorAt(2, 0);\n});\ntestVim('delmark_single', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('m', 't');\n  helpers.doEx('delmarks t');\n  cm.setCursor(0, 0);\n  helpers.doKeys('`', 't');\n  helpers.assertCursorAt(0, 0);\n});\ntestVim('delmark_range', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(3, 2);\n  helpers.doKeys('m', 'c');\n  cm.setCursor(4, 2);\n  helpers.doKeys('m', 'd');\n  cm.setCursor(5, 2);\n  helpers.doKeys('m', 'e');\n  helpers.doEx('delmarks b-d');\n  cm.setCursor(0, 0);\n  helpers.doKeys('`', 'a');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'b');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'c');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'd');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'e');\n  helpers.assertCursorAt(5, 2);\n});\ntestVim('delmark_multi', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(3, 2);\n  helpers.doKeys('m', 'c');\n  cm.setCursor(4, 2);\n  helpers.doKeys('m', 'd');\n  cm.setCursor(5, 2);\n  helpers.doKeys('m', 'e');\n  helpers.doEx('delmarks bcd');\n  cm.setCursor(0, 0);\n  helpers.doKeys('`', 'a');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'b');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'c');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'd');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'e');\n  helpers.assertCursorAt(5, 2);\n});\ntestVim('delmark_multi_space', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(3, 2);\n  helpers.doKeys('m', 'c');\n  cm.setCursor(4, 2);\n  helpers.doKeys('m', 'd');\n  cm.setCursor(5, 2);\n  helpers.doKeys('m', 'e');\n  helpers.doEx('delmarks b c d');\n  cm.setCursor(0, 0);\n  helpers.doKeys('`', 'a');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'b');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'c');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'd');\n  helpers.assertCursorAt(1, 2);\n  helpers.doKeys('`', 'e');\n  helpers.assertCursorAt(5, 2);\n});\ntestVim('delmark_all', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(2, 2);\n  helpers.doKeys('m', 'b');\n  cm.setCursor(3, 2);\n  helpers.doKeys('m', 'c');\n  cm.setCursor(4, 2);\n  helpers.doKeys('m', 'd');\n  cm.setCursor(5, 2);\n  helpers.doKeys('m', 'e');\n  helpers.doEx('delmarks a b-de');\n  cm.setCursor(0, 0);\n  helpers.doKeys('`', 'a');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('`', 'b');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('`', 'c');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('`', 'd');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('`', 'e');\n  helpers.assertCursorAt(0, 0);\n});\ntestVim('visual', function(cm, vim, helpers) {\n  helpers.doKeys('l', 'v', 'l', 'l');\n  helpers.assertCursorAt(0, 4);\n  eqCursorPos(makeCursor(0, 1), cm.getCursor('anchor'));\n  helpers.doKeys('d');\n  eq('15', cm.getValue());\n}, { value: '12345' });\ntestVim('visual_yank', function(cm, vim, helpers) {\n  helpers.doKeys('v', '3', 'l', 'y');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('p');\n  eq('aa te test for yank', cm.getValue());\n}, { value: 'a test for yank' })\ntestVim('visual_w', function(cm, vim, helpers) {\n  helpers.doKeys('v', 'w');\n  eq(cm.getSelection(), 'motion t');\n}, { value: 'motion test'});\ntestVim('visual_initial_selection', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('v');\n  cm.getSelection('n');\n}, { value: 'init'});\ntestVim('visual_crossover_left', function(cm, vim, helpers) {\n  cm.setCursor(0, 2);\n  helpers.doKeys('v', 'l', 'h', 'h');\n  cm.getSelection('ro');\n}, { value: 'cross'});\ntestVim('visual_crossover_left', function(cm, vim, helpers) {\n  cm.setCursor(0, 2);\n  helpers.doKeys('v', 'h', 'l', 'l');\n  cm.getSelection('os');\n}, { value: 'cross'});\ntestVim('visual_crossover_up', function(cm, vim, helpers) {\n  cm.setCursor(3, 2);\n  helpers.doKeys('v', 'j', 'k', 'k');\n  eqCursorPos(Pos(2, 2), cm.getCursor('head'));\n  eqCursorPos(Pos(3, 3), cm.getCursor('anchor'));\n  helpers.doKeys('k');\n  eqCursorPos(Pos(1, 2), cm.getCursor('head'));\n  eqCursorPos(Pos(3, 3), cm.getCursor('anchor'));\n}, { value: 'cross\\ncross\\ncross\\ncross\\ncross\\n'});\ntestVim('visual_crossover_down', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('v', 'k', 'j', 'j');\n  eqCursorPos(Pos(2, 3), cm.getCursor('head'));\n  eqCursorPos(Pos(1, 2), cm.getCursor('anchor'));\n  helpers.doKeys('j');\n  eqCursorPos(Pos(3, 3), cm.getCursor('head'));\n  eqCursorPos(Pos(1, 2), cm.getCursor('anchor'));\n}, { value: 'cross\\ncross\\ncross\\ncross\\ncross\\n'});\ntestVim('visual_exit', function(cm, vim, helpers) {\n  helpers.doKeys('<C-v>', 'l', 'j', 'j', '<Esc>');\n  eqCursorPos(cm.getCursor('anchor'), cm.getCursor('head'));\n  eq(vim.visualMode, false);\n}, { value: 'hello\\nworld\\nfoo' });\ntestVim('visual_line', function(cm, vim, helpers) {\n  helpers.doKeys('l', 'V', 'l', 'j', 'j', 'd');\n  eq(' 4\\n 5', cm.getValue());\n}, { value: ' 1\\n 2\\n 3\\n 4\\n 5' });\ntestVim('visual_block_move_to_eol', function(cm, vim, helpers) {\n  // moveToEol should move all block cursors to end of line\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-v>', 'G', '$');\n  var selections = cm.getSelections().join();\n  eq('123,45,6', selections);\n  // Checks that with cursor at Infinity, finding words backwards still works.\n  helpers.doKeys('2', 'k', 'b');\n  selections = cm.getSelections().join();\n  eq('1', selections);\n}, {value: '123\\n45\\n6'});\ntestVim('visual_block_different_line_lengths', function(cm, vim, helpers) {\n  // test the block selection with lines of different length\n  // i.e. extending the selection\n  // till the end of the longest line.\n  helpers.doKeys('<C-v>', 'l', 'j', 'j', '6', 'l', 'd');\n  helpers.doKeys('d', 'd', 'd', 'd');\n  eq('', cm.getValue());\n}, {value: '1234\\n5678\\nabcdefg'});\ntestVim('visual_block_truncate_on_short_line', function(cm, vim, helpers) {\n  // check for left side selection in case\n  // of moving up to a shorter line.\n  cm.replaceRange('', cm.getCursor());\n  cm.setCursor(3, 4);\n  helpers.doKeys('<C-v>', 'l', 'k', 'k', 'd');\n  eq('hello world\\n{\\ntis\\nsa!', cm.getValue());\n}, {value: 'hello world\\n{\\nthis is\\nsparta!'});\ntestVim('visual_block_corners', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('<C-v>', '2', 'l', 'k');\n  // circle around the anchor\n  // and check the selections\n  var selections = cm.getSelections();\n  eq('345891', selections.join(''));\n  helpers.doKeys('4', 'h');\n  selections = cm.getSelections();\n  eq('123678', selections.join(''));\n  helpers.doKeys('j', 'j');\n  selections = cm.getSelections();\n  eq('678abc', selections.join(''));\n  helpers.doKeys('4', 'l');\n  selections = cm.getSelections();\n  eq('891cde', selections.join(''));\n}, {value: '12345\\n67891\\nabcde'});\ntestVim('visual_block_mode_switch', function(cm, vim, helpers) {\n  // switch between visual modes\n  cm.setCursor(1, 1);\n  // blockwise to characterwise visual\n  helpers.doKeys('<C-v>', 'j', 'l', 'v');\n  var selections = cm.getSelections();\n  eq('7891\\nabc', selections.join(''));\n  // characterwise to blockwise\n  helpers.doKeys('<C-v>');\n  selections = cm.getSelections();\n  eq('78bc', selections.join(''));\n  // blockwise to linewise visual\n  helpers.doKeys('V');\n  selections = cm.getSelections();\n  eq('67891\\nabcde', selections.join(''));\n}, {value: '12345\\n67891\\nabcde'});\ntestVim('visual_block_crossing_short_line', function(cm, vim, helpers) {\n  // visual block with long and short lines\n  cm.setCursor(0, 3);\n  helpers.doKeys('<C-v>', 'j', 'j', 'j');\n  var selections = cm.getSelections().join();\n  eq('4,,d,b', selections);\n  helpers.doKeys('3', 'k');\n  selections = cm.getSelections().join();\n  eq('4', selections);\n  helpers.doKeys('5', 'j', 'k');\n  selections = cm.getSelections().join(\"\");\n  eq(10, selections.length);\n}, {value: '123456\\n78\\nabcdefg\\nfoobar\\n}\\n'});\ntestVim('visual_block_curPos_on_exit', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-v>', '3' , 'l', '<Esc>');\n  eqCursorPos(makeCursor(0, 3), cm.getCursor());\n  helpers.doKeys('h', '<C-v>', '2' , 'j' ,'3' , 'l');\n  eq(cm.getSelections().join(), \"3456,,cdef\");\n  helpers.doKeys('4' , 'h');\n  eq(cm.getSelections().join(), \"23,8,bc\");\n  helpers.doKeys('2' , 'l');\n  eq(cm.getSelections().join(), \"34,,cd\");\n}, {value: '123456\\n78\\nabcdefg\\nfoobar'});\n\ntestVim('visual_marks', function(cm, vim, helpers) {\n  helpers.doKeys('l', 'v', 'l', 'l', 'j', 'j', 'v');\n  // Test visual mode marks\n  cm.setCursor(2, 1);\n  helpers.doKeys('\\'', '<');\n  helpers.assertCursorAt(0, 1);\n  helpers.doKeys('\\'', '>');\n  helpers.assertCursorAt(2, 0);\n});\ntestVim('visual_join', function(cm, vim, helpers) {\n  helpers.doKeys('l', 'V', 'l', 'j', 'j', 'J');\n  eq(' 1 2 3\\n 4\\n 5', cm.getValue());\n  is(!vim.visualMode);\n}, { value: ' 1\\n 2\\n 3\\n 4\\n 5' });\ntestVim('visual_join_2', function(cm, vim, helpers) {\n  helpers.doKeys('G', 'V', 'g', 'g', 'J');\n  eq('1 2 3 4 5 6 ', cm.getValue());\n  is(!vim.visualMode);\n}, { value: '1\\n2\\n3\\n4\\n5\\n6\\n'});\ntestVim('visual_blank', function(cm, vim, helpers) {\n  helpers.doKeys('v', 'k');\n  eq(vim.visualMode, true);\n}, { value: '\\n' });\ntestVim('reselect_visual', function(cm, vim, helpers) {\n  helpers.doKeys('l', 'v', 'l', 'l', 'l', 'y', 'g', 'v');\n  helpers.assertCursorAt(0, 5);\n  eqCursorPos(makeCursor(0, 1), cm.getCursor('anchor'));\n  helpers.doKeys('v');\n  cm.setCursor(1, 0);\n  helpers.doKeys('v', 'l', 'l', 'p');\n  eq('123456\\n2345\\nbar', cm.getValue());\n  cm.setCursor(0, 0);\n  helpers.doKeys('g', 'v');\n  // here the fake cursor is at (1, 3)\n  helpers.assertCursorAt(1, 4);\n  eqCursorPos(makeCursor(1, 0), cm.getCursor('anchor'));\n  helpers.doKeys('v');\n  cm.setCursor(2, 0);\n  helpers.doKeys('v', 'l', 'l', 'g', 'v');\n  helpers.assertCursorAt(1, 4);\n  eqCursorPos(makeCursor(1, 0), cm.getCursor('anchor'));\n  helpers.doKeys('g', 'v');\n  helpers.assertCursorAt(2, 3);\n  eqCursorPos(makeCursor(2, 0), cm.getCursor('anchor'));\n  eq('123456\\n2345\\nbar', cm.getValue());\n}, { value: '123456\\nfoo\\nbar' });\ntestVim('reselect_visual_line', function(cm, vim, helpers) {\n  helpers.doKeys('l', 'V', 'j', 'j', 'V', 'g', 'v', 'd');\n  eq('foo\\nand\\nbar', cm.getValue());\n  cm.setCursor(1, 0);\n  helpers.doKeys('V', 'y', 'j');\n  helpers.doKeys('V', 'p' , 'g', 'v', 'd');\n  eq('foo\\nand', cm.getValue());\n}, { value: 'hello\\nthis\\nis\\nfoo\\nand\\nbar' });\ntestVim('reselect_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(1, 2);\n  helpers.doKeys('<C-v>', 'k', 'h', '<C-v>');\n  cm.setCursor(2, 1);\n  helpers.doKeys('v', 'l', 'g', 'v');\n  eqCursorPos(Pos(1, 2), vim.sel.anchor);\n  eqCursorPos(Pos(0, 1), vim.sel.head);\n  // Ensure selection is done with visual block mode rather than one\n  // continuous range.\n  eq(cm.getSelections().join(''), '23oo')\n  helpers.doKeys('g', 'v');\n  eqCursorPos(Pos(2, 1), vim.sel.anchor);\n  eqCursorPos(Pos(2, 2), vim.sel.head);\n  helpers.doKeys('<Esc>');\n  // Ensure selection of deleted range\n  cm.setCursor(1, 1);\n  helpers.doKeys('v', '<C-v>', 'j', 'd', 'g', 'v');\n  eq(cm.getSelections().join(''), 'or');\n}, { value: '123456\\nfoo\\nbar' });\ntestVim('s_normal', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('s');\n  helpers.doKeys('<Esc>');\n  eq('ac', cm.getValue());\n}, { value: 'abc'});\ntestVim('s_visual', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('v', 's');\n  helpers.doKeys('<Esc>');\n  helpers.assertCursorAt(0, 0);\n  eq('ac', cm.getValue());\n}, { value: 'abc'});\ntestVim('o_visual', function(cm, vim, helpers) {\n  cm.setCursor(0,0);\n  helpers.doKeys('v','l','l','l','o');\n  helpers.assertCursorAt(0,0);\n  helpers.doKeys('v','v','j','j','j','o');\n  helpers.assertCursorAt(0,0);\n  helpers.doKeys('O');\n  helpers.doKeys('l','l')\n  helpers.assertCursorAt(3, 3);\n  helpers.doKeys('d');\n  eq('p',cm.getValue());\n}, { value: 'abcd\\nefgh\\nijkl\\nmnop'});\ntestVim('o_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('<C-v>','3','j','l','l', 'o');\n  eqCursorPos(Pos(3, 3), vim.sel.anchor);\n  eqCursorPos(Pos(0, 1), vim.sel.head);\n  helpers.doKeys('O');\n  eqCursorPos(Pos(3, 1), vim.sel.anchor);\n  eqCursorPos(Pos(0, 3), vim.sel.head);\n  helpers.doKeys('o');\n  eqCursorPos(Pos(0, 3), vim.sel.anchor);\n  eqCursorPos(Pos(3, 1), vim.sel.head);\n}, { value: 'abcd\\nefgh\\nijkl\\nmnop'});\ntestVim('changeCase_visual', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('v', 'l', 'l');\n  helpers.doKeys('U');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('v', 'l', 'l');\n  helpers.doKeys('u');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('l', 'l', 'l', '.');\n  helpers.assertCursorAt(0, 3);\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'a', 'v', 'j', 'U', 'q');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('j', '@', 'a');\n  helpers.assertCursorAt(1, 0);\n  cm.setCursor(3, 0);\n  helpers.doKeys('V', 'U', 'j', '.');\n  eq('ABCDEF\\nGHIJKL\\nMnopq\\nSHORT LINE\\nLONG LINE OF TEXT', cm.getValue());\n}, { value: 'abcdef\\nghijkl\\nmnopq\\nshort line\\nlong line of text'});\ntestVim('changeCase_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(2, 1);\n  helpers.doKeys('<C-v>', 'k', 'k', 'h', 'U');\n  eq('ABcdef\\nGHijkl\\nMNopq\\nfoo', cm.getValue());\n  cm.setCursor(0, 2);\n  helpers.doKeys('.');\n  eq('ABCDef\\nGHIJkl\\nMNOPq\\nfoo', cm.getValue());\n  // check when last line is shorter.\n  cm.setCursor(2, 2);\n  helpers.doKeys('.');\n  eq('ABCDef\\nGHIJkl\\nMNOPq\\nfoO', cm.getValue());\n}, { value: 'abcdef\\nghijkl\\nmnopq\\nfoo'});\ntestVim('visual_paste', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('v', 'l', 'l', 'y');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('3', 'l', 'j', 'v', 'l', 'p');\n  helpers.assertCursorAt(1, 5);\n  eq('this is a\\nunithitest for visual paste', cm.getValue());\n  cm.setCursor(0, 0);\n  // in case of pasting whole line\n  helpers.doKeys('y', 'y');\n  cm.setCursor(1, 6);\n  helpers.doKeys('v', 'l', 'l', 'l', 'p');\n  helpers.assertCursorAt(2, 0);\n  eq('this is a\\nunithi\\nthis is a\\n for visual paste', cm.getValue());\n}, { value: 'this is a\\nunit test for visual paste'});\n\n// This checks the contents of the register used to paste the text\ntestVim('v_paste_from_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('\"', 'a', 'y', 'w');\n  cm.setCursor(1, 0);\n  helpers.doKeys('v', 'p');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/a\\s+register/.test(text));\n  });\n}, { value: 'register contents\\nare not erased'});\ntestVim('S_normal', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('j', 'S');\n  helpers.doKeys('<Esc>');\n  helpers.assertCursorAt(1, 1);\n  eq('aa{\\n  \\ncc', cm.getValue());\n  helpers.doKeys('j', 'S');\n  eq('aa{\\n  \\n  ', cm.getValue());\n  helpers.assertCursorAt(2, 2);\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('d', 'd', 'd', 'd');\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('S');\n  is(vim.insertMode);\n  eq('', cm.getValue());\n}, { value: 'aa{\\nbb\\ncc'});\ntestVim('blockwise_paste', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-v>', '3', 'j', 'l', 'y');\n  cm.setCursor(0, 2);\n  // paste one char after the current cursor position\n  helpers.doKeys('p');\n  eq('helhelo\\nworwold\\nfoofo\\nbarba', cm.getValue());\n  cm.setCursor(0, 0);\n  helpers.doKeys('v', '4', 'l', 'y');\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-v>', '3', 'j', 'p');\n  eq('helheelhelo\\norwold\\noofo\\narba', cm.getValue());\n}, { value: 'hello\\nworld\\nfoo\\nbar'});\ntestVim('blockwise_paste_long/short_line', function(cm, vim, helpers) {\n  // extend short lines in case of different line lengths.\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-v>', 'j', 'j', 'y');\n  cm.setCursor(0, 3);\n  helpers.doKeys('p');\n  eq('hellho\\nfoo f\\nbar b', cm.getValue());\n}, { value: 'hello\\nfoo\\nbar'});\ntestVim('blockwise_paste_cut_paste', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-v>', '2', 'j', 'x');\n  cm.setCursor(0, 0);\n  helpers.doKeys('P');\n  eq('cut\\nand\\npaste\\nme', cm.getValue());\n}, { value: 'cut\\nand\\npaste\\nme'});\ntestVim('blockwise_paste_from_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-v>', '2', 'j', '\"', 'a', 'y');\n  cm.setCursor(0, 3);\n  helpers.doKeys('\"', 'a', 'p');\n  eq('foobfar\\nhellho\\nworlwd', cm.getValue());\n}, { value: 'foobar\\nhello\\nworld'});\ntestVim('blockwise_paste_last_line', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-v>', '2', 'j', 'l', 'y');\n  cm.setCursor(3, 0);\n  helpers.doKeys('p');\n  eq('cut\\nand\\npaste\\nmcue\\n an\\n pa', cm.getValue());\n}, { value: 'cut\\nand\\npaste\\nme'});\n\ntestVim('S_visual', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('v', 'j', 'S');\n  helpers.doKeys('<Esc>');\n  helpers.assertCursorAt(0, 0);\n  eq('\\ncc', cm.getValue());\n}, { value: 'aa\\nbb\\ncc'});\n\ntestVim('d_/', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('match');\n  helpers.doKeys('2', 'd', '/');\n  helpers.assertCursorAt(0, 0);\n  eq('match \\n next', cm.getValue());\n  cm.openDialog = helpers.fakeOpenDialog('2');\n  helpers.doKeys('d', ':');\n  // TODO eq(' next', cm.getValue());\n}, { value: 'text match match \\n next' });\ntestVim('/ and n/N', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('match');\n  helpers.doKeys('/');\n  helpers.assertCursorAt(0, 11);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(1, 6);\n  helpers.doKeys('N');\n  helpers.assertCursorAt(0, 11);\n\n  cm.setCursor(0, 0);\n  helpers.doKeys('2', '/');\n  helpers.assertCursorAt(1, 6);\n}, { value: 'match nope match \\n nope Match' });\ntestVim('/_case', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('Match');\n  helpers.doKeys('/');\n  helpers.assertCursorAt(1, 6);\n}, { value: 'match nope match \\n nope Match' });\ntestVim('/_2_pcre', function(cm, vim, helpers) {\n  CodeMirror.Vim.setOption('pcre', true);\n  cm.openDialog = helpers.fakeOpenDialog('(word){2}');\n  helpers.doKeys('/');\n  helpers.assertCursorAt(1, 9);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(2, 1);\n}, { value: 'word\\n another wordword\\n wordwordword\\n' });\ntestVim('/_2_nopcre', function(cm, vim, helpers) {\n  CodeMirror.Vim.setOption('pcre', false);\n  cm.openDialog = helpers.fakeOpenDialog('\\\\(word\\\\)\\\\{2}');\n  helpers.doKeys('/');\n  helpers.assertCursorAt(1, 9);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(2, 1);\n}, { value: 'word\\n another wordword\\n wordwordword\\n' });\ntestVim('/_nongreedy', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('aa');\n  helpers.doKeys('/');\n  helpers.assertCursorAt(0, 4);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(1, 3);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 0);\n}, { value: 'aaa aa \\n a aa'});\ntestVim('?_nongreedy', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('aa');\n  helpers.doKeys('?');\n  helpers.assertCursorAt(1, 3);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 4);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 0);\n}, { value: 'aaa aa \\n a aa'});\ntestVim('/_greedy', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('a+');\n  helpers.doKeys('/');\n  helpers.assertCursorAt(0, 4);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(1, 1);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(1, 3);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 0);\n}, { value: 'aaa aa \\n a aa'});\ntestVim('?_greedy', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('a+');\n  helpers.doKeys('?');\n  helpers.assertCursorAt(1, 3);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(1, 1);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 4);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 0);\n}, { value: 'aaa aa \\n a aa'});\ntestVim('/_greedy_0_or_more', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('a*');\n  helpers.doKeys('/');\n  helpers.assertCursorAt(0, 3);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 4);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 5);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(1, 0);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(1, 1);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 0);\n}, { value: 'aaa  aa\\n aa'});\ntestVim('?_greedy_0_or_more', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('a*');\n  helpers.doKeys('?');\n  helpers.assertCursorAt(1, 1);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 5);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 3);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 0);\n}, { value: 'aaa  aa\\n aa'});\ntestVim('? and n/N', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('match');\n  helpers.doKeys('?');\n  helpers.assertCursorAt(1, 6);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 11);\n  helpers.doKeys('N');\n  helpers.assertCursorAt(1, 6);\n\n  cm.setCursor(0, 0);\n  helpers.doKeys('2', '?');\n  helpers.assertCursorAt(0, 11);\n}, { value: 'match nope match \\n nope Match' });\ntestVim('*', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('*');\n  helpers.assertCursorAt(0, 22);\n\n  cm.setCursor(0, 9);\n  helpers.doKeys('2', '*');\n  helpers.assertCursorAt(1, 8);\n}, { value: 'nomatch match nomatch match \\nnomatch Match' });\ntestVim('*_no_word', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('*');\n  helpers.assertCursorAt(0, 0);\n}, { value: ' \\n match \\n' });\ntestVim('*_symbol', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('*');\n  helpers.assertCursorAt(1, 0);\n}, { value: ' /}\\n/} match \\n' });\ntestVim('#', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('#');\n  helpers.assertCursorAt(1, 8);\n\n  cm.setCursor(0, 9);\n  helpers.doKeys('2', '#');\n  helpers.assertCursorAt(0, 22);\n}, { value: 'nomatch match nomatch match \\nnomatch Match' });\ntestVim('*_seek', function(cm, vim, helpers) {\n  // Should skip over space and symbols.\n  cm.setCursor(0, 3);\n  helpers.doKeys('*');\n  helpers.assertCursorAt(0, 22);\n}, { value: '    :=  match nomatch match \\nnomatch Match' });\ntestVim('#', function(cm, vim, helpers) {\n  // Should skip over space and symbols.\n  cm.setCursor(0, 3);\n  helpers.doKeys('#');\n  helpers.assertCursorAt(1, 8);\n}, { value: '    :=  match nomatch match \\nnomatch Match' });\ntestVim('g*', function(cm, vim, helpers) {\n  cm.setCursor(0, 8);\n  helpers.doKeys('g', '*');\n  helpers.assertCursorAt(0, 18);\n  cm.setCursor(0, 8);\n  helpers.doKeys('3', 'g', '*');\n  helpers.assertCursorAt(1, 8);\n}, { value: 'matches match alsoMatch\\nmatchme matching' });\ntestVim('g#', function(cm, vim, helpers) {\n  cm.setCursor(0, 8);\n  helpers.doKeys('g', '#');\n  helpers.assertCursorAt(0, 0);\n  cm.setCursor(0, 8);\n  helpers.doKeys('3', 'g', '#');\n  helpers.assertCursorAt(1, 0);\n}, { value: 'matches match alsoMatch\\nmatchme matching' });\ntestVim('macro_insert', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'a', '0', 'i');\n  cm.replaceRange('foo', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('q', '@', 'a');\n  eq('foofoo', cm.getValue());\n}, { value: ''});\ntestVim('macro_insert_repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'a', '$', 'a');\n  cm.replaceRange('larry.', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('a');\n  cm.replaceRange('curly.', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('q');\n  helpers.doKeys('a');\n  cm.replaceRange('moe.', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('@', 'a');\n  // At this point, the most recent edit should be the 2nd insert change\n  // inside the macro, i.e. \"curly.\".\n  helpers.doKeys('.');\n  eq('larry.curly.moe.larry.curly.curly.', cm.getValue());\n}, { value: ''});\ntestVim('macro_space', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('<Space>', '<Space>');\n  helpers.assertCursorAt(0, 2);\n  helpers.doKeys('q', 'a', '<Space>', '<Space>', 'q');\n  helpers.assertCursorAt(0, 4);\n  helpers.doKeys('@', 'a');\n  helpers.assertCursorAt(0, 6);\n  helpers.doKeys('@', 'a');\n  helpers.assertCursorAt(0, 8);\n}, { value: 'one line of text.'});\ntestVim('macro_t_search', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'a', 't', 'e', 'q');\n  helpers.assertCursorAt(0, 1);\n  helpers.doKeys('l', '@', 'a');\n  helpers.assertCursorAt(0, 6);\n  helpers.doKeys('l', ';');\n  helpers.assertCursorAt(0, 12);\n}, { value: 'one line of text.'});\ntestVim('macro_f_search', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'b', 'f', 'e', 'q');\n  helpers.assertCursorAt(0, 2);\n  helpers.doKeys('@', 'b');\n  helpers.assertCursorAt(0, 7);\n  helpers.doKeys(';');\n  helpers.assertCursorAt(0, 13);\n}, { value: 'one line of text.'});\ntestVim('macro_slash_search', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'c');\n  cm.openDialog = helpers.fakeOpenDialog('e');\n  helpers.doKeys('/', 'q');\n  helpers.assertCursorAt(0, 2);\n  helpers.doKeys('@', 'c');\n  helpers.assertCursorAt(0, 7);\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 13);\n}, { value: 'one line of text.'});\ntestVim('macro_multislash_search', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'd');\n  cm.openDialog = helpers.fakeOpenDialog('e');\n  helpers.doKeys('/');\n  cm.openDialog = helpers.fakeOpenDialog('t');\n  helpers.doKeys('/', 'q');\n  helpers.assertCursorAt(0, 12);\n  helpers.doKeys('@', 'd');\n  helpers.assertCursorAt(0, 15);\n}, { value: 'one line of text to rule them all.'});\ntestVim('macro_last_ex_command_register', function (cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doEx('s/a/b');\n  helpers.doKeys('2', '@', ':');\n  eq('bbbaa', cm.getValue());\n  helpers.assertCursorAt(0, 2);\n}, { value: 'aaaaa'});\ntestVim('macro_parens', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'z', 'i');\n  cm.replaceRange('(', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('e', 'a');\n  cm.replaceRange(')', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('q');\n  helpers.doKeys('w', '@', 'z');\n  helpers.doKeys('w', '@', 'z');\n  eq('(see) (spot) (run)', cm.getValue());\n}, { value: 'see spot run'});\ntestVim('macro_overwrite', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'z', '0', 'i');\n  cm.replaceRange('I ', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('q');\n  helpers.doKeys('e');\n  // Now replace the macro with something else.\n  helpers.doKeys('q', 'z', 'a');\n  cm.replaceRange('.', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('q');\n  helpers.doKeys('e', '@', 'z');\n  helpers.doKeys('e', '@', 'z');\n  eq('I see. spot. run.', cm.getValue());\n}, { value: 'see spot run'});\ntestVim('macro_search_f', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'a', 'f', ' ');\n  helpers.assertCursorAt(0,3);\n  helpers.doKeys('q', '0');\n  helpers.assertCursorAt(0,0);\n  helpers.doKeys('@', 'a');\n  helpers.assertCursorAt(0,3);\n}, { value: 'The quick brown fox jumped over the lazy dog.'});\ntestVim('macro_search_2f', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'a', '2', 'f', ' ');\n  helpers.assertCursorAt(0,9);\n  helpers.doKeys('q', '0');\n  helpers.assertCursorAt(0,0);\n  helpers.doKeys('@', 'a');\n  helpers.assertCursorAt(0,9);\n}, { value: 'The quick brown fox jumped over the lazy dog.'});\ntestVim('macro_yank_tick', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  // Start recording a macro into the \\' register.\n  helpers.doKeys('q', '\\'');\n  helpers.doKeys('y', '<Right>', '<Right>', '<Right>', '<Right>', 'p');\n  helpers.assertCursorAt(0,4);\n  eq('the tex parrot', cm.getValue());\n}, { value: 'the ex parrot'});\ntestVim('yank_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('\"', 'a', 'y', 'y');\n  helpers.doKeys('j', '\"', 'b', 'y', 'y');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/a\\s+foo/.test(text));\n    is(/b\\s+bar/.test(text));\n  });\n  helpers.doKeys(':');\n}, { value: 'foo\\nbar'});\ntestVim('yank_visual_block', function(cm, vim, helpers) {\n  cm.setCursor(0, 1);\n  helpers.doKeys('<C-v>', 'l', 'j', '\"', 'a', 'y');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/a\\s+oo\\nar/.test(text));\n  });\n  helpers.doKeys(':');\n}, { value: 'foo\\nbar'});\ntestVim('yank_append_line_to_line_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('\"', 'a', 'y', 'y');\n  helpers.doKeys('j', '\"', 'A', 'y', 'y');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/a\\s+foo\\nbar/.test(text));\n    is(/\"\\s+foo\\nbar/.test(text));\n  });\n  helpers.doKeys(':');\n}, { value: 'foo\\nbar'});\ntestVim('yank_append_word_to_word_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('\"', 'a', 'y', 'w');\n  helpers.doKeys('j', '\"', 'A', 'y', 'w');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/a\\s+foobar/.test(text));\n    is(/\"\\s+foobar/.test(text));\n  });\n  helpers.doKeys(':');\n}, { value: 'foo\\nbar'});\ntestVim('yank_append_line_to_word_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('\"', 'a', 'y', 'w');\n  helpers.doKeys('j', '\"', 'A', 'y', 'y');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/a\\s+foo\\nbar/.test(text));\n    is(/\"\\s+foo\\nbar/.test(text));\n  });\n  helpers.doKeys(':');\n}, { value: 'foo\\nbar'});\ntestVim('yank_append_word_to_line_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('\"', 'a', 'y', 'y');\n  helpers.doKeys('j', '\"', 'A', 'y', 'w');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/a\\s+foo\\nbar/.test(text));\n    is(/\"\\s+foo\\nbar/.test(text));\n  });\n  helpers.doKeys(':');\n}, { value: 'foo\\nbar'});\ntestVim('macro_register', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('q', 'a', 'i');\n  cm.replaceRange('gangnam', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('q');\n  helpers.doKeys('q', 'b', 'o');\n  cm.replaceRange('style', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('q');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/a\\s+i/.test(text));\n    is(/b\\s+o/.test(text));\n  });\n  helpers.doKeys(':');\n}, { value: ''});\ntestVim('._register', function(cm,vim,helpers) {\n  cm.setCursor(0,0);\n  helpers.doKeys('i');\n  cm.replaceRange('foo',cm.getCursor());\n  helpers.doKeys('<Esc>');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/\\.\\s+foo/.test(text));\n  });\n  helpers.doKeys(':');\n}, {value: ''});\ntestVim(':_register', function(cm,vim,helpers) {\n  helpers.doEx('bar');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/:\\s+bar/.test(text));\n  });\n  helpers.doKeys(':');\n}, {value: ''});\ntestVim('search_register_escape', function(cm, vim, helpers) {\n  // Check that the register is restored if the user escapes rather than confirms.\n  cm.openDialog = helpers.fakeOpenDialog('waldo');\n  helpers.doKeys('/');\n  var onKeyDown;\n  var onKeyUp;\n  var KEYCODES = {\n    f: 70,\n    o: 79,\n    Esc: 27\n  };\n  cm.openDialog = function(template, callback, options) {\n    onKeyDown = options.onKeyDown;\n    onKeyUp = options.onKeyUp;\n  };\n  var close = function() {};\n  helpers.doKeys('/');\n  // Fake some keyboard events coming in.\n  onKeyDown({keyCode: KEYCODES.f}, '', close);\n  onKeyUp({keyCode: KEYCODES.f}, '', close);\n  onKeyDown({keyCode: KEYCODES.o}, 'f', close);\n  onKeyUp({keyCode: KEYCODES.o}, 'f', close);\n  onKeyDown({keyCode: KEYCODES.o}, 'fo', close);\n  onKeyUp({keyCode: KEYCODES.o}, 'fo', close);\n  onKeyDown({keyCode: KEYCODES.Esc}, 'foo', close);\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/waldo/.test(text));\n    is(!/foo/.test(text));\n  });\n  helpers.doKeys(':');\n}, {value: ''});\ntestVim('search_register', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('foo');\n  helpers.doKeys('/');\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  cm.openNotification = helpers.fakeOpenNotification(function(text) {\n    is(/\\/\\s+foo/.test(text));\n  });\n  helpers.doKeys(':');\n}, {value: ''});\ntestVim('search_history', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('this');\n  helpers.doKeys('/');\n  cm.openDialog = helpers.fakeOpenDialog('checks');\n  helpers.doKeys('/');\n  cm.openDialog = helpers.fakeOpenDialog('search');\n  helpers.doKeys('/');\n  cm.openDialog = helpers.fakeOpenDialog('history');\n  helpers.doKeys('/');\n  cm.openDialog = helpers.fakeOpenDialog('checks');\n  helpers.doKeys('/');\n  var onKeyDown;\n  var onKeyUp;\n  var query = '';\n  var keyCodes = {\n    Up: 38,\n    Down: 40\n  };\n  cm.openDialog = function(template, callback, options) {\n    onKeyUp = options.onKeyUp;\n    onKeyDown = options.onKeyDown;\n  };\n  var close = function(newVal) {\n    if (typeof newVal == 'string') query = newVal;\n  }\n  helpers.doKeys('/');\n  onKeyDown({keyCode: keyCodes.Up}, query, close);\n  onKeyUp({keyCode: keyCodes.Up}, query, close);\n  eq(query, 'checks');\n  onKeyDown({keyCode: keyCodes.Up}, query, close);\n  onKeyUp({keyCode: keyCodes.Up}, query, close);\n  eq(query, 'history');\n  onKeyDown({keyCode: keyCodes.Up}, query, close);\n  onKeyUp({keyCode: keyCodes.Up}, query, close);\n  eq(query, 'search');\n  onKeyDown({keyCode: keyCodes.Up}, query, close);\n  onKeyUp({keyCode: keyCodes.Up}, query, close);\n  eq(query, 'this');\n  onKeyDown({keyCode: keyCodes.Down}, query, close);\n  onKeyUp({keyCode: keyCodes.Down}, query, close);\n  eq(query, 'search');\n}, {value: ''});\ntestVim('exCommand_history', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('registers');\n  helpers.doKeys(':');\n  cm.openDialog = helpers.fakeOpenDialog('sort');\n  helpers.doKeys(':');\n  cm.openDialog = helpers.fakeOpenDialog('map');\n  helpers.doKeys(':');\n  cm.openDialog = helpers.fakeOpenDialog('invalid');\n  helpers.doKeys(':');\n  var onKeyDown;\n  var onKeyUp;\n  var input = '';\n  var keyCodes = {\n    Up: 38,\n    Down: 40,\n    s: 115\n  };\n  cm.openDialog = function(template, callback, options) {\n    onKeyUp = options.onKeyUp;\n    onKeyDown = options.onKeyDown;\n  };\n  var close = function(newVal) {\n    if (typeof newVal == 'string') input = newVal;\n  }\n  helpers.doKeys(':');\n  onKeyDown({keyCode: keyCodes.Up}, input, close);\n  eq(input, 'invalid');\n  onKeyDown({keyCode: keyCodes.Up}, input, close);\n  eq(input, 'map');\n  onKeyDown({keyCode: keyCodes.Up}, input, close);\n  eq(input, 'sort');\n  onKeyDown({keyCode: keyCodes.Up}, input, close);\n  eq(input, 'registers');\n  onKeyDown({keyCode: keyCodes.s}, '', close);\n  input = 's';\n  onKeyDown({keyCode: keyCodes.Up}, input, close);\n  eq(input, 'sort');\n}, {value: ''});\ntestVim('search_clear', function(cm, vim, helpers) {\n  var onKeyDown;\n  var input = '';\n  var keyCodes = {\n    Ctrl: 17,\n    u: 85\n  };\n  cm.openDialog = function(template, callback, options) {\n    onKeyDown = options.onKeyDown;\n  };\n  var close = function(newVal) {\n    if (typeof newVal == 'string') input = newVal;\n  }\n  helpers.doKeys('/');\n  input = 'foo';\n  onKeyDown({keyCode: keyCodes.Ctrl}, input, close);\n  onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close);\n  eq(input, '');\n});\ntestVim('exCommand_clear', function(cm, vim, helpers) {\n  var onKeyDown;\n  var input = '';\n  var keyCodes = {\n    Ctrl: 17,\n    u: 85\n  };\n  cm.openDialog = function(template, callback, options) {\n    onKeyDown = options.onKeyDown;\n  };\n  var close = function(newVal) {\n    if (typeof newVal == 'string') input = newVal;\n  }\n  helpers.doKeys(':');\n  input = 'foo';\n  onKeyDown({keyCode: keyCodes.Ctrl}, input, close);\n  onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close);\n  eq(input, '');\n});\ntestVim('.', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('2', 'd', 'w');\n  helpers.doKeys('.');\n  eq('5 6', cm.getValue());\n}, { value: '1 2 3 4 5 6'});\ntestVim('._repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('2', 'd', 'w');\n  helpers.doKeys('3', '.');\n  eq('6', cm.getValue());\n}, { value: '1 2 3 4 5 6'});\ntestVim('._insert', function(cm, vim, helpers) {\n  helpers.doKeys('i');\n  cm.replaceRange('test', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('.');\n  eq('testestt', cm.getValue());\n  helpers.assertCursorAt(0, 6);\n  helpers.doKeys('O');\n  cm.replaceRange('xyz', cm.getCursor());\n  helpers.doInsertModeKeys('Backspace');\n  helpers.doInsertModeKeys('Down');\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('.');\n  eq('xy\\nxy\\ntestestt', cm.getValue());\n  helpers.assertCursorAt(1, 1);\n}, { value: ''});\ntestVim('._insert_repeat', function(cm, vim, helpers) {\n  helpers.doKeys('i');\n  cm.replaceRange('test', cm.getCursor());\n  cm.setCursor(0, 4);\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('2', '.');\n  eq('testesttestt', cm.getValue());\n  helpers.assertCursorAt(0, 10);\n}, { value: ''});\ntestVim('._repeat_insert', function(cm, vim, helpers) {\n  helpers.doKeys('3', 'i');\n  cm.replaceRange('te', cm.getCursor());\n  cm.setCursor(0, 2);\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('.');\n  eq('tetettetetee', cm.getValue());\n  helpers.assertCursorAt(0, 10);\n}, { value: ''});\ntestVim('._insert_o', function(cm, vim, helpers) {\n  helpers.doKeys('o');\n  cm.replaceRange('z', cm.getCursor());\n  cm.setCursor(1, 1);\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('.');\n  eq('\\nz\\nz', cm.getValue());\n  helpers.assertCursorAt(2, 0);\n}, { value: ''});\ntestVim('._insert_o_repeat', function(cm, vim, helpers) {\n  helpers.doKeys('o');\n  cm.replaceRange('z', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  cm.setCursor(1, 0);\n  helpers.doKeys('2', '.');\n  eq('\\nz\\nz\\nz', cm.getValue());\n  helpers.assertCursorAt(3, 0);\n}, { value: ''});\ntestVim('._insert_o_indent', function(cm, vim, helpers) {\n  helpers.doKeys('o');\n  cm.replaceRange('z', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  cm.setCursor(1, 2);\n  helpers.doKeys('.');\n  eq('{\\n  z\\n  z', cm.getValue());\n  helpers.assertCursorAt(2, 2);\n}, { value: '{'});\ntestVim('._insert_cw', function(cm, vim, helpers) {\n  helpers.doKeys('c', 'w');\n  cm.replaceRange('test', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  cm.setCursor(0, 3);\n  helpers.doKeys('2', 'l');\n  helpers.doKeys('.');\n  eq('test test word3', cm.getValue());\n  helpers.assertCursorAt(0, 8);\n}, { value: 'word1 word2 word3' });\ntestVim('._insert_cw_repeat', function(cm, vim, helpers) {\n  // For some reason, repeat cw in desktop VIM will does not repeat insert mode\n  // changes. Will conform to that behavior.\n  helpers.doKeys('c', 'w');\n  cm.replaceRange('test', cm.getCursor());\n  helpers.doKeys('<Esc>');\n  cm.setCursor(0, 4);\n  helpers.doKeys('l');\n  helpers.doKeys('2', '.');\n  eq('test test', cm.getValue());\n  helpers.assertCursorAt(0, 8);\n}, { value: 'word1 word2 word3' });\ntestVim('._delete', function(cm, vim, helpers) {\n  cm.setCursor(0, 5);\n  helpers.doKeys('i');\n  helpers.doInsertModeKeys('Backspace');\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('.');\n  eq('zace', cm.getValue());\n  helpers.assertCursorAt(0, 1);\n}, { value: 'zabcde'});\ntestVim('._delete_repeat', function(cm, vim, helpers) {\n  cm.setCursor(0, 6);\n  helpers.doKeys('i');\n  helpers.doInsertModeKeys('Backspace');\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('2', '.');\n  eq('zzce', cm.getValue());\n  helpers.assertCursorAt(0, 1);\n}, { value: 'zzabcde'});\ntestVim('._visual_>', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('V', 'j', '>');\n  cm.setCursor(2, 0)\n  helpers.doKeys('.');\n  eq('  1\\n  2\\n  3\\n  4', cm.getValue());\n  helpers.assertCursorAt(2, 2);\n}, { value: '1\\n2\\n3\\n4'});\ntestVim('._replace_repeat', function(cm, vim, helpers) {\n  helpers.doKeys('R');\n  cm.replaceRange('123', cm.getCursor(), offsetCursor(cm.getCursor(), 0, 3));\n  cm.setCursor(0, 3);\n  helpers.doKeys('<Esc>');\n  helpers.doKeys('2', '.');\n  eq('12123123\\nabcdefg', cm.getValue());\n  helpers.assertCursorAt(0, 7);\n  cm.setCursor(1, 0);\n  helpers.doKeys('.');\n  eq('12123123\\n123123g', cm.getValue());\n  helpers.doKeys('l', '\"', '.', 'p');\n  eq('12123123\\n123123g123', cm.getValue());\n}, { value: 'abcdef\\nabcdefg'});\ntestVim('f;', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('f', 'x');\n  helpers.doKeys(';');\n  helpers.doKeys('2', ';');\n  eq(9, cm.getCursor().ch);\n}, { value: '01x3xx678x'});\ntestVim('F;', function(cm, vim, helpers) {\n  cm.setCursor(0, 8);\n  helpers.doKeys('F', 'x');\n  helpers.doKeys(';');\n  helpers.doKeys('2', ';');\n  eq(2, cm.getCursor().ch);\n}, { value: '01x3xx6x8x'});\ntestVim('t;', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('t', 'x');\n  helpers.doKeys(';');\n  helpers.doKeys('2', ';');\n  eq(8, cm.getCursor().ch);\n}, { value: '01x3xx678x'});\ntestVim('T;', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('T', 'x');\n  helpers.doKeys(';');\n  helpers.doKeys('2', ';');\n  eq(2, cm.getCursor().ch);\n}, { value: '0xx3xx678x'});\ntestVim('f,', function(cm, vim, helpers) {\n  cm.setCursor(0, 6);\n  helpers.doKeys('f', 'x');\n  helpers.doKeys(',');\n  helpers.doKeys('2', ',');\n  eq(2, cm.getCursor().ch);\n}, { value: '01x3xx678x'});\ntestVim('F,', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  helpers.doKeys('F', 'x');\n  helpers.doKeys(',');\n  helpers.doKeys('2', ',');\n  eq(9, cm.getCursor().ch);\n}, { value: '01x3xx678x'});\ntestVim('t,', function(cm, vim, helpers) {\n  cm.setCursor(0, 6);\n  helpers.doKeys('t', 'x');\n  helpers.doKeys(',');\n  helpers.doKeys('2', ',');\n  eq(3, cm.getCursor().ch);\n}, { value: '01x3xx678x'});\ntestVim('T,', function(cm, vim, helpers) {\n  cm.setCursor(0, 4);\n  helpers.doKeys('T', 'x');\n  helpers.doKeys(',');\n  helpers.doKeys('2', ',');\n  eq(8, cm.getCursor().ch);\n}, { value: '01x3xx67xx'});\ntestVim('fd,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('f', '4');\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', ';');\n  eq('56789', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 9);\n  helpers.doKeys('d', ',');\n  eq('01239', cm.getValue());\n}, { value: '0123456789'});\ntestVim('Fd,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('F', '4');\n  cm.setCursor(0, 9);\n  helpers.doKeys('d', ';');\n  eq('01239', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', ',');\n  eq('56789', cm.getValue());\n}, { value: '0123456789'});\ntestVim('td,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('t', '4');\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', ';');\n  eq('456789', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 9);\n  helpers.doKeys('d', ',');\n  eq('012349', cm.getValue());\n}, { value: '0123456789'});\ntestVim('Td,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('T', '4');\n  cm.setCursor(0, 9);\n  helpers.doKeys('d', ';');\n  eq('012349', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 0);\n  helpers.doKeys('d', ',');\n  eq('456789', cm.getValue());\n}, { value: '0123456789'});\ntestVim('fc,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('f', '4');\n  cm.setCursor(0, 0);\n  helpers.doKeys('c', ';', '<Esc>');\n  eq('56789', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 9);\n  helpers.doKeys('c', ',');\n  eq('01239', cm.getValue());\n}, { value: '0123456789'});\ntestVim('Fc,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('F', '4');\n  cm.setCursor(0, 9);\n  helpers.doKeys('c', ';', '<Esc>');\n  eq('01239', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 0);\n  helpers.doKeys('c', ',');\n  eq('56789', cm.getValue());\n}, { value: '0123456789'});\ntestVim('tc,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('t', '4');\n  cm.setCursor(0, 0);\n  helpers.doKeys('c', ';', '<Esc>');\n  eq('456789', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 9);\n  helpers.doKeys('c', ',');\n  eq('012349', cm.getValue());\n}, { value: '0123456789'});\ntestVim('Tc,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('T', '4');\n  cm.setCursor(0, 9);\n  helpers.doKeys('c', ';', '<Esc>');\n  eq('012349', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 0);\n  helpers.doKeys('c', ',');\n  eq('456789', cm.getValue());\n}, { value: '0123456789'});\ntestVim('fy,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('f', '4');\n  cm.setCursor(0, 0);\n  helpers.doKeys('y', ';', 'P');\n  eq('012340123456789', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 9);\n  helpers.doKeys('y', ',', 'P');\n  eq('012345678456789', cm.getValue());\n}, { value: '0123456789'});\ntestVim('Fy,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('F', '4');\n  cm.setCursor(0, 9);\n  helpers.doKeys('y', ';', 'p');\n  eq('012345678945678', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 0);\n  helpers.doKeys('y', ',', 'P');\n  eq('012340123456789', cm.getValue());\n}, { value: '0123456789'});\ntestVim('ty,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys('t', '4');\n  cm.setCursor(0, 0);\n  helpers.doKeys('y', ';', 'P');\n  eq('01230123456789', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 9);\n  helpers.doKeys('y', ',', 'p');\n  eq('01234567895678', cm.getValue());\n}, { value: '0123456789'});\ntestVim('Ty,;', function(cm, vim, helpers) {\n  cm.setCursor(0, 9);\n  helpers.doKeys('T', '4');\n  cm.setCursor(0, 9);\n  helpers.doKeys('y', ';', 'p');\n  eq('01234567895678', cm.getValue());\n  helpers.doKeys('u');\n  cm.setCursor(0, 0);\n  helpers.doKeys('y', ',', 'P');\n  eq('01230123456789', cm.getValue());\n}, { value: '0123456789'});\ntestVim('HML', function(cm, vim, helpers) {\n  var lines = 35;\n  var textHeight = cm.defaultTextHeight();\n  cm.setSize(600, lines*textHeight);\n  cm.setCursor(120, 0);\n  helpers.doKeys('H');\n  helpers.assertCursorAt(86, 2);\n  helpers.doKeys('L');\n  helpers.assertCursorAt(120, 4);\n  helpers.doKeys('M');\n  helpers.assertCursorAt(103,4);\n}, { value: (function(){\n  var lines = new Array(100);\n  var upper = '  xx\\n';\n  var lower = '    xx\\n';\n  upper = lines.join(upper);\n  lower = lines.join(lower);\n  return upper + lower;\n})()});\n\nvar zVals = [];\nforEach(['zb','zz','zt','z-','z.','z<CR>'], function(e, idx){\n  var lineNum = 250;\n  var lines = 35;\n  testVim(e, function(cm, vim, helpers) {\n    var k1 = e[0];\n    var k2 = e.substring(1);\n    var textHeight = cm.defaultTextHeight();\n    cm.setSize(600, lines*textHeight);\n    cm.setCursor(lineNum, 0);\n    helpers.doKeys(k1, k2);\n    zVals[idx] = cm.getScrollInfo().top;\n  }, { value: (function(){\n    return new Array(500).join('\\n');\n  })()});\n});\ntestVim('zb_to_bottom', function(cm, vim, helpers){\n  var lineNum = 250;\n  cm.setSize(600, 35*cm.defaultTextHeight());\n  cm.setCursor(lineNum, 0);\n  helpers.doKeys('z', 'b');\n  var scrollInfo = cm.getScrollInfo();\n  eq(scrollInfo.top + scrollInfo.clientHeight, cm.charCoords(Pos(lineNum, 0), 'local').bottom);\n}, { value: (function(){\n  return new Array(500).join('\\n');\n})()});\ntestVim('zt_to_top', function(cm, vim, helpers){\n  var lineNum = 250;\n  cm.setSize(600, 35*cm.defaultTextHeight());\n  cm.setCursor(lineNum, 0);\n  helpers.doKeys('z', 't');\n  eq(cm.getScrollInfo().top, cm.charCoords(Pos(lineNum, 0), 'local').top);\n}, { value: (function(){\n  return new Array(500).join('\\n');\n})()});\ntestVim('zb<zz', function(cm, vim, helpers){\n  eq(zVals[0]<zVals[1], true);\n});\ntestVim('zz<zt', function(cm, vim, helpers){\n  eq(zVals[1]<zVals[2], true);\n});\ntestVim('zb==z-', function(cm, vim, helpers){\n  eq(zVals[0], zVals[3]);\n});\ntestVim('zz==z.', function(cm, vim, helpers){\n  eq(zVals[1], zVals[4]);\n});\ntestVim('zt==z<CR>', function(cm, vim, helpers){\n  eq(zVals[2], zVals[5]);\n});\n\nvar moveTillCharacterSandbox =\n  'The quick brown fox \\n';\ntestVim('moveTillCharacter', function(cm, vim, helpers){\n  cm.setCursor(0, 0);\n  // Search for the 'q'.\n  cm.openDialog = helpers.fakeOpenDialog('q');\n  helpers.doKeys('/');\n  eq(4, cm.getCursor().ch);\n  // Jump to just before the first o in the list.\n  helpers.doKeys('t');\n  helpers.doKeys('o');\n  eq('The quick brown fox \\n', cm.getValue());\n  // Delete that one character.\n  helpers.doKeys('d');\n  helpers.doKeys('t');\n  helpers.doKeys('o');\n  eq('The quick bown fox \\n', cm.getValue());\n  // Delete everything until the next 'o'.\n  helpers.doKeys('.');\n  eq('The quick box \\n', cm.getValue());\n  // An unmatched character should have no effect.\n  helpers.doKeys('d');\n  helpers.doKeys('t');\n  helpers.doKeys('q');\n  eq('The quick box \\n', cm.getValue());\n  // Matches should only be possible on single lines.\n  helpers.doKeys('d');\n  helpers.doKeys('t');\n  helpers.doKeys('z');\n  eq('The quick box \\n', cm.getValue());\n  // After all that, the search for 'q' should still be active, so the 'N' command\n  // can run it again in reverse. Use that to delete everything back to the 'q'.\n  helpers.doKeys('d');\n  helpers.doKeys('N');\n  eq('The ox \\n', cm.getValue());\n  eq(4, cm.getCursor().ch);\n}, { value: moveTillCharacterSandbox});\ntestVim('searchForPipe', function(cm, vim, helpers){\n  CodeMirror.Vim.setOption('pcre', false);\n  cm.setCursor(0, 0);\n  // Search for the '|'.\n  cm.openDialog = helpers.fakeOpenDialog('|');\n  helpers.doKeys('/');\n  eq(4, cm.getCursor().ch);\n}, { value: 'this|that'});\n\n\nvar scrollMotionSandbox =\n  '\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n';\ntestVim('scrollMotion', function(cm, vim, helpers){\n  var prevCursor, prevScrollInfo;\n  cm.setCursor(0, 0);\n  // ctrl-y at the top of the file should have no effect.\n  helpers.doKeys('<C-y>');\n  eq(0, cm.getCursor().line);\n  prevScrollInfo = cm.getScrollInfo();\n  helpers.doKeys('<C-e>');\n  eq(1, cm.getCursor().line);\n  is(prevScrollInfo.top < cm.getScrollInfo().top);\n  // Jump to the end of the sandbox.\n  cm.setCursor(1000, 0);\n  prevCursor = cm.getCursor();\n  // ctrl-e at the bottom of the file should have no effect.\n  helpers.doKeys('<C-e>');\n  eq(prevCursor.line, cm.getCursor().line);\n  prevScrollInfo = cm.getScrollInfo();\n  helpers.doKeys('<C-y>');\n  eq(prevCursor.line - 1, cm.getCursor().line, \"Y\");\n  is(prevScrollInfo.top > cm.getScrollInfo().top);\n}, { value: scrollMotionSandbox});\n\nvar squareBracketMotionSandbox = ''+\n  '({\\n'+//0\n  '  ({\\n'+//11\n  '  /*comment {\\n'+//2\n  '            */(\\n'+//3\n  '#else                \\n'+//4\n  '  /*       )\\n'+//5\n  '#if        }\\n'+//6\n  '  )}*/\\n'+//7\n  ')}\\n'+//8\n  '{}\\n'+//9\n  '#else {{\\n'+//10\n  '{}\\n'+//11\n  '}\\n'+//12\n  '{\\n'+//13\n  '#endif\\n'+//14\n  '}\\n'+//15\n  '}\\n'+//16\n  '#else';//17\ntestVim('[[, ]]', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys(']', ']');\n  helpers.assertCursorAt(9,0);\n  helpers.doKeys('2', ']', ']');\n  helpers.assertCursorAt(13,0);\n  helpers.doKeys(']', ']');\n  helpers.assertCursorAt(17,0);\n  helpers.doKeys('[', '[');\n  helpers.assertCursorAt(13,0);\n  helpers.doKeys('2', '[', '[');\n  helpers.assertCursorAt(9,0);\n  helpers.doKeys('[', '[');\n  helpers.assertCursorAt(0,0);\n}, { value: squareBracketMotionSandbox});\ntestVim('[], ][', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doKeys(']', '[');\n  helpers.assertCursorAt(12,0);\n  helpers.doKeys('2', ']', '[');\n  helpers.assertCursorAt(16,0);\n  helpers.doKeys(']', '[');\n  helpers.assertCursorAt(17,0);\n  helpers.doKeys('[', ']');\n  helpers.assertCursorAt(16,0);\n  helpers.doKeys('2', '[', ']');\n  helpers.assertCursorAt(12,0);\n  helpers.doKeys('[', ']');\n  helpers.assertCursorAt(0,0);\n}, { value: squareBracketMotionSandbox});\ntestVim('[{, ]}', function(cm, vim, helpers) {\n  cm.setCursor(4, 10);\n  helpers.doKeys('[', '{');\n  helpers.assertCursorAt(2,12);\n  helpers.doKeys('2', '[', '{');\n  helpers.assertCursorAt(0,1);\n  cm.setCursor(4, 10);\n  helpers.doKeys(']', '}');\n  helpers.assertCursorAt(6,11);\n  helpers.doKeys('2', ']', '}');\n  helpers.assertCursorAt(8,1);\n  cm.setCursor(0,1);\n  helpers.doKeys(']', '}');\n  helpers.assertCursorAt(8,1);\n  helpers.doKeys('[', '{');\n  helpers.assertCursorAt(0,1);\n}, { value: squareBracketMotionSandbox});\ntestVim('[(, ])', function(cm, vim, helpers) {\n  cm.setCursor(4, 10);\n  helpers.doKeys('[', '(');\n  helpers.assertCursorAt(3,14);\n  helpers.doKeys('2', '[', '(');\n  helpers.assertCursorAt(0,0);\n  cm.setCursor(4, 10);\n  helpers.doKeys(']', ')');\n  helpers.assertCursorAt(5,11);\n  helpers.doKeys('2', ']', ')');\n  helpers.assertCursorAt(8,0);\n  helpers.doKeys('[', '(');\n  helpers.assertCursorAt(0,0);\n  helpers.doKeys(']', ')');\n  helpers.assertCursorAt(8,0);\n}, { value: squareBracketMotionSandbox});\ntestVim('[*, ]*, [/, ]/', function(cm, vim, helpers) {\n  forEach(['*', '/'], function(key){\n    cm.setCursor(7, 0);\n    helpers.doKeys('2', '[', key);\n    helpers.assertCursorAt(2,2);\n    helpers.doKeys('2', ']', key);\n    helpers.assertCursorAt(7,5);\n  });\n}, { value: squareBracketMotionSandbox});\ntestVim('[#, ]#', function(cm, vim, helpers) {\n  cm.setCursor(10, 3);\n  helpers.doKeys('2', '[', '#');\n  helpers.assertCursorAt(4,0);\n  helpers.doKeys('5', ']', '#');\n  helpers.assertCursorAt(17,0);\n  cm.setCursor(10, 3);\n  helpers.doKeys(']', '#');\n  helpers.assertCursorAt(14,0);\n}, { value: squareBracketMotionSandbox});\ntestVim('[m, ]m, [M, ]M', function(cm, vim, helpers) {\n  cm.setCursor(11, 0);\n  helpers.doKeys('[', 'm');\n  helpers.assertCursorAt(10,7);\n  helpers.doKeys('4', '[', 'm');\n  helpers.assertCursorAt(1,3);\n  helpers.doKeys('5', ']', 'm');\n  helpers.assertCursorAt(11,0);\n  helpers.doKeys('[', 'M');\n  helpers.assertCursorAt(9,1);\n  helpers.doKeys('3', ']', 'M');\n  helpers.assertCursorAt(15,0);\n  helpers.doKeys('5', '[', 'M');\n  helpers.assertCursorAt(7,3);\n}, { value: squareBracketMotionSandbox});\n\ntestVim('i_indent_right', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  var expectedValue = '   word1\\nword2\\nword3 ';\n  helpers.doKeys('i', '<C-t>');\n  eq(expectedValue, cm.getValue());\n  helpers.assertCursorAt(0, 5);\n}, { value: ' word1\\nword2\\nword3 ', indentUnit: 2 });\ntestVim('i_indent_left', function(cm, vim, helpers) {\n  cm.setCursor(0, 3);\n  var expectedValue = ' word1\\nword2\\nword3 ';\n  helpers.doKeys('i', '<C-d>');\n  eq(expectedValue, cm.getValue());\n  helpers.assertCursorAt(0, 1);\n}, { value: '   word1\\nword2\\nword3 ', indentUnit: 2 });\n\n// Ex mode tests\ntestVim('ex_go_to_line', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doEx('4');\n  helpers.assertCursorAt(3, 0);\n}, { value: 'a\\nb\\nc\\nd\\ne\\n'});\ntestVim('ex_go_to_mark', function(cm, vim, helpers) {\n  cm.setCursor(3, 0);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(0, 0);\n  helpers.doEx('\\'a');\n  helpers.assertCursorAt(3, 0);\n}, { value: 'a\\nb\\nc\\nd\\ne\\n'});\ntestVim('ex_go_to_line_offset', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doEx('+3');\n  helpers.assertCursorAt(3, 0);\n  helpers.doEx('-1');\n  helpers.assertCursorAt(2, 0);\n  helpers.doEx('.2');\n  helpers.assertCursorAt(4, 0);\n  helpers.doEx('.-3');\n  helpers.assertCursorAt(1, 0);\n}, { value: 'a\\nb\\nc\\nd\\ne\\n'});\ntestVim('ex_go_to_mark_offset', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('m', 'a');\n  cm.setCursor(0, 0);\n  helpers.doEx('\\'a1');\n  helpers.assertCursorAt(3, 0);\n  helpers.doEx('\\'a-1');\n  helpers.assertCursorAt(1, 0);\n  helpers.doEx('\\'a+2');\n  helpers.assertCursorAt(4, 0);\n}, { value: 'a\\nb\\nc\\nd\\ne\\n'});\ntestVim('ex_write', function(cm, vim, helpers) {\n  var tmp = CodeMirror.commands.save;\n  var written;\n  var actualCm;\n  CodeMirror.commands.save = function(cm) {\n    written = true;\n    actualCm = cm;\n  };\n  // Test that w, wr, wri ... write all trigger :write.\n  var command = 'write';\n  for (var i = 1; i < command.length; i++) {\n    written = false;\n    actualCm = null;\n    helpers.doEx(command.substring(0, i));\n    eq(written, true);\n    eq(actualCm, cm);\n  }\n  CodeMirror.commands.save = tmp;\n});\ntestVim('ex_sort', function(cm, vim, helpers) {\n  helpers.doEx('sort');\n  eq('Z\\na\\nb\\nc\\nd', cm.getValue());\n}, { value: 'b\\nZ\\nd\\nc\\na'});\ntestVim('ex_sort_reverse', function(cm, vim, helpers) {\n  helpers.doEx('sort!');\n  eq('d\\nc\\nb\\na', cm.getValue());\n}, { value: 'b\\nd\\nc\\na'});\ntestVim('ex_sort_range', function(cm, vim, helpers) {\n  helpers.doEx('2,3sort');\n  eq('b\\nc\\nd\\na', cm.getValue());\n}, { value: 'b\\nd\\nc\\na'});\ntestVim('ex_sort_oneline', function(cm, vim, helpers) {\n  helpers.doEx('2sort');\n  // Expect no change.\n  eq('b\\nd\\nc\\na', cm.getValue());\n}, { value: 'b\\nd\\nc\\na'});\ntestVim('ex_sort_ignoreCase', function(cm, vim, helpers) {\n  helpers.doEx('sort i');\n  eq('a\\nb\\nc\\nd\\nZ', cm.getValue());\n}, { value: 'b\\nZ\\nd\\nc\\na'});\ntestVim('ex_sort_unique', function(cm, vim, helpers) {\n  helpers.doEx('sort u');\n  eq('Z\\na\\nb\\nc\\nd', cm.getValue());\n}, { value: 'b\\nZ\\na\\na\\nd\\na\\nc\\na'});\ntestVim('ex_sort_decimal', function(cm, vim, helpers) {\n  helpers.doEx('sort d');\n  eq('d3\\n s5\\n6\\n.9', cm.getValue());\n}, { value: '6\\nd3\\n s5\\n.9'});\ntestVim('ex_sort_decimal_negative', function(cm, vim, helpers) {\n  helpers.doEx('sort d');\n  eq('z-9\\nd3\\n s5\\n6\\n.9', cm.getValue());\n}, { value: '6\\nd3\\n s5\\n.9\\nz-9'});\ntestVim('ex_sort_decimal_reverse', function(cm, vim, helpers) {\n  helpers.doEx('sort! d');\n  eq('.9\\n6\\n s5\\nd3', cm.getValue());\n}, { value: '6\\nd3\\n s5\\n.9'});\ntestVim('ex_sort_hex', function(cm, vim, helpers) {\n  helpers.doEx('sort x');\n  eq(' s5\\n6\\n.9\\n&0xB\\nd3', cm.getValue());\n}, { value: '6\\nd3\\n s5\\n&0xB\\n.9'});\ntestVim('ex_sort_octal', function(cm, vim, helpers) {\n  helpers.doEx('sort o');\n  eq('.9\\n.8\\nd3\\n s5\\n6', cm.getValue());\n}, { value: '6\\nd3\\n s5\\n.9\\n.8'});\ntestVim('ex_sort_decimal_mixed', function(cm, vim, helpers) {\n  helpers.doEx('sort d');\n  eq('z\\ny\\nc1\\nb2\\na3', cm.getValue());\n}, { value: 'a3\\nz\\nc1\\ny\\nb2'});\ntestVim('ex_sort_decimal_mixed_reverse', function(cm, vim, helpers) {\n  helpers.doEx('sort! d');\n  eq('a3\\nb2\\nc1\\nz\\ny', cm.getValue());\n}, { value: 'a3\\nz\\nc1\\ny\\nb2'});\ntestVim('ex_sort_pattern_alpha', function(cm, vim, helpers) {\n  helpers.doEx('sort /[a-z]/');\n  eq('a3\\nb2\\nc1\\ny\\nz', cm.getValue());\n}, { value: 'z\\ny\\nc1\\nb2\\na3'});\ntestVim('ex_sort_pattern_alpha_reverse', function(cm, vim, helpers) {\n  helpers.doEx('sort! /[a-z]/');\n  eq('z\\ny\\nc1\\nb2\\na3', cm.getValue());\n}, { value: 'z\\ny\\nc1\\nb2\\na3'});\ntestVim('ex_sort_pattern_alpha_ignoreCase', function(cm, vim, helpers) {\n  helpers.doEx('sort i/[a-z]/');\n  eq('a3\\nb2\\nC1\\nY\\nz', cm.getValue());\n}, { value: 'z\\nY\\nC1\\nb2\\na3'});\ntestVim('ex_sort_pattern_alpha_longer', function(cm, vim, helpers) {\n  helpers.doEx('sort /[a-z]+/');\n  eq('a\\naa\\nab\\nade\\nadele\\nadelle\\nadriana\\nalex\\nalexandra\\nb\\nc\\ny\\nz', cm.getValue());\n}, { value: 'z\\nab\\naa\\nade\\nadelle\\nalexandra\\nalex\\nadriana\\nadele\\ny\\nc\\nb\\na'});\ntestVim('ex_sort_pattern_alpha_only', function(cm, vim, helpers) {\n  helpers.doEx('sort /^[a-z]$/');\n  eq('z1\\ny2\\na3\\nb\\nc', cm.getValue());\n}, { value: 'z1\\ny2\\na3\\nc\\nb'});\ntestVim('ex_sort_pattern_alpha_only_reverse', function(cm, vim, helpers) {\n  helpers.doEx('sort! /^[a-z]$/');\n  eq('c\\nb\\nz1\\ny2\\na3', cm.getValue());\n}, { value: 'z1\\ny2\\na3\\nc\\nb'});\ntestVim('ex_sort_pattern_alpha_num', function(cm, vim, helpers) {\n  helpers.doEx('sort /[a-z][0-9]/');\n  eq('c\\nb\\na3\\ny2\\nz1', cm.getValue());\n}, { value: 'z1\\ny2\\na3\\nc\\nb'});\n// test for :global command\ntestVim('ex_global', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doEx('g/one/s//two');\n  eq('two two\\n two two\\n two two', cm.getValue());\n  helpers.doEx('1,2g/two/s//one');\n  eq('one one\\n one one\\n two two', cm.getValue());\n}, {value: 'one one\\n one one\\n one one'});\ntestVim('ex_global_confirm', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  var onKeyDown;\n  var openDialogSave = cm.openDialog;\n  var KEYCODES = {\n    a: 65,\n    n: 78,\n    q: 81,\n    y: 89\n  };\n  // Intercept the ex command, 'global'\n  cm.openDialog = function(template, callback, options) {\n    // Intercept the prompt for the embedded ex command, 'substitute'\n    cm.openDialog = function(template, callback, options) {\n      onKeyDown = options.onKeyDown;\n    };\n    callback('g/one/s//two/gc');\n  };\n  helpers.doKeys(':');\n  var close = function() {};\n  onKeyDown({keyCode: KEYCODES.n}, '', close);\n  onKeyDown({keyCode: KEYCODES.y}, '', close);\n  onKeyDown({keyCode: KEYCODES.a}, '', close);\n  onKeyDown({keyCode: KEYCODES.q}, '', close);\n  onKeyDown({keyCode: KEYCODES.y}, '', close);\n  eq('one two\\n two two\\n one one\\n two one\\n one one', cm.getValue());\n}, {value: 'one one\\n one one\\n one one\\n one one\\n one one'});\n// Basic substitute tests.\ntestVim('ex_substitute_same_line', function(cm, vim, helpers) {\n  cm.setCursor(1, 0);\n  helpers.doEx('s/one/two/g');\n  eq('one one\\n two two', cm.getValue());\n}, { value: 'one one\\n one one'});\ntestVim('ex_substitute_alternate_separator', function(cm, vim, helpers) {\n  cm.setCursor(1, 0);\n  helpers.doEx('s#o/e#two#g');\n  eq('o/e o/e\\n two two', cm.getValue());\n}, { value: 'o/e o/e\\n o/e o/e'});\ntestVim('ex_substitute_full_file', function(cm, vim, helpers) {\n  cm.setCursor(1, 0);\n  helpers.doEx('%s/one/two/g');\n  eq('two two\\n two two', cm.getValue());\n}, { value: 'one one\\n one one'});\ntestVim('ex_substitute_input_range', function(cm, vim, helpers) {\n  cm.setCursor(1, 0);\n  helpers.doEx('1,3s/\\\\d/0/g');\n  eq('0\\n0\\n0\\n4', cm.getValue());\n}, { value: '1\\n2\\n3\\n4' });\ntestVim('ex_substitute_range_current_to_input', function(cm, vim, helpers) {\n  cm.setCursor(1, 0);\n  helpers.doEx('.,3s/\\\\d/0/g');\n  eq('1\\n0\\n0\\n4', cm.getValue());\n}, { value: '1\\n2\\n3\\n4' });\ntestVim('ex_substitute_range_input_to_current', function(cm, vim, helpers) {\n  cm.setCursor(3, 0);\n  helpers.doEx('2,.s/\\\\d/0/g');\n  eq('1\\n0\\n0\\n0\\n5', cm.getValue());\n}, { value: '1\\n2\\n3\\n4\\n5' });\ntestVim('ex_substitute_range_offset', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doEx('-1,+1s/\\\\d/0/g');\n  eq('1\\n0\\n0\\n0\\n5', cm.getValue());\n}, { value: '1\\n2\\n3\\n4\\n5' });\ntestVim('ex_substitute_range_implicit_offset', function(cm, vim, helpers) {\n  cm.setCursor(0, 0);\n  helpers.doEx('.1,.3s/\\\\d/0/g');\n  eq('1\\n0\\n0\\n0\\n5', cm.getValue());\n}, { value: '1\\n2\\n3\\n4\\n5' });\ntestVim('ex_substitute_to_eof', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doEx('.,$s/\\\\d/0/g');\n  eq('1\\n2\\n0\\n0\\n0', cm.getValue());\n}, { value: '1\\n2\\n3\\n4\\n5' });\ntestVim('ex_substitute_to_relative_eof', function(cm, vim, helpers) {\n  cm.setCursor(4, 0);\n  helpers.doEx('2,$-2s/\\\\d/0/g');\n  eq('1\\n0\\n0\\n4\\n5', cm.getValue());\n}, { value: '1\\n2\\n3\\n4\\n5' });\ntestVim('ex_substitute_range_mark', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('ma');\n  cm.setCursor(0, 0);\n  helpers.doEx('.,\\'as/\\\\d/0/g');\n  eq('0\\n0\\n0\\n4\\n5', cm.getValue());\n}, { value: '1\\n2\\n3\\n4\\n5' });\ntestVim('ex_substitute_range_mark_offset', function(cm, vim, helpers) {\n  cm.setCursor(2, 0);\n  helpers.doKeys('ma');\n  cm.setCursor(0, 0);\n  helpers.doEx('\\'a-1,\\'a+1s/\\\\d/0/g');\n  eq('1\\n0\\n0\\n0\\n5', cm.getValue());\n}, { value: '1\\n2\\n3\\n4\\n5' });\ntestVim('ex_substitute_visual_range', function(cm, vim, helpers) {\n  cm.setCursor(1, 0);\n  // Set last visual mode selection marks '< and '> at lines 2 and 4\n  helpers.doKeys('V', '2', 'j', 'v');\n  helpers.doEx('\\'<,\\'>s/\\\\d/0/g');\n  eq('1\\n0\\n0\\n0\\n5', cm.getValue());\n}, { value: '1\\n2\\n3\\n4\\n5' });\ntestVim('ex_substitute_empty_query', function(cm, vim, helpers) {\n  // If the query is empty, use last query.\n  cm.setCursor(1, 0);\n  cm.openDialog = helpers.fakeOpenDialog('1');\n  helpers.doKeys('/');\n  helpers.doEx('s//b/g');\n  eq('abb ab2 ab3', cm.getValue());\n}, { value: 'a11 a12 a13' });\ntestVim('ex_substitute_javascript', function(cm, vim, helpers) {\n  CodeMirror.Vim.setOption('pcre', false);\n  cm.setCursor(1, 0);\n  // Throw all the things that javascript likes to treat as special values\n  // into the replace part. All should be literal (this is VIM).\n  helpers.doEx('s/\\\\(\\\\d+\\\\)/$$ $\\' $` $& \\\\1/g')\n  eq('a $$ $\\' $` $& 0 b', cm.getValue());\n}, { value: 'a 0 b' });\ntestVim('ex_substitute_empty_arguments', function(cm,vim,helpers) {\n  cm.setCursor(0, 0);\n  helpers.doEx('s/a/b/g');\n  cm.setCursor(1, 0);\n  helpers.doEx('s');\n  eq('b b\\nb a', cm.getValue());\n}, {value: 'a a\\na a'});\n\n// More complex substitute tests that test both pcre and nopcre options.\nfunction testSubstitute(name, options) {\n  testVim(name + '_pcre', function(cm, vim, helpers) {\n    cm.setCursor(1, 0);\n    CodeMirror.Vim.setOption('pcre', true);\n    helpers.doEx(options.expr);\n    eq(options.expectedValue, cm.getValue());\n  }, options);\n  // If no noPcreExpr is defined, assume that it's the same as the expr.\n  var noPcreExpr = options.noPcreExpr ? options.noPcreExpr : options.expr;\n  testVim(name + '_nopcre', function(cm, vim, helpers) {\n    cm.setCursor(1, 0);\n    CodeMirror.Vim.setOption('pcre', false);\n    helpers.doEx(noPcreExpr);\n    eq(options.expectedValue, cm.getValue());\n  }, options);\n}\ntestSubstitute('ex_substitute_capture', {\n  value: 'a11 a12 a13',\n  expectedValue: 'a1111 a1212 a1313',\n  // $n is a backreference\n  expr: 's/(\\\\d+)/$1$1/g',\n  // \\n is a backreference.\n  noPcreExpr: 's/\\\\(\\\\d+\\\\)/\\\\1\\\\1/g'});\ntestSubstitute('ex_substitute_capture2', {\n  value: 'a 0 b',\n  expectedValue: 'a $00 b',\n  expr: 's/(\\\\d+)/$$$1$1/g',\n  noPcreExpr: 's/\\\\(\\\\d+\\\\)/$\\\\1\\\\1/g'});\ntestSubstitute('ex_substitute_nocapture', {\n  value: 'a11 a12 a13',\n  expectedValue: 'a$1$1 a$1$1 a$1$1',\n  expr: 's/(\\\\d+)/$$1$$1/g',\n  noPcreExpr: 's/\\\\(\\\\d+\\\\)/$1$1/g'});\ntestSubstitute('ex_substitute_nocapture2', {\n  value: 'a 0 b',\n  expectedValue: 'a $10 b',\n  expr: 's/(\\\\d+)/$$1$1/g',\n  noPcreExpr: 's/\\\\(\\\\d+\\\\)/\\\\$1\\\\1/g'});\ntestSubstitute('ex_substitute_nocapture', {\n  value: 'a b c',\n  expectedValue: 'a $ c',\n  expr: 's/b/$$/',\n  noPcreExpr: 's/b/$/'});\ntestSubstitute('ex_substitute_slash_regex', {\n  value: 'one/two \\n three/four',\n  expectedValue: 'one|two \\n three|four',\n  expr: '%s/\\\\//|'});\ntestSubstitute('ex_substitute_pipe_regex', {\n  value: 'one|two \\n three|four',\n  expectedValue: 'one,two \\n three,four',\n  expr: '%s/\\\\|/,/',\n  noPcreExpr: '%s/|/,/'});\ntestSubstitute('ex_substitute_or_regex', {\n  value: 'one|two \\n three|four',\n  expectedValue: 'ana|twa \\n thraa|faar',\n  expr: '%s/o|e|u/a/g',\n  noPcreExpr: '%s/o\\\\|e\\\\|u/a/g'});\ntestSubstitute('ex_substitute_or_word_regex', {\n  value: 'one|two \\n three|four',\n  expectedValue: 'five|five \\n three|four',\n  expr: '%s/(one|two)/five/g',\n  noPcreExpr: '%s/\\\\(one\\\\|two\\\\)/five/g'});\ntestSubstitute('ex_substitute_backslashslash_regex', {\n  value: 'one\\\\two \\n three\\\\four',\n  expectedValue: 'one,two \\n three,four',\n  expr: '%s/\\\\\\\\/,'});\ntestSubstitute('ex_substitute_slash_replacement', {\n  value: 'one,two \\n three,four',\n  expectedValue: 'one/two \\n three/four',\n  expr: '%s/,/\\\\/'});\ntestSubstitute('ex_substitute_backslash_replacement', {\n  value: 'one,two \\n three,four',\n  expectedValue: 'one\\\\two \\n three\\\\four',\n  expr: '%s/,/\\\\\\\\/g'});\ntestSubstitute('ex_substitute_multibackslash_replacement', {\n  value: 'one,two \\n three,four',\n  expectedValue: 'one\\\\\\\\\\\\\\\\two \\n three\\\\\\\\\\\\\\\\four', // 2*8 backslashes.\n  expr: '%s/,/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/g'}); // 16 backslashes.\ntestSubstitute('ex_substitute_dollar_match', {\n  value: 'one,two \\n three,four',\n  expectedValue: 'one,two ,\\n three,four',\n  expr: '%s/$/,/g'});\ntestSubstitute('ex_substitute_newline_match', {\n  value: 'one,two \\n three,four',\n  expectedValue: 'one,two , three,four',\n  expr: '%s/\\\\n/,/g'});\ntestSubstitute('ex_substitute_newline_replacement', {\n  value: 'one,two \\n three,four',\n  expectedValue: 'one\\ntwo \\n three\\nfour',\n  expr: '%s/,/\\\\n/g'});\ntestSubstitute('ex_substitute_braces_word', {\n  value: 'ababab abb ab{2}',\n  expectedValue: 'ab abb ab{2}',\n  expr: '%s/(ab){2}//g',\n  noPcreExpr: '%s/\\\\(ab\\\\)\\\\{2\\\\}//g'});\ntestSubstitute('ex_substitute_braces_range', {\n  value: 'a aa aaa aaaa',\n  expectedValue: 'a   a',\n  expr: '%s/a{2,3}//g',\n  noPcreExpr: '%s/a\\\\{2,3\\\\}//g'});\ntestSubstitute('ex_substitute_braces_literal', {\n  value: 'ababab abb ab{2}',\n  expectedValue: 'ababab abb ',\n  expr: '%s/ab\\\\{2\\\\}//g',\n  noPcreExpr: '%s/ab{2}//g'});\ntestSubstitute('ex_substitute_braces_char', {\n  value: 'ababab abb ab{2}',\n  expectedValue: 'ababab  ab{2}',\n  expr: '%s/ab{2}//g',\n  noPcreExpr: '%s/ab\\\\{2\\\\}//g'});\ntestSubstitute('ex_substitute_braces_no_escape', {\n  value: 'ababab abb ab{2}',\n  expectedValue: 'ababab  ab{2}',\n  expr: '%s/ab{2}//g',\n  noPcreExpr: '%s/ab\\\\{2}//g'});\ntestSubstitute('ex_substitute_count', {\n  value: '1\\n2\\n3\\n4',\n  expectedValue: '1\\n0\\n0\\n4',\n  expr: 's/\\\\d/0/i 2'});\ntestSubstitute('ex_substitute_count_with_range', {\n  value: '1\\n2\\n3\\n4',\n  expectedValue: '1\\n2\\n0\\n0',\n  expr: '1,3s/\\\\d/0/ 3'});\ntestSubstitute('ex_substitute_not_global', {\n  value: 'aaa\\nbaa\\ncaa',\n  expectedValue: 'xaa\\nbxa\\ncxa',\n  expr: '%s/a/x/'});\nfunction testSubstituteConfirm(name, command, initialValue, expectedValue, keys, finalPos) {\n  testVim(name, function(cm, vim, helpers) {\n    var savedOpenDialog = cm.openDialog;\n    var savedKeyName = CodeMirror.keyName;\n    var onKeyDown;\n    var recordedCallback;\n    var closed = true; // Start out closed, set false on second openDialog.\n    function close() {\n      closed = true;\n    }\n    // First openDialog should save callback.\n    cm.openDialog = function(template, callback, options) {\n      recordedCallback = callback;\n    }\n    // Do first openDialog.\n    helpers.doKeys(':');\n    // Second openDialog should save keyDown handler.\n    cm.openDialog = function(template, callback, options) {\n      onKeyDown = options.onKeyDown;\n      closed = false;\n    };\n    // Return the command to Vim and trigger second openDialog.\n    recordedCallback(command);\n    // The event should really use keyCode, but here just mock it out and use\n    // key and replace keyName to just return key.\n    CodeMirror.keyName = function (e) { return e.key; }\n    keys = keys.toUpperCase();\n    for (var i = 0; i < keys.length; i++) {\n      is(!closed);\n      onKeyDown({ key: keys.charAt(i) }, '', close);\n    }\n    try {\n      eq(expectedValue, cm.getValue());\n      helpers.assertCursorAt(finalPos);\n      is(closed);\n    } catch(e) {\n      throw e\n    } finally {\n      // Restore overridden functions.\n      CodeMirror.keyName = savedKeyName;\n      cm.openDialog = savedOpenDialog;\n    }\n  }, { value: initialValue });\n}\ntestSubstituteConfirm('ex_substitute_confirm_emptydoc',\n    '%s/x/b/c', '', '', '', makeCursor(0, 0));\ntestSubstituteConfirm('ex_substitute_confirm_nomatch',\n    '%s/x/b/c', 'ba a\\nbab', 'ba a\\nbab', '', makeCursor(0, 0));\ntestSubstituteConfirm('ex_substitute_confirm_accept',\n    '%s/a/b/cg', 'ba a\\nbab', 'bb b\\nbbb', 'yyy', makeCursor(1, 1));\ntestSubstituteConfirm('ex_substitute_confirm_random_keys',\n    '%s/a/b/cg', 'ba a\\nbab', 'bb b\\nbbb', 'ysdkywerty', makeCursor(1, 1));\ntestSubstituteConfirm('ex_substitute_confirm_some',\n    '%s/a/b/cg', 'ba a\\nbab', 'bb a\\nbbb', 'yny', makeCursor(1, 1));\ntestSubstituteConfirm('ex_substitute_confirm_all',\n    '%s/a/b/cg', 'ba a\\nbab', 'bb b\\nbbb', 'a', makeCursor(1, 1));\ntestSubstituteConfirm('ex_substitute_confirm_accept_then_all',\n    '%s/a/b/cg', 'ba a\\nbab', 'bb b\\nbbb', 'ya', makeCursor(1, 1));\ntestSubstituteConfirm('ex_substitute_confirm_quit',\n    '%s/a/b/cg', 'ba a\\nbab', 'bb a\\nbab', 'yq', makeCursor(0, 3));\ntestSubstituteConfirm('ex_substitute_confirm_last',\n    '%s/a/b/cg', 'ba a\\nbab', 'bb b\\nbab', 'yl', makeCursor(0, 3));\ntestSubstituteConfirm('ex_substitute_confirm_oneline',\n    '1s/a/b/cg', 'ba a\\nbab', 'bb b\\nbab', 'yl', makeCursor(0, 3));\ntestSubstituteConfirm('ex_substitute_confirm_range_accept',\n    '1,2s/a/b/cg', 'aa\\na \\na\\na', 'bb\\nb \\na\\na', 'yyy', makeCursor(1, 0));\ntestSubstituteConfirm('ex_substitute_confirm_range_some',\n    '1,3s/a/b/cg', 'aa\\na \\na\\na', 'ba\\nb \\nb\\na', 'ynyy', makeCursor(2, 0));\ntestSubstituteConfirm('ex_substitute_confirm_range_all',\n    '1,3s/a/b/cg', 'aa\\na \\na\\na', 'bb\\nb \\nb\\na', 'a', makeCursor(2, 0));\ntestSubstituteConfirm('ex_substitute_confirm_range_last',\n    '1,3s/a/b/cg', 'aa\\na \\na\\na', 'bb\\nb \\na\\na', 'yyl', makeCursor(1, 0));\n//:noh should clear highlighting of search-results but allow to resume search through n\ntestVim('ex_noh_clearSearchHighlight', function(cm, vim, helpers) {\n  cm.openDialog = helpers.fakeOpenDialog('match');\n  helpers.doKeys('?');\n  helpers.doEx('noh');\n  eq(vim.searchState_.getOverlay(),null,'match-highlighting wasn\\'t cleared');\n  helpers.doKeys('n');\n  helpers.assertCursorAt(0, 11,'can\\'t resume search after clearing highlighting');\n}, { value: 'match nope match \\n nope Match' });\ntestVim('ex_yank', function (cm, vim, helpers) {\n  var curStart = makeCursor(3, 0);\n  cm.setCursor(curStart);\n  helpers.doEx('y');\n  var register = helpers.getRegisterController().getRegister();\n  var line = cm.getLine(3);\n  eq(line + '\\n', register.toString());\n});\ntestVim('set_boolean', function(cm, vim, helpers) {\n  CodeMirror.Vim.defineOption('testoption', true, 'boolean');\n  // Test default value is set.\n  is(CodeMirror.Vim.getOption('testoption'));\n  try {\n    // Test fail to set to non-boolean\n    CodeMirror.Vim.setOption('testoption', '5');\n    fail();\n  } catch (expected) {}\n  // Test setOption\n  CodeMirror.Vim.setOption('testoption', false);\n  is(!CodeMirror.Vim.getOption('testoption'));\n});\ntestVim('ex_set_boolean', function(cm, vim, helpers) {\n  CodeMirror.Vim.defineOption('testoption', true, 'boolean');\n  // Test default value is set.\n  is(CodeMirror.Vim.getOption('testoption'));\n  try {\n    // Test fail to set to non-boolean\n    helpers.doEx('set testoption=22');\n    fail();\n  } catch (expected) {}\n  // Test setOption\n  helpers.doEx('set notestoption');\n  is(!CodeMirror.Vim.getOption('testoption'));\n});\ntestVim('set_string', function(cm, vim, helpers) {\n  CodeMirror.Vim.defineOption('testoption', 'a', 'string');\n  // Test default value is set.\n  eq('a', CodeMirror.Vim.getOption('testoption'));\n  try {\n    // Test fail to set non-string.\n    CodeMirror.Vim.setOption('testoption', true);\n    fail();\n  } catch (expected) {}\n  try {\n    // Test fail to set 'notestoption'\n    CodeMirror.Vim.setOption('notestoption', 'b');\n    fail();\n  } catch (expected) {}\n  // Test setOption\n  CodeMirror.Vim.setOption('testoption', 'c');\n  eq('c', CodeMirror.Vim.getOption('testoption'));\n});\ntestVim('ex_set_string', function(cm, vim, helpers) {\n  CodeMirror.Vim.defineOption('testopt', 'a', 'string');\n  // Test default value is set.\n  eq('a', CodeMirror.Vim.getOption('testopt'));\n  try {\n    // Test fail to set 'notestopt'\n    helpers.doEx('set notestopt=b');\n    fail();\n  } catch (expected) {}\n  // Test setOption\n  helpers.doEx('set testopt=c')\n  eq('c', CodeMirror.Vim.getOption('testopt'));\n  helpers.doEx('set testopt=c')\n  eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global\n  eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local\n  eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global\n  eq('c', CodeMirror.Vim.getOption('testopt')); // global\n  // Test setOption global\n  helpers.doEx('setg testopt=d')\n  eq('c', CodeMirror.Vim.getOption('testopt', cm));\n  eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));\n  eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));\n  eq('d', CodeMirror.Vim.getOption('testopt'));\n  // Test setOption local\n  helpers.doEx('setl testopt=e')\n  eq('e', CodeMirror.Vim.getOption('testopt', cm));\n  eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));\n  eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));\n  eq('d', CodeMirror.Vim.getOption('testopt'));\n});\ntestVim('ex_set_callback', function(cm, vim, helpers) {\n  var global;\n\n  function cb(val, cm, cfg) {\n    if (val === undefined) {\n      // Getter\n      if (cm) {\n        return cm._local;\n      } else {\n        return global;\n      }\n    } else {\n      // Setter\n      if (cm) {\n        cm._local = val;\n      } else {\n        global = val;\n      }\n    }\n  }\n\n  CodeMirror.Vim.defineOption('testopt', 'a', 'string', cb);\n  // Test default value is set.\n  eq('a', CodeMirror.Vim.getOption('testopt'));\n  try {\n    // Test fail to set 'notestopt'\n    helpers.doEx('set notestopt=b');\n    fail();\n  } catch (expected) {}\n  // Test setOption (Identical to the string tests, but via callback instead)\n  helpers.doEx('set testopt=c')\n  eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global\n  eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local\n  eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global\n  eq('c', CodeMirror.Vim.getOption('testopt')); // global\n  // Test setOption global\n  helpers.doEx('setg testopt=d')\n  eq('c', CodeMirror.Vim.getOption('testopt', cm));\n  eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));\n  eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));\n  eq('d', CodeMirror.Vim.getOption('testopt'));\n  // Test setOption local\n  helpers.doEx('setl testopt=e')\n  eq('e', CodeMirror.Vim.getOption('testopt', cm));\n  eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));\n  eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));\n  eq('d', CodeMirror.Vim.getOption('testopt'));\n})\ntestVim('ex_set_filetype', function(cm, vim, helpers) {\n  CodeMirror.defineMode('test_mode', function() {\n    return {token: function(stream) {\n      stream.match(/^\\s+|^\\S+/);\n    }};\n  });\n  CodeMirror.defineMode('test_mode_2', function() {\n    return {token: function(stream) {\n      stream.match(/^\\s+|^\\S+/);\n    }};\n  });\n  // Test mode is set.\n  helpers.doEx('set filetype=test_mode');\n  eq('test_mode', cm.getMode().name);\n  // Test 'ft' alias also sets mode.\n  helpers.doEx('set ft=test_mode_2');\n  eq('test_mode_2', cm.getMode().name);\n});\ntestVim('ex_set_filetype_null', function(cm, vim, helpers) {\n  CodeMirror.defineMode('test_mode', function() {\n    return {token: function(stream) {\n      stream.match(/^\\s+|^\\S+/);\n    }};\n  });\n  cm.setOption('mode', 'test_mode');\n  // Test mode is set to null.\n  helpers.doEx('set filetype=');\n  eq('null', cm.getMode().name);\n});\n\ntestVim('mapclear', function(cm, vim, helpers) {\n  CodeMirror.Vim.map('w', 'l');\n  cm.setCursor(0, 0);\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('w');\n  helpers.assertCursorAt(0, 1);\n  CodeMirror.Vim.mapclear('visual');\n  helpers.doKeys('v', 'w', 'v');\n  helpers.assertCursorAt(0, 4);\n  helpers.doKeys('w');\n  helpers.assertCursorAt(0, 5);\n  CodeMirror.Vim.mapclear();\n}, { value: 'abc abc' });\ntestVim('mapclear_context', function(cm, vim, helpers) {\n  CodeMirror.Vim.map('w', 'l', 'normal');\n  cm.setCursor(0, 0);\n  helpers.assertCursorAt(0, 0);\n  helpers.doKeys('w');\n  helpers.assertCursorAt(0, 1);\n  CodeMirror.Vim.mapclear('normal');\n  helpers.doKeys('w');\n  helpers.assertCursorAt(0, 4);\n  CodeMirror.Vim.mapclear();\n}, { value: 'abc abc' });\n\ntestVim('ex_map_key2key', function(cm, vim, helpers) {\n  helpers.doEx('map a x');\n  helpers.doKeys('a');\n  helpers.assertCursorAt(0, 0);\n  eq('bc', cm.getValue());\n  CodeMirror.Vim.mapclear();\n}, { value: 'abc' });\ntestVim('ex_unmap_key2key', function(cm, vim, helpers) {\n  helpers.doEx('map a x');\n  helpers.doEx('unmap a');\n  helpers.doKeys('a');\n  eq('vim-insert', cm.getOption('keyMap'));\n  CodeMirror.Vim.mapclear();\n}, { value: 'abc' });\ntestVim('ex_unmap_key2key_does_not_remove_default', function(cm, vim, helpers) {\n  try {\n    helpers.doEx('unmap a');\n    fail();\n  } catch (expected) {}\n  helpers.doKeys('a');\n  eq('vim-insert', cm.getOption('keyMap'));\n  CodeMirror.Vim.mapclear();\n}, { value: 'abc' });\ntestVim('ex_map_key2key_to_colon', function(cm, vim, helpers) {\n  helpers.doEx('map ; :');\n  var dialogOpened = false;\n  cm.openDialog = function() {\n    dialogOpened = true;\n  }\n  helpers.doKeys(';');\n  eq(dialogOpened, true);\n  CodeMirror.Vim.mapclear();\n});\ntestVim('ex_map_ex2key:', function(cm, vim, helpers) {\n  helpers.doEx('map :del x');\n  helpers.doEx('del');\n  helpers.assertCursorAt(0, 0);\n  eq('bc', cm.getValue());\n  CodeMirror.Vim.mapclear();\n}, { value: 'abc' });\ntestVim('ex_map_ex2ex', function(cm, vim, helpers) {\n  helpers.doEx('map :del :w');\n  var tmp = CodeMirror.commands.save;\n  var written = false;\n  var actualCm;\n  CodeMirror.commands.save = function(cm) {\n    written = true;\n    actualCm = cm;\n  };\n  helpers.doEx('del');\n  CodeMirror.commands.save = tmp;\n  eq(written, true);\n  eq(actualCm, cm);\n  CodeMirror.Vim.mapclear();\n});\ntestVim('ex_map_key2ex', function(cm, vim, helpers) {\n  helpers.doEx('map a :w');\n  var tmp = CodeMirror.commands.save;\n  var written = false;\n  var actualCm;\n  CodeMirror.commands.save = function(cm) {\n    written = true;\n    actualCm = cm;\n  };\n  helpers.doKeys('a');\n  CodeMirror.commands.save = tmp;\n  eq(written, true);\n  eq(actualCm, cm);\n  CodeMirror.Vim.mapclear();\n});\ntestVim('ex_map_key2key_visual_api', function(cm, vim, helpers) {\n  CodeMirror.Vim.map('b', ':w', 'visual');\n  var tmp = CodeMirror.commands.save;\n  var written = false;\n  var actualCm;\n  CodeMirror.commands.save = function(cm) {\n    written = true;\n    actualCm = cm;\n  };\n  // Mapping should not work in normal mode.\n  helpers.doKeys('b');\n  eq(written, false);\n  // Mapping should work in visual mode.\n  helpers.doKeys('v', 'b');\n  eq(written, true);\n  eq(actualCm, cm);\n\n  CodeMirror.commands.save = tmp;\n  CodeMirror.Vim.mapclear();\n});\ntestVim('ex_imap', function(cm, vim, helpers) {\n  CodeMirror.Vim.map('jk', '<Esc>', 'insert');\n  helpers.doKeys('i');\n  is(vim.insertMode);\n  helpers.doKeys('j', 'k');\n  is(!vim.insertMode);\n  cm.setCursor(0, 1);\n  CodeMirror.Vim.map('jj', '<Esc>', 'insert');\n  helpers.doKeys('<C-v>', '2', 'j', 'l', 'c');\n  var replacement = fillArray('f', 3);\n  cm.replaceSelections(replacement);\n  var replacement = fillArray('o', 3);\n  cm.replaceSelections(replacement);\n  eq('1fo4\\n5fo8\\nafodefg', cm.getValue());\n  helpers.doKeys('j', 'j');\n  cm.setCursor(0, 0);\n  helpers.doKeys('.');\n  eq('foo4\\nfoo8\\nfoodefg', cm.getValue());\n  CodeMirror.Vim.mapclear();\n}, { value: '1234\\n5678\\nabcdefg' });\ntestVim('ex_unmap_api', function(cm, vim, helpers) {\n  CodeMirror.Vim.map('<Alt-X>', 'gg', 'normal');\n  is(CodeMirror.Vim.handleKey(cm, \"<Alt-X>\", \"normal\"), \"Alt-X key is mapped\");\n  CodeMirror.Vim.unmap(\"<Alt-X>\", \"normal\");\n  is(!CodeMirror.Vim.handleKey(cm, \"<Alt-X>\", \"normal\"), \"Alt-X key is unmapped\");\n  CodeMirror.Vim.mapclear();\n});\n// Testing registration of functions as ex-commands and mapping to <Key>-keys\ntestVim('ex_api_test', function(cm, vim, helpers) {\n  var res=false;\n  var val='from';\n  CodeMirror.Vim.defineEx('extest','ext',function(cm,params){\n    if(params.args)val=params.args[0];\n    else res=true;\n  });\n  helpers.doEx(':ext to');\n  eq(val,'to','Defining ex-command failed');\n  CodeMirror.Vim.map('<C-CR><Space>',':ext');\n  helpers.doKeys('<C-CR>','<Space>');\n  is(res,'Mapping to key failed');\n  CodeMirror.Vim.mapclear();\n});\n// For now, this test needs to be last because it messes up : for future tests.\ntestVim('ex_map_key2key_from_colon', function(cm, vim, helpers) {\n  helpers.doEx('map : x');\n  helpers.doKeys(':');\n  helpers.assertCursorAt(0, 0);\n  eq('bc', cm.getValue());\n  CodeMirror.Vim.mapclear();\n}, { value: 'abc' });\n\ntestVim('noremap', function(cm, vim, helpers) {\n  CodeMirror.Vim.noremap(';', 'l');\n  cm.setCursor(0, 0);\n  eq('wOrd1', cm.getValue());\n  // Mapping should work in normal mode.\n  helpers.doKeys(';', 'r', '1');\n  eq('w1rd1', cm.getValue());\n  // Mapping will not work in insert mode because of no current fallback\n  // keyToKey mapping support.\n  helpers.doKeys('i', ';', '<Esc>');\n  eq('w;1rd1', cm.getValue());\n  // unmap all mappings\n  CodeMirror.Vim.mapclear();\n}, { value: 'wOrd1' });\ntestVim('noremap_swap', function(cm, vim, helpers) {\n  CodeMirror.Vim.noremap('i', 'a', 'normal');\n  CodeMirror.Vim.noremap('a', 'i', 'normal');\n  cm.setCursor(0, 0);\n  // 'a' should act like 'i'.\n  helpers.doKeys('a');\n  eqCursorPos(Pos(0, 0), cm.getCursor());\n  // ...and 'i' should act like 'a'.\n  helpers.doKeys('<Esc>', 'i');\n  eqCursorPos(Pos(0, 1), cm.getCursor());\n  // unmap all mappings\n  CodeMirror.Vim.mapclear();\n}, { value: 'foo' });\ntestVim('noremap_map_interaction', function(cm, vim, helpers) {\n  // noremap should clobber map\n  CodeMirror.Vim.map(';', 'l');\n  CodeMirror.Vim.noremap(';', 'l');\n  CodeMirror.Vim.map('l', 'j');\n  cm.setCursor(0, 0);\n  helpers.doKeys(';');\n  eqCursorPos(Pos(0, 1), cm.getCursor());\n  helpers.doKeys('l');\n  eqCursorPos(Pos(1, 1), cm.getCursor());\n  // map should be able to point to a noremap\n  CodeMirror.Vim.map('m', ';');\n  helpers.doKeys('m');\n  eqCursorPos(Pos(1, 2), cm.getCursor());\n  // unmap all mappings\n  CodeMirror.Vim.mapclear();\n}, { value: 'wOrd1\\nwOrd2' });\ntestVim('noremap_map_interaction2', function(cm, vim, helpers) {\n  // map should point to the most recent noremap\n  CodeMirror.Vim.noremap(';', 'l');\n  CodeMirror.Vim.map('m', ';');\n  CodeMirror.Vim.noremap(';', 'h');\n  cm.setCursor(0, 0);\n  helpers.doKeys('l');\n  eqCursorPos(Pos(0, 1), cm.getCursor());\n  helpers.doKeys('m');\n  eqCursorPos(Pos(0, 0), cm.getCursor());\n  // unmap all mappings\n  CodeMirror.Vim.mapclear();\n}, { value: 'wOrd1\\nwOrd2' });\n\n// Test event handlers\ntestVim('beforeSelectionChange', function(cm, vim, helpers) {\n  cm.setCursor(0, 100);\n  eqCursorPos(cm.getCursor('head'), cm.getCursor('anchor'));\n}, { value: 'abc' });\n\ntestVim('increment_binary', function(cm, vim, helpers) {\n  cm.setCursor(0, 4);\n  helpers.doKeys('<C-a>');\n  eq('0b001', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0b010', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0b001', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0b000', cm.getValue());\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-a>');\n  eq('0b001', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0b010', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0b001', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0b000', cm.getValue());\n}, { value: '0b000' });\n\ntestVim('increment_octal', function(cm, vim, helpers) {\n  cm.setCursor(0, 2);\n  helpers.doKeys('<C-a>');\n  eq('001', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('002', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('003', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('004', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('005', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('006', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('007', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('010', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('007', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('006', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('005', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('004', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('003', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('002', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('001', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('000', cm.getValue());\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-a>');\n  eq('001', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('002', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('001', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('000', cm.getValue());\n}, { value: '000' });\n\ntestVim('increment_decimal', function(cm, vim, helpers) {\n  cm.setCursor(0, 2);\n  helpers.doKeys('<C-a>');\n  eq('101', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('102', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('103', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('104', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('105', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('106', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('107', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('108', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('109', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('110', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('109', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('108', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('107', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('106', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('105', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('104', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('103', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('102', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('101', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('100', cm.getValue());\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-a>');\n  eq('101', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('102', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('101', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('100', cm.getValue());\n}, { value: '100' });\n\ntestVim('increment_decimal_single_zero', function(cm, vim, helpers) {\n  helpers.doKeys('<C-a>');\n  eq('1', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('2', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('3', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('4', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('5', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('6', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('7', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('8', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('9', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('10', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('9', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('8', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('7', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('6', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('5', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('4', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('3', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('2', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('1', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0', cm.getValue());\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-a>');\n  eq('1', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('2', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('1', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0', cm.getValue());\n}, { value: '0' });\n\ntestVim('increment_hexadecimal', function(cm, vim, helpers) {\n  cm.setCursor(0, 2);\n  helpers.doKeys('<C-a>');\n  eq('0x1', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x2', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x3', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x4', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x5', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x6', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x7', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x8', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x9', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0xa', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0xb', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0xc', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0xd', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0xe', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0xf', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x10', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x0f', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x0e', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x0d', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x0c', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x0b', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x0a', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x09', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x08', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x07', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x06', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x05', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x04', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x03', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x02', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x01', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x00', cm.getValue());\n  cm.setCursor(0, 0);\n  helpers.doKeys('<C-a>');\n  eq('0x01', cm.getValue());\n  helpers.doKeys('<C-a>');\n  eq('0x02', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x01', cm.getValue());\n  helpers.doKeys('<C-x>');\n  eq('0x00', cm.getValue());\n}, { value: '0x0' });\n"
  },
  {
    "path": "third_party/CodeMirror/theme/3024-day.css",
    "content": "/*\n\n    Name:       3024 day\n    Author:     Jan T. Sott (http://github.com/idleberg)\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-3024-day.CodeMirror { background: #f7f7f7; color: #3a3432; }\n.cm-s-3024-day div.CodeMirror-selected { background: #d6d5d4; }\n\n.cm-s-3024-day .CodeMirror-line::selection, .cm-s-3024-day .CodeMirror-line > span::selection, .cm-s-3024-day .CodeMirror-line > span > span::selection { background: #d6d5d4; }\n.cm-s-3024-day .CodeMirror-line::-moz-selection, .cm-s-3024-day .CodeMirror-line > span::-moz-selection, .cm-s-3024-day .CodeMirror-line > span > span::selection { background: #d9d9d9; }\n\n.cm-s-3024-day .CodeMirror-gutters { background: #f7f7f7; border-right: 0px; }\n.cm-s-3024-day .CodeMirror-guttermarker { color: #db2d20; }\n.cm-s-3024-day .CodeMirror-guttermarker-subtle { color: #807d7c; }\n.cm-s-3024-day .CodeMirror-linenumber { color: #807d7c; }\n\n.cm-s-3024-day .CodeMirror-cursor { border-left: 1px solid #5c5855; }\n\n.cm-s-3024-day span.cm-comment { color: #cdab53; }\n.cm-s-3024-day span.cm-atom { color: #a16a94; }\n.cm-s-3024-day span.cm-number { color: #a16a94; }\n\n.cm-s-3024-day span.cm-property, .cm-s-3024-day span.cm-attribute { color: #01a252; }\n.cm-s-3024-day span.cm-keyword { color: #db2d20; }\n.cm-s-3024-day span.cm-string { color: #fded02; }\n\n.cm-s-3024-day span.cm-variable { color: #01a252; }\n.cm-s-3024-day span.cm-variable-2 { color: #01a0e4; }\n.cm-s-3024-day span.cm-def { color: #e8bbd0; }\n.cm-s-3024-day span.cm-bracket { color: #3a3432; }\n.cm-s-3024-day span.cm-tag { color: #db2d20; }\n.cm-s-3024-day span.cm-link { color: #a16a94; }\n.cm-s-3024-day span.cm-error { background: #db2d20; color: #5c5855; }\n\n.cm-s-3024-day .CodeMirror-activeline-background { background: #e8f2ff; }\n.cm-s-3024-day .CodeMirror-matchingbracket { text-decoration: underline; color: #a16a94 !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/3024-night.css",
    "content": "/*\n\n    Name:       3024 night\n    Author:     Jan T. Sott (http://github.com/idleberg)\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-3024-night.CodeMirror { background: #090300; color: #d6d5d4; }\n.cm-s-3024-night div.CodeMirror-selected { background: #3a3432; }\n.cm-s-3024-night .CodeMirror-line::selection, .cm-s-3024-night .CodeMirror-line > span::selection, .cm-s-3024-night .CodeMirror-line > span > span::selection { background: rgba(58, 52, 50, .99); }\n.cm-s-3024-night .CodeMirror-line::-moz-selection, .cm-s-3024-night .CodeMirror-line > span::-moz-selection, .cm-s-3024-night .CodeMirror-line > span > span::-moz-selection { background: rgba(58, 52, 50, .99); }\n.cm-s-3024-night .CodeMirror-gutters { background: #090300; border-right: 0px; }\n.cm-s-3024-night .CodeMirror-guttermarker { color: #db2d20; }\n.cm-s-3024-night .CodeMirror-guttermarker-subtle { color: #5c5855; }\n.cm-s-3024-night .CodeMirror-linenumber { color: #5c5855; }\n\n.cm-s-3024-night .CodeMirror-cursor { border-left: 1px solid #807d7c; }\n\n.cm-s-3024-night span.cm-comment { color: #cdab53; }\n.cm-s-3024-night span.cm-atom { color: #a16a94; }\n.cm-s-3024-night span.cm-number { color: #a16a94; }\n\n.cm-s-3024-night span.cm-property, .cm-s-3024-night span.cm-attribute { color: #01a252; }\n.cm-s-3024-night span.cm-keyword { color: #db2d20; }\n.cm-s-3024-night span.cm-string { color: #fded02; }\n\n.cm-s-3024-night span.cm-variable { color: #01a252; }\n.cm-s-3024-night span.cm-variable-2 { color: #01a0e4; }\n.cm-s-3024-night span.cm-def { color: #e8bbd0; }\n.cm-s-3024-night span.cm-bracket { color: #d6d5d4; }\n.cm-s-3024-night span.cm-tag { color: #db2d20; }\n.cm-s-3024-night span.cm-link { color: #a16a94; }\n.cm-s-3024-night span.cm-error { background: #db2d20; color: #807d7c; }\n\n.cm-s-3024-night .CodeMirror-activeline-background { background: #2F2F2F; }\n.cm-s-3024-night .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/abcdef.css",
    "content": ".cm-s-abcdef.CodeMirror { background: #0f0f0f; color: #defdef; }\n.cm-s-abcdef div.CodeMirror-selected { background: #515151; }\n.cm-s-abcdef .CodeMirror-line::selection, .cm-s-abcdef .CodeMirror-line > span::selection, .cm-s-abcdef .CodeMirror-line > span > span::selection { background: rgba(56, 56, 56, 0.99); }\n.cm-s-abcdef .CodeMirror-line::-moz-selection, .cm-s-abcdef .CodeMirror-line > span::-moz-selection, .cm-s-abcdef .CodeMirror-line > span > span::-moz-selection { background: rgba(56, 56, 56, 0.99); }\n.cm-s-abcdef .CodeMirror-gutters { background: #555; border-right: 2px solid #314151; }\n.cm-s-abcdef .CodeMirror-guttermarker { color: #222; }\n.cm-s-abcdef .CodeMirror-guttermarker-subtle { color: azure; }\n.cm-s-abcdef .CodeMirror-linenumber { color: #FFFFFF; }\n.cm-s-abcdef .CodeMirror-cursor { border-left: 1px solid #00FF00; }\n\n.cm-s-abcdef span.cm-keyword { color: darkgoldenrod; font-weight: bold; }\n.cm-s-abcdef span.cm-atom { color: #77F; }\n.cm-s-abcdef span.cm-number { color: violet; }\n.cm-s-abcdef span.cm-def { color: #fffabc; }\n.cm-s-abcdef span.cm-variable { color: #abcdef; }\n.cm-s-abcdef span.cm-variable-2 { color: #cacbcc; }\n.cm-s-abcdef span.cm-variable-3, .cm-s-abcdef span.cm-type { color: #def; }\n.cm-s-abcdef span.cm-property { color: #fedcba; }\n.cm-s-abcdef span.cm-operator { color: #ff0; }\n.cm-s-abcdef span.cm-comment { color: #7a7b7c; font-style: italic;}\n.cm-s-abcdef span.cm-string { color: #2b4; }\n.cm-s-abcdef span.cm-meta { color: #C9F; }\n.cm-s-abcdef span.cm-qualifier { color: #FFF700; }\n.cm-s-abcdef span.cm-builtin { color: #30aabc; }\n.cm-s-abcdef span.cm-bracket { color: #8a8a8a; }\n.cm-s-abcdef span.cm-tag { color: #FFDD44; }\n.cm-s-abcdef span.cm-attribute { color: #DDFF00; }\n.cm-s-abcdef span.cm-error { color: #FF0000; }\n.cm-s-abcdef span.cm-header { color: aquamarine; font-weight: bold; }\n.cm-s-abcdef span.cm-link { color: blueviolet; }\n\n.cm-s-abcdef .CodeMirror-activeline-background { background: #314151; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/ambiance-mobile.css",
    "content": ".cm-s-ambiance.CodeMirror {\n  -webkit-box-shadow: none;\n  -moz-box-shadow: none;\n  box-shadow: none;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/ambiance.css",
    "content": "/* ambiance theme for codemirror */\n\n/* Color scheme */\n\n.cm-s-ambiance .cm-header { color: blue; }\n.cm-s-ambiance .cm-quote { color: #24C2C7; }\n\n.cm-s-ambiance .cm-keyword { color: #cda869; }\n.cm-s-ambiance .cm-atom { color: #CF7EA9; }\n.cm-s-ambiance .cm-number { color: #78CF8A; }\n.cm-s-ambiance .cm-def { color: #aac6e3; }\n.cm-s-ambiance .cm-variable { color: #ffb795; }\n.cm-s-ambiance .cm-variable-2 { color: #eed1b3; }\n.cm-s-ambiance .cm-variable-3, .cm-s-ambiance .cm-type { color: #faded3; }\n.cm-s-ambiance .cm-property { color: #eed1b3; }\n.cm-s-ambiance .cm-operator { color: #fa8d6a; }\n.cm-s-ambiance .cm-comment { color: #555; font-style:italic; }\n.cm-s-ambiance .cm-string { color: #8f9d6a; }\n.cm-s-ambiance .cm-string-2 { color: #9d937c; }\n.cm-s-ambiance .cm-meta { color: #D2A8A1; }\n.cm-s-ambiance .cm-qualifier { color: yellow; }\n.cm-s-ambiance .cm-builtin { color: #9999cc; }\n.cm-s-ambiance .cm-bracket { color: #24C2C7; }\n.cm-s-ambiance .cm-tag { color: #fee4ff; }\n.cm-s-ambiance .cm-attribute { color: #9B859D; }\n.cm-s-ambiance .cm-hr { color: pink; }\n.cm-s-ambiance .cm-link { color: #F4C20B; }\n.cm-s-ambiance .cm-special { color: #FF9D00; }\n.cm-s-ambiance .cm-error { color: #AF2018; }\n\n.cm-s-ambiance .CodeMirror-matchingbracket { color: #0f0; }\n.cm-s-ambiance .CodeMirror-nonmatchingbracket { color: #f22; }\n\n.cm-s-ambiance div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); }\n.cm-s-ambiance.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }\n.cm-s-ambiance .CodeMirror-line::selection, .cm-s-ambiance .CodeMirror-line > span::selection, .cm-s-ambiance .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-ambiance .CodeMirror-line::-moz-selection, .cm-s-ambiance .CodeMirror-line > span::-moz-selection, .cm-s-ambiance .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }\n\n/* Editor styling */\n\n.cm-s-ambiance.CodeMirror {\n  line-height: 1.40em;\n  color: #E6E1DC;\n  background-color: #202020;\n  -webkit-box-shadow: inset 0 0 10px black;\n  -moz-box-shadow: inset 0 0 10px black;\n  box-shadow: inset 0 0 10px black;\n}\n\n.cm-s-ambiance .CodeMirror-gutters {\n  background: #3D3D3D;\n  border-right: 1px solid #4D4D4D;\n  box-shadow: 0 10px 20px black;\n}\n\n.cm-s-ambiance .CodeMirror-linenumber {\n  text-shadow: 0px 1px 1px #4d4d4d;\n  color: #111;\n  padding: 0 5px;\n}\n\n.cm-s-ambiance .CodeMirror-guttermarker { color: #aaa; }\n.cm-s-ambiance .CodeMirror-guttermarker-subtle { color: #111; }\n\n.cm-s-ambiance .CodeMirror-cursor { border-left: 1px solid #7991E8; }\n\n.cm-s-ambiance .CodeMirror-activeline-background {\n  background: none repeat scroll 0% 0% rgba(255, 255, 255, 0.031);\n}\n\n.cm-s-ambiance.CodeMirror,\n.cm-s-ambiance .CodeMirror-gutters {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAQAAAAHUWYVAABFFUlEQVQYGbzBCeDVU/74/6fj9HIcx/FRHx9JCFmzMyGRURhLZIkUsoeRfUjS2FNDtr6WkMhO9sm+S8maJfu+Jcsg+/o/c+Z4z/t97/vezy3z+z8ekGlnYICG/o7gdk+wmSHZ1z4pJItqapjoKXWahm8NmV6eOTbWUOp6/6a/XIg6GQqmenJ2lDHyvCFZ2cBDbmtHA043VFhHwXxClWmeYAdLhV00Bd85go8VmaFCkbVkzlQENzfBDZ5gtN7HwF0KDrTwJ0dypSOzpaKCMwQHKTIreYIxlmhXTzTWkVm+LTynZhiSBT3RZQ7aGfjGEd3qyXQ1FDymqbKxpspERQN2MiRjNZlFFQXfCNFm9nM1zpAsoYjmtRTc5ajwuaXc5xrWskT97RaKzAGe5ARHhVUsDbjKklziiX5WROcJwSNCNI+9w1Jwv4Zb2r7lCMZ4oq5C0EdTx+2GzNuKpJ+iFf38JEWkHJn9DNF7mmBDITrWEg0VWL3pHU20tSZnuqWu+R3BtYa8XxV1HO7GyD32UkOpL/yDloINFTmvtId+nmAjxRw40VMwVKiwrKLE4bK5UOVntYwhOcSSXKrJHKPJedocpGjVz/ZMIbnYUPB10/eKCrs5apqpgVmWzBYWpmtKHecJPjaUuEgRDDaU0oZghCJ6zNMQ5ZhDYx05r5v2muQdM0EILtXUsaKiQX9WMEUotagQzFbUNN6NUPC2nm5pxEWGCjMc3GdJHjSU2kORLK/JGSrkfGEIjncU/CYUnOipoYemwj8tST9NsJmB7TUVXtbUtXATJVZXBMvYeTXJfobgJUPmGMP/yFaWonaa6BcFO3nqcIqCozSZoZoSr1g4zJOzuyGnxTEX3lUEJ7WcZgme8ddaWvWJo2AJR9DZU3CUIbhCSG6ybSwN6qtJVnCU2svDTP2ZInOw2cBTrqtQahtNZn9NcJ4l2NaSmSkkP1noZWnVwkLmdUPOwLZEwy2Z3S3R+4rIG9hcbpPXHFVWcQdZkn2FOta3cKWQnNRC5g1LsJah4GCzSVsKnCOY5OAFRTBekyyryeyilhFKva75r4Mc0aWanGEaThcy31s439KKxTzJYY5WTHPU1FtIHjQU3Oip4xlNzj/lBw23dYZVliQa7WAXf4shetcQfatI+jWRDBPmyNeW6A1P5kdDgyYJlba0BIM8BZu1JfrFwItyjcAMR3K0BWOIrtMEXyhyrlVEx3ui5dUBjmB/Q3CXW85R4mBD0s7B+4q5tKUjOlb9qqmhi5AZ6GFIC5HXtOobdYGlVdMVbNJ8toNTFcHxnoL+muBagcctjWnbNMuR00uI7nQESwg5q2qqrKWIfrNUmeQocY6HuyxJV02wj36w00yhpmUFenv4p6fUkZYqLyuinx2RGOjhCXYyJF84oiU00YMOOhhquNdfbOB7gU88pY4xJO8LVdp6/q2voeB4R04vIdhSE40xZObx1HGGJ/ja0LBthFInKaLPPFzuCaYaoj8JjPME8yoyxo6zlBqkiUZYgq00OYMswbWO5NGmq+xhipxHLRW29ARjNKXO0wRnear8XSg4XFPLKEPUS1GqvyLwiuBUoa7zpZ0l5xxFwWmWZC1H5h5FwU8eQ7K+g8UcVY6TMQreVQT/8uQ8Z+ALIXnSEa2pYZQneE9RZbSBNYXfWYJzW/h/4j4Dp1tYVcFIC5019Vyi4ThPqSFCzjGWaHQTBU8q6vrVwgxP9Lkm840imWKpcLCjYTtrKuwvsKSnrvHCXGkSMk9p6lhckfRpIeis+N2PiszT+mFLspyGleUhDwcLrZqmyeylxwjBcKHEapqkmyangyLZRVOijwOtCY5SsG5zL0OwlCJ4y5KznF3EUNDDrinwiyLZRzOXtlBbK5ITHFGLp8Q0R6ab6mS7enI2cFrxOyHvOCFaT1HThS1krjCwqWeurCkk+willhCC+RSZnRXBiZaC5RXRIZYKp2lyfrHwiKPKR0JDzrdU2EFgpidawlFDR6FgXUMNa+g1FY3bUQh2cLCwosRdnuQTS/S+JVrGLeWIvtQUvONJxlqSQYYKpwoN2kaocLjdVsis4Mk80ESF2YpSkzwldjHkjFCUutI/r+EHDU8oCs6yzL3PhWiEooZdFMkymlas4AcI3KmoMMNSQ3tHzjGWCrcJJdYyZC7QFGwjRL9p+MrRkAGWzIaWCn9W0F3TsK01c2ZvQw0byvxuQU0r1lM0qJO7wW0kRIMdDTtXEdzi4VIh+EoIHm0mWtAtpCixlabgn83fKTI7anJe9ST7WIK1DMGpQmYeA58ImV6ezOGOzK2Kgq01pd60cKWiUi9Lievb/0vIDPHQ05Kzt4ddPckQBQtoaurjyHnek/nKzpQLrVgKPjIkh2v4uyezpv+Xoo7fPFXaGFp1vaLKxQ4uUpQQS5VuQs7BCq4xRJv7fwpVvvFEB3j+620haOuocqMhWd6TTPAEx+mdFNGHdranFe95WrWmIvlY4F1Dle2ECgc6cto7SryuqGGGha0tFQ5V53migUKmg6XKAo4qS3mik+0OZpAhOLeZKicacgaYcyx5hypYQE02ZA4xi/pNhOQxR4klNKyqacj+mpxnLTnnGSo85++3ZCZq6lrZkXlGEX3o+C9FieccJbZWVFjC0Yo1FZnJhoYMFoI1hEZ9r6hwg75HwzBNhbZCdJEfJwTPGzJvaKImw1yYX1HDAmpXR+ZJQ/SmgqMNVQb5vgamGwLtt7VwvP7Qk1xpiM5x5Cyv93E06MZmgs0Nya2azIKOYKCGBQQW97RmhKNKF02JZqHEJ4o58qp7X5EcZmc56trXEqzjCBZ1MFGR87Ql2tSTs6CGxS05PTzRQorkbw7aKoKXFDXsYW42VJih/q+FP2BdTzDTwVqOYB13liM50vG7wy28qagyuIXMeQI/Oqq8bcn5wJI50xH00CRntyfpL1T4hydYpoXgNiFzoIUTDZnLNRzh4TBHwbYGDvZkxmlyJloyr6tRihpeUG94GnKtIznREF0tzJG/OOr73JBcrSh1k6WuTprgLU+mnSGnv6Zge0NNz+kTDdH8nuAuTdJDCNb21LCiIuqlYbqGzT3RAoZofQfjFazkqeNWdYaGvYTM001EW2oKPvVk1ldUGSgUtHFwjKM1h9jnFcmy5lChoLNaQMGGDsYbKixlaMBmmsx1QjCfflwTfO/gckW0ruZ3jugKR3R5W9hGUWqCgxuFgsuaCHorotGKzGaeZB9DMsaTnKCpMtwTvOzhYk0rdrArKCqcaWmVk1+F372ur1YkKxgatI8Qfe1gIX9wE9FgS8ESmuABIXnRUbCapcKe+nO7slClSZFzpV/LkLncEb1qiO42fS3R855Su2mCLh62t1SYZZYVmKwIHjREF2uihTzB20JOkz7dkxzYQnK0UOU494wh+VWRc6Un2kpTaVgLDFEkJ/uhzRcI0YKGgpGWOlocBU/a4fKoJ/pEaNV6jip3+Es9VXY078rGnmAdf7t9ylPXS34RBSuYPs1UecZTU78WanhBCHpZ5sAoTz0LGZKjPf9TRypqWEiTvOFglL1fCEY3wY/++rbk7C8bWebA6p6om6PgOL2kp44TFJlVNBXae2rqqdZztOJpT87GQsE9jqCPIe9VReZuQ/CIgacsyZdCpIScSYqcZk8r+nsyCzhyfhOqHGOIvrLknC8wTpFcaYiGC/RU1NRbUeUpocQOnkRpGOrIOcNRx+1uA0UrzhSSt+VyS3SJpnFWkzNDqOFGIWcfR86DnmARTQ1HKIL33ExPiemeOhYSSjzlSUZZuE4TveoJLnBUOFof6KiysCbnAEcZgcUNTDOwkqWu3RWtmGpZwlHhJENdZ3miGz0lJlsKnjbwqSHQjpxnFDlTLLwqJPMZMjd7KrzkSG7VsxXBZE+F8YZkb01Oe00yyRK9psh5SYh29ySPKBo2ylNht7ZkZnsKenjKNJu9PNEyZpaCHv4Kt6RQsLvAVp7M9kIimmCUwGeWqLMmGuIotYMmWNpSahkhZw9FqZsVnKJhsjAHvtHMsTM9fCI06Dx/u3vfUXCqfsKRc4oFY2jMsoo/7DJDwZ1CsIKnJu+J9ldkpmiCxQx1rWjI+T9FwcWWzOuaYH0Hj7klNRVWEQpmaqosakiGNTFHdjS/qnUdmf0NJW5xsL0HhimCCZZSRzmSPTXJQ4aaztAwtZnoabebJ+htCaZ7Cm535ByoqXKbX1WRc4Eh2MkRXWzImVc96Cj4VdOKVxR84VdQsIUM8Psoou2byVHyZFuq7O8otbSQ2UAoeEWTudATLGSpZzVLlXVkPU2Jc+27lsw2jmg5T5VhbeE3BT083K9WsTTkFU/Osi0rC5lRlpwRHUiesNS0sOvmqGML1aRbPAxTJD9ZKtxuob+hhl8cwYGWpJ8nub7t5p6coYbMovZ1BTdaKn1jYD6h4GFDNFyT/Kqe1XCXphXHOKLZmuRSRdBPEfVUXQzJm5YGPGGJdvAEr7hHNdGZnuBvrpciGmopOLf5N0uVMy0FfYToJk90uUCbJupaVpO53UJXR2bVpoU00V2KOo4zMFrBd0Jtz2pa0clT5Q5L8IpQ177mWQejPMEJhuQjS10ref6HHjdEhy1P1EYR7GtO0uSsKJQYLiTnG1rVScj5lyazpqWGl5uBbRWl7m6ixGOOnEsMJR7z8J0n6KMnCdxhiNYQCoZ6CmYLnO8omC3MkW3bktlPmEt/VQQHejL3+dOE5FlPdK/Mq8hZxxJtLyRrepLThYKbLZxkSb5W52vYxNOaOxUF0yxMUPwBTYqCzy01XayYK0sJyWBLqX0MwU5CzoymRzV0EjjeUeLgDpTo6ij42ZAzvD01dHUUTPLU96MdLbBME8nFBn7zJCMtJcZokn8YoqU0FS5WFKyniHobguMcmW8N0XkWZjkyN3hqOMtS08r+/xTBwpZSZ3qiVRX8SzMHHjfUNFjgHEPmY9PL3ykEzxkSre/1ZD6z/NuznuB0RcE1TWTm9zRgfUWVJiG6yrzgmWPXC8EAR4Wxhlad0ZbgQyEz3pG5RVEwwDJH2mgKpjcTiCOzn1lfUWANFbZ2BA8balnEweJC9J0iuaeZoI+ippFCztEKVvckR2iice1JvhVytrQwUAZpgsubCPaU7xUe9vWnaOpaSBEspalykhC9bUlOMpT42ZHca6hyrqKmw/wMR8H5ZmdFoBVJb03O4UL0tSNnvIeRmkrLWqrs78gcrEn2tpcboh0UPOW3UUR9PMk4T4nnNKWmCjlrefhCwxRNztfmIQVdDElvS4m1/WuOujoZCs5XVOjtKPGokJzsYCtFYoWonSPT21DheU/wWhM19FcElwqNGOsp9Q8N/cwXaiND1MmeL1Q5XROtYYgGeFq1aTMsoMmcrKjQrOFQTQ1fmBYhmW6o8Jkjc7iDJRTBIo5kgJD5yMEYA3srCg7VFKwiVJkmRCc5ohGOKhsYMn/XBLdo5taZjlb9YAlGWRimqbCsoY7HFAXLa5I1HPRxMMsQDHFkWtRNniqT9UEeNjcE7RUlrCJ4R2CSJuqlKHWvJXjAUNcITYkenuBRB84TbeepcqTj3zZyFJzgYQdHnqfgI0ddUwS6GqWpsKWhjq9cV0vBAEMN2znq+EBfIWT+pClYw5xsTlJU6GeIBsjGmmANTzJZiIYpgrM0Oa8ZMjd7NP87jxhqGOhJlnQtjuQpB+8aEE00wZFznSJPyHxgH3HkPOsJFvYk8zqCHzTs1BYOa4J3PFU+UVRZxlHDM4YavlNUuMoRveiZA2d7grMNc2g+RbSCEKzmgYsUmWmazFJyoiOZ4KnyhKOGRzWJa0+moyV4TVHDzn51Awtqaphfk/lRQ08FX1iiqxTB/kLwd0VynKfEvI6cd4XMV5bMhZ7gZUWVzYQ6Nm2BYzxJbw3bGthEUUMfgbGeorae6DxHtJoZ6alhZ0+ytiVoK1R4z5PTrOECT/SugseEOlb1MMNR4VRNcJy+V1Hg9ONClSZFZjdHlc6W6FBLdJja2MC5hhpu0DBYEY1TFGwiFAxRRCsYkiM9JRb0JNMVkW6CZYT/2EiTGWmo8k+h4FhDNE7BvppoTSFnmCV5xZKzvcCdDo7VVPnIU+I+Rc68juApC90MwcFCsJ5hDqxgScYKreruyQwTqrzoqDCmhWi4IbhB0Yrt3RGa6GfDv52rKXWhh28dyZaWUvcZeMTBaZoSGyiCtRU5J8iviioHaErs7Jkj61syVzTTgOcUOQ8buFBTYWdL5g3T4qlpe0+wvD63heAXRfCCIed9RbCsp2CiI7raUOYOTU13N8PNHvpaGvayo4a3LLT1lDrVEPT2zLUlheB1R+ZTRfKWJ+dcocLJfi11vyJ51lLqJ0WD7tRwryezjiV5W28uJO9qykzX8JDe2lHl/9oyBwa2UMfOngpXCixvKdXTk3wrsKmiVYdZIqsoWEERjbcUNDuiaQomGoIbFdEHmsyWnuR+IeriKDVLnlawlyNHKwKlSU631PKep8J4Q+ayjkSLKYLhalNHlYvttb6fHm0p6OApsZ4l2VfdqZkjuysy6ysKLlckf1KUutCTs39bmCgEyyoasIWlVaMF7mgmWtBT8Kol5xpH9IGllo8cJdopcvZ2sImlDmMIbtDk3KIpeNiS08lQw11NFPTwVFlPP6pJ2gvRfI7gQUfmNAtf6Gs0wQxDsKGlVBdF8rCa3jzdwMaGHOsItrZk7hAyOzpK9VS06j5F49b0VNGOOfKs3lDToMsMBe9ZWtHFEgxTJLs7qrygKZjUnmCYoeAqeU6jqWuLJup4WghOdvCYJnrSkSzoyRkm5M2StQwVltPkfCAk58tET/CSg+8MUecmotMEnhBKfWBIZsg2ihruMJQaoIm+tkTLKEqspMh00w95gvFCQRtDwTT1gVDDSEVdlwqZfxoQRbK0g+tbiBZxzKlpnpypejdDwTaeOvorMk/IJE10h9CqRe28hhLbe0pMsdSwv4ZbhKivo2BjDWfL8UKJgeavwlwb5KlwhyE4u4XkGE2ytZCznKLCDZZq42VzT8HLCrpruFbIfOIINmh/qCdZ1ZBc65kLHR1Bkyf5zn6pN3SvGKIlFNGplhrO9QSXanLOMQTLCa0YJCRrCZm/CZmrLTm7WzCK4GJDiWUdFeYx1LCFg3NMd0XmCuF3Y5rITLDUsYS9zoHVzwnJoYpSTQoObyEzr4cFBNqYTopoaU/wkyLZ2lPhX/5Y95ulxGTV7KjhWrOZgl8MyUUafjYraNjNU1N3IWcjT5WzWqjwtoarHSUObGYO3GCJZpsBlnJGPd6ZYLyl1GdCA2625IwwJDP8GUKymbzuyPlZlvTUsaUh5zFDhRWFzPKKZLAlWdcQbObgF9tOqOsmB1dqcqYJmWstFbZRRI9poolmqiLnU0POvxScpah2iSL5UJNzgScY5+AuIbpO0YD3NCW+dLMszFSdFCWGqG6eVq2uYVNDdICGD6W7EPRWZEY5gpsE9rUkS3mijzzJnm6UpUFXG1hCUeVoS5WfNcFpblELL2qqrCvMvRfd45oalvKU2tiQ6ePJOVMRXase9iTtLJztPxJKLWpo2CRDcJwn2sWSLKIO1WQWNTCvpVUvOZhgSC40JD0dOctaSqzkCRbXsKlb11Oip6PCJ0IwSJM31j3akRxlP7Rwn6aGaUL0qiLnJkvB3xWZ2+Q1TfCwpQH3G0o92UzmX4o/oJNQMMSQc547wVHhdk+VCw01DFYEnTxzZKAm74QmeNNR1w6WzEhNK15VJzuCdxQ53dRUDws5KvwgBMOEgpcVNe0hZI6RXT1Jd0cyj5nsaEAHgVmGaJIlWdsc5Ui2ElrRR6jrRAttNMEAIWrTDFubkZaok7/AkzfIwfuWVq0jHzuCK4QabtLUMVPB3kJ0oyHTSVFlqMALilJf2Rf8k5aaHtMfayocLBS8L89oKoxpJvnAkDPa0qp5DAUTHKWmCcnthlou8iCKaFFLHWcINd1nyIwXqrSxMNmSs6KmoL2QrKuWtlQ5V0120xQ5vRyZS1rgFkWwhiOwiuQbR0OOVhQM9iS3tiXp4RawRPMp5tDletOOBL95MpM01dZTBM9pkn5qF010rIeHFcFZhmSGpYpTsI6nwhqe5C9ynhlpp5ophuRb6WcJFldkVnVEwwxVfrVkvnWUuNLCg5bgboFHPDlDPDmnK7hUrWiIbjadDclujlZcaokOFup4Ri1kacV6jmrrK1hN9bGwpKEBQ4Q6DvIUXOmo6U5LqQM6EPyiKNjVkPnJkDPNEaxhiFay5ExW1NXVUGqcpYYdPcGiCq7z/TSlbhL4pplWXKd7NZO5QQFrefhRQW/NHOsqcIglc4UhWklR8K0QzbAw08CBDnpbgqXdeD/QUsM4RZXDFBW6WJKe/mFPdH0LtBgiq57wFLzlyQzz82qYx5D5WJP5yVJDW01BfyHnS6HKO/reZqId1WGa4Hkh2kWodJ8i6KoIPlAj2hPt76CzXsVR6koPRzWTfKqIentatYpQw2me4AA3y1Kind3SwoOKZDcFXTwl9tWU6mfgRk9d71sKtlNwrjnYw5tC5n5LdKiGry3JKNlHEd3oaMCFHrazBPMp/uNJ+V7IudcSbeOIdjUEdwl0VHCOZo5t6YluEuaC9mQeMgSfOyKnYGFHcIeQ84yQWbuJYJpZw5CzglDH7gKnWqqM9ZTaXcN0TeYhR84eQtJT76JJ1lREe7WnnvsMmRc9FQ7SBBM9mV3lCUdmHk/S2RAMt0QjFNFqQpWjDPQ01DXWUdDBkXziKPjGEP3VP+zIWU2t7im41FOloyWzn/L6dkUy3VLDaZ6appgDLHPjJEsyvJngWEPUyVBiAaHCTEXwrLvSEbV1e1gKJniicWorC1MUrVjB3uDhJE/wgSOzk1DXpk0k73qCM8xw2UvD5kJmDUfOomqMpWCkJRlvKXGmoeBm18USjVIk04SClxTB6YrgLAPLWYK9HLUt5cmc0vYES8GnTeRc6skZbQkWdxRsIcyBRzx1DbTk9FbU0caTPOgJHhJKnOGIVhQqvKmo0llRw9sabrZkDtdg3PqaKi9oatjY8B+G371paMg6+mZFNNtQ04mWBq3rYLOmtWWQp8KJnpy9DdFensyjdqZ+yY40VJlH8wcdLzC8PZnvHMFUTZUrDTkLyQaGus5X5LzpYAf3i+e/ZlhqGqWhh6Ou6xTR9Z6oi5AZZtp7Mj2EEm8oSpxiYZCHU/1fbGdNNNRRoZMhmilEb2gqHOEJDtXkHK/JnG6IrvbPCwV3NhONVdS1thBMs1T4QOBcTWa2IzhMk2nW5Kyn9tXUtpv9RsG2msxk+ZsQzRQacJncpgke0+T8y5Fzj8BiGo7XlJjaTIlpQs7KFjpqGnKuoyEPeIKnFMkZHvopgh81ySxNFWvJWcKRs70j2FOT012IllEEO1n4pD1513Yg2ssQPOThOkvyrqHUdEXOSEsihmBbTbKX1kLBPWqWkLOqJbjB3GBIZmoa8qWl4CG/iZ7oiA72ZL7TJNeZUY7kFQftDcHHluBzRbCegzMtrRjVQpX2lgoPKKLJAkcbMl01XK2p7yhL8pCBbQ3BN2avJgKvttcrWDK3CiUOVxQ8ZP+pqXKyIxnmBymCg5vJjNfkPK4+c8cIfK8ocVt7kmfd/I5SR1hKvCzUtb+lhgc00ZaO6CyhIQP1Uv4yIZjload72PXX0OIJvnFU+0Zf6MhsJwTfW0r0UwQfW4LNLZl5HK261JCZ4qnBaAreVAS3WrjV0LBnNDUNNDToCEeFfwgcb4gOEqLRhirWkexrCEYKVV711DLYEE1XBEsp5tpTGjorkomKYF9FDXv7fR3BGwbettSxnyL53MBPjsxDZjMh+VUW9NRxq1DhVk+FSxQcaGjV9Pawv6eGByw5qzoy7xk4RsOShqjJwWKe/1pEEfzkobeD/dQJmpqedcyBTy2sr4nGNRH0c0SPWTLrqAc0OQcb/gemKgqucQT7ySWKCn2EUotoCvpZct7RO2sy/QW0IWcXd7pQRQyZVwT2USRO87uhjioTLKV2brpMUcMQRbKH/N2T+UlTpaMls6cmc6CCNy3JdYYSUzzJQ4oSD3oKLncULOiJvjBEC2oqnCJkJluCYy2ZQ5so9YYlZ1VLlQU1mXEW1jZERwj/MUSRc24TdexlqLKfQBtDTScJUV8FszXBEY5ktpD5Ur9hYB4Nb1iikw3JoYpkKX+RodRKFt53MMuRnKSpY31PwYaGaILh3wxJGz9TkTPEETxoCWZrgvOlmyMzxFEwVJE5xZKzvyJ4WxEc16Gd4Xe3Weq4XH2jKRikqOkGQ87hQnC7wBmGYLAnesX3M+S87eFATauuN+Qcrh7xIxXJbUIdMw3JGE3ylCWzrieaqCn4zhGM19TQ3z1oH1AX+pWEqIc7wNGAkULBo/ZxRaV9NNyh4Br3rCHZzbzmSfawBL0dNRwpW1kK9mxPXR9povcdrGSZK9c2k0xwFGzjuniCtRSZCZ6ccZ7gaktmgAOtKbG/JnOkJrjcQTdFMsxRQ2cLY3WTIrlCw1eWKn8R6pvt4GFDso3QoL4a3nLk3G6JrtME3dSenpx7PNFTmga0EaJTLQ061sEeQoWXhSo9LTXsaSjoJQRXeZLtDclbCrYzfzHHeaKjHCVOUkQHO3JeEepr56mhiyaYYKjjNU+Fed1wS5VlhWSqI/hYUdDOkaxiKehoyOnrCV5yBHtbWFqTHCCwtpDcYolesVR5yUzTZBb3RNMd0d6WP+SvhuBmRcGxnuQzT95IC285cr41cLGQ6aJJhmi4TMGempxeimBRQw1tFKV+8jd6KuzoSTqqDxzRtpZkurvKEHxlqXKRIjjfUNNXQsNOsRScoWFLT+YeRZVD3GRN0MdQcKqQjHDMrdGGVu3iYJpQx3WGUvfbmxwFfR20WBq0oYY7LMFhhgYtr8jpaEnaOzjawWWaTP8mMr0t/EPDPoqcnxTBI5o58L7uoWnMrpoqPwgVrlAUWE+V+TQl9rawoyP6QGAlQw2TPRX+YSkxyBC8Z6jhHkXBgQL7WII3DVFnRfCrBfxewv9D6xsyjys4VkhWb9pUU627JllV0YDNHMku/ldNMMXDEo4aFnAkk4U6frNEU4XgZUPmEKHUl44KrzmYamjAbh0JFvGnaTLPu1s9jPCwjFpYiN7z1DTOk/nc07CfDFzmCf7i+bfNHXhDtLeBXzTBT5rkMvWOIxpl4EMh2LGJBu2syDnAEx2naEhHDWMMzPZEhygyS1mS5RTJr5ZkoKbEUoYqr2kqdDUE8ztK7OaIntJkFrIECwv8LJTaVx5XJE86go8dFeZ3FN3rjabCAYpoYEeC9zzJVULBbmZhDyd7ko09ydpNZ3nm2Kee4FPPXHnYEF1nqOFEC08LUVcDvYXkJHW8gTaKCk9YGOeIJhqiE4ToPEepdp7IWFjdwnWaufGMwJJCMtUTTBBK9BGCOy2tGGrJTHIwyEOzp6aPzNMOtlZkDvcEWpP5SVNhfkvDxhmSazTJXYrM9U1E0xwFVwqZQwzJxw6+kGGGUj2FglGGmnb1/G51udRSMNlTw6GGnCcUwVcOpmsqTHa06o72sw1RL02p9z0VbnMLOaIX3QKaYKSCFQzBKEUNHTSc48k53RH9wxGMtpQa5KjjW0W0n6XCCCG4yxNNdhQ4R4l1Ff+2sSd6UFHiIEOyqqFgT01mEUMD+joy75jPhOA+oVVLm309FR4yVOlp4RhLiScNmSmaYF5Pw0STrOIoWMSR2UkRXOMp+M4SHW8o8Zoi6OZgjKOaFar8zZDzkWzvKOjkKBjmCXby8JahhjXULY4KlzgKLvAwxVGhvyd4zxB1d9T0piazmKLCVZY5sKiD0y2ZSYrkUEPUbIk+dlQ4SJHTR50k1DPaUWIdTZW9NJwnJMOECgd7ou/MnppMJ02O1VT4Wsh85MnZzcFTngpXGKo84qmwgKbCL/orR/SzJ2crA+t6Mp94KvxJUeIbT3CQu1uIdlQEOzlKfS3UMcrTiFmOuroocrZrT2AcmamOKg8YomeEKm/rlT2sociMaybaUlFhuqHCM2qIJ+rg4EcDFymiDSxzaHdPcpE62pD5kyM5SBMoA1PaUtfIthS85ig1VPiPPYXgYEMNk4Qq7TXBgo7oT57gPUdwgCHzhIVFPFU6OYJzHAX9m5oNrVjeE61miDrqQ4VSa1oiURTsKHC0IfjNwU2WzK6eqK8jWln4g15TVBnqmDteCJ501PGAocJhhqjZdtBEB6lnhLreFJKxmlKbeGrqLiSThVIbCdGzloasa6lpMQXHCME2boLpJgT7yWaemu6wBONbqGNVRS0PKIL7LckbjmQtR7K8I5qtqel+T/ChJTNIKLjdUMNIRyvOEko9YYl2cwQveBikCNawJKcLBbc7+JM92mysNvd/Fqp8a0k6CNEe7cnZrxlW0wQXaXjaktnRwNOGZKYiONwS7a1JVheq3WgJHlQUGKHKmp4KAxXR/ULURcNgoa4zhKSLpZR3kxRRb0NmD0OFn+UCS7CzI1nbP6+o4x47QZE5xRCt3ZagnYcvmpYQktXdk5YKXTzBC57kKEe0VVuiSYqapssMS3C9p2CKkHOg8B8Pa8p5atrIw3qezIWanMGa5HRDNF6RM9wcacl0N+Q8Z8hsIkSnaIIdHRUOEebAPy1zbCkhM062FCJtif7PU+UtoVXzWKqM1PxXO8cfdruhFQ/a6x3JKYagvVDhQEtNiyiiSQ7OsuRsZUku0CRNDs4Sog6KKjsZgk2bYJqijgsEenoKeniinRXBn/U3lgpPdyDZynQx8IiioMnCep5Ky8mjGs6Wty0l1hUQTcNWswS3WRp2kCNZwJG8omG8JphPUaFbC8lEfabwP7VtM9yoaNCAjpR41VNhrD9LkbN722v0CoZMByFzhaW+MyzRYEWFDQwN2M4/JiT76PuljT3VU/A36eaIThb+R9oZGOAJ9tewkgGvqOMNRWYjT/Cwu99Q8LqDE4TgbLWxJ1jaDDAERsFOFrobgjUsBScaguXU8kKm2RL19tRypSHnHNlHiIZqgufs4opgQdVdwxBNNFBR6kVFqb8ogimOzB6a6HTzrlDHEpYaxjiiA4TMQobkDg2vejjfwJGWmnbVFAw3H3hq2NyQfG7hz4aC+w3BbwbesG0swYayvpAs6++Ri1Vfzx93mFChvyN5xVHTS+0p9aqCAxyZ6ZacZyw5+7uuQkFPR9DDk9NOiE7X1PCYJVjVUqq7JlrHwWALF5nfHNGjApdpqgzx5OwilDhCiDYTgnc9waGW4BdLNNUQvOtpzDOWHDH8D7TR/A/85KljEQu3NREc4Pl/6B1Hhc8Umb5CsKMmGC9EPcxoT2amwHNCmeOEnOPbklnMkbOgIvO5UMOpQrS9UGVdt6iH/fURjhI/WOpaW9OKLYRod6HCUEdOX000wpDZQ6hwg6LgZfOqo1RfT/CrJzjekXOGhpc1VW71ZLbXyyp+93ILbC1kPtIEYx0FIx1VDrLoVzXRKRYWk809yYlC9ImcrinxtabKnzRJk3lAU1OLEN1j2zrYzr2myHRXJFf4h4QKT1qSTzTB5+ZNTzTRkAxX8FcLV2uS8eoQQ2aAkFzvCM72sJIcJET3WPjRk5wi32uSS9rfZajpWEvj9hW42F4o5NytSXYy8IKHay10VYdrcl4SkqscrXpMwyGOgtkajheSxdQqmpxP1L3t4R5PqasFnrQEjytq6qgp9Y09Qx9o4S1FzhUCn1kyHSzBWLemoSGvOqLNhZyBjmCaAUYpMgt4Ck7wBBMMwWKWgjsUwTaGVsxWC1mYoKiyqqeGKYqonSIRQ3KIkHO0pmAxTdBHkbOvfllfr+AA+7gnc50huVKYK393FOyg7rbPO/izI7hE4CnHHHnJ0ogNPRUGeUpsrZZTBJcrovUcJe51BPsr6GkJdhCCsZ6aTtMEb2pqWkqeVtDXE/QVggsU/Nl86d9RMF3DxvZTA58agu810RWawCiSzzXBeU3MMW9oyJUedvNEvQyNu1f10BSMddR1vaLCYpYa/mGocLSiYDcLbQz8aMn5iyF4xBNMs1P0QEOV7o5gaWGuzSeLue4tt3ro7y4Tgm4G/mopdZgl6q0o6KzJWE3mMksNr3r+a6CbT8g5wZNzT9O7fi/zpaOmnz3BRoqos+tv9zMbdpxsqDBOEewtJLt7cg5wtKKbvldpSzRRCD43VFheCI7yZLppggMVBS/KMAdHODJvOwq2NQSbKKKPLdFWQs7Fqo+mpl01JXYRgq8dnGLhTiFzqmWsUMdpllZdbKlyvSdYxhI9YghOtxR8LgSLWHK62mGGVoxzBE8LNWzqH9CUesQzFy5RQzTc56mhi6fgXEWwpKfE5Z7M05ZgZUPmo6auiv8YKzDYwWBLMErIbKHJvOwIrvEdhOBcQ9JdU1NHQ7CXn2XIDFBKU2WAgcX9UAUzDXWd5alwuyJ41Z9rjKLCL4aCp4WarhPm2rH+SaHUYE001JDZ2ZAzXPjdMpZWvC9wmqIB2lLhQ01D5jO06hghWMndbM7yRJMsoCj1vYbnFQVrW9jak3OlEJ3s/96+p33dEPRV5GxiqaGjIthUU6FFEZyqCa5qJrpBdzSw95IUnOPIrCUUjRZQFrbw5PR0R1qiYx3cb6nrWUMrBmmiBQxVHtTew5ICP/ip6g4hed/Akob/32wvBHsIOX83cI8hGeNeNPCIkPmXe8fPKx84OMSRM1MTdXSwjCZ4S30jVGhvqTRak/OVhgGazHuOCud5onEO1lJr6ecVyaOK6H7zqlBlIaHE0oroCgfvGJIdPcmfLNGLjpz7hZwZQpUbFME0A1cIJa7VNORkgfsMBatbKgwwJM9bSvQXeNOvbIjelg6WWvo5kvbKaJJNHexkKNHL9xRyFlH8Ti2riB5wVPhUk7nGkJnoCe428LR/wRGdYIlmWebCyxou1rCk4g/ShugBDX0V0ZQWkh0dOVsagkM0yV6OoLd5ye+pRlsCr0n+KiQrGuq5yJDzrTAXHtLUMduTDBVKrSm3eHL+6ijxhFDX9Z5gVU/wliHYTMiMFpKLNMEywu80wd3meoFmt6VbRMPenhrOc6DVe4pgXU8DnnHakLOIIrlF4FZPIw6R+zxBP0dyq6OOZ4Q5sLKCcz084ok+VsMMyQhNZmmBgX5xIXOEJTmi7VsGTvMTNdHHhpzdbE8Du2oKxgvBqQKdDDnTFOylCFaxR1syz2iqrOI/FEpNc3C6f11/7+ASS6l2inq2ciTrCCzgyemrCL5SVPjQkdPZUmGy2c9Sw9FtR1sS30RmsKPCS4rkIC/2U0MduwucYolGaPjKEyhzmiPYXagyWbYz8LWBDdzRimAXzxx4z8K9hpzlhLq+NiQ97HuKorMUfK/OVvC2JfiHUPCQI/q7J2gjK+tTDNxkCc4TMssqCs4TGtLVwQihyoAWgj9bosU80XGW6Ac9TJGziaUh5+hnFcHOnlaM1iRn29NaqGENTTTSUHCH2tWTeV0osUhH6psuVLjRUmGWhm6OZEshGeNowABHcJ2Bpy2ZszRcKkRXd2QuKVEeXnbfaEq825FguqfgfE2whlChSRMdron+LATTPQ2Z369t4B9C5gs/ylzv+CMmepIDPclFQl13W0rspPd1JOcbghGOEutqCv5qacURQl3dDKyvyJlqKXGPgcM9FfawJAMVmdcspcYKOZc4GjDYkFlK05olNMHyHn4zFNykyOxt99RkHlfwmiHo60l2EKI+mhreEKp080Tbug08BVPcgoqC5zWt+NLDTZ7oNSF51N1qie7Va3uCCwyZbkINf/NED6jzOsBdZjFN8oqG3wxVunqCSYYKf3EdhJyf9YWGf7tRU2oH3VHgPr1fe5J9hOgHd7xQ0y7qBwXr23aGErP0cm64JVjZwsOGqL+mhNgZmhJLW2oY4UhedsyBgzrCKrq7BmcpNVhR6jBPq64Vgi+kn6XE68pp8J5/+0wRHGOpsKenQn9DZntPzjRLZpDAdD2fnSgkG9tmIXnUwQ6WVighs7Yi2MxQ0N3CqYaCXkJ0oyOztMDJjmSSpcpvlrk0RMMOjmArQ04PRV1DO1FwhCVaUVPpKUM03JK5SxPsIWRu8/CGHi8UHChiqGFDTbSRJWeYUDDcH6vJWUxR4k1FXbMUwV6e4AJFXS8oMqsZKqzvYQ9DDQdZckY4aGsIhtlubbd2r3j4QBMoTamdPZk7O/Bf62lacZwneNjQoGcdVU7zJOd7ghsUHOkosagic6cnWc8+4gg285R6zZP5s1/LUbCKIznTwK36PkdwlOrl4U1LwfdCCa+IrvFkmgw1PCAUXKWo0sURXWcI2muKJlgyFzhynCY4RBOsqCjoI1R5zREco0n2Vt09BQtYSizgKNHfUmUrQ5UOCh51BFcLmY7umhYqXKQomOop8bUnWNNQcIiBcYaC6xzMNOS8JQQfeqKBmmglB+97ok/lfk3ygaHSyZaCRTzRxQo6GzLfa2jWBPepw+UmT7SQEJyiyRkhBLMVOfcoMjcK0eZChfUNzFAUzCsEN5vP/X1uP/n/aoMX+K+nw/Hjr/9xOo7j7Pju61tLcgvJpTWXNbfN5jLpi6VfCOviTktKlFusQixdEKWmEBUKNaIpjZRSSOXSgzaaKLdabrm1/9nZ+/f+vd/vz/v9+Xy+zZ7PRorYoZqyLrCwQdEAixxVOEXNNnjX2nUSRlkqGmWowk8lxR50JPy9Bo6qJXaXwNvREBvnThPEPrewryLhcAnj5WE15Fqi8W7R1sAuEu86S4ENikItFN4xkv9Af4nXSnUVcLiA9xzesFpivRRVeFKtsMRaKBhuSbjOELnAUtlSQUpXgdfB4Z1oSbnFEetbQ0IrAe+Y+pqnDcEJFj6S8LDZzZHwY4e3XONNlARraomNEt2bkvGsosA3ioyHm+6jCMbI59wqt4eeara28IzEmyPgoRaUOEDhTVdEJhmCoTWfC0p8aNkCp0oYqih2iqGi4yXeMkOsn4LdLLnmKfh/YogjNsPebeFGR4m9BJHLzB61XQ3BtpISfS2FugsK9FAtLWX1dCRcrCnUp44CNzuCowUZmxSRgYaE6Za0W2u/E7CVXCiI/UOR8aAm1+OSyE3mOUcwyc1zBBeoX1kiKy0Zfxck1Gsyulti11i83QTBF5Kg3pDQThFMVHiPSlK+0cSedng/VaS8bOZbtsBcTcZAR8JP5KeqQ1OYKAi20njdNNRpgnsU//K+JnaXJaGTomr7aYIphoRn9aeShJWKEq9LcozSF7QleEfDI5LYm5bgVkFkRwVDBCVu0DDIkGupo8TZBq+/pMQURYErJQmPKGKjNDkWOLx7Jd5QizdUweIaKrlP7SwJDhZvONjLkOsBBX9UpGxnydhXkfBLQ8IxgojQbLFnJf81JytSljclYYyEFyx0kVBvKWOFJmONpshGAcsduQY5giVNCV51eOdJYo/pLhbvM0uDHSevNKRcrKZIqnCtJeEsO95RoqcgGK4ocZcho1tTYtcZvH41pNQ7vA0WrhIfOSraIIntIAi+NXWCErdbkvrWwjRLrt0NKUdL6KSOscTOdMSOUtBHwL6OLA0vNSdynaWQEnCpIvKaIrJJEbvHkmuNhn6OjM8VkSGSqn1uYJCGHnq9I3aLhNME3t6GjIkO7xrNFumpyTNX/NrwX7CrIRiqqWijI9JO4d1iieykyfiposQIQ8YjjsjlBh6oHWbwRjgYJQn2NgSnNycmJAk3NiXhx44Sxykihxm8ybUwT1OVKySc7vi3OXVkdBJ4AyXBeksDXG0IhgtYY0lY5ahCD0ehborIk5aUWRJviMA7Xt5kyRjonrXENkm8yYqgs8VzgrJmClK20uMM3jRJ0FiQICQF9hdETlLQWRIb5ki6WDfWRPobvO6a4GP5mcOrNzDFELtTkONLh9dXE8xypEg7z8A9jkhrQ6Fhjlg/QVktJXxt4WXzT/03Q8IaQWSqIuEvloQ2mqC9Jfi7wRul4RX3pSPlzpoVlmCtI2jvKHCFhjcM3sN6lqF6HxnKelLjXWbwrpR4xzuCrTUZx2qq9oAh8p6ixCUGr78g8oyjRAtB5CZFwi80VerVpI0h+IeBxa6Zg6kWvpDHaioYYuEsRbDC3eOmC2JvGYLeioxGknL2UATNJN6hmtj1DlpLvDVmocYbrGCVJKOrg4X6DgddLA203BKMFngdJJFtFd7vJLm6KEpc5yjQrkk7M80SGe34X24nSex1Ra5Omgb71JKyg8SrU3i/kARKwWpH0kOGhKkObyfd0ZGjvyXlAkVZ4xRbYJ2irFMkFY1SwyWxr2oo4zlNiV+7zmaweFpT4kR3kaDAFW6xpSqzJay05FtYR4HmZhc9UxKbbfF2V8RG1MBmSaE+kmC6JnaRXK9gsiXhJHl/U0qM0WTcbyhwkYIvFGwjSbjfwhiJt8ZSQU+Bd5+marPMOkVkD0muxYLIfEuhh60x/J92itguihJSEMySVPQnTewnEm+620rTQEMsOfo4/kP/0ARvWjitlpSX7GxBgcMEsd3EEeYWvdytd+Saawi6aCIj1CkGb6Aj9rwhx16Cf3vAwFy5pyLhVonXzy51FDpdEblbkdJbUcEPDEFzQ8qNmhzzLTmmKWKbFCXeEuRabp6rxbvAtLF442QjQ+wEA9eL1xSR7Q0JXzlSHjJ4exq89yR0laScJ/FW6z4a73pFMEfDiRZvuvijIt86RaSFOl01riV2mD1UEvxGk/Geg5aWwGki1zgKPG9J2U8PEg8qYvMsZeytiTRXBMslCU8JSlxi8EabjwUldlDNLfzTUmCgxWsjqWCOHavYAqsknKFIO0yQ61VL5AVFxk6WhEaCAkdJgt9aSkzXlKNX2jEa79waYuc7gq0N3GDJGCBhoiTXUEPsdknCUE1CK0fwsiaylSF2uiDyO4XX3pFhNd7R4itFGc0k/ElBZwWvq+GC6szVeEoS/MZ+qylwpKNKv9Z469UOjqCjwlusicyTxG6VpNxcQ8IncoR4RhLbR+NdpGGmJWOcIzJGUuKPGpQg8rrG21dOMqQssJQ4RxH5jaUqnZuQ0F4Q+cjxLwPtpZbIAk3QTJHQWBE5S1BokoVtDd6lhqr9UpHSUxMcIYl9pojsb8h4SBOsMQcqvOWC2E8EVehqiJ1hrrAEbQxeK0NGZ0Gkq+guSRgniM23bIHVkqwx4hiHd7smaOyglyIyQuM978j4VS08J/A2G1KeMBRo4fBaSNhKUEZfQewVQ/C1I+MgfbEleEzCUw7mKXI0M3hd1EESVji8x5uQ41nxs1q4RMJCCXs7Iq9acpxn22oSDnQ/sJTxsCbHIYZiLyhY05TY0ZLIOQrGaSJDDN4t8pVaIrsqqFdEegtizc1iTew5Q4ayBDMUsQMkXocaYkc0hZua412siZ1rSXlR460zRJ5SlHGe5j801RLMlJTxtaOM3Q1pvxJ45zUlWFD7rsAbpfEm1JHxG0eh8w2R7QQVzBUw28FhFp5QZzq8t2rx2joqulYTWSuJdTYfWwqMFMcovFmSyJPNyLhE4E10pHzYjOC3huArRa571ZsGajQpQx38SBP5pyZB6lMU3khDnp0MBV51BE9o2E+TY5Ml2E8S7C0o6w1xvCZjf0HkVEHCzFoyNmqC+9wdcqN+Tp7jSDheE9ws8Y5V0NJCn2bk2tqSY4okdrEhx1iDN8cSudwepWmAGXKcJXK65H9to8jYQRH7SBF01ESUJdd0TayVInaWhLkOjlXE5irKGOnI6GSWGCJa482zBI9rCr0jyTVcEuzriC1vcr6mwFGSiqy5zMwxBH/TJHwjSPhL8+01kaaSUuMFKTcLEvaUePcrSmwn8DZrgikWb7CGPxkSjhQwrRk57tctmxLsb9sZvL9LSlyuSLlWkqOjwduo8b6Uv1DkmudIeFF2dHCgxVtk8dpIvHpBxhEOdhKk7OLIUSdJ+cSRY57B+0DgGUUlNfpthTfGkauzxrvTsUUaCVhlKeteTXCoJDCa2NOKhOmC4G1H8JBd4OBZReSRGkqcb/CO1PyLJTLB4j1q8JYaIutEjSLX8YKM+a6phdMsdLFUoV5RTm9JSkuDN8WcIon0NZMNZWh1q8C7SJEwV5HxrmnnTrf3KoJBlmCYI2ilSLlfEvlE4011NNgjgthzEua0oKK7JLE7HZHlEl60BLMVFewg4EWNt0ThrVNEVkkiTwpKXSWJzdRENgvKGq4IhjsiezgSFtsfCUq8qki5S1LRQeYQQ4nemmCkImWMw3tFUoUBZk4NOeZYEp4XRKTGa6wJjrWNHBVJR4m3FCnbuD6aak2WsMTh3SZImGCIPKNgsDpVwnsa70K31lCFJZYcwwSMFcQulGTsZuEaSdBXkPGZhu0FsdUO73RHjq8MPGGIfaGIbVTk6iuI3GFgucHrIQkmWSJdBd7BBu+uOryWAhY7+Lki9rK5wtEQzWwvtbqGhIMFwWRJsElsY4m9IIg9L6lCX0VklaPAYkfkZEGDnOWowlBJjtMUkcGK4Lg6EtoZInMUBVYLgn0UsdmCyCz7gIGHFfk+k1QwTh5We7A9x+IdJ6CvIkEagms0hR50eH9UnTQJ+2oiKyVlLFUE+8gBGu8MQ3CppUHesnjTHN4QB/UGPhCTHLFPHMFrCqa73gqObUJGa03wgbhHkrCfpEpzNLE7JDS25FMKhlhKKWKfCgqstLCPu1zBXy0J2ztwjtixBu8UTRn9LVtkmCN2iyFhtME70JHRQ1KVZXqKI/KNIKYMCYs1GUMEKbM1bKOI9LDXC7zbHS+bt+1MTWS9odA9DtrYtpbImQJ2VHh/lisEwaHqUk1kjKTAKknkBEXkbkdMGwq0dnhzLJF3NJH3JVwrqOB4Sca2hti75nmJN0WzxS6UxDYoEpxpa4htVlRjkYE7DZGzJVU72uC9IyhQL4i8YfGWSYLLNcHXloyz7QhNifmKSE9JgfGmuyLhc403Xm9vqcp6gXe3xuuv8F6VJNxkyTHEkHG2g0aKXL0MsXc1bGfgas2//dCONXiNLCX+5mB7eZIl1kHh7ajwpikyzlUUWOVOsjSQlsS+M0R+pPje/dzBXRZGO0rMtgQrLLG9VSu9n6CMXS3BhwYmSoIBhsjNBmZbgusE9BCPCP5triU4VhNbJfE+swSP27aayE8tuTpYYjtrYjMVGZdp2NpS1s6aBnKSHDsbKuplKbHM4a0wMFd/5/DmGyKrJSUaW4IBrqUhx0vyfzTBBLPIUcnZdrAkNsKR0sWRspumSns6Ch0v/qqIbBYUWKvPU/CFoyrDJGwSNFhbA/MlzKqjrO80hRbpKx0Jewsi/STftwGSlKc1JZyAzx05dhLEdnfQvhZOqiHWWEAHC7+30FuRcZUgaO5gpaIK+xsiHRUsqaPElTV40xQZQ107Q9BZE1nryDVGU9ZSQ47bmhBpLcYpUt7S+xuK/FiT8qKjwXYw5ypS2iuCv7q1gtgjhuBuB8LCFY5cUuCNtsQOFcT+4Ih9JX+k8Ea6v0iCIRZOtCT0Et00JW5UeC85Cg0ScK0k411HcG1zKtre3SeITBRk7WfwDhEvaYLTHP9le0m8By0JDwn4TlLW/aJOvGHxdjYUes+ScZigCkYQdNdEOhkiezgShqkx8ueKjI8lDfK2oNiOFvrZH1hS+tk7NV7nOmLHicGWEgubkXKdwdtZknCLJXaCpkrjZBtLZFsDP9CdxWsSr05Sxl6CMmoFbCOgryX40uDtamB7SVmXW4Ihlgpmq+00tBKUUa83WbjLUNkzDmY7cow1JDygyPGlhgGKYKz4vcV7QBNbJIgM11TUqZaMdwTeSguH6rOaw1JRKzaaGyxVm2EJ/uCIrVWUcZUkcp2grMsEjK+DMwS59jQk3Kd6SEq1d0S6uVmO4Bc1lDXTUcHjluCXEq+1OlBDj1pi9zgiXxnKuE0SqTXwhqbETW6RggMEnGl/q49UT2iCzgJvRwVXS2K/d6+ZkyUl7jawSVLit46EwxVljDZwoSQ20sDBihztHfk2yA8NVZghiXwrYHQdfKAOtzsayjhY9bY0yE2CWEeJ9xfzO423xhL5syS2TFJofO2pboHob0nY4GiAgRrvGQEDa/FWSsoaaYl0syRsEt3kWoH3B01shCXhTUWe9w3Bt44SC9QCh3eShQctwbaK2ApLroGCMlZrYqvlY3qYhM0aXpFkPOuoqJ3Dm6fxXrGwVF9gCWZagjPqznfkuMKQ8DPTQRO8ZqG1hPGKEm9IgpGW4DZDgTNriTxvFiq+Lz+0cKfp4wj6OCK9JSnzNSn9LFU7UhKZZMnYwcJ8s8yRsECScK4j5UOB95HFO0CzhY4xJxuCix0lDlEUeMdS6EZBkTsUkZ4K74dugyTXS7aNgL8aqjDfkCE0ZbwkCXpaWCKhl8P7VD5jxykivSyxyZrYERbe168LYu9ZYh86IkscgVLE7tWPKmJv11CgoyJltMEbrohtVAQfO4ImltiHEroYEs7RxAarVpY8AwXMcMReFOTYWe5iiLRQxJ5Q8DtJ8LQhWOhIeFESPGsILhbNDRljNbHzNRlTFbk2S3L0NOS6V1KFJYKUbSTcIIhM0wQ/s2TM0SRMNcQmSap3jCH4yhJZKSkwyRHpYYgsFeQ4U7xoCB7VVOExhXepo9ABBsYbvGWKXPME3lyH95YioZ0gssQRWWbI+FaSMkXijZXwgiTlYdPdkNLaETxlyDVIwqeaEus0aTcYcg0RVOkpR3CSJqIddK+90JCxzsDVloyrFd5ZAr4TBKfaWa6boEA7C7s6EpYaeFPjveooY72mjIccLHJ9HUwVlDhKkmutJDJBwnp1rvulJZggKDRfbXAkvC/4l3ozQOG9a8lxjx0i7nV4jSXc7vhe3OwIxjgSHjdEhhsif9YkPGlus3iLFDnWOFhtCZbJg0UbQcIaR67JjthoCyMEZRwhiXWyxO5QxI6w5NhT4U1WsJvDO60J34fW9hwzwlKij6ZAW9ne4L0s8C6XeBMEkd/LQy1VucBRot6QMlbivaBhoBgjqGiCJNhsqVp/S2SsG6DIONCR0dXhvWbJ+MRRZJkkuEjgDXJjFQW6SSL7GXK8Z2CZg7cVsbWGoKmEpzQ5elpiy8Ryg7dMkLLUEauzeO86CuwlSOlgYLojZWeJ9xM3S1PWfEfKl5ISLQ0MEKR8YOB2QfCxJBjrKPCN4f9MkaSsqoVXJBmP7EpFZ9UQfOoOFwSzBN4MQ8LsGrymlipcJQhmy0GaQjPqCHaXRwuCZwRbqK2Fg9wlClZqYicrIgMdZfxTQ0c7TBIbrChxmuzoKG8XRaSrIhhiyNFJkrC7oIAWMEOQa5aBekPCRknCo4IKPrYkvCDI8aYmY7WFtprgekcJZ3oLIqssCSMtFbQTJKwXYy3BY5oCh2iKPCpJOE+zRdpYgi6O2KmOAgvVCYaU4ySRek1sgyFhJ403QFHiVEmJHwtybO1gs8Hr5+BETQX3War0qZngYGgtVZtoqd6vFSk/UwdZElYqyjrF4HXUeFspIi9IGKf4j92pKGAdCYMVsbcV3kRF0N+R8LUd5PCsIGWoxDtBkCI0nKofdJQxT+LtZflvuc8Q3CjwWkq8KwUpHzkK/NmSsclCL0nseQdj5FRH5CNHSgtLiW80Of5HU9Hhlsga9bnBq3fEVltKfO5IaSTmGjjc4J0otcP7QsJUSQM8pEj5/wCuUuC2DWz8AAAAAElFTkSuQmCC\");\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/base16-dark.css",
    "content": "/*\n\n    Name:       Base16 Default Dark\n    Author:     Chris Kempson (http://chriskempson.com)\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-base16-dark.CodeMirror { background: #151515; color: #e0e0e0; }\n.cm-s-base16-dark div.CodeMirror-selected { background: #303030; }\n.cm-s-base16-dark .CodeMirror-line::selection, .cm-s-base16-dark .CodeMirror-line > span::selection, .cm-s-base16-dark .CodeMirror-line > span > span::selection { background: rgba(48, 48, 48, .99); }\n.cm-s-base16-dark .CodeMirror-line::-moz-selection, .cm-s-base16-dark .CodeMirror-line > span::-moz-selection, .cm-s-base16-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(48, 48, 48, .99); }\n.cm-s-base16-dark .CodeMirror-gutters { background: #151515; border-right: 0px; }\n.cm-s-base16-dark .CodeMirror-guttermarker { color: #ac4142; }\n.cm-s-base16-dark .CodeMirror-guttermarker-subtle { color: #505050; }\n.cm-s-base16-dark .CodeMirror-linenumber { color: #505050; }\n.cm-s-base16-dark .CodeMirror-cursor { border-left: 1px solid #b0b0b0; }\n\n.cm-s-base16-dark span.cm-comment { color: #8f5536; }\n.cm-s-base16-dark span.cm-atom { color: #aa759f; }\n.cm-s-base16-dark span.cm-number { color: #aa759f; }\n\n.cm-s-base16-dark span.cm-property, .cm-s-base16-dark span.cm-attribute { color: #90a959; }\n.cm-s-base16-dark span.cm-keyword { color: #ac4142; }\n.cm-s-base16-dark span.cm-string { color: #f4bf75; }\n\n.cm-s-base16-dark span.cm-variable { color: #90a959; }\n.cm-s-base16-dark span.cm-variable-2 { color: #6a9fb5; }\n.cm-s-base16-dark span.cm-def { color: #d28445; }\n.cm-s-base16-dark span.cm-bracket { color: #e0e0e0; }\n.cm-s-base16-dark span.cm-tag { color: #ac4142; }\n.cm-s-base16-dark span.cm-link { color: #aa759f; }\n.cm-s-base16-dark span.cm-error { background: #ac4142; color: #b0b0b0; }\n\n.cm-s-base16-dark .CodeMirror-activeline-background { background: #202020; }\n.cm-s-base16-dark .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/base16-light.css",
    "content": "/*\n\n    Name:       Base16 Default Light\n    Author:     Chris Kempson (http://chriskempson.com)\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-base16-light.CodeMirror { background: #f5f5f5; color: #202020; }\n.cm-s-base16-light div.CodeMirror-selected { background: #e0e0e0; }\n.cm-s-base16-light .CodeMirror-line::selection, .cm-s-base16-light .CodeMirror-line > span::selection, .cm-s-base16-light .CodeMirror-line > span > span::selection { background: #e0e0e0; }\n.cm-s-base16-light .CodeMirror-line::-moz-selection, .cm-s-base16-light .CodeMirror-line > span::-moz-selection, .cm-s-base16-light .CodeMirror-line > span > span::-moz-selection { background: #e0e0e0; }\n.cm-s-base16-light .CodeMirror-gutters { background: #f5f5f5; border-right: 0px; }\n.cm-s-base16-light .CodeMirror-guttermarker { color: #ac4142; }\n.cm-s-base16-light .CodeMirror-guttermarker-subtle { color: #b0b0b0; }\n.cm-s-base16-light .CodeMirror-linenumber { color: #b0b0b0; }\n.cm-s-base16-light .CodeMirror-cursor { border-left: 1px solid #505050; }\n\n.cm-s-base16-light span.cm-comment { color: #8f5536; }\n.cm-s-base16-light span.cm-atom { color: #aa759f; }\n.cm-s-base16-light span.cm-number { color: #aa759f; }\n\n.cm-s-base16-light span.cm-property, .cm-s-base16-light span.cm-attribute { color: #90a959; }\n.cm-s-base16-light span.cm-keyword { color: #ac4142; }\n.cm-s-base16-light span.cm-string { color: #f4bf75; }\n\n.cm-s-base16-light span.cm-variable { color: #90a959; }\n.cm-s-base16-light span.cm-variable-2 { color: #6a9fb5; }\n.cm-s-base16-light span.cm-def { color: #d28445; }\n.cm-s-base16-light span.cm-bracket { color: #202020; }\n.cm-s-base16-light span.cm-tag { color: #ac4142; }\n.cm-s-base16-light span.cm-link { color: #aa759f; }\n.cm-s-base16-light span.cm-error { background: #ac4142; color: #505050; }\n\n.cm-s-base16-light .CodeMirror-activeline-background { background: #DDDCDC; }\n.cm-s-base16-light .CodeMirror-matchingbracket { color: #f5f5f5 !important; background-color: #6A9FB5 !important}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/bespin.css",
    "content": "/*\n\n    Name:       Bespin\n    Author:     Mozilla / Jan T. Sott\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-bespin.CodeMirror {background: #28211c; color: #9d9b97;}\n.cm-s-bespin div.CodeMirror-selected {background: #36312e !important;}\n.cm-s-bespin .CodeMirror-gutters {background: #28211c; border-right: 0px;}\n.cm-s-bespin .CodeMirror-linenumber {color: #666666;}\n.cm-s-bespin .CodeMirror-cursor {border-left: 1px solid #797977 !important;}\n\n.cm-s-bespin span.cm-comment {color: #937121;}\n.cm-s-bespin span.cm-atom {color: #9b859d;}\n.cm-s-bespin span.cm-number {color: #9b859d;}\n\n.cm-s-bespin span.cm-property, .cm-s-bespin span.cm-attribute {color: #54be0d;}\n.cm-s-bespin span.cm-keyword {color: #cf6a4c;}\n.cm-s-bespin span.cm-string {color: #f9ee98;}\n\n.cm-s-bespin span.cm-variable {color: #54be0d;}\n.cm-s-bespin span.cm-variable-2 {color: #5ea6ea;}\n.cm-s-bespin span.cm-def {color: #cf7d34;}\n.cm-s-bespin span.cm-error {background: #cf6a4c; color: #797977;}\n.cm-s-bespin span.cm-bracket {color: #9d9b97;}\n.cm-s-bespin span.cm-tag {color: #cf6a4c;}\n.cm-s-bespin span.cm-link {color: #9b859d;}\n\n.cm-s-bespin .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}\n.cm-s-bespin .CodeMirror-activeline-background { background: #404040; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/blackboard.css",
    "content": "/* Port of TextMate's Blackboard theme */\n\n.cm-s-blackboard.CodeMirror { background: #0C1021; color: #F8F8F8; }\n.cm-s-blackboard div.CodeMirror-selected { background: #253B76; }\n.cm-s-blackboard .CodeMirror-line::selection, .cm-s-blackboard .CodeMirror-line > span::selection, .cm-s-blackboard .CodeMirror-line > span > span::selection { background: rgba(37, 59, 118, .99); }\n.cm-s-blackboard .CodeMirror-line::-moz-selection, .cm-s-blackboard .CodeMirror-line > span::-moz-selection, .cm-s-blackboard .CodeMirror-line > span > span::-moz-selection { background: rgba(37, 59, 118, .99); }\n.cm-s-blackboard .CodeMirror-gutters { background: #0C1021; border-right: 0; }\n.cm-s-blackboard .CodeMirror-guttermarker { color: #FBDE2D; }\n.cm-s-blackboard .CodeMirror-guttermarker-subtle { color: #888; }\n.cm-s-blackboard .CodeMirror-linenumber { color: #888; }\n.cm-s-blackboard .CodeMirror-cursor { border-left: 1px solid #A7A7A7; }\n\n.cm-s-blackboard .cm-keyword { color: #FBDE2D; }\n.cm-s-blackboard .cm-atom { color: #D8FA3C; }\n.cm-s-blackboard .cm-number { color: #D8FA3C; }\n.cm-s-blackboard .cm-def { color: #8DA6CE; }\n.cm-s-blackboard .cm-variable { color: #FF6400; }\n.cm-s-blackboard .cm-operator { color: #FBDE2D; }\n.cm-s-blackboard .cm-comment { color: #AEAEAE; }\n.cm-s-blackboard .cm-string { color: #61CE3C; }\n.cm-s-blackboard .cm-string-2 { color: #61CE3C; }\n.cm-s-blackboard .cm-meta { color: #D8FA3C; }\n.cm-s-blackboard .cm-builtin { color: #8DA6CE; }\n.cm-s-blackboard .cm-tag { color: #8DA6CE; }\n.cm-s-blackboard .cm-attribute { color: #8DA6CE; }\n.cm-s-blackboard .cm-header { color: #FF6400; }\n.cm-s-blackboard .cm-hr { color: #AEAEAE; }\n.cm-s-blackboard .cm-link { color: #8DA6CE; }\n.cm-s-blackboard .cm-error { background: #9D1E15; color: #F8F8F8; }\n\n.cm-s-blackboard .CodeMirror-activeline-background { background: #3C3636; }\n.cm-s-blackboard .CodeMirror-matchingbracket { outline:1px solid grey;color:white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/cobalt.css",
    "content": ".cm-s-cobalt.CodeMirror { background: #002240; color: white; }\n.cm-s-cobalt div.CodeMirror-selected { background: #b36539; }\n.cm-s-cobalt .CodeMirror-line::selection, .cm-s-cobalt .CodeMirror-line > span::selection, .cm-s-cobalt .CodeMirror-line > span > span::selection { background: rgba(179, 101, 57, .99); }\n.cm-s-cobalt .CodeMirror-line::-moz-selection, .cm-s-cobalt .CodeMirror-line > span::-moz-selection, .cm-s-cobalt .CodeMirror-line > span > span::-moz-selection { background: rgba(179, 101, 57, .99); }\n.cm-s-cobalt .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }\n.cm-s-cobalt .CodeMirror-guttermarker { color: #ffee80; }\n.cm-s-cobalt .CodeMirror-guttermarker-subtle { color: #d0d0d0; }\n.cm-s-cobalt .CodeMirror-linenumber { color: #d0d0d0; }\n.cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white; }\n\n.cm-s-cobalt span.cm-comment { color: #08f; }\n.cm-s-cobalt span.cm-atom { color: #845dc4; }\n.cm-s-cobalt span.cm-number, .cm-s-cobalt span.cm-attribute { color: #ff80e1; }\n.cm-s-cobalt span.cm-keyword { color: #ffee80; }\n.cm-s-cobalt span.cm-string { color: #3ad900; }\n.cm-s-cobalt span.cm-meta { color: #ff9d00; }\n.cm-s-cobalt span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #9effff; }\n.cm-s-cobalt span.cm-variable-3, .cm-s-cobalt span.cm-def, .cm-s-cobalt .cm-type { color: white; }\n.cm-s-cobalt span.cm-bracket { color: #d8d8d8; }\n.cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; }\n.cm-s-cobalt span.cm-link { color: #845dc4; }\n.cm-s-cobalt span.cm-error { color: #9d1e15; }\n\n.cm-s-cobalt .CodeMirror-activeline-background { background: #002D57; }\n.cm-s-cobalt .CodeMirror-matchingbracket { outline:1px solid grey;color:white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/colorforth.css",
    "content": ".cm-s-colorforth.CodeMirror { background: #000000; color: #f8f8f8; }\n.cm-s-colorforth .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; }\n.cm-s-colorforth .CodeMirror-guttermarker { color: #FFBD40; }\n.cm-s-colorforth .CodeMirror-guttermarker-subtle { color: #78846f; }\n.cm-s-colorforth .CodeMirror-linenumber { color: #bababa; }\n.cm-s-colorforth .CodeMirror-cursor { border-left: 1px solid white; }\n\n.cm-s-colorforth span.cm-comment     { color: #ededed; }\n.cm-s-colorforth span.cm-def         { color: #ff1c1c; font-weight:bold; }\n.cm-s-colorforth span.cm-keyword     { color: #ffd900; }\n.cm-s-colorforth span.cm-builtin     { color: #00d95a; }\n.cm-s-colorforth span.cm-variable    { color: #73ff00; }\n.cm-s-colorforth span.cm-string      { color: #007bff; }\n.cm-s-colorforth span.cm-number      { color: #00c4ff; }\n.cm-s-colorforth span.cm-atom        { color: #606060; }\n\n.cm-s-colorforth span.cm-variable-2  { color: #EEE; }\n.cm-s-colorforth span.cm-variable-3, .cm-s-colorforth span.cm-type { color: #DDD; }\n.cm-s-colorforth span.cm-property    {}\n.cm-s-colorforth span.cm-operator    {}\n\n.cm-s-colorforth span.cm-meta        { color: yellow; }\n.cm-s-colorforth span.cm-qualifier   { color: #FFF700; }\n.cm-s-colorforth span.cm-bracket     { color: #cc7; }\n.cm-s-colorforth span.cm-tag         { color: #FFBD40; }\n.cm-s-colorforth span.cm-attribute   { color: #FFF700; }\n.cm-s-colorforth span.cm-error       { color: #f00; }\n\n.cm-s-colorforth div.CodeMirror-selected { background: #333d53; }\n\n.cm-s-colorforth span.cm-compilation { background: rgba(255, 255, 255, 0.12); }\n\n.cm-s-colorforth .CodeMirror-activeline-background { background: #253540; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/darcula.css",
    "content": "/**\n    Name: IntelliJ IDEA darcula theme\n    From IntelliJ IDEA by JetBrains\n */\n\n.cm-s-darcula  { font-family: Consolas, Menlo, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New', monospace, serif;}\n.cm-s-darcula.CodeMirror { background: #2B2B2B; color: #A9B7C6; } \n\n.cm-s-darcula span.cm-meta { color: #BBB529; }\n.cm-s-darcula span.cm-number { color: #6897BB; }\n.cm-s-darcula span.cm-keyword { color: #CC7832; line-height: 1em; font-weight: bold; }  \n.cm-s-darcula span.cm-def { color: #A9B7C6; font-style: italic; }\n.cm-s-darcula span.cm-variable { color: #A9B7C6; }\n.cm-s-darcula span.cm-variable-2 { color: #A9B7C6; }\n.cm-s-darcula span.cm-variable-3 { color: #9876AA; }\n.cm-s-darcula span.cm-type { color: #AABBCC; font-weight: bold; }\n.cm-s-darcula span.cm-property { color: #FFC66D; }\n.cm-s-darcula span.cm-operator { color: #A9B7C6; }\n.cm-s-darcula span.cm-string { color: #6A8759; }\n.cm-s-darcula span.cm-string-2 { color: #6A8759; }\n.cm-s-darcula span.cm-comment { color: #61A151; font-style: italic; } \n.cm-s-darcula span.cm-link { color: #CC7832; }\n.cm-s-darcula span.cm-atom { color: #CC7832; }\n.cm-s-darcula span.cm-error { color: #BC3F3C; }\n.cm-s-darcula span.cm-tag { color: #629755; font-weight: bold; font-style: italic; text-decoration: underline; }\n.cm-s-darcula span.cm-attribute { color: #6897bb; }\n.cm-s-darcula span.cm-qualifier { color: #6A8759; }\n.cm-s-darcula span.cm-bracket { color: #A9B7C6; }\n.cm-s-darcula span.cm-builtin { color: #FF9E59; }\n.cm-s-darcula span.cm-special { color: #FF9E59; }\n\n.cm-s-darcula .CodeMirror-cursor { border-left: 1px solid #A9B7C6; }  \n.cm-s-darcula .CodeMirror-activeline-background { background: #323232; } \n.cm-s-darcula .CodeMirror-gutters { background: #313335; border-right: 1px solid #313335; } \n.cm-s-darcula .CodeMirror-guttermarker { color: #FFEE80; }  \n.cm-s-darcula .CodeMirror-guttermarker-subtle { color: #D0D0D0; }  \n.cm-s-darcula .CodeMirrir-linenumber { color: #606366; } \n.cm-s-darcula .CodeMirror-matchingbracket { background-color: #3B514D; color: #FFEF28 !important; font-weight: bold; } \n\n.cm-s-darcula div.CodeMirror-selected { background: #214283; }  \n\n.CodeMirror-hints.darcula {\n  font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;\n  color: #9C9E9E;\n  background-color: #3B3E3F !important;\n}\n\n.CodeMirror-hints.darcula .CodeMirror-hint-active {\n  background-color: #494D4E !important;\n  color: #9C9E9E !important;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/dracula.css",
    "content": "/*\n\n    Name:       dracula\n    Author:     Michael Kaminsky (http://github.com/mkaminsky11)\n\n    Original dracula color scheme by Zeno Rocha (https://github.com/zenorocha/dracula-theme)\n\n*/\n\n\n.cm-s-dracula.CodeMirror, .cm-s-dracula .CodeMirror-gutters {\n  background-color: #282a36 !important;\n  color: #f8f8f2 !important;\n  border: none;\n}\n.cm-s-dracula .CodeMirror-gutters { color: #282a36; }\n.cm-s-dracula .CodeMirror-cursor { border-left: solid thin #f8f8f0; }\n.cm-s-dracula .CodeMirror-linenumber { color: #6D8A88; }\n.cm-s-dracula .CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula .CodeMirror-line::selection, .cm-s-dracula .CodeMirror-line > span::selection, .cm-s-dracula .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula .CodeMirror-line::-moz-selection, .cm-s-dracula .CodeMirror-line > span::-moz-selection, .cm-s-dracula .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula span.cm-comment { color: #6272a4; }\n.cm-s-dracula span.cm-string, .cm-s-dracula span.cm-string-2 { color: #f1fa8c; }\n.cm-s-dracula span.cm-number { color: #bd93f9; }\n.cm-s-dracula span.cm-variable { color: #50fa7b; }\n.cm-s-dracula span.cm-variable-2 { color: white; }\n.cm-s-dracula span.cm-def { color: #50fa7b; }\n.cm-s-dracula span.cm-operator { color: #ff79c6; }\n.cm-s-dracula span.cm-keyword { color: #ff79c6; }\n.cm-s-dracula span.cm-atom { color: #bd93f9; }\n.cm-s-dracula span.cm-meta { color: #f8f8f2; }\n.cm-s-dracula span.cm-tag { color: #ff79c6; }\n.cm-s-dracula span.cm-attribute { color: #50fa7b; }\n.cm-s-dracula span.cm-qualifier { color: #50fa7b; }\n.cm-s-dracula span.cm-property { color: #66d9ef; }\n.cm-s-dracula span.cm-builtin { color: #50fa7b; }\n.cm-s-dracula span.cm-variable-3, .cm-s-dracula span.cm-type { color: #ffb86c; }\n\n.cm-s-dracula .CodeMirror-activeline-background { background: rgba(255,255,255,0.1); }\n.cm-s-dracula .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/duotone-dark.css",
    "content": "/*\nName:   DuoTone-Dark\nAuthor: by Bram de Haan, adapted from DuoTone themes by Simurai (http://simurai.com/projects/2016/01/01/duotone-themes)\n\nCodeMirror template by Jan T. Sott (https://github.com/idleberg), adapted by Bram de Haan (https://github.com/atelierbram/)\n*/\n\n.cm-s-duotone-dark.CodeMirror { background: #2a2734; color: #6c6783; }\n.cm-s-duotone-dark div.CodeMirror-selected { background: #545167!important; }\n.cm-s-duotone-dark .CodeMirror-gutters { background: #2a2734; border-right: 0px; }\n.cm-s-duotone-dark .CodeMirror-linenumber { color: #545167; }\n\n/* begin cursor */\n.cm-s-duotone-dark .CodeMirror-cursor { border-left: 1px solid #ffad5c; /* border-left: 1px solid #ffad5c80; */ border-right: .5em solid #ffad5c; /* border-right: .5em solid #ffad5c80; */ opacity: .5; }\n.cm-s-duotone-dark .CodeMirror-activeline-background { background: #363342; /* background: #36334280;  */ opacity: .5;}\n.cm-s-duotone-dark .cm-fat-cursor .CodeMirror-cursor { background: #ffad5c; /* background: #ffad5c80; */ opacity: .5;}\n/* end cursor */\n\n.cm-s-duotone-dark span.cm-atom, .cm-s-duotone-dark span.cm-number, .cm-s-duotone-dark span.cm-keyword, .cm-s-duotone-dark span.cm-variable, .cm-s-duotone-dark span.cm-attribute, .cm-s-duotone-dark span.cm-quote, .cm-s-duotone-dark span.cm-hr, .cm-s-duotone-dark span.cm-link { color: #ffcc99; }\n\n.cm-s-duotone-dark span.cm-property { color: #9a86fd; }\n.cm-s-duotone-dark span.cm-punctuation, .cm-s-duotone-dark span.cm-unit, .cm-s-duotone-dark span.cm-negative { color: #e09142; }\n.cm-s-duotone-dark span.cm-string { color: #ffb870; }\n.cm-s-duotone-dark span.cm-operator { color: #ffad5c; }\n.cm-s-duotone-dark span.cm-positive { color: #6a51e6; }\n\n.cm-s-duotone-dark span.cm-variable-2, .cm-s-duotone-dark span.cm-variable-3, .cm-s-duotone-dark span.cm-type, .cm-s-duotone-dark span.cm-string-2, .cm-s-duotone-dark span.cm-url { color: #7a63ee; }\n.cm-s-duotone-dark span.cm-def, .cm-s-duotone-dark span.cm-tag, .cm-s-duotone-dark span.cm-builtin, .cm-s-duotone-dark span.cm-qualifier, .cm-s-duotone-dark span.cm-header, .cm-s-duotone-dark span.cm-em { color: #eeebff; }\n.cm-s-duotone-dark span.cm-bracket, .cm-s-duotone-dark span.cm-comment { color: #6c6783; }\n\n/* using #f00 red for errors, don't think any of the colorscheme variables will stand out enough, ... maybe by giving it a background-color ... */\n.cm-s-duotone-dark span.cm-error, .cm-s-duotone-dark span.cm-invalidchar { color: #f00; }\n\n.cm-s-duotone-dark span.cm-header { font-weight: normal; }\n.cm-s-duotone-dark .CodeMirror-matchingbracket { text-decoration: underline; color: #eeebff !important; } \n"
  },
  {
    "path": "third_party/CodeMirror/theme/duotone-light.css",
    "content": "/*\nName:   DuoTone-Light\nAuthor: by Bram de Haan, adapted from DuoTone themes by Simurai (http://simurai.com/projects/2016/01/01/duotone-themes)\n\nCodeMirror template by Jan T. Sott (https://github.com/idleberg), adapted by Bram de Haan (https://github.com/atelierbram/)\n*/\n\n.cm-s-duotone-light.CodeMirror { background: #faf8f5; color: #b29762; }\n.cm-s-duotone-light div.CodeMirror-selected { background: #e3dcce !important; }\n.cm-s-duotone-light .CodeMirror-gutters { background: #faf8f5; border-right: 0px; }\n.cm-s-duotone-light .CodeMirror-linenumber { color: #cdc4b1; }\n\n/* begin cursor */\n.cm-s-duotone-light .CodeMirror-cursor { border-left: 1px solid #93abdc; /* border-left: 1px solid #93abdc80; */ border-right: .5em solid #93abdc; /* border-right: .5em solid #93abdc80; */ opacity: .5; }\n.cm-s-duotone-light .CodeMirror-activeline-background { background: #e3dcce;  /* background: #e3dcce80; */ opacity: .5; }\n.cm-s-duotone-light .cm-fat-cursor .CodeMirror-cursor { background: #93abdc; /* #93abdc80; */ opacity: .5; }\n/* end cursor */\n\n.cm-s-duotone-light span.cm-atom, .cm-s-duotone-light span.cm-number, .cm-s-duotone-light span.cm-keyword, .cm-s-duotone-light span.cm-variable, .cm-s-duotone-light span.cm-attribute, .cm-s-duotone-light span.cm-quote, .cm-s-duotone-light-light span.cm-hr, .cm-s-duotone-light-light span.cm-link { color: #063289; }\n\n.cm-s-duotone-light span.cm-property { color: #b29762; }\n.cm-s-duotone-light span.cm-punctuation, .cm-s-duotone-light span.cm-unit, .cm-s-duotone-light span.cm-negative { color: #063289; }\n.cm-s-duotone-light span.cm-string, .cm-s-duotone-light span.cm-operator { color: #1659df; }\n.cm-s-duotone-light span.cm-positive { color: #896724; }\n\n.cm-s-duotone-light span.cm-variable-2, .cm-s-duotone-light span.cm-variable-3, .cm-s-duotone-light span.cm-type, .cm-s-duotone-light span.cm-string-2, .cm-s-duotone-light span.cm-url { color: #896724; }\n.cm-s-duotone-light span.cm-def, .cm-s-duotone-light span.cm-tag, .cm-s-duotone-light span.cm-builtin, .cm-s-duotone-light span.cm-qualifier, .cm-s-duotone-light span.cm-header, .cm-s-duotone-light span.cm-em { color: #2d2006; }\n.cm-s-duotone-light span.cm-bracket, .cm-s-duotone-light span.cm-comment { color: #b6ad9a; }\n\n/* using #f00 red for errors, don't think any of the colorscheme variables will stand out enough, ... maybe by giving it a background-color ... */\n/* .cm-s-duotone-light span.cm-error { background: #896724; color: #728fcb; } */\n.cm-s-duotone-light span.cm-error, .cm-s-duotone-light span.cm-invalidchar { color: #f00; }\n\n.cm-s-duotone-light span.cm-header { font-weight: normal; }\n.cm-s-duotone-light .CodeMirror-matchingbracket { text-decoration: underline; color: #faf8f5 !important; }\n\n"
  },
  {
    "path": "third_party/CodeMirror/theme/eclipse.css",
    "content": ".cm-s-eclipse span.cm-meta { color: #FF1717; }\n.cm-s-eclipse span.cm-keyword { line-height: 1em; font-weight: bold; color: #7F0055; }\n.cm-s-eclipse span.cm-atom { color: #219; }\n.cm-s-eclipse span.cm-number { color: #164; }\n.cm-s-eclipse span.cm-def { color: #00f; }\n.cm-s-eclipse span.cm-variable { color: black; }\n.cm-s-eclipse span.cm-variable-2 { color: #0000C0; }\n.cm-s-eclipse span.cm-variable-3, .cm-s-eclipse span.cm-type { color: #0000C0; }\n.cm-s-eclipse span.cm-property { color: black; }\n.cm-s-eclipse span.cm-operator { color: black; }\n.cm-s-eclipse span.cm-comment { color: #3F7F5F; }\n.cm-s-eclipse span.cm-string { color: #2A00FF; }\n.cm-s-eclipse span.cm-string-2 { color: #f50; }\n.cm-s-eclipse span.cm-qualifier { color: #555; }\n.cm-s-eclipse span.cm-builtin { color: #30a; }\n.cm-s-eclipse span.cm-bracket { color: #cc7; }\n.cm-s-eclipse span.cm-tag { color: #170; }\n.cm-s-eclipse span.cm-attribute { color: #00c; }\n.cm-s-eclipse span.cm-link { color: #219; }\n.cm-s-eclipse span.cm-error { color: #f00; }\n\n.cm-s-eclipse .CodeMirror-activeline-background { background: #e8f2ff; }\n.cm-s-eclipse .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/elegant.css",
    "content": ".cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom { color: #762; }\n.cm-s-elegant span.cm-comment { color: #262; font-style: italic; line-height: 1em; }\n.cm-s-elegant span.cm-meta { color: #555; font-style: italic; line-height: 1em; }\n.cm-s-elegant span.cm-variable { color: black; }\n.cm-s-elegant span.cm-variable-2 { color: #b11; }\n.cm-s-elegant span.cm-qualifier { color: #555; }\n.cm-s-elegant span.cm-keyword { color: #730; }\n.cm-s-elegant span.cm-builtin { color: #30a; }\n.cm-s-elegant span.cm-link { color: #762; }\n.cm-s-elegant span.cm-error { background-color: #fdd; }\n\n.cm-s-elegant .CodeMirror-activeline-background { background: #e8f2ff; }\n.cm-s-elegant .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/erlang-dark.css",
    "content": ".cm-s-erlang-dark.CodeMirror { background: #002240; color: white; }\n.cm-s-erlang-dark div.CodeMirror-selected { background: #b36539; }\n.cm-s-erlang-dark .CodeMirror-line::selection, .cm-s-erlang-dark .CodeMirror-line > span::selection, .cm-s-erlang-dark .CodeMirror-line > span > span::selection { background: rgba(179, 101, 57, .99); }\n.cm-s-erlang-dark .CodeMirror-line::-moz-selection, .cm-s-erlang-dark .CodeMirror-line > span::-moz-selection, .cm-s-erlang-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(179, 101, 57, .99); }\n.cm-s-erlang-dark .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }\n.cm-s-erlang-dark .CodeMirror-guttermarker { color: white; }\n.cm-s-erlang-dark .CodeMirror-guttermarker-subtle { color: #d0d0d0; }\n.cm-s-erlang-dark .CodeMirror-linenumber { color: #d0d0d0; }\n.cm-s-erlang-dark .CodeMirror-cursor { border-left: 1px solid white; }\n\n.cm-s-erlang-dark span.cm-quote      { color: #ccc; }\n.cm-s-erlang-dark span.cm-atom       { color: #f133f1; }\n.cm-s-erlang-dark span.cm-attribute  { color: #ff80e1; }\n.cm-s-erlang-dark span.cm-bracket    { color: #ff9d00; }\n.cm-s-erlang-dark span.cm-builtin    { color: #eaa; }\n.cm-s-erlang-dark span.cm-comment    { color: #77f; }\n.cm-s-erlang-dark span.cm-def        { color: #e7a; }\n.cm-s-erlang-dark span.cm-keyword    { color: #ffee80; }\n.cm-s-erlang-dark span.cm-meta       { color: #50fefe; }\n.cm-s-erlang-dark span.cm-number     { color: #ffd0d0; }\n.cm-s-erlang-dark span.cm-operator   { color: #d55; }\n.cm-s-erlang-dark span.cm-property   { color: #ccc; }\n.cm-s-erlang-dark span.cm-qualifier  { color: #ccc; }\n.cm-s-erlang-dark span.cm-special    { color: #ffbbbb; }\n.cm-s-erlang-dark span.cm-string     { color: #3ad900; }\n.cm-s-erlang-dark span.cm-string-2   { color: #ccc; }\n.cm-s-erlang-dark span.cm-tag        { color: #9effff; }\n.cm-s-erlang-dark span.cm-variable   { color: #50fe50; }\n.cm-s-erlang-dark span.cm-variable-2 { color: #e0e; }\n.cm-s-erlang-dark span.cm-variable-3, .cm-s-erlang-dark span.cm-type { color: #ccc; }\n.cm-s-erlang-dark span.cm-error      { color: #9d1e15; }\n\n.cm-s-erlang-dark .CodeMirror-activeline-background { background: #013461; }\n.cm-s-erlang-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/gruvbox-dark.css",
    "content": "/*\n\n    Name:       gruvbox-dark\n    Author:     kRkk (https://github.com/krkk)\n\n    Original gruvbox color scheme by Pavel Pertsev (https://github.com/morhetz/gruvbox)\n\n*/\n\n.cm-s-gruvbox-dark.CodeMirror, .cm-s-gruvbox-dark .CodeMirror-gutters { background-color: #282828; color: #bdae93; }\n.cm-s-gruvbox-dark .CodeMirror-gutters {background: #282828; border-right: 0px;}\n.cm-s-gruvbox-dark .CodeMirror-linenumber {color: #7c6f64;}\n.cm-s-gruvbox-dark .CodeMirror-cursor { border-left: 1px solid #ebdbb2; }\n.cm-s-gruvbox-dark div.CodeMirror-selected { background: #928374; }\n.cm-s-gruvbox-dark span.cm-meta { color: #83a598; }\n\n.cm-s-gruvbox-dark span.cm-comment { color: #928374; }\n.cm-s-gruvbox-dark span.cm-number, span.cm-atom { color: #d3869b; }\n.cm-s-gruvbox-dark span.cm-keyword { color: #f84934; }\n\n.cm-s-gruvbox-dark span.cm-variable { color: #ebdbb2; }\n.cm-s-gruvbox-dark span.cm-variable-2 { color: #ebdbb2; }\n.cm-s-gruvbox-dark span.cm-variable-3, .cm-s-gruvbox-dark span.cm-type { color: #fabd2f; }\n.cm-s-gruvbox-dark span.cm-operator { color: #ebdbb2; }\n.cm-s-gruvbox-dark span.cm-callee { color: #ebdbb2; }\n.cm-s-gruvbox-dark span.cm-def { color: #ebdbb2; }\n.cm-s-gruvbox-dark span.cm-property { color: #ebdbb2; }\n.cm-s-gruvbox-dark span.cm-string { color: #b8bb26; }\n.cm-s-gruvbox-dark span.cm-string-2 { color: #8ec07c; }\n.cm-s-gruvbox-dark span.cm-qualifier { color: #8ec07c; }\n.cm-s-gruvbox-dark span.cm-attribute { color: #8ec07c; }\n\n.cm-s-gruvbox-dark .CodeMirror-activeline-background { background: #3c3836; }\n.cm-s-gruvbox-dark .CodeMirror-matchingbracket { background: #928374; color:#282828 !important; }\n\n.cm-s-gruvbox-dark span.cm-builtin { color: #fe8019; }\n.cm-s-gruvbox-dark span.cm-tag { color: #fe8019; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/hopscotch.css",
    "content": "/*\n\n    Name:       Hopscotch\n    Author:     Jan T. Sott\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-hopscotch.CodeMirror {background: #322931; color: #d5d3d5;}\n.cm-s-hopscotch div.CodeMirror-selected {background: #433b42 !important;}\n.cm-s-hopscotch .CodeMirror-gutters {background: #322931; border-right: 0px;}\n.cm-s-hopscotch .CodeMirror-linenumber {color: #797379;}\n.cm-s-hopscotch .CodeMirror-cursor {border-left: 1px solid #989498 !important;}\n\n.cm-s-hopscotch span.cm-comment {color: #b33508;}\n.cm-s-hopscotch span.cm-atom {color: #c85e7c;}\n.cm-s-hopscotch span.cm-number {color: #c85e7c;}\n\n.cm-s-hopscotch span.cm-property, .cm-s-hopscotch span.cm-attribute {color: #8fc13e;}\n.cm-s-hopscotch span.cm-keyword {color: #dd464c;}\n.cm-s-hopscotch span.cm-string {color: #fdcc59;}\n\n.cm-s-hopscotch span.cm-variable {color: #8fc13e;}\n.cm-s-hopscotch span.cm-variable-2 {color: #1290bf;}\n.cm-s-hopscotch span.cm-def {color: #fd8b19;}\n.cm-s-hopscotch span.cm-error {background: #dd464c; color: #989498;}\n.cm-s-hopscotch span.cm-bracket {color: #d5d3d5;}\n.cm-s-hopscotch span.cm-tag {color: #dd464c;}\n.cm-s-hopscotch span.cm-link {color: #c85e7c;}\n\n.cm-s-hopscotch .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}\n.cm-s-hopscotch .CodeMirror-activeline-background { background: #302020; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/icecoder.css",
    "content": "/*\nICEcoder default theme by Matt Pass, used in code editor available at https://icecoder.net\n*/\n\n.cm-s-icecoder { color: #666; background: #1d1d1b; }\n\n.cm-s-icecoder span.cm-keyword { color: #eee; font-weight:bold; }  /* off-white 1 */\n.cm-s-icecoder span.cm-atom { color: #e1c76e; }                    /* yellow */\n.cm-s-icecoder span.cm-number { color: #6cb5d9; }                  /* blue */\n.cm-s-icecoder span.cm-def { color: #b9ca4a; }                     /* green */\n\n.cm-s-icecoder span.cm-variable { color: #6cb5d9; }                /* blue */\n.cm-s-icecoder span.cm-variable-2 { color: #cc1e5c; }              /* pink */\n.cm-s-icecoder span.cm-variable-3, .cm-s-icecoder span.cm-type { color: #f9602c; } /* orange */\n\n.cm-s-icecoder span.cm-property { color: #eee; }                   /* off-white 1 */\n.cm-s-icecoder span.cm-operator { color: #9179bb; }                /* purple */\n.cm-s-icecoder span.cm-comment { color: #97a3aa; }                 /* grey-blue */\n\n.cm-s-icecoder span.cm-string { color: #b9ca4a; }                  /* green */\n.cm-s-icecoder span.cm-string-2 { color: #6cb5d9; }                /* blue */\n\n.cm-s-icecoder span.cm-meta { color: #555; }                       /* grey */\n\n.cm-s-icecoder span.cm-qualifier { color: #555; }                  /* grey */\n.cm-s-icecoder span.cm-builtin { color: #214e7b; }                 /* bright blue */\n.cm-s-icecoder span.cm-bracket { color: #cc7; }                    /* grey-yellow */\n\n.cm-s-icecoder span.cm-tag { color: #e8e8e8; }                     /* off-white 2 */\n.cm-s-icecoder span.cm-attribute { color: #099; }                  /* teal */\n\n.cm-s-icecoder span.cm-header { color: #6a0d6a; }                  /* purple-pink */\n.cm-s-icecoder span.cm-quote { color: #186718; }                   /* dark green */\n.cm-s-icecoder span.cm-hr { color: #888; }                         /* mid-grey */\n.cm-s-icecoder span.cm-link { color: #e1c76e; }                    /* yellow */\n.cm-s-icecoder span.cm-error { color: #d00; }                      /* red */\n\n.cm-s-icecoder .CodeMirror-cursor { border-left: 1px solid white; }\n.cm-s-icecoder div.CodeMirror-selected { color: #fff; background: #037; }\n.cm-s-icecoder .CodeMirror-gutters { background: #1d1d1b; min-width: 41px; border-right: 0; }\n.cm-s-icecoder .CodeMirror-linenumber { color: #555; cursor: default; }\n.cm-s-icecoder .CodeMirror-matchingbracket { color: #fff !important; background: #555 !important; }\n.cm-s-icecoder .CodeMirror-activeline-background { background: #000; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/idea.css",
    "content": "/**\n    Name:       IDEA default theme\n    From IntelliJ IDEA by JetBrains\n */\n\n.cm-s-idea span.cm-meta { color: #808000; }\n.cm-s-idea span.cm-number { color: #0000FF; }\n.cm-s-idea span.cm-keyword { line-height: 1em; font-weight: bold; color: #000080; }\n.cm-s-idea span.cm-atom { font-weight: bold; color: #000080; }\n.cm-s-idea span.cm-def { color: #000000; }\n.cm-s-idea span.cm-variable { color: black; }\n.cm-s-idea span.cm-variable-2 { color: black; }\n.cm-s-idea span.cm-variable-3, .cm-s-idea span.cm-type { color: black; }\n.cm-s-idea span.cm-property { color: black; }\n.cm-s-idea span.cm-operator { color: black; }\n.cm-s-idea span.cm-comment { color: #808080; }\n.cm-s-idea span.cm-string { color: #008000; }\n.cm-s-idea span.cm-string-2 { color: #008000; }\n.cm-s-idea span.cm-qualifier { color: #555; }\n.cm-s-idea span.cm-error { color: #FF0000; }\n.cm-s-idea span.cm-attribute { color: #0000FF; }\n.cm-s-idea span.cm-tag { color: #000080; }\n.cm-s-idea span.cm-link { color: #0000FF; }\n.cm-s-idea .CodeMirror-activeline-background { background: #FFFAE3; }\n\n.cm-s-idea span.cm-builtin { color: #30a; }\n.cm-s-idea span.cm-bracket { color: #cc7; }\n.cm-s-idea  { font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;}\n\n\n.cm-s-idea .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; }\n\n.CodeMirror-hints.idea {\n  font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;\n  color: #616569;\n  background-color: #ebf3fd !important;\n}\n\n.CodeMirror-hints.idea .CodeMirror-hint-active {\n  background-color: #a2b8c9 !important;\n  color: #5c6065 !important;\n}"
  },
  {
    "path": "third_party/CodeMirror/theme/isotope.css",
    "content": "/*\n\n    Name:       Isotope\n    Author:     David Desandro / Jan T. Sott\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-isotope.CodeMirror {background: #000000; color: #e0e0e0;}\n.cm-s-isotope div.CodeMirror-selected {background: #404040 !important;}\n.cm-s-isotope .CodeMirror-gutters {background: #000000; border-right: 0px;}\n.cm-s-isotope .CodeMirror-linenumber {color: #808080;}\n.cm-s-isotope .CodeMirror-cursor {border-left: 1px solid #c0c0c0 !important;}\n\n.cm-s-isotope span.cm-comment {color: #3300ff;}\n.cm-s-isotope span.cm-atom {color: #cc00ff;}\n.cm-s-isotope span.cm-number {color: #cc00ff;}\n\n.cm-s-isotope span.cm-property, .cm-s-isotope span.cm-attribute {color: #33ff00;}\n.cm-s-isotope span.cm-keyword {color: #ff0000;}\n.cm-s-isotope span.cm-string {color: #ff0099;}\n\n.cm-s-isotope span.cm-variable {color: #33ff00;}\n.cm-s-isotope span.cm-variable-2 {color: #0066ff;}\n.cm-s-isotope span.cm-def {color: #ff9900;}\n.cm-s-isotope span.cm-error {background: #ff0000; color: #c0c0c0;}\n.cm-s-isotope span.cm-bracket {color: #e0e0e0;}\n.cm-s-isotope span.cm-tag {color: #ff0000;}\n.cm-s-isotope span.cm-link {color: #cc00ff;}\n\n.cm-s-isotope .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}\n.cm-s-isotope .CodeMirror-activeline-background { background: #202020; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/lesser-dark.css",
    "content": "/*\nhttp://lesscss.org/ dark theme\nPorted to CodeMirror by Peter Kroon\n*/\n.cm-s-lesser-dark {\n  line-height: 1.3em;\n}\n.cm-s-lesser-dark.CodeMirror { background: #262626; color: #EBEFE7; text-shadow: 0 -1px 1px #262626; }\n.cm-s-lesser-dark div.CodeMirror-selected { background: #45443B; } /* 33322B*/\n.cm-s-lesser-dark .CodeMirror-line::selection, .cm-s-lesser-dark .CodeMirror-line > span::selection, .cm-s-lesser-dark .CodeMirror-line > span > span::selection { background: rgba(69, 68, 59, .99); }\n.cm-s-lesser-dark .CodeMirror-line::-moz-selection, .cm-s-lesser-dark .CodeMirror-line > span::-moz-selection, .cm-s-lesser-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(69, 68, 59, .99); }\n.cm-s-lesser-dark .CodeMirror-cursor { border-left: 1px solid white; }\n.cm-s-lesser-dark pre { padding: 0 8px; }/*editable code holder*/\n\n.cm-s-lesser-dark.CodeMirror span.CodeMirror-matchingbracket { color: #7EFC7E; }/*65FC65*/\n\n.cm-s-lesser-dark .CodeMirror-gutters { background: #262626; border-right:1px solid #aaa; }\n.cm-s-lesser-dark .CodeMirror-guttermarker { color: #599eff; }\n.cm-s-lesser-dark .CodeMirror-guttermarker-subtle { color: #777; }\n.cm-s-lesser-dark .CodeMirror-linenumber { color: #777; }\n\n.cm-s-lesser-dark span.cm-header { color: #a0a; }\n.cm-s-lesser-dark span.cm-quote { color: #090; }\n.cm-s-lesser-dark span.cm-keyword { color: #599eff; }\n.cm-s-lesser-dark span.cm-atom { color: #C2B470; }\n.cm-s-lesser-dark span.cm-number { color: #B35E4D; }\n.cm-s-lesser-dark span.cm-def { color: white; }\n.cm-s-lesser-dark span.cm-variable { color:#D9BF8C; }\n.cm-s-lesser-dark span.cm-variable-2 { color: #669199; }\n.cm-s-lesser-dark span.cm-variable-3, .cm-s-lesser-dark span.cm-type { color: white; }\n.cm-s-lesser-dark span.cm-property { color: #92A75C; }\n.cm-s-lesser-dark span.cm-operator { color: #92A75C; }\n.cm-s-lesser-dark span.cm-comment { color: #666; }\n.cm-s-lesser-dark span.cm-string { color: #BCD279; }\n.cm-s-lesser-dark span.cm-string-2 { color: #f50; }\n.cm-s-lesser-dark span.cm-meta { color: #738C73; }\n.cm-s-lesser-dark span.cm-qualifier { color: #555; }\n.cm-s-lesser-dark span.cm-builtin { color: #ff9e59; }\n.cm-s-lesser-dark span.cm-bracket { color: #EBEFE7; }\n.cm-s-lesser-dark span.cm-tag { color: #669199; }\n.cm-s-lesser-dark span.cm-attribute { color: #81a4d5; }\n.cm-s-lesser-dark span.cm-hr { color: #999; }\n.cm-s-lesser-dark span.cm-link { color: #00c; }\n.cm-s-lesser-dark span.cm-error { color: #9d1e15; }\n\n.cm-s-lesser-dark .CodeMirror-activeline-background { background: #3C3A3A; }\n.cm-s-lesser-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/liquibyte.css",
    "content": ".cm-s-liquibyte.CodeMirror {\n\tbackground-color: #000;\n\tcolor: #fff;\n\tline-height: 1.2em;\n\tfont-size: 1em;\n}\n.cm-s-liquibyte .CodeMirror-focused .cm-matchhighlight {\n\ttext-decoration: underline;\n\ttext-decoration-color: #0f0;\n\ttext-decoration-style: wavy;\n}\n.cm-s-liquibyte .cm-trailingspace {\n\ttext-decoration: line-through;\n\ttext-decoration-color: #f00;\n\ttext-decoration-style: dotted;\n}\n.cm-s-liquibyte .cm-tab {\n\ttext-decoration: line-through;\n\ttext-decoration-color: #404040;\n\ttext-decoration-style: dotted;\n}\n.cm-s-liquibyte .CodeMirror-gutters { background-color: #262626; border-right: 1px solid #505050; padding-right: 0.8em; }\n.cm-s-liquibyte .CodeMirror-gutter-elt div { font-size: 1.2em; }\n.cm-s-liquibyte .CodeMirror-guttermarker {  }\n.cm-s-liquibyte .CodeMirror-guttermarker-subtle {  }\n.cm-s-liquibyte .CodeMirror-linenumber { color: #606060; padding-left: 0; }\n.cm-s-liquibyte .CodeMirror-cursor { border-left: 1px solid #eee; }\n\n.cm-s-liquibyte span.cm-comment     { color: #008000; }\n.cm-s-liquibyte span.cm-def         { color: #ffaf40; font-weight: bold; }\n.cm-s-liquibyte span.cm-keyword     { color: #c080ff; font-weight: bold; }\n.cm-s-liquibyte span.cm-builtin     { color: #ffaf40; font-weight: bold; }\n.cm-s-liquibyte span.cm-variable    { color: #5967ff; font-weight: bold; }\n.cm-s-liquibyte span.cm-string      { color: #ff8000; }\n.cm-s-liquibyte span.cm-number      { color: #0f0; font-weight: bold; }\n.cm-s-liquibyte span.cm-atom        { color: #bf3030; font-weight: bold; }\n\n.cm-s-liquibyte span.cm-variable-2  { color: #007f7f; font-weight: bold; }\n.cm-s-liquibyte span.cm-variable-3, .cm-s-liquibyte span.cm-type { color: #c080ff; font-weight: bold; }\n.cm-s-liquibyte span.cm-property    { color: #999; font-weight: bold; }\n.cm-s-liquibyte span.cm-operator    { color: #fff; }\n\n.cm-s-liquibyte span.cm-meta        { color: #0f0; }\n.cm-s-liquibyte span.cm-qualifier   { color: #fff700; font-weight: bold; }\n.cm-s-liquibyte span.cm-bracket     { color: #cc7; }\n.cm-s-liquibyte span.cm-tag         { color: #ff0; font-weight: bold; }\n.cm-s-liquibyte span.cm-attribute   { color: #c080ff; font-weight: bold; }\n.cm-s-liquibyte span.cm-error       { color: #f00; }\n\n.cm-s-liquibyte div.CodeMirror-selected { background-color: rgba(255, 0, 0, 0.25); }\n\n.cm-s-liquibyte span.cm-compilation { background-color: rgba(255, 255, 255, 0.12); }\n\n.cm-s-liquibyte .CodeMirror-activeline-background { background-color: rgba(0, 255, 0, 0.15); }\n\n/* Default styles for common addons */\n.cm-s-liquibyte .CodeMirror span.CodeMirror-matchingbracket { color: #0f0; font-weight: bold; }\n.cm-s-liquibyte .CodeMirror span.CodeMirror-nonmatchingbracket { color: #f00; font-weight: bold; }\n.CodeMirror-matchingtag { background-color: rgba(150, 255, 0, .3); }\n/* Scrollbars */\n/* Simple */\n.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div:hover, .cm-s-liquibyte div.CodeMirror-simplescroll-vertical div:hover {\n\tbackground-color: rgba(80, 80, 80, .7);\n}\n.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div, .cm-s-liquibyte div.CodeMirror-simplescroll-vertical div {\n\tbackground-color: rgba(80, 80, 80, .3);\n\tborder: 1px solid #404040;\n\tborder-radius: 5px;\n}\n.cm-s-liquibyte div.CodeMirror-simplescroll-vertical div {\n\tborder-top: 1px solid #404040;\n\tborder-bottom: 1px solid #404040;\n}\n.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div {\n\tborder-left: 1px solid #404040;\n\tborder-right: 1px solid #404040;\n}\n.cm-s-liquibyte div.CodeMirror-simplescroll-vertical {\n\tbackground-color: #262626;\n}\n.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal {\n\tbackground-color: #262626;\n\tborder-top: 1px solid #404040;\n}\n/* Overlay */\n.cm-s-liquibyte div.CodeMirror-overlayscroll-horizontal div, div.CodeMirror-overlayscroll-vertical div {\n\tbackground-color: #404040;\n\tborder-radius: 5px;\n}\n.cm-s-liquibyte div.CodeMirror-overlayscroll-vertical div {\n\tborder: 1px solid #404040;\n}\n.cm-s-liquibyte div.CodeMirror-overlayscroll-horizontal div {\n\tborder: 1px solid #404040;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/lucario.css",
    "content": "/*\n  Name:       lucario\n  Author:     Raphael Amorim\n\n  Original Lucario color scheme (https://github.com/raphamorim/lucario)\n*/\n\n.cm-s-lucario.CodeMirror, .cm-s-lucario .CodeMirror-gutters {\n  background-color: #2b3e50 !important;\n  color: #f8f8f2 !important;\n  border: none;\n}\n.cm-s-lucario .CodeMirror-gutters { color: #2b3e50; }\n.cm-s-lucario .CodeMirror-cursor { border-left: solid thin #E6C845; }\n.cm-s-lucario .CodeMirror-linenumber { color: #f8f8f2; }\n.cm-s-lucario .CodeMirror-selected { background: #243443; }\n.cm-s-lucario .CodeMirror-line::selection, .cm-s-lucario .CodeMirror-line > span::selection, .cm-s-lucario .CodeMirror-line > span > span::selection { background: #243443; }\n.cm-s-lucario .CodeMirror-line::-moz-selection, .cm-s-lucario .CodeMirror-line > span::-moz-selection, .cm-s-lucario .CodeMirror-line > span > span::-moz-selection { background: #243443; }\n.cm-s-lucario span.cm-comment { color: #5c98cd; }\n.cm-s-lucario span.cm-string, .cm-s-lucario span.cm-string-2 { color: #E6DB74; }\n.cm-s-lucario span.cm-number { color: #ca94ff; }\n.cm-s-lucario span.cm-variable { color: #f8f8f2; }\n.cm-s-lucario span.cm-variable-2 { color: #f8f8f2; }\n.cm-s-lucario span.cm-def { color: #72C05D; }\n.cm-s-lucario span.cm-operator { color: #66D9EF; }\n.cm-s-lucario span.cm-keyword { color: #ff6541; }\n.cm-s-lucario span.cm-atom { color: #bd93f9; }\n.cm-s-lucario span.cm-meta { color: #f8f8f2; }\n.cm-s-lucario span.cm-tag { color: #ff6541; }\n.cm-s-lucario span.cm-attribute { color: #66D9EF; }\n.cm-s-lucario span.cm-qualifier { color: #72C05D; }\n.cm-s-lucario span.cm-property { color: #f8f8f2; }\n.cm-s-lucario span.cm-builtin { color: #72C05D; }\n.cm-s-lucario span.cm-variable-3, .cm-s-lucario span.cm-type { color: #ffb86c; }\n\n.cm-s-lucario .CodeMirror-activeline-background { background: #243443; }\n.cm-s-lucario .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/material.css",
    "content": "/*\n\n    Name:       material\n    Author:     Michael Kaminsky (http://github.com/mkaminsky11)\n\n    Original material color scheme by Mattia Astorino (https://github.com/equinusocio/material-theme)\n\n*/\n\n.cm-s-material.CodeMirror {\n  background-color: #263238;\n  color: rgba(233, 237, 237, 1);\n}\n.cm-s-material .CodeMirror-gutters {\n  background: #263238;\n  color: rgb(83,127,126);\n  border: none;\n}\n.cm-s-material .CodeMirror-guttermarker, .cm-s-material .CodeMirror-guttermarker-subtle, .cm-s-material .CodeMirror-linenumber { color: rgb(83,127,126); }\n.cm-s-material .CodeMirror-cursor { border-left: 1px solid #f8f8f0; }\n.cm-s-material div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); }\n.cm-s-material.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }\n.cm-s-material .CodeMirror-line::selection, .cm-s-material .CodeMirror-line > span::selection, .cm-s-material .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-material .CodeMirror-line::-moz-selection, .cm-s-material .CodeMirror-line > span::-moz-selection, .cm-s-material .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }\n\n.cm-s-material .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); }\n.cm-s-material .cm-keyword { color: rgba(199, 146, 234, 1); }\n.cm-s-material .cm-operator { color: rgba(233, 237, 237, 1); }\n.cm-s-material .cm-variable-2 { color: #80CBC4; }\n.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #82B1FF; }\n.cm-s-material .cm-builtin { color: #DECB6B; }\n.cm-s-material .cm-atom { color: #F77669; }\n.cm-s-material .cm-number { color: #F77669; }\n.cm-s-material .cm-def { color: rgba(233, 237, 237, 1); }\n.cm-s-material .cm-string { color: #C3E88D; }\n.cm-s-material .cm-string-2 { color: #80CBC4; }\n.cm-s-material .cm-comment { color: #546E7A; }\n.cm-s-material .cm-variable { color: #82B1FF; }\n.cm-s-material .cm-tag { color: #80CBC4; }\n.cm-s-material .cm-meta { color: #80CBC4; }\n.cm-s-material .cm-attribute { color: #FFCB6B; }\n.cm-s-material .cm-property { color: #80CBAE; }\n.cm-s-material .cm-qualifier { color: #DECB6B; }\n.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #DECB6B; }\n.cm-s-material .cm-tag { color: rgba(255, 83, 112, 1); }\n.cm-s-material .cm-error {\n  color: rgba(255, 255, 255, 1.0);\n  background-color: #EC5F67;\n}\n.cm-s-material .CodeMirror-matchingbracket {\n  text-decoration: underline;\n  color: white !important;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/mbo.css",
    "content": "/****************************************************************/\n/*   Based on mbonaci's Brackets mbo theme                      */\n/*   https://github.com/mbonaci/global/blob/master/Mbo.tmTheme  */\n/*   Create your own: http://tmtheme-editor.herokuapp.com       */\n/****************************************************************/\n\n.cm-s-mbo.CodeMirror { background: #2c2c2c; color: #ffffec; }\n.cm-s-mbo div.CodeMirror-selected { background: #716C62; }\n.cm-s-mbo .CodeMirror-line::selection, .cm-s-mbo .CodeMirror-line > span::selection, .cm-s-mbo .CodeMirror-line > span > span::selection { background: rgba(113, 108, 98, .99); }\n.cm-s-mbo .CodeMirror-line::-moz-selection, .cm-s-mbo .CodeMirror-line > span::-moz-selection, .cm-s-mbo .CodeMirror-line > span > span::-moz-selection { background: rgba(113, 108, 98, .99); }\n.cm-s-mbo .CodeMirror-gutters { background: #4e4e4e; border-right: 0px; }\n.cm-s-mbo .CodeMirror-guttermarker { color: white; }\n.cm-s-mbo .CodeMirror-guttermarker-subtle { color: grey; }\n.cm-s-mbo .CodeMirror-linenumber { color: #dadada; }\n.cm-s-mbo .CodeMirror-cursor { border-left: 1px solid #ffffec; }\n\n.cm-s-mbo span.cm-comment { color: #95958a; }\n.cm-s-mbo span.cm-atom { color: #00a8c6; }\n.cm-s-mbo span.cm-number { color: #00a8c6; }\n\n.cm-s-mbo span.cm-property, .cm-s-mbo span.cm-attribute { color: #9ddfe9; }\n.cm-s-mbo span.cm-keyword { color: #ffb928; }\n.cm-s-mbo span.cm-string { color: #ffcf6c; }\n.cm-s-mbo span.cm-string.cm-property { color: #ffffec; }\n\n.cm-s-mbo span.cm-variable { color: #ffffec; }\n.cm-s-mbo span.cm-variable-2 { color: #00a8c6; }\n.cm-s-mbo span.cm-def { color: #ffffec; }\n.cm-s-mbo span.cm-bracket { color: #fffffc; font-weight: bold; }\n.cm-s-mbo span.cm-tag { color: #9ddfe9; }\n.cm-s-mbo span.cm-link { color: #f54b07; }\n.cm-s-mbo span.cm-error { border-bottom: #636363; color: #ffffec; }\n.cm-s-mbo span.cm-qualifier { color: #ffffec; }\n\n.cm-s-mbo .CodeMirror-activeline-background { background: #494b41; }\n.cm-s-mbo .CodeMirror-matchingbracket { color: #ffb928 !important; }\n.cm-s-mbo .CodeMirror-matchingtag { background: rgba(255, 255, 255, .37); }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/mdn-like.css",
    "content": "/*\n  MDN-LIKE Theme - Mozilla\n  Ported to CodeMirror by Peter Kroon <plakroon@gmail.com>\n  Report bugs/issues here: https://github.com/codemirror/CodeMirror/issues\n  GitHub: @peterkroon\n\n  The mdn-like theme is inspired on the displayed code examples at: https://developer.mozilla.org/en-US/docs/Web/CSS/animation\n\n*/\n.cm-s-mdn-like.CodeMirror { color: #999; background-color: #fff; }\n.cm-s-mdn-like div.CodeMirror-selected { background: #cfc; }\n.cm-s-mdn-like .CodeMirror-line::selection, .cm-s-mdn-like .CodeMirror-line > span::selection, .cm-s-mdn-like .CodeMirror-line > span > span::selection { background: #cfc; }\n.cm-s-mdn-like .CodeMirror-line::-moz-selection, .cm-s-mdn-like .CodeMirror-line > span::-moz-selection, .cm-s-mdn-like .CodeMirror-line > span > span::-moz-selection { background: #cfc; }\n\n.cm-s-mdn-like .CodeMirror-gutters { background: #f8f8f8; border-left: 6px solid rgba(0,83,159,0.65); color: #333; }\n.cm-s-mdn-like .CodeMirror-linenumber { color: #aaa; padding-left: 8px; }\n.cm-s-mdn-like .CodeMirror-cursor { border-left: 2px solid #222; }\n\n.cm-s-mdn-like .cm-keyword { color: #6262FF; }\n.cm-s-mdn-like .cm-atom { color: #F90; }\n.cm-s-mdn-like .cm-number { color:  #ca7841; }\n.cm-s-mdn-like .cm-def { color: #8DA6CE; }\n.cm-s-mdn-like span.cm-variable-2, .cm-s-mdn-like span.cm-tag { color: #690; }\n.cm-s-mdn-like span.cm-variable-3, .cm-s-mdn-like span.cm-def, .cm-s-mdn-like span.cm-type { color: #07a; }\n\n.cm-s-mdn-like .cm-variable { color: #07a; }\n.cm-s-mdn-like .cm-property { color: #905; }\n.cm-s-mdn-like .cm-qualifier { color: #690; }\n\n.cm-s-mdn-like .cm-operator { color: #cda869; }\n.cm-s-mdn-like .cm-comment { color:#777; font-weight:normal; }\n.cm-s-mdn-like .cm-string { color:#07a; font-style:italic; }\n.cm-s-mdn-like .cm-string-2 { color:#bd6b18; } /*?*/\n.cm-s-mdn-like .cm-meta { color: #000; } /*?*/\n.cm-s-mdn-like .cm-builtin { color: #9B7536; } /*?*/\n.cm-s-mdn-like .cm-tag { color: #997643; }\n.cm-s-mdn-like .cm-attribute { color: #d6bb6d; } /*?*/\n.cm-s-mdn-like .cm-header { color: #FF6400; }\n.cm-s-mdn-like .cm-hr { color: #AEAEAE; }\n.cm-s-mdn-like .cm-link { color:#ad9361; font-style:italic; text-decoration:none; }\n.cm-s-mdn-like .cm-error { border-bottom: 1px solid red; }\n\ndiv.cm-s-mdn-like .CodeMirror-activeline-background { background: #efefff; }\ndiv.cm-s-mdn-like span.CodeMirror-matchingbracket { outline:1px solid grey; color: inherit; }\n\n.cm-s-mdn-like.CodeMirror { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFcAAAAyCAYAAAAp8UeFAAAHvklEQVR42s2b63bcNgyEQZCSHCdt2vd/0tWF7I+Q6XgMXiTtuvU5Pl57ZQKkKHzEAOtF5KeIJBGJ8uvL599FRFREZhFx8DeXv8trn68RuGaC8TRfo3SNp9dlDDHedyLyTUTeRWStXKPZrjtpZxaRw5hPqozRs1N8/enzIiQRWcCgy4MUA0f+XWliDhyL8Lfyvx7ei/Ae3iQFHyw7U/59pQVIMEEPEz0G7XiwdRjzSfC3UTtz9vchIntxvry5iMgfIhJoEflOz2CQr3F5h/HfeFe+GTdLaKcu9L8LTeQb/R/7GgbsfKedyNdoHsN31uRPWrfZ5wsj/NzzRQHuToIdU3ahwnsKPxXCjJITuOsi7XLc7SG/v5GdALs7wf8JjTFiB5+QvTEfRyGOfX3Lrx8wxyQi3sNq46O7QahQiCsRFgqddjBouVEHOKDgXAQHD9gJCr5sMKkEdjwsarG/ww3BMHBU7OBjXnzdyY7SfCxf5/z6ATccrwlKuwC/jhznnPF4CgVzhhVf4xp2EixcBActO75iZ8/fM9zAs2OMzKdslgXWJ9XG8PQoOAMA5fGcsvORgv0doBXyHrCwfLJAOwo71QLNkb8n2Pl6EWiR7OCibtkPaz4Kc/0NNAze2gju3zOwekALDaCFPI5vjPFmgGY5AZqyGEvH1x7QfIb8YtxMnA/b+QQ0aQDAwc6JMFg8CbQZ4qoYEEHbRwNojuK3EHwd7VALSgq+MNDKzfT58T8qdpADrgW0GmgcAS1lhzztJmkAzcPNOQbsWEALBDSlMKUG0Eq4CLAQWvEVQ9WU57gZJwZtgPO3r9oBTQ9WO8TjqXINx8R0EYpiZEUWOF3FxkbJkgU9B2f41YBrIj5ZfsQa0M5kTgiAAqM3ShXLgu8XMqcrQBvJ0CL5pnTsfMB13oB8athpAq2XOQmcGmoACCLydx7nToa23ATaSIY2ichfOdPTGxlasXMLaL0MLZAOwAKIM+y8CmicobGdCcbbK9DzN+yYGVoNNI5iUKTMyYOjPse4A8SM1MmcXgU0toOq1yO/v8FOxlASyc7TgeYaAMBJHcY1CcCwGI/TK4AmDbDyKYBBtFUkRwto8gygiQEaByFgJ00BH2M8JWwQS1nafDXQCidWyOI8AcjDCSjCLk8ngObuAm3JAHAdubAmOaK06V8MNEsKPJOhobSprwQa6gD7DclRQdqcwL4zxqgBrQcabUiBLclRDKAlWp+etPkBaNMA0AKlrHwTdEByZAA4GM+SNluSY6wAzcMNewxmgig5Ks0nkrSpBvSaQHMdKTBAnLojOdYyGpQ254602ZILPdTD1hdlggdIm74jbTp8vDwF5ZYUeLWGJpWsh6XNyXgcYwVoJQTEhhTYkxzZjiU5npU2TaB979TQehlaAVq4kaGpiPwwwLkYUuBbQwocyQTv1tA0+1UFWoJF3iv1oq+qoSk8EQdJmwHkziIF7oOZk14EGitibAdjLYYK78H5vZOhtWpoI0ATGHs0Q8OMb4Ey+2bU2UYztCtA0wFAs7TplGLRVQCcqaFdGSPCeTI1QNIC52iWNzof6Uib7xjEp07mNNoUYmVosVItHrHzRlLgBn9LFyRHaQCtVUMbtTNhoXWiTOO9k/V8BdAc1Oq0ArSQs6/5SU0hckNy9NnXqQY0PGYo5dWJ7nINaN6o958FWin27aBaWRka1r5myvLOAm0j30eBJqCxHLReVclxhxOEN2JfDWjxBtAC7MIH1fVaGdoOp4qJYDgKtKPSFNID2gSnGldrCqkFZ+5UeQXQBIRrSwocbdZYQT/2LwRahBPBXoHrB8nxaGROST62DKUbQOMMzZIC9abkuELfQzQALWTnDNAm8KHWFOJgJ5+SHIvTPcmx1xQyZRhNL5Qci689aXMEaN/uNIWkEwDAvFpOZmgsBaaGnbs1NPa1Jm32gBZAIh1pCtG7TSH4aE0y1uVY4uqoFPisGlpP2rSA5qTecWn5agK6BzSpgAyD+wFaqhnYoSZ1Vwr8CmlTQbrcO3ZaX0NAEyMbYaAlyquFoLKK3SPby9CeVUPThrSJmkCAE0CrKUQadi4DrdSlWhmah0YL9z9vClH59YGbHx1J8VZTyAjQepJjmXwAKTDQI3omc3p1U4gDUf6RfcdYfrUp5ClAi2J3Ba6UOXGo+K+bQrjjssitG2SJzshaLwMtXgRagUNpYYoVkMSBLM+9GGiJZMvduG6DRZ4qc04DMPtQQxOjEtACmhO7K1AbNbQDEggZyJwscFpAGwENhoBeUwh3bWolhe8BTYVKxQEWrSUn/uhcM5KhvUu/+eQu0Lzhi+VrK0PrZZNDQKs9cpYUuFYgMVpD4/NxenJTiMCNqdUEUf1qZWjppLT5qSkkUZbCwkbZMSuVnu80hfSkzRbQeqCZSAh6huR4VtoM2gHAlLf72smuWgE+VV7XpE25Ab2WFDgyhnSuKbs4GuGzCjR+tIoUuMFg3kgcWKLTwRqanJQ2W00hAsenfaApRC42hbCvK1SlE0HtE9BGgneJO+ELamitD1YjjOYnNYVcraGhtKkW0EqVVeDx733I2NH581k1NNxNLG0i0IJ8/NjVaOZ0tYZ2Vtr0Xv7tPV3hkWp9EFkgS/J0vosngTaSoaG06WHi+xObQkaAdlbanP8B2+2l0f90LmUAAAAASUVORK5CYII=); }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/midnight.css",
    "content": "/* Based on the theme at http://bonsaiden.github.com/JavaScript-Garden */\n\n/*<!--match-->*/\n.cm-s-midnight span.CodeMirror-matchhighlight { background: #494949; }\n.cm-s-midnight.CodeMirror-focused span.CodeMirror-matchhighlight { background: #314D67 !important; }\n\n/*<!--activeline-->*/\n.cm-s-midnight .CodeMirror-activeline-background { background: #253540; }\n\n.cm-s-midnight.CodeMirror {\n    background: #0F192A;\n    color: #D1EDFF;\n}\n\n.cm-s-midnight div.CodeMirror-selected { background: #314D67; }\n.cm-s-midnight .CodeMirror-line::selection, .cm-s-midnight .CodeMirror-line > span::selection, .cm-s-midnight .CodeMirror-line > span > span::selection { background: rgba(49, 77, 103, .99); }\n.cm-s-midnight .CodeMirror-line::-moz-selection, .cm-s-midnight .CodeMirror-line > span::-moz-selection, .cm-s-midnight .CodeMirror-line > span > span::-moz-selection { background: rgba(49, 77, 103, .99); }\n.cm-s-midnight .CodeMirror-gutters { background: #0F192A; border-right: 1px solid; }\n.cm-s-midnight .CodeMirror-guttermarker { color: white; }\n.cm-s-midnight .CodeMirror-guttermarker-subtle { color: #d0d0d0; }\n.cm-s-midnight .CodeMirror-linenumber { color: #D0D0D0; }\n.cm-s-midnight .CodeMirror-cursor { border-left: 1px solid #F8F8F0; }\n\n.cm-s-midnight span.cm-comment { color: #428BDD; }\n.cm-s-midnight span.cm-atom { color: #AE81FF; }\n.cm-s-midnight span.cm-number { color: #D1EDFF; }\n\n.cm-s-midnight span.cm-property, .cm-s-midnight span.cm-attribute { color: #A6E22E; }\n.cm-s-midnight span.cm-keyword { color: #E83737; }\n.cm-s-midnight span.cm-string { color: #1DC116; }\n\n.cm-s-midnight span.cm-variable { color: #FFAA3E; }\n.cm-s-midnight span.cm-variable-2 { color: #FFAA3E; }\n.cm-s-midnight span.cm-def { color: #4DD; }\n.cm-s-midnight span.cm-bracket { color: #D1EDFF; }\n.cm-s-midnight span.cm-tag { color: #449; }\n.cm-s-midnight span.cm-link { color: #AE81FF; }\n.cm-s-midnight span.cm-error { background: #F92672; color: #F8F8F0; }\n\n.cm-s-midnight .CodeMirror-matchingbracket {\n  text-decoration: underline;\n  color: white !important;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/monokai.css",
    "content": "/* Based on Sublime Text's Monokai theme */\n\n.cm-s-monokai.CodeMirror { background: #272822; color: #f8f8f2; }\n.cm-s-monokai div.CodeMirror-selected { background: #49483E; }\n.cm-s-monokai .CodeMirror-line::selection, .cm-s-monokai .CodeMirror-line > span::selection, .cm-s-monokai .CodeMirror-line > span > span::selection { background: rgba(73, 72, 62, .99); }\n.cm-s-monokai .CodeMirror-line::-moz-selection, .cm-s-monokai .CodeMirror-line > span::-moz-selection, .cm-s-monokai .CodeMirror-line > span > span::-moz-selection { background: rgba(73, 72, 62, .99); }\n.cm-s-monokai .CodeMirror-gutters { background: #272822; border-right: 0px; }\n.cm-s-monokai .CodeMirror-guttermarker { color: white; }\n.cm-s-monokai .CodeMirror-guttermarker-subtle { color: #d0d0d0; }\n.cm-s-monokai .CodeMirror-linenumber { color: #d0d0d0; }\n.cm-s-monokai .CodeMirror-cursor { border-left: 1px solid #f8f8f0; }\n\n.cm-s-monokai span.cm-comment { color: #75715e; }\n.cm-s-monokai span.cm-atom { color: #ae81ff; }\n.cm-s-monokai span.cm-number { color: #ae81ff; }\n\n.cm-s-monokai span.cm-comment.cm-attribute { color: #97b757; }\n.cm-s-monokai span.cm-comment.cm-def { color: #bc9262; }\n.cm-s-monokai span.cm-comment.cm-tag { color: #bc6283; }\n.cm-s-monokai span.cm-comment.cm-type { color: #5998a6; }\n\n.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute { color: #a6e22e; }\n.cm-s-monokai span.cm-keyword { color: #f92672; }\n.cm-s-monokai span.cm-builtin { color: #66d9ef; }\n.cm-s-monokai span.cm-string { color: #e6db74; }\n\n.cm-s-monokai span.cm-variable { color: #f8f8f2; }\n.cm-s-monokai span.cm-variable-2 { color: #9effff; }\n.cm-s-monokai span.cm-variable-3, .cm-s-monokai span.cm-type { color: #66d9ef; }\n.cm-s-monokai span.cm-def { color: #fd971f; }\n.cm-s-monokai span.cm-bracket { color: #f8f8f2; }\n.cm-s-monokai span.cm-tag { color: #f92672; }\n.cm-s-monokai span.cm-header { color: #ae81ff; }\n.cm-s-monokai span.cm-link { color: #ae81ff; }\n.cm-s-monokai span.cm-error { background: #f92672; color: #f8f8f0; }\n\n.cm-s-monokai .CodeMirror-activeline-background { background: #373831; }\n.cm-s-monokai .CodeMirror-matchingbracket {\n  text-decoration: underline;\n  color: white !important;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/neat.css",
    "content": ".cm-s-neat span.cm-comment { color: #a86; }\n.cm-s-neat span.cm-keyword { line-height: 1em; font-weight: bold; color: blue; }\n.cm-s-neat span.cm-string { color: #a22; }\n.cm-s-neat span.cm-builtin { line-height: 1em; font-weight: bold; color: #077; }\n.cm-s-neat span.cm-special { line-height: 1em; font-weight: bold; color: #0aa; }\n.cm-s-neat span.cm-variable { color: black; }\n.cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; }\n.cm-s-neat span.cm-meta { color: #555; }\n.cm-s-neat span.cm-link { color: #3a3; }\n\n.cm-s-neat .CodeMirror-activeline-background { background: #e8f2ff; }\n.cm-s-neat .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/neo.css",
    "content": "/* neo theme for codemirror */\n\n/* Color scheme */\n\n.cm-s-neo.CodeMirror {\n  background-color:#ffffff;\n  color:#2e383c;\n  line-height:1.4375;\n}\n.cm-s-neo .cm-comment { color:#75787b; }\n.cm-s-neo .cm-keyword, .cm-s-neo .cm-property { color:#1d75b3; }\n.cm-s-neo .cm-atom,.cm-s-neo .cm-number { color:#75438a; }\n.cm-s-neo .cm-node,.cm-s-neo .cm-tag { color:#9c3328; }\n.cm-s-neo .cm-string { color:#b35e14; }\n.cm-s-neo .cm-variable,.cm-s-neo .cm-qualifier { color:#047d65; }\n\n\n/* Editor styling */\n\n.cm-s-neo pre {\n  padding:0;\n}\n\n.cm-s-neo .CodeMirror-gutters {\n  border:none;\n  border-right:10px solid transparent;\n  background-color:transparent;\n}\n\n.cm-s-neo .CodeMirror-linenumber {\n  padding:0;\n  color:#e0e2e5;\n}\n\n.cm-s-neo .CodeMirror-guttermarker { color: #1d75b3; }\n.cm-s-neo .CodeMirror-guttermarker-subtle { color: #e0e2e5; }\n\n.cm-s-neo .CodeMirror-cursor {\n  width: auto;\n  border: 0;\n  background: rgba(155,157,162,0.37);\n  z-index: 1;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/night.css",
    "content": "/* Loosely based on the Midnight Textmate theme */\n\n.cm-s-night.CodeMirror { background: #0a001f; color: #f8f8f8; }\n.cm-s-night div.CodeMirror-selected { background: #447; }\n.cm-s-night .CodeMirror-line::selection, .cm-s-night .CodeMirror-line > span::selection, .cm-s-night .CodeMirror-line > span > span::selection { background: rgba(68, 68, 119, .99); }\n.cm-s-night .CodeMirror-line::-moz-selection, .cm-s-night .CodeMirror-line > span::-moz-selection, .cm-s-night .CodeMirror-line > span > span::-moz-selection { background: rgba(68, 68, 119, .99); }\n.cm-s-night .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; }\n.cm-s-night .CodeMirror-guttermarker { color: white; }\n.cm-s-night .CodeMirror-guttermarker-subtle { color: #bbb; }\n.cm-s-night .CodeMirror-linenumber { color: #f8f8f8; }\n.cm-s-night .CodeMirror-cursor { border-left: 1px solid white; }\n\n.cm-s-night span.cm-comment { color: #8900d1; }\n.cm-s-night span.cm-atom { color: #845dc4; }\n.cm-s-night span.cm-number, .cm-s-night span.cm-attribute { color: #ffd500; }\n.cm-s-night span.cm-keyword { color: #599eff; }\n.cm-s-night span.cm-string { color: #37f14a; }\n.cm-s-night span.cm-meta { color: #7678e2; }\n.cm-s-night span.cm-variable-2, .cm-s-night span.cm-tag { color: #99b2ff; }\n.cm-s-night span.cm-variable-3, .cm-s-night span.cm-def, .cm-s-night span.cm-type { color: white; }\n.cm-s-night span.cm-bracket { color: #8da6ce; }\n.cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; }\n.cm-s-night span.cm-link { color: #845dc4; }\n.cm-s-night span.cm-error { color: #9d1e15; }\n\n.cm-s-night .CodeMirror-activeline-background { background: #1C005A; }\n.cm-s-night .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/oceanic-next.css",
    "content": "/*\n\n    Name:       oceanic-next\n    Author:     Filype Pereira (https://github.com/fpereira1)\n\n    Original oceanic-next color scheme by Dmitri Voronianski (https://github.com/voronianski/oceanic-next-color-scheme)\n\n*/\n\n.cm-s-oceanic-next.CodeMirror { background: #304148; color: #f8f8f2; }\n.cm-s-oceanic-next div.CodeMirror-selected { background: rgba(101, 115, 126, 0.33); }\n.cm-s-oceanic-next .CodeMirror-line::selection, .cm-s-oceanic-next .CodeMirror-line > span::selection, .cm-s-oceanic-next .CodeMirror-line > span > span::selection { background: rgba(101, 115, 126, 0.33); }\n.cm-s-oceanic-next .CodeMirror-line::-moz-selection, .cm-s-oceanic-next .CodeMirror-line > span::-moz-selection, .cm-s-oceanic-next .CodeMirror-line > span > span::-moz-selection { background: rgba(101, 115, 126, 0.33); }\n.cm-s-oceanic-next .CodeMirror-gutters { background: #304148; border-right: 10px; }\n.cm-s-oceanic-next .CodeMirror-guttermarker { color: white; }\n.cm-s-oceanic-next .CodeMirror-guttermarker-subtle { color: #d0d0d0; }\n.cm-s-oceanic-next .CodeMirror-linenumber { color: #d0d0d0; }\n.cm-s-oceanic-next .CodeMirror-cursor { border-left: 1px solid #f8f8f0; }\n\n.cm-s-oceanic-next span.cm-comment { color: #65737E; }\n.cm-s-oceanic-next span.cm-atom { color: #C594C5; }\n.cm-s-oceanic-next span.cm-number { color: #F99157; }\n\n.cm-s-oceanic-next span.cm-property { color: #99C794; }\n.cm-s-oceanic-next span.cm-attribute,\n.cm-s-oceanic-next span.cm-keyword { color: #C594C5; }\n.cm-s-oceanic-next span.cm-builtin { color: #66d9ef; }\n.cm-s-oceanic-next span.cm-string { color: #99C794; }\n\n.cm-s-oceanic-next span.cm-variable,\n.cm-s-oceanic-next span.cm-variable-2,\n.cm-s-oceanic-next span.cm-variable-3 { color: #f8f8f2; }\n.cm-s-oceanic-next span.cm-def { color: #6699CC; }\n.cm-s-oceanic-next span.cm-bracket { color: #5FB3B3; }\n.cm-s-oceanic-next span.cm-tag { color: #C594C5; }\n.cm-s-oceanic-next span.cm-header { color: #C594C5; }\n.cm-s-oceanic-next span.cm-link { color: #C594C5; }\n.cm-s-oceanic-next span.cm-error { background: #C594C5; color: #f8f8f0; }\n\n.cm-s-oceanic-next .CodeMirror-activeline-background { background: rgba(101, 115, 126, 0.33); }\n.cm-s-oceanic-next .CodeMirror-matchingbracket {\n  text-decoration: underline;\n  color: white !important;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/panda-syntax.css",
    "content": "/*\n\tName:       Panda Syntax\n\tAuthor:     Siamak Mokhtari (http://github.com/siamak/)\n\tCodeMirror template by Siamak Mokhtari (https://github.com/siamak/atom-panda-syntax)\n*/\n.cm-s-panda-syntax {\n\tbackground: #292A2B;\n\tcolor: #E6E6E6;\n\tline-height: 1.5;\n\tfont-family: 'Operator Mono', 'Source Sans Pro', Menlo, Monaco, Consolas, Courier New, monospace;\n}\n.cm-s-panda-syntax .CodeMirror-cursor { border-color: #ff2c6d; }\n.cm-s-panda-syntax .CodeMirror-activeline-background {\n\tbackground: rgba(99, 123, 156, 0.1);\n}\n.cm-s-panda-syntax .CodeMirror-selected {\n\tbackground: #FFF;\n}\n.cm-s-panda-syntax .cm-comment {\n\tfont-style: italic;\n\tcolor: #676B79;\n}\n.cm-s-panda-syntax .cm-operator {\n\tcolor: #f3f3f3;\n}\n.cm-s-panda-syntax .cm-string {\n\tcolor: #19F9D8;\n}\n.cm-s-panda-syntax .cm-string-2 {\n    color: #FFB86C;\n}\n\n.cm-s-panda-syntax .cm-tag {\n\tcolor: #ff2c6d;\n}\n.cm-s-panda-syntax .cm-meta {\n\tcolor: #b084eb;\n}\n\n.cm-s-panda-syntax .cm-number {\n\tcolor: #FFB86C;\n}\n.cm-s-panda-syntax .cm-atom {\n\tcolor: #ff2c6d;\n}\n.cm-s-panda-syntax .cm-keyword {\n\tcolor: #FF75B5;\n}\n.cm-s-panda-syntax .cm-variable {\n\tcolor: #ffb86c;\n}\n.cm-s-panda-syntax .cm-variable-2 {\n\tcolor: #ff9ac1;\n}\n.cm-s-panda-syntax .cm-variable-3, .cm-s-panda-syntax .cm-type {\n\tcolor: #ff9ac1;\n}\n\n.cm-s-panda-syntax .cm-def {\n\tcolor: #e6e6e6;\n}\n.cm-s-panda-syntax .cm-property {\n\tcolor: #f3f3f3;\n}\n.cm-s-panda-syntax .cm-unit {\n    color: #ffb86c;\n}\n\n.cm-s-panda-syntax .cm-attribute {\n    color: #ffb86c;\n}\n\n.cm-s-panda-syntax .CodeMirror-matchingbracket {\n    border-bottom: 1px dotted #19F9D8;\n    padding-bottom: 2px;\n    color: #e6e6e6;\n}\n.cm-s-panda-syntax .CodeMirror-gutters {\n    background: #292a2b;\n    border-right-color: rgba(255, 255, 255, 0.1);\n}\n.cm-s-panda-syntax .CodeMirror-linenumber {\n    color: #e6e6e6;\n    opacity: 0.6;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/paraiso-dark.css",
    "content": "/*\n\n    Name:       Paraíso (Dark)\n    Author:     Jan T. Sott\n\n    Color scheme by Jan T. Sott (https://github.com/idleberg/Paraiso-CodeMirror)\n    Inspired by the art of Rubens LP (http://www.rubenslp.com.br)\n\n*/\n\n.cm-s-paraiso-dark.CodeMirror { background: #2f1e2e; color: #b9b6b0; }\n.cm-s-paraiso-dark div.CodeMirror-selected { background: #41323f; }\n.cm-s-paraiso-dark .CodeMirror-line::selection, .cm-s-paraiso-dark .CodeMirror-line > span::selection, .cm-s-paraiso-dark .CodeMirror-line > span > span::selection { background: rgba(65, 50, 63, .99); }\n.cm-s-paraiso-dark .CodeMirror-line::-moz-selection, .cm-s-paraiso-dark .CodeMirror-line > span::-moz-selection, .cm-s-paraiso-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(65, 50, 63, .99); }\n.cm-s-paraiso-dark .CodeMirror-gutters { background: #2f1e2e; border-right: 0px; }\n.cm-s-paraiso-dark .CodeMirror-guttermarker { color: #ef6155; }\n.cm-s-paraiso-dark .CodeMirror-guttermarker-subtle { color: #776e71; }\n.cm-s-paraiso-dark .CodeMirror-linenumber { color: #776e71; }\n.cm-s-paraiso-dark .CodeMirror-cursor { border-left: 1px solid #8d8687; }\n\n.cm-s-paraiso-dark span.cm-comment { color: #e96ba8; }\n.cm-s-paraiso-dark span.cm-atom { color: #815ba4; }\n.cm-s-paraiso-dark span.cm-number { color: #815ba4; }\n\n.cm-s-paraiso-dark span.cm-property, .cm-s-paraiso-dark span.cm-attribute { color: #48b685; }\n.cm-s-paraiso-dark span.cm-keyword { color: #ef6155; }\n.cm-s-paraiso-dark span.cm-string { color: #fec418; }\n\n.cm-s-paraiso-dark span.cm-variable { color: #48b685; }\n.cm-s-paraiso-dark span.cm-variable-2 { color: #06b6ef; }\n.cm-s-paraiso-dark span.cm-def { color: #f99b15; }\n.cm-s-paraiso-dark span.cm-bracket { color: #b9b6b0; }\n.cm-s-paraiso-dark span.cm-tag { color: #ef6155; }\n.cm-s-paraiso-dark span.cm-link { color: #815ba4; }\n.cm-s-paraiso-dark span.cm-error { background: #ef6155; color: #8d8687; }\n\n.cm-s-paraiso-dark .CodeMirror-activeline-background { background: #4D344A; }\n.cm-s-paraiso-dark .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/paraiso-light.css",
    "content": "/*\n\n    Name:       Paraíso (Light)\n    Author:     Jan T. Sott\n\n    Color scheme by Jan T. Sott (https://github.com/idleberg/Paraiso-CodeMirror)\n    Inspired by the art of Rubens LP (http://www.rubenslp.com.br)\n\n*/\n\n.cm-s-paraiso-light.CodeMirror { background: #e7e9db; color: #41323f; }\n.cm-s-paraiso-light div.CodeMirror-selected { background: #b9b6b0; }\n.cm-s-paraiso-light .CodeMirror-line::selection, .cm-s-paraiso-light .CodeMirror-line > span::selection, .cm-s-paraiso-light .CodeMirror-line > span > span::selection { background: #b9b6b0; }\n.cm-s-paraiso-light .CodeMirror-line::-moz-selection, .cm-s-paraiso-light .CodeMirror-line > span::-moz-selection, .cm-s-paraiso-light .CodeMirror-line > span > span::-moz-selection { background: #b9b6b0; }\n.cm-s-paraiso-light .CodeMirror-gutters { background: #e7e9db; border-right: 0px; }\n.cm-s-paraiso-light .CodeMirror-guttermarker { color: black; }\n.cm-s-paraiso-light .CodeMirror-guttermarker-subtle { color: #8d8687; }\n.cm-s-paraiso-light .CodeMirror-linenumber { color: #8d8687; }\n.cm-s-paraiso-light .CodeMirror-cursor { border-left: 1px solid #776e71; }\n\n.cm-s-paraiso-light span.cm-comment { color: #e96ba8; }\n.cm-s-paraiso-light span.cm-atom { color: #815ba4; }\n.cm-s-paraiso-light span.cm-number { color: #815ba4; }\n\n.cm-s-paraiso-light span.cm-property, .cm-s-paraiso-light span.cm-attribute { color: #48b685; }\n.cm-s-paraiso-light span.cm-keyword { color: #ef6155; }\n.cm-s-paraiso-light span.cm-string { color: #fec418; }\n\n.cm-s-paraiso-light span.cm-variable { color: #48b685; }\n.cm-s-paraiso-light span.cm-variable-2 { color: #06b6ef; }\n.cm-s-paraiso-light span.cm-def { color: #f99b15; }\n.cm-s-paraiso-light span.cm-bracket { color: #41323f; }\n.cm-s-paraiso-light span.cm-tag { color: #ef6155; }\n.cm-s-paraiso-light span.cm-link { color: #815ba4; }\n.cm-s-paraiso-light span.cm-error { background: #ef6155; color: #776e71; }\n\n.cm-s-paraiso-light .CodeMirror-activeline-background { background: #CFD1C4; }\n.cm-s-paraiso-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/pastel-on-dark.css",
    "content": "/**\n * Pastel On Dark theme ported from ACE editor\n * @license MIT\n * @copyright AtomicPages LLC 2014\n * @author Dennis Thompson, AtomicPages LLC\n * @version 1.1\n * @source https://github.com/atomicpages/codemirror-pastel-on-dark-theme\n */\n\n.cm-s-pastel-on-dark.CodeMirror {\n\tbackground: #2c2827;\n\tcolor: #8F938F;\n\tline-height: 1.5;\n}\n.cm-s-pastel-on-dark div.CodeMirror-selected { background: rgba(221,240,255,0.2); }\n.cm-s-pastel-on-dark .CodeMirror-line::selection, .cm-s-pastel-on-dark .CodeMirror-line > span::selection, .cm-s-pastel-on-dark .CodeMirror-line > span > span::selection { background: rgba(221,240,255,0.2); }\n.cm-s-pastel-on-dark .CodeMirror-line::-moz-selection, .cm-s-pastel-on-dark .CodeMirror-line > span::-moz-selection, .cm-s-pastel-on-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(221,240,255,0.2); }\n\n.cm-s-pastel-on-dark .CodeMirror-gutters {\n\tbackground: #34302f;\n\tborder-right: 0px;\n\tpadding: 0 3px;\n}\n.cm-s-pastel-on-dark .CodeMirror-guttermarker { color: white; }\n.cm-s-pastel-on-dark .CodeMirror-guttermarker-subtle { color: #8F938F; }\n.cm-s-pastel-on-dark .CodeMirror-linenumber { color: #8F938F; }\n.cm-s-pastel-on-dark .CodeMirror-cursor { border-left: 1px solid #A7A7A7; }\n.cm-s-pastel-on-dark span.cm-comment { color: #A6C6FF; }\n.cm-s-pastel-on-dark span.cm-atom { color: #DE8E30; }\n.cm-s-pastel-on-dark span.cm-number { color: #CCCCCC; }\n.cm-s-pastel-on-dark span.cm-property { color: #8F938F; }\n.cm-s-pastel-on-dark span.cm-attribute { color: #a6e22e; }\n.cm-s-pastel-on-dark span.cm-keyword { color: #AEB2F8; }\n.cm-s-pastel-on-dark span.cm-string { color: #66A968; }\n.cm-s-pastel-on-dark span.cm-variable { color: #AEB2F8; }\n.cm-s-pastel-on-dark span.cm-variable-2 { color: #BEBF55; }\n.cm-s-pastel-on-dark span.cm-variable-3, .cm-s-pastel-on-dark span.cm-type { color: #DE8E30; }\n.cm-s-pastel-on-dark span.cm-def { color: #757aD8; }\n.cm-s-pastel-on-dark span.cm-bracket { color: #f8f8f2; }\n.cm-s-pastel-on-dark span.cm-tag { color: #C1C144; }\n.cm-s-pastel-on-dark span.cm-link { color: #ae81ff; }\n.cm-s-pastel-on-dark span.cm-qualifier,.cm-s-pastel-on-dark span.cm-builtin { color: #C1C144; }\n.cm-s-pastel-on-dark span.cm-error {\n\tbackground: #757aD8;\n\tcolor: #f8f8f0;\n}\n.cm-s-pastel-on-dark .CodeMirror-activeline-background { background: rgba(255, 255, 255, 0.031); }\n.cm-s-pastel-on-dark .CodeMirror-matchingbracket {\n\tborder: 1px solid rgba(255,255,255,0.25);\n\tcolor: #8F938F !important;\n\tmargin: -1px -1px 0 -1px;\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/railscasts.css",
    "content": "/*\n\n    Name:       Railscasts\n    Author:     Ryan Bates (http://railscasts.com)\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-railscasts.CodeMirror {background: #2b2b2b; color: #f4f1ed;}\n.cm-s-railscasts div.CodeMirror-selected {background: #272935 !important;}\n.cm-s-railscasts .CodeMirror-gutters {background: #2b2b2b; border-right: 0px;}\n.cm-s-railscasts .CodeMirror-linenumber {color: #5a647e;}\n.cm-s-railscasts .CodeMirror-cursor {border-left: 1px solid #d4cfc9 !important;}\n\n.cm-s-railscasts span.cm-comment {color: #bc9458;}\n.cm-s-railscasts span.cm-atom {color: #b6b3eb;}\n.cm-s-railscasts span.cm-number {color: #b6b3eb;}\n\n.cm-s-railscasts span.cm-property, .cm-s-railscasts span.cm-attribute {color: #a5c261;}\n.cm-s-railscasts span.cm-keyword {color: #da4939;}\n.cm-s-railscasts span.cm-string {color: #ffc66d;}\n\n.cm-s-railscasts span.cm-variable {color: #a5c261;}\n.cm-s-railscasts span.cm-variable-2 {color: #6d9cbe;}\n.cm-s-railscasts span.cm-def {color: #cc7833;}\n.cm-s-railscasts span.cm-error {background: #da4939; color: #d4cfc9;}\n.cm-s-railscasts span.cm-bracket {color: #f4f1ed;}\n.cm-s-railscasts span.cm-tag {color: #da4939;}\n.cm-s-railscasts span.cm-link {color: #b6b3eb;}\n\n.cm-s-railscasts .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}\n.cm-s-railscasts .CodeMirror-activeline-background { background: #303040; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/rubyblue.css",
    "content": ".cm-s-rubyblue.CodeMirror { background: #112435; color: white; }\n.cm-s-rubyblue div.CodeMirror-selected { background: #38566F; }\n.cm-s-rubyblue .CodeMirror-line::selection, .cm-s-rubyblue .CodeMirror-line > span::selection, .cm-s-rubyblue .CodeMirror-line > span > span::selection { background: rgba(56, 86, 111, 0.99); }\n.cm-s-rubyblue .CodeMirror-line::-moz-selection, .cm-s-rubyblue .CodeMirror-line > span::-moz-selection, .cm-s-rubyblue .CodeMirror-line > span > span::-moz-selection { background: rgba(56, 86, 111, 0.99); }\n.cm-s-rubyblue .CodeMirror-gutters { background: #1F4661; border-right: 7px solid #3E7087; }\n.cm-s-rubyblue .CodeMirror-guttermarker { color: white; }\n.cm-s-rubyblue .CodeMirror-guttermarker-subtle { color: #3E7087; }\n.cm-s-rubyblue .CodeMirror-linenumber { color: white; }\n.cm-s-rubyblue .CodeMirror-cursor { border-left: 1px solid white; }\n\n.cm-s-rubyblue span.cm-comment { color: #999; font-style:italic; line-height: 1em; }\n.cm-s-rubyblue span.cm-atom { color: #F4C20B; }\n.cm-s-rubyblue span.cm-number, .cm-s-rubyblue span.cm-attribute { color: #82C6E0; }\n.cm-s-rubyblue span.cm-keyword { color: #F0F; }\n.cm-s-rubyblue span.cm-string { color: #F08047; }\n.cm-s-rubyblue span.cm-meta { color: #F0F; }\n.cm-s-rubyblue span.cm-variable-2, .cm-s-rubyblue span.cm-tag { color: #7BD827; }\n.cm-s-rubyblue span.cm-variable-3, .cm-s-rubyblue span.cm-def, .cm-s-rubyblue span.cm-type { color: white; }\n.cm-s-rubyblue span.cm-bracket { color: #F0F; }\n.cm-s-rubyblue span.cm-link { color: #F4C20B; }\n.cm-s-rubyblue span.CodeMirror-matchingbracket { color:#F0F !important; }\n.cm-s-rubyblue span.cm-builtin, .cm-s-rubyblue span.cm-special { color: #FF9D00; }\n.cm-s-rubyblue span.cm-error { color: #AF2018; }\n\n.cm-s-rubyblue .CodeMirror-activeline-background { background: #173047; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/seti.css",
    "content": "/*\n\n    Name:       seti\n    Author:     Michael Kaminsky (http://github.com/mkaminsky11)\n\n    Original seti color scheme by Jesse Weed (https://github.com/jesseweed/seti-syntax)\n\n*/\n\n\n.cm-s-seti.CodeMirror {\n  background-color: #151718 !important;\n  color: #CFD2D1 !important;\n  border: none;\n}\n.cm-s-seti .CodeMirror-gutters {\n  color: #404b53;\n  background-color: #0E1112;\n  border: none;\n}\n.cm-s-seti .CodeMirror-cursor { border-left: solid thin #f8f8f0; }\n.cm-s-seti .CodeMirror-linenumber { color: #6D8A88; }\n.cm-s-seti.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }\n.cm-s-seti .CodeMirror-line::selection, .cm-s-seti .CodeMirror-line > span::selection, .cm-s-seti .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-seti .CodeMirror-line::-moz-selection, .cm-s-seti .CodeMirror-line > span::-moz-selection, .cm-s-seti .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-seti span.cm-comment { color: #41535b; }\n.cm-s-seti span.cm-string, .cm-s-seti span.cm-string-2 { color: #55b5db; }\n.cm-s-seti span.cm-number { color: #cd3f45; }\n.cm-s-seti span.cm-variable { color: #55b5db; }\n.cm-s-seti span.cm-variable-2 { color: #a074c4; }\n.cm-s-seti span.cm-def { color: #55b5db; }\n.cm-s-seti span.cm-keyword { color: #ff79c6; }\n.cm-s-seti span.cm-operator { color: #9fca56; }\n.cm-s-seti span.cm-keyword { color: #e6cd69; }\n.cm-s-seti span.cm-atom { color: #cd3f45; }\n.cm-s-seti span.cm-meta { color: #55b5db; }\n.cm-s-seti span.cm-tag { color: #55b5db; }\n.cm-s-seti span.cm-attribute { color: #9fca56; }\n.cm-s-seti span.cm-qualifier { color: #9fca56; }\n.cm-s-seti span.cm-property { color: #a074c4; }\n.cm-s-seti span.cm-variable-3, .cm-s-seti span.cm-type { color: #9fca56; }\n.cm-s-seti span.cm-builtin { color: #9fca56; }\n.cm-s-seti .CodeMirror-activeline-background { background: #101213; }\n.cm-s-seti .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/shadowfox.css",
    "content": "/*\n\n    Name:       shadowfox\n    Author:     overdodactyl (http://github.com/overdodactyl)\n\n    Original shadowfox color scheme by Firefox\n\n*/\n\n.cm-s-shadowfox.CodeMirror { background: #2a2a2e; color: #b1b1b3; }\n.cm-s-shadowfox div.CodeMirror-selected { background: #353B48; }\n.cm-s-shadowfox .CodeMirror-line::selection, .cm-s-shadowfox .CodeMirror-line > span::selection, .cm-s-shadowfox .CodeMirror-line > span > span::selection { background: #353B48; }\n.cm-s-shadowfox .CodeMirror-line::-moz-selection, .cm-s-shadowfox .CodeMirror-line > span::-moz-selection, .cm-s-shadowfox .CodeMirror-line > span > span::-moz-selection { background: #353B48; }\n.cm-s-shadowfox .CodeMirror-gutters { background: #0c0c0d ; border-right: 1px solid #0c0c0d; }\n.cm-s-shadowfox .CodeMirror-guttermarker { color: #555; }\n.cm-s-shadowfox .CodeMirror-linenumber { color: #939393; }\n.cm-s-shadowfox .CodeMirror-cursor { border-left: 1px solid #fff; }\n\n.cm-s-shadowfox span.cm-comment { color: #939393; }\n.cm-s-shadowfox span.cm-atom { color: #FF7DE9; }\n.cm-s-shadowfox span.cm-quote { color: #FF7DE9; }\n.cm-s-shadowfox span.cm-builtin { color: #FF7DE9; }\n.cm-s-shadowfox span.cm-attribute { color: #FF7DE9; }\n.cm-s-shadowfox span.cm-keyword { color: #FF7DE9; }\n.cm-s-shadowfox span.cm-error { color: #FF7DE9; }\n\n.cm-s-shadowfox span.cm-number { color: #6B89FF; }\n.cm-s-shadowfox span.cm-string { color: #6B89FF; }\n.cm-s-shadowfox span.cm-string-2 { color: #6B89FF; }\n\n.cm-s-shadowfox span.cm-meta { color: #939393; }\n.cm-s-shadowfox span.cm-hr { color: #939393; }\n\n.cm-s-shadowfox span.cm-header { color: #75BFFF; }\n.cm-s-shadowfox span.cm-qualifier { color: #75BFFF; }\n.cm-s-shadowfox span.cm-variable-2 { color: #75BFFF; }\n\n.cm-s-shadowfox span.cm-property { color: #86DE74; }\n\n.cm-s-shadowfox span.cm-def { color: #75BFFF; }\n.cm-s-shadowfox span.cm-bracket { color: #75BFFF; }\n.cm-s-shadowfox span.cm-tag { color: #75BFFF; }\n.cm-s-shadowfox span.cm-link:visited { color: #75BFFF; }\n\n.cm-s-shadowfox span.cm-variable { color: #B98EFF; }\n.cm-s-shadowfox span.cm-variable-3 { color: #d7d7db; }\n.cm-s-shadowfox span.cm-link { color: #737373; }\n.cm-s-shadowfox span.cm-operator { color: #b1b1b3; }\n.cm-s-shadowfox span.cm-special { color: #d7d7db; }\n\n.cm-s-shadowfox .CodeMirror-activeline-background { background: rgba(185, 215, 253, .15) }\n.cm-s-shadowfox .CodeMirror-matchingbracket { outline: solid 1px rgba(255, 255, 255, .25); color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/solarized.css",
    "content": "/*\nSolarized theme for code-mirror\nhttp://ethanschoonover.com/solarized\n*/\n\n/*\nSolarized color palette\nhttp://ethanschoonover.com/solarized/img/solarized-palette.png\n*/\n\n.solarized.base03 { color: #002b36; }\n.solarized.base02 { color: #073642; }\n.solarized.base01 { color: #586e75; }\n.solarized.base00 { color: #657b83; }\n.solarized.base0 { color: #839496; }\n.solarized.base1 { color: #93a1a1; }\n.solarized.base2 { color: #eee8d5; }\n.solarized.base3  { color: #fdf6e3; }\n.solarized.solar-yellow  { color: #b58900; }\n.solarized.solar-orange  { color: #cb4b16; }\n.solarized.solar-red { color: #dc322f; }\n.solarized.solar-magenta { color: #d33682; }\n.solarized.solar-violet  { color: #6c71c4; }\n.solarized.solar-blue { color: #268bd2; }\n.solarized.solar-cyan { color: #2aa198; }\n.solarized.solar-green { color: #859900; }\n\n/* Color scheme for code-mirror */\n\n.cm-s-solarized {\n  line-height: 1.45em;\n  color-profile: sRGB;\n  rendering-intent: auto;\n}\n.cm-s-solarized.cm-s-dark {\n  color: #839496;\n  background-color: #002b36;\n  text-shadow: #002b36 0 1px;\n}\n.cm-s-solarized.cm-s-light {\n  background-color: #fdf6e3;\n  color: #657b83;\n  text-shadow: #eee8d5 0 1px;\n}\n\n.cm-s-solarized .CodeMirror-widget {\n  text-shadow: none;\n}\n\n.cm-s-solarized .cm-header { color: #586e75; }\n.cm-s-solarized .cm-quote { color: #93a1a1; }\n\n.cm-s-solarized .cm-keyword { color: #cb4b16; }\n.cm-s-solarized .cm-atom { color: #d33682; }\n.cm-s-solarized .cm-number { color: #d33682; }\n.cm-s-solarized .cm-def { color: #2aa198; }\n\n.cm-s-solarized .cm-variable { color: #839496; }\n.cm-s-solarized .cm-variable-2 { color: #b58900; }\n.cm-s-solarized .cm-variable-3, .cm-s-solarized .cm-type { color: #6c71c4; }\n\n.cm-s-solarized .cm-property { color: #2aa198; }\n.cm-s-solarized .cm-operator { color: #6c71c4; }\n\n.cm-s-solarized .cm-comment { color: #586e75; font-style:italic; }\n\n.cm-s-solarized .cm-string { color: #859900; }\n.cm-s-solarized .cm-string-2 { color: #b58900; }\n\n.cm-s-solarized .cm-meta { color: #859900; }\n.cm-s-solarized .cm-qualifier { color: #b58900; }\n.cm-s-solarized .cm-builtin { color: #d33682; }\n.cm-s-solarized .cm-bracket { color: #cb4b16; }\n.cm-s-solarized .CodeMirror-matchingbracket { color: #859900; }\n.cm-s-solarized .CodeMirror-nonmatchingbracket { color: #dc322f; }\n.cm-s-solarized .cm-tag { color: #93a1a1; }\n.cm-s-solarized .cm-attribute { color: #2aa198; }\n.cm-s-solarized .cm-hr {\n  color: transparent;\n  border-top: 1px solid #586e75;\n  display: block;\n}\n.cm-s-solarized .cm-link { color: #93a1a1; cursor: pointer; }\n.cm-s-solarized .cm-special { color: #6c71c4; }\n.cm-s-solarized .cm-em {\n  color: #999;\n  text-decoration: underline;\n  text-decoration-style: dotted;\n}\n.cm-s-solarized .cm-error,\n.cm-s-solarized .cm-invalidchar {\n  color: #586e75;\n  border-bottom: 1px dotted #dc322f;\n}\n\n.cm-s-solarized.cm-s-dark div.CodeMirror-selected { background: #073642; }\n.cm-s-solarized.cm-s-dark.CodeMirror ::selection { background: rgba(7, 54, 66, 0.99); }\n.cm-s-solarized.cm-s-dark .CodeMirror-line::-moz-selection, .cm-s-dark .CodeMirror-line > span::-moz-selection, .cm-s-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(7, 54, 66, 0.99); }\n\n.cm-s-solarized.cm-s-light div.CodeMirror-selected { background: #eee8d5; }\n.cm-s-solarized.cm-s-light .CodeMirror-line::selection, .cm-s-light .CodeMirror-line > span::selection, .cm-s-light .CodeMirror-line > span > span::selection { background: #eee8d5; }\n.cm-s-solarized.cm-s-light .CodeMirror-line::-moz-selection, .cm-s-ligh .CodeMirror-line > span::-moz-selection, .cm-s-ligh .CodeMirror-line > span > span::-moz-selection { background: #eee8d5; }\n\n/* Editor styling */\n\n\n\n/* Little shadow on the view-port of the buffer view */\n.cm-s-solarized.CodeMirror {\n  -moz-box-shadow: inset 7px 0 12px -6px #000;\n  -webkit-box-shadow: inset 7px 0 12px -6px #000;\n  box-shadow: inset 7px 0 12px -6px #000;\n}\n\n/* Remove gutter border */\n.cm-s-solarized .CodeMirror-gutters {\n  border-right: 0;\n}\n\n/* Gutter colors and line number styling based of color scheme (dark / light) */\n\n/* Dark */\n.cm-s-solarized.cm-s-dark .CodeMirror-gutters {\n  background-color: #073642;\n}\n\n.cm-s-solarized.cm-s-dark .CodeMirror-linenumber {\n  color: #586e75;\n  text-shadow: #021014 0 -1px;\n}\n\n/* Light */\n.cm-s-solarized.cm-s-light .CodeMirror-gutters {\n  background-color: #eee8d5;\n}\n\n.cm-s-solarized.cm-s-light .CodeMirror-linenumber {\n  color: #839496;\n}\n\n/* Common */\n.cm-s-solarized .CodeMirror-linenumber {\n  padding: 0 5px;\n}\n.cm-s-solarized .CodeMirror-guttermarker-subtle { color: #586e75; }\n.cm-s-solarized.cm-s-dark .CodeMirror-guttermarker { color: #ddd; }\n.cm-s-solarized.cm-s-light .CodeMirror-guttermarker { color: #cb4b16; }\n\n.cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text {\n  color: #586e75;\n}\n\n/* Cursor */\n.cm-s-solarized .CodeMirror-cursor { border-left: 1px solid #819090; }\n\n/* Fat cursor */\n.cm-s-solarized.cm-s-light.cm-fat-cursor .CodeMirror-cursor { background: #77ee77; }\n.cm-s-solarized.cm-s-light .cm-animate-fat-cursor { background-color: #77ee77; }\n.cm-s-solarized.cm-s-dark.cm-fat-cursor .CodeMirror-cursor { background: #586e75; }\n.cm-s-solarized.cm-s-dark .cm-animate-fat-cursor { background-color: #586e75; }\n\n/* Active line */\n.cm-s-solarized.cm-s-dark .CodeMirror-activeline-background {\n  background: rgba(255, 255, 255, 0.06);\n}\n.cm-s-solarized.cm-s-light .CodeMirror-activeline-background {\n  background: rgba(0, 0, 0, 0.06);\n}\n"
  },
  {
    "path": "third_party/CodeMirror/theme/ssms.css",
    "content": ".cm-s-ssms span.cm-keyword { color: blue; }\n.cm-s-ssms span.cm-comment { color: darkgreen; }\n.cm-s-ssms span.cm-string { color: red; }\n.cm-s-ssms span.cm-def { color: black; }\n.cm-s-ssms span.cm-variable { color: black; }\n.cm-s-ssms span.cm-variable-2 { color: black; }\n.cm-s-ssms span.cm-atom { color: darkgray; }\n.cm-s-ssms .CodeMirror-linenumber { color: teal; }\n.cm-s-ssms .CodeMirror-activeline-background { background: #ffffff; }\n.cm-s-ssms span.cm-string-2 { color: #FF00FF; }\n.cm-s-ssms span.cm-operator, \n.cm-s-ssms span.cm-bracket, \n.cm-s-ssms span.cm-punctuation { color: darkgray; }\n.cm-s-ssms .CodeMirror-gutters { border-right: 3px solid #ffee62; background-color: #ffffff; }\n.cm-s-ssms div.CodeMirror-selected { background: #ADD6FF; }\n\n"
  },
  {
    "path": "third_party/CodeMirror/theme/the-matrix.css",
    "content": ".cm-s-the-matrix.CodeMirror { background: #000000; color: #00FF00; }\n.cm-s-the-matrix div.CodeMirror-selected { background: #2D2D2D; }\n.cm-s-the-matrix .CodeMirror-line::selection, .cm-s-the-matrix .CodeMirror-line > span::selection, .cm-s-the-matrix .CodeMirror-line > span > span::selection { background: rgba(45, 45, 45, 0.99); }\n.cm-s-the-matrix .CodeMirror-line::-moz-selection, .cm-s-the-matrix .CodeMirror-line > span::-moz-selection, .cm-s-the-matrix .CodeMirror-line > span > span::-moz-selection { background: rgba(45, 45, 45, 0.99); }\n.cm-s-the-matrix .CodeMirror-gutters { background: #060; border-right: 2px solid #00FF00; }\n.cm-s-the-matrix .CodeMirror-guttermarker { color: #0f0; }\n.cm-s-the-matrix .CodeMirror-guttermarker-subtle { color: white; }\n.cm-s-the-matrix .CodeMirror-linenumber { color: #FFFFFF; }\n.cm-s-the-matrix .CodeMirror-cursor { border-left: 1px solid #00FF00; }\n\n.cm-s-the-matrix span.cm-keyword { color: #008803; font-weight: bold; }\n.cm-s-the-matrix span.cm-atom { color: #3FF; }\n.cm-s-the-matrix span.cm-number { color: #FFB94F; }\n.cm-s-the-matrix span.cm-def { color: #99C; }\n.cm-s-the-matrix span.cm-variable { color: #F6C; }\n.cm-s-the-matrix span.cm-variable-2 { color: #C6F; }\n.cm-s-the-matrix span.cm-variable-3, .cm-s-the-matrix span.cm-type { color: #96F; }\n.cm-s-the-matrix span.cm-property { color: #62FFA0; }\n.cm-s-the-matrix span.cm-operator { color: #999; }\n.cm-s-the-matrix span.cm-comment { color: #CCCCCC; }\n.cm-s-the-matrix span.cm-string { color: #39C; }\n.cm-s-the-matrix span.cm-meta { color: #C9F; }\n.cm-s-the-matrix span.cm-qualifier { color: #FFF700; }\n.cm-s-the-matrix span.cm-builtin { color: #30a; }\n.cm-s-the-matrix span.cm-bracket { color: #cc7; }\n.cm-s-the-matrix span.cm-tag { color: #FFBD40; }\n.cm-s-the-matrix span.cm-attribute { color: #FFF700; }\n.cm-s-the-matrix span.cm-error { color: #FF0000; }\n\n.cm-s-the-matrix .CodeMirror-activeline-background { background: #040; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/tomorrow-night-bright.css",
    "content": "/*\n\n    Name:       Tomorrow Night - Bright\n    Author:     Chris Kempson\n\n    Port done by Gerard Braad <me@gbraad.nl>\n\n*/\n\n.cm-s-tomorrow-night-bright.CodeMirror { background: #000000; color: #eaeaea; }\n.cm-s-tomorrow-night-bright div.CodeMirror-selected { background: #424242; }\n.cm-s-tomorrow-night-bright .CodeMirror-gutters { background: #000000; border-right: 0px; }\n.cm-s-tomorrow-night-bright .CodeMirror-guttermarker { color: #e78c45; }\n.cm-s-tomorrow-night-bright .CodeMirror-guttermarker-subtle { color: #777; }\n.cm-s-tomorrow-night-bright .CodeMirror-linenumber { color: #424242; }\n.cm-s-tomorrow-night-bright .CodeMirror-cursor { border-left: 1px solid #6A6A6A; }\n\n.cm-s-tomorrow-night-bright span.cm-comment { color: #d27b53; }\n.cm-s-tomorrow-night-bright span.cm-atom { color: #a16a94; }\n.cm-s-tomorrow-night-bright span.cm-number { color: #a16a94; }\n\n.cm-s-tomorrow-night-bright span.cm-property, .cm-s-tomorrow-night-bright span.cm-attribute { color: #99cc99; }\n.cm-s-tomorrow-night-bright span.cm-keyword { color: #d54e53; }\n.cm-s-tomorrow-night-bright span.cm-string { color: #e7c547; }\n\n.cm-s-tomorrow-night-bright span.cm-variable { color: #b9ca4a; }\n.cm-s-tomorrow-night-bright span.cm-variable-2 { color: #7aa6da; }\n.cm-s-tomorrow-night-bright span.cm-def { color: #e78c45; }\n.cm-s-tomorrow-night-bright span.cm-bracket { color: #eaeaea; }\n.cm-s-tomorrow-night-bright span.cm-tag { color: #d54e53; }\n.cm-s-tomorrow-night-bright span.cm-link { color: #a16a94; }\n.cm-s-tomorrow-night-bright span.cm-error { background: #d54e53; color: #6A6A6A; }\n\n.cm-s-tomorrow-night-bright .CodeMirror-activeline-background { background: #2a2a2a; }\n.cm-s-tomorrow-night-bright .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/tomorrow-night-eighties.css",
    "content": "/*\n\n    Name:       Tomorrow Night - Eighties\n    Author:     Chris Kempson\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-tomorrow-night-eighties.CodeMirror { background: #000000; color: #CCCCCC; }\n.cm-s-tomorrow-night-eighties div.CodeMirror-selected { background: #2D2D2D; }\n.cm-s-tomorrow-night-eighties .CodeMirror-line::selection, .cm-s-tomorrow-night-eighties .CodeMirror-line > span::selection, .cm-s-tomorrow-night-eighties .CodeMirror-line > span > span::selection { background: rgba(45, 45, 45, 0.99); }\n.cm-s-tomorrow-night-eighties .CodeMirror-line::-moz-selection, .cm-s-tomorrow-night-eighties .CodeMirror-line > span::-moz-selection, .cm-s-tomorrow-night-eighties .CodeMirror-line > span > span::-moz-selection { background: rgba(45, 45, 45, 0.99); }\n.cm-s-tomorrow-night-eighties .CodeMirror-gutters { background: #000000; border-right: 0px; }\n.cm-s-tomorrow-night-eighties .CodeMirror-guttermarker { color: #f2777a; }\n.cm-s-tomorrow-night-eighties .CodeMirror-guttermarker-subtle { color: #777; }\n.cm-s-tomorrow-night-eighties .CodeMirror-linenumber { color: #515151; }\n.cm-s-tomorrow-night-eighties .CodeMirror-cursor { border-left: 1px solid #6A6A6A; }\n\n.cm-s-tomorrow-night-eighties span.cm-comment { color: #d27b53; }\n.cm-s-tomorrow-night-eighties span.cm-atom { color: #a16a94; }\n.cm-s-tomorrow-night-eighties span.cm-number { color: #a16a94; }\n\n.cm-s-tomorrow-night-eighties span.cm-property, .cm-s-tomorrow-night-eighties span.cm-attribute { color: #99cc99; }\n.cm-s-tomorrow-night-eighties span.cm-keyword { color: #f2777a; }\n.cm-s-tomorrow-night-eighties span.cm-string { color: #ffcc66; }\n\n.cm-s-tomorrow-night-eighties span.cm-variable { color: #99cc99; }\n.cm-s-tomorrow-night-eighties span.cm-variable-2 { color: #6699cc; }\n.cm-s-tomorrow-night-eighties span.cm-def { color: #f99157; }\n.cm-s-tomorrow-night-eighties span.cm-bracket { color: #CCCCCC; }\n.cm-s-tomorrow-night-eighties span.cm-tag { color: #f2777a; }\n.cm-s-tomorrow-night-eighties span.cm-link { color: #a16a94; }\n.cm-s-tomorrow-night-eighties span.cm-error { background: #f2777a; color: #6A6A6A; }\n\n.cm-s-tomorrow-night-eighties .CodeMirror-activeline-background { background: #343600; }\n.cm-s-tomorrow-night-eighties .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/ttcn.css",
    "content": ".cm-s-ttcn .cm-quote { color: #090; }\n.cm-s-ttcn .cm-negative { color: #d44; }\n.cm-s-ttcn .cm-positive { color: #292; }\n.cm-s-ttcn .cm-header, .cm-strong { font-weight: bold; }\n.cm-s-ttcn .cm-em { font-style: italic; }\n.cm-s-ttcn .cm-link { text-decoration: underline; }\n.cm-s-ttcn .cm-strikethrough { text-decoration: line-through; }\n.cm-s-ttcn .cm-header { color: #00f; font-weight: bold; }\n\n.cm-s-ttcn .cm-atom { color: #219; }\n.cm-s-ttcn .cm-attribute { color: #00c; }\n.cm-s-ttcn .cm-bracket { color: #997; }\n.cm-s-ttcn .cm-comment { color: #333333; }\n.cm-s-ttcn .cm-def { color: #00f; }\n.cm-s-ttcn .cm-em { font-style: italic; }\n.cm-s-ttcn .cm-error { color: #f00; }\n.cm-s-ttcn .cm-hr { color: #999; }\n.cm-s-ttcn .cm-invalidchar { color: #f00; }\n.cm-s-ttcn .cm-keyword { font-weight:bold; }\n.cm-s-ttcn .cm-link { color: #00c; text-decoration: underline; }\n.cm-s-ttcn .cm-meta { color: #555; }\n.cm-s-ttcn .cm-negative { color: #d44; }\n.cm-s-ttcn .cm-positive { color: #292; }\n.cm-s-ttcn .cm-qualifier { color: #555; }\n.cm-s-ttcn .cm-strikethrough { text-decoration: line-through; }\n.cm-s-ttcn .cm-string { color: #006400; }\n.cm-s-ttcn .cm-string-2 { color: #f50; }\n.cm-s-ttcn .cm-strong { font-weight: bold; }\n.cm-s-ttcn .cm-tag { color: #170; }\n.cm-s-ttcn .cm-variable { color: #8B2252; }\n.cm-s-ttcn .cm-variable-2 { color: #05a; }\n.cm-s-ttcn .cm-variable-3, .cm-s-ttcn .cm-type { color: #085; }\n\n.cm-s-ttcn .cm-invalidchar { color: #f00; }\n\n/* ASN */\n.cm-s-ttcn .cm-accessTypes,\n.cm-s-ttcn .cm-compareTypes { color: #27408B; }\n.cm-s-ttcn .cm-cmipVerbs { color: #8B2252; }\n.cm-s-ttcn .cm-modifier { color:#D2691E; }\n.cm-s-ttcn .cm-status { color:#8B4545; }\n.cm-s-ttcn .cm-storage { color:#A020F0; }\n.cm-s-ttcn .cm-tags { color:#006400; }\n\n/* CFG */\n.cm-s-ttcn .cm-externalCommands { color: #8B4545; font-weight:bold; }\n.cm-s-ttcn .cm-fileNCtrlMaskOptions,\n.cm-s-ttcn .cm-sectionTitle { color: #2E8B57; font-weight:bold; }\n\n/* TTCN */\n.cm-s-ttcn .cm-booleanConsts,\n.cm-s-ttcn .cm-otherConsts,\n.cm-s-ttcn .cm-verdictConsts { color: #006400; }\n.cm-s-ttcn .cm-configOps,\n.cm-s-ttcn .cm-functionOps,\n.cm-s-ttcn .cm-portOps,\n.cm-s-ttcn .cm-sutOps,\n.cm-s-ttcn .cm-timerOps,\n.cm-s-ttcn .cm-verdictOps { color: #0000FF; }\n.cm-s-ttcn .cm-preprocessor,\n.cm-s-ttcn .cm-templateMatch,\n.cm-s-ttcn .cm-ttcn3Macros { color: #27408B; }\n.cm-s-ttcn .cm-types { color: #A52A2A; font-weight:bold; }\n.cm-s-ttcn .cm-visibilityModifiers { font-weight:bold; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/twilight.css",
    "content": ".cm-s-twilight.CodeMirror { background: #141414; color: #f7f7f7; } /**/\n.cm-s-twilight div.CodeMirror-selected { background: #323232; } /**/\n.cm-s-twilight .CodeMirror-line::selection, .cm-s-twilight .CodeMirror-line > span::selection, .cm-s-twilight .CodeMirror-line > span > span::selection { background: rgba(50, 50, 50, 0.99); }\n.cm-s-twilight .CodeMirror-line::-moz-selection, .cm-s-twilight .CodeMirror-line > span::-moz-selection, .cm-s-twilight .CodeMirror-line > span > span::-moz-selection { background: rgba(50, 50, 50, 0.99); }\n\n.cm-s-twilight .CodeMirror-gutters { background: #222; border-right: 1px solid #aaa; }\n.cm-s-twilight .CodeMirror-guttermarker { color: white; }\n.cm-s-twilight .CodeMirror-guttermarker-subtle { color: #aaa; }\n.cm-s-twilight .CodeMirror-linenumber { color: #aaa; }\n.cm-s-twilight .CodeMirror-cursor { border-left: 1px solid white; }\n\n.cm-s-twilight .cm-keyword { color: #f9ee98; } /**/\n.cm-s-twilight .cm-atom { color: #FC0; }\n.cm-s-twilight .cm-number { color:  #ca7841; } /**/\n.cm-s-twilight .cm-def { color: #8DA6CE; }\n.cm-s-twilight span.cm-variable-2, .cm-s-twilight span.cm-tag { color: #607392; } /**/\n.cm-s-twilight span.cm-variable-3, .cm-s-twilight span.cm-def, .cm-s-twilight span.cm-type { color: #607392; } /**/\n.cm-s-twilight .cm-operator { color: #cda869; } /**/\n.cm-s-twilight .cm-comment { color:#777; font-style:italic; font-weight:normal; } /**/\n.cm-s-twilight .cm-string { color:#8f9d6a; font-style:italic; } /**/\n.cm-s-twilight .cm-string-2 { color:#bd6b18; } /*?*/\n.cm-s-twilight .cm-meta { background-color:#141414; color:#f7f7f7; } /*?*/\n.cm-s-twilight .cm-builtin { color: #cda869; } /*?*/\n.cm-s-twilight .cm-tag { color: #997643; } /**/\n.cm-s-twilight .cm-attribute { color: #d6bb6d; } /*?*/\n.cm-s-twilight .cm-header { color: #FF6400; }\n.cm-s-twilight .cm-hr { color: #AEAEAE; }\n.cm-s-twilight .cm-link { color:#ad9361; font-style:italic; text-decoration:none; } /**/\n.cm-s-twilight .cm-error { border-bottom: 1px solid red; }\n\n.cm-s-twilight .CodeMirror-activeline-background { background: #27282E; }\n.cm-s-twilight .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/vibrant-ink.css",
    "content": "/* Taken from the popular Visual Studio Vibrant Ink Schema */\n\n.cm-s-vibrant-ink.CodeMirror { background: black; color: white; }\n.cm-s-vibrant-ink div.CodeMirror-selected { background: #35493c; }\n.cm-s-vibrant-ink .CodeMirror-line::selection, .cm-s-vibrant-ink .CodeMirror-line > span::selection, .cm-s-vibrant-ink .CodeMirror-line > span > span::selection { background: rgba(53, 73, 60, 0.99); }\n.cm-s-vibrant-ink .CodeMirror-line::-moz-selection, .cm-s-vibrant-ink .CodeMirror-line > span::-moz-selection, .cm-s-vibrant-ink .CodeMirror-line > span > span::-moz-selection { background: rgba(53, 73, 60, 0.99); }\n\n.cm-s-vibrant-ink .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }\n.cm-s-vibrant-ink .CodeMirror-guttermarker { color: white; }\n.cm-s-vibrant-ink .CodeMirror-guttermarker-subtle { color: #d0d0d0; }\n.cm-s-vibrant-ink .CodeMirror-linenumber { color: #d0d0d0; }\n.cm-s-vibrant-ink .CodeMirror-cursor { border-left: 1px solid white; }\n\n.cm-s-vibrant-ink .cm-keyword { color: #CC7832; }\n.cm-s-vibrant-ink .cm-atom { color: #FC0; }\n.cm-s-vibrant-ink .cm-number { color:  #FFEE98; }\n.cm-s-vibrant-ink .cm-def { color: #8DA6CE; }\n.cm-s-vibrant-ink span.cm-variable-2, .cm-s-vibrant span.cm-tag { color: #FFC66D; }\n.cm-s-vibrant-ink span.cm-variable-3, .cm-s-vibrant span.cm-def, .cm-s-vibrant span.cm-type { color: #FFC66D; }\n.cm-s-vibrant-ink .cm-operator { color: #888; }\n.cm-s-vibrant-ink .cm-comment { color: gray; font-weight: bold; }\n.cm-s-vibrant-ink .cm-string { color:  #A5C25C; }\n.cm-s-vibrant-ink .cm-string-2 { color: red; }\n.cm-s-vibrant-ink .cm-meta { color: #D8FA3C; }\n.cm-s-vibrant-ink .cm-builtin { color: #8DA6CE; }\n.cm-s-vibrant-ink .cm-tag { color: #8DA6CE; }\n.cm-s-vibrant-ink .cm-attribute { color: #8DA6CE; }\n.cm-s-vibrant-ink .cm-header { color: #FF6400; }\n.cm-s-vibrant-ink .cm-hr { color: #AEAEAE; }\n.cm-s-vibrant-ink .cm-link { color: blue; }\n.cm-s-vibrant-ink .cm-error { border-bottom: 1px solid red; }\n\n.cm-s-vibrant-ink .CodeMirror-activeline-background { background: #27282E; }\n.cm-s-vibrant-ink .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/xq-dark.css",
    "content": "/*\nCopyright (C) 2011 by MarkLogic Corporation\nAuthor: Mike Brevoort <mike@brevoort.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n.cm-s-xq-dark.CodeMirror { background: #0a001f; color: #f8f8f8; }\n.cm-s-xq-dark div.CodeMirror-selected { background: #27007A; }\n.cm-s-xq-dark .CodeMirror-line::selection, .cm-s-xq-dark .CodeMirror-line > span::selection, .cm-s-xq-dark .CodeMirror-line > span > span::selection { background: rgba(39, 0, 122, 0.99); }\n.cm-s-xq-dark .CodeMirror-line::-moz-selection, .cm-s-xq-dark .CodeMirror-line > span::-moz-selection, .cm-s-xq-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(39, 0, 122, 0.99); }\n.cm-s-xq-dark .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; }\n.cm-s-xq-dark .CodeMirror-guttermarker { color: #FFBD40; }\n.cm-s-xq-dark .CodeMirror-guttermarker-subtle { color: #f8f8f8; }\n.cm-s-xq-dark .CodeMirror-linenumber { color: #f8f8f8; }\n.cm-s-xq-dark .CodeMirror-cursor { border-left: 1px solid white; }\n\n.cm-s-xq-dark span.cm-keyword { color: #FFBD40; }\n.cm-s-xq-dark span.cm-atom { color: #6C8CD5; }\n.cm-s-xq-dark span.cm-number { color: #164; }\n.cm-s-xq-dark span.cm-def { color: #FFF; text-decoration:underline; }\n.cm-s-xq-dark span.cm-variable { color: #FFF; }\n.cm-s-xq-dark span.cm-variable-2 { color: #EEE; }\n.cm-s-xq-dark span.cm-variable-3, .cm-s-xq-dark span.cm-type { color: #DDD; }\n.cm-s-xq-dark span.cm-property {}\n.cm-s-xq-dark span.cm-operator {}\n.cm-s-xq-dark span.cm-comment { color: gray; }\n.cm-s-xq-dark span.cm-string { color: #9FEE00; }\n.cm-s-xq-dark span.cm-meta { color: yellow; }\n.cm-s-xq-dark span.cm-qualifier { color: #FFF700; }\n.cm-s-xq-dark span.cm-builtin { color: #30a; }\n.cm-s-xq-dark span.cm-bracket { color: #cc7; }\n.cm-s-xq-dark span.cm-tag { color: #FFBD40; }\n.cm-s-xq-dark span.cm-attribute { color: #FFF700; }\n.cm-s-xq-dark span.cm-error { color: #f00; }\n\n.cm-s-xq-dark .CodeMirror-activeline-background { background: #27282E; }\n.cm-s-xq-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/xq-light.css",
    "content": "/*\nCopyright (C) 2011 by MarkLogic Corporation\nAuthor: Mike Brevoort <mike@brevoort.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n.cm-s-xq-light span.cm-keyword { line-height: 1em; font-weight: bold; color: #5A5CAD; }\n.cm-s-xq-light span.cm-atom { color: #6C8CD5; }\n.cm-s-xq-light span.cm-number { color: #164; }\n.cm-s-xq-light span.cm-def { text-decoration:underline; }\n.cm-s-xq-light span.cm-variable { color: black; }\n.cm-s-xq-light span.cm-variable-2 { color:black; }\n.cm-s-xq-light span.cm-variable-3, .cm-s-xq-light span.cm-type { color: black; }\n.cm-s-xq-light span.cm-property {}\n.cm-s-xq-light span.cm-operator {}\n.cm-s-xq-light span.cm-comment { color: #0080FF; font-style: italic; }\n.cm-s-xq-light span.cm-string { color: red; }\n.cm-s-xq-light span.cm-meta { color: yellow; }\n.cm-s-xq-light span.cm-qualifier { color: grey; }\n.cm-s-xq-light span.cm-builtin { color: #7EA656; }\n.cm-s-xq-light span.cm-bracket { color: #cc7; }\n.cm-s-xq-light span.cm-tag { color: #3F7F7F; }\n.cm-s-xq-light span.cm-attribute { color: #7F007F; }\n.cm-s-xq-light span.cm-error { color: #f00; }\n\n.cm-s-xq-light .CodeMirror-activeline-background { background: #e8f2ff; }\n.cm-s-xq-light .CodeMirror-matchingbracket { outline:1px solid grey;color:black !important;background:yellow; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/yeti.css",
    "content": "/*\n\n    Name:       yeti\n    Author:     Michael Kaminsky (http://github.com/mkaminsky11)\n\n    Original yeti color scheme by Jesse Weed (https://github.com/jesseweed/yeti-syntax)\n\n*/\n\n\n.cm-s-yeti.CodeMirror {\n  background-color: #ECEAE8 !important;\n  color: #d1c9c0 !important;\n  border: none;\n}\n\n.cm-s-yeti .CodeMirror-gutters {\n  color: #adaba6;\n  background-color: #E5E1DB;\n  border: none;\n}\n.cm-s-yeti .CodeMirror-cursor { border-left: solid thin #d1c9c0; }\n.cm-s-yeti .CodeMirror-linenumber { color: #adaba6; }\n.cm-s-yeti.CodeMirror-focused div.CodeMirror-selected { background: #DCD8D2; }\n.cm-s-yeti .CodeMirror-line::selection, .cm-s-yeti .CodeMirror-line > span::selection, .cm-s-yeti .CodeMirror-line > span > span::selection { background: #DCD8D2; }\n.cm-s-yeti .CodeMirror-line::-moz-selection, .cm-s-yeti .CodeMirror-line > span::-moz-selection, .cm-s-yeti .CodeMirror-line > span > span::-moz-selection { background: #DCD8D2; }\n.cm-s-yeti span.cm-comment { color: #d4c8be; }\n.cm-s-yeti span.cm-string, .cm-s-yeti span.cm-string-2 { color: #96c0d8; }\n.cm-s-yeti span.cm-number { color: #a074c4; }\n.cm-s-yeti span.cm-variable { color: #55b5db; }\n.cm-s-yeti span.cm-variable-2 { color: #a074c4; }\n.cm-s-yeti span.cm-def { color: #55b5db; }\n.cm-s-yeti span.cm-operator { color: #9fb96e; }\n.cm-s-yeti span.cm-keyword { color: #9fb96e; }\n.cm-s-yeti span.cm-atom { color: #a074c4; }\n.cm-s-yeti span.cm-meta { color: #96c0d8; }\n.cm-s-yeti span.cm-tag { color: #96c0d8; }\n.cm-s-yeti span.cm-attribute { color: #9fb96e; }\n.cm-s-yeti span.cm-qualifier { color: #96c0d8; }\n.cm-s-yeti span.cm-property { color: #a074c4; }\n.cm-s-yeti span.cm-builtin { color: #a074c4; }\n.cm-s-yeti span.cm-variable-3, .cm-s-yeti span.cm-type { color: #96c0d8; }\n.cm-s-yeti .CodeMirror-activeline-background { background: #E7E4E0; }\n.cm-s-yeti .CodeMirror-matchingbracket { text-decoration: underline; }\n"
  },
  {
    "path": "third_party/CodeMirror/theme/zenburn.css",
    "content": "/**\n * \"\n *  Using Zenburn color palette from the Emacs Zenburn Theme\n *  https://github.com/bbatsov/zenburn-emacs/blob/master/zenburn-theme.el\n *\n *  Also using parts of https://github.com/xavi/coderay-lighttable-theme\n * \"\n * From: https://github.com/wisenomad/zenburn-lighttable-theme/blob/master/zenburn.css\n */\n\n.cm-s-zenburn .CodeMirror-gutters { background: #3f3f3f !important; }\n.cm-s-zenburn .CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded { color: #999; }\n.cm-s-zenburn .CodeMirror-cursor { border-left: 1px solid white; }\n.cm-s-zenburn { background-color: #3f3f3f; color: #dcdccc; }\n.cm-s-zenburn span.cm-builtin { color: #dcdccc; font-weight: bold; }\n.cm-s-zenburn span.cm-comment { color: #7f9f7f; }\n.cm-s-zenburn span.cm-keyword { color: #f0dfaf; font-weight: bold; }\n.cm-s-zenburn span.cm-atom { color: #bfebbf; }\n.cm-s-zenburn span.cm-def { color: #dcdccc; }\n.cm-s-zenburn span.cm-variable { color: #dfaf8f; }\n.cm-s-zenburn span.cm-variable-2 { color: #dcdccc; }\n.cm-s-zenburn span.cm-string { color: #cc9393; }\n.cm-s-zenburn span.cm-string-2 { color: #cc9393; }\n.cm-s-zenburn span.cm-number { color: #dcdccc; }\n.cm-s-zenburn span.cm-tag { color: #93e0e3; }\n.cm-s-zenburn span.cm-property { color: #dfaf8f; }\n.cm-s-zenburn span.cm-attribute { color: #dfaf8f; }\n.cm-s-zenburn span.cm-qualifier { color: #7cb8bb; }\n.cm-s-zenburn span.cm-meta { color: #f0dfaf; }\n.cm-s-zenburn span.cm-header { color: #f0efd0; }\n.cm-s-zenburn span.cm-operator { color: #f0efd0; }\n.cm-s-zenburn span.CodeMirror-matchingbracket { box-sizing: border-box; background: transparent; border-bottom: 1px solid; }\n.cm-s-zenburn span.CodeMirror-nonmatchingbracket { border-bottom: 1px solid; background: none; }\n.cm-s-zenburn .CodeMirror-activeline { background: #000000; }\n.cm-s-zenburn .CodeMirror-activeline-background { background: #000000; }\n.cm-s-zenburn div.CodeMirror-selected { background: #545454; }\n.cm-s-zenburn .CodeMirror-focused div.CodeMirror-selected { background: #4f4f4f; }\n"
  },
  {
    "path": "third_party/DMP/AUTHORS",
    "content": "# Below is a list of people and organizations that have contributed\n# to the Diff Match Patch project.\n\nGoogle Inc.\n\nDuncan Cross <duncan.cross@gmail.com> (Lua port)\nJan Weiß <jan@geheimwerk.de> (Objective C port)\nMatthaeus G. Chajdas <anteru@developer.shelter13.net> (C# port)\nMike Slemmer <mikeslemmer@gmail.com> (C++ port)\n\n"
  },
  {
    "path": "third_party/DMP/LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "third_party/DMP/METADATA",
    "content": "name: \"diff-match-patch\"\ndescription:\n    \"Library required for synchronizing plain text.\"\n\nthird_party {\n  url {\n    type: GIT\n    value: \"https://github.com/google/diff-match-patch\"\n  }\n  version: \"f7ec0851994c8989cfb709dbda202ad1881472d4\"\n  last_upgrade_date { year: 2018 month: 6 day: 18 }\n  license_type: NOTICE\n}\n"
  },
  {
    "path": "third_party/DMP/diff_match_patch.py",
    "content": "#!/usr/bin/python2.4\n\nfrom __future__ import division\n\n\"\"\"Diff Match and Patch\nCopyright 2018 The diff-match-patch Authors.\nhttps://github.com/google/diff-match-patch\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n  http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\"\"\"Functions for diff, match and patch.\n\nComputes the difference between two texts to create a patch.\nApplies the patch onto another text, allowing for errors.\n\"\"\"\n\n__author__ = 'fraser@google.com (Neil Fraser)'\n\nimport re\nimport sys\nimport time\nimport urllib\n\n\nclass diff_match_patch:\n  \"\"\"Class containing the diff, match and patch methods.\n\n  Also contains the behaviour settings.\n  \"\"\"\n\n  def __init__(self):\n    \"\"\"Inits a diff_match_patch object with default settings.\n    Redefine these in your program to override the defaults.\n    \"\"\"\n\n    # Number of seconds to map a diff before giving up (0 for infinity).\n    self.Diff_Timeout = 1.0\n    # Cost of an empty edit operation in terms of edit characters.\n    self.Diff_EditCost = 4\n    # At what point is no match declared (0.0 = perfection, 1.0 = very loose).\n    self.Match_Threshold = 0.5\n    # How far to search for a match (0 = exact location, 1000+ = broad match).\n    # A match this many characters away from the expected location will add\n    # 1.0 to the score (0.0 is a perfect match).\n    self.Match_Distance = 1000\n    # When deleting a large block of text (over ~64 characters), how close do\n    # the contents have to be to match the expected contents. (0.0 = perfection,\n    # 1.0 = very loose).  Note that Match_Threshold controls how closely the\n    # end points of a delete need to match.\n    self.Patch_DeleteThreshold = 0.5\n    # Chunk size for context length.\n    self.Patch_Margin = 4\n\n    # The number of bits in an int.\n    # Python has no maximum, thus to disable patch splitting set to 0.\n    # However to avoid long patches in certain pathological cases, use 32.\n    # Multiple short patches (using native ints) are much faster than long ones.\n    self.Match_MaxBits = 32\n\n  #  DIFF FUNCTIONS\n\n  # The data structure representing a diff is an array of tuples:\n  # [(DIFF_DELETE, \"Hello\"), (DIFF_INSERT, \"Goodbye\"), (DIFF_EQUAL, \" world.\")]\n  # which means: delete \"Hello\", add \"Goodbye\" and keep \" world.\"\n  DIFF_DELETE = -1\n  DIFF_INSERT = 1\n  DIFF_EQUAL = 0\n\n  def diff_main(self, text1, text2, checklines=True, deadline=None):\n    \"\"\"Find the differences between two texts.  Simplifies the problem by\n      stripping any common prefix or suffix off the texts before diffing.\n\n    Args:\n      text1: Old string to be diffed.\n      text2: New string to be diffed.\n      checklines: Optional speedup flag.  If present and false, then don't run\n        a line-level diff first to identify the changed areas.\n        Defaults to true, which does a faster, slightly less optimal diff.\n      deadline: Optional time when the diff should be complete by.  Used\n        internally for recursive calls.  Users should set DiffTimeout instead.\n\n    Returns:\n      Array of changes.\n    \"\"\"\n    # Set a deadline by which time the diff must be complete.\n    if deadline == None:\n      # Unlike in most languages, Python counts time in seconds.\n      if self.Diff_Timeout <= 0:\n        deadline = sys.maxint\n      else:\n        deadline = time.time() + self.Diff_Timeout\n\n    # Check for null inputs.\n    if text1 == None or text2 == None:\n      raise ValueError(\"Null inputs. (diff_main)\")\n\n    # Check for equality (speedup).\n    if text1 == text2:\n      if text1:\n        return [(self.DIFF_EQUAL, text1)]\n      return []\n\n    # Trim off common prefix (speedup).\n    commonlength = self.diff_commonPrefix(text1, text2)\n    commonprefix = text1[:commonlength]\n    text1 = text1[commonlength:]\n    text2 = text2[commonlength:]\n\n    # Trim off common suffix (speedup).\n    commonlength = self.diff_commonSuffix(text1, text2)\n    if commonlength == 0:\n      commonsuffix = ''\n    else:\n      commonsuffix = text1[-commonlength:]\n      text1 = text1[:-commonlength]\n      text2 = text2[:-commonlength]\n\n    # Compute the diff on the middle block.\n    diffs = self.diff_compute(text1, text2, checklines, deadline)\n\n    # Restore the prefix and suffix.\n    if commonprefix:\n      diffs[:0] = [(self.DIFF_EQUAL, commonprefix)]\n    if commonsuffix:\n      diffs.append((self.DIFF_EQUAL, commonsuffix))\n    self.diff_cleanupMerge(diffs)\n    return diffs\n\n  def diff_compute(self, text1, text2, checklines, deadline):\n    \"\"\"Find the differences between two texts.  Assumes that the texts do not\n      have any common prefix or suffix.\n\n    Args:\n      text1: Old string to be diffed.\n      text2: New string to be diffed.\n      checklines: Speedup flag.  If false, then don't run a line-level diff\n        first to identify the changed areas.\n        If true, then run a faster, slightly less optimal diff.\n      deadline: Time when the diff should be complete by.\n\n    Returns:\n      Array of changes.\n    \"\"\"\n    if not text1:\n      # Just add some text (speedup).\n      return [(self.DIFF_INSERT, text2)]\n\n    if not text2:\n      # Just delete some text (speedup).\n      return [(self.DIFF_DELETE, text1)]\n\n    if len(text1) > len(text2):\n      (longtext, shorttext) = (text1, text2)\n    else:\n      (shorttext, longtext) = (text1, text2)\n    i = longtext.find(shorttext)\n    if i != -1:\n      # Shorter text is inside the longer text (speedup).\n      diffs = [(self.DIFF_INSERT, longtext[:i]), (self.DIFF_EQUAL, shorttext),\n               (self.DIFF_INSERT, longtext[i + len(shorttext):])]\n      # Swap insertions for deletions if diff is reversed.\n      if len(text1) > len(text2):\n        diffs[0] = (self.DIFF_DELETE, diffs[0][1])\n        diffs[2] = (self.DIFF_DELETE, diffs[2][1])\n      return diffs\n\n    if len(shorttext) == 1:\n      # Single character string.\n      # After the previous speedup, the character can't be an equality.\n      return [(self.DIFF_DELETE, text1), (self.DIFF_INSERT, text2)]\n\n    # Check to see if the problem can be split in two.\n    hm = self.diff_halfMatch(text1, text2)\n    if hm:\n      # A half-match was found, sort out the return data.\n      (text1_a, text1_b, text2_a, text2_b, mid_common) = hm\n      # Send both pairs off for separate processing.\n      diffs_a = self.diff_main(text1_a, text2_a, checklines, deadline)\n      diffs_b = self.diff_main(text1_b, text2_b, checklines, deadline)\n      # Merge the results.\n      return diffs_a + [(self.DIFF_EQUAL, mid_common)] + diffs_b\n\n    if checklines and len(text1) > 100 and len(text2) > 100:\n      return self.diff_lineMode(text1, text2, deadline)\n\n    return self.diff_bisect(text1, text2, deadline)\n\n  def diff_lineMode(self, text1, text2, deadline):\n    \"\"\"Do a quick line-level diff on both strings, then rediff the parts for\n      greater accuracy.\n      This speedup can produce non-minimal diffs.\n\n    Args:\n      text1: Old string to be diffed.\n      text2: New string to be diffed.\n      deadline: Time when the diff should be complete by.\n\n    Returns:\n      Array of changes.\n    \"\"\"\n\n    # Scan the text on a line-by-line basis first.\n    (text1, text2, linearray) = self.diff_linesToChars(text1, text2)\n\n    diffs = self.diff_main(text1, text2, False, deadline)\n\n    # Convert the diff back to original text.\n    self.diff_charsToLines(diffs, linearray)\n    # Eliminate freak matches (e.g. blank lines)\n    self.diff_cleanupSemantic(diffs)\n\n    # Rediff any replacement blocks, this time character-by-character.\n    # Add a dummy entry at the end.\n    diffs.append((self.DIFF_EQUAL, ''))\n    pointer = 0\n    count_delete = 0\n    count_insert = 0\n    text_delete = ''\n    text_insert = ''\n    while pointer < len(diffs):\n      if diffs[pointer][0] == self.DIFF_INSERT:\n        count_insert += 1\n        text_insert += diffs[pointer][1]\n      elif diffs[pointer][0] == self.DIFF_DELETE:\n        count_delete += 1\n        text_delete += diffs[pointer][1]\n      elif diffs[pointer][0] == self.DIFF_EQUAL:\n        # Upon reaching an equality, check for prior redundancies.\n        if count_delete >= 1 and count_insert >= 1:\n          # Delete the offending records and add the merged ones.\n          subDiff = self.diff_main(text_delete, text_insert, False, deadline)\n          diffs[pointer - count_delete - count_insert : pointer] = subDiff\n          pointer = pointer - count_delete - count_insert + len(subDiff)\n        count_insert = 0\n        count_delete = 0\n        text_delete = ''\n        text_insert = ''\n\n      pointer += 1\n\n    diffs.pop()  # Remove the dummy entry at the end.\n\n    return diffs\n\n  def diff_bisect(self, text1, text2, deadline):\n    \"\"\"Find the 'middle snake' of a diff, split the problem in two\n      and return the recursively constructed diff.\n      See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.\n\n    Args:\n      text1: Old string to be diffed.\n      text2: New string to be diffed.\n      deadline: Time at which to bail if not yet complete.\n\n    Returns:\n      Array of diff tuples.\n    \"\"\"\n\n    # Cache the text lengths to prevent multiple calls.\n    text1_length = len(text1)\n    text2_length = len(text2)\n    max_d = (text1_length + text2_length + 1) // 2\n    v_offset = max_d\n    v_length = 2 * max_d\n    v1 = [-1] * v_length\n    v1[v_offset + 1] = 0\n    v2 = v1[:]\n    delta = text1_length - text2_length\n    # If the total number of characters is odd, then the front path will\n    # collide with the reverse path.\n    front = (delta % 2 != 0)\n    # Offsets for start and end of k loop.\n    # Prevents mapping of space beyond the grid.\n    k1start = 0\n    k1end = 0\n    k2start = 0\n    k2end = 0\n    for d in xrange(max_d):\n      # Bail out if deadline is reached.\n      if time.time() > deadline:\n        break\n\n      # Walk the front path one step.\n      for k1 in xrange(-d + k1start, d + 1 - k1end, 2):\n        k1_offset = v_offset + k1\n        if k1 == -d or (k1 != d and\n            v1[k1_offset - 1] < v1[k1_offset + 1]):\n          x1 = v1[k1_offset + 1]\n        else:\n          x1 = v1[k1_offset - 1] + 1\n        y1 = x1 - k1\n        while (x1 < text1_length and y1 < text2_length and\n               text1[x1] == text2[y1]):\n          x1 += 1\n          y1 += 1\n        v1[k1_offset] = x1\n        if x1 > text1_length:\n          # Ran off the right of the graph.\n          k1end += 2\n        elif y1 > text2_length:\n          # Ran off the bottom of the graph.\n          k1start += 2\n        elif front:\n          k2_offset = v_offset + delta - k1\n          if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] != -1:\n            # Mirror x2 onto top-left coordinate system.\n            x2 = text1_length - v2[k2_offset]\n            if x1 >= x2:\n              # Overlap detected.\n              return self.diff_bisectSplit(text1, text2, x1, y1, deadline)\n\n      # Walk the reverse path one step.\n      for k2 in xrange(-d + k2start, d + 1 - k2end, 2):\n        k2_offset = v_offset + k2\n        if k2 == -d or (k2 != d and\n            v2[k2_offset - 1] < v2[k2_offset + 1]):\n          x2 = v2[k2_offset + 1]\n        else:\n          x2 = v2[k2_offset - 1] + 1\n        y2 = x2 - k2\n        while (x2 < text1_length and y2 < text2_length and\n               text1[-x2 - 1] == text2[-y2 - 1]):\n          x2 += 1\n          y2 += 1\n        v2[k2_offset] = x2\n        if x2 > text1_length:\n          # Ran off the left of the graph.\n          k2end += 2\n        elif y2 > text2_length:\n          # Ran off the top of the graph.\n          k2start += 2\n        elif not front:\n          k1_offset = v_offset + delta - k2\n          if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] != -1:\n            x1 = v1[k1_offset]\n            y1 = v_offset + x1 - k1_offset\n            # Mirror x2 onto top-left coordinate system.\n            x2 = text1_length - x2\n            if x1 >= x2:\n              # Overlap detected.\n              return self.diff_bisectSplit(text1, text2, x1, y1, deadline)\n\n    # Diff took too long and hit the deadline or\n    # number of diffs equals number of characters, no commonality at all.\n    return [(self.DIFF_DELETE, text1), (self.DIFF_INSERT, text2)]\n\n  def diff_bisectSplit(self, text1, text2, x, y, deadline):\n    \"\"\"Given the location of the 'middle snake', split the diff in two parts\n    and recurse.\n\n    Args:\n      text1: Old string to be diffed.\n      text2: New string to be diffed.\n      x: Index of split point in text1.\n      y: Index of split point in text2.\n      deadline: Time at which to bail if not yet complete.\n\n    Returns:\n      Array of diff tuples.\n    \"\"\"\n    text1a = text1[:x]\n    text2a = text2[:y]\n    text1b = text1[x:]\n    text2b = text2[y:]\n\n    # Compute both diffs serially.\n    diffs = self.diff_main(text1a, text2a, False, deadline)\n    diffsb = self.diff_main(text1b, text2b, False, deadline)\n\n    return diffs + diffsb\n\n  def diff_linesToChars(self, text1, text2):\n    \"\"\"Split two texts into an array of strings.  Reduce the texts to a string\n    of hashes where each Unicode character represents one line.\n\n    Args:\n      text1: First string.\n      text2: Second string.\n\n    Returns:\n      Three element tuple, containing the encoded text1, the encoded text2 and\n      the array of unique strings.  The zeroth element of the array of unique\n      strings is intentionally blank.\n    \"\"\"\n    lineArray = []  # e.g. lineArray[4] == \"Hello\\n\"\n    lineHash = {}   # e.g. lineHash[\"Hello\\n\"] == 4\n\n    # \"\\x00\" is a valid character, but various debuggers don't like it.\n    # So we'll insert a junk entry to avoid generating a null character.\n    lineArray.append('')\n\n    def diff_linesToCharsMunge(text):\n      \"\"\"Split a text into an array of strings.  Reduce the texts to a string\n      of hashes where each Unicode character represents one line.\n      Modifies linearray and linehash through being a closure.\n\n      Args:\n        text: String to encode.\n\n      Returns:\n        Encoded string.\n      \"\"\"\n      chars = []\n      # Walk the text, pulling out a substring for each line.\n      # text.split('\\n') would would temporarily double our memory footprint.\n      # Modifying text would create many large strings to garbage collect.\n      lineStart = 0\n      lineEnd = -1\n      while lineEnd < len(text) - 1:\n        lineEnd = text.find('\\n', lineStart)\n        if lineEnd == -1:\n          lineEnd = len(text) - 1\n        line = text[lineStart:lineEnd + 1]\n\n        if line in lineHash:\n          chars.append(unichr(lineHash[line]))\n        else:\n          if len(lineArray) == maxLines:\n            # Bail out at 65535 because unichr(65536) throws.\n            line = text[lineStart:]\n            lineEnd = len(text)\n          lineArray.append(line)\n          lineHash[line] = len(lineArray) - 1\n          chars.append(unichr(len(lineArray) - 1))\n        lineStart = lineEnd + 1\n      return \"\".join(chars)\n\n    # Allocate 2/3rds of the space for text1, the rest for text2.\n    maxLines = 40000\n    chars1 = diff_linesToCharsMunge(text1)\n    maxLines = 65535\n    chars2 = diff_linesToCharsMunge(text2)\n    return (chars1, chars2, lineArray)\n\n  def diff_charsToLines(self, diffs, lineArray):\n    \"\"\"Rehydrate the text in a diff from a string of line hashes to real lines\n    of text.\n\n    Args:\n      diffs: Array of diff tuples.\n      lineArray: Array of unique strings.\n    \"\"\"\n    for x in xrange(len(diffs)):\n      text = []\n      for char in diffs[x][1]:\n        text.append(lineArray[ord(char)])\n      diffs[x] = (diffs[x][0], \"\".join(text))\n\n  def diff_commonPrefix(self, text1, text2):\n    \"\"\"Determine the common prefix of two strings.\n\n    Args:\n      text1: First string.\n      text2: Second string.\n\n    Returns:\n      The number of characters common to the start of each string.\n    \"\"\"\n    # Quick check for common null cases.\n    if not text1 or not text2 or text1[0] != text2[0]:\n      return 0\n    # Binary search.\n    # Performance analysis: https://neil.fraser.name/news/2007/10/09/\n    pointermin = 0\n    pointermax = min(len(text1), len(text2))\n    pointermid = pointermax\n    pointerstart = 0\n    while pointermin < pointermid:\n      if text1[pointerstart:pointermid] == text2[pointerstart:pointermid]:\n        pointermin = pointermid\n        pointerstart = pointermin\n      else:\n        pointermax = pointermid\n      pointermid = (pointermax - pointermin) // 2 + pointermin\n    return pointermid\n\n  def diff_commonSuffix(self, text1, text2):\n    \"\"\"Determine the common suffix of two strings.\n\n    Args:\n      text1: First string.\n      text2: Second string.\n\n    Returns:\n      The number of characters common to the end of each string.\n    \"\"\"\n    # Quick check for common null cases.\n    if not text1 or not text2 or text1[-1] != text2[-1]:\n      return 0\n    # Binary search.\n    # Performance analysis: https://neil.fraser.name/news/2007/10/09/\n    pointermin = 0\n    pointermax = min(len(text1), len(text2))\n    pointermid = pointermax\n    pointerend = 0\n    while pointermin < pointermid:\n      if (text1[-pointermid:len(text1) - pointerend] ==\n          text2[-pointermid:len(text2) - pointerend]):\n        pointermin = pointermid\n        pointerend = pointermin\n      else:\n        pointermax = pointermid\n      pointermid = (pointermax - pointermin) // 2 + pointermin\n    return pointermid\n\n  def diff_commonOverlap(self, text1, text2):\n    \"\"\"Determine if the suffix of one string is the prefix of another.\n\n    Args:\n      text1 First string.\n      text2 Second string.\n\n    Returns:\n      The number of characters common to the end of the first\n      string and the start of the second string.\n    \"\"\"\n    # Cache the text lengths to prevent multiple calls.\n    text1_length = len(text1)\n    text2_length = len(text2)\n    # Eliminate the null case.\n    if text1_length == 0 or text2_length == 0:\n      return 0\n    # Truncate the longer string.\n    if text1_length > text2_length:\n      text1 = text1[-text2_length:]\n    elif text1_length < text2_length:\n      text2 = text2[:text1_length]\n    text_length = min(text1_length, text2_length)\n    # Quick check for the worst case.\n    if text1 == text2:\n      return text_length\n\n    # Start by looking for a single character match\n    # and increase length until no match is found.\n    # Performance analysis: https://neil.fraser.name/news/2010/11/04/\n    best = 0\n    length = 1\n    while True:\n      pattern = text1[-length:]\n      found = text2.find(pattern)\n      if found == -1:\n        return best\n      length += found\n      if found == 0 or text1[-length:] == text2[:length]:\n        best = length\n        length += 1\n\n  def diff_halfMatch(self, text1, text2):\n    \"\"\"Do the two texts share a substring which is at least half the length of\n    the longer text?\n    This speedup can produce non-minimal diffs.\n\n    Args:\n      text1: First string.\n      text2: Second string.\n\n    Returns:\n      Five element Array, containing the prefix of text1, the suffix of text1,\n      the prefix of text2, the suffix of text2 and the common middle.  Or None\n      if there was no match.\n    \"\"\"\n    if self.Diff_Timeout <= 0:\n      # Don't risk returning a non-optimal diff if we have unlimited time.\n      return None\n    if len(text1) > len(text2):\n      (longtext, shorttext) = (text1, text2)\n    else:\n      (shorttext, longtext) = (text1, text2)\n    if len(longtext) < 4 or len(shorttext) * 2 < len(longtext):\n      return None  # Pointless.\n\n    def diff_halfMatchI(longtext, shorttext, i):\n      \"\"\"Does a substring of shorttext exist within longtext such that the\n      substring is at least half the length of longtext?\n      Closure, but does not reference any external variables.\n\n      Args:\n        longtext: Longer string.\n        shorttext: Shorter string.\n        i: Start index of quarter length substring within longtext.\n\n      Returns:\n        Five element Array, containing the prefix of longtext, the suffix of\n        longtext, the prefix of shorttext, the suffix of shorttext and the\n        common middle.  Or None if there was no match.\n      \"\"\"\n      seed = longtext[i:i + len(longtext) // 4]\n      best_common = ''\n      j = shorttext.find(seed)\n      while j != -1:\n        prefixLength = self.diff_commonPrefix(longtext[i:], shorttext[j:])\n        suffixLength = self.diff_commonSuffix(longtext[:i], shorttext[:j])\n        if len(best_common) < suffixLength + prefixLength:\n          best_common = (shorttext[j - suffixLength:j] +\n              shorttext[j:j + prefixLength])\n          best_longtext_a = longtext[:i - suffixLength]\n          best_longtext_b = longtext[i + prefixLength:]\n          best_shorttext_a = shorttext[:j - suffixLength]\n          best_shorttext_b = shorttext[j + prefixLength:]\n        j = shorttext.find(seed, j + 1)\n\n      if len(best_common) * 2 >= len(longtext):\n        return (best_longtext_a, best_longtext_b,\n                best_shorttext_a, best_shorttext_b, best_common)\n      else:\n        return None\n\n    # First check if the second quarter is the seed for a half-match.\n    hm1 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 3) // 4)\n    # Check again based on the third quarter.\n    hm2 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 1) // 2)\n    if not hm1 and not hm2:\n      return None\n    elif not hm2:\n      hm = hm1\n    elif not hm1:\n      hm = hm2\n    else:\n      # Both matched.  Select the longest.\n      if len(hm1[4]) > len(hm2[4]):\n        hm = hm1\n      else:\n        hm = hm2\n\n    # A half-match was found, sort out the return data.\n    if len(text1) > len(text2):\n      (text1_a, text1_b, text2_a, text2_b, mid_common) = hm\n    else:\n      (text2_a, text2_b, text1_a, text1_b, mid_common) = hm\n    return (text1_a, text1_b, text2_a, text2_b, mid_common)\n\n  def diff_cleanupSemantic(self, diffs):\n    \"\"\"Reduce the number of edits by eliminating semantically trivial\n    equalities.\n\n    Args:\n      diffs: Array of diff tuples.\n    \"\"\"\n    changes = False\n    equalities = []  # Stack of indices where equalities are found.\n    lastequality = None  # Always equal to diffs[equalities[-1]][1]\n    pointer = 0  # Index of current position.\n    # Number of chars that changed prior to the equality.\n    length_insertions1, length_deletions1 = 0, 0\n    # Number of chars that changed after the equality.\n    length_insertions2, length_deletions2 = 0, 0\n    while pointer < len(diffs):\n      if diffs[pointer][0] == self.DIFF_EQUAL:  # Equality found.\n        equalities.append(pointer)\n        length_insertions1, length_insertions2 = length_insertions2, 0\n        length_deletions1, length_deletions2 = length_deletions2, 0\n        lastequality = diffs[pointer][1]\n      else:  # An insertion or deletion.\n        if diffs[pointer][0] == self.DIFF_INSERT:\n          length_insertions2 += len(diffs[pointer][1])\n        else:\n          length_deletions2 += len(diffs[pointer][1])\n        # Eliminate an equality that is smaller or equal to the edits on both\n        # sides of it.\n        if (lastequality and (len(lastequality) <=\n            max(length_insertions1, length_deletions1)) and\n            (len(lastequality) <= max(length_insertions2, length_deletions2))):\n          # Duplicate record.\n          diffs.insert(equalities[-1], (self.DIFF_DELETE, lastequality))\n          # Change second copy to insert.\n          diffs[equalities[-1] + 1] = (self.DIFF_INSERT,\n              diffs[equalities[-1] + 1][1])\n          # Throw away the equality we just deleted.\n          equalities.pop()\n          # Throw away the previous equality (it needs to be reevaluated).\n          if len(equalities):\n            equalities.pop()\n          if len(equalities):\n            pointer = equalities[-1]\n          else:\n            pointer = -1\n          # Reset the counters.\n          length_insertions1, length_deletions1 = 0, 0\n          length_insertions2, length_deletions2 = 0, 0\n          lastequality = None\n          changes = True\n      pointer += 1\n\n    # Normalize the diff.\n    if changes:\n      self.diff_cleanupMerge(diffs)\n    self.diff_cleanupSemanticLossless(diffs)\n\n    # Find any overlaps between deletions and insertions.\n    # e.g: <del>abcxxx</del><ins>xxxdef</ins>\n    #   -> <del>abc</del>xxx<ins>def</ins>\n    # e.g: <del>xxxabc</del><ins>defxxx</ins>\n    #   -> <ins>def</ins>xxx<del>abc</del>\n    # Only extract an overlap if it is as big as the edit ahead or behind it.\n    pointer = 1\n    while pointer < len(diffs):\n      if (diffs[pointer - 1][0] == self.DIFF_DELETE and\n          diffs[pointer][0] == self.DIFF_INSERT):\n        deletion = diffs[pointer - 1][1]\n        insertion = diffs[pointer][1]\n        overlap_length1 = self.diff_commonOverlap(deletion, insertion)\n        overlap_length2 = self.diff_commonOverlap(insertion, deletion)\n        if overlap_length1 >= overlap_length2:\n          if (overlap_length1 >= len(deletion) / 2.0 or\n              overlap_length1 >= len(insertion) / 2.0):\n            # Overlap found.  Insert an equality and trim the surrounding edits.\n            diffs.insert(pointer, (self.DIFF_EQUAL,\n                                   insertion[:overlap_length1]))\n            diffs[pointer - 1] = (self.DIFF_DELETE,\n                                  deletion[:len(deletion) - overlap_length1])\n            diffs[pointer + 1] = (self.DIFF_INSERT,\n                                  insertion[overlap_length1:])\n            pointer += 1\n        else:\n          if (overlap_length2 >= len(deletion) / 2.0 or\n              overlap_length2 >= len(insertion) / 2.0):\n            # Reverse overlap found.\n            # Insert an equality and swap and trim the surrounding edits.\n            diffs.insert(pointer, (self.DIFF_EQUAL, deletion[:overlap_length2]))\n            diffs[pointer - 1] = (self.DIFF_INSERT,\n                                  insertion[:len(insertion) - overlap_length2])\n            diffs[pointer + 1] = (self.DIFF_DELETE, deletion[overlap_length2:])\n            pointer += 1\n        pointer += 1\n      pointer += 1\n\n  def diff_cleanupSemanticLossless(self, diffs):\n    \"\"\"Look for single edits surrounded on both sides by equalities\n    which can be shifted sideways to align the edit to a word boundary.\n    e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.\n\n    Args:\n      diffs: Array of diff tuples.\n    \"\"\"\n\n    def diff_cleanupSemanticScore(one, two):\n      \"\"\"Given two strings, compute a score representing whether the\n      internal boundary falls on logical boundaries.\n      Scores range from 6 (best) to 0 (worst).\n      Closure, but does not reference any external variables.\n\n      Args:\n        one: First string.\n        two: Second string.\n\n      Returns:\n        The score.\n      \"\"\"\n      if not one or not two:\n        # Edges are the best.\n        return 6\n\n      # Each port of this function behaves slightly differently due to\n      # subtle differences in each language's definition of things like\n      # 'whitespace'.  Since this function's purpose is largely cosmetic,\n      # the choice has been made to use each language's native features\n      # rather than force total conformity.\n      char1 = one[-1]\n      char2 = two[0]\n      nonAlphaNumeric1 = not char1.isalnum()\n      nonAlphaNumeric2 = not char2.isalnum()\n      whitespace1 = nonAlphaNumeric1 and char1.isspace()\n      whitespace2 = nonAlphaNumeric2 and char2.isspace()\n      lineBreak1 = whitespace1 and (char1 == \"\\r\" or char1 == \"\\n\")\n      lineBreak2 = whitespace2 and (char2 == \"\\r\" or char2 == \"\\n\")\n      blankLine1 = lineBreak1 and self.BLANKLINEEND.search(one)\n      blankLine2 = lineBreak2 and self.BLANKLINESTART.match(two)\n\n      if blankLine1 or blankLine2:\n        # Five points for blank lines.\n        return 5\n      elif lineBreak1 or lineBreak2:\n        # Four points for line breaks.\n        return 4\n      elif nonAlphaNumeric1 and not whitespace1 and whitespace2:\n        # Three points for end of sentences.\n        return 3\n      elif whitespace1 or whitespace2:\n        # Two points for whitespace.\n        return 2\n      elif nonAlphaNumeric1 or nonAlphaNumeric2:\n        # One point for non-alphanumeric.\n        return 1\n      return 0\n\n    pointer = 1\n    # Intentionally ignore the first and last element (don't need checking).\n    while pointer < len(diffs) - 1:\n      if (diffs[pointer - 1][0] == self.DIFF_EQUAL and\n          diffs[pointer + 1][0] == self.DIFF_EQUAL):\n        # This is a single edit surrounded by equalities.\n        equality1 = diffs[pointer - 1][1]\n        edit = diffs[pointer][1]\n        equality2 = diffs[pointer + 1][1]\n\n        # First, shift the edit as far left as possible.\n        commonOffset = self.diff_commonSuffix(equality1, edit)\n        if commonOffset:\n          commonString = edit[-commonOffset:]\n          equality1 = equality1[:-commonOffset]\n          edit = commonString + edit[:-commonOffset]\n          equality2 = commonString + equality2\n\n        # Second, step character by character right, looking for the best fit.\n        bestEquality1 = equality1\n        bestEdit = edit\n        bestEquality2 = equality2\n        bestScore = (diff_cleanupSemanticScore(equality1, edit) +\n            diff_cleanupSemanticScore(edit, equality2))\n        while edit and equality2 and edit[0] == equality2[0]:\n          equality1 += edit[0]\n          edit = edit[1:] + equality2[0]\n          equality2 = equality2[1:]\n          score = (diff_cleanupSemanticScore(equality1, edit) +\n              diff_cleanupSemanticScore(edit, equality2))\n          # The >= encourages trailing rather than leading whitespace on edits.\n          if score >= bestScore:\n            bestScore = score\n            bestEquality1 = equality1\n            bestEdit = edit\n            bestEquality2 = equality2\n\n        if diffs[pointer - 1][1] != bestEquality1:\n          # We have an improvement, save it back to the diff.\n          if bestEquality1:\n            diffs[pointer - 1] = (diffs[pointer - 1][0], bestEquality1)\n          else:\n            del diffs[pointer - 1]\n            pointer -= 1\n          diffs[pointer] = (diffs[pointer][0], bestEdit)\n          if bestEquality2:\n            diffs[pointer + 1] = (diffs[pointer + 1][0], bestEquality2)\n          else:\n            del diffs[pointer + 1]\n            pointer -= 1\n      pointer += 1\n\n  # Define some regex patterns for matching boundaries.\n  BLANKLINEEND = re.compile(r\"\\n\\r?\\n$\")\n  BLANKLINESTART = re.compile(r\"^\\r?\\n\\r?\\n\")\n\n  def diff_cleanupEfficiency(self, diffs):\n    \"\"\"Reduce the number of edits by eliminating operationally trivial\n    equalities.\n\n    Args:\n      diffs: Array of diff tuples.\n    \"\"\"\n    changes = False\n    equalities = []  # Stack of indices where equalities are found.\n    lastequality = None  # Always equal to diffs[equalities[-1]][1]\n    pointer = 0  # Index of current position.\n    pre_ins = False  # Is there an insertion operation before the last equality.\n    pre_del = False  # Is there a deletion operation before the last equality.\n    post_ins = False  # Is there an insertion operation after the last equality.\n    post_del = False  # Is there a deletion operation after the last equality.\n    while pointer < len(diffs):\n      if diffs[pointer][0] == self.DIFF_EQUAL:  # Equality found.\n        if (len(diffs[pointer][1]) < self.Diff_EditCost and\n            (post_ins or post_del)):\n          # Candidate found.\n          equalities.append(pointer)\n          pre_ins = post_ins\n          pre_del = post_del\n          lastequality = diffs[pointer][1]\n        else:\n          # Not a candidate, and can never become one.\n          equalities = []\n          lastequality = None\n\n        post_ins = post_del = False\n      else:  # An insertion or deletion.\n        if diffs[pointer][0] == self.DIFF_DELETE:\n          post_del = True\n        else:\n          post_ins = True\n\n        # Five types to be split:\n        # <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>\n        # <ins>A</ins>X<ins>C</ins><del>D</del>\n        # <ins>A</ins><del>B</del>X<ins>C</ins>\n        # <ins>A</del>X<ins>C</ins><del>D</del>\n        # <ins>A</ins><del>B</del>X<del>C</del>\n\n        if lastequality and ((pre_ins and pre_del and post_ins and post_del) or\n                             ((len(lastequality) < self.Diff_EditCost / 2) and\n                              (pre_ins + pre_del + post_ins + post_del) == 3)):\n          # Duplicate record.\n          diffs.insert(equalities[-1], (self.DIFF_DELETE, lastequality))\n          # Change second copy to insert.\n          diffs[equalities[-1] + 1] = (self.DIFF_INSERT,\n              diffs[equalities[-1] + 1][1])\n          equalities.pop()  # Throw away the equality we just deleted.\n          lastequality = None\n          if pre_ins and pre_del:\n            # No changes made which could affect previous entry, keep going.\n            post_ins = post_del = True\n            equalities = []\n          else:\n            if len(equalities):\n              equalities.pop()  # Throw away the previous equality.\n            if len(equalities):\n              pointer = equalities[-1]\n            else:\n              pointer = -1\n            post_ins = post_del = False\n          changes = True\n      pointer += 1\n\n    if changes:\n      self.diff_cleanupMerge(diffs)\n\n  def diff_cleanupMerge(self, diffs):\n    \"\"\"Reorder and merge like edit sections.  Merge equalities.\n    Any edit section can move as long as it doesn't cross an equality.\n\n    Args:\n      diffs: Array of diff tuples.\n    \"\"\"\n    diffs.append((self.DIFF_EQUAL, ''))  # Add a dummy entry at the end.\n    pointer = 0\n    count_delete = 0\n    count_insert = 0\n    text_delete = ''\n    text_insert = ''\n    while pointer < len(diffs):\n      if diffs[pointer][0] == self.DIFF_INSERT:\n        count_insert += 1\n        text_insert += diffs[pointer][1]\n        pointer += 1\n      elif diffs[pointer][0] == self.DIFF_DELETE:\n        count_delete += 1\n        text_delete += diffs[pointer][1]\n        pointer += 1\n      elif diffs[pointer][0] == self.DIFF_EQUAL:\n        # Upon reaching an equality, check for prior redundancies.\n        if count_delete + count_insert > 1:\n          if count_delete != 0 and count_insert != 0:\n            # Factor out any common prefixies.\n            commonlength = self.diff_commonPrefix(text_insert, text_delete)\n            if commonlength != 0:\n              x = pointer - count_delete - count_insert - 1\n              if x >= 0 and diffs[x][0] == self.DIFF_EQUAL:\n                diffs[x] = (diffs[x][0], diffs[x][1] +\n                            text_insert[:commonlength])\n              else:\n                diffs.insert(0, (self.DIFF_EQUAL, text_insert[:commonlength]))\n                pointer += 1\n              text_insert = text_insert[commonlength:]\n              text_delete = text_delete[commonlength:]\n            # Factor out any common suffixies.\n            commonlength = self.diff_commonSuffix(text_insert, text_delete)\n            if commonlength != 0:\n              diffs[pointer] = (diffs[pointer][0], text_insert[-commonlength:] +\n                  diffs[pointer][1])\n              text_insert = text_insert[:-commonlength]\n              text_delete = text_delete[:-commonlength]\n          # Delete the offending records and add the merged ones.\n          new_ops = []\n          if len(text_delete) != 0:\n            new_ops.append((self.DIFF_DELETE, text_delete))\n          if len(text_insert) != 0:\n            new_ops.append((self.DIFF_INSERT, text_insert))\n          pointer -= count_delete + count_insert\n          diffs[pointer : pointer + count_delete + count_insert] = new_ops\n          pointer += len(new_ops) + 1\n        elif pointer != 0 and diffs[pointer - 1][0] == self.DIFF_EQUAL:\n          # Merge this equality with the previous one.\n          diffs[pointer - 1] = (diffs[pointer - 1][0],\n                                diffs[pointer - 1][1] + diffs[pointer][1])\n          del diffs[pointer]\n        else:\n          pointer += 1\n\n        count_insert = 0\n        count_delete = 0\n        text_delete = ''\n        text_insert = ''\n\n    if diffs[-1][1] == '':\n      diffs.pop()  # Remove the dummy entry at the end.\n\n    # Second pass: look for single edits surrounded on both sides by equalities\n    # which can be shifted sideways to eliminate an equality.\n    # e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC\n    changes = False\n    pointer = 1\n    # Intentionally ignore the first and last element (don't need checking).\n    while pointer < len(diffs) - 1:\n      if (diffs[pointer - 1][0] == self.DIFF_EQUAL and\n          diffs[pointer + 1][0] == self.DIFF_EQUAL):\n        # This is a single edit surrounded by equalities.\n        if diffs[pointer][1].endswith(diffs[pointer - 1][1]):\n          # Shift the edit over the previous equality.\n          if diffs[pointer - 1][1] != \"\":\n            diffs[pointer] = (diffs[pointer][0],\n                diffs[pointer - 1][1] +\n                diffs[pointer][1][:-len(diffs[pointer - 1][1])])\n            diffs[pointer + 1] = (diffs[pointer + 1][0],\n                                  diffs[pointer - 1][1] + diffs[pointer + 1][1])\n          del diffs[pointer - 1]\n          changes = True\n        elif diffs[pointer][1].startswith(diffs[pointer + 1][1]):\n          # Shift the edit over the next equality.\n          diffs[pointer - 1] = (diffs[pointer - 1][0],\n                                diffs[pointer - 1][1] + diffs[pointer + 1][1])\n          diffs[pointer] = (diffs[pointer][0],\n              diffs[pointer][1][len(diffs[pointer + 1][1]):] +\n              diffs[pointer + 1][1])\n          del diffs[pointer + 1]\n          changes = True\n      pointer += 1\n\n    # If shifts were made, the diff needs reordering and another shift sweep.\n    if changes:\n      self.diff_cleanupMerge(diffs)\n\n  def diff_xIndex(self, diffs, loc):\n    \"\"\"loc is a location in text1, compute and return the equivalent location\n    in text2.  e.g. \"The cat\" vs \"The big cat\", 1->1, 5->8\n\n    Args:\n      diffs: Array of diff tuples.\n      loc: Location within text1.\n\n    Returns:\n      Location within text2.\n    \"\"\"\n    chars1 = 0\n    chars2 = 0\n    last_chars1 = 0\n    last_chars2 = 0\n    for x in xrange(len(diffs)):\n      (op, text) = diffs[x]\n      if op != self.DIFF_INSERT:  # Equality or deletion.\n        chars1 += len(text)\n      if op != self.DIFF_DELETE:  # Equality or insertion.\n        chars2 += len(text)\n      if chars1 > loc:  # Overshot the location.\n        break\n      last_chars1 = chars1\n      last_chars2 = chars2\n\n    if len(diffs) != x and diffs[x][0] == self.DIFF_DELETE:\n      # The location was deleted.\n      return last_chars2\n    # Add the remaining len(character).\n    return last_chars2 + (loc - last_chars1)\n\n  def diff_prettyHtml(self, diffs):\n    \"\"\"Convert a diff array into a pretty HTML report.\n\n    Args:\n      diffs: Array of diff tuples.\n\n    Returns:\n      HTML representation.\n    \"\"\"\n    html = []\n    for (op, data) in diffs:\n      text = (data.replace(\"&\", \"&amp;\").replace(\"<\", \"&lt;\")\n                 .replace(\">\", \"&gt;\").replace(\"\\n\", \"&para;<br>\"))\n      if op == self.DIFF_INSERT:\n        html.append(\"<ins style=\\\"background:#e6ffe6;\\\">%s</ins>\" % text)\n      elif op == self.DIFF_DELETE:\n        html.append(\"<del style=\\\"background:#ffe6e6;\\\">%s</del>\" % text)\n      elif op == self.DIFF_EQUAL:\n        html.append(\"<span>%s</span>\" % text)\n    return \"\".join(html)\n\n  def diff_text1(self, diffs):\n    \"\"\"Compute and return the source text (all equalities and deletions).\n\n    Args:\n      diffs: Array of diff tuples.\n\n    Returns:\n      Source text.\n    \"\"\"\n    text = []\n    for (op, data) in diffs:\n      if op != self.DIFF_INSERT:\n        text.append(data)\n    return \"\".join(text)\n\n  def diff_text2(self, diffs):\n    \"\"\"Compute and return the destination text (all equalities and insertions).\n\n    Args:\n      diffs: Array of diff tuples.\n\n    Returns:\n      Destination text.\n    \"\"\"\n    text = []\n    for (op, data) in diffs:\n      if op != self.DIFF_DELETE:\n        text.append(data)\n    return \"\".join(text)\n\n  def diff_levenshtein(self, diffs):\n    \"\"\"Compute the Levenshtein distance; the number of inserted, deleted or\n    substituted characters.\n\n    Args:\n      diffs: Array of diff tuples.\n\n    Returns:\n      Number of changes.\n    \"\"\"\n    levenshtein = 0\n    insertions = 0\n    deletions = 0\n    for (op, data) in diffs:\n      if op == self.DIFF_INSERT:\n        insertions += len(data)\n      elif op == self.DIFF_DELETE:\n        deletions += len(data)\n      elif op == self.DIFF_EQUAL:\n        # A deletion and an insertion is one substitution.\n        levenshtein += max(insertions, deletions)\n        insertions = 0\n        deletions = 0\n    levenshtein += max(insertions, deletions)\n    return levenshtein\n\n  def diff_toDelta(self, diffs):\n    \"\"\"Crush the diff into an encoded string which describes the operations\n    required to transform text1 into text2.\n    E.g. =3\\t-2\\t+ing  -> Keep 3 chars, delete 2 chars, insert 'ing'.\n    Operations are tab-separated.  Inserted text is escaped using %xx notation.\n\n    Args:\n      diffs: Array of diff tuples.\n\n    Returns:\n      Delta text.\n    \"\"\"\n    text = []\n    for (op, data) in diffs:\n      if op == self.DIFF_INSERT:\n        # High ascii will raise UnicodeDecodeError.  Use Unicode instead.\n        data = data.encode(\"utf-8\")\n        text.append(\"+\" + urllib.quote(data, \"!~*'();/?:@&=+$,# \"))\n      elif op == self.DIFF_DELETE:\n        text.append(\"-%d\" % len(data))\n      elif op == self.DIFF_EQUAL:\n        text.append(\"=%d\" % len(data))\n    return \"\\t\".join(text)\n\n  def diff_fromDelta(self, text1, delta):\n    \"\"\"Given the original text1, and an encoded string which describes the\n    operations required to transform text1 into text2, compute the full diff.\n\n    Args:\n      text1: Source string for the diff.\n      delta: Delta text.\n\n    Returns:\n      Array of diff tuples.\n\n    Raises:\n      ValueError: If invalid input.\n    \"\"\"\n    if type(delta) == unicode:\n      # Deltas should be composed of a subset of ascii chars, Unicode not\n      # required.  If this encode raises UnicodeEncodeError, delta is invalid.\n      delta = delta.encode(\"ascii\")\n    diffs = []\n    pointer = 0  # Cursor in text1\n    tokens = delta.split(\"\\t\")\n    for token in tokens:\n      if token == \"\":\n        # Blank tokens are ok (from a trailing \\t).\n        continue\n      # Each token begins with a one character parameter which specifies the\n      # operation of this token (delete, insert, equality).\n      param = token[1:]\n      if token[0] == \"+\":\n        param = urllib.unquote(param).decode(\"utf-8\")\n        diffs.append((self.DIFF_INSERT, param))\n      elif token[0] == \"-\" or token[0] == \"=\":\n        try:\n          n = int(param)\n        except ValueError:\n          raise ValueError(\"Invalid number in diff_fromDelta: \" + param)\n        if n < 0:\n          raise ValueError(\"Negative number in diff_fromDelta: \" + param)\n        text = text1[pointer : pointer + n]\n        pointer += n\n        if token[0] == \"=\":\n          diffs.append((self.DIFF_EQUAL, text))\n        else:\n          diffs.append((self.DIFF_DELETE, text))\n      else:\n        # Anything else is an error.\n        raise ValueError(\"Invalid diff operation in diff_fromDelta: \" +\n            token[0])\n    if pointer != len(text1):\n      raise ValueError(\n          \"Delta length (%d) does not equal source text length (%d).\" %\n         (pointer, len(text1)))\n    return diffs\n\n  #  MATCH FUNCTIONS\n\n  def match_main(self, text, pattern, loc):\n    \"\"\"Locate the best instance of 'pattern' in 'text' near 'loc'.\n\n    Args:\n      text: The text to search.\n      pattern: The pattern to search for.\n      loc: The location to search around.\n\n    Returns:\n      Best match index or -1.\n    \"\"\"\n    # Check for null inputs.\n    if text == None or pattern == None:\n      raise ValueError(\"Null inputs. (match_main)\")\n\n    loc = max(0, min(loc, len(text)))\n    if text == pattern:\n      # Shortcut (potentially not guaranteed by the algorithm)\n      return 0\n    elif not text:\n      # Nothing to match.\n      return -1\n    elif text[loc:loc + len(pattern)] == pattern:\n      # Perfect match at the perfect spot!  (Includes case of null pattern)\n      return loc\n    else:\n      # Do a fuzzy compare.\n      match = self.match_bitap(text, pattern, loc)\n      return match\n\n  def match_bitap(self, text, pattern, loc):\n    \"\"\"Locate the best instance of 'pattern' in 'text' near 'loc' using the\n    Bitap algorithm.\n\n    Args:\n      text: The text to search.\n      pattern: The pattern to search for.\n      loc: The location to search around.\n\n    Returns:\n      Best match index or -1.\n    \"\"\"\n    # Python doesn't have a maxint limit, so ignore this check.\n    #if self.Match_MaxBits != 0 and len(pattern) > self.Match_MaxBits:\n    #  raise ValueError(\"Pattern too long for this application.\")\n\n    # Initialise the alphabet.\n    s = self.match_alphabet(pattern)\n\n    def match_bitapScore(e, x):\n      \"\"\"Compute and return the score for a match with e errors and x location.\n      Accesses loc and pattern through being a closure.\n\n      Args:\n        e: Number of errors in match.\n        x: Location of match.\n\n      Returns:\n        Overall score for match (0.0 = good, 1.0 = bad).\n      \"\"\"\n      accuracy = float(e) / len(pattern)\n      proximity = abs(loc - x)\n      if not self.Match_Distance:\n        # Dodge divide by zero error.\n        return proximity and 1.0 or accuracy\n      return accuracy + (proximity / float(self.Match_Distance))\n\n    # Highest score beyond which we give up.\n    score_threshold = self.Match_Threshold\n    # Is there a nearby exact match? (speedup)\n    best_loc = text.find(pattern, loc)\n    if best_loc != -1:\n      score_threshold = min(match_bitapScore(0, best_loc), score_threshold)\n      # What about in the other direction? (speedup)\n      best_loc = text.rfind(pattern, loc + len(pattern))\n      if best_loc != -1:\n        score_threshold = min(match_bitapScore(0, best_loc), score_threshold)\n\n    # Initialise the bit arrays.\n    matchmask = 1 << (len(pattern) - 1)\n    best_loc = -1\n\n    bin_max = len(pattern) + len(text)\n    # Empty initialization added to appease pychecker.\n    last_rd = None\n    for d in xrange(len(pattern)):\n      # Scan for the best match each iteration allows for one more error.\n      # Run a binary search to determine how far from 'loc' we can stray at\n      # this error level.\n      bin_min = 0\n      bin_mid = bin_max\n      while bin_min < bin_mid:\n        if match_bitapScore(d, loc + bin_mid) <= score_threshold:\n          bin_min = bin_mid\n        else:\n          bin_max = bin_mid\n        bin_mid = (bin_max - bin_min) // 2 + bin_min\n\n      # Use the result from this iteration as the maximum for the next.\n      bin_max = bin_mid\n      start = max(1, loc - bin_mid + 1)\n      finish = min(loc + bin_mid, len(text)) + len(pattern)\n\n      rd = [0] * (finish + 2)\n      rd[finish + 1] = (1 << d) - 1\n      for j in xrange(finish, start - 1, -1):\n        if len(text) <= j - 1:\n          # Out of range.\n          charMatch = 0\n        else:\n          charMatch = s.get(text[j - 1], 0)\n        if d == 0:  # First pass: exact match.\n          rd[j] = ((rd[j + 1] << 1) | 1) & charMatch\n        else:  # Subsequent passes: fuzzy match.\n          rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | (\n              ((last_rd[j + 1] | last_rd[j]) << 1) | 1) | last_rd[j + 1]\n        if rd[j] & matchmask:\n          score = match_bitapScore(d, j - 1)\n          # This match will almost certainly be better than any existing match.\n          # But check anyway.\n          if score <= score_threshold:\n            # Told you so.\n            score_threshold = score\n            best_loc = j - 1\n            if best_loc > loc:\n              # When passing loc, don't exceed our current distance from loc.\n              start = max(1, 2 * loc - best_loc)\n            else:\n              # Already passed loc, downhill from here on in.\n              break\n      # No hope for a (better) match at greater error levels.\n      if match_bitapScore(d + 1, loc) > score_threshold:\n        break\n      last_rd = rd\n    return best_loc\n\n  def match_alphabet(self, pattern):\n    \"\"\"Initialise the alphabet for the Bitap algorithm.\n\n    Args:\n      pattern: The text to encode.\n\n    Returns:\n      Hash of character locations.\n    \"\"\"\n    s = {}\n    for char in pattern:\n      s[char] = 0\n    for i in xrange(len(pattern)):\n      s[pattern[i]] |= 1 << (len(pattern) - i - 1)\n    return s\n\n  #  PATCH FUNCTIONS\n\n  def patch_addContext(self, patch, text):\n    \"\"\"Increase the context until it is unique,\n    but don't let the pattern expand beyond Match_MaxBits.\n\n    Args:\n      patch: The patch to grow.\n      text: Source text.\n    \"\"\"\n    if len(text) == 0:\n      return\n    pattern = text[patch.start2 : patch.start2 + patch.length1]\n    padding = 0\n\n    # Look for the first and last matches of pattern in text.  If two different\n    # matches are found, increase the pattern length.\n    while (text.find(pattern) != text.rfind(pattern) and (self.Match_MaxBits ==\n        0 or len(pattern) < self.Match_MaxBits - self.Patch_Margin -\n        self.Patch_Margin)):\n      padding += self.Patch_Margin\n      pattern = text[max(0, patch.start2 - padding) :\n                     patch.start2 + patch.length1 + padding]\n    # Add one chunk for good luck.\n    padding += self.Patch_Margin\n\n    # Add the prefix.\n    prefix = text[max(0, patch.start2 - padding) : patch.start2]\n    if prefix:\n      patch.diffs[:0] = [(self.DIFF_EQUAL, prefix)]\n    # Add the suffix.\n    suffix = text[patch.start2 + patch.length1 :\n                  patch.start2 + patch.length1 + padding]\n    if suffix:\n      patch.diffs.append((self.DIFF_EQUAL, suffix))\n\n    # Roll back the start points.\n    patch.start1 -= len(prefix)\n    patch.start2 -= len(prefix)\n    # Extend lengths.\n    patch.length1 += len(prefix) + len(suffix)\n    patch.length2 += len(prefix) + len(suffix)\n\n  def patch_make(self, a, b=None, c=None):\n    \"\"\"Compute a list of patches to turn text1 into text2.\n    Use diffs if provided, otherwise compute it ourselves.\n    There are four ways to call this function, depending on what data is\n    available to the caller:\n    Method 1:\n    a = text1, b = text2\n    Method 2:\n    a = diffs\n    Method 3 (optimal):\n    a = text1, b = diffs\n    Method 4 (deprecated, use method 3):\n    a = text1, b = text2, c = diffs\n\n    Args:\n      a: text1 (methods 1,3,4) or Array of diff tuples for text1 to\n          text2 (method 2).\n      b: text2 (methods 1,4) or Array of diff tuples for text1 to\n          text2 (method 3) or undefined (method 2).\n      c: Array of diff tuples for text1 to text2 (method 4) or\n          undefined (methods 1,2,3).\n\n    Returns:\n      Array of Patch objects.\n    \"\"\"\n    text1 = None\n    diffs = None\n    # Note that texts may arrive as 'str' or 'unicode'.\n    if isinstance(a, basestring) and isinstance(b, basestring) and c is None:\n      # Method 1: text1, text2\n      # Compute diffs from text1 and text2.\n      text1 = a\n      diffs = self.diff_main(text1, b, True)\n      if len(diffs) > 2:\n        self.diff_cleanupSemantic(diffs)\n        self.diff_cleanupEfficiency(diffs)\n    elif isinstance(a, list) and b is None and c is None:\n      # Method 2: diffs\n      # Compute text1 from diffs.\n      diffs = a\n      text1 = self.diff_text1(diffs)\n    elif isinstance(a, basestring) and isinstance(b, list) and c is None:\n      # Method 3: text1, diffs\n      text1 = a\n      diffs = b\n    elif (isinstance(a, basestring) and isinstance(b, basestring) and\n          isinstance(c, list)):\n      # Method 4: text1, text2, diffs\n      # text2 is not used.\n      text1 = a\n      diffs = c\n    else:\n      raise ValueError(\"Unknown call format to patch_make.\")\n\n    if not diffs:\n      return []  # Get rid of the None case.\n    patches = []\n    patch = patch_obj()\n    char_count1 = 0  # Number of characters into the text1 string.\n    char_count2 = 0  # Number of characters into the text2 string.\n    prepatch_text = text1  # Recreate the patches to determine context info.\n    postpatch_text = text1\n    for x in xrange(len(diffs)):\n      (diff_type, diff_text) = diffs[x]\n      if len(patch.diffs) == 0 and diff_type != self.DIFF_EQUAL:\n        # A new patch starts here.\n        patch.start1 = char_count1\n        patch.start2 = char_count2\n      if diff_type == self.DIFF_INSERT:\n        # Insertion\n        patch.diffs.append(diffs[x])\n        patch.length2 += len(diff_text)\n        postpatch_text = (postpatch_text[:char_count2] + diff_text +\n                          postpatch_text[char_count2:])\n      elif diff_type == self.DIFF_DELETE:\n        # Deletion.\n        patch.length1 += len(diff_text)\n        patch.diffs.append(diffs[x])\n        postpatch_text = (postpatch_text[:char_count2] +\n                          postpatch_text[char_count2 + len(diff_text):])\n      elif (diff_type == self.DIFF_EQUAL and\n            len(diff_text) <= 2 * self.Patch_Margin and\n            len(patch.diffs) != 0 and len(diffs) != x + 1):\n        # Small equality inside a patch.\n        patch.diffs.append(diffs[x])\n        patch.length1 += len(diff_text)\n        patch.length2 += len(diff_text)\n\n      if (diff_type == self.DIFF_EQUAL and\n          len(diff_text) >= 2 * self.Patch_Margin):\n        # Time for a new patch.\n        if len(patch.diffs) != 0:\n          self.patch_addContext(patch, prepatch_text)\n          patches.append(patch)\n          patch = patch_obj()\n          # Unlike Unidiff, our patch lists have a rolling context.\n          # https://github.com/google/diff-match-patch/wiki/Unidiff\n          # Update prepatch text & pos to reflect the application of the\n          # just completed patch.\n          prepatch_text = postpatch_text\n          char_count1 = char_count2\n\n      # Update the current character count.\n      if diff_type != self.DIFF_INSERT:\n        char_count1 += len(diff_text)\n      if diff_type != self.DIFF_DELETE:\n        char_count2 += len(diff_text)\n\n    # Pick up the leftover patch if not empty.\n    if len(patch.diffs) != 0:\n      self.patch_addContext(patch, prepatch_text)\n      patches.append(patch)\n    return patches\n\n  def patch_deepCopy(self, patches):\n    \"\"\"Given an array of patches, return another array that is identical.\n\n    Args:\n      patches: Array of Patch objects.\n\n    Returns:\n      Array of Patch objects.\n    \"\"\"\n    patchesCopy = []\n    for patch in patches:\n      patchCopy = patch_obj()\n      # No need to deep copy the tuples since they are immutable.\n      patchCopy.diffs = patch.diffs[:]\n      patchCopy.start1 = patch.start1\n      patchCopy.start2 = patch.start2\n      patchCopy.length1 = patch.length1\n      patchCopy.length2 = patch.length2\n      patchesCopy.append(patchCopy)\n    return patchesCopy\n\n  def patch_apply(self, patches, text):\n    \"\"\"Merge a set of patches onto the text.  Return a patched text, as well\n    as a list of true/false values indicating which patches were applied.\n\n    Args:\n      patches: Array of Patch objects.\n      text: Old text.\n\n    Returns:\n      Two element Array, containing the new text and an array of boolean values.\n    \"\"\"\n    if not patches:\n      return (text, [])\n\n    # Deep copy the patches so that no changes are made to originals.\n    patches = self.patch_deepCopy(patches)\n\n    nullPadding = self.patch_addPadding(patches)\n    text = nullPadding + text + nullPadding\n    self.patch_splitMax(patches)\n\n    # delta keeps track of the offset between the expected and actual location\n    # of the previous patch.  If there are patches expected at positions 10 and\n    # 20, but the first patch was found at 12, delta is 2 and the second patch\n    # has an effective expected position of 22.\n    delta = 0\n    results = []\n    for patch in patches:\n      expected_loc = patch.start2 + delta\n      text1 = self.diff_text1(patch.diffs)\n      end_loc = -1\n      if len(text1) > self.Match_MaxBits:\n        # patch_splitMax will only provide an oversized pattern in the case of\n        # a monster delete.\n        start_loc = self.match_main(text, text1[:self.Match_MaxBits],\n                                    expected_loc)\n        if start_loc != -1:\n          end_loc = self.match_main(text, text1[-self.Match_MaxBits:],\n              expected_loc + len(text1) - self.Match_MaxBits)\n          if end_loc == -1 or start_loc >= end_loc:\n            # Can't find valid trailing context.  Drop this patch.\n            start_loc = -1\n      else:\n        start_loc = self.match_main(text, text1, expected_loc)\n      if start_loc == -1:\n        # No match found.  :(\n        results.append(False)\n        # Subtract the delta for this failed patch from subsequent patches.\n        delta -= patch.length2 - patch.length1\n      else:\n        # Found a match.  :)\n        results.append(True)\n        delta = start_loc - expected_loc\n        if end_loc == -1:\n          text2 = text[start_loc : start_loc + len(text1)]\n        else:\n          text2 = text[start_loc : end_loc + self.Match_MaxBits]\n        if text1 == text2:\n          # Perfect match, just shove the replacement text in.\n          text = (text[:start_loc] + self.diff_text2(patch.diffs) +\n                      text[start_loc + len(text1):])\n        else:\n          # Imperfect match.\n          # Run a diff to get a framework of equivalent indices.\n          diffs = self.diff_main(text1, text2, False)\n          if (len(text1) > self.Match_MaxBits and\n              self.diff_levenshtein(diffs) / float(len(text1)) >\n              self.Patch_DeleteThreshold):\n            # The end points match, but the content is unacceptably bad.\n            results[-1] = False\n          else:\n            self.diff_cleanupSemanticLossless(diffs)\n            index1 = 0\n            for (op, data) in patch.diffs:\n              if op != self.DIFF_EQUAL:\n                index2 = self.diff_xIndex(diffs, index1)\n              if op == self.DIFF_INSERT:  # Insertion\n                text = text[:start_loc + index2] + data + text[start_loc +\n                                                               index2:]\n              elif op == self.DIFF_DELETE:  # Deletion\n                text = text[:start_loc + index2] + text[start_loc +\n                    self.diff_xIndex(diffs, index1 + len(data)):]\n              if op != self.DIFF_DELETE:\n                index1 += len(data)\n    # Strip the padding off.\n    text = text[len(nullPadding):-len(nullPadding)]\n    return (text, results)\n\n  def patch_addPadding(self, patches):\n    \"\"\"Add some padding on text start and end so that edges can match\n    something.  Intended to be called only from within patch_apply.\n\n    Args:\n      patches: Array of Patch objects.\n\n    Returns:\n      The padding string added to each side.\n    \"\"\"\n    paddingLength = self.Patch_Margin\n    nullPadding = \"\"\n    for x in xrange(1, paddingLength + 1):\n      nullPadding += chr(x)\n\n    # Bump all the patches forward.\n    for patch in patches:\n      patch.start1 += paddingLength\n      patch.start2 += paddingLength\n\n    # Add some padding on start of first diff.\n    patch = patches[0]\n    diffs = patch.diffs\n    if not diffs or diffs[0][0] != self.DIFF_EQUAL:\n      # Add nullPadding equality.\n      diffs.insert(0, (self.DIFF_EQUAL, nullPadding))\n      patch.start1 -= paddingLength  # Should be 0.\n      patch.start2 -= paddingLength  # Should be 0.\n      patch.length1 += paddingLength\n      patch.length2 += paddingLength\n    elif paddingLength > len(diffs[0][1]):\n      # Grow first equality.\n      extraLength = paddingLength - len(diffs[0][1])\n      newText = nullPadding[len(diffs[0][1]):] + diffs[0][1]\n      diffs[0] = (diffs[0][0], newText)\n      patch.start1 -= extraLength\n      patch.start2 -= extraLength\n      patch.length1 += extraLength\n      patch.length2 += extraLength\n\n    # Add some padding on end of last diff.\n    patch = patches[-1]\n    diffs = patch.diffs\n    if not diffs or diffs[-1][0] != self.DIFF_EQUAL:\n      # Add nullPadding equality.\n      diffs.append((self.DIFF_EQUAL, nullPadding))\n      patch.length1 += paddingLength\n      patch.length2 += paddingLength\n    elif paddingLength > len(diffs[-1][1]):\n      # Grow last equality.\n      extraLength = paddingLength - len(diffs[-1][1])\n      newText = diffs[-1][1] + nullPadding[:extraLength]\n      diffs[-1] = (diffs[-1][0], newText)\n      patch.length1 += extraLength\n      patch.length2 += extraLength\n\n    return nullPadding\n\n  def patch_splitMax(self, patches):\n    \"\"\"Look through the patches and break up any which are longer than the\n    maximum limit of the match algorithm.\n    Intended to be called only from within patch_apply.\n\n    Args:\n      patches: Array of Patch objects.\n    \"\"\"\n    patch_size = self.Match_MaxBits\n    if patch_size == 0:\n      # Python has the option of not splitting strings due to its ability\n      # to handle integers of arbitrary precision.\n      return\n    for x in xrange(len(patches)):\n      if patches[x].length1 <= patch_size:\n        continue\n      bigpatch = patches[x]\n      # Remove the big old patch.\n      del patches[x]\n      x -= 1\n      start1 = bigpatch.start1\n      start2 = bigpatch.start2\n      precontext = ''\n      while len(bigpatch.diffs) != 0:\n        # Create one of several smaller patches.\n        patch = patch_obj()\n        empty = True\n        patch.start1 = start1 - len(precontext)\n        patch.start2 = start2 - len(precontext)\n        if precontext:\n          patch.length1 = patch.length2 = len(precontext)\n          patch.diffs.append((self.DIFF_EQUAL, precontext))\n\n        while (len(bigpatch.diffs) != 0 and\n               patch.length1 < patch_size - self.Patch_Margin):\n          (diff_type, diff_text) = bigpatch.diffs[0]\n          if diff_type == self.DIFF_INSERT:\n            # Insertions are harmless.\n            patch.length2 += len(diff_text)\n            start2 += len(diff_text)\n            patch.diffs.append(bigpatch.diffs.pop(0))\n            empty = False\n          elif (diff_type == self.DIFF_DELETE and len(patch.diffs) == 1 and\n              patch.diffs[0][0] == self.DIFF_EQUAL and\n              len(diff_text) > 2 * patch_size):\n            # This is a large deletion.  Let it pass in one chunk.\n            patch.length1 += len(diff_text)\n            start1 += len(diff_text)\n            empty = False\n            patch.diffs.append((diff_type, diff_text))\n            del bigpatch.diffs[0]\n          else:\n            # Deletion or equality.  Only take as much as we can stomach.\n            diff_text = diff_text[:patch_size - patch.length1 -\n                                  self.Patch_Margin]\n            patch.length1 += len(diff_text)\n            start1 += len(diff_text)\n            if diff_type == self.DIFF_EQUAL:\n              patch.length2 += len(diff_text)\n              start2 += len(diff_text)\n            else:\n              empty = False\n\n            patch.diffs.append((diff_type, diff_text))\n            if diff_text == bigpatch.diffs[0][1]:\n              del bigpatch.diffs[0]\n            else:\n              bigpatch.diffs[0] = (bigpatch.diffs[0][0],\n                                   bigpatch.diffs[0][1][len(diff_text):])\n\n        # Compute the head context for the next patch.\n        precontext = self.diff_text2(patch.diffs)\n        precontext = precontext[-self.Patch_Margin:]\n        # Append the end context for this patch.\n        postcontext = self.diff_text1(bigpatch.diffs)[:self.Patch_Margin]\n        if postcontext:\n          patch.length1 += len(postcontext)\n          patch.length2 += len(postcontext)\n          if len(patch.diffs) != 0 and patch.diffs[-1][0] == self.DIFF_EQUAL:\n            patch.diffs[-1] = (self.DIFF_EQUAL, patch.diffs[-1][1] +\n                               postcontext)\n          else:\n            patch.diffs.append((self.DIFF_EQUAL, postcontext))\n\n        if not empty:\n          x += 1\n          patches.insert(x, patch)\n\n  def patch_toText(self, patches):\n    \"\"\"Take a list of patches and return a textual representation.\n\n    Args:\n      patches: Array of Patch objects.\n\n    Returns:\n      Text representation of patches.\n    \"\"\"\n    text = []\n    for patch in patches:\n      text.append(str(patch))\n    return \"\".join(text)\n\n  def patch_fromText(self, textline):\n    \"\"\"Parse a textual representation of patches and return a list of patch\n    objects.\n\n    Args:\n      textline: Text representation of patches.\n\n    Returns:\n      Array of Patch objects.\n\n    Raises:\n      ValueError: If invalid input.\n    \"\"\"\n    if type(textline) == unicode:\n      # Patches should be composed of a subset of ascii chars, Unicode not\n      # required.  If this encode raises UnicodeEncodeError, patch is invalid.\n      textline = textline.encode(\"ascii\")\n    patches = []\n    if not textline:\n      return patches\n    text = textline.split('\\n')\n    while len(text) != 0:\n      m = re.match(\"^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$\", text[0])\n      if not m:\n        raise ValueError(\"Invalid patch string: \" + text[0])\n      patch = patch_obj()\n      patches.append(patch)\n      patch.start1 = int(m.group(1))\n      if m.group(2) == '':\n        patch.start1 -= 1\n        patch.length1 = 1\n      elif m.group(2) == '0':\n        patch.length1 = 0\n      else:\n        patch.start1 -= 1\n        patch.length1 = int(m.group(2))\n\n      patch.start2 = int(m.group(3))\n      if m.group(4) == '':\n        patch.start2 -= 1\n        patch.length2 = 1\n      elif m.group(4) == '0':\n        patch.length2 = 0\n      else:\n        patch.start2 -= 1\n        patch.length2 = int(m.group(4))\n\n      del text[0]\n\n      while len(text) != 0:\n        if text[0]:\n          sign = text[0][0]\n        else:\n          sign = ''\n        line = urllib.unquote(text[0][1:])\n        line = line.decode(\"utf-8\")\n        if sign == '+':\n          # Insertion.\n          patch.diffs.append((self.DIFF_INSERT, line))\n        elif sign == '-':\n          # Deletion.\n          patch.diffs.append((self.DIFF_DELETE, line))\n        elif sign == ' ':\n          # Minor equality.\n          patch.diffs.append((self.DIFF_EQUAL, line))\n        elif sign == '@':\n          # Start of next patch.\n          break\n        elif sign == '':\n          # Blank line?  Whatever.\n          pass\n        else:\n          # WTF?\n          raise ValueError(\"Invalid patch mode: '%s'\\n%s\" % (sign, line))\n        del text[0]\n    return patches\n\n\nclass patch_obj:\n  \"\"\"Class representing one patch operation.\n  \"\"\"\n\n  def __init__(self):\n    \"\"\"Initializes with an empty list of diffs.\n    \"\"\"\n    self.diffs = []\n    self.start1 = None\n    self.start2 = None\n    self.length1 = 0\n    self.length2 = 0\n\n  def __str__(self):\n    \"\"\"Emulate GNU diff's format.\n    Header: @@ -382,8 +481,9 @@\n    Indices are printed as 1-based, not 0-based.\n\n    Returns:\n      The GNU diff string.\n    \"\"\"\n    if self.length1 == 0:\n      coords1 = str(self.start1) + \",0\"\n    elif self.length1 == 1:\n      coords1 = str(self.start1 + 1)\n    else:\n      coords1 = str(self.start1 + 1) + \",\" + str(self.length1)\n    if self.length2 == 0:\n      coords2 = str(self.start2) + \",0\"\n    elif self.length2 == 1:\n      coords2 = str(self.start2 + 1)\n    else:\n      coords2 = str(self.start2 + 1) + \",\" + str(self.length2)\n    text = [\"@@ -\", coords1, \" +\", coords2, \" @@\\n\"]\n    # Escape the body of the patch with %xx notation.\n    for (op, data) in self.diffs:\n      if op == diff_match_patch.DIFF_INSERT:\n        text.append(\"+\")\n      elif op == diff_match_patch.DIFF_DELETE:\n        text.append(\"-\")\n      elif op == diff_match_patch.DIFF_EQUAL:\n        text.append(\" \")\n      # High ascii will raise UnicodeDecodeError.  Use Unicode instead.\n      data = data.encode(\"utf-8\")\n      text.append(urllib.quote(data, \"!~*'();/?:@&=+$,# \") + \"\\n\")\n    return \"\".join(text)\n"
  },
  {
    "path": "third_party/DMP/diff_match_patch_uncompressed.js",
    "content": "/**\n * Diff Match and Patch\n * Copyright 2018 The diff-match-patch Authors.\n * https://github.com/google/diff-match-patch\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Computes the difference between two texts to create a patch.\n * Applies the patch onto another text, allowing for errors.\n * @author fraser@google.com (Neil Fraser)\n */\n\n/**\n * Class containing the diff, match and patch methods.\n * @constructor\n */\nvar diff_match_patch = function() {\n\n  // Defaults.\n  // Redefine these in your program to override the defaults.\n\n  // Number of seconds to map a diff before giving up (0 for infinity).\n  this.Diff_Timeout = 1.0;\n  // Cost of an empty edit operation in terms of edit characters.\n  this.Diff_EditCost = 4;\n  // At what point is no match declared (0.0 = perfection, 1.0 = very loose).\n  this.Match_Threshold = 0.5;\n  // How far to search for a match (0 = exact location, 1000+ = broad match).\n  // A match this many characters away from the expected location will add\n  // 1.0 to the score (0.0 is a perfect match).\n  this.Match_Distance = 1000;\n  // When deleting a large block of text (over ~64 characters), how close do\n  // the contents have to be to match the expected contents. (0.0 = perfection,\n  // 1.0 = very loose).  Note that Match_Threshold controls how closely the\n  // end points of a delete need to match.\n  this.Patch_DeleteThreshold = 0.5;\n  // Chunk size for context length.\n  this.Patch_Margin = 4;\n\n  // The number of bits in an int.\n  this.Match_MaxBits = 32;\n};\n\n\n//  DIFF FUNCTIONS\n\n\n/**\n * The data structure representing a diff is an array of tuples:\n * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]\n * which means: delete 'Hello', add 'Goodbye' and keep ' world.'\n */\nvar DIFF_DELETE = -1;\nvar DIFF_INSERT = 1;\nvar DIFF_EQUAL = 0;\n\n/**\n * Class representing one diff tuple.\n * Attempts to look like a two-element array (which is what this used to be).\n * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL.\n * @param {string} text Text to be deleted, inserted, or retained.\n * @constructor\n */\ndiff_match_patch.Diff = function(op, text) {\n  this[0] = op;\n  this[1] = text;\n};\n\ndiff_match_patch.Diff.prototype.length = 2;\n\n/**\n * Emulate the output of a two-element array.\n * @return {string} Diff operation as a string.\n */\ndiff_match_patch.Diff.prototype.toString = function() {\n  return this[0] + ',' + this[1];\n};\n\n\n/**\n * Find the differences between two texts.  Simplifies the problem by stripping\n * any common prefix or suffix off the texts before diffing.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {boolean=} opt_checklines Optional speedup flag. If present and false,\n *     then don't run a line-level diff first to identify the changed areas.\n *     Defaults to true, which does a faster, slightly less optimal diff.\n * @param {number=} opt_deadline Optional time when the diff should be complete\n *     by.  Used internally for recursive calls.  Users should set DiffTimeout\n *     instead.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines,\n    opt_deadline) {\n  // Set a deadline by which time the diff must be complete.\n  if (typeof opt_deadline == 'undefined') {\n    if (this.Diff_Timeout <= 0) {\n      opt_deadline = Number.MAX_VALUE;\n    } else {\n      opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000;\n    }\n  }\n  var deadline = opt_deadline;\n\n  // Check for null inputs.\n  if (text1 == null || text2 == null) {\n    throw new Error('Null input. (diff_main)');\n  }\n\n  // Check for equality (speedup).\n  if (text1 == text2) {\n    if (text1) {\n      return [new diff_match_patch.Diff(DIFF_EQUAL, text1)];\n    }\n    return [];\n  }\n\n  if (typeof opt_checklines == 'undefined') {\n    opt_checklines = true;\n  }\n  var checklines = opt_checklines;\n\n  // Trim off common prefix (speedup).\n  var commonlength = this.diff_commonPrefix(text1, text2);\n  var commonprefix = text1.substring(0, commonlength);\n  text1 = text1.substring(commonlength);\n  text2 = text2.substring(commonlength);\n\n  // Trim off common suffix (speedup).\n  commonlength = this.diff_commonSuffix(text1, text2);\n  var commonsuffix = text1.substring(text1.length - commonlength);\n  text1 = text1.substring(0, text1.length - commonlength);\n  text2 = text2.substring(0, text2.length - commonlength);\n\n  // Compute the diff on the middle block.\n  var diffs = this.diff_compute_(text1, text2, checklines, deadline);\n\n  // Restore the prefix and suffix.\n  if (commonprefix) {\n    diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, commonprefix));\n  }\n  if (commonsuffix) {\n    diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, commonsuffix));\n  }\n  this.diff_cleanupMerge(diffs);\n  return diffs;\n};\n\n\n/**\n * Find the differences between two texts.  Assumes that the texts do not\n * have any common prefix or suffix.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {boolean} checklines Speedup flag.  If false, then don't run a\n *     line-level diff first to identify the changed areas.\n *     If true, then run a faster, slightly less optimal diff.\n * @param {number} deadline Time when the diff should be complete by.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines,\n    deadline) {\n  var diffs;\n\n  if (!text1) {\n    // Just add some text (speedup).\n    return [new diff_match_patch.Diff(DIFF_INSERT, text2)];\n  }\n\n  if (!text2) {\n    // Just delete some text (speedup).\n    return [new diff_match_patch.Diff(DIFF_DELETE, text1)];\n  }\n\n  var longtext = text1.length > text2.length ? text1 : text2;\n  var shorttext = text1.length > text2.length ? text2 : text1;\n  var i = longtext.indexOf(shorttext);\n  if (i != -1) {\n    // Shorter text is inside the longer text (speedup).\n    diffs = [new diff_match_patch.Diff(DIFF_INSERT, longtext.substring(0, i)),\n             new diff_match_patch.Diff(DIFF_EQUAL, shorttext),\n             new diff_match_patch.Diff(DIFF_INSERT,\n                 longtext.substring(i + shorttext.length))];\n    // Swap insertions for deletions if diff is reversed.\n    if (text1.length > text2.length) {\n      diffs[0][0] = diffs[2][0] = DIFF_DELETE;\n    }\n    return diffs;\n  }\n\n  if (shorttext.length == 1) {\n    // Single character string.\n    // After the previous speedup, the character can't be an equality.\n    return [new diff_match_patch.Diff(DIFF_DELETE, text1),\n            new diff_match_patch.Diff(DIFF_INSERT, text2)];\n  }\n\n  // Check to see if the problem can be split in two.\n  var hm = this.diff_halfMatch_(text1, text2);\n  if (hm) {\n    // A half-match was found, sort out the return data.\n    var text1_a = hm[0];\n    var text1_b = hm[1];\n    var text2_a = hm[2];\n    var text2_b = hm[3];\n    var mid_common = hm[4];\n    // Send both pairs off for separate processing.\n    var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline);\n    var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline);\n    // Merge the results.\n    return diffs_a.concat([new diff_match_patch.Diff(DIFF_EQUAL, mid_common)],\n                          diffs_b);\n  }\n\n  if (checklines && text1.length > 100 && text2.length > 100) {\n    return this.diff_lineMode_(text1, text2, deadline);\n  }\n\n  return this.diff_bisect_(text1, text2, deadline);\n};\n\n\n/**\n * Do a quick line-level diff on both strings, then rediff the parts for\n * greater accuracy.\n * This speedup can produce non-minimal diffs.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} deadline Time when the diff should be complete by.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) {\n  // Scan the text on a line-by-line basis first.\n  var a = this.diff_linesToChars_(text1, text2);\n  text1 = a.chars1;\n  text2 = a.chars2;\n  var linearray = a.lineArray;\n\n  var diffs = this.diff_main(text1, text2, false, deadline);\n\n  // Convert the diff back to original text.\n  this.diff_charsToLines_(diffs, linearray);\n  // Eliminate freak matches (e.g. blank lines)\n  this.diff_cleanupSemantic(diffs);\n\n  // Rediff any replacement blocks, this time character-by-character.\n  // Add a dummy entry at the end.\n  diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));\n  var pointer = 0;\n  var count_delete = 0;\n  var count_insert = 0;\n  var text_delete = '';\n  var text_insert = '';\n  while (pointer < diffs.length) {\n    switch (diffs[pointer][0]) {\n      case DIFF_INSERT:\n        count_insert++;\n        text_insert += diffs[pointer][1];\n        break;\n      case DIFF_DELETE:\n        count_delete++;\n        text_delete += diffs[pointer][1];\n        break;\n      case DIFF_EQUAL:\n        // Upon reaching an equality, check for prior redundancies.\n        if (count_delete >= 1 && count_insert >= 1) {\n          // Delete the offending records and add the merged ones.\n          diffs.splice(pointer - count_delete - count_insert,\n                       count_delete + count_insert);\n          pointer = pointer - count_delete - count_insert;\n          var subDiff =\n              this.diff_main(text_delete, text_insert, false, deadline);\n          for (var j = subDiff.length - 1; j >= 0; j--) {\n            diffs.splice(pointer, 0, subDiff[j]);\n          }\n          pointer = pointer + subDiff.length;\n        }\n        count_insert = 0;\n        count_delete = 0;\n        text_delete = '';\n        text_insert = '';\n        break;\n    }\n    pointer++;\n  }\n  diffs.pop();  // Remove the dummy entry at the end.\n\n  return diffs;\n};\n\n\n/**\n * Find the 'middle snake' of a diff, split the problem in two\n * and return the recursively constructed diff.\n * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} deadline Time at which to bail if not yet complete.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) {\n  // Cache the text lengths to prevent multiple calls.\n  var text1_length = text1.length;\n  var text2_length = text2.length;\n  var max_d = Math.ceil((text1_length + text2_length) / 2);\n  var v_offset = max_d;\n  var v_length = 2 * max_d;\n  var v1 = new Array(v_length);\n  var v2 = new Array(v_length);\n  // Setting all elements to -1 is faster in Chrome & Firefox than mixing\n  // integers and undefined.\n  for (var x = 0; x < v_length; x++) {\n    v1[x] = -1;\n    v2[x] = -1;\n  }\n  v1[v_offset + 1] = 0;\n  v2[v_offset + 1] = 0;\n  var delta = text1_length - text2_length;\n  // If the total number of characters is odd, then the front path will collide\n  // with the reverse path.\n  var front = (delta % 2 != 0);\n  // Offsets for start and end of k loop.\n  // Prevents mapping of space beyond the grid.\n  var k1start = 0;\n  var k1end = 0;\n  var k2start = 0;\n  var k2end = 0;\n  for (var d = 0; d < max_d; d++) {\n    // Bail out if deadline is reached.\n    if ((new Date()).getTime() > deadline) {\n      break;\n    }\n\n    // Walk the front path one step.\n    for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {\n      var k1_offset = v_offset + k1;\n      var x1;\n      if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {\n        x1 = v1[k1_offset + 1];\n      } else {\n        x1 = v1[k1_offset - 1] + 1;\n      }\n      var y1 = x1 - k1;\n      while (x1 < text1_length && y1 < text2_length &&\n             text1.charAt(x1) == text2.charAt(y1)) {\n        x1++;\n        y1++;\n      }\n      v1[k1_offset] = x1;\n      if (x1 > text1_length) {\n        // Ran off the right of the graph.\n        k1end += 2;\n      } else if (y1 > text2_length) {\n        // Ran off the bottom of the graph.\n        k1start += 2;\n      } else if (front) {\n        var k2_offset = v_offset + delta - k1;\n        if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {\n          // Mirror x2 onto top-left coordinate system.\n          var x2 = text1_length - v2[k2_offset];\n          if (x1 >= x2) {\n            // Overlap detected.\n            return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);\n          }\n        }\n      }\n    }\n\n    // Walk the reverse path one step.\n    for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {\n      var k2_offset = v_offset + k2;\n      var x2;\n      if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {\n        x2 = v2[k2_offset + 1];\n      } else {\n        x2 = v2[k2_offset - 1] + 1;\n      }\n      var y2 = x2 - k2;\n      while (x2 < text1_length && y2 < text2_length &&\n             text1.charAt(text1_length - x2 - 1) ==\n             text2.charAt(text2_length - y2 - 1)) {\n        x2++;\n        y2++;\n      }\n      v2[k2_offset] = x2;\n      if (x2 > text1_length) {\n        // Ran off the left of the graph.\n        k2end += 2;\n      } else if (y2 > text2_length) {\n        // Ran off the top of the graph.\n        k2start += 2;\n      } else if (!front) {\n        var k1_offset = v_offset + delta - k2;\n        if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {\n          var x1 = v1[k1_offset];\n          var y1 = v_offset + x1 - k1_offset;\n          // Mirror x2 onto top-left coordinate system.\n          x2 = text1_length - x2;\n          if (x1 >= x2) {\n            // Overlap detected.\n            return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);\n          }\n        }\n      }\n    }\n  }\n  // Diff took too long and hit the deadline or\n  // number of diffs equals number of characters, no commonality at all.\n  return [new diff_match_patch.Diff(DIFF_DELETE, text1),\n          new diff_match_patch.Diff(DIFF_INSERT, text2)];\n};\n\n\n/**\n * Given the location of the 'middle snake', split the diff in two parts\n * and recurse.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} x Index of split point in text1.\n * @param {number} y Index of split point in text2.\n * @param {number} deadline Time at which to bail if not yet complete.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y,\n    deadline) {\n  var text1a = text1.substring(0, x);\n  var text2a = text2.substring(0, y);\n  var text1b = text1.substring(x);\n  var text2b = text2.substring(y);\n\n  // Compute both diffs serially.\n  var diffs = this.diff_main(text1a, text2a, false, deadline);\n  var diffsb = this.diff_main(text1b, text2b, false, deadline);\n\n  return diffs.concat(diffsb);\n};\n\n\n/**\n * Split two texts into an array of strings.  Reduce the texts to a string of\n * hashes where each Unicode character represents one line.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}\n *     An object containing the encoded text1, the encoded text2 and\n *     the array of unique strings.\n *     The zeroth element of the array of unique strings is intentionally blank.\n * @private\n */\ndiff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) {\n  var lineArray = [];  // e.g. lineArray[4] == 'Hello\\n'\n  var lineHash = {};   // e.g. lineHash['Hello\\n'] == 4\n\n  // '\\x00' is a valid character, but various debuggers don't like it.\n  // So we'll insert a junk entry to avoid generating a null character.\n  lineArray[0] = '';\n\n  /**\n   * Split a text into an array of strings.  Reduce the texts to a string of\n   * hashes where each Unicode character represents one line.\n   * Modifies linearray and linehash through being a closure.\n   * @param {string} text String to encode.\n   * @return {string} Encoded string.\n   * @private\n   */\n  function diff_linesToCharsMunge_(text) {\n    var chars = '';\n    // Walk the text, pulling out a substring for each line.\n    // text.split('\\n') would would temporarily double our memory footprint.\n    // Modifying text would create many large strings to garbage collect.\n    var lineStart = 0;\n    var lineEnd = -1;\n    // Keeping our own length variable is faster than looking it up.\n    var lineArrayLength = lineArray.length;\n    while (lineEnd < text.length - 1) {\n      lineEnd = text.indexOf('\\n', lineStart);\n      if (lineEnd == -1) {\n        lineEnd = text.length - 1;\n      }\n      var line = text.substring(lineStart, lineEnd + 1);\n\n      if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :\n          (lineHash[line] !== undefined)) {\n        chars += String.fromCharCode(lineHash[line]);\n      } else {\n        if (lineArrayLength == maxLines) {\n          // Bail out at 65535 because\n          // String.fromCharCode(65536) == String.fromCharCode(0)\n          line = text.substring(lineStart);\n          lineEnd = text.length;\n        }\n        chars += String.fromCharCode(lineArrayLength);\n        lineHash[line] = lineArrayLength;\n        lineArray[lineArrayLength++] = line;\n      }\n      lineStart = lineEnd + 1;\n    }\n    return chars;\n  }\n  // Allocate 2/3rds of the space for text1, the rest for text2.\n  var maxLines = 40000;\n  var chars1 = diff_linesToCharsMunge_(text1);\n  maxLines = 65535;\n  var chars2 = diff_linesToCharsMunge_(text2);\n  return {chars1: chars1, chars2: chars2, lineArray: lineArray};\n};\n\n\n/**\n * Rehydrate the text in a diff from a string of line hashes to real lines of\n * text.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @param {!Array.<string>} lineArray Array of unique strings.\n * @private\n */\ndiff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) {\n  for (var x = 0; x < diffs.length; x++) {\n    var chars = diffs[x][1];\n    var text = [];\n    for (var y = 0; y < chars.length; y++) {\n      text[y] = lineArray[chars.charCodeAt(y)];\n    }\n    diffs[x][1] = text.join('');\n  }\n};\n\n\n/**\n * Determine the common prefix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the start of each\n *     string.\n */\ndiff_match_patch.prototype.diff_commonPrefix = function(text1, text2) {\n  // Quick check for common null cases.\n  if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {\n    return 0;\n  }\n  // Binary search.\n  // Performance analysis: https://neil.fraser.name/news/2007/10/09/\n  var pointermin = 0;\n  var pointermax = Math.min(text1.length, text2.length);\n  var pointermid = pointermax;\n  var pointerstart = 0;\n  while (pointermin < pointermid) {\n    if (text1.substring(pointerstart, pointermid) ==\n        text2.substring(pointerstart, pointermid)) {\n      pointermin = pointermid;\n      pointerstart = pointermin;\n    } else {\n      pointermax = pointermid;\n    }\n    pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n  }\n  return pointermid;\n};\n\n\n/**\n * Determine the common suffix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of each string.\n */\ndiff_match_patch.prototype.diff_commonSuffix = function(text1, text2) {\n  // Quick check for common null cases.\n  if (!text1 || !text2 ||\n      text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {\n    return 0;\n  }\n  // Binary search.\n  // Performance analysis: https://neil.fraser.name/news/2007/10/09/\n  var pointermin = 0;\n  var pointermax = Math.min(text1.length, text2.length);\n  var pointermid = pointermax;\n  var pointerend = 0;\n  while (pointermin < pointermid) {\n    if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==\n        text2.substring(text2.length - pointermid, text2.length - pointerend)) {\n      pointermin = pointermid;\n      pointerend = pointermin;\n    } else {\n      pointermax = pointermid;\n    }\n    pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n  }\n  return pointermid;\n};\n\n\n/**\n * Determine if the suffix of one string is the prefix of another.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of the first\n *     string and the start of the second string.\n * @private\n */\ndiff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) {\n  // Cache the text lengths to prevent multiple calls.\n  var text1_length = text1.length;\n  var text2_length = text2.length;\n  // Eliminate the null case.\n  if (text1_length == 0 || text2_length == 0) {\n    return 0;\n  }\n  // Truncate the longer string.\n  if (text1_length > text2_length) {\n    text1 = text1.substring(text1_length - text2_length);\n  } else if (text1_length < text2_length) {\n    text2 = text2.substring(0, text1_length);\n  }\n  var text_length = Math.min(text1_length, text2_length);\n  // Quick check for the worst case.\n  if (text1 == text2) {\n    return text_length;\n  }\n\n  // Start by looking for a single character match\n  // and increase length until no match is found.\n  // Performance analysis: https://neil.fraser.name/news/2010/11/04/\n  var best = 0;\n  var length = 1;\n  while (true) {\n    var pattern = text1.substring(text_length - length);\n    var found = text2.indexOf(pattern);\n    if (found == -1) {\n      return best;\n    }\n    length += found;\n    if (found == 0 || text1.substring(text_length - length) ==\n        text2.substring(0, length)) {\n      best = length;\n      length++;\n    }\n  }\n};\n\n\n/**\n * Do the two texts share a substring which is at least half the length of the\n * longer text?\n * This speedup can produce non-minimal diffs.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {Array.<string>} Five element Array, containing the prefix of\n *     text1, the suffix of text1, the prefix of text2, the suffix of\n *     text2 and the common middle.  Or null if there was no match.\n * @private\n */\ndiff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) {\n  if (this.Diff_Timeout <= 0) {\n    // Don't risk returning a non-optimal diff if we have unlimited time.\n    return null;\n  }\n  var longtext = text1.length > text2.length ? text1 : text2;\n  var shorttext = text1.length > text2.length ? text2 : text1;\n  if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {\n    return null;  // Pointless.\n  }\n  var dmp = this;  // 'this' becomes 'window' in a closure.\n\n  /**\n   * Does a substring of shorttext exist within longtext such that the substring\n   * is at least half the length of longtext?\n   * Closure, but does not reference any external variables.\n   * @param {string} longtext Longer string.\n   * @param {string} shorttext Shorter string.\n   * @param {number} i Start index of quarter length substring within longtext.\n   * @return {Array.<string>} Five element Array, containing the prefix of\n   *     longtext, the suffix of longtext, the prefix of shorttext, the suffix\n   *     of shorttext and the common middle.  Or null if there was no match.\n   * @private\n   */\n  function diff_halfMatchI_(longtext, shorttext, i) {\n    // Start with a 1/4 length substring at position i as a seed.\n    var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));\n    var j = -1;\n    var best_common = '';\n    var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;\n    while ((j = shorttext.indexOf(seed, j + 1)) != -1) {\n      var prefixLength = dmp.diff_commonPrefix(longtext.substring(i),\n                                               shorttext.substring(j));\n      var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i),\n                                               shorttext.substring(0, j));\n      if (best_common.length < suffixLength + prefixLength) {\n        best_common = shorttext.substring(j - suffixLength, j) +\n            shorttext.substring(j, j + prefixLength);\n        best_longtext_a = longtext.substring(0, i - suffixLength);\n        best_longtext_b = longtext.substring(i + prefixLength);\n        best_shorttext_a = shorttext.substring(0, j - suffixLength);\n        best_shorttext_b = shorttext.substring(j + prefixLength);\n      }\n    }\n    if (best_common.length * 2 >= longtext.length) {\n      return [best_longtext_a, best_longtext_b,\n              best_shorttext_a, best_shorttext_b, best_common];\n    } else {\n      return null;\n    }\n  }\n\n  // First check if the second quarter is the seed for a half-match.\n  var hm1 = diff_halfMatchI_(longtext, shorttext,\n                             Math.ceil(longtext.length / 4));\n  // Check again based on the third quarter.\n  var hm2 = diff_halfMatchI_(longtext, shorttext,\n                             Math.ceil(longtext.length / 2));\n  var hm;\n  if (!hm1 && !hm2) {\n    return null;\n  } else if (!hm2) {\n    hm = hm1;\n  } else if (!hm1) {\n    hm = hm2;\n  } else {\n    // Both matched.  Select the longest.\n    hm = hm1[4].length > hm2[4].length ? hm1 : hm2;\n  }\n\n  // A half-match was found, sort out the return data.\n  var text1_a, text1_b, text2_a, text2_b;\n  if (text1.length > text2.length) {\n    text1_a = hm[0];\n    text1_b = hm[1];\n    text2_a = hm[2];\n    text2_b = hm[3];\n  } else {\n    text2_a = hm[0];\n    text2_b = hm[1];\n    text1_a = hm[2];\n    text1_b = hm[3];\n  }\n  var mid_common = hm[4];\n  return [text1_a, text1_b, text2_a, text2_b, mid_common];\n};\n\n\n/**\n * Reduce the number of edits by eliminating semantically trivial equalities.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupSemantic = function(diffs) {\n  var changes = false;\n  var equalities = [];  // Stack of indices where equalities are found.\n  var equalitiesLength = 0;  // Keeping our own length var is faster in JS.\n  /** @type {?string} */\n  var lastequality = null;\n  // Always equal to diffs[equalities[equalitiesLength - 1]][1]\n  var pointer = 0;  // Index of current position.\n  // Number of characters that changed prior to the equality.\n  var length_insertions1 = 0;\n  var length_deletions1 = 0;\n  // Number of characters that changed after the equality.\n  var length_insertions2 = 0;\n  var length_deletions2 = 0;\n  while (pointer < diffs.length) {\n    if (diffs[pointer][0] == DIFF_EQUAL) {  // Equality found.\n      equalities[equalitiesLength++] = pointer;\n      length_insertions1 = length_insertions2;\n      length_deletions1 = length_deletions2;\n      length_insertions2 = 0;\n      length_deletions2 = 0;\n      lastequality = diffs[pointer][1];\n    } else {  // An insertion or deletion.\n      if (diffs[pointer][0] == DIFF_INSERT) {\n        length_insertions2 += diffs[pointer][1].length;\n      } else {\n        length_deletions2 += diffs[pointer][1].length;\n      }\n      // Eliminate an equality that is smaller or equal to the edits on both\n      // sides of it.\n      if (lastequality && (lastequality.length <=\n          Math.max(length_insertions1, length_deletions1)) &&\n          (lastequality.length <= Math.max(length_insertions2,\n                                           length_deletions2))) {\n        // Duplicate record.\n        diffs.splice(equalities[equalitiesLength - 1], 0,\n                     new diff_match_patch.Diff(DIFF_DELETE, lastequality));\n        // Change second copy to insert.\n        diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n        // Throw away the equality we just deleted.\n        equalitiesLength--;\n        // Throw away the previous equality (it needs to be reevaluated).\n        equalitiesLength--;\n        pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;\n        length_insertions1 = 0;  // Reset the counters.\n        length_deletions1 = 0;\n        length_insertions2 = 0;\n        length_deletions2 = 0;\n        lastequality = null;\n        changes = true;\n      }\n    }\n    pointer++;\n  }\n\n  // Normalize the diff.\n  if (changes) {\n    this.diff_cleanupMerge(diffs);\n  }\n  this.diff_cleanupSemanticLossless(diffs);\n\n  // Find any overlaps between deletions and insertions.\n  // e.g: <del>abcxxx</del><ins>xxxdef</ins>\n  //   -> <del>abc</del>xxx<ins>def</ins>\n  // e.g: <del>xxxabc</del><ins>defxxx</ins>\n  //   -> <ins>def</ins>xxx<del>abc</del>\n  // Only extract an overlap if it is as big as the edit ahead or behind it.\n  pointer = 1;\n  while (pointer < diffs.length) {\n    if (diffs[pointer - 1][0] == DIFF_DELETE &&\n        diffs[pointer][0] == DIFF_INSERT) {\n      var deletion = diffs[pointer - 1][1];\n      var insertion = diffs[pointer][1];\n      var overlap_length1 = this.diff_commonOverlap_(deletion, insertion);\n      var overlap_length2 = this.diff_commonOverlap_(insertion, deletion);\n      if (overlap_length1 >= overlap_length2) {\n        if (overlap_length1 >= deletion.length / 2 ||\n            overlap_length1 >= insertion.length / 2) {\n          // Overlap found.  Insert an equality and trim the surrounding edits.\n          diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,\n              insertion.substring(0, overlap_length1)));\n          diffs[pointer - 1][1] =\n              deletion.substring(0, deletion.length - overlap_length1);\n          diffs[pointer + 1][1] = insertion.substring(overlap_length1);\n          pointer++;\n        }\n      } else {\n        if (overlap_length2 >= deletion.length / 2 ||\n            overlap_length2 >= insertion.length / 2) {\n          // Reverse overlap found.\n          // Insert an equality and swap and trim the surrounding edits.\n          diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,\n              deletion.substring(0, overlap_length2)));\n          diffs[pointer - 1][0] = DIFF_INSERT;\n          diffs[pointer - 1][1] =\n              insertion.substring(0, insertion.length - overlap_length2);\n          diffs[pointer + 1][0] = DIFF_DELETE;\n          diffs[pointer + 1][1] =\n              deletion.substring(overlap_length2);\n          pointer++;\n        }\n      }\n      pointer++;\n    }\n    pointer++;\n  }\n};\n\n\n/**\n * Look for single edits surrounded on both sides by equalities\n * which can be shifted sideways to align the edit to a word boundary.\n * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) {\n  /**\n   * Given two strings, compute a score representing whether the internal\n   * boundary falls on logical boundaries.\n   * Scores range from 6 (best) to 0 (worst).\n   * Closure, but does not reference any external variables.\n   * @param {string} one First string.\n   * @param {string} two Second string.\n   * @return {number} The score.\n   * @private\n   */\n  function diff_cleanupSemanticScore_(one, two) {\n    if (!one || !two) {\n      // Edges are the best.\n      return 6;\n    }\n\n    // Each port of this function behaves slightly differently due to\n    // subtle differences in each language's definition of things like\n    // 'whitespace'.  Since this function's purpose is largely cosmetic,\n    // the choice has been made to use each language's native features\n    // rather than force total conformity.\n    var char1 = one.charAt(one.length - 1);\n    var char2 = two.charAt(0);\n    var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_);\n    var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_);\n    var whitespace1 = nonAlphaNumeric1 &&\n        char1.match(diff_match_patch.whitespaceRegex_);\n    var whitespace2 = nonAlphaNumeric2 &&\n        char2.match(diff_match_patch.whitespaceRegex_);\n    var lineBreak1 = whitespace1 &&\n        char1.match(diff_match_patch.linebreakRegex_);\n    var lineBreak2 = whitespace2 &&\n        char2.match(diff_match_patch.linebreakRegex_);\n    var blankLine1 = lineBreak1 &&\n        one.match(diff_match_patch.blanklineEndRegex_);\n    var blankLine2 = lineBreak2 &&\n        two.match(diff_match_patch.blanklineStartRegex_);\n\n    if (blankLine1 || blankLine2) {\n      // Five points for blank lines.\n      return 5;\n    } else if (lineBreak1 || lineBreak2) {\n      // Four points for line breaks.\n      return 4;\n    } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {\n      // Three points for end of sentences.\n      return 3;\n    } else if (whitespace1 || whitespace2) {\n      // Two points for whitespace.\n      return 2;\n    } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {\n      // One point for non-alphanumeric.\n      return 1;\n    }\n    return 0;\n  }\n\n  var pointer = 1;\n  // Intentionally ignore the first and last element (don't need checking).\n  while (pointer < diffs.length - 1) {\n    if (diffs[pointer - 1][0] == DIFF_EQUAL &&\n        diffs[pointer + 1][0] == DIFF_EQUAL) {\n      // This is a single edit surrounded by equalities.\n      var equality1 = diffs[pointer - 1][1];\n      var edit = diffs[pointer][1];\n      var equality2 = diffs[pointer + 1][1];\n\n      // First, shift the edit as far left as possible.\n      var commonOffset = this.diff_commonSuffix(equality1, edit);\n      if (commonOffset) {\n        var commonString = edit.substring(edit.length - commonOffset);\n        equality1 = equality1.substring(0, equality1.length - commonOffset);\n        edit = commonString + edit.substring(0, edit.length - commonOffset);\n        equality2 = commonString + equality2;\n      }\n\n      // Second, step character by character right, looking for the best fit.\n      var bestEquality1 = equality1;\n      var bestEdit = edit;\n      var bestEquality2 = equality2;\n      var bestScore = diff_cleanupSemanticScore_(equality1, edit) +\n          diff_cleanupSemanticScore_(edit, equality2);\n      while (edit.charAt(0) === equality2.charAt(0)) {\n        equality1 += edit.charAt(0);\n        edit = edit.substring(1) + equality2.charAt(0);\n        equality2 = equality2.substring(1);\n        var score = diff_cleanupSemanticScore_(equality1, edit) +\n            diff_cleanupSemanticScore_(edit, equality2);\n        // The >= encourages trailing rather than leading whitespace on edits.\n        if (score >= bestScore) {\n          bestScore = score;\n          bestEquality1 = equality1;\n          bestEdit = edit;\n          bestEquality2 = equality2;\n        }\n      }\n\n      if (diffs[pointer - 1][1] != bestEquality1) {\n        // We have an improvement, save it back to the diff.\n        if (bestEquality1) {\n          diffs[pointer - 1][1] = bestEquality1;\n        } else {\n          diffs.splice(pointer - 1, 1);\n          pointer--;\n        }\n        diffs[pointer][1] = bestEdit;\n        if (bestEquality2) {\n          diffs[pointer + 1][1] = bestEquality2;\n        } else {\n          diffs.splice(pointer + 1, 1);\n          pointer--;\n        }\n      }\n    }\n    pointer++;\n  }\n};\n\n// Define some regex patterns for matching boundaries.\ndiff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;\ndiff_match_patch.whitespaceRegex_ = /\\s/;\ndiff_match_patch.linebreakRegex_ = /[\\r\\n]/;\ndiff_match_patch.blanklineEndRegex_ = /\\n\\r?\\n$/;\ndiff_match_patch.blanklineStartRegex_ = /^\\r?\\n\\r?\\n/;\n\n/**\n * Reduce the number of edits by eliminating operationally trivial equalities.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) {\n  var changes = false;\n  var equalities = [];  // Stack of indices where equalities are found.\n  var equalitiesLength = 0;  // Keeping our own length var is faster in JS.\n  /** @type {?string} */\n  var lastequality = null;\n  // Always equal to diffs[equalities[equalitiesLength - 1]][1]\n  var pointer = 0;  // Index of current position.\n  // Is there an insertion operation before the last equality.\n  var pre_ins = false;\n  // Is there a deletion operation before the last equality.\n  var pre_del = false;\n  // Is there an insertion operation after the last equality.\n  var post_ins = false;\n  // Is there a deletion operation after the last equality.\n  var post_del = false;\n  while (pointer < diffs.length) {\n    if (diffs[pointer][0] == DIFF_EQUAL) {  // Equality found.\n      if (diffs[pointer][1].length < this.Diff_EditCost &&\n          (post_ins || post_del)) {\n        // Candidate found.\n        equalities[equalitiesLength++] = pointer;\n        pre_ins = post_ins;\n        pre_del = post_del;\n        lastequality = diffs[pointer][1];\n      } else {\n        // Not a candidate, and can never become one.\n        equalitiesLength = 0;\n        lastequality = null;\n      }\n      post_ins = post_del = false;\n    } else {  // An insertion or deletion.\n      if (diffs[pointer][0] == DIFF_DELETE) {\n        post_del = true;\n      } else {\n        post_ins = true;\n      }\n      /*\n       * Five types to be split:\n       * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>\n       * <ins>A</ins>X<ins>C</ins><del>D</del>\n       * <ins>A</ins><del>B</del>X<ins>C</ins>\n       * <ins>A</del>X<ins>C</ins><del>D</del>\n       * <ins>A</ins><del>B</del>X<del>C</del>\n       */\n      if (lastequality && ((pre_ins && pre_del && post_ins && post_del) ||\n                           ((lastequality.length < this.Diff_EditCost / 2) &&\n                            (pre_ins + pre_del + post_ins + post_del) == 3))) {\n        // Duplicate record.\n        diffs.splice(equalities[equalitiesLength - 1], 0,\n                     new diff_match_patch.Diff(DIFF_DELETE, lastequality));\n        // Change second copy to insert.\n        diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n        equalitiesLength--;  // Throw away the equality we just deleted;\n        lastequality = null;\n        if (pre_ins && pre_del) {\n          // No changes made which could affect previous entry, keep going.\n          post_ins = post_del = true;\n          equalitiesLength = 0;\n        } else {\n          equalitiesLength--;  // Throw away the previous equality.\n          pointer = equalitiesLength > 0 ?\n              equalities[equalitiesLength - 1] : -1;\n          post_ins = post_del = false;\n        }\n        changes = true;\n      }\n    }\n    pointer++;\n  }\n\n  if (changes) {\n    this.diff_cleanupMerge(diffs);\n  }\n};\n\n\n/**\n * Reorder and merge like edit sections.  Merge equalities.\n * Any edit section can move as long as it doesn't cross an equality.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupMerge = function(diffs) {\n  // Add a dummy entry at the end.\n  diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));\n  var pointer = 0;\n  var count_delete = 0;\n  var count_insert = 0;\n  var text_delete = '';\n  var text_insert = '';\n  var commonlength;\n  while (pointer < diffs.length) {\n    switch (diffs[pointer][0]) {\n      case DIFF_INSERT:\n        count_insert++;\n        text_insert += diffs[pointer][1];\n        pointer++;\n        break;\n      case DIFF_DELETE:\n        count_delete++;\n        text_delete += diffs[pointer][1];\n        pointer++;\n        break;\n      case DIFF_EQUAL:\n        // Upon reaching an equality, check for prior redundancies.\n        if (count_delete + count_insert > 1) {\n          if (count_delete !== 0 && count_insert !== 0) {\n            // Factor out any common prefixies.\n            commonlength = this.diff_commonPrefix(text_insert, text_delete);\n            if (commonlength !== 0) {\n              if ((pointer - count_delete - count_insert) > 0 &&\n                  diffs[pointer - count_delete - count_insert - 1][0] ==\n                  DIFF_EQUAL) {\n                diffs[pointer - count_delete - count_insert - 1][1] +=\n                    text_insert.substring(0, commonlength);\n              } else {\n                diffs.splice(0, 0, new diff_match_patch.Diff(DIFF_EQUAL,\n                    text_insert.substring(0, commonlength)));\n                pointer++;\n              }\n              text_insert = text_insert.substring(commonlength);\n              text_delete = text_delete.substring(commonlength);\n            }\n            // Factor out any common suffixies.\n            commonlength = this.diff_commonSuffix(text_insert, text_delete);\n            if (commonlength !== 0) {\n              diffs[pointer][1] = text_insert.substring(text_insert.length -\n                  commonlength) + diffs[pointer][1];\n              text_insert = text_insert.substring(0, text_insert.length -\n                  commonlength);\n              text_delete = text_delete.substring(0, text_delete.length -\n                  commonlength);\n            }\n          }\n          // Delete the offending records and add the merged ones.\n          pointer -= count_delete + count_insert;\n          diffs.splice(pointer, count_delete + count_insert);\n          if (text_delete.length) {\n            diffs.splice(pointer, 0,\n                new diff_match_patch.Diff(DIFF_DELETE, text_delete));\n            pointer++;\n          }\n          if (text_insert.length) {\n            diffs.splice(pointer, 0,\n                new diff_match_patch.Diff(DIFF_INSERT, text_insert));\n            pointer++;\n          }\n          pointer++;\n        } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {\n          // Merge this equality with the previous one.\n          diffs[pointer - 1][1] += diffs[pointer][1];\n          diffs.splice(pointer, 1);\n        } else {\n          pointer++;\n        }\n        count_insert = 0;\n        count_delete = 0;\n        text_delete = '';\n        text_insert = '';\n        break;\n    }\n  }\n  if (diffs[diffs.length - 1][1] === '') {\n    diffs.pop();  // Remove the dummy entry at the end.\n  }\n\n  // Second pass: look for single edits surrounded on both sides by equalities\n  // which can be shifted sideways to eliminate an equality.\n  // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC\n  var changes = false;\n  pointer = 1;\n  // Intentionally ignore the first and last element (don't need checking).\n  while (pointer < diffs.length - 1) {\n    if (diffs[pointer - 1][0] == DIFF_EQUAL &&\n        diffs[pointer + 1][0] == DIFF_EQUAL) {\n      // This is a single edit surrounded by equalities.\n      if (diffs[pointer][1].substring(diffs[pointer][1].length -\n          diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {\n        // Shift the edit over the previous equality.\n        diffs[pointer][1] = diffs[pointer - 1][1] +\n            diffs[pointer][1].substring(0, diffs[pointer][1].length -\n                                        diffs[pointer - 1][1].length);\n        diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];\n        diffs.splice(pointer - 1, 1);\n        changes = true;\n      } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==\n          diffs[pointer + 1][1]) {\n        // Shift the edit over the next equality.\n        diffs[pointer - 1][1] += diffs[pointer + 1][1];\n        diffs[pointer][1] =\n            diffs[pointer][1].substring(diffs[pointer + 1][1].length) +\n            diffs[pointer + 1][1];\n        diffs.splice(pointer + 1, 1);\n        changes = true;\n      }\n    }\n    pointer++;\n  }\n  // If shifts were made, the diff needs reordering and another shift sweep.\n  if (changes) {\n    this.diff_cleanupMerge(diffs);\n  }\n};\n\n\n/**\n * loc is a location in text1, compute and return the equivalent location in\n * text2.\n * e.g. 'The cat' vs 'The big cat', 1->1, 5->8\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @param {number} loc Location within text1.\n * @return {number} Location within text2.\n */\ndiff_match_patch.prototype.diff_xIndex = function(diffs, loc) {\n  var chars1 = 0;\n  var chars2 = 0;\n  var last_chars1 = 0;\n  var last_chars2 = 0;\n  var x;\n  for (x = 0; x < diffs.length; x++) {\n    if (diffs[x][0] !== DIFF_INSERT) {  // Equality or deletion.\n      chars1 += diffs[x][1].length;\n    }\n    if (diffs[x][0] !== DIFF_DELETE) {  // Equality or insertion.\n      chars2 += diffs[x][1].length;\n    }\n    if (chars1 > loc) {  // Overshot the location.\n      break;\n    }\n    last_chars1 = chars1;\n    last_chars2 = chars2;\n  }\n  // Was the location was deleted?\n  if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {\n    return last_chars2;\n  }\n  // Add the remaining character length.\n  return last_chars2 + (loc - last_chars1);\n};\n\n\n/**\n * Convert a diff array into a pretty HTML report.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {string} HTML representation.\n */\ndiff_match_patch.prototype.diff_prettyHtml = function(diffs) {\n  var html = [];\n  var pattern_amp = /&/g;\n  var pattern_lt = /</g;\n  var pattern_gt = />/g;\n  var pattern_para = /\\n/g;\n  for (var x = 0; x < diffs.length; x++) {\n    var op = diffs[x][0];    // Operation (insert, delete, equal)\n    var data = diffs[x][1];  // Text of change.\n    var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')\n        .replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');\n    switch (op) {\n      case DIFF_INSERT:\n        html[x] = '<ins style=\"background:#e6ffe6;\">' + text + '</ins>';\n        break;\n      case DIFF_DELETE:\n        html[x] = '<del style=\"background:#ffe6e6;\">' + text + '</del>';\n        break;\n      case DIFF_EQUAL:\n        html[x] = '<span>' + text + '</span>';\n        break;\n    }\n  }\n  return html.join('');\n};\n\n\n/**\n * Compute and return the source text (all equalities and deletions).\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {string} Source text.\n */\ndiff_match_patch.prototype.diff_text1 = function(diffs) {\n  var text = [];\n  for (var x = 0; x < diffs.length; x++) {\n    if (diffs[x][0] !== DIFF_INSERT) {\n      text[x] = diffs[x][1];\n    }\n  }\n  return text.join('');\n};\n\n\n/**\n * Compute and return the destination text (all equalities and insertions).\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {string} Destination text.\n */\ndiff_match_patch.prototype.diff_text2 = function(diffs) {\n  var text = [];\n  for (var x = 0; x < diffs.length; x++) {\n    if (diffs[x][0] !== DIFF_DELETE) {\n      text[x] = diffs[x][1];\n    }\n  }\n  return text.join('');\n};\n\n\n/**\n * Compute the Levenshtein distance; the number of inserted, deleted or\n * substituted characters.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {number} Number of changes.\n */\ndiff_match_patch.prototype.diff_levenshtein = function(diffs) {\n  var levenshtein = 0;\n  var insertions = 0;\n  var deletions = 0;\n  for (var x = 0; x < diffs.length; x++) {\n    var op = diffs[x][0];\n    var data = diffs[x][1];\n    switch (op) {\n      case DIFF_INSERT:\n        insertions += data.length;\n        break;\n      case DIFF_DELETE:\n        deletions += data.length;\n        break;\n      case DIFF_EQUAL:\n        // A deletion and an insertion is one substitution.\n        levenshtein += Math.max(insertions, deletions);\n        insertions = 0;\n        deletions = 0;\n        break;\n    }\n  }\n  levenshtein += Math.max(insertions, deletions);\n  return levenshtein;\n};\n\n\n/**\n * Crush the diff into an encoded string which describes the operations\n * required to transform text1 into text2.\n * E.g. =3\\t-2\\t+ing  -> Keep 3 chars, delete 2 chars, insert 'ing'.\n * Operations are tab-separated.  Inserted text is escaped using %xx notation.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {string} Delta text.\n */\ndiff_match_patch.prototype.diff_toDelta = function(diffs) {\n  var text = [];\n  for (var x = 0; x < diffs.length; x++) {\n    switch (diffs[x][0]) {\n      case DIFF_INSERT:\n        text[x] = '+' + encodeURI(diffs[x][1]);\n        break;\n      case DIFF_DELETE:\n        text[x] = '-' + diffs[x][1].length;\n        break;\n      case DIFF_EQUAL:\n        text[x] = '=' + diffs[x][1].length;\n        break;\n    }\n  }\n  return text.join('\\t').replace(/%20/g, ' ');\n};\n\n\n/**\n * Given the original text1, and an encoded string which describes the\n * operations required to transform text1 into text2, compute the full diff.\n * @param {string} text1 Source string for the diff.\n * @param {string} delta Delta text.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @throws {!Error} If invalid input.\n */\ndiff_match_patch.prototype.diff_fromDelta = function(text1, delta) {\n  var diffs = [];\n  var diffsLength = 0;  // Keeping our own length var is faster in JS.\n  var pointer = 0;  // Cursor in text1\n  var tokens = delta.split(/\\t/g);\n  for (var x = 0; x < tokens.length; x++) {\n    // Each token begins with a one character parameter which specifies the\n    // operation of this token (delete, insert, equality).\n    var param = tokens[x].substring(1);\n    switch (tokens[x].charAt(0)) {\n      case '+':\n        try {\n          diffs[diffsLength++] =\n              new diff_match_patch.Diff(DIFF_INSERT, decodeURI(param));\n        } catch (ex) {\n          // Malformed URI sequence.\n          throw new Error('Illegal escape in diff_fromDelta: ' + param);\n        }\n        break;\n      case '-':\n        // Fall through.\n      case '=':\n        var n = parseInt(param, 10);\n        if (isNaN(n) || n < 0) {\n          throw new Error('Invalid number in diff_fromDelta: ' + param);\n        }\n        var text = text1.substring(pointer, pointer += n);\n        if (tokens[x].charAt(0) == '=') {\n          diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_EQUAL, text);\n        } else {\n          diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_DELETE, text);\n        }\n        break;\n      default:\n        // Blank tokens are ok (from a trailing \\t).\n        // Anything else is an error.\n        if (tokens[x]) {\n          throw new Error('Invalid diff operation in diff_fromDelta: ' +\n                          tokens[x]);\n        }\n    }\n  }\n  if (pointer != text1.length) {\n    throw new Error('Delta length (' + pointer +\n        ') does not equal source text length (' + text1.length + ').');\n  }\n  return diffs;\n};\n\n\n//  MATCH FUNCTIONS\n\n\n/**\n * Locate the best instance of 'pattern' in 'text' near 'loc'.\n * @param {string} text The text to search.\n * @param {string} pattern The pattern to search for.\n * @param {number} loc The location to search around.\n * @return {number} Best match index or -1.\n */\ndiff_match_patch.prototype.match_main = function(text, pattern, loc) {\n  // Check for null inputs.\n  if (text == null || pattern == null || loc == null) {\n    throw new Error('Null input. (match_main)');\n  }\n\n  loc = Math.max(0, Math.min(loc, text.length));\n  if (text == pattern) {\n    // Shortcut (potentially not guaranteed by the algorithm)\n    return 0;\n  } else if (!text.length) {\n    // Nothing to match.\n    return -1;\n  } else if (text.substring(loc, loc + pattern.length) == pattern) {\n    // Perfect match at the perfect spot!  (Includes case of null pattern)\n    return loc;\n  } else {\n    // Do a fuzzy compare.\n    return this.match_bitap_(text, pattern, loc);\n  }\n};\n\n\n/**\n * Locate the best instance of 'pattern' in 'text' near 'loc' using the\n * Bitap algorithm.\n * @param {string} text The text to search.\n * @param {string} pattern The pattern to search for.\n * @param {number} loc The location to search around.\n * @return {number} Best match index or -1.\n * @private\n */\ndiff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) {\n  if (pattern.length > this.Match_MaxBits) {\n    throw new Error('Pattern too long for this browser.');\n  }\n\n  // Initialise the alphabet.\n  var s = this.match_alphabet_(pattern);\n\n  var dmp = this;  // 'this' becomes 'window' in a closure.\n\n  /**\n   * Compute and return the score for a match with e errors and x location.\n   * Accesses loc and pattern through being a closure.\n   * @param {number} e Number of errors in match.\n   * @param {number} x Location of match.\n   * @return {number} Overall score for match (0.0 = good, 1.0 = bad).\n   * @private\n   */\n  function match_bitapScore_(e, x) {\n    var accuracy = e / pattern.length;\n    var proximity = Math.abs(loc - x);\n    if (!dmp.Match_Distance) {\n      // Dodge divide by zero error.\n      return proximity ? 1.0 : accuracy;\n    }\n    return accuracy + (proximity / dmp.Match_Distance);\n  }\n\n  // Highest score beyond which we give up.\n  var score_threshold = this.Match_Threshold;\n  // Is there a nearby exact match? (speedup)\n  var best_loc = text.indexOf(pattern, loc);\n  if (best_loc != -1) {\n    score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);\n    // What about in the other direction? (speedup)\n    best_loc = text.lastIndexOf(pattern, loc + pattern.length);\n    if (best_loc != -1) {\n      score_threshold =\n          Math.min(match_bitapScore_(0, best_loc), score_threshold);\n    }\n  }\n\n  // Initialise the bit arrays.\n  var matchmask = 1 << (pattern.length - 1);\n  best_loc = -1;\n\n  var bin_min, bin_mid;\n  var bin_max = pattern.length + text.length;\n  var last_rd;\n  for (var d = 0; d < pattern.length; d++) {\n    // Scan for the best match; each iteration allows for one more error.\n    // Run a binary search to determine how far from 'loc' we can stray at this\n    // error level.\n    bin_min = 0;\n    bin_mid = bin_max;\n    while (bin_min < bin_mid) {\n      if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {\n        bin_min = bin_mid;\n      } else {\n        bin_max = bin_mid;\n      }\n      bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);\n    }\n    // Use the result from this iteration as the maximum for the next.\n    bin_max = bin_mid;\n    var start = Math.max(1, loc - bin_mid + 1);\n    var finish = Math.min(loc + bin_mid, text.length) + pattern.length;\n\n    var rd = Array(finish + 2);\n    rd[finish + 1] = (1 << d) - 1;\n    for (var j = finish; j >= start; j--) {\n      // The alphabet (s) is a sparse hash, so the following line generates\n      // warnings.\n      var charMatch = s[text.charAt(j - 1)];\n      if (d === 0) {  // First pass: exact match.\n        rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;\n      } else {  // Subsequent passes: fuzzy match.\n        rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) |\n                (((last_rd[j + 1] | last_rd[j]) << 1) | 1) |\n                last_rd[j + 1];\n      }\n      if (rd[j] & matchmask) {\n        var score = match_bitapScore_(d, j - 1);\n        // This match will almost certainly be better than any existing match.\n        // But check anyway.\n        if (score <= score_threshold) {\n          // Told you so.\n          score_threshold = score;\n          best_loc = j - 1;\n          if (best_loc > loc) {\n            // When passing loc, don't exceed our current distance from loc.\n            start = Math.max(1, 2 * loc - best_loc);\n          } else {\n            // Already passed loc, downhill from here on in.\n            break;\n          }\n        }\n      }\n    }\n    // No hope for a (better) match at greater error levels.\n    if (match_bitapScore_(d + 1, loc) > score_threshold) {\n      break;\n    }\n    last_rd = rd;\n  }\n  return best_loc;\n};\n\n\n/**\n * Initialise the alphabet for the Bitap algorithm.\n * @param {string} pattern The text to encode.\n * @return {!Object} Hash of character locations.\n * @private\n */\ndiff_match_patch.prototype.match_alphabet_ = function(pattern) {\n  var s = {};\n  for (var i = 0; i < pattern.length; i++) {\n    s[pattern.charAt(i)] = 0;\n  }\n  for (var i = 0; i < pattern.length; i++) {\n    s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1);\n  }\n  return s;\n};\n\n\n//  PATCH FUNCTIONS\n\n\n/**\n * Increase the context until it is unique,\n * but don't let the pattern expand beyond Match_MaxBits.\n * @param {!diff_match_patch.patch_obj} patch The patch to grow.\n * @param {string} text Source text.\n * @private\n */\ndiff_match_patch.prototype.patch_addContext_ = function(patch, text) {\n  if (text.length == 0) {\n    return;\n  }\n  if (patch.start2 === null) {\n    throw Error('patch not initialized');\n  }\n  var pattern = text.substring(patch.start2, patch.start2 + patch.length1);\n  var padding = 0;\n\n  // Look for the first and last matches of pattern in text.  If two different\n  // matches are found, increase the pattern length.\n  while (text.indexOf(pattern) != text.lastIndexOf(pattern) &&\n         pattern.length < this.Match_MaxBits - this.Patch_Margin -\n         this.Patch_Margin) {\n    padding += this.Patch_Margin;\n    pattern = text.substring(patch.start2 - padding,\n                             patch.start2 + patch.length1 + padding);\n  }\n  // Add one chunk for good luck.\n  padding += this.Patch_Margin;\n\n  // Add the prefix.\n  var prefix = text.substring(patch.start2 - padding, patch.start2);\n  if (prefix) {\n    patch.diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, prefix));\n  }\n  // Add the suffix.\n  var suffix = text.substring(patch.start2 + patch.length1,\n                              patch.start2 + patch.length1 + padding);\n  if (suffix) {\n    patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, suffix));\n  }\n\n  // Roll back the start points.\n  patch.start1 -= prefix.length;\n  patch.start2 -= prefix.length;\n  // Extend the lengths.\n  patch.length1 += prefix.length + suffix.length;\n  patch.length2 += prefix.length + suffix.length;\n};\n\n\n/**\n * Compute a list of patches to turn text1 into text2.\n * Use diffs if provided, otherwise compute it ourselves.\n * There are four ways to call this function, depending on what data is\n * available to the caller:\n * Method 1:\n * a = text1, b = text2\n * Method 2:\n * a = diffs\n * Method 3 (optimal):\n * a = text1, b = diffs\n * Method 4 (deprecated, use method 3):\n * a = text1, b = text2, c = diffs\n *\n * @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or\n * Array of diff tuples for text1 to text2 (method 2).\n * @param {string|!Array.<!diff_match_patch.Diff>} opt_b text2 (methods 1,4) or\n * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).\n * @param {string|!Array.<!diff_match_patch.Diff>} opt_c Array of diff tuples\n * for text1 to text2 (method 4) or undefined (methods 1,2,3).\n * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.\n */\ndiff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) {\n  var text1, diffs;\n  if (typeof a == 'string' && typeof opt_b == 'string' &&\n      typeof opt_c == 'undefined') {\n    // Method 1: text1, text2\n    // Compute diffs from text1 and text2.\n    text1 = /** @type {string} */(a);\n    diffs = this.diff_main(text1, /** @type {string} */(opt_b), true);\n    if (diffs.length > 2) {\n      this.diff_cleanupSemantic(diffs);\n      this.diff_cleanupEfficiency(diffs);\n    }\n  } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' &&\n      typeof opt_c == 'undefined') {\n    // Method 2: diffs\n    // Compute text1 from diffs.\n    diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(a);\n    text1 = this.diff_text1(diffs);\n  } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' &&\n      typeof opt_c == 'undefined') {\n    // Method 3: text1, diffs\n    text1 = /** @type {string} */(a);\n    diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_b);\n  } else if (typeof a == 'string' && typeof opt_b == 'string' &&\n      opt_c && typeof opt_c == 'object') {\n    // Method 4: text1, text2, diffs\n    // text2 is not used.\n    text1 = /** @type {string} */(a);\n    diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_c);\n  } else {\n    throw new Error('Unknown call format to patch_make.');\n  }\n\n  if (diffs.length === 0) {\n    return [];  // Get rid of the null case.\n  }\n  var patches = [];\n  var patch = new diff_match_patch.patch_obj();\n  var patchDiffLength = 0;  // Keeping our own length var is faster in JS.\n  var char_count1 = 0;  // Number of characters into the text1 string.\n  var char_count2 = 0;  // Number of characters into the text2 string.\n  // Start with text1 (prepatch_text) and apply the diffs until we arrive at\n  // text2 (postpatch_text).  We recreate the patches one by one to determine\n  // context info.\n  var prepatch_text = text1;\n  var postpatch_text = text1;\n  for (var x = 0; x < diffs.length; x++) {\n    var diff_type = diffs[x][0];\n    var diff_text = diffs[x][1];\n\n    if (!patchDiffLength && diff_type !== DIFF_EQUAL) {\n      // A new patch starts here.\n      patch.start1 = char_count1;\n      patch.start2 = char_count2;\n    }\n\n    switch (diff_type) {\n      case DIFF_INSERT:\n        patch.diffs[patchDiffLength++] = diffs[x];\n        patch.length2 += diff_text.length;\n        postpatch_text = postpatch_text.substring(0, char_count2) + diff_text +\n                         postpatch_text.substring(char_count2);\n        break;\n      case DIFF_DELETE:\n        patch.length1 += diff_text.length;\n        patch.diffs[patchDiffLength++] = diffs[x];\n        postpatch_text = postpatch_text.substring(0, char_count2) +\n                         postpatch_text.substring(char_count2 +\n                             diff_text.length);\n        break;\n      case DIFF_EQUAL:\n        if (diff_text.length <= 2 * this.Patch_Margin &&\n            patchDiffLength && diffs.length != x + 1) {\n          // Small equality inside a patch.\n          patch.diffs[patchDiffLength++] = diffs[x];\n          patch.length1 += diff_text.length;\n          patch.length2 += diff_text.length;\n        } else if (diff_text.length >= 2 * this.Patch_Margin) {\n          // Time for a new patch.\n          if (patchDiffLength) {\n            this.patch_addContext_(patch, prepatch_text);\n            patches.push(patch);\n            patch = new diff_match_patch.patch_obj();\n            patchDiffLength = 0;\n            // Unlike Unidiff, our patch lists have a rolling context.\n            // https://github.com/google/diff-match-patch/wiki/Unidiff\n            // Update prepatch text & pos to reflect the application of the\n            // just completed patch.\n            prepatch_text = postpatch_text;\n            char_count1 = char_count2;\n          }\n        }\n        break;\n    }\n\n    // Update the current character count.\n    if (diff_type !== DIFF_INSERT) {\n      char_count1 += diff_text.length;\n    }\n    if (diff_type !== DIFF_DELETE) {\n      char_count2 += diff_text.length;\n    }\n  }\n  // Pick up the leftover patch if not empty.\n  if (patchDiffLength) {\n    this.patch_addContext_(patch, prepatch_text);\n    patches.push(patch);\n  }\n\n  return patches;\n};\n\n\n/**\n * Given an array of patches, return another array that is identical.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.\n */\ndiff_match_patch.prototype.patch_deepCopy = function(patches) {\n  // Making deep copies is hard in JavaScript.\n  var patchesCopy = [];\n  for (var x = 0; x < patches.length; x++) {\n    var patch = patches[x];\n    var patchCopy = new diff_match_patch.patch_obj();\n    patchCopy.diffs = [];\n    for (var y = 0; y < patch.diffs.length; y++) {\n      patchCopy.diffs[y] =\n          new diff_match_patch.Diff(patch.diffs[y][0], patch.diffs[y][1]);\n    }\n    patchCopy.start1 = patch.start1;\n    patchCopy.start2 = patch.start2;\n    patchCopy.length1 = patch.length1;\n    patchCopy.length2 = patch.length2;\n    patchesCopy[x] = patchCopy;\n  }\n  return patchesCopy;\n};\n\n\n/**\n * Merge a set of patches onto the text.  Return a patched text, as well\n * as a list of true/false values indicating which patches were applied.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n * @param {string} text Old text.\n * @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the\n *      new text and an array of boolean values.\n */\ndiff_match_patch.prototype.patch_apply = function(patches, text) {\n  if (patches.length == 0) {\n    return [text, []];\n  }\n\n  // Deep copy the patches so that no changes are made to originals.\n  patches = this.patch_deepCopy(patches);\n\n  var nullPadding = this.patch_addPadding(patches);\n  text = nullPadding + text + nullPadding;\n\n  this.patch_splitMax(patches);\n  // delta keeps track of the offset between the expected and actual location\n  // of the previous patch.  If there are patches expected at positions 10 and\n  // 20, but the first patch was found at 12, delta is 2 and the second patch\n  // has an effective expected position of 22.\n  var delta = 0;\n  var results = [];\n  for (var x = 0; x < patches.length; x++) {\n    var expected_loc = patches[x].start2 + delta;\n    var text1 = this.diff_text1(patches[x].diffs);\n    var start_loc;\n    var end_loc = -1;\n    if (text1.length > this.Match_MaxBits) {\n      // patch_splitMax will only provide an oversized pattern in the case of\n      // a monster delete.\n      start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits),\n                                  expected_loc);\n      if (start_loc != -1) {\n        end_loc = this.match_main(text,\n            text1.substring(text1.length - this.Match_MaxBits),\n            expected_loc + text1.length - this.Match_MaxBits);\n        if (end_loc == -1 || start_loc >= end_loc) {\n          // Can't find valid trailing context.  Drop this patch.\n          start_loc = -1;\n        }\n      }\n    } else {\n      start_loc = this.match_main(text, text1, expected_loc);\n    }\n    if (start_loc == -1) {\n      // No match found.  :(\n      results[x] = false;\n      // Subtract the delta for this failed patch from subsequent patches.\n      delta -= patches[x].length2 - patches[x].length1;\n    } else {\n      // Found a match.  :)\n      results[x] = true;\n      delta = start_loc - expected_loc;\n      var text2;\n      if (end_loc == -1) {\n        text2 = text.substring(start_loc, start_loc + text1.length);\n      } else {\n        text2 = text.substring(start_loc, end_loc + this.Match_MaxBits);\n      }\n      if (text1 == text2) {\n        // Perfect match, just shove the replacement text in.\n        text = text.substring(0, start_loc) +\n               this.diff_text2(patches[x].diffs) +\n               text.substring(start_loc + text1.length);\n      } else {\n        // Imperfect match.  Run a diff to get a framework of equivalent\n        // indices.\n        var diffs = this.diff_main(text1, text2, false);\n        if (text1.length > this.Match_MaxBits &&\n            this.diff_levenshtein(diffs) / text1.length >\n            this.Patch_DeleteThreshold) {\n          // The end points match, but the content is unacceptably bad.\n          results[x] = false;\n        } else {\n          this.diff_cleanupSemanticLossless(diffs);\n          var index1 = 0;\n          var index2;\n          for (var y = 0; y < patches[x].diffs.length; y++) {\n            var mod = patches[x].diffs[y];\n            if (mod[0] !== DIFF_EQUAL) {\n              index2 = this.diff_xIndex(diffs, index1);\n            }\n            if (mod[0] === DIFF_INSERT) {  // Insertion\n              text = text.substring(0, start_loc + index2) + mod[1] +\n                     text.substring(start_loc + index2);\n            } else if (mod[0] === DIFF_DELETE) {  // Deletion\n              text = text.substring(0, start_loc + index2) +\n                     text.substring(start_loc + this.diff_xIndex(diffs,\n                         index1 + mod[1].length));\n            }\n            if (mod[0] !== DIFF_DELETE) {\n              index1 += mod[1].length;\n            }\n          }\n        }\n      }\n    }\n  }\n  // Strip the padding off.\n  text = text.substring(nullPadding.length, text.length - nullPadding.length);\n  return [text, results];\n};\n\n\n/**\n * Add some padding on text start and end so that edges can match something.\n * Intended to be called only from within patch_apply.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n * @return {string} The padding string added to each side.\n */\ndiff_match_patch.prototype.patch_addPadding = function(patches) {\n  var paddingLength = this.Patch_Margin;\n  var nullPadding = '';\n  for (var x = 1; x <= paddingLength; x++) {\n    nullPadding += String.fromCharCode(x);\n  }\n\n  // Bump all the patches forward.\n  for (var x = 0; x < patches.length; x++) {\n    patches[x].start1 += paddingLength;\n    patches[x].start2 += paddingLength;\n  }\n\n  // Add some padding on start of first diff.\n  var patch = patches[0];\n  var diffs = patch.diffs;\n  if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {\n    // Add nullPadding equality.\n    diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));\n    patch.start1 -= paddingLength;  // Should be 0.\n    patch.start2 -= paddingLength;  // Should be 0.\n    patch.length1 += paddingLength;\n    patch.length2 += paddingLength;\n  } else if (paddingLength > diffs[0][1].length) {\n    // Grow first equality.\n    var extraLength = paddingLength - diffs[0][1].length;\n    diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1];\n    patch.start1 -= extraLength;\n    patch.start2 -= extraLength;\n    patch.length1 += extraLength;\n    patch.length2 += extraLength;\n  }\n\n  // Add some padding on end of last diff.\n  patch = patches[patches.length - 1];\n  diffs = patch.diffs;\n  if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {\n    // Add nullPadding equality.\n    diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));\n    patch.length1 += paddingLength;\n    patch.length2 += paddingLength;\n  } else if (paddingLength > diffs[diffs.length - 1][1].length) {\n    // Grow last equality.\n    var extraLength = paddingLength - diffs[diffs.length - 1][1].length;\n    diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);\n    patch.length1 += extraLength;\n    patch.length2 += extraLength;\n  }\n\n  return nullPadding;\n};\n\n\n/**\n * Look through the patches and break up any which are longer than the maximum\n * limit of the match algorithm.\n * Intended to be called only from within patch_apply.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n */\ndiff_match_patch.prototype.patch_splitMax = function(patches) {\n  var patch_size = this.Match_MaxBits;\n  for (var x = 0; x < patches.length; x++) {\n    if (patches[x].length1 <= patch_size) {\n      continue;\n    }\n    var bigpatch = patches[x];\n    // Remove the big old patch.\n    patches.splice(x--, 1);\n    var start1 = bigpatch.start1;\n    var start2 = bigpatch.start2;\n    var precontext = '';\n    while (bigpatch.diffs.length !== 0) {\n      // Create one of several smaller patches.\n      var patch = new diff_match_patch.patch_obj();\n      var empty = true;\n      patch.start1 = start1 - precontext.length;\n      patch.start2 = start2 - precontext.length;\n      if (precontext !== '') {\n        patch.length1 = patch.length2 = precontext.length;\n        patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, precontext));\n      }\n      while (bigpatch.diffs.length !== 0 &&\n             patch.length1 < patch_size - this.Patch_Margin) {\n        var diff_type = bigpatch.diffs[0][0];\n        var diff_text = bigpatch.diffs[0][1];\n        if (diff_type === DIFF_INSERT) {\n          // Insertions are harmless.\n          patch.length2 += diff_text.length;\n          start2 += diff_text.length;\n          patch.diffs.push(bigpatch.diffs.shift());\n          empty = false;\n        } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 &&\n                   patch.diffs[0][0] == DIFF_EQUAL &&\n                   diff_text.length > 2 * patch_size) {\n          // This is a large deletion.  Let it pass in one chunk.\n          patch.length1 += diff_text.length;\n          start1 += diff_text.length;\n          empty = false;\n          patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));\n          bigpatch.diffs.shift();\n        } else {\n          // Deletion or equality.  Only take as much as we can stomach.\n          diff_text = diff_text.substring(0,\n              patch_size - patch.length1 - this.Patch_Margin);\n          patch.length1 += diff_text.length;\n          start1 += diff_text.length;\n          if (diff_type === DIFF_EQUAL) {\n            patch.length2 += diff_text.length;\n            start2 += diff_text.length;\n          } else {\n            empty = false;\n          }\n          patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));\n          if (diff_text == bigpatch.diffs[0][1]) {\n            bigpatch.diffs.shift();\n          } else {\n            bigpatch.diffs[0][1] =\n                bigpatch.diffs[0][1].substring(diff_text.length);\n          }\n        }\n      }\n      // Compute the head context for the next patch.\n      precontext = this.diff_text2(patch.diffs);\n      precontext =\n          precontext.substring(precontext.length - this.Patch_Margin);\n      // Append the end context for this patch.\n      var postcontext = this.diff_text1(bigpatch.diffs)\n                            .substring(0, this.Patch_Margin);\n      if (postcontext !== '') {\n        patch.length1 += postcontext.length;\n        patch.length2 += postcontext.length;\n        if (patch.diffs.length !== 0 &&\n            patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {\n          patch.diffs[patch.diffs.length - 1][1] += postcontext;\n        } else {\n          patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, postcontext));\n        }\n      }\n      if (!empty) {\n        patches.splice(++x, 0, patch);\n      }\n    }\n  }\n};\n\n\n/**\n * Take a list of patches and return a textual representation.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n * @return {string} Text representation of patches.\n */\ndiff_match_patch.prototype.patch_toText = function(patches) {\n  var text = [];\n  for (var x = 0; x < patches.length; x++) {\n    text[x] = patches[x];\n  }\n  return text.join('');\n};\n\n\n/**\n * Parse a textual representation of patches and return a list of Patch objects.\n * @param {string} textline Text representation of patches.\n * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.\n * @throws {!Error} If invalid input.\n */\ndiff_match_patch.prototype.patch_fromText = function(textline) {\n  var patches = [];\n  if (!textline) {\n    return patches;\n  }\n  var text = textline.split('\\n');\n  var textPointer = 0;\n  var patchHeader = /^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$/;\n  while (textPointer < text.length) {\n    var m = text[textPointer].match(patchHeader);\n    if (!m) {\n      throw new Error('Invalid patch string: ' + text[textPointer]);\n    }\n    var patch = new diff_match_patch.patch_obj();\n    patches.push(patch);\n    patch.start1 = parseInt(m[1], 10);\n    if (m[2] === '') {\n      patch.start1--;\n      patch.length1 = 1;\n    } else if (m[2] == '0') {\n      patch.length1 = 0;\n    } else {\n      patch.start1--;\n      patch.length1 = parseInt(m[2], 10);\n    }\n\n    patch.start2 = parseInt(m[3], 10);\n    if (m[4] === '') {\n      patch.start2--;\n      patch.length2 = 1;\n    } else if (m[4] == '0') {\n      patch.length2 = 0;\n    } else {\n      patch.start2--;\n      patch.length2 = parseInt(m[4], 10);\n    }\n    textPointer++;\n\n    while (textPointer < text.length) {\n      var sign = text[textPointer].charAt(0);\n      try {\n        var line = decodeURI(text[textPointer].substring(1));\n      } catch (ex) {\n        // Malformed URI sequence.\n        throw new Error('Illegal escape in patch_fromText: ' + line);\n      }\n      if (sign == '-') {\n        // Deletion.\n        patch.diffs.push(new diff_match_patch.Diff(DIFF_DELETE, line));\n      } else if (sign == '+') {\n        // Insertion.\n        patch.diffs.push(new diff_match_patch.Diff(DIFF_INSERT, line));\n      } else if (sign == ' ') {\n        // Minor equality.\n        patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, line));\n      } else if (sign == '@') {\n        // Start of next patch.\n        break;\n      } else if (sign === '') {\n        // Blank line?  Whatever.\n      } else {\n        // WTF?\n        throw new Error('Invalid patch mode \"' + sign + '\" in: ' + line);\n      }\n      textPointer++;\n    }\n  }\n  return patches;\n};\n\n\n/**\n * Class representing one patch operation.\n * @constructor\n */\ndiff_match_patch.patch_obj = function() {\n  /** @type {!Array.<!diff_match_patch.Diff>} */\n  this.diffs = [];\n  /** @type {?number} */\n  this.start1 = null;\n  /** @type {?number} */\n  this.start2 = null;\n  /** @type {number} */\n  this.length1 = 0;\n  /** @type {number} */\n  this.length2 = 0;\n};\n\n\n/**\n * Emulate GNU diff's format.\n * Header: @@ -382,8 +481,9 @@\n * Indices are printed as 1-based, not 0-based.\n * @return {string} The GNU diff string.\n */\ndiff_match_patch.patch_obj.prototype.toString = function() {\n  var coords1, coords2;\n  if (this.length1 === 0) {\n    coords1 = this.start1 + ',0';\n  } else if (this.length1 == 1) {\n    coords1 = this.start1 + 1;\n  } else {\n    coords1 = (this.start1 + 1) + ',' + this.length1;\n  }\n  if (this.length2 === 0) {\n    coords2 = this.start2 + ',0';\n  } else if (this.length2 == 1) {\n    coords2 = this.start2 + 1;\n  } else {\n    coords2 = (this.start2 + 1) + ',' + this.length2;\n  }\n  var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\\n'];\n  var op;\n  // Escape the body of the patch with %xx notation.\n  for (var x = 0; x < this.diffs.length; x++) {\n    switch (this.diffs[x][0]) {\n      case DIFF_INSERT:\n        op = '+';\n        break;\n      case DIFF_DELETE:\n        op = '-';\n        break;\n      case DIFF_EQUAL:\n        op = ' ';\n        break;\n    }\n    text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\\n';\n  }\n  return text.join('').replace(/%20/g, ' ');\n};\n\n// STRIP_FOR_CLOSURE\n// Lines below here will not be included in the Closure-compatible library.\n\n// Export these global variables so that they survive Google's JS compiler.\n// In a browser, 'this' will be 'window'.\n// Users of node.js should 'require' the uncompressed version since Google's\n// JS compiler may break the following exports for non-browser environments.\n/** @suppress {globalThis} */\nthis['diff_match_patch'] = diff_match_patch;\n/** @suppress {globalThis} */\nthis['DIFF_DELETE'] = DIFF_DELETE;\n/** @suppress {globalThis} */\nthis['DIFF_INSERT'] = DIFF_INSERT;\n/** @suppress {globalThis} */\nthis['DIFF_EQUAL'] = DIFF_EQUAL;\n"
  },
  {
    "path": "third_party/JSHint/LICENSE",
    "content": "Copyright 2012 Anton Kovalyov (http://jshint.com)\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "third_party/JSHint/README.md",
    "content": "# JSHint, A Static Code Analysis Tool for JavaScript\n\n\\[ [Use it online](http://jshint.com/) •\n[Docs](http://jshint.com/docs/) • [FAQ](http://jshint.com/docs/faq) •\n[Install](http://jshint.com/install/) •\n[Contribute](http://jshint.com/contribute/) •\n[Blog](http://jshint.com/blog/) • [Twitter](https://twitter.com/jshint/) \\]\n\n[![NPM version](https://img.shields.io/npm/v/jshint.svg?style=flat)](https://www.npmjs.com/package/jshint)\n[![Linux Build Status](https://img.shields.io/travis/jshint/jshint/master.svg?style=flat&label=Linux%20build)](https://travis-ci.org/jshint/jshint)\n[![Windows Build status](https://img.shields.io/appveyor/ci/jshint/jshint/master.svg?style=flat&label=Windows%20build)](https://ci.appveyor.com/project/jshint/jshint/branch/master)\n[![Dependency Status](https://img.shields.io/david/jshint/jshint.svg?style=flat)](https://david-dm.org/jshint/jshint)\n[![devDependency Status](https://img.shields.io/david/dev/jshint/jshint.svg?style=flat)](https://david-dm.org/jshint/jshint#info=devDependencies)\n[![Coverage Status](https://img.shields.io/coveralls/jshint/jshint.svg?style=flat)](https://coveralls.io/r/jshint/jshint?branch=master)\n\nJSHint is a community-driven tool that detects errors and potential problems in\nJavaScript code. Since JSHint is so flexible, you can easily adjust it in \nthe environment you expect your code to execute. JSHint is open source and\nwill always stay this way.\n\n## Our goal\n\nThe project aims to help JavaScript developers write complex programs\nwithout worrying about typos and language gotchas.\n\nAny code base eventually becomes huge at some point, so simple mistakes — that\nwould not show themselves when written — can become show stoppers and add \nextra hours of debugging. So, static code analysis tools come into play\nand help developers spot such problems. JSHint scans a program written in\nJavaScript and reports about commonly made mistakes and potential bugs. The\npotential problem could be a syntax error, a bug due to an implicit type\nconversion, a leaking variable, or something else entirely.\n\nOnly 15% of all programs linted on [jshint.com](http://jshint.com) pass the\nJSHint checks. In all other cases, JSHint finds some red flags that could've\nbeen bugs or potential problems.\n\nPlease note, that while static code analysis tools can spot many different kind\nof mistakes, it can't detect if your program is correct, fast or has memory\nleaks. You should always combine tools like JSHint with unit and functional\ntests as well as with code reviews.\n\n## Reporting a bug\n\nTo report a bug simply create a\n[new GitHub Issue](https://github.com/jshint/jshint/issues/new) and describe\nyour problem or suggestion. We welcome all kinds of feedback regarding\nJSHint including but not limited to:\n\n * When JSHint doesn't work as expected\n * When JSHint complains about valid JavaScript code that works in all browsers\n * When you simply want a new option or feature\n\nBefore reporting a bug, please look around to see if there are any open or closed tickets\nthat discuss your issue, and remember the wisdom: pull request > bug report > tweet.\n\n## Who uses JSHint?\n\nEngineers from these companies and projects use JSHint:\n\n* [Mozilla](https://www.mozilla.org/)\n* [Wikipedia](https://wikipedia.org/)\n* [Facebook](https://facebook.com/)\n* [Twitter](https://twitter.com/)\n* [Bootstrap](http://getbootstrap.com/)\n* [Disqus](https://disqus.com/)\n* [Medium](https://medium.com/)\n* [Yahoo!](https://yahoo.com/)\n* [SmugMug](http://smugmug.com/)\n* [jQuery](http://jquery.com/)\n* [PDF.js](http://mozilla.github.io/pdf.js)\n* [Coursera](http://coursera.com/)\n* [Adobe Brackets](http://brackets.io/)\n* [Apache Cordova](http://cordova.io/)\n* [RedHat](http://redhat.com/)\n* [SoundCloud](http://soundcloud.com/)\n* [Nodejitsu](http://nodejitsu.com/)\n* [Yelp](https://yelp.com/)\n* [Voxer](http://voxer.com/)\n* [EnyoJS](http://enyojs.com/)\n* [QuickenLoans](http://quickenloans.com/)\n* [Cloud9](http://c9.io/)\n* [CodeClimate](https://codeclimate.com/)\n* [Zendesk](http://zendesk.com/)\n* [Apache CouchDB](http://couchdb.apache.org/)\n* [Google](https://www.google.com/)\n* [Codacy](https://www.codacy.com) [ref](https://support.codacy.com/hc/en-us/articles/207995005-Special-Thanks)\n\nAnd many more!\n\n## License\n\nMost files are published using [the standard MIT Expat\nlicense](https://www.gnu.org/licenses/license-list.html#Expat). One file,\nhowever, is provided under a slightly modified version of that license. The\nso-called [JSON license](https://www.gnu.org/licenses/license-list.html#JSON)\nis a non-free license, and unfortunately, we can't change it due to historical\nreasons. This license is included as an in-line within the file it concerns.\n\n## The JSHint Team\n\nJSHint is currently maintained by [Rick Waldron](https://github.com/rwaldron/),\n[Caitlin Potter](https://github.com/caitp/), [Mike\nPennisi](https://github.com/jugglinmike/), and [Luke\nPage](https://github.com/lukeapage). You can reach them via admin@jshint.org.\n\n## Previous Maintainers\n\nOriginating from the JSLint project in 2010, JSHint has been maintained by a\nnumber of dedicated individuals. In chronological order, they are: Douglas\nCrockford, Anton Kovalyov, and Mike Sherov. We appreciate their long-term\ncommitment!\n\n## Thank you!\n\nWe really appreciate all kinds of feedback and contributions. Thanks for using and supporting JSHint!\n"
  },
  {
    "path": "third_party/JSHint/jshint.js",
    "content": "/*! 2.9.6 */\nvar JSHINT;\nif (typeof window === 'undefined') window = {};\n(function () {\nvar require;\nrequire=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){\nvar identifierStartTable = [];\n\nfor (var i = 0; i < 128; i++) {\n  identifierStartTable[i] =\n    i === 36 ||           // $\n    i >= 65 && i <= 90 || // A-Z\n    i === 95 ||           // _\n    i >= 97 && i <= 122;  // a-z\n}\n\nvar identifierPartTable = [];\n\nfor (var i = 0; i < 128; i++) {\n  identifierPartTable[i] =\n    identifierStartTable[i] || // $, _, A-Z, a-z\n    i >= 48 && i <= 57;        // 0-9\n}\n\nmodule.exports = {\n  asciiIdentifierStartTable: identifierStartTable,\n  asciiIdentifierPartTable: identifierPartTable\n};\n\n},{}],2:[function(require,module,exports){\nmodule.exports = /^(?:[\\$A-Z_a-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0525\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCB\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA2D\\uFA30-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC])(?:[\\$0-9A-Z_a-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u0525\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0621-\\u065E\\u0660-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0900-\\u0939\\u093C-\\u094E\\u0950-\\u0955\\u0958-\\u0963\\u0966-\\u096F\\u0971\\u0972\\u0979-\\u097F\\u0981-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BEF\\u0C01-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58\\u0C59\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C82\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0D02\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D60-\\u0D63\\u0D66-\\u0D6F\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC\\u0EDD\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F8B\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135F\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17B3\\u17B6-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19DA\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BAA\\u1BAE-\\u1BB9\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1CD0-\\u1CD2\\u1CD4-\\u1CF2\\u1D00-\\u1DE6\\u1DFD-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u200C\\u200D\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u2094\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF1\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCB\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA65F\\uA662-\\uA66F\\uA67C\\uA67D\\uA67F-\\uA697\\uA6A0-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA827\\uA840-\\uA873\\uA880-\\uA8C4\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A\\uAA7B\\uAA80-\\uAAC2\\uAADB-\\uAADD\\uABC0-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA2D\\uFA30-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE26\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC])*$/;\n},{}],3:[function(require,module,exports){\nvar str = '183,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,903,1155,1156,1157,1158,1159,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1471,1473,1474,1476,1477,1479,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1632,1633,1634,1635,1636,1637,1638,1639,1640,1641,1648,1750,1751,1752,1753,1754,1755,1756,1759,1760,1761,1762,1763,1764,1767,1768,1770,1771,1772,1773,1776,1777,1778,1779,1780,1781,1782,1783,1784,1785,1809,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,2027,2028,2029,2030,2031,2032,2033,2034,2035,2045,2070,2071,2072,2073,2075,2076,2077,2078,2079,2080,2081,2082,2083,2085,2086,2087,2089,2090,2091,2092,2093,2137,2138,2139,2259,2260,2261,2262,2263,2264,2265,2266,2267,2268,2269,2270,2271,2272,2273,2275,2276,2277,2278,2279,2280,2281,2282,2283,2284,2285,2286,2287,2288,2289,2290,2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302,2303,2304,2305,2306,2307,2362,2363,2364,2366,2367,2368,2369,2370,2371,2372,2373,2374,2375,2376,2377,2378,2379,2380,2381,2382,2383,2385,2386,2387,2388,2389,2390,2391,2402,2403,2406,2407,2408,2409,2410,2411,2412,2413,2414,2415,2433,2434,2435,2492,2494,2495,2496,2497,2498,2499,2500,2503,2504,2507,2508,2509,2519,2530,2531,2534,2535,2536,2537,2538,2539,2540,2541,2542,2543,2558,2561,2562,2563,2620,2622,2623,2624,2625,2626,2631,2632,2635,2636,2637,2641,2662,2663,2664,2665,2666,2667,2668,2669,2670,2671,2672,2673,2677,2689,2690,2691,2748,2750,2751,2752,2753,2754,2755,2756,2757,2759,2760,2761,2763,2764,2765,2786,2787,2790,2791,2792,2793,2794,2795,2796,2797,2798,2799,2810,2811,2812,2813,2814,2815,2817,2818,2819,2876,2878,2879,2880,2881,2882,2883,2884,2887,2888,2891,2892,2893,2902,2903,2914,2915,2918,2919,2920,2921,2922,2923,2924,2925,2926,2927,2946,3006,3007,3008,3009,3010,3014,3015,3016,3018,3019,3020,3021,3031,3046,3047,3048,3049,3050,3051,3052,3053,3054,3055,3072,3073,3074,3075,3076,3134,3135,3136,3137,3138,3139,3140,3142,3143,3144,3146,3147,3148,3149,3157,3158,3170,3171,3174,3175,3176,3177,3178,3179,3180,3181,3182,3183,3201,3202,3203,3260,3262,3263,3264,3265,3266,3267,3268,3270,3271,3272,3274,3275,3276,3277,3285,3286,3298,3299,3302,3303,3304,3305,3306,3307,3308,3309,3310,3311,3328,3329,3330,3331,3387,3388,3390,3391,3392,3393,3394,3395,3396,3398,3399,3400,3402,3403,3404,3405,3415,3426,3427,3430,3431,3432,3433,3434,3435,3436,3437,3438,3439,3458,3459,3530,3535,3536,3537,3538,3539,3540,3542,3544,3545,3546,3547,3548,3549,3550,3551,3558,3559,3560,3561,3562,3563,3564,3565,3566,3567,3570,3571,3633,3636,3637,3638,3639,3640,3641,3642,3655,3656,3657,3658,3659,3660,3661,3662,3664,3665,3666,3667,3668,3669,3670,3671,3672,3673,3761,3764,3765,3766,3767,3768,3769,3771,3772,3784,3785,3786,3787,3788,3789,3792,3793,3794,3795,3796,3797,3798,3799,3800,3801,3864,3865,3872,3873,3874,3875,3876,3877,3878,3879,3880,3881,3893,3895,3897,3902,3903,3953,3954,3955,3956,3957,3958,3959,3960,3961,3962,3963,3964,3965,3966,3967,3968,3969,3970,3971,3972,3974,3975,3981,3982,3983,3984,3985,3986,3987,3988,3989,3990,3991,3993,3994,3995,3996,3997,3998,3999,4000,4001,4002,4003,4004,4005,4006,4007,4008,4009,4010,4011,4012,4013,4014,4015,4016,4017,4018,4019,4020,4021,4022,4023,4024,4025,4026,4027,4028,4038,4139,4140,4141,4142,4143,4144,4145,4146,4147,4148,4149,4150,4151,4152,4153,4154,4155,4156,4157,4158,4160,4161,4162,4163,4164,4165,4166,4167,4168,4169,4182,4183,4184,4185,4190,4191,4192,4194,4195,4196,4199,4200,4201,4202,4203,4204,4205,4209,4210,4211,4212,4226,4227,4228,4229,4230,4231,4232,4233,4234,4235,4236,4237,4239,4240,4241,4242,4243,4244,4245,4246,4247,4248,4249,4250,4251,4252,4253,4957,4958,4959,4969,4970,4971,4972,4973,4974,4975,4976,4977,5906,5907,5908,5938,5939,5940,5970,5971,6002,6003,6068,6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084,6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6109,6112,6113,6114,6115,6116,6117,6118,6119,6120,6121,6155,6156,6157,6160,6161,6162,6163,6164,6165,6166,6167,6168,6169,6313,6432,6433,6434,6435,6436,6437,6438,6439,6440,6441,6442,6443,6448,6449,6450,6451,6452,6453,6454,6455,6456,6457,6458,6459,6470,6471,6472,6473,6474,6475,6476,6477,6478,6479,6608,6609,6610,6611,6612,6613,6614,6615,6616,6617,6618,6679,6680,6681,6682,6683,6741,6742,6743,6744,6745,6746,6747,6748,6749,6750,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761,6762,6763,6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777,6778,6779,6780,6783,6784,6785,6786,6787,6788,6789,6790,6791,6792,6793,6800,6801,6802,6803,6804,6805,6806,6807,6808,6809,6832,6833,6834,6835,6836,6837,6838,6839,6840,6841,6842,6843,6844,6845,6912,6913,6914,6915,6916,6964,6965,6966,6967,6968,6969,6970,6971,6972,6973,6974,6975,6976,6977,6978,6979,6980,6992,6993,6994,6995,6996,6997,6998,6999,7000,7001,7019,7020,7021,7022,7023,7024,7025,7026,7027,7040,7041,7042,7073,7074,7075,7076,7077,7078,7079,7080,7081,7082,7083,7084,7085,7088,7089,7090,7091,7092,7093,7094,7095,7096,7097,7142,7143,7144,7145,7146,7147,7148,7149,7150,7151,7152,7153,7154,7155,7204,7205,7206,7207,7208,7209,7210,7211,7212,7213,7214,7215,7216,7217,7218,7219,7220,7221,7222,7223,7232,7233,7234,7235,7236,7237,7238,7239,7240,7241,7248,7249,7250,7251,7252,7253,7254,7255,7256,7257,7376,7377,7378,7380,7381,7382,7383,7384,7385,7386,7387,7388,7389,7390,7391,7392,7393,7394,7395,7396,7397,7398,7399,7400,7405,7410,7411,7412,7415,7416,7417,7616,7617,7618,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628,7629,7630,7631,7632,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643,7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659,7660,7661,7662,7663,7664,7665,7666,7667,7668,7669,7670,7671,7672,7673,7675,7676,7677,7678,7679,8204,8205,8255,8256,8276,8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,8411,8412,8417,8421,8422,8423,8424,8425,8426,8427,8428,8429,8430,8431,8432,11503,11504,11505,11647,11744,11745,11746,11747,11748,11749,11750,11751,11752,11753,11754,11755,11756,11757,11758,11759,11760,11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,12330,12331,12332,12333,12334,12335,12441,12442,42528,42529,42530,42531,42532,42533,42534,42535,42536,42537,42607,42612,42613,42614,42615,42616,42617,42618,42619,42620,42621,42654,42655,42736,42737,43010,43014,43019,43043,43044,43045,43046,43047,43136,43137,43188,43189,43190,43191,43192,43193,43194,43195,43196,43197,43198,43199,43200,43201,43202,43203,43204,43205,43216,43217,43218,43219,43220,43221,43222,43223,43224,43225,43232,43233,43234,43235,43236,43237,43238,43239,43240,43241,43242,43243,43244,43245,43246,43247,43248,43249,43263,43264,43265,43266,43267,43268,43269,43270,43271,43272,43273,43302,43303,43304,43305,43306,43307,43308,43309,43335,43336,43337,43338,43339,43340,43341,43342,43343,43344,43345,43346,43347,43392,43393,43394,43395,43443,43444,43445,43446,43447,43448,43449,43450,43451,43452,43453,43454,43455,43456,43472,43473,43474,43475,43476,43477,43478,43479,43480,43481,43493,43504,43505,43506,43507,43508,43509,43510,43511,43512,43513,43561,43562,43563,43564,43565,43566,43567,43568,43569,43570,43571,43572,43573,43574,43587,43596,43597,43600,43601,43602,43603,43604,43605,43606,43607,43608,43609,43643,43644,43645,43696,43698,43699,43700,43703,43704,43710,43711,43713,43755,43756,43757,43758,43759,43765,43766,44003,44004,44005,44006,44007,44008,44009,44010,44012,44013,44016,44017,44018,44019,44020,44021,44022,44023,44024,44025,64286,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65056,65057,65058,65059,65060,65061,65062,65063,65064,65065,65066,65067,65068,65069,65070,65071,65075,65076,65101,65102,65103,65296,65297,65298,65299,65300,65301,65302,65303,65304,65305,65343';\nvar arr = str.split(',').map(function(code) {\n  return parseInt(code, 10);\n});\nmodule.exports = arr;\n},{}],4:[function(require,module,exports){\nvar str = '170,181,186,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,710,711,712,713,714,715,716,717,718,719,720,721,736,737,738,739,740,748,750,880,881,882,883,884,886,887,890,891,892,893,895,902,904,905,906,908,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257,1258,1259,1260,1261,1262,1263,1264,1265,1266,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279,1280,1281,1282,1283,1284,1285,1286,1287,1288,1289,1290,1291,1292,1293,1294,1295,1296,1297,1298,1299,1300,1301,1302,1303,1304,1305,1306,1307,1308,1309,1310,1311,1312,1313,1314,1315,1316,1317,1318,1319,1320,1321,1322,1323,1324,1325,1326,1327,1329,1330,1331,1332,1333,1334,1335,1336,1337,1338,1339,1340,1341,1342,1343,1344,1345,1346,1347,1348,1349,1350,1351,1352,1353,1354,1355,1356,1357,1358,1359,1360,1361,1362,1363,1364,1365,1366,1369,1376,1377,1378,1379,1380,1381,1382,1383,1384,1385,1386,1387,1388,1389,1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1403,1404,1405,1406,1407,1408,1409,1410,1411,1412,1413,1414,1415,1416,1488,1489,1490,1491,1492,1493,1494,1495,1496,1497,1498,1499,1500,1501,1502,1503,1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,1519,1520,1521,1522,1568,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,1591,1592,1593,1594,1595,1596,1597,1598,1599,1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1646,1647,1649,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659,1660,1661,1662,1663,1664,1665,1666,1667,1668,1669,1670,1671,1672,1673,1674,1675,1676,1677,1678,1679,1680,1681,1682,1683,1684,1685,1686,1687,1688,1689,1690,1691,1692,1693,1694,1695,1696,1697,1698,1699,1700,1701,1702,1703,1704,1705,1706,1707,1708,1709,1710,1711,1712,1713,1714,1715,1716,1717,1718,1719,1720,1721,1722,1723,1724,1725,1726,1727,1728,1729,1730,1731,1732,1733,1734,1735,1736,1737,1738,1739,1740,1741,1742,1743,1744,1745,1746,1747,1749,1765,1766,1774,1775,1786,1787,1788,1791,1808,1810,1811,1812,1813,1814,1815,1816,1817,1818,1819,1820,1821,1822,1823,1824,1825,1826,1827,1828,1829,1830,1831,1832,1833,1834,1835,1836,1837,1838,1839,1869,1870,1871,1872,1873,1874,1875,1876,1877,1878,1879,1880,1881,1882,1883,1884,1885,1886,1887,1888,1889,1890,1891,1892,1893,1894,1895,1896,1897,1898,1899,1900,1901,1902,1903,1904,1905,1906,1907,1908,1909,1910,1911,1912,1913,1914,1915,1916,1917,1918,1919,1920,1921,1922,1923,1924,1925,1926,1927,1928,1929,1930,1931,1932,1933,1934,1935,1936,1937,1938,1939,1940,1941,1942,1943,1944,1945,1946,1947,1948,1949,1950,1951,1952,1953,1954,1955,1956,1957,1969,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025,2026,2036,2037,2042,2048,2049,2050,2051,2052,2053,2054,2055,2056,2057,2058,2059,2060,2061,2062,2063,2064,2065,2066,2067,2068,2069,2074,2084,2088,2112,2113,2114,2115,2116,2117,2118,2119,2120,2121,2122,2123,2124,2125,2126,2127,2128,2129,2130,2131,2132,2133,2134,2135,2136,2144,2145,2146,2147,2148,2149,2150,2151,2152,2153,2154,2208,2209,2210,2211,2212,2213,2214,2215,2216,2217,2218,2219,2220,2221,2222,2223,2224,2225,2226,2227,2228,2230,2231,2232,2233,2234,2235,2236,2237,2308,2309,2310,2311,2312,2313,2314,2315,2316,2317,2318,2319,2320,2321,2322,2323,2324,2325,2326,2327,2328,2329,2330,2331,2332,2333,2334,2335,2336,2337,2338,2339,2340,2341,2342,2343,2344,2345,2346,2347,2348,2349,2350,2351,2352,2353,2354,2355,2356,2357,2358,2359,2360,2361,2365,2384,2392,2393,2394,2395,2396,2397,2398,2399,2400,2401,2417,2418,2419,2420,2421,2422,2423,2424,2425,2426,2427,2428,2429,2430,2431,2432,2437,2438,2439,2440,2441,2442,2443,2444,2447,2448,2451,2452,2453,2454,2455,2456,2457,2458,2459,2460,2461,2462,2463,2464,2465,2466,2467,2468,2469,2470,2471,2472,2474,2475,2476,2477,2478,2479,2480,2482,2486,2487,2488,2489,2493,2510,2524,2525,2527,2528,2529,2544,2545,2556,2565,2566,2567,2568,2569,2570,2575,2576,2579,2580,2581,2582,2583,2584,2585,2586,2587,2588,2589,2590,2591,2592,2593,2594,2595,2596,2597,2598,2599,2600,2602,2603,2604,2605,2606,2607,2608,2610,2611,2613,2614,2616,2617,2649,2650,2651,2652,2654,2674,2675,2676,2693,2694,2695,2696,2697,2698,2699,2700,2701,2703,2704,2705,2707,2708,2709,2710,2711,2712,2713,2714,2715,2716,2717,2718,2719,2720,2721,2722,2723,2724,2725,2726,2727,2728,2730,2731,2732,2733,2734,2735,2736,2738,2739,2741,2742,2743,2744,2745,2749,2768,2784,2785,2809,2821,2822,2823,2824,2825,2826,2827,2828,2831,2832,2835,2836,2837,2838,2839,2840,2841,2842,2843,2844,2845,2846,2847,2848,2849,2850,2851,2852,2853,2854,2855,2856,2858,2859,2860,2861,2862,2863,2864,2866,2867,2869,2870,2871,2872,2873,2877,2908,2909,2911,2912,2913,2929,2947,2949,2950,2951,2952,2953,2954,2958,2959,2960,2962,2963,2964,2965,2969,2970,2972,2974,2975,2979,2980,2984,2985,2986,2990,2991,2992,2993,2994,2995,2996,2997,2998,2999,3000,3001,3024,3077,3078,3079,3080,3081,3082,3083,3084,3086,3087,3088,3090,3091,3092,3093,3094,3095,3096,3097,3098,3099,3100,3101,3102,3103,3104,3105,3106,3107,3108,3109,3110,3111,3112,3114,3115,3116,3117,3118,3119,3120,3121,3122,3123,3124,3125,3126,3127,3128,3129,3133,3160,3161,3162,3168,3169,3200,3205,3206,3207,3208,3209,3210,3211,3212,3214,3215,3216,3218,3219,3220,3221,3222,3223,3224,3225,3226,3227,3228,3229,3230,3231,3232,3233,3234,3235,3236,3237,3238,3239,3240,3242,3243,3244,3245,3246,3247,3248,3249,3250,3251,3253,3254,3255,3256,3257,3261,3294,3296,3297,3313,3314,3333,3334,3335,3336,3337,3338,3339,3340,3342,3343,3344,3346,3347,3348,3349,3350,3351,3352,3353,3354,3355,3356,3357,3358,3359,3360,3361,3362,3363,3364,3365,3366,3367,3368,3369,3370,3371,3372,3373,3374,3375,3376,3377,3378,3379,3380,3381,3382,3383,3384,3385,3386,3389,3406,3412,3413,3414,3423,3424,3425,3450,3451,3452,3453,3454,3455,3461,3462,3463,3464,3465,3466,3467,3468,3469,3470,3471,3472,3473,3474,3475,3476,3477,3478,3482,3483,3484,3485,3486,3487,3488,3489,3490,3491,3492,3493,3494,3495,3496,3497,3498,3499,3500,3501,3502,3503,3504,3505,3507,3508,3509,3510,3511,3512,3513,3514,3515,3517,3520,3521,3522,3523,3524,3525,3526,3585,3586,3587,3588,3589,3590,3591,3592,3593,3594,3595,3596,3597,3598,3599,3600,3601,3602,3603,3604,3605,3606,3607,3608,3609,3610,3611,3612,3613,3614,3615,3616,3617,3618,3619,3620,3621,3622,3623,3624,3625,3626,3627,3628,3629,3630,3631,3632,3634,3635,3648,3649,3650,3651,3652,3653,3654,3713,3714,3716,3719,3720,3722,3725,3732,3733,3734,3735,3737,3738,3739,3740,3741,3742,3743,3745,3746,3747,3749,3751,3754,3755,3757,3758,3759,3760,3762,3763,3773,3776,3777,3778,3779,3780,3782,3804,3805,3806,3807,3840,3904,3905,3906,3907,3908,3909,3910,3911,3913,3914,3915,3916,3917,3918,3919,3920,3921,3922,3923,3924,3925,3926,3927,3928,3929,3930,3931,3932,3933,3934,3935,3936,3937,3938,3939,3940,3941,3942,3943,3944,3945,3946,3947,3948,3976,3977,3978,3979,3980,4096,4097,4098,4099,4100,4101,4102,4103,4104,4105,4106,4107,4108,4109,4110,4111,4112,4113,4114,4115,4116,4117,4118,4119,4120,4121,4122,4123,4124,4125,4126,4127,4128,4129,4130,4131,4132,4133,4134,4135,4136,4137,4138,4159,4176,4177,4178,4179,4180,4181,4186,4187,4188,4189,4193,4197,4198,4206,4207,4208,4213,4214,4215,4216,4217,4218,4219,4220,4221,4222,4223,4224,4225,4238,4256,4257,4258,4259,4260,4261,4262,4263,4264,4265,4266,4267,4268,4269,4270,4271,4272,4273,4274,4275,4276,4277,4278,4279,4280,4281,4282,4283,4284,4285,4286,4287,4288,4289,4290,4291,4292,4293,4295,4301,4304,4305,4306,4307,4308,4309,4310,4311,4312,4313,4314,4315,4316,4317,4318,4319,4320,4321,4322,4323,4324,4325,4326,4327,4328,4329,4330,4331,4332,4333,4334,4335,4336,4337,4338,4339,4340,4341,4342,4343,4344,4345,4346,4348,4349,4350,4351,4352,4353,4354,4355,4356,4357,4358,4359,4360,4361,4362,4363,4364,4365,4366,4367,4368,4369,4370,4371,4372,4373,4374,4375,4376,4377,4378,4379,4380,4381,4382,4383,4384,4385,4386,4387,4388,4389,4390,4391,4392,4393,4394,4395,4396,4397,4398,4399,4400,4401,4402,4403,4404,4405,4406,4407,4408,4409,4410,4411,4412,4413,4414,4415,4416,4417,4418,4419,4420,4421,4422,4423,4424,4425,4426,4427,4428,4429,4430,4431,4432,4433,4434,4435,4436,4437,4438,4439,4440,4441,4442,4443,4444,4445,4446,4447,4448,4449,4450,4451,4452,4453,4454,4455,4456,4457,4458,4459,4460,4461,4462,4463,4464,4465,4466,4467,4468,4469,4470,4471,4472,4473,4474,4475,4476,4477,4478,4479,4480,4481,4482,4483,4484,4485,4486,4487,4488,4489,4490,4491,4492,4493,4494,4495,4496,4497,4498,4499,4500,4501,4502,4503,4504,4505,4506,4507,4508,4509,4510,4511,4512,4513,4514,4515,4516,4517,4518,4519,4520,4521,4522,4523,4524,4525,4526,4527,4528,4529,4530,4531,4532,4533,4534,4535,4536,4537,4538,4539,4540,4541,4542,4543,4544,4545,4546,4547,4548,4549,4550,4551,4552,4553,4554,4555,4556,4557,4558,4559,4560,4561,4562,4563,4564,4565,4566,4567,4568,4569,4570,4571,4572,4573,4574,4575,4576,4577,4578,4579,4580,4581,4582,4583,4584,4585,4586,4587,4588,4589,4590,4591,4592,4593,4594,4595,4596,4597,4598,4599,4600,4601,4602,4603,4604,4605,4606,4607,4608,4609,4610,4611,4612,4613,4614,4615,4616,4617,4618,4619,4620,4621,4622,4623,4624,4625,4626,4627,4628,4629,4630,4631,4632,4633,4634,4635,4636,4637,4638,4639,4640,4641,4642,4643,4644,4645,4646,4647,4648,4649,4650,4651,4652,4653,4654,4655,4656,4657,4658,4659,4660,4661,4662,4663,4664,4665,4666,4667,4668,4669,4670,4671,4672,4673,4674,4675,4676,4677,4678,4679,4680,4682,4683,4684,4685,4688,4689,4690,4691,4692,4693,4694,4696,4698,4699,4700,4701,4704,4705,4706,4707,4708,4709,4710,4711,4712,4713,4714,4715,4716,4717,4718,4719,4720,4721,4722,4723,4724,4725,4726,4727,4728,4729,4730,4731,4732,4733,4734,4735,4736,4737,4738,4739,4740,4741,4742,4743,4744,4746,4747,4748,4749,4752,4753,4754,4755,4756,4757,4758,4759,4760,4761,4762,4763,4764,4765,4766,4767,4768,4769,4770,4771,4772,4773,4774,4775,4776,4777,4778,4779,4780,4781,4782,4783,4784,4786,4787,4788,4789,4792,4793,4794,4795,4796,4797,4798,4800,4802,4803,4804,4805,4808,4809,4810,4811,4812,4813,4814,4815,4816,4817,4818,4819,4820,4821,4822,4824,4825,4826,4827,4828,4829,4830,4831,4832,4833,4834,4835,4836,4837,4838,4839,4840,4841,4842,4843,4844,4845,4846,4847,4848,4849,4850,4851,4852,4853,4854,4855,4856,4857,4858,4859,4860,4861,4862,4863,4864,4865,4866,4867,4868,4869,4870,4871,4872,4873,4874,4875,4876,4877,4878,4879,4880,4882,4883,4884,4885,4888,4889,4890,4891,4892,4893,4894,4895,4896,4897,4898,4899,4900,4901,4902,4903,4904,4905,4906,4907,4908,4909,4910,4911,4912,4913,4914,4915,4916,4917,4918,4919,4920,4921,4922,4923,4924,4925,4926,4927,4928,4929,4930,4931,4932,4933,4934,4935,4936,4937,4938,4939,4940,4941,4942,4943,4944,4945,4946,4947,4948,4949,4950,4951,4952,4953,4954,4992,4993,4994,4995,4996,4997,4998,4999,5000,5001,5002,5003,5004,5005,5006,5007,5024,5025,5026,5027,5028,5029,5030,5031,5032,5033,5034,5035,5036,5037,5038,5039,5040,5041,5042,5043,5044,5045,5046,5047,5048,5049,5050,5051,5052,5053,5054,5055,5056,5057,5058,5059,5060,5061,5062,5063,5064,5065,5066,5067,5068,5069,5070,5071,5072,5073,5074,5075,5076,5077,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087,5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102,5103,5104,5105,5106,5107,5108,5109,5112,5113,5114,5115,5116,5117,5121,5122,5123,5124,5125,5126,5127,5128,5129,5130,5131,5132,5133,5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148,5149,5150,5151,5152,5153,5154,5155,5156,5157,5158,5159,5160,5161,5162,5163,5164,5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,5176,5177,5178,5179,5180,5181,5182,5183,5184,5185,5186,5187,5188,5189,5190,5191,5192,5193,5194,5195,5196,5197,5198,5199,5200,5201,5202,5203,5204,5205,5206,5207,5208,5209,5210,5211,5212,5213,5214,5215,5216,5217,5218,5219,5220,5221,5222,5223,5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234,5235,5236,5237,5238,5239,5240,5241,5242,5243,5244,5245,5246,5247,5248,5249,5250,5251,5252,5253,5254,5255,5256,5257,5258,5259,5260,5261,5262,5263,5264,5265,5266,5267,5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278,5279,5280,5281,5282,5283,5284,5285,5286,5287,5288,5289,5290,5291,5292,5293,5294,5295,5296,5297,5298,5299,5300,5301,5302,5303,5304,5305,5306,5307,5308,5309,5310,5311,5312,5313,5314,5315,5316,5317,5318,5319,5320,5321,5322,5323,5324,5325,5326,5327,5328,5329,5330,5331,5332,5333,5334,5335,5336,5337,5338,5339,5340,5341,5342,5343,5344,5345,5346,5347,5348,5349,5350,5351,5352,5353,5354,5355,5356,5357,5358,5359,5360,5361,5362,5363,5364,5365,5366,5367,5368,5369,5370,5371,5372,5373,5374,5375,5376,5377,5378,5379,5380,5381,5382,5383,5384,5385,5386,5387,5388,5389,5390,5391,5392,5393,5394,5395,5396,5397,5398,5399,5400,5401,5402,5403,5404,5405,5406,5407,5408,5409,5410,5411,5412,5413,5414,5415,5416,5417,5418,5419,5420,5421,5422,5423,5424,5425,5426,5427,5428,5429,5430,5431,5432,5433,5434,5435,5436,5437,5438,5439,5440,5441,5442,5443,5444,5445,5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456,5457,5458,5459,5460,5461,5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472,5473,5474,5475,5476,5477,5478,5479,5480,5481,5482,5483,5484,5485,5486,5487,5488,5489,5490,5491,5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504,5505,5506,5507,5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520,5521,5522,5523,5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536,5537,5538,5539,5540,5541,5542,5543,5544,5545,5546,5547,5548,5549,5550,5551,5552,5553,5554,5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568,5569,5570,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584,5585,5586,5587,5588,5589,5590,5591,5592,5593,5594,5595,5596,5597,5598,5599,5600,5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,5615,5616,5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631,5632,5633,5634,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646,5647,5648,5649,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660,5661,5662,5663,5664,5665,5666,5667,5668,5669,5670,5671,5672,5673,5674,5675,5676,5677,5678,5679,5680,5681,5682,5683,5684,5685,5686,5687,5688,5689,5690,5691,5692,5693,5694,5695,5696,5697,5698,5699,5700,5701,5702,5703,5704,5705,5706,5707,5708,5709,5710,5711,5712,5713,5714,5715,5716,5717,5718,5719,5720,5721,5722,5723,5724,5725,5726,5727,5728,5729,5730,5731,5732,5733,5734,5735,5736,5737,5738,5739,5740,5743,5744,5745,5746,5747,5748,5749,5750,5751,5752,5753,5754,5755,5756,5757,5758,5759,5761,5762,5763,5764,5765,5766,5767,5768,5769,5770,5771,5772,5773,5774,5775,5776,5777,5778,5779,5780,5781,5782,5783,5784,5785,5786,5792,5793,5794,5795,5796,5797,5798,5799,5800,5801,5802,5803,5804,5805,5806,5807,5808,5809,5810,5811,5812,5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828,5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844,5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856,5857,5858,5859,5860,5861,5862,5863,5864,5865,5866,5870,5871,5872,5873,5874,5875,5876,5877,5878,5879,5880,5888,5889,5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5902,5903,5904,5905,5920,5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936,5937,5952,5953,5954,5955,5956,5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968,5969,5984,5985,5986,5987,5988,5989,5990,5991,5992,5993,5994,5995,5996,5998,5999,6000,6016,6017,6018,6019,6020,6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032,6033,6034,6035,6036,6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052,6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6103,6108,6176,6177,6178,6179,6180,6181,6182,6183,6184,6185,6186,6187,6188,6189,6190,6191,6192,6193,6194,6195,6196,6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210,6211,6212,6213,6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,6224,6225,6226,6227,6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241,6242,6243,6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,6254,6255,6256,6257,6258,6259,6260,6261,6262,6263,6264,6272,6273,6274,6275,6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,6286,6287,6288,6289,6290,6291,6292,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,6303,6304,6305,6306,6307,6308,6309,6310,6311,6312,6314,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333,6334,6335,6336,6337,6338,6339,6340,6341,6342,6343,6344,6345,6346,6347,6348,6349,6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363,6364,6365,6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379,6380,6381,6382,6383,6384,6385,6386,6387,6388,6389,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,6411,6412,6413,6414,6415,6416,6417,6418,6419,6420,6421,6422,6423,6424,6425,6426,6427,6428,6429,6430,6480,6481,6482,6483,6484,6485,6486,6487,6488,6489,6490,6491,6492,6493,6494,6495,6496,6497,6498,6499,6500,6501,6502,6503,6504,6505,6506,6507,6508,6509,6512,6513,6514,6515,6516,6528,6529,6530,6531,6532,6533,6534,6535,6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548,6549,6550,6551,6552,6553,6554,6555,6556,6557,6558,6559,6560,6561,6562,6563,6564,6565,6566,6567,6568,6569,6570,6571,6576,6577,6578,6579,6580,6581,6582,6583,6584,6585,6586,6587,6588,6589,6590,6591,6592,6593,6594,6595,6596,6597,6598,6599,6600,6601,6656,6657,6658,6659,6660,6661,6662,6663,6664,6665,6666,6667,6668,6669,6670,6671,6672,6673,6674,6675,6676,6677,6678,6688,6689,6690,6691,6692,6693,6694,6695,6696,6697,6698,6699,6700,6701,6702,6703,6704,6705,6706,6707,6708,6709,6710,6711,6712,6713,6714,6715,6716,6717,6718,6719,6720,6721,6722,6723,6724,6725,6726,6727,6728,6729,6730,6731,6732,6733,6734,6735,6736,6737,6738,6739,6740,6823,6917,6918,6919,6920,6921,6922,6923,6924,6925,6926,6927,6928,6929,6930,6931,6932,6933,6934,6935,6936,6937,6938,6939,6940,6941,6942,6943,6944,6945,6946,6947,6948,6949,6950,6951,6952,6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6981,6982,6983,6984,6985,6986,6987,7043,7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058,7059,7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,7071,7072,7086,7087,7098,7099,7100,7101,7102,7103,7104,7105,7106,7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,7119,7120,7121,7122,7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136,7137,7138,7139,7140,7141,7168,7169,7170,7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183,7184,7185,7186,7187,7188,7189,7190,7191,7192,7193,7194,7195,7196,7197,7198,7199,7200,7201,7202,7203,7245,7246,7247,7258,7259,7260,7261,7262,7263,7264,7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277,7278,7279,7280,7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293,7296,7297,7298,7299,7300,7301,7302,7303,7304,7312,7313,7314,7315,7316,7317,7318,7319,7320,7321,7322,7323,7324,7325,7326,7327,7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339,7340,7341,7342,7343,7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,7354,7357,7358,7359,7401,7402,7403,7404,7406,7407,7408,7409,7413,7414,7424,7425,7426,7427,7428,7429,7430,7431,7432,7433,7434,7435,7436,7437,7438,7439,7440,7441,7442,7443,7444,7445,7446,7447,7448,7449,7450,7451,7452,7453,7454,7455,7456,7457,7458,7459,7460,7461,7462,7463,7464,7465,7466,7467,7468,7469,7470,7471,7472,7473,7474,7475,7476,7477,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487,7488,7489,7490,7491,7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,7503,7504,7505,7506,7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519,7520,7521,7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535,7536,7537,7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,7550,7551,7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567,7568,7569,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582,7583,7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598,7599,7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614,7615,7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690,7691,7692,7693,7694,7695,7696,7697,7698,7699,7700,7701,7702,7703,7704,7705,7706,7707,7708,7709,7710,7711,7712,7713,7714,7715,7716,7717,7718,7719,7720,7721,7722,7723,7724,7725,7726,7727,7728,7729,7730,7731,7732,7733,7734,7735,7736,7737,7738,7739,7740,7741,7742,7743,7744,7745,7746,7747,7748,7749,7750,7751,7752,7753,7754,7755,7756,7757,7758,7759,7760,7761,7762,7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,7777,7778,7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791,7792,7793,7794,7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,7806,7807,7808,7809,7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824,7825,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840,7841,7842,7843,7844,7845,7846,7847,7848,7849,7850,7851,7852,7853,7854,7855,7856,7857,7858,7859,7860,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870,7871,7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886,7887,7888,7889,7890,7891,7892,7893,7894,7895,7896,7897,7898,7899,7900,7901,7902,7903,7904,7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919,7920,7921,7922,7923,7924,7925,7926,7927,7928,7929,7930,7931,7932,7933,7934,7935,7936,7937,7938,7939,7940,7941,7942,7943,7944,7945,7946,7947,7948,7949,7950,7951,7952,7953,7954,7955,7956,7957,7960,7961,7962,7963,7964,7965,7968,7969,7970,7971,7972,7973,7974,7975,7976,7977,7978,7979,7980,7981,7982,7983,7984,7985,7986,7987,7988,7989,7990,7991,7992,7993,7994,7995,7996,7997,7998,7999,8000,8001,8002,8003,8004,8005,8008,8009,8010,8011,8012,8013,8016,8017,8018,8019,8020,8021,8022,8023,8025,8027,8029,8031,8032,8033,8034,8035,8036,8037,8038,8039,8040,8041,8042,8043,8044,8045,8046,8047,8048,8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8064,8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079,8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095,8096,8097,8098,8099,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110,8111,8112,8113,8114,8115,8116,8118,8119,8120,8121,8122,8123,8124,8126,8130,8131,8132,8134,8135,8136,8137,8138,8139,8140,8144,8145,8146,8147,8150,8151,8152,8153,8154,8155,8160,8161,8162,8163,8164,8165,8166,8167,8168,8169,8170,8171,8172,8178,8179,8180,8182,8183,8184,8185,8186,8187,8188,8305,8319,8336,8337,8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8450,8455,8458,8459,8460,8461,8462,8463,8464,8465,8466,8467,8469,8472,8473,8474,8475,8476,8477,8484,8486,8488,8490,8491,8492,8493,8494,8495,8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8508,8509,8510,8511,8517,8518,8519,8520,8521,8526,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554,8555,8556,8557,8558,8559,8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,8570,8571,8572,8573,8574,8575,8576,8577,8578,8579,8580,8581,8582,8583,8584,11264,11265,11266,11267,11268,11269,11270,11271,11272,11273,11274,11275,11276,11277,11278,11279,11280,11281,11282,11283,11284,11285,11286,11287,11288,11289,11290,11291,11292,11293,11294,11295,11296,11297,11298,11299,11300,11301,11302,11303,11304,11305,11306,11307,11308,11309,11310,11312,11313,11314,11315,11316,11317,11318,11319,11320,11321,11322,11323,11324,11325,11326,11327,11328,11329,11330,11331,11332,11333,11334,11335,11336,11337,11338,11339,11340,11341,11342,11343,11344,11345,11346,11347,11348,11349,11350,11351,11352,11353,11354,11355,11356,11357,11358,11360,11361,11362,11363,11364,11365,11366,11367,11368,11369,11370,11371,11372,11373,11374,11375,11376,11377,11378,11379,11380,11381,11382,11383,11384,11385,11386,11387,11388,11389,11390,11391,11392,11393,11394,11395,11396,11397,11398,11399,11400,11401,11402,11403,11404,11405,11406,11407,11408,11409,11410,11411,11412,11413,11414,11415,11416,11417,11418,11419,11420,11421,11422,11423,11424,11425,11426,11427,11428,11429,11430,11431,11432,11433,11434,11435,11436,11437,11438,11439,11440,11441,11442,11443,11444,11445,11446,11447,11448,11449,11450,11451,11452,11453,11454,11455,11456,11457,11458,11459,11460,11461,11462,11463,11464,11465,11466,11467,11468,11469,11470,11471,11472,11473,11474,11475,11476,11477,11478,11479,11480,11481,11482,11483,11484,11485,11486,11487,11488,11489,11490,11491,11492,11499,11500,11501,11502,11506,11507,11520,11521,11522,11523,11524,11525,11526,11527,11528,11529,11530,11531,11532,11533,11534,11535,11536,11537,11538,11539,11540,11541,11542,11543,11544,11545,11546,11547,11548,11549,11550,11551,11552,11553,11554,11555,11556,11557,11559,11565,11568,11569,11570,11571,11572,11573,11574,11575,11576,11577,11578,11579,11580,11581,11582,11583,11584,11585,11586,11587,11588,11589,11590,11591,11592,11593,11594,11595,11596,11597,11598,11599,11600,11601,11602,11603,11604,11605,11606,11607,11608,11609,11610,11611,11612,11613,11614,11615,11616,11617,11618,11619,11620,11621,11622,11623,11631,11648,11649,11650,11651,11652,11653,11654,11655,11656,11657,11658,11659,11660,11661,11662,11663,11664,11665,11666,11667,11668,11669,11670,11680,11681,11682,11683,11684,11685,11686,11688,11689,11690,11691,11692,11693,11694,11696,11697,11698,11699,11700,11701,11702,11704,11705,11706,11707,11708,11709,11710,11712,11713,11714,11715,11716,11717,11718,11720,11721,11722,11723,11724,11725,11726,11728,11729,11730,11731,11732,11733,11734,11736,11737,11738,11739,11740,11741,11742,12293,12294,12295,12321,12322,12323,12324,12325,12326,12327,12328,12329,12337,12338,12339,12340,12341,12344,12345,12346,12347,12348,12353,12354,12355,12356,12357,12358,12359,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369,12370,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384,12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400,12401,12402,12403,12404,12405,12406,12407,12408,12409,12410,12411,12412,12413,12414,12415,12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431,12432,12433,12434,12435,12436,12437,12438,12443,12444,12445,12446,12447,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462,12463,12464,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477,12478,12479,12480,12481,12482,12483,12484,12485,12486,12487,12488,12489,12490,12491,12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507,12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523,12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,12535,12536,12537,12538,12540,12541,12542,12543,12549,12550,12551,12552,12553,12554,12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570,12571,12572,12573,12574,12575,12576,12577,12578,12579,12580,12581,12582,12583,12584,12585,12586,12587,12588,12589,12590,12591,12593,12594,12595,12596,12597,12598,12599,12600,12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616,12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632,12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,12647,12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663,12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679,12680,12681,12682,12683,12684,12685,12686,12704,12705,12706,12707,12708,12709,12710,12711,12712,12713,12714,12715,12716,12717,12718,12719,12720,12721,12722,12723,12724,12725,12726,12727,12728,12729,12730,12784,12785,12786,12787,12788,12789,12790,12791,12792,12793,12794,12795,12796,12797,12798,12799,13312,13313,13314,13315,13316,13317,13318,13319,13320,13321,13322,13323,13324,13325,13326,13327,13328,13329,13330,13331,13332,13333,13334,13335,13336,13337,13338,13339,13340,13341,13342,13343,13344,13345,13346,13347,13348,13349,13350,13351,13352,13353,13354,13355,13356,13357,13358,13359,13360,13361,13362,13363,13364,13365,13366,13367,13368,13369,13370,13371,13372,13373,13374,13375,13376,13377,13378,13379,13380,13381,13382,13383,13384,13385,13386,13387,13388,13389,13390,13391,13392,13393,13394,13395,13396,13397,13398,13399,13400,13401,13402,13403,13404,13405,13406,13407,13408,13409,13410,13411,13412,13413,13414,13415,13416,13417,13418,13419,13420,13421,13422,13423,13424,13425,13426,13427,13428,13429,13430,13431,13432,13433,13434,13435,13436,13437,13438,13439,13440,13441,13442,13443,13444,13445,13446,13447,13448,13449,13450,13451,13452,13453,13454,13455,13456,13457,13458,13459,13460,13461,13462,13463,13464,13465,13466,13467,13468,13469,13470,13471,13472,13473,13474,13475,13476,13477,13478,13479,13480,13481,13482,13483,13484,13485,13486,13487,13488,13489,13490,13491,13492,13493,13494,13495,13496,13497,13498,13499,13500,13501,13502,13503,13504,13505,13506,13507,13508,13509,13510,13511,13512,13513,13514,13515,13516,13517,13518,13519,13520,13521,13522,13523,13524,13525,13526,13527,13528,13529,13530,13531,13532,13533,13534,13535,13536,13537,13538,13539,13540,13541,13542,13543,13544,13545,13546,13547,13548,13549,13550,13551,13552,13553,13554,13555,13556,13557,13558,13559,13560,13561,13562,13563,13564,13565,13566,13567,13568,13569,13570,13571,13572,13573,13574,13575,13576,13577,13578,13579,13580,13581,13582,13583,13584,13585,13586,13587,13588,13589,13590,13591,13592,13593,13594,13595,13596,13597,13598,13599,13600,13601,13602,13603,13604,13605,13606,13607,13608,13609,13610,13611,13612,13613,13614,13615,13616,13617,13618,13619,13620,13621,13622,13623,13624,13625,13626,13627,13628,13629,13630,13631,13632,13633,13634,13635,13636,13637,13638,13639,13640,13641,13642,13643,13644,13645,13646,13647,13648,13649,13650,13651,13652,13653,13654,13655,13656,13657,13658,13659,13660,13661,13662,13663,13664,13665,13666,13667,13668,13669,13670,13671,13672,13673,13674,13675,13676,13677,13678,13679,13680,13681,13682,13683,13684,13685,13686,13687,13688,13689,13690,13691,13692,13693,13694,13695,13696,13697,13698,13699,13700,13701,13702,13703,13704,13705,13706,13707,13708,13709,13710,13711,13712,13713,13714,13715,13716,13717,13718,13719,13720,13721,13722,13723,13724,13725,13726,13727,13728,13729,13730,13731,13732,13733,13734,13735,13736,13737,13738,13739,13740,13741,13742,13743,13744,13745,13746,13747,13748,13749,13750,13751,13752,13753,13754,13755,13756,13757,13758,13759,13760,13761,13762,13763,13764,13765,13766,13767,13768,13769,13770,13771,13772,13773,13774,13775,13776,13777,13778,13779,13780,13781,13782,13783,13784,13785,13786,13787,13788,13789,13790,13791,13792,13793,13794,13795,13796,13797,13798,13799,13800,13801,13802,13803,13804,13805,13806,13807,13808,13809,13810,13811,13812,13813,13814,13815,13816,13817,13818,13819,13820,13821,13822,13823,13824,13825,13826,13827,13828,13829,13830,13831,13832,13833,13834,13835,13836,13837,13838,13839,13840,13841,13842,13843,13844,13845,13846,13847,13848,13849,13850,13851,13852,13853,13854,13855,13856,13857,13858,13859,13860,13861,13862,13863,13864,13865,13866,13867,13868,13869,13870,13871,13872,13873,13874,13875,13876,13877,13878,13879,13880,13881,13882,13883,13884,13885,13886,13887,13888,13889,13890,13891,13892,13893,13894,13895,13896,13897,13898,13899,13900,13901,13902,13903,13904,13905,13906,13907,13908,13909,13910,13911,13912,13913,13914,13915,13916,13917,13918,13919,13920,13921,13922,13923,13924,13925,13926,13927,13928,13929,13930,13931,13932,13933,13934,13935,13936,13937,13938,13939,13940,13941,13942,13943,13944,13945,13946,13947,13948,13949,13950,13951,13952,13953,13954,13955,13956,13957,13958,13959,13960,13961,13962,13963,13964,13965,13966,13967,13968,13969,13970,13971,13972,13973,13974,13975,13976,13977,13978,13979,13980,13981,13982,13983,13984,13985,13986,13987,13988,13989,13990,13991,13992,13993,13994,13995,13996,13997,13998,13999,14000,14001,14002,14003,14004,14005,14006,14007,14008,14009,14010,14011,14012,14013,14014,14015,14016,14017,14018,14019,14020,14021,14022,14023,14024,14025,14026,14027,14028,14029,14030,14031,14032,14033,14034,14035,14036,14037,14038,14039,14040,14041,14042,14043,14044,14045,14046,14047,14048,14049,14050,14051,14052,14053,14054,14055,14056,14057,14058,14059,14060,14061,14062,14063,14064,14065,14066,14067,14068,14069,14070,14071,14072,14073,14074,14075,14076,14077,14078,14079,14080,14081,14082,14083,14084,14085,14086,14087,14088,14089,14090,14091,14092,14093,14094,14095,14096,14097,14098,14099,14100,14101,14102,14103,14104,14105,14106,14107,14108,14109,14110,14111,14112,14113,14114,14115,14116,14117,14118,14119,14120,14121,14122,14123,14124,14125,14126,14127,14128,14129,14130,14131,14132,14133,14134,14135,14136,14137,14138,14139,14140,14141,14142,14143,14144,14145,14146,14147,14148,14149,14150,14151,14152,14153,14154,14155,14156,14157,14158,14159,14160,14161,14162,14163,14164,14165,14166,14167,14168,14169,14170,14171,14172,14173,14174,14175,14176,14177,14178,14179,14180,14181,14182,14183,14184,14185,14186,14187,14188,14189,14190,14191,14192,14193,14194,14195,14196,14197,14198,14199,14200,14201,14202,14203,14204,14205,14206,14207,14208,14209,14210,14211,14212,14213,14214,14215,14216,14217,14218,14219,14220,14221,14222,14223,14224,14225,14226,14227,14228,14229,14230,14231,14232,14233,14234,14235,14236,14237,14238,14239,14240,14241,14242,14243,14244,14245,14246,14247,14248,14249,14250,14251,14252,14253,14254,14255,14256,14257,14258,14259,14260,14261,14262,14263,14264,14265,14266,14267,14268,14269,14270,14271,14272,14273,14274,14275,14276,14277,14278,14279,14280,14281,14282,14283,14284,14285,14286,14287,14288,14289,14290,14291,14292,14293,14294,14295,14296,14297,14298,14299,14300,14301,14302,14303,14304,14305,14306,14307,14308,14309,14310,14311,14312,14313,14314,14315,14316,14317,14318,14319,14320,14321,14322,14323,14324,14325,14326,14327,14328,14329,14330,14331,14332,14333,14334,14335,14336,14337,14338,14339,14340,14341,14342,14343,14344,14345,14346,14347,14348,14349,14350,14351,14352,14353,14354,14355,14356,14357,14358,14359,14360,14361,14362,14363,14364,14365,14366,14367,14368,14369,14370,14371,14372,14373,14374,14375,14376,14377,14378,14379,14380,14381,14382,14383,14384,14385,14386,14387,14388,14389,14390,14391,14392,14393,14394,14395,14396,14397,14398,14399,14400,14401,14402,14403,14404,14405,14406,14407,14408,14409,14410,14411,14412,14413,14414,14415,14416,14417,14418,14419,14420,14421,14422,14423,14424,14425,14426,14427,14428,14429,14430,14431,14432,14433,14434,14435,14436,14437,14438,14439,14440,14441,14442,14443,14444,14445,14446,14447,14448,14449,14450,14451,14452,14453,14454,14455,14456,14457,14458,14459,14460,14461,14462,14463,14464,14465,14466,14467,14468,14469,14470,14471,14472,14473,14474,14475,14476,14477,14478,14479,14480,14481,14482,14483,14484,14485,14486,14487,14488,14489,14490,14491,14492,14493,14494,14495,14496,14497,14498,14499,14500,14501,14502,14503,14504,14505,14506,14507,14508,14509,14510,14511,14512,14513,14514,14515,14516,14517,14518,14519,14520,14521,14522,14523,14524,14525,14526,14527,14528,14529,14530,14531,14532,14533,14534,14535,14536,14537,14538,14539,14540,14541,14542,14543,14544,14545,14546,14547,14548,14549,14550,14551,14552,14553,14554,14555,14556,14557,14558,14559,14560,14561,14562,14563,14564,14565,14566,14567,14568,14569,14570,14571,14572,14573,14574,14575,14576,14577,14578,14579,14580,14581,14582,14583,14584,14585,14586,14587,14588,14589,14590,14591,14592,14593,14594,14595,14596,14597,14598,14599,14600,14601,14602,14603,14604,14605,14606,14607,14608,14609,14610,14611,14612,14613,14614,14615,14616,14617,14618,14619,14620,14621,14622,14623,14624,14625,14626,14627,14628,14629,14630,14631,14632,14633,14634,14635,14636,14637,14638,14639,14640,14641,14642,14643,14644,14645,14646,14647,14648,14649,14650,14651,14652,14653,14654,14655,14656,14657,14658,14659,14660,14661,14662,14663,14664,14665,14666,14667,14668,14669,14670,14671,14672,14673,14674,14675,14676,14677,14678,14679,14680,14681,14682,14683,14684,14685,14686,14687,14688,14689,14690,14691,14692,14693,14694,14695,14696,14697,14698,14699,14700,14701,14702,14703,14704,14705,14706,14707,14708,14709,14710,14711,14712,14713,14714,14715,14716,14717,14718,14719,14720,14721,14722,14723,14724,14725,14726,14727,14728,14729,14730,14731,14732,14733,14734,14735,14736,14737,14738,14739,14740,14741,14742,14743,14744,14745,14746,14747,14748,14749,14750,14751,14752,14753,14754,14755,14756,14757,14758,14759,14760,14761,14762,14763,14764,14765,14766,14767,14768,14769,14770,14771,14772,14773,14774,14775,14776,14777,14778,14779,14780,14781,14782,14783,14784,14785,14786,14787,14788,14789,14790,14791,14792,14793,14794,14795,14796,14797,14798,14799,14800,14801,14802,14803,14804,14805,14806,14807,14808,14809,14810,14811,14812,14813,14814,14815,14816,14817,14818,14819,14820,14821,14822,14823,14824,14825,14826,14827,14828,14829,14830,14831,14832,14833,14834,14835,14836,14837,14838,14839,14840,14841,14842,14843,14844,14845,14846,14847,14848,14849,14850,14851,14852,14853,14854,14855,14856,14857,14858,14859,14860,14861,14862,14863,14864,14865,14866,14867,14868,14869,14870,14871,14872,14873,14874,14875,14876,14877,14878,14879,14880,14881,14882,14883,14884,14885,14886,14887,14888,14889,14890,14891,14892,14893,14894,14895,14896,14897,14898,14899,14900,14901,14902,14903,14904,14905,14906,14907,14908,14909,14910,14911,14912,14913,14914,14915,14916,14917,14918,14919,14920,14921,14922,14923,14924,14925,14926,14927,14928,14929,14930,14931,14932,14933,14934,14935,14936,14937,14938,14939,14940,14941,14942,14943,14944,14945,14946,14947,14948,14949,14950,14951,14952,14953,14954,14955,14956,14957,14958,14959,14960,14961,14962,14963,14964,14965,14966,14967,14968,14969,14970,14971,14972,14973,14974,14975,14976,14977,14978,14979,14980,14981,14982,14983,14984,14985,14986,14987,14988,14989,14990,14991,14992,14993,14994,14995,14996,14997,14998,14999,15000,15001,15002,15003,15004,15005,15006,15007,15008,15009,15010,15011,15012,15013,15014,15015,15016,15017,15018,15019,15020,15021,15022,15023,15024,15025,15026,15027,15028,15029,15030,15031,15032,15033,15034,15035,15036,15037,15038,15039,15040,15041,15042,15043,15044,15045,15046,15047,15048,15049,15050,15051,15052,15053,15054,15055,15056,15057,15058,15059,15060,15061,15062,15063,15064,15065,15066,15067,15068,15069,15070,15071,15072,15073,15074,15075,15076,15077,15078,15079,15080,15081,15082,15083,15084,15085,15086,15087,15088,15089,15090,15091,15092,15093,15094,15095,15096,15097,15098,15099,15100,15101,15102,15103,15104,15105,15106,15107,15108,15109,15110,15111,15112,15113,15114,15115,15116,15117,15118,15119,15120,15121,15122,15123,15124,15125,15126,15127,15128,15129,15130,15131,15132,15133,15134,15135,15136,15137,15138,15139,15140,15141,15142,15143,15144,15145,15146,15147,15148,15149,15150,15151,15152,15153,15154,15155,15156,15157,15158,15159,15160,15161,15162,15163,15164,15165,15166,15167,15168,15169,15170,15171,15172,15173,15174,15175,15176,15177,15178,15179,15180,15181,15182,15183,15184,15185,15186,15187,15188,15189,15190,15191,15192,15193,15194,15195,15196,15197,15198,15199,15200,15201,15202,15203,15204,15205,15206,15207,15208,15209,15210,15211,15212,15213,15214,15215,15216,15217,15218,15219,15220,15221,15222,15223,15224,15225,15226,15227,15228,15229,15230,15231,15232,15233,15234,15235,15236,15237,15238,15239,15240,15241,15242,15243,15244,15245,15246,15247,15248,15249,15250,15251,15252,15253,15254,15255,15256,15257,15258,15259,15260,15261,15262,15263,15264,15265,15266,15267,15268,15269,15270,15271,15272,15273,15274,15275,15276,15277,15278,15279,15280,15281,15282,15283,15284,15285,15286,15287,15288,15289,15290,15291,15292,15293,15294,15295,15296,15297,15298,15299,15300,15301,15302,15303,15304,15305,15306,15307,15308,15309,15310,15311,15312,15313,15314,15315,15316,15317,15318,15319,15320,15321,15322,15323,15324,15325,15326,15327,15328,15329,15330,15331,15332,15333,15334,15335,15336,15337,15338,15339,15340,15341,15342,15343,15344,15345,15346,15347,15348,15349,15350,15351,15352,15353,15354,15355,15356,15357,15358,15359,15360,15361,15362,15363,15364,15365,15366,15367,15368,15369,15370,15371,15372,15373,15374,15375,15376,15377,15378,15379,15380,15381,15382,15383,15384,15385,15386,15387,15388,15389,15390,15391,15392,15393,15394,15395,15396,15397,15398,15399,15400,15401,15402,15403,15404,15405,15406,15407,15408,15409,15410,15411,15412,15413,15414,15415,15416,15417,15418,15419,15420,15421,15422,15423,15424,15425,15426,15427,15428,15429,15430,15431,15432,15433,15434,15435,15436,15437,15438,15439,15440,15441,15442,15443,15444,15445,15446,15447,15448,15449,15450,15451,15452,15453,15454,15455,15456,15457,15458,15459,15460,15461,15462,15463,15464,15465,15466,15467,15468,15469,15470,15471,15472,15473,15474,15475,15476,15477,15478,15479,15480,15481,15482,15483,15484,15485,15486,15487,15488,15489,15490,15491,15492,15493,15494,15495,15496,15497,15498,15499,15500,15501,15502,15503,15504,15505,15506,15507,15508,15509,15510,15511,15512,15513,15514,15515,15516,15517,15518,15519,15520,15521,15522,15523,15524,15525,15526,15527,15528,15529,15530,15531,15532,15533,15534,15535,15536,15537,15538,15539,15540,15541,15542,15543,15544,15545,15546,15547,15548,15549,15550,15551,15552,15553,15554,15555,15556,15557,15558,15559,15560,15561,15562,15563,15564,15565,15566,15567,15568,15569,15570,15571,15572,15573,15574,15575,15576,15577,15578,15579,15580,15581,15582,15583,15584,15585,15586,15587,15588,15589,15590,15591,15592,15593,15594,15595,15596,15597,15598,15599,15600,15601,15602,15603,15604,15605,15606,15607,15608,15609,15610,15611,15612,15613,15614,15615,15616,15617,15618,15619,15620,15621,15622,15623,15624,15625,15626,15627,15628,15629,15630,15631,15632,15633,15634,15635,15636,15637,15638,15639,15640,15641,15642,15643,15644,15645,15646,15647,15648,15649,15650,15651,15652,15653,15654,15655,15656,15657,15658,15659,15660,15661,15662,15663,15664,15665,15666,15667,15668,15669,15670,15671,15672,15673,15674,15675,15676,15677,15678,15679,15680,15681,15682,15683,15684,15685,15686,15687,15688,15689,15690,15691,15692,15693,15694,15695,15696,15697,15698,15699,15700,15701,15702,15703,15704,15705,15706,15707,15708,15709,15710,15711,15712,15713,15714,15715,15716,15717,15718,15719,15720,15721,15722,15723,15724,15725,15726,15727,15728,15729,15730,15731,15732,15733,15734,15735,15736,15737,15738,15739,15740,15741,15742,15743,15744,15745,15746,15747,15748,15749,15750,15751,15752,15753,15754,15755,15756,15757,15758,15759,15760,15761,15762,15763,15764,15765,15766,15767,15768,15769,15770,15771,15772,15773,15774,15775,15776,15777,15778,15779,15780,15781,15782,15783,15784,15785,15786,15787,15788,15789,15790,15791,15792,15793,15794,15795,15796,15797,15798,15799,15800,15801,15802,15803,15804,15805,15806,15807,15808,15809,15810,15811,15812,15813,15814,15815,15816,15817,15818,15819,15820,15821,15822,15823,15824,15825,15826,15827,15828,15829,15830,15831,15832,15833,15834,15835,15836,15837,15838,15839,15840,15841,15842,15843,15844,15845,15846,15847,15848,15849,15850,15851,15852,15853,15854,15855,15856,15857,15858,15859,15860,15861,15862,15863,15864,15865,15866,15867,15868,15869,15870,15871,15872,15873,15874,15875,15876,15877,15878,15879,15880,15881,15882,15883,15884,15885,15886,15887,15888,15889,15890,15891,15892,15893,15894,15895,15896,15897,15898,15899,15900,15901,15902,15903,15904,15905,15906,15907,15908,15909,15910,15911,15912,15913,15914,15915,15916,15917,15918,15919,15920,15921,15922,15923,15924,15925,15926,15927,15928,15929,15930,15931,15932,15933,15934,15935,15936,15937,15938,15939,15940,15941,15942,15943,15944,15945,15946,15947,15948,15949,15950,15951,15952,15953,15954,15955,15956,15957,15958,15959,15960,15961,15962,15963,15964,15965,15966,15967,15968,15969,15970,15971,15972,15973,15974,15975,15976,15977,15978,15979,15980,15981,15982,15983,15984,15985,15986,15987,15988,15989,15990,15991,15992,15993,15994,15995,15996,15997,15998,15999,16000,16001,16002,16003,16004,16005,16006,16007,16008,16009,16010,16011,16012,16013,16014,16015,16016,16017,16018,16019,16020,16021,16022,16023,16024,16025,16026,16027,16028,16029,16030,16031,16032,16033,16034,16035,16036,16037,16038,16039,16040,16041,16042,16043,16044,16045,16046,16047,16048,16049,16050,16051,16052,16053,16054,16055,16056,16057,16058,16059,16060,16061,16062,16063,16064,16065,16066,16067,16068,16069,16070,16071,16072,16073,16074,16075,16076,16077,16078,16079,16080,16081,16082,16083,16084,16085,16086,16087,16088,16089,16090,16091,16092,16093,16094,16095,16096,16097,16098,16099,16100,16101,16102,16103,16104,16105,16106,16107,16108,16109,16110,16111,16112,16113,16114,16115,16116,16117,16118,16119,16120,16121,16122,16123,16124,16125,16126,16127,16128,16129,16130,16131,16132,16133,16134,16135,16136,16137,16138,16139,16140,16141,16142,16143,16144,16145,16146,16147,16148,16149,16150,16151,16152,16153,16154,16155,16156,16157,16158,16159,16160,16161,16162,16163,16164,16165,16166,16167,16168,16169,16170,16171,16172,16173,16174,16175,16176,16177,16178,16179,16180,16181,16182,16183,16184,16185,16186,16187,16188,16189,16190,16191,16192,16193,16194,16195,16196,16197,16198,16199,16200,16201,16202,16203,16204,16205,16206,16207,16208,16209,16210,16211,16212,16213,16214,16215,16216,16217,16218,16219,16220,16221,16222,16223,16224,16225,16226,16227,16228,16229,16230,16231,16232,16233,16234,16235,16236,16237,16238,16239,16240,16241,16242,16243,16244,16245,16246,16247,16248,16249,16250,16251,16252,16253,16254,16255,16256,16257,16258,16259,16260,16261,16262,16263,16264,16265,16266,16267,16268,16269,16270,16271,16272,16273,16274,16275,16276,16277,16278,16279,16280,16281,16282,16283,16284,16285,16286,16287,16288,16289,16290,16291,16292,16293,16294,16295,16296,16297,16298,16299,16300,16301,16302,16303,16304,16305,16306,16307,16308,16309,16310,16311,16312,16313,16314,16315,16316,16317,16318,16319,16320,16321,16322,16323,16324,16325,16326,16327,16328,16329,16330,16331,16332,16333,16334,16335,16336,16337,16338,16339,16340,16341,16342,16343,16344,16345,16346,16347,16348,16349,16350,16351,16352,16353,16354,16355,16356,16357,16358,16359,16360,16361,16362,16363,16364,16365,16366,16367,16368,16369,16370,16371,16372,16373,16374,16375,16376,16377,16378,16379,16380,16381,16382,16383,16384,16385,16386,16387,16388,16389,16390,16391,16392,16393,16394,16395,16396,16397,16398,16399,16400,16401,16402,16403,16404,16405,16406,16407,16408,16409,16410,16411,16412,16413,16414,16415,16416,16417,16418,16419,16420,16421,16422,16423,16424,16425,16426,16427,16428,16429,16430,16431,16432,16433,16434,16435,16436,16437,16438,16439,16440,16441,16442,16443,16444,16445,16446,16447,16448,16449,16450,16451,16452,16453,16454,16455,16456,16457,16458,16459,16460,16461,16462,16463,16464,16465,16466,16467,16468,16469,16470,16471,16472,16473,16474,16475,16476,16477,16478,16479,16480,16481,16482,16483,16484,16485,16486,16487,16488,16489,16490,16491,16492,16493,16494,16495,16496,16497,16498,16499,16500,16501,16502,16503,16504,16505,16506,16507,16508,16509,16510,16511,16512,16513,16514,16515,16516,16517,16518,16519,16520,16521,16522,16523,16524,16525,16526,16527,16528,16529,16530,16531,16532,16533,16534,16535,16536,16537,16538,16539,16540,16541,16542,16543,16544,16545,16546,16547,16548,16549,16550,16551,16552,16553,16554,16555,16556,16557,16558,16559,16560,16561,16562,16563,16564,16565,16566,16567,16568,16569,16570,16571,16572,16573,16574,16575,16576,16577,16578,16579,16580,16581,16582,16583,16584,16585,16586,16587,16588,16589,16590,16591,16592,16593,16594,16595,16596,16597,16598,16599,16600,16601,16602,16603,16604,16605,16606,16607,16608,16609,16610,16611,16612,16613,16614,16615,16616,16617,16618,16619,16620,16621,16622,16623,16624,16625,16626,16627,16628,16629,16630,16631,16632,16633,16634,16635,16636,16637,16638,16639,16640,16641,16642,16643,16644,16645,16646,16647,16648,16649,16650,16651,16652,16653,16654,16655,16656,16657,16658,16659,16660,16661,16662,16663,16664,16665,16666,16667,16668,16669,16670,16671,16672,16673,16674,16675,16676,16677,16678,16679,16680,16681,16682,16683,16684,16685,16686,16687,16688,16689,16690,16691,16692,16693,16694,16695,16696,16697,16698,16699,16700,16701,16702,16703,16704,16705,16706,16707,16708,16709,16710,16711,16712,16713,16714,16715,16716,16717,16718,16719,16720,16721,16722,16723,16724,16725,16726,16727,16728,16729,16730,16731,16732,16733,16734,16735,16736,16737,16738,16739,16740,16741,16742,16743,16744,16745,16746,16747,16748,16749,16750,16751,16752,16753,16754,16755,16756,16757,16758,16759,16760,16761,16762,16763,16764,16765,16766,16767,16768,16769,16770,16771,16772,16773,16774,16775,16776,16777,16778,16779,16780,16781,16782,16783,16784,16785,16786,16787,16788,16789,16790,16791,16792,16793,16794,16795,16796,16797,16798,16799,16800,16801,16802,16803,16804,16805,16806,16807,16808,16809,16810,16811,16812,16813,16814,16815,16816,16817,16818,16819,16820,16821,16822,16823,16824,16825,16826,16827,16828,16829,16830,16831,16832,16833,16834,16835,16836,16837,16838,16839,16840,16841,16842,16843,16844,16845,16846,16847,16848,16849,16850,16851,16852,16853,16854,16855,16856,16857,16858,16859,16860,16861,16862,16863,16864,16865,16866,16867,16868,16869,16870,16871,16872,16873,16874,16875,16876,16877,16878,16879,16880,16881,16882,16883,16884,16885,16886,16887,16888,16889,16890,16891,16892,16893,16894,16895,16896,16897,16898,16899,16900,16901,16902,16903,16904,16905,16906,16907,16908,16909,16910,16911,16912,16913,16914,16915,16916,16917,16918,16919,16920,16921,16922,16923,16924,16925,16926,16927,16928,16929,16930,16931,16932,16933,16934,16935,16936,16937,16938,16939,16940,16941,16942,16943,16944,16945,16946,16947,16948,16949,16950,16951,16952,16953,16954,16955,16956,16957,16958,16959,16960,16961,16962,16963,16964,16965,16966,16967,16968,16969,16970,16971,16972,16973,16974,16975,16976,16977,16978,16979,16980,16981,16982,16983,16984,16985,16986,16987,16988,16989,16990,16991,16992,16993,16994,16995,16996,16997,16998,16999,17000,17001,17002,17003,17004,17005,17006,17007,17008,17009,17010,17011,17012,17013,17014,17015,17016,17017,17018,17019,17020,17021,17022,17023,17024,17025,17026,17027,17028,17029,17030,17031,17032,17033,17034,17035,17036,17037,17038,17039,17040,17041,17042,17043,17044,17045,17046,17047,17048,17049,17050,17051,17052,17053,17054,17055,17056,17057,17058,17059,17060,17061,17062,17063,17064,17065,17066,17067,17068,17069,17070,17071,17072,17073,17074,17075,17076,17077,17078,17079,17080,17081,17082,17083,17084,17085,17086,17087,17088,17089,17090,17091,17092,17093,17094,17095,17096,17097,17098,17099,17100,17101,17102,17103,17104,17105,17106,17107,17108,17109,17110,17111,17112,17113,17114,17115,17116,17117,17118,17119,17120,17121,17122,17123,17124,17125,17126,17127,17128,17129,17130,17131,17132,17133,17134,17135,17136,17137,17138,17139,17140,17141,17142,17143,17144,17145,17146,17147,17148,17149,17150,17151,17152,17153,17154,17155,17156,17157,17158,17159,17160,17161,17162,17163,17164,17165,17166,17167,17168,17169,17170,17171,17172,17173,17174,17175,17176,17177,17178,17179,17180,17181,17182,17183,17184,17185,17186,17187,17188,17189,17190,17191,17192,17193,17194,17195,17196,17197,17198,17199,17200,17201,17202,17203,17204,17205,17206,17207,17208,17209,17210,17211,17212,17213,17214,17215,17216,17217,17218,17219,17220,17221,17222,17223,17224,17225,17226,17227,17228,17229,17230,17231,17232,17233,17234,17235,17236,17237,17238,17239,17240,17241,17242,17243,17244,17245,17246,17247,17248,17249,17250,17251,17252,17253,17254,17255,17256,17257,17258,17259,17260,17261,17262,17263,17264,17265,17266,17267,17268,17269,17270,17271,17272,17273,17274,17275,17276,17277,17278,17279,17280,17281,17282,17283,17284,17285,17286,17287,17288,17289,17290,17291,17292,17293,17294,17295,17296,17297,17298,17299,17300,17301,17302,17303,17304,17305,17306,17307,17308,17309,17310,17311,17312,17313,17314,17315,17316,17317,17318,17319,17320,17321,17322,17323,17324,17325,17326,17327,17328,17329,17330,17331,17332,17333,17334,17335,17336,17337,17338,17339,17340,17341,17342,17343,17344,17345,17346,17347,17348,17349,17350,17351,17352,17353,17354,17355,17356,17357,17358,17359,17360,17361,17362,17363,17364,17365,17366,17367,17368,17369,17370,17371,17372,17373,17374,17375,17376,17377,17378,17379,17380,17381,17382,17383,17384,17385,17386,17387,17388,17389,17390,17391,17392,17393,17394,17395,17396,17397,17398,17399,17400,17401,17402,17403,17404,17405,17406,17407,17408,17409,17410,17411,17412,17413,17414,17415,17416,17417,17418,17419,17420,17421,17422,17423,17424,17425,17426,17427,17428,17429,17430,17431,17432,17433,17434,17435,17436,17437,17438,17439,17440,17441,17442,17443,17444,17445,17446,17447,17448,17449,17450,17451,17452,17453,17454,17455,17456,17457,17458,17459,17460,17461,17462,17463,17464,17465,17466,17467,17468,17469,17470,17471,17472,17473,17474,17475,17476,17477,17478,17479,17480,17481,17482,17483,17484,17485,17486,17487,17488,17489,17490,17491,17492,17493,17494,17495,17496,17497,17498,17499,17500,17501,17502,17503,17504,17505,17506,17507,17508,17509,17510,17511,17512,17513,17514,17515,17516,17517,17518,17519,17520,17521,17522,17523,17524,17525,17526,17527,17528,17529,17530,17531,17532,17533,17534,17535,17536,17537,17538,17539,17540,17541,17542,17543,17544,17545,17546,17547,17548,17549,17550,17551,17552,17553,17554,17555,17556,17557,17558,17559,17560,17561,17562,17563,17564,17565,17566,17567,17568,17569,17570,17571,17572,17573,17574,17575,17576,17577,17578,17579,17580,17581,17582,17583,17584,17585,17586,17587,17588,17589,17590,17591,17592,17593,17594,17595,17596,17597,17598,17599,17600,17601,17602,17603,17604,17605,17606,17607,17608,17609,17610,17611,17612,17613,17614,17615,17616,17617,17618,17619,17620,17621,17622,17623,17624,17625,17626,17627,17628,17629,17630,17631,17632,17633,17634,17635,17636,17637,17638,17639,17640,17641,17642,17643,17644,17645,17646,17647,17648,17649,17650,17651,17652,17653,17654,17655,17656,17657,17658,17659,17660,17661,17662,17663,17664,17665,17666,17667,17668,17669,17670,17671,17672,17673,17674,17675,17676,17677,17678,17679,17680,17681,17682,17683,17684,17685,17686,17687,17688,17689,17690,17691,17692,17693,17694,17695,17696,17697,17698,17699,17700,17701,17702,17703,17704,17705,17706,17707,17708,17709,17710,17711,17712,17713,17714,17715,17716,17717,17718,17719,17720,17721,17722,17723,17724,17725,17726,17727,17728,17729,17730,17731,17732,17733,17734,17735,17736,17737,17738,17739,17740,17741,17742,17743,17744,17745,17746,17747,17748,17749,17750,17751,17752,17753,17754,17755,17756,17757,17758,17759,17760,17761,17762,17763,17764,17765,17766,17767,17768,17769,17770,17771,17772,17773,17774,17775,17776,17777,17778,17779,17780,17781,17782,17783,17784,17785,17786,17787,17788,17789,17790,17791,17792,17793,17794,17795,17796,17797,17798,17799,17800,17801,17802,17803,17804,17805,17806,17807,17808,17809,17810,17811,17812,17813,17814,17815,17816,17817,17818,17819,17820,17821,17822,17823,17824,17825,17826,17827,17828,17829,17830,17831,17832,17833,17834,17835,17836,17837,17838,17839,17840,17841,17842,17843,17844,17845,17846,17847,17848,17849,17850,17851,17852,17853,17854,17855,17856,17857,17858,17859,17860,17861,17862,17863,17864,17865,17866,17867,17868,17869,17870,17871,17872,17873,17874,17875,17876,17877,17878,17879,17880,17881,17882,17883,17884,17885,17886,17887,17888,17889,17890,17891,17892,17893,17894,17895,17896,17897,17898,17899,17900,17901,17902,17903,17904,17905,17906,17907,17908,17909,17910,17911,17912,17913,17914,17915,17916,17917,17918,17919,17920,17921,17922,17923,17924,17925,17926,17927,17928,17929,17930,17931,17932,17933,17934,17935,17936,17937,17938,17939,17940,17941,17942,17943,17944,17945,17946,17947,17948,17949,17950,17951,17952,17953,17954,17955,17956,17957,17958,17959,17960,17961,17962,17963,17964,17965,17966,17967,17968,17969,17970,17971,17972,17973,17974,17975,17976,17977,17978,17979,17980,17981,17982,17983,17984,17985,17986,17987,17988,17989,17990,17991,17992,17993,17994,17995,17996,17997,17998,17999,18000,18001,18002,18003,18004,18005,18006,18007,18008,18009,18010,18011,18012,18013,18014,18015,18016,18017,18018,18019,18020,18021,18022,18023,18024,18025,18026,18027,18028,18029,18030,18031,18032,18033,18034,18035,18036,18037,18038,18039,18040,18041,18042,18043,18044,18045,18046,18047,18048,18049,18050,18051,18052,18053,18054,18055,18056,18057,18058,18059,18060,18061,18062,18063,18064,18065,18066,18067,18068,18069,18070,18071,18072,18073,18074,18075,18076,18077,18078,18079,18080,18081,18082,18083,18084,18085,18086,18087,18088,18089,18090,18091,18092,18093,18094,18095,18096,18097,18098,18099,18100,18101,18102,18103,18104,18105,18106,18107,18108,18109,18110,18111,18112,18113,18114,18115,18116,18117,18118,18119,18120,18121,18122,18123,18124,18125,18126,18127,18128,18129,18130,18131,18132,18133,18134,18135,18136,18137,18138,18139,18140,18141,18142,18143,18144,18145,18146,18147,18148,18149,18150,18151,18152,18153,18154,18155,18156,18157,18158,18159,18160,18161,18162,18163,18164,18165,18166,18167,18168,18169,18170,18171,18172,18173,18174,18175,18176,18177,18178,18179,18180,18181,18182,18183,18184,18185,18186,18187,18188,18189,18190,18191,18192,18193,18194,18195,18196,18197,18198,18199,18200,18201,18202,18203,18204,18205,18206,18207,18208,18209,18210,18211,18212,18213,18214,18215,18216,18217,18218,18219,18220,18221,18222,18223,18224,18225,18226,18227,18228,18229,18230,18231,18232,18233,18234,18235,18236,18237,18238,18239,18240,18241,18242,18243,18244,18245,18246,18247,18248,18249,18250,18251,18252,18253,18254,18255,18256,18257,18258,18259,18260,18261,18262,18263,18264,18265,18266,18267,18268,18269,18270,18271,18272,18273,18274,18275,18276,18277,18278,18279,18280,18281,18282,18283,18284,18285,18286,18287,18288,18289,18290,18291,18292,18293,18294,18295,18296,18297,18298,18299,18300,18301,18302,18303,18304,18305,18306,18307,18308,18309,18310,18311,18312,18313,18314,18315,18316,18317,18318,18319,18320,18321,18322,18323,18324,18325,18326,18327,18328,18329,18330,18331,18332,18333,18334,18335,18336,18337,18338,18339,18340,18341,18342,18343,18344,18345,18346,18347,18348,18349,18350,18351,18352,18353,18354,18355,18356,18357,18358,18359,18360,18361,18362,18363,18364,18365,18366,18367,18368,18369,18370,18371,18372,18373,18374,18375,18376,18377,18378,18379,18380,18381,18382,18383,18384,18385,18386,18387,18388,18389,18390,18391,18392,18393,18394,18395,18396,18397,18398,18399,18400,18401,18402,18403,18404,18405,18406,18407,18408,18409,18410,18411,18412,18413,18414,18415,18416,18417,18418,18419,18420,18421,18422,18423,18424,18425,18426,18427,18428,18429,18430,18431,18432,18433,18434,18435,18436,18437,18438,18439,18440,18441,18442,18443,18444,18445,18446,18447,18448,18449,18450,18451,18452,18453,18454,18455,18456,18457,18458,18459,18460,18461,18462,18463,18464,18465,18466,18467,18468,18469,18470,18471,18472,18473,18474,18475,18476,18477,18478,18479,18480,18481,18482,18483,18484,18485,18486,18487,18488,18489,18490,18491,18492,18493,18494,18495,18496,18497,18498,18499,18500,18501,18502,18503,18504,18505,18506,18507,18508,18509,18510,18511,18512,18513,18514,18515,18516,18517,18518,18519,18520,18521,18522,18523,18524,18525,18526,18527,18528,18529,18530,18531,18532,18533,18534,18535,18536,18537,18538,18539,18540,18541,18542,18543,18544,18545,18546,18547,18548,18549,18550,18551,18552,18553,18554,18555,18556,18557,18558,18559,18560,18561,18562,18563,18564,18565,18566,18567,18568,18569,18570,18571,18572,18573,18574,18575,18576,18577,18578,18579,18580,18581,18582,18583,18584,18585,18586,18587,18588,18589,18590,18591,18592,18593,18594,18595,18596,18597,18598,18599,18600,18601,18602,18603,18604,18605,18606,18607,18608,18609,18610,18611,18612,18613,18614,18615,18616,18617,18618,18619,18620,18621,18622,18623,18624,18625,18626,18627,18628,18629,18630,18631,18632,18633,18634,18635,18636,18637,18638,18639,18640,18641,18642,18643,18644,18645,18646,18647,18648,18649,18650,18651,18652,18653,18654,18655,18656,18657,18658,18659,18660,18661,18662,18663,18664,18665,18666,18667,18668,18669,18670,18671,18672,18673,18674,18675,18676,18677,18678,18679,18680,18681,18682,18683,18684,18685,18686,18687,18688,18689,18690,18691,18692,18693,18694,18695,18696,18697,18698,18699,18700,18701,18702,18703,18704,18705,18706,18707,18708,18709,18710,18711,18712,18713,18714,18715,18716,18717,18718,18719,18720,18721,18722,18723,18724,18725,18726,18727,18728,18729,18730,18731,18732,18733,18734,18735,18736,18737,18738,18739,18740,18741,18742,18743,18744,18745,18746,18747,18748,18749,18750,18751,18752,18753,18754,18755,18756,18757,18758,18759,18760,18761,18762,18763,18764,18765,18766,18767,18768,18769,18770,18771,18772,18773,18774,18775,18776,18777,18778,18779,18780,18781,18782,18783,18784,18785,18786,18787,18788,18789,18790,18791,18792,18793,18794,18795,18796,18797,18798,18799,18800,18801,18802,18803,18804,18805,18806,18807,18808,18809,18810,18811,18812,18813,18814,18815,18816,18817,18818,18819,18820,18821,18822,18823,18824,18825,18826,18827,18828,18829,18830,18831,18832,18833,18834,18835,18836,18837,18838,18839,18840,18841,18842,18843,18844,18845,18846,18847,18848,18849,18850,18851,18852,18853,18854,18855,18856,18857,18858,18859,18860,18861,18862,18863,18864,18865,18866,18867,18868,18869,18870,18871,18872,18873,18874,18875,18876,18877,18878,18879,18880,18881,18882,18883,18884,18885,18886,18887,18888,18889,18890,18891,18892,18893,18894,18895,18896,18897,18898,18899,18900,18901,18902,18903,18904,18905,18906,18907,18908,18909,18910,18911,18912,18913,18914,18915,18916,18917,18918,18919,18920,18921,18922,18923,18924,18925,18926,18927,18928,18929,18930,18931,18932,18933,18934,18935,18936,18937,18938,18939,18940,18941,18942,18943,18944,18945,18946,18947,18948,18949,18950,18951,18952,18953,18954,18955,18956,18957,18958,18959,18960,18961,18962,18963,18964,18965,18966,18967,18968,18969,18970,18971,18972,18973,18974,18975,18976,18977,18978,18979,18980,18981,18982,18983,18984,18985,18986,18987,18988,18989,18990,18991,18992,18993,18994,18995,18996,18997,18998,18999,19000,19001,19002,19003,19004,19005,19006,19007,19008,19009,19010,19011,19012,19013,19014,19015,19016,19017,19018,19019,19020,19021,19022,19023,19024,19025,19026,19027,19028,19029,19030,19031,19032,19033,19034,19035,19036,19037,19038,19039,19040,19041,19042,19043,19044,19045,19046,19047,19048,19049,19050,19051,19052,19053,19054,19055,19056,19057,19058,19059,19060,19061,19062,19063,19064,19065,19066,19067,19068,19069,19070,19071,19072,19073,19074,19075,19076,19077,19078,19079,19080,19081,19082,19083,19084,19085,19086,19087,19088,19089,19090,19091,19092,19093,19094,19095,19096,19097,19098,19099,19100,19101,19102,19103,19104,19105,19106,19107,19108,19109,19110,19111,19112,19113,19114,19115,19116,19117,19118,19119,19120,19121,19122,19123,19124,19125,19126,19127,19128,19129,19130,19131,19132,19133,19134,19135,19136,19137,19138,19139,19140,19141,19142,19143,19144,19145,19146,19147,19148,19149,19150,19151,19152,19153,19154,19155,19156,19157,19158,19159,19160,19161,19162,19163,19164,19165,19166,19167,19168,19169,19170,19171,19172,19173,19174,19175,19176,19177,19178,19179,19180,19181,19182,19183,19184,19185,19186,19187,19188,19189,19190,19191,19192,19193,19194,19195,19196,19197,19198,19199,19200,19201,19202,19203,19204,19205,19206,19207,19208,19209,19210,19211,19212,19213,19214,19215,19216,19217,19218,19219,19220,19221,19222,19223,19224,19225,19226,19227,19228,19229,19230,19231,19232,19233,19234,19235,19236,19237,19238,19239,19240,19241,19242,19243,19244,19245,19246,19247,19248,19249,19250,19251,19252,19253,19254,19255,19256,19257,19258,19259,19260,19261,19262,19263,19264,19265,19266,19267,19268,19269,19270,19271,19272,19273,19274,19275,19276,19277,19278,19279,19280,19281,19282,19283,19284,19285,19286,19287,19288,19289,19290,19291,19292,19293,19294,19295,19296,19297,19298,19299,19300,19301,19302,19303,19304,19305,19306,19307,19308,19309,19310,19311,19312,19313,19314,19315,19316,19317,19318,19319,19320,19321,19322,19323,19324,19325,19326,19327,19328,19329,19330,19331,19332,19333,19334,19335,19336,19337,19338,19339,19340,19341,19342,19343,19344,19345,19346,19347,19348,19349,19350,19351,19352,19353,19354,19355,19356,19357,19358,19359,19360,19361,19362,19363,19364,19365,19366,19367,19368,19369,19370,19371,19372,19373,19374,19375,19376,19377,19378,19379,19380,19381,19382,19383,19384,19385,19386,19387,19388,19389,19390,19391,19392,19393,19394,19395,19396,19397,19398,19399,19400,19401,19402,19403,19404,19405,19406,19407,19408,19409,19410,19411,19412,19413,19414,19415,19416,19417,19418,19419,19420,19421,19422,19423,19424,19425,19426,19427,19428,19429,19430,19431,19432,19433,19434,19435,19436,19437,19438,19439,19440,19441,19442,19443,19444,19445,19446,19447,19448,19449,19450,19451,19452,19453,19454,19455,19456,19457,19458,19459,19460,19461,19462,19463,19464,19465,19466,19467,19468,19469,19470,19471,19472,19473,19474,19475,19476,19477,19478,19479,19480,19481,19482,19483,19484,19485,19486,19487,19488,19489,19490,19491,19492,19493,19494,19495,19496,19497,19498,19499,19500,19501,19502,19503,19504,19505,19506,19507,19508,19509,19510,19511,19512,19513,19514,19515,19516,19517,19518,19519,19520,19521,19522,19523,19524,19525,19526,19527,19528,19529,19530,19531,19532,19533,19534,19535,19536,19537,19538,19539,19540,19541,19542,19543,19544,19545,19546,19547,19548,19549,19550,19551,19552,19553,19554,19555,19556,19557,19558,19559,19560,19561,19562,19563,19564,19565,19566,19567,19568,19569,19570,19571,19572,19573,19574,19575,19576,19577,19578,19579,19580,19581,19582,19583,19584,19585,19586,19587,19588,19589,19590,19591,19592,19593,19594,19595,19596,19597,19598,19599,19600,19601,19602,19603,19604,19605,19606,19607,19608,19609,19610,19611,19612,19613,19614,19615,19616,19617,19618,19619,19620,19621,19622,19623,19624,19625,19626,19627,19628,19629,19630,19631,19632,19633,19634,19635,19636,19637,19638,19639,19640,19641,19642,19643,19644,19645,19646,19647,19648,19649,19650,19651,19652,19653,19654,19655,19656,19657,19658,19659,19660,19661,19662,19663,19664,19665,19666,19667,19668,19669,19670,19671,19672,19673,19674,19675,19676,19677,19678,19679,19680,19681,19682,19683,19684,19685,19686,19687,19688,19689,19690,19691,19692,19693,19694,19695,19696,19697,19698,19699,19700,19701,19702,19703,19704,19705,19706,19707,19708,19709,19710,19711,19712,19713,19714,19715,19716,19717,19718,19719,19720,19721,19722,19723,19724,19725,19726,19727,19728,19729,19730,19731,19732,19733,19734,19735,19736,19737,19738,19739,19740,19741,19742,19743,19744,19745,19746,19747,19748,19749,19750,19751,19752,19753,19754,19755,19756,19757,19758,19759,19760,19761,19762,19763,19764,19765,19766,19767,19768,19769,19770,19771,19772,19773,19774,19775,19776,19777,19778,19779,19780,19781,19782,19783,19784,19785,19786,19787,19788,19789,19790,19791,19792,19793,19794,19795,19796,19797,19798,19799,19800,19801,19802,19803,19804,19805,19806,19807,19808,19809,19810,19811,19812,19813,19814,19815,19816,19817,19818,19819,19820,19821,19822,19823,19824,19825,19826,19827,19828,19829,19830,19831,19832,19833,19834,19835,19836,19837,19838,19839,19840,19841,19842,19843,19844,19845,19846,19847,19848,19849,19850,19851,19852,19853,19854,19855,19856,19857,19858,19859,19860,19861,19862,19863,19864,19865,19866,19867,19868,19869,19870,19871,19872,19873,19874,19875,19876,19877,19878,19879,19880,19881,19882,19883,19884,19885,19886,19887,19888,19889,19890,19891,19892,19893,19968,19969,19970,19971,19972,19973,19974,19975,19976,19977,19978,19979,19980,19981,19982,19983,19984,19985,19986,19987,19988,19989,19990,19991,19992,19993,19994,19995,19996,19997,19998,19999,20000,20001,20002,20003,20004,20005,20006,20007,20008,20009,20010,20011,20012,20013,20014,20015,20016,20017,20018,20019,20020,20021,20022,20023,20024,20025,20026,20027,20028,20029,20030,20031,20032,20033,20034,20035,20036,20037,20038,20039,20040,20041,20042,20043,20044,20045,20046,20047,20048,20049,20050,20051,20052,20053,20054,20055,20056,20057,20058,20059,20060,20061,20062,20063,20064,20065,20066,20067,20068,20069,20070,20071,20072,20073,20074,20075,20076,20077,20078,20079,20080,20081,20082,20083,20084,20085,20086,20087,20088,20089,20090,20091,20092,20093,20094,20095,20096,20097,20098,20099,20100,20101,20102,20103,20104,20105,20106,20107,20108,20109,20110,20111,20112,20113,20114,20115,20116,20117,20118,20119,20120,20121,20122,20123,20124,20125,20126,20127,20128,20129,20130,20131,20132,20133,20134,20135,20136,20137,20138,20139,20140,20141,20142,20143,20144,20145,20146,20147,20148,20149,20150,20151,20152,20153,20154,20155,20156,20157,20158,20159,20160,20161,20162,20163,20164,20165,20166,20167,20168,20169,20170,20171,20172,20173,20174,20175,20176,20177,20178,20179,20180,20181,20182,20183,20184,20185,20186,20187,20188,20189,20190,20191,20192,20193,20194,20195,20196,20197,20198,20199,20200,20201,20202,20203,20204,20205,20206,20207,20208,20209,20210,20211,20212,20213,20214,20215,20216,20217,20218,20219,20220,20221,20222,20223,20224,20225,20226,20227,20228,20229,20230,20231,20232,20233,20234,20235,20236,20237,20238,20239,20240,20241,20242,20243,20244,20245,20246,20247,20248,20249,20250,20251,20252,20253,20254,20255,20256,20257,20258,20259,20260,20261,20262,20263,20264,20265,20266,20267,20268,20269,20270,20271,20272,20273,20274,20275,20276,20277,20278,20279,20280,20281,20282,20283,20284,20285,20286,20287,20288,20289,20290,20291,20292,20293,20294,20295,20296,20297,20298,20299,20300,20301,20302,20303,20304,20305,20306,20307,20308,20309,20310,20311,20312,20313,20314,20315,20316,20317,20318,20319,20320,20321,20322,20323,20324,20325,20326,20327,20328,20329,20330,20331,20332,20333,20334,20335,20336,20337,20338,20339,20340,20341,20342,20343,20344,20345,20346,20347,20348,20349,20350,20351,20352,20353,20354,20355,20356,20357,20358,20359,20360,20361,20362,20363,20364,20365,20366,20367,20368,20369,20370,20371,20372,20373,20374,20375,20376,20377,20378,20379,20380,20381,20382,20383,20384,20385,20386,20387,20388,20389,20390,20391,20392,20393,20394,20395,20396,20397,20398,20399,20400,20401,20402,20403,20404,20405,20406,20407,20408,20409,20410,20411,20412,20413,20414,20415,20416,20417,20418,20419,20420,20421,20422,20423,20424,20425,20426,20427,20428,20429,20430,20431,20432,20433,20434,20435,20436,20437,20438,20439,20440,20441,20442,20443,20444,20445,20446,20447,20448,20449,20450,20451,20452,20453,20454,20455,20456,20457,20458,20459,20460,20461,20462,20463,20464,20465,20466,20467,20468,20469,20470,20471,20472,20473,20474,20475,20476,20477,20478,20479,20480,20481,20482,20483,20484,20485,20486,20487,20488,20489,20490,20491,20492,20493,20494,20495,20496,20497,20498,20499,20500,20501,20502,20503,20504,20505,20506,20507,20508,20509,20510,20511,20512,20513,20514,20515,20516,20517,20518,20519,20520,20521,20522,20523,20524,20525,20526,20527,20528,20529,20530,20531,20532,20533,20534,20535,20536,20537,20538,20539,20540,20541,20542,20543,20544,20545,20546,20547,20548,20549,20550,20551,20552,20553,20554,20555,20556,20557,20558,20559,20560,20561,20562,20563,20564,20565,20566,20567,20568,20569,20570,20571,20572,20573,20574,20575,20576,20577,20578,20579,20580,20581,20582,20583,20584,20585,20586,20587,20588,20589,20590,20591,20592,20593,20594,20595,20596,20597,20598,20599,20600,20601,20602,20603,20604,20605,20606,20607,20608,20609,20610,20611,20612,20613,20614,20615,20616,20617,20618,20619,20620,20621,20622,20623,20624,20625,20626,20627,20628,20629,20630,20631,20632,20633,20634,20635,20636,20637,20638,20639,20640,20641,20642,20643,20644,20645,20646,20647,20648,20649,20650,20651,20652,20653,20654,20655,20656,20657,20658,20659,20660,20661,20662,20663,20664,20665,20666,20667,20668,20669,20670,20671,20672,20673,20674,20675,20676,20677,20678,20679,20680,20681,20682,20683,20684,20685,20686,20687,20688,20689,20690,20691,20692,20693,20694,20695,20696,20697,20698,20699,20700,20701,20702,20703,20704,20705,20706,20707,20708,20709,20710,20711,20712,20713,20714,20715,20716,20717,20718,20719,20720,20721,20722,20723,20724,20725,20726,20727,20728,20729,20730,20731,20732,20733,20734,20735,20736,20737,20738,20739,20740,20741,20742,20743,20744,20745,20746,20747,20748,20749,20750,20751,20752,20753,20754,20755,20756,20757,20758,20759,20760,20761,20762,20763,20764,20765,20766,20767,20768,20769,20770,20771,20772,20773,20774,20775,20776,20777,20778,20779,20780,20781,20782,20783,20784,20785,20786,20787,20788,20789,20790,20791,20792,20793,20794,20795,20796,20797,20798,20799,20800,20801,20802,20803,20804,20805,20806,20807,20808,20809,20810,20811,20812,20813,20814,20815,20816,20817,20818,20819,20820,20821,20822,20823,20824,20825,20826,20827,20828,20829,20830,20831,20832,20833,20834,20835,20836,20837,20838,20839,20840,20841,20842,20843,20844,20845,20846,20847,20848,20849,20850,20851,20852,20853,20854,20855,20856,20857,20858,20859,20860,20861,20862,20863,20864,20865,20866,20867,20868,20869,20870,20871,20872,20873,20874,20875,20876,20877,20878,20879,20880,20881,20882,20883,20884,20885,20886,20887,20888,20889,20890,20891,20892,20893,20894,20895,20896,20897,20898,20899,20900,20901,20902,20903,20904,20905,20906,20907,20908,20909,20910,20911,20912,20913,20914,20915,20916,20917,20918,20919,20920,20921,20922,20923,20924,20925,20926,20927,20928,20929,20930,20931,20932,20933,20934,20935,20936,20937,20938,20939,20940,20941,20942,20943,20944,20945,20946,20947,20948,20949,20950,20951,20952,20953,20954,20955,20956,20957,20958,20959,20960,20961,20962,20963,20964,20965,20966,20967,20968,20969,20970,20971,20972,20973,20974,20975,20976,20977,20978,20979,20980,20981,20982,20983,20984,20985,20986,20987,20988,20989,20990,20991,20992,20993,20994,20995,20996,20997,20998,20999,21000,21001,21002,21003,21004,21005,21006,21007,21008,21009,21010,21011,21012,21013,21014,21015,21016,21017,21018,21019,21020,21021,21022,21023,21024,21025,21026,21027,21028,21029,21030,21031,21032,21033,21034,21035,21036,21037,21038,21039,21040,21041,21042,21043,21044,21045,21046,21047,21048,21049,21050,21051,21052,21053,21054,21055,21056,21057,21058,21059,21060,21061,21062,21063,21064,21065,21066,21067,21068,21069,21070,21071,21072,21073,21074,21075,21076,21077,21078,21079,21080,21081,21082,21083,21084,21085,21086,21087,21088,21089,21090,21091,21092,21093,21094,21095,21096,21097,21098,21099,21100,21101,21102,21103,21104,21105,21106,21107,21108,21109,21110,21111,21112,21113,21114,21115,21116,21117,21118,21119,21120,21121,21122,21123,21124,21125,21126,21127,21128,21129,21130,21131,21132,21133,21134,21135,21136,21137,21138,21139,21140,21141,21142,21143,21144,21145,21146,21147,21148,21149,21150,21151,21152,21153,21154,21155,21156,21157,21158,21159,21160,21161,21162,21163,21164,21165,21166,21167,21168,21169,21170,21171,21172,21173,21174,21175,21176,21177,21178,21179,21180,21181,21182,21183,21184,21185,21186,21187,21188,21189,21190,21191,21192,21193,21194,21195,21196,21197,21198,21199,21200,21201,21202,21203,21204,21205,21206,21207,21208,21209,21210,21211,21212,21213,21214,21215,21216,21217,21218,21219,21220,21221,21222,21223,21224,21225,21226,21227,21228,21229,21230,21231,21232,21233,21234,21235,21236,21237,21238,21239,21240,21241,21242,21243,21244,21245,21246,21247,21248,21249,21250,21251,21252,21253,21254,21255,21256,21257,21258,21259,21260,21261,21262,21263,21264,21265,21266,21267,21268,21269,21270,21271,21272,21273,21274,21275,21276,21277,21278,21279,21280,21281,21282,21283,21284,21285,21286,21287,21288,21289,21290,21291,21292,21293,21294,21295,21296,21297,21298,21299,21300,21301,21302,21303,21304,21305,21306,21307,21308,21309,21310,21311,21312,21313,21314,21315,21316,21317,21318,21319,21320,21321,21322,21323,21324,21325,21326,21327,21328,21329,21330,21331,21332,21333,21334,21335,21336,21337,21338,21339,21340,21341,21342,21343,21344,21345,21346,21347,21348,21349,21350,21351,21352,21353,21354,21355,21356,21357,21358,21359,21360,21361,21362,21363,21364,21365,21366,21367,21368,21369,21370,21371,21372,21373,21374,21375,21376,21377,21378,21379,21380,21381,21382,21383,21384,21385,21386,21387,21388,21389,21390,21391,21392,21393,21394,21395,21396,21397,21398,21399,21400,21401,21402,21403,21404,21405,21406,21407,21408,21409,21410,21411,21412,21413,21414,21415,21416,21417,21418,21419,21420,21421,21422,21423,21424,21425,21426,21427,21428,21429,21430,21431,21432,21433,21434,21435,21436,21437,21438,21439,21440,21441,21442,21443,21444,21445,21446,21447,21448,21449,21450,21451,21452,21453,21454,21455,21456,21457,21458,21459,21460,21461,21462,21463,21464,21465,21466,21467,21468,21469,21470,21471,21472,21473,21474,21475,21476,21477,21478,21479,21480,21481,21482,21483,21484,21485,21486,21487,21488,21489,21490,21491,21492,21493,21494,21495,21496,21497,21498,21499,21500,21501,21502,21503,21504,21505,21506,21507,21508,21509,21510,21511,21512,21513,21514,21515,21516,21517,21518,21519,21520,21521,21522,21523,21524,21525,21526,21527,21528,21529,21530,21531,21532,21533,21534,21535,21536,21537,21538,21539,21540,21541,21542,21543,21544,21545,21546,21547,21548,21549,21550,21551,21552,21553,21554,21555,21556,21557,21558,21559,21560,21561,21562,21563,21564,21565,21566,21567,21568,21569,21570,21571,21572,21573,21574,21575,21576,21577,21578,21579,21580,21581,21582,21583,21584,21585,21586,21587,21588,21589,21590,21591,21592,21593,21594,21595,21596,21597,21598,21599,21600,21601,21602,21603,21604,21605,21606,21607,21608,21609,21610,21611,21612,21613,21614,21615,21616,21617,21618,21619,21620,21621,21622,21623,21624,21625,21626,21627,21628,21629,21630,21631,21632,21633,21634,21635,21636,21637,21638,21639,21640,21641,21642,21643,21644,21645,21646,21647,21648,21649,21650,21651,21652,21653,21654,21655,21656,21657,21658,21659,21660,21661,21662,21663,21664,21665,21666,21667,21668,21669,21670,21671,21672,21673,21674,21675,21676,21677,21678,21679,21680,21681,21682,21683,21684,21685,21686,21687,21688,21689,21690,21691,21692,21693,21694,21695,21696,21697,21698,21699,21700,21701,21702,21703,21704,21705,21706,21707,21708,21709,21710,21711,21712,21713,21714,21715,21716,21717,21718,21719,21720,21721,21722,21723,21724,21725,21726,21727,21728,21729,21730,21731,21732,21733,21734,21735,21736,21737,21738,21739,21740,21741,21742,21743,21744,21745,21746,21747,21748,21749,21750,21751,21752,21753,21754,21755,21756,21757,21758,21759,21760,21761,21762,21763,21764,21765,21766,21767,21768,21769,21770,21771,21772,21773,21774,21775,21776,21777,21778,21779,21780,21781,21782,21783,21784,21785,21786,21787,21788,21789,21790,21791,21792,21793,21794,21795,21796,21797,21798,21799,21800,21801,21802,21803,21804,21805,21806,21807,21808,21809,21810,21811,21812,21813,21814,21815,21816,21817,21818,21819,21820,21821,21822,21823,21824,21825,21826,21827,21828,21829,21830,21831,21832,21833,21834,21835,21836,21837,21838,21839,21840,21841,21842,21843,21844,21845,21846,21847,21848,21849,21850,21851,21852,21853,21854,21855,21856,21857,21858,21859,21860,21861,21862,21863,21864,21865,21866,21867,21868,21869,21870,21871,21872,21873,21874,21875,21876,21877,21878,21879,21880,21881,21882,21883,21884,21885,21886,21887,21888,21889,21890,21891,21892,21893,21894,21895,21896,21897,21898,21899,21900,21901,21902,21903,21904,21905,21906,21907,21908,21909,21910,21911,21912,21913,21914,21915,21916,21917,21918,21919,21920,21921,21922,21923,21924,21925,21926,21927,21928,21929,21930,21931,21932,21933,21934,21935,21936,21937,21938,21939,21940,21941,21942,21943,21944,21945,21946,21947,21948,21949,21950,21951,21952,21953,21954,21955,21956,21957,21958,21959,21960,21961,21962,21963,21964,21965,21966,21967,21968,21969,21970,21971,21972,21973,21974,21975,21976,21977,21978,21979,21980,21981,21982,21983,21984,21985,21986,21987,21988,21989,21990,21991,21992,21993,21994,21995,21996,21997,21998,21999,22000,22001,22002,22003,22004,22005,22006,22007,22008,22009,22010,22011,22012,22013,22014,22015,22016,22017,22018,22019,22020,22021,22022,22023,22024,22025,22026,22027,22028,22029,22030,22031,22032,22033,22034,22035,22036,22037,22038,22039,22040,22041,22042,22043,22044,22045,22046,22047,22048,22049,22050,22051,22052,22053,22054,22055,22056,22057,22058,22059,22060,22061,22062,22063,22064,22065,22066,22067,22068,22069,22070,22071,22072,22073,22074,22075,22076,22077,22078,22079,22080,22081,22082,22083,22084,22085,22086,22087,22088,22089,22090,22091,22092,22093,22094,22095,22096,22097,22098,22099,22100,22101,22102,22103,22104,22105,22106,22107,22108,22109,22110,22111,22112,22113,22114,22115,22116,22117,22118,22119,22120,22121,22122,22123,22124,22125,22126,22127,22128,22129,22130,22131,22132,22133,22134,22135,22136,22137,22138,22139,22140,22141,22142,22143,22144,22145,22146,22147,22148,22149,22150,22151,22152,22153,22154,22155,22156,22157,22158,22159,22160,22161,22162,22163,22164,22165,22166,22167,22168,22169,22170,22171,22172,22173,22174,22175,22176,22177,22178,22179,22180,22181,22182,22183,22184,22185,22186,22187,22188,22189,22190,22191,22192,22193,22194,22195,22196,22197,22198,22199,22200,22201,22202,22203,22204,22205,22206,22207,22208,22209,22210,22211,22212,22213,22214,22215,22216,22217,22218,22219,22220,22221,22222,22223,22224,22225,22226,22227,22228,22229,22230,22231,22232,22233,22234,22235,22236,22237,22238,22239,22240,22241,22242,22243,22244,22245,22246,22247,22248,22249,22250,22251,22252,22253,22254,22255,22256,22257,22258,22259,22260,22261,22262,22263,22264,22265,22266,22267,22268,22269,22270,22271,22272,22273,22274,22275,22276,22277,22278,22279,22280,22281,22282,22283,22284,22285,22286,22287,22288,22289,22290,22291,22292,22293,22294,22295,22296,22297,22298,22299,22300,22301,22302,22303,22304,22305,22306,22307,22308,22309,22310,22311,22312,22313,22314,22315,22316,22317,22318,22319,22320,22321,22322,22323,22324,22325,22326,22327,22328,22329,22330,22331,22332,22333,22334,22335,22336,22337,22338,22339,22340,22341,22342,22343,22344,22345,22346,22347,22348,22349,22350,22351,22352,22353,22354,22355,22356,22357,22358,22359,22360,22361,22362,22363,22364,22365,22366,22367,22368,22369,22370,22371,22372,22373,22374,22375,22376,22377,22378,22379,22380,22381,22382,22383,22384,22385,22386,22387,22388,22389,22390,22391,22392,22393,22394,22395,22396,22397,22398,22399,22400,22401,22402,22403,22404,22405,22406,22407,22408,22409,22410,22411,22412,22413,22414,22415,22416,22417,22418,22419,22420,22421,22422,22423,22424,22425,22426,22427,22428,22429,22430,22431,22432,22433,22434,22435,22436,22437,22438,22439,22440,22441,22442,22443,22444,22445,22446,22447,22448,22449,22450,22451,22452,22453,22454,22455,22456,22457,22458,22459,22460,22461,22462,22463,22464,22465,22466,22467,22468,22469,22470,22471,22472,22473,22474,22475,22476,22477,22478,22479,22480,22481,22482,22483,22484,22485,22486,22487,22488,22489,22490,22491,22492,22493,22494,22495,22496,22497,22498,22499,22500,22501,22502,22503,22504,22505,22506,22507,22508,22509,22510,22511,22512,22513,22514,22515,22516,22517,22518,22519,22520,22521,22522,22523,22524,22525,22526,22527,22528,22529,22530,22531,22532,22533,22534,22535,22536,22537,22538,22539,22540,22541,22542,22543,22544,22545,22546,22547,22548,22549,22550,22551,22552,22553,22554,22555,22556,22557,22558,22559,22560,22561,22562,22563,22564,22565,22566,22567,22568,22569,22570,22571,22572,22573,22574,22575,22576,22577,22578,22579,22580,22581,22582,22583,22584,22585,22586,22587,22588,22589,22590,22591,22592,22593,22594,22595,22596,22597,22598,22599,22600,22601,22602,22603,22604,22605,22606,22607,22608,22609,22610,22611,22612,22613,22614,22615,22616,22617,22618,22619,22620,22621,22622,22623,22624,22625,22626,22627,22628,22629,22630,22631,22632,22633,22634,22635,22636,22637,22638,22639,22640,22641,22642,22643,22644,22645,22646,22647,22648,22649,22650,22651,22652,22653,22654,22655,22656,22657,22658,22659,22660,22661,22662,22663,22664,22665,22666,22667,22668,22669,22670,22671,22672,22673,22674,22675,22676,22677,22678,22679,22680,22681,22682,22683,22684,22685,22686,22687,22688,22689,22690,22691,22692,22693,22694,22695,22696,22697,22698,22699,22700,22701,22702,22703,22704,22705,22706,22707,22708,22709,22710,22711,22712,22713,22714,22715,22716,22717,22718,22719,22720,22721,22722,22723,22724,22725,22726,22727,22728,22729,22730,22731,22732,22733,22734,22735,22736,22737,22738,22739,22740,22741,22742,22743,22744,22745,22746,22747,22748,22749,22750,22751,22752,22753,22754,22755,22756,22757,22758,22759,22760,22761,22762,22763,22764,22765,22766,22767,22768,22769,22770,22771,22772,22773,22774,22775,22776,22777,22778,22779,22780,22781,22782,22783,22784,22785,22786,22787,22788,22789,22790,22791,22792,22793,22794,22795,22796,22797,22798,22799,22800,22801,22802,22803,22804,22805,22806,22807,22808,22809,22810,22811,22812,22813,22814,22815,22816,22817,22818,22819,22820,22821,22822,22823,22824,22825,22826,22827,22828,22829,22830,22831,22832,22833,22834,22835,22836,22837,22838,22839,22840,22841,22842,22843,22844,22845,22846,22847,22848,22849,22850,22851,22852,22853,22854,22855,22856,22857,22858,22859,22860,22861,22862,22863,22864,22865,22866,22867,22868,22869,22870,22871,22872,22873,22874,22875,22876,22877,22878,22879,22880,22881,22882,22883,22884,22885,22886,22887,22888,22889,22890,22891,22892,22893,22894,22895,22896,22897,22898,22899,22900,22901,22902,22903,22904,22905,22906,22907,22908,22909,22910,22911,22912,22913,22914,22915,22916,22917,22918,22919,22920,22921,22922,22923,22924,22925,22926,22927,22928,22929,22930,22931,22932,22933,22934,22935,22936,22937,22938,22939,22940,22941,22942,22943,22944,22945,22946,22947,22948,22949,22950,22951,22952,22953,22954,22955,22956,22957,22958,22959,22960,22961,22962,22963,22964,22965,22966,22967,22968,22969,22970,22971,22972,22973,22974,22975,22976,22977,22978,22979,22980,22981,22982,22983,22984,22985,22986,22987,22988,22989,22990,22991,22992,22993,22994,22995,22996,22997,22998,22999,23000,23001,23002,23003,23004,23005,23006,23007,23008,23009,23010,23011,23012,23013,23014,23015,23016,23017,23018,23019,23020,23021,23022,23023,23024,23025,23026,23027,23028,23029,23030,23031,23032,23033,23034,23035,23036,23037,23038,23039,23040,23041,23042,23043,23044,23045,23046,23047,23048,23049,23050,23051,23052,23053,23054,23055,23056,23057,23058,23059,23060,23061,23062,23063,23064,23065,23066,23067,23068,23069,23070,23071,23072,23073,23074,23075,23076,23077,23078,23079,23080,23081,23082,23083,23084,23085,23086,23087,23088,23089,23090,23091,23092,23093,23094,23095,23096,23097,23098,23099,23100,23101,23102,23103,23104,23105,23106,23107,23108,23109,23110,23111,23112,23113,23114,23115,23116,23117,23118,23119,23120,23121,23122,23123,23124,23125,23126,23127,23128,23129,23130,23131,23132,23133,23134,23135,23136,23137,23138,23139,23140,23141,23142,23143,23144,23145,23146,23147,23148,23149,23150,23151,23152,23153,23154,23155,23156,23157,23158,23159,23160,23161,23162,23163,23164,23165,23166,23167,23168,23169,23170,23171,23172,23173,23174,23175,23176,23177,23178,23179,23180,23181,23182,23183,23184,23185,23186,23187,23188,23189,23190,23191,23192,23193,23194,23195,23196,23197,23198,23199,23200,23201,23202,23203,23204,23205,23206,23207,23208,23209,23210,23211,23212,23213,23214,23215,23216,23217,23218,23219,23220,23221,23222,23223,23224,23225,23226,23227,23228,23229,23230,23231,23232,23233,23234,23235,23236,23237,23238,23239,23240,23241,23242,23243,23244,23245,23246,23247,23248,23249,23250,23251,23252,23253,23254,23255,23256,23257,23258,23259,23260,23261,23262,23263,23264,23265,23266,23267,23268,23269,23270,23271,23272,23273,23274,23275,23276,23277,23278,23279,23280,23281,23282,23283,23284,23285,23286,23287,23288,23289,23290,23291,23292,23293,23294,23295,23296,23297,23298,23299,23300,23301,23302,23303,23304,23305,23306,23307,23308,23309,23310,23311,23312,23313,23314,23315,23316,23317,23318,23319,23320,23321,23322,23323,23324,23325,23326,23327,23328,23329,23330,23331,23332,23333,23334,23335,23336,23337,23338,23339,23340,23341,23342,23343,23344,23345,23346,23347,23348,23349,23350,23351,23352,23353,23354,23355,23356,23357,23358,23359,23360,23361,23362,23363,23364,23365,23366,23367,23368,23369,23370,23371,23372,23373,23374,23375,23376,23377,23378,23379,23380,23381,23382,23383,23384,23385,23386,23387,23388,23389,23390,23391,23392,23393,23394,23395,23396,23397,23398,23399,23400,23401,23402,23403,23404,23405,23406,23407,23408,23409,23410,23411,23412,23413,23414,23415,23416,23417,23418,23419,23420,23421,23422,23423,23424,23425,23426,23427,23428,23429,23430,23431,23432,23433,23434,23435,23436,23437,23438,23439,23440,23441,23442,23443,23444,23445,23446,23447,23448,23449,23450,23451,23452,23453,23454,23455,23456,23457,23458,23459,23460,23461,23462,23463,23464,23465,23466,23467,23468,23469,23470,23471,23472,23473,23474,23475,23476,23477,23478,23479,23480,23481,23482,23483,23484,23485,23486,23487,23488,23489,23490,23491,23492,23493,23494,23495,23496,23497,23498,23499,23500,23501,23502,23503,23504,23505,23506,23507,23508,23509,23510,23511,23512,23513,23514,23515,23516,23517,23518,23519,23520,23521,23522,23523,23524,23525,23526,23527,23528,23529,23530,23531,23532,23533,23534,23535,23536,23537,23538,23539,23540,23541,23542,23543,23544,23545,23546,23547,23548,23549,23550,23551,23552,23553,23554,23555,23556,23557,23558,23559,23560,23561,23562,23563,23564,23565,23566,23567,23568,23569,23570,23571,23572,23573,23574,23575,23576,23577,23578,23579,23580,23581,23582,23583,23584,23585,23586,23587,23588,23589,23590,23591,23592,23593,23594,23595,23596,23597,23598,23599,23600,23601,23602,23603,23604,23605,23606,23607,23608,23609,23610,23611,23612,23613,23614,23615,23616,23617,23618,23619,23620,23621,23622,23623,23624,23625,23626,23627,23628,23629,23630,23631,23632,23633,23634,23635,23636,23637,23638,23639,23640,23641,23642,23643,23644,23645,23646,23647,23648,23649,23650,23651,23652,23653,23654,23655,23656,23657,23658,23659,23660,23661,23662,23663,23664,23665,23666,23667,23668,23669,23670,23671,23672,23673,23674,23675,23676,23677,23678,23679,23680,23681,23682,23683,23684,23685,23686,23687,23688,23689,23690,23691,23692,23693,23694,23695,23696,23697,23698,23699,23700,23701,23702,23703,23704,23705,23706,23707,23708,23709,23710,23711,23712,23713,23714,23715,23716,23717,23718,23719,23720,23721,23722,23723,23724,23725,23726,23727,23728,23729,23730,23731,23732,23733,23734,23735,23736,23737,23738,23739,23740,23741,23742,23743,23744,23745,23746,23747,23748,23749,23750,23751,23752,23753,23754,23755,23756,23757,23758,23759,23760,23761,23762,23763,23764,23765,23766,23767,23768,23769,23770,23771,23772,23773,23774,23775,23776,23777,23778,23779,23780,23781,23782,23783,23784,23785,23786,23787,23788,23789,23790,23791,23792,23793,23794,23795,23796,23797,23798,23799,23800,23801,23802,23803,23804,23805,23806,23807,23808,23809,23810,23811,23812,23813,23814,23815,23816,23817,23818,23819,23820,23821,23822,23823,23824,23825,23826,23827,23828,23829,23830,23831,23832,23833,23834,23835,23836,23837,23838,23839,23840,23841,23842,23843,23844,23845,23846,23847,23848,23849,23850,23851,23852,23853,23854,23855,23856,23857,23858,23859,23860,23861,23862,23863,23864,23865,23866,23867,23868,23869,23870,23871,23872,23873,23874,23875,23876,23877,23878,23879,23880,23881,23882,23883,23884,23885,23886,23887,23888,23889,23890,23891,23892,23893,23894,23895,23896,23897,23898,23899,23900,23901,23902,23903,23904,23905,23906,23907,23908,23909,23910,23911,23912,23913,23914,23915,23916,23917,23918,23919,23920,23921,23922,23923,23924,23925,23926,23927,23928,23929,23930,23931,23932,23933,23934,23935,23936,23937,23938,23939,23940,23941,23942,23943,23944,23945,23946,23947,23948,23949,23950,23951,23952,23953,23954,23955,23956,23957,23958,23959,23960,23961,23962,23963,23964,23965,23966,23967,23968,23969,23970,23971,23972,23973,23974,23975,23976,23977,23978,23979,23980,23981,23982,23983,23984,23985,23986,23987,23988,23989,23990,23991,23992,23993,23994,23995,23996,23997,23998,23999,24000,24001,24002,24003,24004,24005,24006,24007,24008,24009,24010,24011,24012,24013,24014,24015,24016,24017,24018,24019,24020,24021,24022,24023,24024,24025,24026,24027,24028,24029,24030,24031,24032,24033,24034,24035,24036,24037,24038,24039,24040,24041,24042,24043,24044,24045,24046,24047,24048,24049,24050,24051,24052,24053,24054,24055,24056,24057,24058,24059,24060,24061,24062,24063,24064,24065,24066,24067,24068,24069,24070,24071,24072,24073,24074,24075,24076,24077,24078,24079,24080,24081,24082,24083,24084,24085,24086,24087,24088,24089,24090,24091,24092,24093,24094,24095,24096,24097,24098,24099,24100,24101,24102,24103,24104,24105,24106,24107,24108,24109,24110,24111,24112,24113,24114,24115,24116,24117,24118,24119,24120,24121,24122,24123,24124,24125,24126,24127,24128,24129,24130,24131,24132,24133,24134,24135,24136,24137,24138,24139,24140,24141,24142,24143,24144,24145,24146,24147,24148,24149,24150,24151,24152,24153,24154,24155,24156,24157,24158,24159,24160,24161,24162,24163,24164,24165,24166,24167,24168,24169,24170,24171,24172,24173,24174,24175,24176,24177,24178,24179,24180,24181,24182,24183,24184,24185,24186,24187,24188,24189,24190,24191,24192,24193,24194,24195,24196,24197,24198,24199,24200,24201,24202,24203,24204,24205,24206,24207,24208,24209,24210,24211,24212,24213,24214,24215,24216,24217,24218,24219,24220,24221,24222,24223,24224,24225,24226,24227,24228,24229,24230,24231,24232,24233,24234,24235,24236,24237,24238,24239,24240,24241,24242,24243,24244,24245,24246,24247,24248,24249,24250,24251,24252,24253,24254,24255,24256,24257,24258,24259,24260,24261,24262,24263,24264,24265,24266,24267,24268,24269,24270,24271,24272,24273,24274,24275,24276,24277,24278,24279,24280,24281,24282,24283,24284,24285,24286,24287,24288,24289,24290,24291,24292,24293,24294,24295,24296,24297,24298,24299,24300,24301,24302,24303,24304,24305,24306,24307,24308,24309,24310,24311,24312,24313,24314,24315,24316,24317,24318,24319,24320,24321,24322,24323,24324,24325,24326,24327,24328,24329,24330,24331,24332,24333,24334,24335,24336,24337,24338,24339,24340,24341,24342,24343,24344,24345,24346,24347,24348,24349,24350,24351,24352,24353,24354,24355,24356,24357,24358,24359,24360,24361,24362,24363,24364,24365,24366,24367,24368,24369,24370,24371,24372,24373,24374,24375,24376,24377,24378,24379,24380,24381,24382,24383,24384,24385,24386,24387,24388,24389,24390,24391,24392,24393,24394,24395,24396,24397,24398,24399,24400,24401,24402,24403,24404,24405,24406,24407,24408,24409,24410,24411,24412,24413,24414,24415,24416,24417,24418,24419,24420,24421,24422,24423,24424,24425,24426,24427,24428,24429,24430,24431,24432,24433,24434,24435,24436,24437,24438,24439,24440,24441,24442,24443,24444,24445,24446,24447,24448,24449,24450,24451,24452,24453,24454,24455,24456,24457,24458,24459,24460,24461,24462,24463,24464,24465,24466,24467,24468,24469,24470,24471,24472,24473,24474,24475,24476,24477,24478,24479,24480,24481,24482,24483,24484,24485,24486,24487,24488,24489,24490,24491,24492,24493,24494,24495,24496,24497,24498,24499,24500,24501,24502,24503,24504,24505,24506,24507,24508,24509,24510,24511,24512,24513,24514,24515,24516,24517,24518,24519,24520,24521,24522,24523,24524,24525,24526,24527,24528,24529,24530,24531,24532,24533,24534,24535,24536,24537,24538,24539,24540,24541,24542,24543,24544,24545,24546,24547,24548,24549,24550,24551,24552,24553,24554,24555,24556,24557,24558,24559,24560,24561,24562,24563,24564,24565,24566,24567,24568,24569,24570,24571,24572,24573,24574,24575,24576,24577,24578,24579,24580,24581,24582,24583,24584,24585,24586,24587,24588,24589,24590,24591,24592,24593,24594,24595,24596,24597,24598,24599,24600,24601,24602,24603,24604,24605,24606,24607,24608,24609,24610,24611,24612,24613,24614,24615,24616,24617,24618,24619,24620,24621,24622,24623,24624,24625,24626,24627,24628,24629,24630,24631,24632,24633,24634,24635,24636,24637,24638,24639,24640,24641,24642,24643,24644,24645,24646,24647,24648,24649,24650,24651,24652,24653,24654,24655,24656,24657,24658,24659,24660,24661,24662,24663,24664,24665,24666,24667,24668,24669,24670,24671,24672,24673,24674,24675,24676,24677,24678,24679,24680,24681,24682,24683,24684,24685,24686,24687,24688,24689,24690,24691,24692,24693,24694,24695,24696,24697,24698,24699,24700,24701,24702,24703,24704,24705,24706,24707,24708,24709,24710,24711,24712,24713,24714,24715,24716,24717,24718,24719,24720,24721,24722,24723,24724,24725,24726,24727,24728,24729,24730,24731,24732,24733,24734,24735,24736,24737,24738,24739,24740,24741,24742,24743,24744,24745,24746,24747,24748,24749,24750,24751,24752,24753,24754,24755,24756,24757,24758,24759,24760,24761,24762,24763,24764,24765,24766,24767,24768,24769,24770,24771,24772,24773,24774,24775,24776,24777,24778,24779,24780,24781,24782,24783,24784,24785,24786,24787,24788,24789,24790,24791,24792,24793,24794,24795,24796,24797,24798,24799,24800,24801,24802,24803,24804,24805,24806,24807,24808,24809,24810,24811,24812,24813,24814,24815,24816,24817,24818,24819,24820,24821,24822,24823,24824,24825,24826,24827,24828,24829,24830,24831,24832,24833,24834,24835,24836,24837,24838,24839,24840,24841,24842,24843,24844,24845,24846,24847,24848,24849,24850,24851,24852,24853,24854,24855,24856,24857,24858,24859,24860,24861,24862,24863,24864,24865,24866,24867,24868,24869,24870,24871,24872,24873,24874,24875,24876,24877,24878,24879,24880,24881,24882,24883,24884,24885,24886,24887,24888,24889,24890,24891,24892,24893,24894,24895,24896,24897,24898,24899,24900,24901,24902,24903,24904,24905,24906,24907,24908,24909,24910,24911,24912,24913,24914,24915,24916,24917,24918,24919,24920,24921,24922,24923,24924,24925,24926,24927,24928,24929,24930,24931,24932,24933,24934,24935,24936,24937,24938,24939,24940,24941,24942,24943,24944,24945,24946,24947,24948,24949,24950,24951,24952,24953,24954,24955,24956,24957,24958,24959,24960,24961,24962,24963,24964,24965,24966,24967,24968,24969,24970,24971,24972,24973,24974,24975,24976,24977,24978,24979,24980,24981,24982,24983,24984,24985,24986,24987,24988,24989,24990,24991,24992,24993,24994,24995,24996,24997,24998,24999,25000,25001,25002,25003,25004,25005,25006,25007,25008,25009,25010,25011,25012,25013,25014,25015,25016,25017,25018,25019,25020,25021,25022,25023,25024,25025,25026,25027,25028,25029,25030,25031,25032,25033,25034,25035,25036,25037,25038,25039,25040,25041,25042,25043,25044,25045,25046,25047,25048,25049,25050,25051,25052,25053,25054,25055,25056,25057,25058,25059,25060,25061,25062,25063,25064,25065,25066,25067,25068,25069,25070,25071,25072,25073,25074,25075,25076,25077,25078,25079,25080,25081,25082,25083,25084,25085,25086,25087,25088,25089,25090,25091,25092,25093,25094,25095,25096,25097,25098,25099,25100,25101,25102,25103,25104,25105,25106,25107,25108,25109,25110,25111,25112,25113,25114,25115,25116,25117,25118,25119,25120,25121,25122,25123,25124,25125,25126,25127,25128,25129,25130,25131,25132,25133,25134,25135,25136,25137,25138,25139,25140,25141,25142,25143,25144,25145,25146,25147,25148,25149,25150,25151,25152,25153,25154,25155,25156,25157,25158,25159,25160,25161,25162,25163,25164,25165,25166,25167,25168,25169,25170,25171,25172,25173,25174,25175,25176,25177,25178,25179,25180,25181,25182,25183,25184,25185,25186,25187,25188,25189,25190,25191,25192,25193,25194,25195,25196,25197,25198,25199,25200,25201,25202,25203,25204,25205,25206,25207,25208,25209,25210,25211,25212,25213,25214,25215,25216,25217,25218,25219,25220,25221,25222,25223,25224,25225,25226,25227,25228,25229,25230,25231,25232,25233,25234,25235,25236,25237,25238,25239,25240,25241,25242,25243,25244,25245,25246,25247,25248,25249,25250,25251,25252,25253,25254,25255,25256,25257,25258,25259,25260,25261,25262,25263,25264,25265,25266,25267,25268,25269,25270,25271,25272,25273,25274,25275,25276,25277,25278,25279,25280,25281,25282,25283,25284,25285,25286,25287,25288,25289,25290,25291,25292,25293,25294,25295,25296,25297,25298,25299,25300,25301,25302,25303,25304,25305,25306,25307,25308,25309,25310,25311,25312,25313,25314,25315,25316,25317,25318,25319,25320,25321,25322,25323,25324,25325,25326,25327,25328,25329,25330,25331,25332,25333,25334,25335,25336,25337,25338,25339,25340,25341,25342,25343,25344,25345,25346,25347,25348,25349,25350,25351,25352,25353,25354,25355,25356,25357,25358,25359,25360,25361,25362,25363,25364,25365,25366,25367,25368,25369,25370,25371,25372,25373,25374,25375,25376,25377,25378,25379,25380,25381,25382,25383,25384,25385,25386,25387,25388,25389,25390,25391,25392,25393,25394,25395,25396,25397,25398,25399,25400,25401,25402,25403,25404,25405,25406,25407,25408,25409,25410,25411,25412,25413,25414,25415,25416,25417,25418,25419,25420,25421,25422,25423,25424,25425,25426,25427,25428,25429,25430,25431,25432,25433,25434,25435,25436,25437,25438,25439,25440,25441,25442,25443,25444,25445,25446,25447,25448,25449,25450,25451,25452,25453,25454,25455,25456,25457,25458,25459,25460,25461,25462,25463,25464,25465,25466,25467,25468,25469,25470,25471,25472,25473,25474,25475,25476,25477,25478,25479,25480,25481,25482,25483,25484,25485,25486,25487,25488,25489,25490,25491,25492,25493,25494,25495,25496,25497,25498,25499,25500,25501,25502,25503,25504,25505,25506,25507,25508,25509,25510,25511,25512,25513,25514,25515,25516,25517,25518,25519,25520,25521,25522,25523,25524,25525,25526,25527,25528,25529,25530,25531,25532,25533,25534,25535,25536,25537,25538,25539,25540,25541,25542,25543,25544,25545,25546,25547,25548,25549,25550,25551,25552,25553,25554,25555,25556,25557,25558,25559,25560,25561,25562,25563,25564,25565,25566,25567,25568,25569,25570,25571,25572,25573,25574,25575,25576,25577,25578,25579,25580,25581,25582,25583,25584,25585,25586,25587,25588,25589,25590,25591,25592,25593,25594,25595,25596,25597,25598,25599,25600,25601,25602,25603,25604,25605,25606,25607,25608,25609,25610,25611,25612,25613,25614,25615,25616,25617,25618,25619,25620,25621,25622,25623,25624,25625,25626,25627,25628,25629,25630,25631,25632,25633,25634,25635,25636,25637,25638,25639,25640,25641,25642,25643,25644,25645,25646,25647,25648,25649,25650,25651,25652,25653,25654,25655,25656,25657,25658,25659,25660,25661,25662,25663,25664,25665,25666,25667,25668,25669,25670,25671,25672,25673,25674,25675,25676,25677,25678,25679,25680,25681,25682,25683,25684,25685,25686,25687,25688,25689,25690,25691,25692,25693,25694,25695,25696,25697,25698,25699,25700,25701,25702,25703,25704,25705,25706,25707,25708,25709,25710,25711,25712,25713,25714,25715,25716,25717,25718,25719,25720,25721,25722,25723,25724,25725,25726,25727,25728,25729,25730,25731,25732,25733,25734,25735,25736,25737,25738,25739,25740,25741,25742,25743,25744,25745,25746,25747,25748,25749,25750,25751,25752,25753,25754,25755,25756,25757,25758,25759,25760,25761,25762,25763,25764,25765,25766,25767,25768,25769,25770,25771,25772,25773,25774,25775,25776,25777,25778,25779,25780,25781,25782,25783,25784,25785,25786,25787,25788,25789,25790,25791,25792,25793,25794,25795,25796,25797,25798,25799,25800,25801,25802,25803,25804,25805,25806,25807,25808,25809,25810,25811,25812,25813,25814,25815,25816,25817,25818,25819,25820,25821,25822,25823,25824,25825,25826,25827,25828,25829,25830,25831,25832,25833,25834,25835,25836,25837,25838,25839,25840,25841,25842,25843,25844,25845,25846,25847,25848,25849,25850,25851,25852,25853,25854,25855,25856,25857,25858,25859,25860,25861,25862,25863,25864,25865,25866,25867,25868,25869,25870,25871,25872,25873,25874,25875,25876,25877,25878,25879,25880,25881,25882,25883,25884,25885,25886,25887,25888,25889,25890,25891,25892,25893,25894,25895,25896,25897,25898,25899,25900,25901,25902,25903,25904,25905,25906,25907,25908,25909,25910,25911,25912,25913,25914,25915,25916,25917,25918,25919,25920,25921,25922,25923,25924,25925,25926,25927,25928,25929,25930,25931,25932,25933,25934,25935,25936,25937,25938,25939,25940,25941,25942,25943,25944,25945,25946,25947,25948,25949,25950,25951,25952,25953,25954,25955,25956,25957,25958,25959,25960,25961,25962,25963,25964,25965,25966,25967,25968,25969,25970,25971,25972,25973,25974,25975,25976,25977,25978,25979,25980,25981,25982,25983,25984,25985,25986,25987,25988,25989,25990,25991,25992,25993,25994,25995,25996,25997,25998,25999,26000,26001,26002,26003,26004,26005,26006,26007,26008,26009,26010,26011,26012,26013,26014,26015,26016,26017,26018,26019,26020,26021,26022,26023,26024,26025,26026,26027,26028,26029,26030,26031,26032,26033,26034,26035,26036,26037,26038,26039,26040,26041,26042,26043,26044,26045,26046,26047,26048,26049,26050,26051,26052,26053,26054,26055,26056,26057,26058,26059,26060,26061,26062,26063,26064,26065,26066,26067,26068,26069,26070,26071,26072,26073,26074,26075,26076,26077,26078,26079,26080,26081,26082,26083,26084,26085,26086,26087,26088,26089,26090,26091,26092,26093,26094,26095,26096,26097,26098,26099,26100,26101,26102,26103,26104,26105,26106,26107,26108,26109,26110,26111,26112,26113,26114,26115,26116,26117,26118,26119,26120,26121,26122,26123,26124,26125,26126,26127,26128,26129,26130,26131,26132,26133,26134,26135,26136,26137,26138,26139,26140,26141,26142,26143,26144,26145,26146,26147,26148,26149,26150,26151,26152,26153,26154,26155,26156,26157,26158,26159,26160,26161,26162,26163,26164,26165,26166,26167,26168,26169,26170,26171,26172,26173,26174,26175,26176,26177,26178,26179,26180,26181,26182,26183,26184,26185,26186,26187,26188,26189,26190,26191,26192,26193,26194,26195,26196,26197,26198,26199,26200,26201,26202,26203,26204,26205,26206,26207,26208,26209,26210,26211,26212,26213,26214,26215,26216,26217,26218,26219,26220,26221,26222,26223,26224,26225,26226,26227,26228,26229,26230,26231,26232,26233,26234,26235,26236,26237,26238,26239,26240,26241,26242,26243,26244,26245,26246,26247,26248,26249,26250,26251,26252,26253,26254,26255,26256,26257,26258,26259,26260,26261,26262,26263,26264,26265,26266,26267,26268,26269,26270,26271,26272,26273,26274,26275,26276,26277,26278,26279,26280,26281,26282,26283,26284,26285,26286,26287,26288,26289,26290,26291,26292,26293,26294,26295,26296,26297,26298,26299,26300,26301,26302,26303,26304,26305,26306,26307,26308,26309,26310,26311,26312,26313,26314,26315,26316,26317,26318,26319,26320,26321,26322,26323,26324,26325,26326,26327,26328,26329,26330,26331,26332,26333,26334,26335,26336,26337,26338,26339,26340,26341,26342,26343,26344,26345,26346,26347,26348,26349,26350,26351,26352,26353,26354,26355,26356,26357,26358,26359,26360,26361,26362,26363,26364,26365,26366,26367,26368,26369,26370,26371,26372,26373,26374,26375,26376,26377,26378,26379,26380,26381,26382,26383,26384,26385,26386,26387,26388,26389,26390,26391,26392,26393,26394,26395,26396,26397,26398,26399,26400,26401,26402,26403,26404,26405,26406,26407,26408,26409,26410,26411,26412,26413,26414,26415,26416,26417,26418,26419,26420,26421,26422,26423,26424,26425,26426,26427,26428,26429,26430,26431,26432,26433,26434,26435,26436,26437,26438,26439,26440,26441,26442,26443,26444,26445,26446,26447,26448,26449,26450,26451,26452,26453,26454,26455,26456,26457,26458,26459,26460,26461,26462,26463,26464,26465,26466,26467,26468,26469,26470,26471,26472,26473,26474,26475,26476,26477,26478,26479,26480,26481,26482,26483,26484,26485,26486,26487,26488,26489,26490,26491,26492,26493,26494,26495,26496,26497,26498,26499,26500,26501,26502,26503,26504,26505,26506,26507,26508,26509,26510,26511,26512,26513,26514,26515,26516,26517,26518,26519,26520,26521,26522,26523,26524,26525,26526,26527,26528,26529,26530,26531,26532,26533,26534,26535,26536,26537,26538,26539,26540,26541,26542,26543,26544,26545,26546,26547,26548,26549,26550,26551,26552,26553,26554,26555,26556,26557,26558,26559,26560,26561,26562,26563,26564,26565,26566,26567,26568,26569,26570,26571,26572,26573,26574,26575,26576,26577,26578,26579,26580,26581,26582,26583,26584,26585,26586,26587,26588,26589,26590,26591,26592,26593,26594,26595,26596,26597,26598,26599,26600,26601,26602,26603,26604,26605,26606,26607,26608,26609,26610,26611,26612,26613,26614,26615,26616,26617,26618,26619,26620,26621,26622,26623,26624,26625,26626,26627,26628,26629,26630,26631,26632,26633,26634,26635,26636,26637,26638,26639,26640,26641,26642,26643,26644,26645,26646,26647,26648,26649,26650,26651,26652,26653,26654,26655,26656,26657,26658,26659,26660,26661,26662,26663,26664,26665,26666,26667,26668,26669,26670,26671,26672,26673,26674,26675,26676,26677,26678,26679,26680,26681,26682,26683,26684,26685,26686,26687,26688,26689,26690,26691,26692,26693,26694,26695,26696,26697,26698,26699,26700,26701,26702,26703,26704,26705,26706,26707,26708,26709,26710,26711,26712,26713,26714,26715,26716,26717,26718,26719,26720,26721,26722,26723,26724,26725,26726,26727,26728,26729,26730,26731,26732,26733,26734,26735,26736,26737,26738,26739,26740,26741,26742,26743,26744,26745,26746,26747,26748,26749,26750,26751,26752,26753,26754,26755,26756,26757,26758,26759,26760,26761,26762,26763,26764,26765,26766,26767,26768,26769,26770,26771,26772,26773,26774,26775,26776,26777,26778,26779,26780,26781,26782,26783,26784,26785,26786,26787,26788,26789,26790,26791,26792,26793,26794,26795,26796,26797,26798,26799,26800,26801,26802,26803,26804,26805,26806,26807,26808,26809,26810,26811,26812,26813,26814,26815,26816,26817,26818,26819,26820,26821,26822,26823,26824,26825,26826,26827,26828,26829,26830,26831,26832,26833,26834,26835,26836,26837,26838,26839,26840,26841,26842,26843,26844,26845,26846,26847,26848,26849,26850,26851,26852,26853,26854,26855,26856,26857,26858,26859,26860,26861,26862,26863,26864,26865,26866,26867,26868,26869,26870,26871,26872,26873,26874,26875,26876,26877,26878,26879,26880,26881,26882,26883,26884,26885,26886,26887,26888,26889,26890,26891,26892,26893,26894,26895,26896,26897,26898,26899,26900,26901,26902,26903,26904,26905,26906,26907,26908,26909,26910,26911,26912,26913,26914,26915,26916,26917,26918,26919,26920,26921,26922,26923,26924,26925,26926,26927,26928,26929,26930,26931,26932,26933,26934,26935,26936,26937,26938,26939,26940,26941,26942,26943,26944,26945,26946,26947,26948,26949,26950,26951,26952,26953,26954,26955,26956,26957,26958,26959,26960,26961,26962,26963,26964,26965,26966,26967,26968,26969,26970,26971,26972,26973,26974,26975,26976,26977,26978,26979,26980,26981,26982,26983,26984,26985,26986,26987,26988,26989,26990,26991,26992,26993,26994,26995,26996,26997,26998,26999,27000,27001,27002,27003,27004,27005,27006,27007,27008,27009,27010,27011,27012,27013,27014,27015,27016,27017,27018,27019,27020,27021,27022,27023,27024,27025,27026,27027,27028,27029,27030,27031,27032,27033,27034,27035,27036,27037,27038,27039,27040,27041,27042,27043,27044,27045,27046,27047,27048,27049,27050,27051,27052,27053,27054,27055,27056,27057,27058,27059,27060,27061,27062,27063,27064,27065,27066,27067,27068,27069,27070,27071,27072,27073,27074,27075,27076,27077,27078,27079,27080,27081,27082,27083,27084,27085,27086,27087,27088,27089,27090,27091,27092,27093,27094,27095,27096,27097,27098,27099,27100,27101,27102,27103,27104,27105,27106,27107,27108,27109,27110,27111,27112,27113,27114,27115,27116,27117,27118,27119,27120,27121,27122,27123,27124,27125,27126,27127,27128,27129,27130,27131,27132,27133,27134,27135,27136,27137,27138,27139,27140,27141,27142,27143,27144,27145,27146,27147,27148,27149,27150,27151,27152,27153,27154,27155,27156,27157,27158,27159,27160,27161,27162,27163,27164,27165,27166,27167,27168,27169,27170,27171,27172,27173,27174,27175,27176,27177,27178,27179,27180,27181,27182,27183,27184,27185,27186,27187,27188,27189,27190,27191,27192,27193,27194,27195,27196,27197,27198,27199,27200,27201,27202,27203,27204,27205,27206,27207,27208,27209,27210,27211,27212,27213,27214,27215,27216,27217,27218,27219,27220,27221,27222,27223,27224,27225,27226,27227,27228,27229,27230,27231,27232,27233,27234,27235,27236,27237,27238,27239,27240,27241,27242,27243,27244,27245,27246,27247,27248,27249,27250,27251,27252,27253,27254,27255,27256,27257,27258,27259,27260,27261,27262,27263,27264,27265,27266,27267,27268,27269,27270,27271,27272,27273,27274,27275,27276,27277,27278,27279,27280,27281,27282,27283,27284,27285,27286,27287,27288,27289,27290,27291,27292,27293,27294,27295,27296,27297,27298,27299,27300,27301,27302,27303,27304,27305,27306,27307,27308,27309,27310,27311,27312,27313,27314,27315,27316,27317,27318,27319,27320,27321,27322,27323,27324,27325,27326,27327,27328,27329,27330,27331,27332,27333,27334,27335,27336,27337,27338,27339,27340,27341,27342,27343,27344,27345,27346,27347,27348,27349,27350,27351,27352,27353,27354,27355,27356,27357,27358,27359,27360,27361,27362,27363,27364,27365,27366,27367,27368,27369,27370,27371,27372,27373,27374,27375,27376,27377,27378,27379,27380,27381,27382,27383,27384,27385,27386,27387,27388,27389,27390,27391,27392,27393,27394,27395,27396,27397,27398,27399,27400,27401,27402,27403,27404,27405,27406,27407,27408,27409,27410,27411,27412,27413,27414,27415,27416,27417,27418,27419,27420,27421,27422,27423,27424,27425,27426,27427,27428,27429,27430,27431,27432,27433,27434,27435,27436,27437,27438,27439,27440,27441,27442,27443,27444,27445,27446,27447,27448,27449,27450,27451,27452,27453,27454,27455,27456,27457,27458,27459,27460,27461,27462,27463,27464,27465,27466,27467,27468,27469,27470,27471,27472,27473,27474,27475,27476,27477,27478,27479,27480,27481,27482,27483,27484,27485,27486,27487,27488,27489,27490,27491,27492,27493,27494,27495,27496,27497,27498,27499,27500,27501,27502,27503,27504,27505,27506,27507,27508,27509,27510,27511,27512,27513,27514,27515,27516,27517,27518,27519,27520,27521,27522,27523,27524,27525,27526,27527,27528,27529,27530,27531,27532,27533,27534,27535,27536,27537,27538,27539,27540,27541,27542,27543,27544,27545,27546,27547,27548,27549,27550,27551,27552,27553,27554,27555,27556,27557,27558,27559,27560,27561,27562,27563,27564,27565,27566,27567,27568,27569,27570,27571,27572,27573,27574,27575,27576,27577,27578,27579,27580,27581,27582,27583,27584,27585,27586,27587,27588,27589,27590,27591,27592,27593,27594,27595,27596,27597,27598,27599,27600,27601,27602,27603,27604,27605,27606,27607,27608,27609,27610,27611,27612,27613,27614,27615,27616,27617,27618,27619,27620,27621,27622,27623,27624,27625,27626,27627,27628,27629,27630,27631,27632,27633,27634,27635,27636,27637,27638,27639,27640,27641,27642,27643,27644,27645,27646,27647,27648,27649,27650,27651,27652,27653,27654,27655,27656,27657,27658,27659,27660,27661,27662,27663,27664,27665,27666,27667,27668,27669,27670,27671,27672,27673,27674,27675,27676,27677,27678,27679,27680,27681,27682,27683,27684,27685,27686,27687,27688,27689,27690,27691,27692,27693,27694,27695,27696,27697,27698,27699,27700,27701,27702,27703,27704,27705,27706,27707,27708,27709,27710,27711,27712,27713,27714,27715,27716,27717,27718,27719,27720,27721,27722,27723,27724,27725,27726,27727,27728,27729,27730,27731,27732,27733,27734,27735,27736,27737,27738,27739,27740,27741,27742,27743,27744,27745,27746,27747,27748,27749,27750,27751,27752,27753,27754,27755,27756,27757,27758,27759,27760,27761,27762,27763,27764,27765,27766,27767,27768,27769,27770,27771,27772,27773,27774,27775,27776,27777,27778,27779,27780,27781,27782,27783,27784,27785,27786,27787,27788,27789,27790,27791,27792,27793,27794,27795,27796,27797,27798,27799,27800,27801,27802,27803,27804,27805,27806,27807,27808,27809,27810,27811,27812,27813,27814,27815,27816,27817,27818,27819,27820,27821,27822,27823,27824,27825,27826,27827,27828,27829,27830,27831,27832,27833,27834,27835,27836,27837,27838,27839,27840,27841,27842,27843,27844,27845,27846,27847,27848,27849,27850,27851,27852,27853,27854,27855,27856,27857,27858,27859,27860,27861,27862,27863,27864,27865,27866,27867,27868,27869,27870,27871,27872,27873,27874,27875,27876,27877,27878,27879,27880,27881,27882,27883,27884,27885,27886,27887,27888,27889,27890,27891,27892,27893,27894,27895,27896,27897,27898,27899,27900,27901,27902,27903,27904,27905,27906,27907,27908,27909,27910,27911,27912,27913,27914,27915,27916,27917,27918,27919,27920,27921,27922,27923,27924,27925,27926,27927,27928,27929,27930,27931,27932,27933,27934,27935,27936,27937,27938,27939,27940,27941,27942,27943,27944,27945,27946,27947,27948,27949,27950,27951,27952,27953,27954,27955,27956,27957,27958,27959,27960,27961,27962,27963,27964,27965,27966,27967,27968,27969,27970,27971,27972,27973,27974,27975,27976,27977,27978,27979,27980,27981,27982,27983,27984,27985,27986,27987,27988,27989,27990,27991,27992,27993,27994,27995,27996,27997,27998,27999,28000,28001,28002,28003,28004,28005,28006,28007,28008,28009,28010,28011,28012,28013,28014,28015,28016,28017,28018,28019,28020,28021,28022,28023,28024,28025,28026,28027,28028,28029,28030,28031,28032,28033,28034,28035,28036,28037,28038,28039,28040,28041,28042,28043,28044,28045,28046,28047,28048,28049,28050,28051,28052,28053,28054,28055,28056,28057,28058,28059,28060,28061,28062,28063,28064,28065,28066,28067,28068,28069,28070,28071,28072,28073,28074,28075,28076,28077,28078,28079,28080,28081,28082,28083,28084,28085,28086,28087,28088,28089,28090,28091,28092,28093,28094,28095,28096,28097,28098,28099,28100,28101,28102,28103,28104,28105,28106,28107,28108,28109,28110,28111,28112,28113,28114,28115,28116,28117,28118,28119,28120,28121,28122,28123,28124,28125,28126,28127,28128,28129,28130,28131,28132,28133,28134,28135,28136,28137,28138,28139,28140,28141,28142,28143,28144,28145,28146,28147,28148,28149,28150,28151,28152,28153,28154,28155,28156,28157,28158,28159,28160,28161,28162,28163,28164,28165,28166,28167,28168,28169,28170,28171,28172,28173,28174,28175,28176,28177,28178,28179,28180,28181,28182,28183,28184,28185,28186,28187,28188,28189,28190,28191,28192,28193,28194,28195,28196,28197,28198,28199,28200,28201,28202,28203,28204,28205,28206,28207,28208,28209,28210,28211,28212,28213,28214,28215,28216,28217,28218,28219,28220,28221,28222,28223,28224,28225,28226,28227,28228,28229,28230,28231,28232,28233,28234,28235,28236,28237,28238,28239,28240,28241,28242,28243,28244,28245,28246,28247,28248,28249,28250,28251,28252,28253,28254,28255,28256,28257,28258,28259,28260,28261,28262,28263,28264,28265,28266,28267,28268,28269,28270,28271,28272,28273,28274,28275,28276,28277,28278,28279,28280,28281,28282,28283,28284,28285,28286,28287,28288,28289,28290,28291,28292,28293,28294,28295,28296,28297,28298,28299,28300,28301,28302,28303,28304,28305,28306,28307,28308,28309,28310,28311,28312,28313,28314,28315,28316,28317,28318,28319,28320,28321,28322,28323,28324,28325,28326,28327,28328,28329,28330,28331,28332,28333,28334,28335,28336,28337,28338,28339,28340,28341,28342,28343,28344,28345,28346,28347,28348,28349,28350,28351,28352,28353,28354,28355,28356,28357,28358,28359,28360,28361,28362,28363,28364,28365,28366,28367,28368,28369,28370,28371,28372,28373,28374,28375,28376,28377,28378,28379,28380,28381,28382,28383,28384,28385,28386,28387,28388,28389,28390,28391,28392,28393,28394,28395,28396,28397,28398,28399,28400,28401,28402,28403,28404,28405,28406,28407,28408,28409,28410,28411,28412,28413,28414,28415,28416,28417,28418,28419,28420,28421,28422,28423,28424,28425,28426,28427,28428,28429,28430,28431,28432,28433,28434,28435,28436,28437,28438,28439,28440,28441,28442,28443,28444,28445,28446,28447,28448,28449,28450,28451,28452,28453,28454,28455,28456,28457,28458,28459,28460,28461,28462,28463,28464,28465,28466,28467,28468,28469,28470,28471,28472,28473,28474,28475,28476,28477,28478,28479,28480,28481,28482,28483,28484,28485,28486,28487,28488,28489,28490,28491,28492,28493,28494,28495,28496,28497,28498,28499,28500,28501,28502,28503,28504,28505,28506,28507,28508,28509,28510,28511,28512,28513,28514,28515,28516,28517,28518,28519,28520,28521,28522,28523,28524,28525,28526,28527,28528,28529,28530,28531,28532,28533,28534,28535,28536,28537,28538,28539,28540,28541,28542,28543,28544,28545,28546,28547,28548,28549,28550,28551,28552,28553,28554,28555,28556,28557,28558,28559,28560,28561,28562,28563,28564,28565,28566,28567,28568,28569,28570,28571,28572,28573,28574,28575,28576,28577,28578,28579,28580,28581,28582,28583,28584,28585,28586,28587,28588,28589,28590,28591,28592,28593,28594,28595,28596,28597,28598,28599,28600,28601,28602,28603,28604,28605,28606,28607,28608,28609,28610,28611,28612,28613,28614,28615,28616,28617,28618,28619,28620,28621,28622,28623,28624,28625,28626,28627,28628,28629,28630,28631,28632,28633,28634,28635,28636,28637,28638,28639,28640,28641,28642,28643,28644,28645,28646,28647,28648,28649,28650,28651,28652,28653,28654,28655,28656,28657,28658,28659,28660,28661,28662,28663,28664,28665,28666,28667,28668,28669,28670,28671,28672,28673,28674,28675,28676,28677,28678,28679,28680,28681,28682,28683,28684,28685,28686,28687,28688,28689,28690,28691,28692,28693,28694,28695,28696,28697,28698,28699,28700,28701,28702,28703,28704,28705,28706,28707,28708,28709,28710,28711,28712,28713,28714,28715,28716,28717,28718,28719,28720,28721,28722,28723,28724,28725,28726,28727,28728,28729,28730,28731,28732,28733,28734,28735,28736,28737,28738,28739,28740,28741,28742,28743,28744,28745,28746,28747,28748,28749,28750,28751,28752,28753,28754,28755,28756,28757,28758,28759,28760,28761,28762,28763,28764,28765,28766,28767,28768,28769,28770,28771,28772,28773,28774,28775,28776,28777,28778,28779,28780,28781,28782,28783,28784,28785,28786,28787,28788,28789,28790,28791,28792,28793,28794,28795,28796,28797,28798,28799,28800,28801,28802,28803,28804,28805,28806,28807,28808,28809,28810,28811,28812,28813,28814,28815,28816,28817,28818,28819,28820,28821,28822,28823,28824,28825,28826,28827,28828,28829,28830,28831,28832,28833,28834,28835,28836,28837,28838,28839,28840,28841,28842,28843,28844,28845,28846,28847,28848,28849,28850,28851,28852,28853,28854,28855,28856,28857,28858,28859,28860,28861,28862,28863,28864,28865,28866,28867,28868,28869,28870,28871,28872,28873,28874,28875,28876,28877,28878,28879,28880,28881,28882,28883,28884,28885,28886,28887,28888,28889,28890,28891,28892,28893,28894,28895,28896,28897,28898,28899,28900,28901,28902,28903,28904,28905,28906,28907,28908,28909,28910,28911,28912,28913,28914,28915,28916,28917,28918,28919,28920,28921,28922,28923,28924,28925,28926,28927,28928,28929,28930,28931,28932,28933,28934,28935,28936,28937,28938,28939,28940,28941,28942,28943,28944,28945,28946,28947,28948,28949,28950,28951,28952,28953,28954,28955,28956,28957,28958,28959,28960,28961,28962,28963,28964,28965,28966,28967,28968,28969,28970,28971,28972,28973,28974,28975,28976,28977,28978,28979,28980,28981,28982,28983,28984,28985,28986,28987,28988,28989,28990,28991,28992,28993,28994,28995,28996,28997,28998,28999,29000,29001,29002,29003,29004,29005,29006,29007,29008,29009,29010,29011,29012,29013,29014,29015,29016,29017,29018,29019,29020,29021,29022,29023,29024,29025,29026,29027,29028,29029,29030,29031,29032,29033,29034,29035,29036,29037,29038,29039,29040,29041,29042,29043,29044,29045,29046,29047,29048,29049,29050,29051,29052,29053,29054,29055,29056,29057,29058,29059,29060,29061,29062,29063,29064,29065,29066,29067,29068,29069,29070,29071,29072,29073,29074,29075,29076,29077,29078,29079,29080,29081,29082,29083,29084,29085,29086,29087,29088,29089,29090,29091,29092,29093,29094,29095,29096,29097,29098,29099,29100,29101,29102,29103,29104,29105,29106,29107,29108,29109,29110,29111,29112,29113,29114,29115,29116,29117,29118,29119,29120,29121,29122,29123,29124,29125,29126,29127,29128,29129,29130,29131,29132,29133,29134,29135,29136,29137,29138,29139,29140,29141,29142,29143,29144,29145,29146,29147,29148,29149,29150,29151,29152,29153,29154,29155,29156,29157,29158,29159,29160,29161,29162,29163,29164,29165,29166,29167,29168,29169,29170,29171,29172,29173,29174,29175,29176,29177,29178,29179,29180,29181,29182,29183,29184,29185,29186,29187,29188,29189,29190,29191,29192,29193,29194,29195,29196,29197,29198,29199,29200,29201,29202,29203,29204,29205,29206,29207,29208,29209,29210,29211,29212,29213,29214,29215,29216,29217,29218,29219,29220,29221,29222,29223,29224,29225,29226,29227,29228,29229,29230,29231,29232,29233,29234,29235,29236,29237,29238,29239,29240,29241,29242,29243,29244,29245,29246,29247,29248,29249,29250,29251,29252,29253,29254,29255,29256,29257,29258,29259,29260,29261,29262,29263,29264,29265,29266,29267,29268,29269,29270,29271,29272,29273,29274,29275,29276,29277,29278,29279,29280,29281,29282,29283,29284,29285,29286,29287,29288,29289,29290,29291,29292,29293,29294,29295,29296,29297,29298,29299,29300,29301,29302,29303,29304,29305,29306,29307,29308,29309,29310,29311,29312,29313,29314,29315,29316,29317,29318,29319,29320,29321,29322,29323,29324,29325,29326,29327,29328,29329,29330,29331,29332,29333,29334,29335,29336,29337,29338,29339,29340,29341,29342,29343,29344,29345,29346,29347,29348,29349,29350,29351,29352,29353,29354,29355,29356,29357,29358,29359,29360,29361,29362,29363,29364,29365,29366,29367,29368,29369,29370,29371,29372,29373,29374,29375,29376,29377,29378,29379,29380,29381,29382,29383,29384,29385,29386,29387,29388,29389,29390,29391,29392,29393,29394,29395,29396,29397,29398,29399,29400,29401,29402,29403,29404,29405,29406,29407,29408,29409,29410,29411,29412,29413,29414,29415,29416,29417,29418,29419,29420,29421,29422,29423,29424,29425,29426,29427,29428,29429,29430,29431,29432,29433,29434,29435,29436,29437,29438,29439,29440,29441,29442,29443,29444,29445,29446,29447,29448,29449,29450,29451,29452,29453,29454,29455,29456,29457,29458,29459,29460,29461,29462,29463,29464,29465,29466,29467,29468,29469,29470,29471,29472,29473,29474,29475,29476,29477,29478,29479,29480,29481,29482,29483,29484,29485,29486,29487,29488,29489,29490,29491,29492,29493,29494,29495,29496,29497,29498,29499,29500,29501,29502,29503,29504,29505,29506,29507,29508,29509,29510,29511,29512,29513,29514,29515,29516,29517,29518,29519,29520,29521,29522,29523,29524,29525,29526,29527,29528,29529,29530,29531,29532,29533,29534,29535,29536,29537,29538,29539,29540,29541,29542,29543,29544,29545,29546,29547,29548,29549,29550,29551,29552,29553,29554,29555,29556,29557,29558,29559,29560,29561,29562,29563,29564,29565,29566,29567,29568,29569,29570,29571,29572,29573,29574,29575,29576,29577,29578,29579,29580,29581,29582,29583,29584,29585,29586,29587,29588,29589,29590,29591,29592,29593,29594,29595,29596,29597,29598,29599,29600,29601,29602,29603,29604,29605,29606,29607,29608,29609,29610,29611,29612,29613,29614,29615,29616,29617,29618,29619,29620,29621,29622,29623,29624,29625,29626,29627,29628,29629,29630,29631,29632,29633,29634,29635,29636,29637,29638,29639,29640,29641,29642,29643,29644,29645,29646,29647,29648,29649,29650,29651,29652,29653,29654,29655,29656,29657,29658,29659,29660,29661,29662,29663,29664,29665,29666,29667,29668,29669,29670,29671,29672,29673,29674,29675,29676,29677,29678,29679,29680,29681,29682,29683,29684,29685,29686,29687,29688,29689,29690,29691,29692,29693,29694,29695,29696,29697,29698,29699,29700,29701,29702,29703,29704,29705,29706,29707,29708,29709,29710,29711,29712,29713,29714,29715,29716,29717,29718,29719,29720,29721,29722,29723,29724,29725,29726,29727,29728,29729,29730,29731,29732,29733,29734,29735,29736,29737,29738,29739,29740,29741,29742,29743,29744,29745,29746,29747,29748,29749,29750,29751,29752,29753,29754,29755,29756,29757,29758,29759,29760,29761,29762,29763,29764,29765,29766,29767,29768,29769,29770,29771,29772,29773,29774,29775,29776,29777,29778,29779,29780,29781,29782,29783,29784,29785,29786,29787,29788,29789,29790,29791,29792,29793,29794,29795,29796,29797,29798,29799,29800,29801,29802,29803,29804,29805,29806,29807,29808,29809,29810,29811,29812,29813,29814,29815,29816,29817,29818,29819,29820,29821,29822,29823,29824,29825,29826,29827,29828,29829,29830,29831,29832,29833,29834,29835,29836,29837,29838,29839,29840,29841,29842,29843,29844,29845,29846,29847,29848,29849,29850,29851,29852,29853,29854,29855,29856,29857,29858,29859,29860,29861,29862,29863,29864,29865,29866,29867,29868,29869,29870,29871,29872,29873,29874,29875,29876,29877,29878,29879,29880,29881,29882,29883,29884,29885,29886,29887,29888,29889,29890,29891,29892,29893,29894,29895,29896,29897,29898,29899,29900,29901,29902,29903,29904,29905,29906,29907,29908,29909,29910,29911,29912,29913,29914,29915,29916,29917,29918,29919,29920,29921,29922,29923,29924,29925,29926,29927,29928,29929,29930,29931,29932,29933,29934,29935,29936,29937,29938,29939,29940,29941,29942,29943,29944,29945,29946,29947,29948,29949,29950,29951,29952,29953,29954,29955,29956,29957,29958,29959,29960,29961,29962,29963,29964,29965,29966,29967,29968,29969,29970,29971,29972,29973,29974,29975,29976,29977,29978,29979,29980,29981,29982,29983,29984,29985,29986,29987,29988,29989,29990,29991,29992,29993,29994,29995,29996,29997,29998,29999,30000,30001,30002,30003,30004,30005,30006,30007,30008,30009,30010,30011,30012,30013,30014,30015,30016,30017,30018,30019,30020,30021,30022,30023,30024,30025,30026,30027,30028,30029,30030,30031,30032,30033,30034,30035,30036,30037,30038,30039,30040,30041,30042,30043,30044,30045,30046,30047,30048,30049,30050,30051,30052,30053,30054,30055,30056,30057,30058,30059,30060,30061,30062,30063,30064,30065,30066,30067,30068,30069,30070,30071,30072,30073,30074,30075,30076,30077,30078,30079,30080,30081,30082,30083,30084,30085,30086,30087,30088,30089,30090,30091,30092,30093,30094,30095,30096,30097,30098,30099,30100,30101,30102,30103,30104,30105,30106,30107,30108,30109,30110,30111,30112,30113,30114,30115,30116,30117,30118,30119,30120,30121,30122,30123,30124,30125,30126,30127,30128,30129,30130,30131,30132,30133,30134,30135,30136,30137,30138,30139,30140,30141,30142,30143,30144,30145,30146,30147,30148,30149,30150,30151,30152,30153,30154,30155,30156,30157,30158,30159,30160,30161,30162,30163,30164,30165,30166,30167,30168,30169,30170,30171,30172,30173,30174,30175,30176,30177,30178,30179,30180,30181,30182,30183,30184,30185,30186,30187,30188,30189,30190,30191,30192,30193,30194,30195,30196,30197,30198,30199,30200,30201,30202,30203,30204,30205,30206,30207,30208,30209,30210,30211,30212,30213,30214,30215,30216,30217,30218,30219,30220,30221,30222,30223,30224,30225,30226,30227,30228,30229,30230,30231,30232,30233,30234,30235,30236,30237,30238,30239,30240,30241,30242,30243,30244,30245,30246,30247,30248,30249,30250,30251,30252,30253,30254,30255,30256,30257,30258,30259,30260,30261,30262,30263,30264,30265,30266,30267,30268,30269,30270,30271,30272,30273,30274,30275,30276,30277,30278,30279,30280,30281,30282,30283,30284,30285,30286,30287,30288,30289,30290,30291,30292,30293,30294,30295,30296,30297,30298,30299,30300,30301,30302,30303,30304,30305,30306,30307,30308,30309,30310,30311,30312,30313,30314,30315,30316,30317,30318,30319,30320,30321,30322,30323,30324,30325,30326,30327,30328,30329,30330,30331,30332,30333,30334,30335,30336,30337,30338,30339,30340,30341,30342,30343,30344,30345,30346,30347,30348,30349,30350,30351,30352,30353,30354,30355,30356,30357,30358,30359,30360,30361,30362,30363,30364,30365,30366,30367,30368,30369,30370,30371,30372,30373,30374,30375,30376,30377,30378,30379,30380,30381,30382,30383,30384,30385,30386,30387,30388,30389,30390,30391,30392,30393,30394,30395,30396,30397,30398,30399,30400,30401,30402,30403,30404,30405,30406,30407,30408,30409,30410,30411,30412,30413,30414,30415,30416,30417,30418,30419,30420,30421,30422,30423,30424,30425,30426,30427,30428,30429,30430,30431,30432,30433,30434,30435,30436,30437,30438,30439,30440,30441,30442,30443,30444,30445,30446,30447,30448,30449,30450,30451,30452,30453,30454,30455,30456,30457,30458,30459,30460,30461,30462,30463,30464,30465,30466,30467,30468,30469,30470,30471,30472,30473,30474,30475,30476,30477,30478,30479,30480,30481,30482,30483,30484,30485,30486,30487,30488,30489,30490,30491,30492,30493,30494,30495,30496,30497,30498,30499,30500,30501,30502,30503,30504,30505,30506,30507,30508,30509,30510,30511,30512,30513,30514,30515,30516,30517,30518,30519,30520,30521,30522,30523,30524,30525,30526,30527,30528,30529,30530,30531,30532,30533,30534,30535,30536,30537,30538,30539,30540,30541,30542,30543,30544,30545,30546,30547,30548,30549,30550,30551,30552,30553,30554,30555,30556,30557,30558,30559,30560,30561,30562,30563,30564,30565,30566,30567,30568,30569,30570,30571,30572,30573,30574,30575,30576,30577,30578,30579,30580,30581,30582,30583,30584,30585,30586,30587,30588,30589,30590,30591,30592,30593,30594,30595,30596,30597,30598,30599,30600,30601,30602,30603,30604,30605,30606,30607,30608,30609,30610,30611,30612,30613,30614,30615,30616,30617,30618,30619,30620,30621,30622,30623,30624,30625,30626,30627,30628,30629,30630,30631,30632,30633,30634,30635,30636,30637,30638,30639,30640,30641,30642,30643,30644,30645,30646,30647,30648,30649,30650,30651,30652,30653,30654,30655,30656,30657,30658,30659,30660,30661,30662,30663,30664,30665,30666,30667,30668,30669,30670,30671,30672,30673,30674,30675,30676,30677,30678,30679,30680,30681,30682,30683,30684,30685,30686,30687,30688,30689,30690,30691,30692,30693,30694,30695,30696,30697,30698,30699,30700,30701,30702,30703,30704,30705,30706,30707,30708,30709,30710,30711,30712,30713,30714,30715,30716,30717,30718,30719,30720,30721,30722,30723,30724,30725,30726,30727,30728,30729,30730,30731,30732,30733,30734,30735,30736,30737,30738,30739,30740,30741,30742,30743,30744,30745,30746,30747,30748,30749,30750,30751,30752,30753,30754,30755,30756,30757,30758,30759,30760,30761,30762,30763,30764,30765,30766,30767,30768,30769,30770,30771,30772,30773,30774,30775,30776,30777,30778,30779,30780,30781,30782,30783,30784,30785,30786,30787,30788,30789,30790,30791,30792,30793,30794,30795,30796,30797,30798,30799,30800,30801,30802,30803,30804,30805,30806,30807,30808,30809,30810,30811,30812,30813,30814,30815,30816,30817,30818,30819,30820,30821,30822,30823,30824,30825,30826,30827,30828,30829,30830,30831,30832,30833,30834,30835,30836,30837,30838,30839,30840,30841,30842,30843,30844,30845,30846,30847,30848,30849,30850,30851,30852,30853,30854,30855,30856,30857,30858,30859,30860,30861,30862,30863,30864,30865,30866,30867,30868,30869,30870,30871,30872,30873,30874,30875,30876,30877,30878,30879,30880,30881,30882,30883,30884,30885,30886,30887,30888,30889,30890,30891,30892,30893,30894,30895,30896,30897,30898,30899,30900,30901,30902,30903,30904,30905,30906,30907,30908,30909,30910,30911,30912,30913,30914,30915,30916,30917,30918,30919,30920,30921,30922,30923,30924,30925,30926,30927,30928,30929,30930,30931,30932,30933,30934,30935,30936,30937,30938,30939,30940,30941,30942,30943,30944,30945,30946,30947,30948,30949,30950,30951,30952,30953,30954,30955,30956,30957,30958,30959,30960,30961,30962,30963,30964,30965,30966,30967,30968,30969,30970,30971,30972,30973,30974,30975,30976,30977,30978,30979,30980,30981,30982,30983,30984,30985,30986,30987,30988,30989,30990,30991,30992,30993,30994,30995,30996,30997,30998,30999,31000,31001,31002,31003,31004,31005,31006,31007,31008,31009,31010,31011,31012,31013,31014,31015,31016,31017,31018,31019,31020,31021,31022,31023,31024,31025,31026,31027,31028,31029,31030,31031,31032,31033,31034,31035,31036,31037,31038,31039,31040,31041,31042,31043,31044,31045,31046,31047,31048,31049,31050,31051,31052,31053,31054,31055,31056,31057,31058,31059,31060,31061,31062,31063,31064,31065,31066,31067,31068,31069,31070,31071,31072,31073,31074,31075,31076,31077,31078,31079,31080,31081,31082,31083,31084,31085,31086,31087,31088,31089,31090,31091,31092,31093,31094,31095,31096,31097,31098,31099,31100,31101,31102,31103,31104,31105,31106,31107,31108,31109,31110,31111,31112,31113,31114,31115,31116,31117,31118,31119,31120,31121,31122,31123,31124,31125,31126,31127,31128,31129,31130,31131,31132,31133,31134,31135,31136,31137,31138,31139,31140,31141,31142,31143,31144,31145,31146,31147,31148,31149,31150,31151,31152,31153,31154,31155,31156,31157,31158,31159,31160,31161,31162,31163,31164,31165,31166,31167,31168,31169,31170,31171,31172,31173,31174,31175,31176,31177,31178,31179,31180,31181,31182,31183,31184,31185,31186,31187,31188,31189,31190,31191,31192,31193,31194,31195,31196,31197,31198,31199,31200,31201,31202,31203,31204,31205,31206,31207,31208,31209,31210,31211,31212,31213,31214,31215,31216,31217,31218,31219,31220,31221,31222,31223,31224,31225,31226,31227,31228,31229,31230,31231,31232,31233,31234,31235,31236,31237,31238,31239,31240,31241,31242,31243,31244,31245,31246,31247,31248,31249,31250,31251,31252,31253,31254,31255,31256,31257,31258,31259,31260,31261,31262,31263,31264,31265,31266,31267,31268,31269,31270,31271,31272,31273,31274,31275,31276,31277,31278,31279,31280,31281,31282,31283,31284,31285,31286,31287,31288,31289,31290,31291,31292,31293,31294,31295,31296,31297,31298,31299,31300,31301,31302,31303,31304,31305,31306,31307,31308,31309,31310,31311,31312,31313,31314,31315,31316,31317,31318,31319,31320,31321,31322,31323,31324,31325,31326,31327,31328,31329,31330,31331,31332,31333,31334,31335,31336,31337,31338,31339,31340,31341,31342,31343,31344,31345,31346,31347,31348,31349,31350,31351,31352,31353,31354,31355,31356,31357,31358,31359,31360,31361,31362,31363,31364,31365,31366,31367,31368,31369,31370,31371,31372,31373,31374,31375,31376,31377,31378,31379,31380,31381,31382,31383,31384,31385,31386,31387,31388,31389,31390,31391,31392,31393,31394,31395,31396,31397,31398,31399,31400,31401,31402,31403,31404,31405,31406,31407,31408,31409,31410,31411,31412,31413,31414,31415,31416,31417,31418,31419,31420,31421,31422,31423,31424,31425,31426,31427,31428,31429,31430,31431,31432,31433,31434,31435,31436,31437,31438,31439,31440,31441,31442,31443,31444,31445,31446,31447,31448,31449,31450,31451,31452,31453,31454,31455,31456,31457,31458,31459,31460,31461,31462,31463,31464,31465,31466,31467,31468,31469,31470,31471,31472,31473,31474,31475,31476,31477,31478,31479,31480,31481,31482,31483,31484,31485,31486,31487,31488,31489,31490,31491,31492,31493,31494,31495,31496,31497,31498,31499,31500,31501,31502,31503,31504,31505,31506,31507,31508,31509,31510,31511,31512,31513,31514,31515,31516,31517,31518,31519,31520,31521,31522,31523,31524,31525,31526,31527,31528,31529,31530,31531,31532,31533,31534,31535,31536,31537,31538,31539,31540,31541,31542,31543,31544,31545,31546,31547,31548,31549,31550,31551,31552,31553,31554,31555,31556,31557,31558,31559,31560,31561,31562,31563,31564,31565,31566,31567,31568,31569,31570,31571,31572,31573,31574,31575,31576,31577,31578,31579,31580,31581,31582,31583,31584,31585,31586,31587,31588,31589,31590,31591,31592,31593,31594,31595,31596,31597,31598,31599,31600,31601,31602,31603,31604,31605,31606,31607,31608,31609,31610,31611,31612,31613,31614,31615,31616,31617,31618,31619,31620,31621,31622,31623,31624,31625,31626,31627,31628,31629,31630,31631,31632,31633,31634,31635,31636,31637,31638,31639,31640,31641,31642,31643,31644,31645,31646,31647,31648,31649,31650,31651,31652,31653,31654,31655,31656,31657,31658,31659,31660,31661,31662,31663,31664,31665,31666,31667,31668,31669,31670,31671,31672,31673,31674,31675,31676,31677,31678,31679,31680,31681,31682,31683,31684,31685,31686,31687,31688,31689,31690,31691,31692,31693,31694,31695,31696,31697,31698,31699,31700,31701,31702,31703,31704,31705,31706,31707,31708,31709,31710,31711,31712,31713,31714,31715,31716,31717,31718,31719,31720,31721,31722,31723,31724,31725,31726,31727,31728,31729,31730,31731,31732,31733,31734,31735,31736,31737,31738,31739,31740,31741,31742,31743,31744,31745,31746,31747,31748,31749,31750,31751,31752,31753,31754,31755,31756,31757,31758,31759,31760,31761,31762,31763,31764,31765,31766,31767,31768,31769,31770,31771,31772,31773,31774,31775,31776,31777,31778,31779,31780,31781,31782,31783,31784,31785,31786,31787,31788,31789,31790,31791,31792,31793,31794,31795,31796,31797,31798,31799,31800,31801,31802,31803,31804,31805,31806,31807,31808,31809,31810,31811,31812,31813,31814,31815,31816,31817,31818,31819,31820,31821,31822,31823,31824,31825,31826,31827,31828,31829,31830,31831,31832,31833,31834,31835,31836,31837,31838,31839,31840,31841,31842,31843,31844,31845,31846,31847,31848,31849,31850,31851,31852,31853,31854,31855,31856,31857,31858,31859,31860,31861,31862,31863,31864,31865,31866,31867,31868,31869,31870,31871,31872,31873,31874,31875,31876,31877,31878,31879,31880,31881,31882,31883,31884,31885,31886,31887,31888,31889,31890,31891,31892,31893,31894,31895,31896,31897,31898,31899,31900,31901,31902,31903,31904,31905,31906,31907,31908,31909,31910,31911,31912,31913,31914,31915,31916,31917,31918,31919,31920,31921,31922,31923,31924,31925,31926,31927,31928,31929,31930,31931,31932,31933,31934,31935,31936,31937,31938,31939,31940,31941,31942,31943,31944,31945,31946,31947,31948,31949,31950,31951,31952,31953,31954,31955,31956,31957,31958,31959,31960,31961,31962,31963,31964,31965,31966,31967,31968,31969,31970,31971,31972,31973,31974,31975,31976,31977,31978,31979,31980,31981,31982,31983,31984,31985,31986,31987,31988,31989,31990,31991,31992,31993,31994,31995,31996,31997,31998,31999,32000,32001,32002,32003,32004,32005,32006,32007,32008,32009,32010,32011,32012,32013,32014,32015,32016,32017,32018,32019,32020,32021,32022,32023,32024,32025,32026,32027,32028,32029,32030,32031,32032,32033,32034,32035,32036,32037,32038,32039,32040,32041,32042,32043,32044,32045,32046,32047,32048,32049,32050,32051,32052,32053,32054,32055,32056,32057,32058,32059,32060,32061,32062,32063,32064,32065,32066,32067,32068,32069,32070,32071,32072,32073,32074,32075,32076,32077,32078,32079,32080,32081,32082,32083,32084,32085,32086,32087,32088,32089,32090,32091,32092,32093,32094,32095,32096,32097,32098,32099,32100,32101,32102,32103,32104,32105,32106,32107,32108,32109,32110,32111,32112,32113,32114,32115,32116,32117,32118,32119,32120,32121,32122,32123,32124,32125,32126,32127,32128,32129,32130,32131,32132,32133,32134,32135,32136,32137,32138,32139,32140,32141,32142,32143,32144,32145,32146,32147,32148,32149,32150,32151,32152,32153,32154,32155,32156,32157,32158,32159,32160,32161,32162,32163,32164,32165,32166,32167,32168,32169,32170,32171,32172,32173,32174,32175,32176,32177,32178,32179,32180,32181,32182,32183,32184,32185,32186,32187,32188,32189,32190,32191,32192,32193,32194,32195,32196,32197,32198,32199,32200,32201,32202,32203,32204,32205,32206,32207,32208,32209,32210,32211,32212,32213,32214,32215,32216,32217,32218,32219,32220,32221,32222,32223,32224,32225,32226,32227,32228,32229,32230,32231,32232,32233,32234,32235,32236,32237,32238,32239,32240,32241,32242,32243,32244,32245,32246,32247,32248,32249,32250,32251,32252,32253,32254,32255,32256,32257,32258,32259,32260,32261,32262,32263,32264,32265,32266,32267,32268,32269,32270,32271,32272,32273,32274,32275,32276,32277,32278,32279,32280,32281,32282,32283,32284,32285,32286,32287,32288,32289,32290,32291,32292,32293,32294,32295,32296,32297,32298,32299,32300,32301,32302,32303,32304,32305,32306,32307,32308,32309,32310,32311,32312,32313,32314,32315,32316,32317,32318,32319,32320,32321,32322,32323,32324,32325,32326,32327,32328,32329,32330,32331,32332,32333,32334,32335,32336,32337,32338,32339,32340,32341,32342,32343,32344,32345,32346,32347,32348,32349,32350,32351,32352,32353,32354,32355,32356,32357,32358,32359,32360,32361,32362,32363,32364,32365,32366,32367,32368,32369,32370,32371,32372,32373,32374,32375,32376,32377,32378,32379,32380,32381,32382,32383,32384,32385,32386,32387,32388,32389,32390,32391,32392,32393,32394,32395,32396,32397,32398,32399,32400,32401,32402,32403,32404,32405,32406,32407,32408,32409,32410,32411,32412,32413,32414,32415,32416,32417,32418,32419,32420,32421,32422,32423,32424,32425,32426,32427,32428,32429,32430,32431,32432,32433,32434,32435,32436,32437,32438,32439,32440,32441,32442,32443,32444,32445,32446,32447,32448,32449,32450,32451,32452,32453,32454,32455,32456,32457,32458,32459,32460,32461,32462,32463,32464,32465,32466,32467,32468,32469,32470,32471,32472,32473,32474,32475,32476,32477,32478,32479,32480,32481,32482,32483,32484,32485,32486,32487,32488,32489,32490,32491,32492,32493,32494,32495,32496,32497,32498,32499,32500,32501,32502,32503,32504,32505,32506,32507,32508,32509,32510,32511,32512,32513,32514,32515,32516,32517,32518,32519,32520,32521,32522,32523,32524,32525,32526,32527,32528,32529,32530,32531,32532,32533,32534,32535,32536,32537,32538,32539,32540,32541,32542,32543,32544,32545,32546,32547,32548,32549,32550,32551,32552,32553,32554,32555,32556,32557,32558,32559,32560,32561,32562,32563,32564,32565,32566,32567,32568,32569,32570,32571,32572,32573,32574,32575,32576,32577,32578,32579,32580,32581,32582,32583,32584,32585,32586,32587,32588,32589,32590,32591,32592,32593,32594,32595,32596,32597,32598,32599,32600,32601,32602,32603,32604,32605,32606,32607,32608,32609,32610,32611,32612,32613,32614,32615,32616,32617,32618,32619,32620,32621,32622,32623,32624,32625,32626,32627,32628,32629,32630,32631,32632,32633,32634,32635,32636,32637,32638,32639,32640,32641,32642,32643,32644,32645,32646,32647,32648,32649,32650,32651,32652,32653,32654,32655,32656,32657,32658,32659,32660,32661,32662,32663,32664,32665,32666,32667,32668,32669,32670,32671,32672,32673,32674,32675,32676,32677,32678,32679,32680,32681,32682,32683,32684,32685,32686,32687,32688,32689,32690,32691,32692,32693,32694,32695,32696,32697,32698,32699,32700,32701,32702,32703,32704,32705,32706,32707,32708,32709,32710,32711,32712,32713,32714,32715,32716,32717,32718,32719,32720,32721,32722,32723,32724,32725,32726,32727,32728,32729,32730,32731,32732,32733,32734,32735,32736,32737,32738,32739,32740,32741,32742,32743,32744,32745,32746,32747,32748,32749,32750,32751,32752,32753,32754,32755,32756,32757,32758,32759,32760,32761,32762,32763,32764,32765,32766,32767,32768,32769,32770,32771,32772,32773,32774,32775,32776,32777,32778,32779,32780,32781,32782,32783,32784,32785,32786,32787,32788,32789,32790,32791,32792,32793,32794,32795,32796,32797,32798,32799,32800,32801,32802,32803,32804,32805,32806,32807,32808,32809,32810,32811,32812,32813,32814,32815,32816,32817,32818,32819,32820,32821,32822,32823,32824,32825,32826,32827,32828,32829,32830,32831,32832,32833,32834,32835,32836,32837,32838,32839,32840,32841,32842,32843,32844,32845,32846,32847,32848,32849,32850,32851,32852,32853,32854,32855,32856,32857,32858,32859,32860,32861,32862,32863,32864,32865,32866,32867,32868,32869,32870,32871,32872,32873,32874,32875,32876,32877,32878,32879,32880,32881,32882,32883,32884,32885,32886,32887,32888,32889,32890,32891,32892,32893,32894,32895,32896,32897,32898,32899,32900,32901,32902,32903,32904,32905,32906,32907,32908,32909,32910,32911,32912,32913,32914,32915,32916,32917,32918,32919,32920,32921,32922,32923,32924,32925,32926,32927,32928,32929,32930,32931,32932,32933,32934,32935,32936,32937,32938,32939,32940,32941,32942,32943,32944,32945,32946,32947,32948,32949,32950,32951,32952,32953,32954,32955,32956,32957,32958,32959,32960,32961,32962,32963,32964,32965,32966,32967,32968,32969,32970,32971,32972,32973,32974,32975,32976,32977,32978,32979,32980,32981,32982,32983,32984,32985,32986,32987,32988,32989,32990,32991,32992,32993,32994,32995,32996,32997,32998,32999,33000,33001,33002,33003,33004,33005,33006,33007,33008,33009,33010,33011,33012,33013,33014,33015,33016,33017,33018,33019,33020,33021,33022,33023,33024,33025,33026,33027,33028,33029,33030,33031,33032,33033,33034,33035,33036,33037,33038,33039,33040,33041,33042,33043,33044,33045,33046,33047,33048,33049,33050,33051,33052,33053,33054,33055,33056,33057,33058,33059,33060,33061,33062,33063,33064,33065,33066,33067,33068,33069,33070,33071,33072,33073,33074,33075,33076,33077,33078,33079,33080,33081,33082,33083,33084,33085,33086,33087,33088,33089,33090,33091,33092,33093,33094,33095,33096,33097,33098,33099,33100,33101,33102,33103,33104,33105,33106,33107,33108,33109,33110,33111,33112,33113,33114,33115,33116,33117,33118,33119,33120,33121,33122,33123,33124,33125,33126,33127,33128,33129,33130,33131,33132,33133,33134,33135,33136,33137,33138,33139,33140,33141,33142,33143,33144,33145,33146,33147,33148,33149,33150,33151,33152,33153,33154,33155,33156,33157,33158,33159,33160,33161,33162,33163,33164,33165,33166,33167,33168,33169,33170,33171,33172,33173,33174,33175,33176,33177,33178,33179,33180,33181,33182,33183,33184,33185,33186,33187,33188,33189,33190,33191,33192,33193,33194,33195,33196,33197,33198,33199,33200,33201,33202,33203,33204,33205,33206,33207,33208,33209,33210,33211,33212,33213,33214,33215,33216,33217,33218,33219,33220,33221,33222,33223,33224,33225,33226,33227,33228,33229,33230,33231,33232,33233,33234,33235,33236,33237,33238,33239,33240,33241,33242,33243,33244,33245,33246,33247,33248,33249,33250,33251,33252,33253,33254,33255,33256,33257,33258,33259,33260,33261,33262,33263,33264,33265,33266,33267,33268,33269,33270,33271,33272,33273,33274,33275,33276,33277,33278,33279,33280,33281,33282,33283,33284,33285,33286,33287,33288,33289,33290,33291,33292,33293,33294,33295,33296,33297,33298,33299,33300,33301,33302,33303,33304,33305,33306,33307,33308,33309,33310,33311,33312,33313,33314,33315,33316,33317,33318,33319,33320,33321,33322,33323,33324,33325,33326,33327,33328,33329,33330,33331,33332,33333,33334,33335,33336,33337,33338,33339,33340,33341,33342,33343,33344,33345,33346,33347,33348,33349,33350,33351,33352,33353,33354,33355,33356,33357,33358,33359,33360,33361,33362,33363,33364,33365,33366,33367,33368,33369,33370,33371,33372,33373,33374,33375,33376,33377,33378,33379,33380,33381,33382,33383,33384,33385,33386,33387,33388,33389,33390,33391,33392,33393,33394,33395,33396,33397,33398,33399,33400,33401,33402,33403,33404,33405,33406,33407,33408,33409,33410,33411,33412,33413,33414,33415,33416,33417,33418,33419,33420,33421,33422,33423,33424,33425,33426,33427,33428,33429,33430,33431,33432,33433,33434,33435,33436,33437,33438,33439,33440,33441,33442,33443,33444,33445,33446,33447,33448,33449,33450,33451,33452,33453,33454,33455,33456,33457,33458,33459,33460,33461,33462,33463,33464,33465,33466,33467,33468,33469,33470,33471,33472,33473,33474,33475,33476,33477,33478,33479,33480,33481,33482,33483,33484,33485,33486,33487,33488,33489,33490,33491,33492,33493,33494,33495,33496,33497,33498,33499,33500,33501,33502,33503,33504,33505,33506,33507,33508,33509,33510,33511,33512,33513,33514,33515,33516,33517,33518,33519,33520,33521,33522,33523,33524,33525,33526,33527,33528,33529,33530,33531,33532,33533,33534,33535,33536,33537,33538,33539,33540,33541,33542,33543,33544,33545,33546,33547,33548,33549,33550,33551,33552,33553,33554,33555,33556,33557,33558,33559,33560,33561,33562,33563,33564,33565,33566,33567,33568,33569,33570,33571,33572,33573,33574,33575,33576,33577,33578,33579,33580,33581,33582,33583,33584,33585,33586,33587,33588,33589,33590,33591,33592,33593,33594,33595,33596,33597,33598,33599,33600,33601,33602,33603,33604,33605,33606,33607,33608,33609,33610,33611,33612,33613,33614,33615,33616,33617,33618,33619,33620,33621,33622,33623,33624,33625,33626,33627,33628,33629,33630,33631,33632,33633,33634,33635,33636,33637,33638,33639,33640,33641,33642,33643,33644,33645,33646,33647,33648,33649,33650,33651,33652,33653,33654,33655,33656,33657,33658,33659,33660,33661,33662,33663,33664,33665,33666,33667,33668,33669,33670,33671,33672,33673,33674,33675,33676,33677,33678,33679,33680,33681,33682,33683,33684,33685,33686,33687,33688,33689,33690,33691,33692,33693,33694,33695,33696,33697,33698,33699,33700,33701,33702,33703,33704,33705,33706,33707,33708,33709,33710,33711,33712,33713,33714,33715,33716,33717,33718,33719,33720,33721,33722,33723,33724,33725,33726,33727,33728,33729,33730,33731,33732,33733,33734,33735,33736,33737,33738,33739,33740,33741,33742,33743,33744,33745,33746,33747,33748,33749,33750,33751,33752,33753,33754,33755,33756,33757,33758,33759,33760,33761,33762,33763,33764,33765,33766,33767,33768,33769,33770,33771,33772,33773,33774,33775,33776,33777,33778,33779,33780,33781,33782,33783,33784,33785,33786,33787,33788,33789,33790,33791,33792,33793,33794,33795,33796,33797,33798,33799,33800,33801,33802,33803,33804,33805,33806,33807,33808,33809,33810,33811,33812,33813,33814,33815,33816,33817,33818,33819,33820,33821,33822,33823,33824,33825,33826,33827,33828,33829,33830,33831,33832,33833,33834,33835,33836,33837,33838,33839,33840,33841,33842,33843,33844,33845,33846,33847,33848,33849,33850,33851,33852,33853,33854,33855,33856,33857,33858,33859,33860,33861,33862,33863,33864,33865,33866,33867,33868,33869,33870,33871,33872,33873,33874,33875,33876,33877,33878,33879,33880,33881,33882,33883,33884,33885,33886,33887,33888,33889,33890,33891,33892,33893,33894,33895,33896,33897,33898,33899,33900,33901,33902,33903,33904,33905,33906,33907,33908,33909,33910,33911,33912,33913,33914,33915,33916,33917,33918,33919,33920,33921,33922,33923,33924,33925,33926,33927,33928,33929,33930,33931,33932,33933,33934,33935,33936,33937,33938,33939,33940,33941,33942,33943,33944,33945,33946,33947,33948,33949,33950,33951,33952,33953,33954,33955,33956,33957,33958,33959,33960,33961,33962,33963,33964,33965,33966,33967,33968,33969,33970,33971,33972,33973,33974,33975,33976,33977,33978,33979,33980,33981,33982,33983,33984,33985,33986,33987,33988,33989,33990,33991,33992,33993,33994,33995,33996,33997,33998,33999,34000,34001,34002,34003,34004,34005,34006,34007,34008,34009,34010,34011,34012,34013,34014,34015,34016,34017,34018,34019,34020,34021,34022,34023,34024,34025,34026,34027,34028,34029,34030,34031,34032,34033,34034,34035,34036,34037,34038,34039,34040,34041,34042,34043,34044,34045,34046,34047,34048,34049,34050,34051,34052,34053,34054,34055,34056,34057,34058,34059,34060,34061,34062,34063,34064,34065,34066,34067,34068,34069,34070,34071,34072,34073,34074,34075,34076,34077,34078,34079,34080,34081,34082,34083,34084,34085,34086,34087,34088,34089,34090,34091,34092,34093,34094,34095,34096,34097,34098,34099,34100,34101,34102,34103,34104,34105,34106,34107,34108,34109,34110,34111,34112,34113,34114,34115,34116,34117,34118,34119,34120,34121,34122,34123,34124,34125,34126,34127,34128,34129,34130,34131,34132,34133,34134,34135,34136,34137,34138,34139,34140,34141,34142,34143,34144,34145,34146,34147,34148,34149,34150,34151,34152,34153,34154,34155,34156,34157,34158,34159,34160,34161,34162,34163,34164,34165,34166,34167,34168,34169,34170,34171,34172,34173,34174,34175,34176,34177,34178,34179,34180,34181,34182,34183,34184,34185,34186,34187,34188,34189,34190,34191,34192,34193,34194,34195,34196,34197,34198,34199,34200,34201,34202,34203,34204,34205,34206,34207,34208,34209,34210,34211,34212,34213,34214,34215,34216,34217,34218,34219,34220,34221,34222,34223,34224,34225,34226,34227,34228,34229,34230,34231,34232,34233,34234,34235,34236,34237,34238,34239,34240,34241,34242,34243,34244,34245,34246,34247,34248,34249,34250,34251,34252,34253,34254,34255,34256,34257,34258,34259,34260,34261,34262,34263,34264,34265,34266,34267,34268,34269,34270,34271,34272,34273,34274,34275,34276,34277,34278,34279,34280,34281,34282,34283,34284,34285,34286,34287,34288,34289,34290,34291,34292,34293,34294,34295,34296,34297,34298,34299,34300,34301,34302,34303,34304,34305,34306,34307,34308,34309,34310,34311,34312,34313,34314,34315,34316,34317,34318,34319,34320,34321,34322,34323,34324,34325,34326,34327,34328,34329,34330,34331,34332,34333,34334,34335,34336,34337,34338,34339,34340,34341,34342,34343,34344,34345,34346,34347,34348,34349,34350,34351,34352,34353,34354,34355,34356,34357,34358,34359,34360,34361,34362,34363,34364,34365,34366,34367,34368,34369,34370,34371,34372,34373,34374,34375,34376,34377,34378,34379,34380,34381,34382,34383,34384,34385,34386,34387,34388,34389,34390,34391,34392,34393,34394,34395,34396,34397,34398,34399,34400,34401,34402,34403,34404,34405,34406,34407,34408,34409,34410,34411,34412,34413,34414,34415,34416,34417,34418,34419,34420,34421,34422,34423,34424,34425,34426,34427,34428,34429,34430,34431,34432,34433,34434,34435,34436,34437,34438,34439,34440,34441,34442,34443,34444,34445,34446,34447,34448,34449,34450,34451,34452,34453,34454,34455,34456,34457,34458,34459,34460,34461,34462,34463,34464,34465,34466,34467,34468,34469,34470,34471,34472,34473,34474,34475,34476,34477,34478,34479,34480,34481,34482,34483,34484,34485,34486,34487,34488,34489,34490,34491,34492,34493,34494,34495,34496,34497,34498,34499,34500,34501,34502,34503,34504,34505,34506,34507,34508,34509,34510,34511,34512,34513,34514,34515,34516,34517,34518,34519,34520,34521,34522,34523,34524,34525,34526,34527,34528,34529,34530,34531,34532,34533,34534,34535,34536,34537,34538,34539,34540,34541,34542,34543,34544,34545,34546,34547,34548,34549,34550,34551,34552,34553,34554,34555,34556,34557,34558,34559,34560,34561,34562,34563,34564,34565,34566,34567,34568,34569,34570,34571,34572,34573,34574,34575,34576,34577,34578,34579,34580,34581,34582,34583,34584,34585,34586,34587,34588,34589,34590,34591,34592,34593,34594,34595,34596,34597,34598,34599,34600,34601,34602,34603,34604,34605,34606,34607,34608,34609,34610,34611,34612,34613,34614,34615,34616,34617,34618,34619,34620,34621,34622,34623,34624,34625,34626,34627,34628,34629,34630,34631,34632,34633,34634,34635,34636,34637,34638,34639,34640,34641,34642,34643,34644,34645,34646,34647,34648,34649,34650,34651,34652,34653,34654,34655,34656,34657,34658,34659,34660,34661,34662,34663,34664,34665,34666,34667,34668,34669,34670,34671,34672,34673,34674,34675,34676,34677,34678,34679,34680,34681,34682,34683,34684,34685,34686,34687,34688,34689,34690,34691,34692,34693,34694,34695,34696,34697,34698,34699,34700,34701,34702,34703,34704,34705,34706,34707,34708,34709,34710,34711,34712,34713,34714,34715,34716,34717,34718,34719,34720,34721,34722,34723,34724,34725,34726,34727,34728,34729,34730,34731,34732,34733,34734,34735,34736,34737,34738,34739,34740,34741,34742,34743,34744,34745,34746,34747,34748,34749,34750,34751,34752,34753,34754,34755,34756,34757,34758,34759,34760,34761,34762,34763,34764,34765,34766,34767,34768,34769,34770,34771,34772,34773,34774,34775,34776,34777,34778,34779,34780,34781,34782,34783,34784,34785,34786,34787,34788,34789,34790,34791,34792,34793,34794,34795,34796,34797,34798,34799,34800,34801,34802,34803,34804,34805,34806,34807,34808,34809,34810,34811,34812,34813,34814,34815,34816,34817,34818,34819,34820,34821,34822,34823,34824,34825,34826,34827,34828,34829,34830,34831,34832,34833,34834,34835,34836,34837,34838,34839,34840,34841,34842,34843,34844,34845,34846,34847,34848,34849,34850,34851,34852,34853,34854,34855,34856,34857,34858,34859,34860,34861,34862,34863,34864,34865,34866,34867,34868,34869,34870,34871,34872,34873,34874,34875,34876,34877,34878,34879,34880,34881,34882,34883,34884,34885,34886,34887,34888,34889,34890,34891,34892,34893,34894,34895,34896,34897,34898,34899,34900,34901,34902,34903,34904,34905,34906,34907,34908,34909,34910,34911,34912,34913,34914,34915,34916,34917,34918,34919,34920,34921,34922,34923,34924,34925,34926,34927,34928,34929,34930,34931,34932,34933,34934,34935,34936,34937,34938,34939,34940,34941,34942,34943,34944,34945,34946,34947,34948,34949,34950,34951,34952,34953,34954,34955,34956,34957,34958,34959,34960,34961,34962,34963,34964,34965,34966,34967,34968,34969,34970,34971,34972,34973,34974,34975,34976,34977,34978,34979,34980,34981,34982,34983,34984,34985,34986,34987,34988,34989,34990,34991,34992,34993,34994,34995,34996,34997,34998,34999,35000,35001,35002,35003,35004,35005,35006,35007,35008,35009,35010,35011,35012,35013,35014,35015,35016,35017,35018,35019,35020,35021,35022,35023,35024,35025,35026,35027,35028,35029,35030,35031,35032,35033,35034,35035,35036,35037,35038,35039,35040,35041,35042,35043,35044,35045,35046,35047,35048,35049,35050,35051,35052,35053,35054,35055,35056,35057,35058,35059,35060,35061,35062,35063,35064,35065,35066,35067,35068,35069,35070,35071,35072,35073,35074,35075,35076,35077,35078,35079,35080,35081,35082,35083,35084,35085,35086,35087,35088,35089,35090,35091,35092,35093,35094,35095,35096,35097,35098,35099,35100,35101,35102,35103,35104,35105,35106,35107,35108,35109,35110,35111,35112,35113,35114,35115,35116,35117,35118,35119,35120,35121,35122,35123,35124,35125,35126,35127,35128,35129,35130,35131,35132,35133,35134,35135,35136,35137,35138,35139,35140,35141,35142,35143,35144,35145,35146,35147,35148,35149,35150,35151,35152,35153,35154,35155,35156,35157,35158,35159,35160,35161,35162,35163,35164,35165,35166,35167,35168,35169,35170,35171,35172,35173,35174,35175,35176,35177,35178,35179,35180,35181,35182,35183,35184,35185,35186,35187,35188,35189,35190,35191,35192,35193,35194,35195,35196,35197,35198,35199,35200,35201,35202,35203,35204,35205,35206,35207,35208,35209,35210,35211,35212,35213,35214,35215,35216,35217,35218,35219,35220,35221,35222,35223,35224,35225,35226,35227,35228,35229,35230,35231,35232,35233,35234,35235,35236,35237,35238,35239,35240,35241,35242,35243,35244,35245,35246,35247,35248,35249,35250,35251,35252,35253,35254,35255,35256,35257,35258,35259,35260,35261,35262,35263,35264,35265,35266,35267,35268,35269,35270,35271,35272,35273,35274,35275,35276,35277,35278,35279,35280,35281,35282,35283,35284,35285,35286,35287,35288,35289,35290,35291,35292,35293,35294,35295,35296,35297,35298,35299,35300,35301,35302,35303,35304,35305,35306,35307,35308,35309,35310,35311,35312,35313,35314,35315,35316,35317,35318,35319,35320,35321,35322,35323,35324,35325,35326,35327,35328,35329,35330,35331,35332,35333,35334,35335,35336,35337,35338,35339,35340,35341,35342,35343,35344,35345,35346,35347,35348,35349,35350,35351,35352,35353,35354,35355,35356,35357,35358,35359,35360,35361,35362,35363,35364,35365,35366,35367,35368,35369,35370,35371,35372,35373,35374,35375,35376,35377,35378,35379,35380,35381,35382,35383,35384,35385,35386,35387,35388,35389,35390,35391,35392,35393,35394,35395,35396,35397,35398,35399,35400,35401,35402,35403,35404,35405,35406,35407,35408,35409,35410,35411,35412,35413,35414,35415,35416,35417,35418,35419,35420,35421,35422,35423,35424,35425,35426,35427,35428,35429,35430,35431,35432,35433,35434,35435,35436,35437,35438,35439,35440,35441,35442,35443,35444,35445,35446,35447,35448,35449,35450,35451,35452,35453,35454,35455,35456,35457,35458,35459,35460,35461,35462,35463,35464,35465,35466,35467,35468,35469,35470,35471,35472,35473,35474,35475,35476,35477,35478,35479,35480,35481,35482,35483,35484,35485,35486,35487,35488,35489,35490,35491,35492,35493,35494,35495,35496,35497,35498,35499,35500,35501,35502,35503,35504,35505,35506,35507,35508,35509,35510,35511,35512,35513,35514,35515,35516,35517,35518,35519,35520,35521,35522,35523,35524,35525,35526,35527,35528,35529,35530,35531,35532,35533,35534,35535,35536,35537,35538,35539,35540,35541,35542,35543,35544,35545,35546,35547,35548,35549,35550,35551,35552,35553,35554,35555,35556,35557,35558,35559,35560,35561,35562,35563,35564,35565,35566,35567,35568,35569,35570,35571,35572,35573,35574,35575,35576,35577,35578,35579,35580,35581,35582,35583,35584,35585,35586,35587,35588,35589,35590,35591,35592,35593,35594,35595,35596,35597,35598,35599,35600,35601,35602,35603,35604,35605,35606,35607,35608,35609,35610,35611,35612,35613,35614,35615,35616,35617,35618,35619,35620,35621,35622,35623,35624,35625,35626,35627,35628,35629,35630,35631,35632,35633,35634,35635,35636,35637,35638,35639,35640,35641,35642,35643,35644,35645,35646,35647,35648,35649,35650,35651,35652,35653,35654,35655,35656,35657,35658,35659,35660,35661,35662,35663,35664,35665,35666,35667,35668,35669,35670,35671,35672,35673,35674,35675,35676,35677,35678,35679,35680,35681,35682,35683,35684,35685,35686,35687,35688,35689,35690,35691,35692,35693,35694,35695,35696,35697,35698,35699,35700,35701,35702,35703,35704,35705,35706,35707,35708,35709,35710,35711,35712,35713,35714,35715,35716,35717,35718,35719,35720,35721,35722,35723,35724,35725,35726,35727,35728,35729,35730,35731,35732,35733,35734,35735,35736,35737,35738,35739,35740,35741,35742,35743,35744,35745,35746,35747,35748,35749,35750,35751,35752,35753,35754,35755,35756,35757,35758,35759,35760,35761,35762,35763,35764,35765,35766,35767,35768,35769,35770,35771,35772,35773,35774,35775,35776,35777,35778,35779,35780,35781,35782,35783,35784,35785,35786,35787,35788,35789,35790,35791,35792,35793,35794,35795,35796,35797,35798,35799,35800,35801,35802,35803,35804,35805,35806,35807,35808,35809,35810,35811,35812,35813,35814,35815,35816,35817,35818,35819,35820,35821,35822,35823,35824,35825,35826,35827,35828,35829,35830,35831,35832,35833,35834,35835,35836,35837,35838,35839,35840,35841,35842,35843,35844,35845,35846,35847,35848,35849,35850,35851,35852,35853,35854,35855,35856,35857,35858,35859,35860,35861,35862,35863,35864,35865,35866,35867,35868,35869,35870,35871,35872,35873,35874,35875,35876,35877,35878,35879,35880,35881,35882,35883,35884,35885,35886,35887,35888,35889,35890,35891,35892,35893,35894,35895,35896,35897,35898,35899,35900,35901,35902,35903,35904,35905,35906,35907,35908,35909,35910,35911,35912,35913,35914,35915,35916,35917,35918,35919,35920,35921,35922,35923,35924,35925,35926,35927,35928,35929,35930,35931,35932,35933,35934,35935,35936,35937,35938,35939,35940,35941,35942,35943,35944,35945,35946,35947,35948,35949,35950,35951,35952,35953,35954,35955,35956,35957,35958,35959,35960,35961,35962,35963,35964,35965,35966,35967,35968,35969,35970,35971,35972,35973,35974,35975,35976,35977,35978,35979,35980,35981,35982,35983,35984,35985,35986,35987,35988,35989,35990,35991,35992,35993,35994,35995,35996,35997,35998,35999,36000,36001,36002,36003,36004,36005,36006,36007,36008,36009,36010,36011,36012,36013,36014,36015,36016,36017,36018,36019,36020,36021,36022,36023,36024,36025,36026,36027,36028,36029,36030,36031,36032,36033,36034,36035,36036,36037,36038,36039,36040,36041,36042,36043,36044,36045,36046,36047,36048,36049,36050,36051,36052,36053,36054,36055,36056,36057,36058,36059,36060,36061,36062,36063,36064,36065,36066,36067,36068,36069,36070,36071,36072,36073,36074,36075,36076,36077,36078,36079,36080,36081,36082,36083,36084,36085,36086,36087,36088,36089,36090,36091,36092,36093,36094,36095,36096,36097,36098,36099,36100,36101,36102,36103,36104,36105,36106,36107,36108,36109,36110,36111,36112,36113,36114,36115,36116,36117,36118,36119,36120,36121,36122,36123,36124,36125,36126,36127,36128,36129,36130,36131,36132,36133,36134,36135,36136,36137,36138,36139,36140,36141,36142,36143,36144,36145,36146,36147,36148,36149,36150,36151,36152,36153,36154,36155,36156,36157,36158,36159,36160,36161,36162,36163,36164,36165,36166,36167,36168,36169,36170,36171,36172,36173,36174,36175,36176,36177,36178,36179,36180,36181,36182,36183,36184,36185,36186,36187,36188,36189,36190,36191,36192,36193,36194,36195,36196,36197,36198,36199,36200,36201,36202,36203,36204,36205,36206,36207,36208,36209,36210,36211,36212,36213,36214,36215,36216,36217,36218,36219,36220,36221,36222,36223,36224,36225,36226,36227,36228,36229,36230,36231,36232,36233,36234,36235,36236,36237,36238,36239,36240,36241,36242,36243,36244,36245,36246,36247,36248,36249,36250,36251,36252,36253,36254,36255,36256,36257,36258,36259,36260,36261,36262,36263,36264,36265,36266,36267,36268,36269,36270,36271,36272,36273,36274,36275,36276,36277,36278,36279,36280,36281,36282,36283,36284,36285,36286,36287,36288,36289,36290,36291,36292,36293,36294,36295,36296,36297,36298,36299,36300,36301,36302,36303,36304,36305,36306,36307,36308,36309,36310,36311,36312,36313,36314,36315,36316,36317,36318,36319,36320,36321,36322,36323,36324,36325,36326,36327,36328,36329,36330,36331,36332,36333,36334,36335,36336,36337,36338,36339,36340,36341,36342,36343,36344,36345,36346,36347,36348,36349,36350,36351,36352,36353,36354,36355,36356,36357,36358,36359,36360,36361,36362,36363,36364,36365,36366,36367,36368,36369,36370,36371,36372,36373,36374,36375,36376,36377,36378,36379,36380,36381,36382,36383,36384,36385,36386,36387,36388,36389,36390,36391,36392,36393,36394,36395,36396,36397,36398,36399,36400,36401,36402,36403,36404,36405,36406,36407,36408,36409,36410,36411,36412,36413,36414,36415,36416,36417,36418,36419,36420,36421,36422,36423,36424,36425,36426,36427,36428,36429,36430,36431,36432,36433,36434,36435,36436,36437,36438,36439,36440,36441,36442,36443,36444,36445,36446,36447,36448,36449,36450,36451,36452,36453,36454,36455,36456,36457,36458,36459,36460,36461,36462,36463,36464,36465,36466,36467,36468,36469,36470,36471,36472,36473,36474,36475,36476,36477,36478,36479,36480,36481,36482,36483,36484,36485,36486,36487,36488,36489,36490,36491,36492,36493,36494,36495,36496,36497,36498,36499,36500,36501,36502,36503,36504,36505,36506,36507,36508,36509,36510,36511,36512,36513,36514,36515,36516,36517,36518,36519,36520,36521,36522,36523,36524,36525,36526,36527,36528,36529,36530,36531,36532,36533,36534,36535,36536,36537,36538,36539,36540,36541,36542,36543,36544,36545,36546,36547,36548,36549,36550,36551,36552,36553,36554,36555,36556,36557,36558,36559,36560,36561,36562,36563,36564,36565,36566,36567,36568,36569,36570,36571,36572,36573,36574,36575,36576,36577,36578,36579,36580,36581,36582,36583,36584,36585,36586,36587,36588,36589,36590,36591,36592,36593,36594,36595,36596,36597,36598,36599,36600,36601,36602,36603,36604,36605,36606,36607,36608,36609,36610,36611,36612,36613,36614,36615,36616,36617,36618,36619,36620,36621,36622,36623,36624,36625,36626,36627,36628,36629,36630,36631,36632,36633,36634,36635,36636,36637,36638,36639,36640,36641,36642,36643,36644,36645,36646,36647,36648,36649,36650,36651,36652,36653,36654,36655,36656,36657,36658,36659,36660,36661,36662,36663,36664,36665,36666,36667,36668,36669,36670,36671,36672,36673,36674,36675,36676,36677,36678,36679,36680,36681,36682,36683,36684,36685,36686,36687,36688,36689,36690,36691,36692,36693,36694,36695,36696,36697,36698,36699,36700,36701,36702,36703,36704,36705,36706,36707,36708,36709,36710,36711,36712,36713,36714,36715,36716,36717,36718,36719,36720,36721,36722,36723,36724,36725,36726,36727,36728,36729,36730,36731,36732,36733,36734,36735,36736,36737,36738,36739,36740,36741,36742,36743,36744,36745,36746,36747,36748,36749,36750,36751,36752,36753,36754,36755,36756,36757,36758,36759,36760,36761,36762,36763,36764,36765,36766,36767,36768,36769,36770,36771,36772,36773,36774,36775,36776,36777,36778,36779,36780,36781,36782,36783,36784,36785,36786,36787,36788,36789,36790,36791,36792,36793,36794,36795,36796,36797,36798,36799,36800,36801,36802,36803,36804,36805,36806,36807,36808,36809,36810,36811,36812,36813,36814,36815,36816,36817,36818,36819,36820,36821,36822,36823,36824,36825,36826,36827,36828,36829,36830,36831,36832,36833,36834,36835,36836,36837,36838,36839,36840,36841,36842,36843,36844,36845,36846,36847,36848,36849,36850,36851,36852,36853,36854,36855,36856,36857,36858,36859,36860,36861,36862,36863,36864,36865,36866,36867,36868,36869,36870,36871,36872,36873,36874,36875,36876,36877,36878,36879,36880,36881,36882,36883,36884,36885,36886,36887,36888,36889,36890,36891,36892,36893,36894,36895,36896,36897,36898,36899,36900,36901,36902,36903,36904,36905,36906,36907,36908,36909,36910,36911,36912,36913,36914,36915,36916,36917,36918,36919,36920,36921,36922,36923,36924,36925,36926,36927,36928,36929,36930,36931,36932,36933,36934,36935,36936,36937,36938,36939,36940,36941,36942,36943,36944,36945,36946,36947,36948,36949,36950,36951,36952,36953,36954,36955,36956,36957,36958,36959,36960,36961,36962,36963,36964,36965,36966,36967,36968,36969,36970,36971,36972,36973,36974,36975,36976,36977,36978,36979,36980,36981,36982,36983,36984,36985,36986,36987,36988,36989,36990,36991,36992,36993,36994,36995,36996,36997,36998,36999,37000,37001,37002,37003,37004,37005,37006,37007,37008,37009,37010,37011,37012,37013,37014,37015,37016,37017,37018,37019,37020,37021,37022,37023,37024,37025,37026,37027,37028,37029,37030,37031,37032,37033,37034,37035,37036,37037,37038,37039,37040,37041,37042,37043,37044,37045,37046,37047,37048,37049,37050,37051,37052,37053,37054,37055,37056,37057,37058,37059,37060,37061,37062,37063,37064,37065,37066,37067,37068,37069,37070,37071,37072,37073,37074,37075,37076,37077,37078,37079,37080,37081,37082,37083,37084,37085,37086,37087,37088,37089,37090,37091,37092,37093,37094,37095,37096,37097,37098,37099,37100,37101,37102,37103,37104,37105,37106,37107,37108,37109,37110,37111,37112,37113,37114,37115,37116,37117,37118,37119,37120,37121,37122,37123,37124,37125,37126,37127,37128,37129,37130,37131,37132,37133,37134,37135,37136,37137,37138,37139,37140,37141,37142,37143,37144,37145,37146,37147,37148,37149,37150,37151,37152,37153,37154,37155,37156,37157,37158,37159,37160,37161,37162,37163,37164,37165,37166,37167,37168,37169,37170,37171,37172,37173,37174,37175,37176,37177,37178,37179,37180,37181,37182,37183,37184,37185,37186,37187,37188,37189,37190,37191,37192,37193,37194,37195,37196,37197,37198,37199,37200,37201,37202,37203,37204,37205,37206,37207,37208,37209,37210,37211,37212,37213,37214,37215,37216,37217,37218,37219,37220,37221,37222,37223,37224,37225,37226,37227,37228,37229,37230,37231,37232,37233,37234,37235,37236,37237,37238,37239,37240,37241,37242,37243,37244,37245,37246,37247,37248,37249,37250,37251,37252,37253,37254,37255,37256,37257,37258,37259,37260,37261,37262,37263,37264,37265,37266,37267,37268,37269,37270,37271,37272,37273,37274,37275,37276,37277,37278,37279,37280,37281,37282,37283,37284,37285,37286,37287,37288,37289,37290,37291,37292,37293,37294,37295,37296,37297,37298,37299,37300,37301,37302,37303,37304,37305,37306,37307,37308,37309,37310,37311,37312,37313,37314,37315,37316,37317,37318,37319,37320,37321,37322,37323,37324,37325,37326,37327,37328,37329,37330,37331,37332,37333,37334,37335,37336,37337,37338,37339,37340,37341,37342,37343,37344,37345,37346,37347,37348,37349,37350,37351,37352,37353,37354,37355,37356,37357,37358,37359,37360,37361,37362,37363,37364,37365,37366,37367,37368,37369,37370,37371,37372,37373,37374,37375,37376,37377,37378,37379,37380,37381,37382,37383,37384,37385,37386,37387,37388,37389,37390,37391,37392,37393,37394,37395,37396,37397,37398,37399,37400,37401,37402,37403,37404,37405,37406,37407,37408,37409,37410,37411,37412,37413,37414,37415,37416,37417,37418,37419,37420,37421,37422,37423,37424,37425,37426,37427,37428,37429,37430,37431,37432,37433,37434,37435,37436,37437,37438,37439,37440,37441,37442,37443,37444,37445,37446,37447,37448,37449,37450,37451,37452,37453,37454,37455,37456,37457,37458,37459,37460,37461,37462,37463,37464,37465,37466,37467,37468,37469,37470,37471,37472,37473,37474,37475,37476,37477,37478,37479,37480,37481,37482,37483,37484,37485,37486,37487,37488,37489,37490,37491,37492,37493,37494,37495,37496,37497,37498,37499,37500,37501,37502,37503,37504,37505,37506,37507,37508,37509,37510,37511,37512,37513,37514,37515,37516,37517,37518,37519,37520,37521,37522,37523,37524,37525,37526,37527,37528,37529,37530,37531,37532,37533,37534,37535,37536,37537,37538,37539,37540,37541,37542,37543,37544,37545,37546,37547,37548,37549,37550,37551,37552,37553,37554,37555,37556,37557,37558,37559,37560,37561,37562,37563,37564,37565,37566,37567,37568,37569,37570,37571,37572,37573,37574,37575,37576,37577,37578,37579,37580,37581,37582,37583,37584,37585,37586,37587,37588,37589,37590,37591,37592,37593,37594,37595,37596,37597,37598,37599,37600,37601,37602,37603,37604,37605,37606,37607,37608,37609,37610,37611,37612,37613,37614,37615,37616,37617,37618,37619,37620,37621,37622,37623,37624,37625,37626,37627,37628,37629,37630,37631,37632,37633,37634,37635,37636,37637,37638,37639,37640,37641,37642,37643,37644,37645,37646,37647,37648,37649,37650,37651,37652,37653,37654,37655,37656,37657,37658,37659,37660,37661,37662,37663,37664,37665,37666,37667,37668,37669,37670,37671,37672,37673,37674,37675,37676,37677,37678,37679,37680,37681,37682,37683,37684,37685,37686,37687,37688,37689,37690,37691,37692,37693,37694,37695,37696,37697,37698,37699,37700,37701,37702,37703,37704,37705,37706,37707,37708,37709,37710,37711,37712,37713,37714,37715,37716,37717,37718,37719,37720,37721,37722,37723,37724,37725,37726,37727,37728,37729,37730,37731,37732,37733,37734,37735,37736,37737,37738,37739,37740,37741,37742,37743,37744,37745,37746,37747,37748,37749,37750,37751,37752,37753,37754,37755,37756,37757,37758,37759,37760,37761,37762,37763,37764,37765,37766,37767,37768,37769,37770,37771,37772,37773,37774,37775,37776,37777,37778,37779,37780,37781,37782,37783,37784,37785,37786,37787,37788,37789,37790,37791,37792,37793,37794,37795,37796,37797,37798,37799,37800,37801,37802,37803,37804,37805,37806,37807,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,37822,37823,37824,37825,37826,37827,37828,37829,37830,37831,37832,37833,37834,37835,37836,37837,37838,37839,37840,37841,37842,37843,37844,37845,37846,37847,37848,37849,37850,37851,37852,37853,37854,37855,37856,37857,37858,37859,37860,37861,37862,37863,37864,37865,37866,37867,37868,37869,37870,37871,37872,37873,37874,37875,37876,37877,37878,37879,37880,37881,37882,37883,37884,37885,37886,37887,37888,37889,37890,37891,37892,37893,37894,37895,37896,37897,37898,37899,37900,37901,37902,37903,37904,37905,37906,37907,37908,37909,37910,37911,37912,37913,37914,37915,37916,37917,37918,37919,37920,37921,37922,37923,37924,37925,37926,37927,37928,37929,37930,37931,37932,37933,37934,37935,37936,37937,37938,37939,37940,37941,37942,37943,37944,37945,37946,37947,37948,37949,37950,37951,37952,37953,37954,37955,37956,37957,37958,37959,37960,37961,37962,37963,37964,37965,37966,37967,37968,37969,37970,37971,37972,37973,37974,37975,37976,37977,37978,37979,37980,37981,37982,37983,37984,37985,37986,37987,37988,37989,37990,37991,37992,37993,37994,37995,37996,37997,37998,37999,38000,38001,38002,38003,38004,38005,38006,38007,38008,38009,38010,38011,38012,38013,38014,38015,38016,38017,38018,38019,38020,38021,38022,38023,38024,38025,38026,38027,38028,38029,38030,38031,38032,38033,38034,38035,38036,38037,38038,38039,38040,38041,38042,38043,38044,38045,38046,38047,38048,38049,38050,38051,38052,38053,38054,38055,38056,38057,38058,38059,38060,38061,38062,38063,38064,38065,38066,38067,38068,38069,38070,38071,38072,38073,38074,38075,38076,38077,38078,38079,38080,38081,38082,38083,38084,38085,38086,38087,38088,38089,38090,38091,38092,38093,38094,38095,38096,38097,38098,38099,38100,38101,38102,38103,38104,38105,38106,38107,38108,38109,38110,38111,38112,38113,38114,38115,38116,38117,38118,38119,38120,38121,38122,38123,38124,38125,38126,38127,38128,38129,38130,38131,38132,38133,38134,38135,38136,38137,38138,38139,38140,38141,38142,38143,38144,38145,38146,38147,38148,38149,38150,38151,38152,38153,38154,38155,38156,38157,38158,38159,38160,38161,38162,38163,38164,38165,38166,38167,38168,38169,38170,38171,38172,38173,38174,38175,38176,38177,38178,38179,38180,38181,38182,38183,38184,38185,38186,38187,38188,38189,38190,38191,38192,38193,38194,38195,38196,38197,38198,38199,38200,38201,38202,38203,38204,38205,38206,38207,38208,38209,38210,38211,38212,38213,38214,38215,38216,38217,38218,38219,38220,38221,38222,38223,38224,38225,38226,38227,38228,38229,38230,38231,38232,38233,38234,38235,38236,38237,38238,38239,38240,38241,38242,38243,38244,38245,38246,38247,38248,38249,38250,38251,38252,38253,38254,38255,38256,38257,38258,38259,38260,38261,38262,38263,38264,38265,38266,38267,38268,38269,38270,38271,38272,38273,38274,38275,38276,38277,38278,38279,38280,38281,38282,38283,38284,38285,38286,38287,38288,38289,38290,38291,38292,38293,38294,38295,38296,38297,38298,38299,38300,38301,38302,38303,38304,38305,38306,38307,38308,38309,38310,38311,38312,38313,38314,38315,38316,38317,38318,38319,38320,38321,38322,38323,38324,38325,38326,38327,38328,38329,38330,38331,38332,38333,38334,38335,38336,38337,38338,38339,38340,38341,38342,38343,38344,38345,38346,38347,38348,38349,38350,38351,38352,38353,38354,38355,38356,38357,38358,38359,38360,38361,38362,38363,38364,38365,38366,38367,38368,38369,38370,38371,38372,38373,38374,38375,38376,38377,38378,38379,38380,38381,38382,38383,38384,38385,38386,38387,38388,38389,38390,38391,38392,38393,38394,38395,38396,38397,38398,38399,38400,38401,38402,38403,38404,38405,38406,38407,38408,38409,38410,38411,38412,38413,38414,38415,38416,38417,38418,38419,38420,38421,38422,38423,38424,38425,38426,38427,38428,38429,38430,38431,38432,38433,38434,38435,38436,38437,38438,38439,38440,38441,38442,38443,38444,38445,38446,38447,38448,38449,38450,38451,38452,38453,38454,38455,38456,38457,38458,38459,38460,38461,38462,38463,38464,38465,38466,38467,38468,38469,38470,38471,38472,38473,38474,38475,38476,38477,38478,38479,38480,38481,38482,38483,38484,38485,38486,38487,38488,38489,38490,38491,38492,38493,38494,38495,38496,38497,38498,38499,38500,38501,38502,38503,38504,38505,38506,38507,38508,38509,38510,38511,38512,38513,38514,38515,38516,38517,38518,38519,38520,38521,38522,38523,38524,38525,38526,38527,38528,38529,38530,38531,38532,38533,38534,38535,38536,38537,38538,38539,38540,38541,38542,38543,38544,38545,38546,38547,38548,38549,38550,38551,38552,38553,38554,38555,38556,38557,38558,38559,38560,38561,38562,38563,38564,38565,38566,38567,38568,38569,38570,38571,38572,38573,38574,38575,38576,38577,38578,38579,38580,38581,38582,38583,38584,38585,38586,38587,38588,38589,38590,38591,38592,38593,38594,38595,38596,38597,38598,38599,38600,38601,38602,38603,38604,38605,38606,38607,38608,38609,38610,38611,38612,38613,38614,38615,38616,38617,38618,38619,38620,38621,38622,38623,38624,38625,38626,38627,38628,38629,38630,38631,38632,38633,38634,38635,38636,38637,38638,38639,38640,38641,38642,38643,38644,38645,38646,38647,38648,38649,38650,38651,38652,38653,38654,38655,38656,38657,38658,38659,38660,38661,38662,38663,38664,38665,38666,38667,38668,38669,38670,38671,38672,38673,38674,38675,38676,38677,38678,38679,38680,38681,38682,38683,38684,38685,38686,38687,38688,38689,38690,38691,38692,38693,38694,38695,38696,38697,38698,38699,38700,38701,38702,38703,38704,38705,38706,38707,38708,38709,38710,38711,38712,38713,38714,38715,38716,38717,38718,38719,38720,38721,38722,38723,38724,38725,38726,38727,38728,38729,38730,38731,38732,38733,38734,38735,38736,38737,38738,38739,38740,38741,38742,38743,38744,38745,38746,38747,38748,38749,38750,38751,38752,38753,38754,38755,38756,38757,38758,38759,38760,38761,38762,38763,38764,38765,38766,38767,38768,38769,38770,38771,38772,38773,38774,38775,38776,38777,38778,38779,38780,38781,38782,38783,38784,38785,38786,38787,38788,38789,38790,38791,38792,38793,38794,38795,38796,38797,38798,38799,38800,38801,38802,38803,38804,38805,38806,38807,38808,38809,38810,38811,38812,38813,38814,38815,38816,38817,38818,38819,38820,38821,38822,38823,38824,38825,38826,38827,38828,38829,38830,38831,38832,38833,38834,38835,38836,38837,38838,38839,38840,38841,38842,38843,38844,38845,38846,38847,38848,38849,38850,38851,38852,38853,38854,38855,38856,38857,38858,38859,38860,38861,38862,38863,38864,38865,38866,38867,38868,38869,38870,38871,38872,38873,38874,38875,38876,38877,38878,38879,38880,38881,38882,38883,38884,38885,38886,38887,38888,38889,38890,38891,38892,38893,38894,38895,38896,38897,38898,38899,38900,38901,38902,38903,38904,38905,38906,38907,38908,38909,38910,38911,38912,38913,38914,38915,38916,38917,38918,38919,38920,38921,38922,38923,38924,38925,38926,38927,38928,38929,38930,38931,38932,38933,38934,38935,38936,38937,38938,38939,38940,38941,38942,38943,38944,38945,38946,38947,38948,38949,38950,38951,38952,38953,38954,38955,38956,38957,38958,38959,38960,38961,38962,38963,38964,38965,38966,38967,38968,38969,38970,38971,38972,38973,38974,38975,38976,38977,38978,38979,38980,38981,38982,38983,38984,38985,38986,38987,38988,38989,38990,38991,38992,38993,38994,38995,38996,38997,38998,38999,39000,39001,39002,39003,39004,39005,39006,39007,39008,39009,39010,39011,39012,39013,39014,39015,39016,39017,39018,39019,39020,39021,39022,39023,39024,39025,39026,39027,39028,39029,39030,39031,39032,39033,39034,39035,39036,39037,39038,39039,39040,39041,39042,39043,39044,39045,39046,39047,39048,39049,39050,39051,39052,39053,39054,39055,39056,39057,39058,39059,39060,39061,39062,39063,39064,39065,39066,39067,39068,39069,39070,39071,39072,39073,39074,39075,39076,39077,39078,39079,39080,39081,39082,39083,39084,39085,39086,39087,39088,39089,39090,39091,39092,39093,39094,39095,39096,39097,39098,39099,39100,39101,39102,39103,39104,39105,39106,39107,39108,39109,39110,39111,39112,39113,39114,39115,39116,39117,39118,39119,39120,39121,39122,39123,39124,39125,39126,39127,39128,39129,39130,39131,39132,39133,39134,39135,39136,39137,39138,39139,39140,39141,39142,39143,39144,39145,39146,39147,39148,39149,39150,39151,39152,39153,39154,39155,39156,39157,39158,39159,39160,39161,39162,39163,39164,39165,39166,39167,39168,39169,39170,39171,39172,39173,39174,39175,39176,39177,39178,39179,39180,39181,39182,39183,39184,39185,39186,39187,39188,39189,39190,39191,39192,39193,39194,39195,39196,39197,39198,39199,39200,39201,39202,39203,39204,39205,39206,39207,39208,39209,39210,39211,39212,39213,39214,39215,39216,39217,39218,39219,39220,39221,39222,39223,39224,39225,39226,39227,39228,39229,39230,39231,39232,39233,39234,39235,39236,39237,39238,39239,39240,39241,39242,39243,39244,39245,39246,39247,39248,39249,39250,39251,39252,39253,39254,39255,39256,39257,39258,39259,39260,39261,39262,39263,39264,39265,39266,39267,39268,39269,39270,39271,39272,39273,39274,39275,39276,39277,39278,39279,39280,39281,39282,39283,39284,39285,39286,39287,39288,39289,39290,39291,39292,39293,39294,39295,39296,39297,39298,39299,39300,39301,39302,39303,39304,39305,39306,39307,39308,39309,39310,39311,39312,39313,39314,39315,39316,39317,39318,39319,39320,39321,39322,39323,39324,39325,39326,39327,39328,39329,39330,39331,39332,39333,39334,39335,39336,39337,39338,39339,39340,39341,39342,39343,39344,39345,39346,39347,39348,39349,39350,39351,39352,39353,39354,39355,39356,39357,39358,39359,39360,39361,39362,39363,39364,39365,39366,39367,39368,39369,39370,39371,39372,39373,39374,39375,39376,39377,39378,39379,39380,39381,39382,39383,39384,39385,39386,39387,39388,39389,39390,39391,39392,39393,39394,39395,39396,39397,39398,39399,39400,39401,39402,39403,39404,39405,39406,39407,39408,39409,39410,39411,39412,39413,39414,39415,39416,39417,39418,39419,39420,39421,39422,39423,39424,39425,39426,39427,39428,39429,39430,39431,39432,39433,39434,39435,39436,39437,39438,39439,39440,39441,39442,39443,39444,39445,39446,39447,39448,39449,39450,39451,39452,39453,39454,39455,39456,39457,39458,39459,39460,39461,39462,39463,39464,39465,39466,39467,39468,39469,39470,39471,39472,39473,39474,39475,39476,39477,39478,39479,39480,39481,39482,39483,39484,39485,39486,39487,39488,39489,39490,39491,39492,39493,39494,39495,39496,39497,39498,39499,39500,39501,39502,39503,39504,39505,39506,39507,39508,39509,39510,39511,39512,39513,39514,39515,39516,39517,39518,39519,39520,39521,39522,39523,39524,39525,39526,39527,39528,39529,39530,39531,39532,39533,39534,39535,39536,39537,39538,39539,39540,39541,39542,39543,39544,39545,39546,39547,39548,39549,39550,39551,39552,39553,39554,39555,39556,39557,39558,39559,39560,39561,39562,39563,39564,39565,39566,39567,39568,39569,39570,39571,39572,39573,39574,39575,39576,39577,39578,39579,39580,39581,39582,39583,39584,39585,39586,39587,39588,39589,39590,39591,39592,39593,39594,39595,39596,39597,39598,39599,39600,39601,39602,39603,39604,39605,39606,39607,39608,39609,39610,39611,39612,39613,39614,39615,39616,39617,39618,39619,39620,39621,39622,39623,39624,39625,39626,39627,39628,39629,39630,39631,39632,39633,39634,39635,39636,39637,39638,39639,39640,39641,39642,39643,39644,39645,39646,39647,39648,39649,39650,39651,39652,39653,39654,39655,39656,39657,39658,39659,39660,39661,39662,39663,39664,39665,39666,39667,39668,39669,39670,39671,39672,39673,39674,39675,39676,39677,39678,39679,39680,39681,39682,39683,39684,39685,39686,39687,39688,39689,39690,39691,39692,39693,39694,39695,39696,39697,39698,39699,39700,39701,39702,39703,39704,39705,39706,39707,39708,39709,39710,39711,39712,39713,39714,39715,39716,39717,39718,39719,39720,39721,39722,39723,39724,39725,39726,39727,39728,39729,39730,39731,39732,39733,39734,39735,39736,39737,39738,39739,39740,39741,39742,39743,39744,39745,39746,39747,39748,39749,39750,39751,39752,39753,39754,39755,39756,39757,39758,39759,39760,39761,39762,39763,39764,39765,39766,39767,39768,39769,39770,39771,39772,39773,39774,39775,39776,39777,39778,39779,39780,39781,39782,39783,39784,39785,39786,39787,39788,39789,39790,39791,39792,39793,39794,39795,39796,39797,39798,39799,39800,39801,39802,39803,39804,39805,39806,39807,39808,39809,39810,39811,39812,39813,39814,39815,39816,39817,39818,39819,39820,39821,39822,39823,39824,39825,39826,39827,39828,39829,39830,39831,39832,39833,39834,39835,39836,39837,39838,39839,39840,39841,39842,39843,39844,39845,39846,39847,39848,39849,39850,39851,39852,39853,39854,39855,39856,39857,39858,39859,39860,39861,39862,39863,39864,39865,39866,39867,39868,39869,39870,39871,39872,39873,39874,39875,39876,39877,39878,39879,39880,39881,39882,39883,39884,39885,39886,39887,39888,39889,39890,39891,39892,39893,39894,39895,39896,39897,39898,39899,39900,39901,39902,39903,39904,39905,39906,39907,39908,39909,39910,39911,39912,39913,39914,39915,39916,39917,39918,39919,39920,39921,39922,39923,39924,39925,39926,39927,39928,39929,39930,39931,39932,39933,39934,39935,39936,39937,39938,39939,39940,39941,39942,39943,39944,39945,39946,39947,39948,39949,39950,39951,39952,39953,39954,39955,39956,39957,39958,39959,39960,39961,39962,39963,39964,39965,39966,39967,39968,39969,39970,39971,39972,39973,39974,39975,39976,39977,39978,39979,39980,39981,39982,39983,39984,39985,39986,39987,39988,39989,39990,39991,39992,39993,39994,39995,39996,39997,39998,39999,40000,40001,40002,40003,40004,40005,40006,40007,40008,40009,40010,40011,40012,40013,40014,40015,40016,40017,40018,40019,40020,40021,40022,40023,40024,40025,40026,40027,40028,40029,40030,40031,40032,40033,40034,40035,40036,40037,40038,40039,40040,40041,40042,40043,40044,40045,40046,40047,40048,40049,40050,40051,40052,40053,40054,40055,40056,40057,40058,40059,40060,40061,40062,40063,40064,40065,40066,40067,40068,40069,40070,40071,40072,40073,40074,40075,40076,40077,40078,40079,40080,40081,40082,40083,40084,40085,40086,40087,40088,40089,40090,40091,40092,40093,40094,40095,40096,40097,40098,40099,40100,40101,40102,40103,40104,40105,40106,40107,40108,40109,40110,40111,40112,40113,40114,40115,40116,40117,40118,40119,40120,40121,40122,40123,40124,40125,40126,40127,40128,40129,40130,40131,40132,40133,40134,40135,40136,40137,40138,40139,40140,40141,40142,40143,40144,40145,40146,40147,40148,40149,40150,40151,40152,40153,40154,40155,40156,40157,40158,40159,40160,40161,40162,40163,40164,40165,40166,40167,40168,40169,40170,40171,40172,40173,40174,40175,40176,40177,40178,40179,40180,40181,40182,40183,40184,40185,40186,40187,40188,40189,40190,40191,40192,40193,40194,40195,40196,40197,40198,40199,40200,40201,40202,40203,40204,40205,40206,40207,40208,40209,40210,40211,40212,40213,40214,40215,40216,40217,40218,40219,40220,40221,40222,40223,40224,40225,40226,40227,40228,40229,40230,40231,40232,40233,40234,40235,40236,40237,40238,40239,40240,40241,40242,40243,40244,40245,40246,40247,40248,40249,40250,40251,40252,40253,40254,40255,40256,40257,40258,40259,40260,40261,40262,40263,40264,40265,40266,40267,40268,40269,40270,40271,40272,40273,40274,40275,40276,40277,40278,40279,40280,40281,40282,40283,40284,40285,40286,40287,40288,40289,40290,40291,40292,40293,40294,40295,40296,40297,40298,40299,40300,40301,40302,40303,40304,40305,40306,40307,40308,40309,40310,40311,40312,40313,40314,40315,40316,40317,40318,40319,40320,40321,40322,40323,40324,40325,40326,40327,40328,40329,40330,40331,40332,40333,40334,40335,40336,40337,40338,40339,40340,40341,40342,40343,40344,40345,40346,40347,40348,40349,40350,40351,40352,40353,40354,40355,40356,40357,40358,40359,40360,40361,40362,40363,40364,40365,40366,40367,40368,40369,40370,40371,40372,40373,40374,40375,40376,40377,40378,40379,40380,40381,40382,40383,40384,40385,40386,40387,40388,40389,40390,40391,40392,40393,40394,40395,40396,40397,40398,40399,40400,40401,40402,40403,40404,40405,40406,40407,40408,40409,40410,40411,40412,40413,40414,40415,40416,40417,40418,40419,40420,40421,40422,40423,40424,40425,40426,40427,40428,40429,40430,40431,40432,40433,40434,40435,40436,40437,40438,40439,40440,40441,40442,40443,40444,40445,40446,40447,40448,40449,40450,40451,40452,40453,40454,40455,40456,40457,40458,40459,40460,40461,40462,40463,40464,40465,40466,40467,40468,40469,40470,40471,40472,40473,40474,40475,40476,40477,40478,40479,40480,40481,40482,40483,40484,40485,40486,40487,40488,40489,40490,40491,40492,40493,40494,40495,40496,40497,40498,40499,40500,40501,40502,40503,40504,40505,40506,40507,40508,40509,40510,40511,40512,40513,40514,40515,40516,40517,40518,40519,40520,40521,40522,40523,40524,40525,40526,40527,40528,40529,40530,40531,40532,40533,40534,40535,40536,40537,40538,40539,40540,40541,40542,40543,40544,40545,40546,40547,40548,40549,40550,40551,40552,40553,40554,40555,40556,40557,40558,40559,40560,40561,40562,40563,40564,40565,40566,40567,40568,40569,40570,40571,40572,40573,40574,40575,40576,40577,40578,40579,40580,40581,40582,40583,40584,40585,40586,40587,40588,40589,40590,40591,40592,40593,40594,40595,40596,40597,40598,40599,40600,40601,40602,40603,40604,40605,40606,40607,40608,40609,40610,40611,40612,40613,40614,40615,40616,40617,40618,40619,40620,40621,40622,40623,40624,40625,40626,40627,40628,40629,40630,40631,40632,40633,40634,40635,40636,40637,40638,40639,40640,40641,40642,40643,40644,40645,40646,40647,40648,40649,40650,40651,40652,40653,40654,40655,40656,40657,40658,40659,40660,40661,40662,40663,40664,40665,40666,40667,40668,40669,40670,40671,40672,40673,40674,40675,40676,40677,40678,40679,40680,40681,40682,40683,40684,40685,40686,40687,40688,40689,40690,40691,40692,40693,40694,40695,40696,40697,40698,40699,40700,40701,40702,40703,40704,40705,40706,40707,40708,40709,40710,40711,40712,40713,40714,40715,40716,40717,40718,40719,40720,40721,40722,40723,40724,40725,40726,40727,40728,40729,40730,40731,40732,40733,40734,40735,40736,40737,40738,40739,40740,40741,40742,40743,40744,40745,40746,40747,40748,40749,40750,40751,40752,40753,40754,40755,40756,40757,40758,40759,40760,40761,40762,40763,40764,40765,40766,40767,40768,40769,40770,40771,40772,40773,40774,40775,40776,40777,40778,40779,40780,40781,40782,40783,40784,40785,40786,40787,40788,40789,40790,40791,40792,40793,40794,40795,40796,40797,40798,40799,40800,40801,40802,40803,40804,40805,40806,40807,40808,40809,40810,40811,40812,40813,40814,40815,40816,40817,40818,40819,40820,40821,40822,40823,40824,40825,40826,40827,40828,40829,40830,40831,40832,40833,40834,40835,40836,40837,40838,40839,40840,40841,40842,40843,40844,40845,40846,40847,40848,40849,40850,40851,40852,40853,40854,40855,40856,40857,40858,40859,40860,40861,40862,40863,40864,40865,40866,40867,40868,40869,40870,40871,40872,40873,40874,40875,40876,40877,40878,40879,40880,40881,40882,40883,40884,40885,40886,40887,40888,40889,40890,40891,40892,40893,40894,40895,40896,40897,40898,40899,40900,40901,40902,40903,40904,40905,40906,40907,40908,40909,40910,40911,40912,40913,40914,40915,40916,40917,40918,40919,40920,40921,40922,40923,40924,40925,40926,40927,40928,40929,40930,40931,40932,40933,40934,40935,40936,40937,40938,40939,40940,40941,40942,40943,40960,40961,40962,40963,40964,40965,40966,40967,40968,40969,40970,40971,40972,40973,40974,40975,40976,40977,40978,40979,40980,40981,40982,40983,40984,40985,40986,40987,40988,40989,40990,40991,40992,40993,40994,40995,40996,40997,40998,40999,41000,41001,41002,41003,41004,41005,41006,41007,41008,41009,41010,41011,41012,41013,41014,41015,41016,41017,41018,41019,41020,41021,41022,41023,41024,41025,41026,41027,41028,41029,41030,41031,41032,41033,41034,41035,41036,41037,41038,41039,41040,41041,41042,41043,41044,41045,41046,41047,41048,41049,41050,41051,41052,41053,41054,41055,41056,41057,41058,41059,41060,41061,41062,41063,41064,41065,41066,41067,41068,41069,41070,41071,41072,41073,41074,41075,41076,41077,41078,41079,41080,41081,41082,41083,41084,41085,41086,41087,41088,41089,41090,41091,41092,41093,41094,41095,41096,41097,41098,41099,41100,41101,41102,41103,41104,41105,41106,41107,41108,41109,41110,41111,41112,41113,41114,41115,41116,41117,41118,41119,41120,41121,41122,41123,41124,41125,41126,41127,41128,41129,41130,41131,41132,41133,41134,41135,41136,41137,41138,41139,41140,41141,41142,41143,41144,41145,41146,41147,41148,41149,41150,41151,41152,41153,41154,41155,41156,41157,41158,41159,41160,41161,41162,41163,41164,41165,41166,41167,41168,41169,41170,41171,41172,41173,41174,41175,41176,41177,41178,41179,41180,41181,41182,41183,41184,41185,41186,41187,41188,41189,41190,41191,41192,41193,41194,41195,41196,41197,41198,41199,41200,41201,41202,41203,41204,41205,41206,41207,41208,41209,41210,41211,41212,41213,41214,41215,41216,41217,41218,41219,41220,41221,41222,41223,41224,41225,41226,41227,41228,41229,41230,41231,41232,41233,41234,41235,41236,41237,41238,41239,41240,41241,41242,41243,41244,41245,41246,41247,41248,41249,41250,41251,41252,41253,41254,41255,41256,41257,41258,41259,41260,41261,41262,41263,41264,41265,41266,41267,41268,41269,41270,41271,41272,41273,41274,41275,41276,41277,41278,41279,41280,41281,41282,41283,41284,41285,41286,41287,41288,41289,41290,41291,41292,41293,41294,41295,41296,41297,41298,41299,41300,41301,41302,41303,41304,41305,41306,41307,41308,41309,41310,41311,41312,41313,41314,41315,41316,41317,41318,41319,41320,41321,41322,41323,41324,41325,41326,41327,41328,41329,41330,41331,41332,41333,41334,41335,41336,41337,41338,41339,41340,41341,41342,41343,41344,41345,41346,41347,41348,41349,41350,41351,41352,41353,41354,41355,41356,41357,41358,41359,41360,41361,41362,41363,41364,41365,41366,41367,41368,41369,41370,41371,41372,41373,41374,41375,41376,41377,41378,41379,41380,41381,41382,41383,41384,41385,41386,41387,41388,41389,41390,41391,41392,41393,41394,41395,41396,41397,41398,41399,41400,41401,41402,41403,41404,41405,41406,41407,41408,41409,41410,41411,41412,41413,41414,41415,41416,41417,41418,41419,41420,41421,41422,41423,41424,41425,41426,41427,41428,41429,41430,41431,41432,41433,41434,41435,41436,41437,41438,41439,41440,41441,41442,41443,41444,41445,41446,41447,41448,41449,41450,41451,41452,41453,41454,41455,41456,41457,41458,41459,41460,41461,41462,41463,41464,41465,41466,41467,41468,41469,41470,41471,41472,41473,41474,41475,41476,41477,41478,41479,41480,41481,41482,41483,41484,41485,41486,41487,41488,41489,41490,41491,41492,41493,41494,41495,41496,41497,41498,41499,41500,41501,41502,41503,41504,41505,41506,41507,41508,41509,41510,41511,41512,41513,41514,41515,41516,41517,41518,41519,41520,41521,41522,41523,41524,41525,41526,41527,41528,41529,41530,41531,41532,41533,41534,41535,41536,41537,41538,41539,41540,41541,41542,41543,41544,41545,41546,41547,41548,41549,41550,41551,41552,41553,41554,41555,41556,41557,41558,41559,41560,41561,41562,41563,41564,41565,41566,41567,41568,41569,41570,41571,41572,41573,41574,41575,41576,41577,41578,41579,41580,41581,41582,41583,41584,41585,41586,41587,41588,41589,41590,41591,41592,41593,41594,41595,41596,41597,41598,41599,41600,41601,41602,41603,41604,41605,41606,41607,41608,41609,41610,41611,41612,41613,41614,41615,41616,41617,41618,41619,41620,41621,41622,41623,41624,41625,41626,41627,41628,41629,41630,41631,41632,41633,41634,41635,41636,41637,41638,41639,41640,41641,41642,41643,41644,41645,41646,41647,41648,41649,41650,41651,41652,41653,41654,41655,41656,41657,41658,41659,41660,41661,41662,41663,41664,41665,41666,41667,41668,41669,41670,41671,41672,41673,41674,41675,41676,41677,41678,41679,41680,41681,41682,41683,41684,41685,41686,41687,41688,41689,41690,41691,41692,41693,41694,41695,41696,41697,41698,41699,41700,41701,41702,41703,41704,41705,41706,41707,41708,41709,41710,41711,41712,41713,41714,41715,41716,41717,41718,41719,41720,41721,41722,41723,41724,41725,41726,41727,41728,41729,41730,41731,41732,41733,41734,41735,41736,41737,41738,41739,41740,41741,41742,41743,41744,41745,41746,41747,41748,41749,41750,41751,41752,41753,41754,41755,41756,41757,41758,41759,41760,41761,41762,41763,41764,41765,41766,41767,41768,41769,41770,41771,41772,41773,41774,41775,41776,41777,41778,41779,41780,41781,41782,41783,41784,41785,41786,41787,41788,41789,41790,41791,41792,41793,41794,41795,41796,41797,41798,41799,41800,41801,41802,41803,41804,41805,41806,41807,41808,41809,41810,41811,41812,41813,41814,41815,41816,41817,41818,41819,41820,41821,41822,41823,41824,41825,41826,41827,41828,41829,41830,41831,41832,41833,41834,41835,41836,41837,41838,41839,41840,41841,41842,41843,41844,41845,41846,41847,41848,41849,41850,41851,41852,41853,41854,41855,41856,41857,41858,41859,41860,41861,41862,41863,41864,41865,41866,41867,41868,41869,41870,41871,41872,41873,41874,41875,41876,41877,41878,41879,41880,41881,41882,41883,41884,41885,41886,41887,41888,41889,41890,41891,41892,41893,41894,41895,41896,41897,41898,41899,41900,41901,41902,41903,41904,41905,41906,41907,41908,41909,41910,41911,41912,41913,41914,41915,41916,41917,41918,41919,41920,41921,41922,41923,41924,41925,41926,41927,41928,41929,41930,41931,41932,41933,41934,41935,41936,41937,41938,41939,41940,41941,41942,41943,41944,41945,41946,41947,41948,41949,41950,41951,41952,41953,41954,41955,41956,41957,41958,41959,41960,41961,41962,41963,41964,41965,41966,41967,41968,41969,41970,41971,41972,41973,41974,41975,41976,41977,41978,41979,41980,41981,41982,41983,41984,41985,41986,41987,41988,41989,41990,41991,41992,41993,41994,41995,41996,41997,41998,41999,42000,42001,42002,42003,42004,42005,42006,42007,42008,42009,42010,42011,42012,42013,42014,42015,42016,42017,42018,42019,42020,42021,42022,42023,42024,42025,42026,42027,42028,42029,42030,42031,42032,42033,42034,42035,42036,42037,42038,42039,42040,42041,42042,42043,42044,42045,42046,42047,42048,42049,42050,42051,42052,42053,42054,42055,42056,42057,42058,42059,42060,42061,42062,42063,42064,42065,42066,42067,42068,42069,42070,42071,42072,42073,42074,42075,42076,42077,42078,42079,42080,42081,42082,42083,42084,42085,42086,42087,42088,42089,42090,42091,42092,42093,42094,42095,42096,42097,42098,42099,42100,42101,42102,42103,42104,42105,42106,42107,42108,42109,42110,42111,42112,42113,42114,42115,42116,42117,42118,42119,42120,42121,42122,42123,42124,42192,42193,42194,42195,42196,42197,42198,42199,42200,42201,42202,42203,42204,42205,42206,42207,42208,42209,42210,42211,42212,42213,42214,42215,42216,42217,42218,42219,42220,42221,42222,42223,42224,42225,42226,42227,42228,42229,42230,42231,42232,42233,42234,42235,42236,42237,42240,42241,42242,42243,42244,42245,42246,42247,42248,42249,42250,42251,42252,42253,42254,42255,42256,42257,42258,42259,42260,42261,42262,42263,42264,42265,42266,42267,42268,42269,42270,42271,42272,42273,42274,42275,42276,42277,42278,42279,42280,42281,42282,42283,42284,42285,42286,42287,42288,42289,42290,42291,42292,42293,42294,42295,42296,42297,42298,42299,42300,42301,42302,42303,42304,42305,42306,42307,42308,42309,42310,42311,42312,42313,42314,42315,42316,42317,42318,42319,42320,42321,42322,42323,42324,42325,42326,42327,42328,42329,42330,42331,42332,42333,42334,42335,42336,42337,42338,42339,42340,42341,42342,42343,42344,42345,42346,42347,42348,42349,42350,42351,42352,42353,42354,42355,42356,42357,42358,42359,42360,42361,42362,42363,42364,42365,42366,42367,42368,42369,42370,42371,42372,42373,42374,42375,42376,42377,42378,42379,42380,42381,42382,42383,42384,42385,42386,42387,42388,42389,42390,42391,42392,42393,42394,42395,42396,42397,42398,42399,42400,42401,42402,42403,42404,42405,42406,42407,42408,42409,42410,42411,42412,42413,42414,42415,42416,42417,42418,42419,42420,42421,42422,42423,42424,42425,42426,42427,42428,42429,42430,42431,42432,42433,42434,42435,42436,42437,42438,42439,42440,42441,42442,42443,42444,42445,42446,42447,42448,42449,42450,42451,42452,42453,42454,42455,42456,42457,42458,42459,42460,42461,42462,42463,42464,42465,42466,42467,42468,42469,42470,42471,42472,42473,42474,42475,42476,42477,42478,42479,42480,42481,42482,42483,42484,42485,42486,42487,42488,42489,42490,42491,42492,42493,42494,42495,42496,42497,42498,42499,42500,42501,42502,42503,42504,42505,42506,42507,42508,42512,42513,42514,42515,42516,42517,42518,42519,42520,42521,42522,42523,42524,42525,42526,42527,42538,42539,42560,42561,42562,42563,42564,42565,42566,42567,42568,42569,42570,42571,42572,42573,42574,42575,42576,42577,42578,42579,42580,42581,42582,42583,42584,42585,42586,42587,42588,42589,42590,42591,42592,42593,42594,42595,42596,42597,42598,42599,42600,42601,42602,42603,42604,42605,42606,42623,42624,42625,42626,42627,42628,42629,42630,42631,42632,42633,42634,42635,42636,42637,42638,42639,42640,42641,42642,42643,42644,42645,42646,42647,42648,42649,42650,42651,42652,42653,42656,42657,42658,42659,42660,42661,42662,42663,42664,42665,42666,42667,42668,42669,42670,42671,42672,42673,42674,42675,42676,42677,42678,42679,42680,42681,42682,42683,42684,42685,42686,42687,42688,42689,42690,42691,42692,42693,42694,42695,42696,42697,42698,42699,42700,42701,42702,42703,42704,42705,42706,42707,42708,42709,42710,42711,42712,42713,42714,42715,42716,42717,42718,42719,42720,42721,42722,42723,42724,42725,42726,42727,42728,42729,42730,42731,42732,42733,42734,42735,42775,42776,42777,42778,42779,42780,42781,42782,42783,42786,42787,42788,42789,42790,42791,42792,42793,42794,42795,42796,42797,42798,42799,42800,42801,42802,42803,42804,42805,42806,42807,42808,42809,42810,42811,42812,42813,42814,42815,42816,42817,42818,42819,42820,42821,42822,42823,42824,42825,42826,42827,42828,42829,42830,42831,42832,42833,42834,42835,42836,42837,42838,42839,42840,42841,42842,42843,42844,42845,42846,42847,42848,42849,42850,42851,42852,42853,42854,42855,42856,42857,42858,42859,42860,42861,42862,42863,42864,42865,42866,42867,42868,42869,42870,42871,42872,42873,42874,42875,42876,42877,42878,42879,42880,42881,42882,42883,42884,42885,42886,42887,42888,42891,42892,42893,42894,42895,42896,42897,42898,42899,42900,42901,42902,42903,42904,42905,42906,42907,42908,42909,42910,42911,42912,42913,42914,42915,42916,42917,42918,42919,42920,42921,42922,42923,42924,42925,42926,42927,42928,42929,42930,42931,42932,42933,42934,42935,42936,42937,42999,43000,43001,43002,43003,43004,43005,43006,43007,43008,43009,43011,43012,43013,43015,43016,43017,43018,43020,43021,43022,43023,43024,43025,43026,43027,43028,43029,43030,43031,43032,43033,43034,43035,43036,43037,43038,43039,43040,43041,43042,43072,43073,43074,43075,43076,43077,43078,43079,43080,43081,43082,43083,43084,43085,43086,43087,43088,43089,43090,43091,43092,43093,43094,43095,43096,43097,43098,43099,43100,43101,43102,43103,43104,43105,43106,43107,43108,43109,43110,43111,43112,43113,43114,43115,43116,43117,43118,43119,43120,43121,43122,43123,43138,43139,43140,43141,43142,43143,43144,43145,43146,43147,43148,43149,43150,43151,43152,43153,43154,43155,43156,43157,43158,43159,43160,43161,43162,43163,43164,43165,43166,43167,43168,43169,43170,43171,43172,43173,43174,43175,43176,43177,43178,43179,43180,43181,43182,43183,43184,43185,43186,43187,43250,43251,43252,43253,43254,43255,43259,43261,43262,43274,43275,43276,43277,43278,43279,43280,43281,43282,43283,43284,43285,43286,43287,43288,43289,43290,43291,43292,43293,43294,43295,43296,43297,43298,43299,43300,43301,43312,43313,43314,43315,43316,43317,43318,43319,43320,43321,43322,43323,43324,43325,43326,43327,43328,43329,43330,43331,43332,43333,43334,43360,43361,43362,43363,43364,43365,43366,43367,43368,43369,43370,43371,43372,43373,43374,43375,43376,43377,43378,43379,43380,43381,43382,43383,43384,43385,43386,43387,43388,43396,43397,43398,43399,43400,43401,43402,43403,43404,43405,43406,43407,43408,43409,43410,43411,43412,43413,43414,43415,43416,43417,43418,43419,43420,43421,43422,43423,43424,43425,43426,43427,43428,43429,43430,43431,43432,43433,43434,43435,43436,43437,43438,43439,43440,43441,43442,43471,43488,43489,43490,43491,43492,43494,43495,43496,43497,43498,43499,43500,43501,43502,43503,43514,43515,43516,43517,43518,43520,43521,43522,43523,43524,43525,43526,43527,43528,43529,43530,43531,43532,43533,43534,43535,43536,43537,43538,43539,43540,43541,43542,43543,43544,43545,43546,43547,43548,43549,43550,43551,43552,43553,43554,43555,43556,43557,43558,43559,43560,43584,43585,43586,43588,43589,43590,43591,43592,43593,43594,43595,43616,43617,43618,43619,43620,43621,43622,43623,43624,43625,43626,43627,43628,43629,43630,43631,43632,43633,43634,43635,43636,43637,43638,43642,43646,43647,43648,43649,43650,43651,43652,43653,43654,43655,43656,43657,43658,43659,43660,43661,43662,43663,43664,43665,43666,43667,43668,43669,43670,43671,43672,43673,43674,43675,43676,43677,43678,43679,43680,43681,43682,43683,43684,43685,43686,43687,43688,43689,43690,43691,43692,43693,43694,43695,43697,43701,43702,43705,43706,43707,43708,43709,43712,43714,43739,43740,43741,43744,43745,43746,43747,43748,43749,43750,43751,43752,43753,43754,43762,43763,43764,43777,43778,43779,43780,43781,43782,43785,43786,43787,43788,43789,43790,43793,43794,43795,43796,43797,43798,43808,43809,43810,43811,43812,43813,43814,43816,43817,43818,43819,43820,43821,43822,43824,43825,43826,43827,43828,43829,43830,43831,43832,43833,43834,43835,43836,43837,43838,43839,43840,43841,43842,43843,43844,43845,43846,43847,43848,43849,43850,43851,43852,43853,43854,43855,43856,43857,43858,43859,43860,43861,43862,43863,43864,43865,43866,43868,43869,43870,43871,43872,43873,43874,43875,43876,43877,43888,43889,43890,43891,43892,43893,43894,43895,43896,43897,43898,43899,43900,43901,43902,43903,43904,43905,43906,43907,43908,43909,43910,43911,43912,43913,43914,43915,43916,43917,43918,43919,43920,43921,43922,43923,43924,43925,43926,43927,43928,43929,43930,43931,43932,43933,43934,43935,43936,43937,43938,43939,43940,43941,43942,43943,43944,43945,43946,43947,43948,43949,43950,43951,43952,43953,43954,43955,43956,43957,43958,43959,43960,43961,43962,43963,43964,43965,43966,43967,43968,43969,43970,43971,43972,43973,43974,43975,43976,43977,43978,43979,43980,43981,43982,43983,43984,43985,43986,43987,43988,43989,43990,43991,43992,43993,43994,43995,43996,43997,43998,43999,44000,44001,44002,44032,44033,44034,44035,44036,44037,44038,44039,44040,44041,44042,44043,44044,44045,44046,44047,44048,44049,44050,44051,44052,44053,44054,44055,44056,44057,44058,44059,44060,44061,44062,44063,44064,44065,44066,44067,44068,44069,44070,44071,44072,44073,44074,44075,44076,44077,44078,44079,44080,44081,44082,44083,44084,44085,44086,44087,44088,44089,44090,44091,44092,44093,44094,44095,44096,44097,44098,44099,44100,44101,44102,44103,44104,44105,44106,44107,44108,44109,44110,44111,44112,44113,44114,44115,44116,44117,44118,44119,44120,44121,44122,44123,44124,44125,44126,44127,44128,44129,44130,44131,44132,44133,44134,44135,44136,44137,44138,44139,44140,44141,44142,44143,44144,44145,44146,44147,44148,44149,44150,44151,44152,44153,44154,44155,44156,44157,44158,44159,44160,44161,44162,44163,44164,44165,44166,44167,44168,44169,44170,44171,44172,44173,44174,44175,44176,44177,44178,44179,44180,44181,44182,44183,44184,44185,44186,44187,44188,44189,44190,44191,44192,44193,44194,44195,44196,44197,44198,44199,44200,44201,44202,44203,44204,44205,44206,44207,44208,44209,44210,44211,44212,44213,44214,44215,44216,44217,44218,44219,44220,44221,44222,44223,44224,44225,44226,44227,44228,44229,44230,44231,44232,44233,44234,44235,44236,44237,44238,44239,44240,44241,44242,44243,44244,44245,44246,44247,44248,44249,44250,44251,44252,44253,44254,44255,44256,44257,44258,44259,44260,44261,44262,44263,44264,44265,44266,44267,44268,44269,44270,44271,44272,44273,44274,44275,44276,44277,44278,44279,44280,44281,44282,44283,44284,44285,44286,44287,44288,44289,44290,44291,44292,44293,44294,44295,44296,44297,44298,44299,44300,44301,44302,44303,44304,44305,44306,44307,44308,44309,44310,44311,44312,44313,44314,44315,44316,44317,44318,44319,44320,44321,44322,44323,44324,44325,44326,44327,44328,44329,44330,44331,44332,44333,44334,44335,44336,44337,44338,44339,44340,44341,44342,44343,44344,44345,44346,44347,44348,44349,44350,44351,44352,44353,44354,44355,44356,44357,44358,44359,44360,44361,44362,44363,44364,44365,44366,44367,44368,44369,44370,44371,44372,44373,44374,44375,44376,44377,44378,44379,44380,44381,44382,44383,44384,44385,44386,44387,44388,44389,44390,44391,44392,44393,44394,44395,44396,44397,44398,44399,44400,44401,44402,44403,44404,44405,44406,44407,44408,44409,44410,44411,44412,44413,44414,44415,44416,44417,44418,44419,44420,44421,44422,44423,44424,44425,44426,44427,44428,44429,44430,44431,44432,44433,44434,44435,44436,44437,44438,44439,44440,44441,44442,44443,44444,44445,44446,44447,44448,44449,44450,44451,44452,44453,44454,44455,44456,44457,44458,44459,44460,44461,44462,44463,44464,44465,44466,44467,44468,44469,44470,44471,44472,44473,44474,44475,44476,44477,44478,44479,44480,44481,44482,44483,44484,44485,44486,44487,44488,44489,44490,44491,44492,44493,44494,44495,44496,44497,44498,44499,44500,44501,44502,44503,44504,44505,44506,44507,44508,44509,44510,44511,44512,44513,44514,44515,44516,44517,44518,44519,44520,44521,44522,44523,44524,44525,44526,44527,44528,44529,44530,44531,44532,44533,44534,44535,44536,44537,44538,44539,44540,44541,44542,44543,44544,44545,44546,44547,44548,44549,44550,44551,44552,44553,44554,44555,44556,44557,44558,44559,44560,44561,44562,44563,44564,44565,44566,44567,44568,44569,44570,44571,44572,44573,44574,44575,44576,44577,44578,44579,44580,44581,44582,44583,44584,44585,44586,44587,44588,44589,44590,44591,44592,44593,44594,44595,44596,44597,44598,44599,44600,44601,44602,44603,44604,44605,44606,44607,44608,44609,44610,44611,44612,44613,44614,44615,44616,44617,44618,44619,44620,44621,44622,44623,44624,44625,44626,44627,44628,44629,44630,44631,44632,44633,44634,44635,44636,44637,44638,44639,44640,44641,44642,44643,44644,44645,44646,44647,44648,44649,44650,44651,44652,44653,44654,44655,44656,44657,44658,44659,44660,44661,44662,44663,44664,44665,44666,44667,44668,44669,44670,44671,44672,44673,44674,44675,44676,44677,44678,44679,44680,44681,44682,44683,44684,44685,44686,44687,44688,44689,44690,44691,44692,44693,44694,44695,44696,44697,44698,44699,44700,44701,44702,44703,44704,44705,44706,44707,44708,44709,44710,44711,44712,44713,44714,44715,44716,44717,44718,44719,44720,44721,44722,44723,44724,44725,44726,44727,44728,44729,44730,44731,44732,44733,44734,44735,44736,44737,44738,44739,44740,44741,44742,44743,44744,44745,44746,44747,44748,44749,44750,44751,44752,44753,44754,44755,44756,44757,44758,44759,44760,44761,44762,44763,44764,44765,44766,44767,44768,44769,44770,44771,44772,44773,44774,44775,44776,44777,44778,44779,44780,44781,44782,44783,44784,44785,44786,44787,44788,44789,44790,44791,44792,44793,44794,44795,44796,44797,44798,44799,44800,44801,44802,44803,44804,44805,44806,44807,44808,44809,44810,44811,44812,44813,44814,44815,44816,44817,44818,44819,44820,44821,44822,44823,44824,44825,44826,44827,44828,44829,44830,44831,44832,44833,44834,44835,44836,44837,44838,44839,44840,44841,44842,44843,44844,44845,44846,44847,44848,44849,44850,44851,44852,44853,44854,44855,44856,44857,44858,44859,44860,44861,44862,44863,44864,44865,44866,44867,44868,44869,44870,44871,44872,44873,44874,44875,44876,44877,44878,44879,44880,44881,44882,44883,44884,44885,44886,44887,44888,44889,44890,44891,44892,44893,44894,44895,44896,44897,44898,44899,44900,44901,44902,44903,44904,44905,44906,44907,44908,44909,44910,44911,44912,44913,44914,44915,44916,44917,44918,44919,44920,44921,44922,44923,44924,44925,44926,44927,44928,44929,44930,44931,44932,44933,44934,44935,44936,44937,44938,44939,44940,44941,44942,44943,44944,44945,44946,44947,44948,44949,44950,44951,44952,44953,44954,44955,44956,44957,44958,44959,44960,44961,44962,44963,44964,44965,44966,44967,44968,44969,44970,44971,44972,44973,44974,44975,44976,44977,44978,44979,44980,44981,44982,44983,44984,44985,44986,44987,44988,44989,44990,44991,44992,44993,44994,44995,44996,44997,44998,44999,45000,45001,45002,45003,45004,45005,45006,45007,45008,45009,45010,45011,45012,45013,45014,45015,45016,45017,45018,45019,45020,45021,45022,45023,45024,45025,45026,45027,45028,45029,45030,45031,45032,45033,45034,45035,45036,45037,45038,45039,45040,45041,45042,45043,45044,45045,45046,45047,45048,45049,45050,45051,45052,45053,45054,45055,45056,45057,45058,45059,45060,45061,45062,45063,45064,45065,45066,45067,45068,45069,45070,45071,45072,45073,45074,45075,45076,45077,45078,45079,45080,45081,45082,45083,45084,45085,45086,45087,45088,45089,45090,45091,45092,45093,45094,45095,45096,45097,45098,45099,45100,45101,45102,45103,45104,45105,45106,45107,45108,45109,45110,45111,45112,45113,45114,45115,45116,45117,45118,45119,45120,45121,45122,45123,45124,45125,45126,45127,45128,45129,45130,45131,45132,45133,45134,45135,45136,45137,45138,45139,45140,45141,45142,45143,45144,45145,45146,45147,45148,45149,45150,45151,45152,45153,45154,45155,45156,45157,45158,45159,45160,45161,45162,45163,45164,45165,45166,45167,45168,45169,45170,45171,45172,45173,45174,45175,45176,45177,45178,45179,45180,45181,45182,45183,45184,45185,45186,45187,45188,45189,45190,45191,45192,45193,45194,45195,45196,45197,45198,45199,45200,45201,45202,45203,45204,45205,45206,45207,45208,45209,45210,45211,45212,45213,45214,45215,45216,45217,45218,45219,45220,45221,45222,45223,45224,45225,45226,45227,45228,45229,45230,45231,45232,45233,45234,45235,45236,45237,45238,45239,45240,45241,45242,45243,45244,45245,45246,45247,45248,45249,45250,45251,45252,45253,45254,45255,45256,45257,45258,45259,45260,45261,45262,45263,45264,45265,45266,45267,45268,45269,45270,45271,45272,45273,45274,45275,45276,45277,45278,45279,45280,45281,45282,45283,45284,45285,45286,45287,45288,45289,45290,45291,45292,45293,45294,45295,45296,45297,45298,45299,45300,45301,45302,45303,45304,45305,45306,45307,45308,45309,45310,45311,45312,45313,45314,45315,45316,45317,45318,45319,45320,45321,45322,45323,45324,45325,45326,45327,45328,45329,45330,45331,45332,45333,45334,45335,45336,45337,45338,45339,45340,45341,45342,45343,45344,45345,45346,45347,45348,45349,45350,45351,45352,45353,45354,45355,45356,45357,45358,45359,45360,45361,45362,45363,45364,45365,45366,45367,45368,45369,45370,45371,45372,45373,45374,45375,45376,45377,45378,45379,45380,45381,45382,45383,45384,45385,45386,45387,45388,45389,45390,45391,45392,45393,45394,45395,45396,45397,45398,45399,45400,45401,45402,45403,45404,45405,45406,45407,45408,45409,45410,45411,45412,45413,45414,45415,45416,45417,45418,45419,45420,45421,45422,45423,45424,45425,45426,45427,45428,45429,45430,45431,45432,45433,45434,45435,45436,45437,45438,45439,45440,45441,45442,45443,45444,45445,45446,45447,45448,45449,45450,45451,45452,45453,45454,45455,45456,45457,45458,45459,45460,45461,45462,45463,45464,45465,45466,45467,45468,45469,45470,45471,45472,45473,45474,45475,45476,45477,45478,45479,45480,45481,45482,45483,45484,45485,45486,45487,45488,45489,45490,45491,45492,45493,45494,45495,45496,45497,45498,45499,45500,45501,45502,45503,45504,45505,45506,45507,45508,45509,45510,45511,45512,45513,45514,45515,45516,45517,45518,45519,45520,45521,45522,45523,45524,45525,45526,45527,45528,45529,45530,45531,45532,45533,45534,45535,45536,45537,45538,45539,45540,45541,45542,45543,45544,45545,45546,45547,45548,45549,45550,45551,45552,45553,45554,45555,45556,45557,45558,45559,45560,45561,45562,45563,45564,45565,45566,45567,45568,45569,45570,45571,45572,45573,45574,45575,45576,45577,45578,45579,45580,45581,45582,45583,45584,45585,45586,45587,45588,45589,45590,45591,45592,45593,45594,45595,45596,45597,45598,45599,45600,45601,45602,45603,45604,45605,45606,45607,45608,45609,45610,45611,45612,45613,45614,45615,45616,45617,45618,45619,45620,45621,45622,45623,45624,45625,45626,45627,45628,45629,45630,45631,45632,45633,45634,45635,45636,45637,45638,45639,45640,45641,45642,45643,45644,45645,45646,45647,45648,45649,45650,45651,45652,45653,45654,45655,45656,45657,45658,45659,45660,45661,45662,45663,45664,45665,45666,45667,45668,45669,45670,45671,45672,45673,45674,45675,45676,45677,45678,45679,45680,45681,45682,45683,45684,45685,45686,45687,45688,45689,45690,45691,45692,45693,45694,45695,45696,45697,45698,45699,45700,45701,45702,45703,45704,45705,45706,45707,45708,45709,45710,45711,45712,45713,45714,45715,45716,45717,45718,45719,45720,45721,45722,45723,45724,45725,45726,45727,45728,45729,45730,45731,45732,45733,45734,45735,45736,45737,45738,45739,45740,45741,45742,45743,45744,45745,45746,45747,45748,45749,45750,45751,45752,45753,45754,45755,45756,45757,45758,45759,45760,45761,45762,45763,45764,45765,45766,45767,45768,45769,45770,45771,45772,45773,45774,45775,45776,45777,45778,45779,45780,45781,45782,45783,45784,45785,45786,45787,45788,45789,45790,45791,45792,45793,45794,45795,45796,45797,45798,45799,45800,45801,45802,45803,45804,45805,45806,45807,45808,45809,45810,45811,45812,45813,45814,45815,45816,45817,45818,45819,45820,45821,45822,45823,45824,45825,45826,45827,45828,45829,45830,45831,45832,45833,45834,45835,45836,45837,45838,45839,45840,45841,45842,45843,45844,45845,45846,45847,45848,45849,45850,45851,45852,45853,45854,45855,45856,45857,45858,45859,45860,45861,45862,45863,45864,45865,45866,45867,45868,45869,45870,45871,45872,45873,45874,45875,45876,45877,45878,45879,45880,45881,45882,45883,45884,45885,45886,45887,45888,45889,45890,45891,45892,45893,45894,45895,45896,45897,45898,45899,45900,45901,45902,45903,45904,45905,45906,45907,45908,45909,45910,45911,45912,45913,45914,45915,45916,45917,45918,45919,45920,45921,45922,45923,45924,45925,45926,45927,45928,45929,45930,45931,45932,45933,45934,45935,45936,45937,45938,45939,45940,45941,45942,45943,45944,45945,45946,45947,45948,45949,45950,45951,45952,45953,45954,45955,45956,45957,45958,45959,45960,45961,45962,45963,45964,45965,45966,45967,45968,45969,45970,45971,45972,45973,45974,45975,45976,45977,45978,45979,45980,45981,45982,45983,45984,45985,45986,45987,45988,45989,45990,45991,45992,45993,45994,45995,45996,45997,45998,45999,46000,46001,46002,46003,46004,46005,46006,46007,46008,46009,46010,46011,46012,46013,46014,46015,46016,46017,46018,46019,46020,46021,46022,46023,46024,46025,46026,46027,46028,46029,46030,46031,46032,46033,46034,46035,46036,46037,46038,46039,46040,46041,46042,46043,46044,46045,46046,46047,46048,46049,46050,46051,46052,46053,46054,46055,46056,46057,46058,46059,46060,46061,46062,46063,46064,46065,46066,46067,46068,46069,46070,46071,46072,46073,46074,46075,46076,46077,46078,46079,46080,46081,46082,46083,46084,46085,46086,46087,46088,46089,46090,46091,46092,46093,46094,46095,46096,46097,46098,46099,46100,46101,46102,46103,46104,46105,46106,46107,46108,46109,46110,46111,46112,46113,46114,46115,46116,46117,46118,46119,46120,46121,46122,46123,46124,46125,46126,46127,46128,46129,46130,46131,46132,46133,46134,46135,46136,46137,46138,46139,46140,46141,46142,46143,46144,46145,46146,46147,46148,46149,46150,46151,46152,46153,46154,46155,46156,46157,46158,46159,46160,46161,46162,46163,46164,46165,46166,46167,46168,46169,46170,46171,46172,46173,46174,46175,46176,46177,46178,46179,46180,46181,46182,46183,46184,46185,46186,46187,46188,46189,46190,46191,46192,46193,46194,46195,46196,46197,46198,46199,46200,46201,46202,46203,46204,46205,46206,46207,46208,46209,46210,46211,46212,46213,46214,46215,46216,46217,46218,46219,46220,46221,46222,46223,46224,46225,46226,46227,46228,46229,46230,46231,46232,46233,46234,46235,46236,46237,46238,46239,46240,46241,46242,46243,46244,46245,46246,46247,46248,46249,46250,46251,46252,46253,46254,46255,46256,46257,46258,46259,46260,46261,46262,46263,46264,46265,46266,46267,46268,46269,46270,46271,46272,46273,46274,46275,46276,46277,46278,46279,46280,46281,46282,46283,46284,46285,46286,46287,46288,46289,46290,46291,46292,46293,46294,46295,46296,46297,46298,46299,46300,46301,46302,46303,46304,46305,46306,46307,46308,46309,46310,46311,46312,46313,46314,46315,46316,46317,46318,46319,46320,46321,46322,46323,46324,46325,46326,46327,46328,46329,46330,46331,46332,46333,46334,46335,46336,46337,46338,46339,46340,46341,46342,46343,46344,46345,46346,46347,46348,46349,46350,46351,46352,46353,46354,46355,46356,46357,46358,46359,46360,46361,46362,46363,46364,46365,46366,46367,46368,46369,46370,46371,46372,46373,46374,46375,46376,46377,46378,46379,46380,46381,46382,46383,46384,46385,46386,46387,46388,46389,46390,46391,46392,46393,46394,46395,46396,46397,46398,46399,46400,46401,46402,46403,46404,46405,46406,46407,46408,46409,46410,46411,46412,46413,46414,46415,46416,46417,46418,46419,46420,46421,46422,46423,46424,46425,46426,46427,46428,46429,46430,46431,46432,46433,46434,46435,46436,46437,46438,46439,46440,46441,46442,46443,46444,46445,46446,46447,46448,46449,46450,46451,46452,46453,46454,46455,46456,46457,46458,46459,46460,46461,46462,46463,46464,46465,46466,46467,46468,46469,46470,46471,46472,46473,46474,46475,46476,46477,46478,46479,46480,46481,46482,46483,46484,46485,46486,46487,46488,46489,46490,46491,46492,46493,46494,46495,46496,46497,46498,46499,46500,46501,46502,46503,46504,46505,46506,46507,46508,46509,46510,46511,46512,46513,46514,46515,46516,46517,46518,46519,46520,46521,46522,46523,46524,46525,46526,46527,46528,46529,46530,46531,46532,46533,46534,46535,46536,46537,46538,46539,46540,46541,46542,46543,46544,46545,46546,46547,46548,46549,46550,46551,46552,46553,46554,46555,46556,46557,46558,46559,46560,46561,46562,46563,46564,46565,46566,46567,46568,46569,46570,46571,46572,46573,46574,46575,46576,46577,46578,46579,46580,46581,46582,46583,46584,46585,46586,46587,46588,46589,46590,46591,46592,46593,46594,46595,46596,46597,46598,46599,46600,46601,46602,46603,46604,46605,46606,46607,46608,46609,46610,46611,46612,46613,46614,46615,46616,46617,46618,46619,46620,46621,46622,46623,46624,46625,46626,46627,46628,46629,46630,46631,46632,46633,46634,46635,46636,46637,46638,46639,46640,46641,46642,46643,46644,46645,46646,46647,46648,46649,46650,46651,46652,46653,46654,46655,46656,46657,46658,46659,46660,46661,46662,46663,46664,46665,46666,46667,46668,46669,46670,46671,46672,46673,46674,46675,46676,46677,46678,46679,46680,46681,46682,46683,46684,46685,46686,46687,46688,46689,46690,46691,46692,46693,46694,46695,46696,46697,46698,46699,46700,46701,46702,46703,46704,46705,46706,46707,46708,46709,46710,46711,46712,46713,46714,46715,46716,46717,46718,46719,46720,46721,46722,46723,46724,46725,46726,46727,46728,46729,46730,46731,46732,46733,46734,46735,46736,46737,46738,46739,46740,46741,46742,46743,46744,46745,46746,46747,46748,46749,46750,46751,46752,46753,46754,46755,46756,46757,46758,46759,46760,46761,46762,46763,46764,46765,46766,46767,46768,46769,46770,46771,46772,46773,46774,46775,46776,46777,46778,46779,46780,46781,46782,46783,46784,46785,46786,46787,46788,46789,46790,46791,46792,46793,46794,46795,46796,46797,46798,46799,46800,46801,46802,46803,46804,46805,46806,46807,46808,46809,46810,46811,46812,46813,46814,46815,46816,46817,46818,46819,46820,46821,46822,46823,46824,46825,46826,46827,46828,46829,46830,46831,46832,46833,46834,46835,46836,46837,46838,46839,46840,46841,46842,46843,46844,46845,46846,46847,46848,46849,46850,46851,46852,46853,46854,46855,46856,46857,46858,46859,46860,46861,46862,46863,46864,46865,46866,46867,46868,46869,46870,46871,46872,46873,46874,46875,46876,46877,46878,46879,46880,46881,46882,46883,46884,46885,46886,46887,46888,46889,46890,46891,46892,46893,46894,46895,46896,46897,46898,46899,46900,46901,46902,46903,46904,46905,46906,46907,46908,46909,46910,46911,46912,46913,46914,46915,46916,46917,46918,46919,46920,46921,46922,46923,46924,46925,46926,46927,46928,46929,46930,46931,46932,46933,46934,46935,46936,46937,46938,46939,46940,46941,46942,46943,46944,46945,46946,46947,46948,46949,46950,46951,46952,46953,46954,46955,46956,46957,46958,46959,46960,46961,46962,46963,46964,46965,46966,46967,46968,46969,46970,46971,46972,46973,46974,46975,46976,46977,46978,46979,46980,46981,46982,46983,46984,46985,46986,46987,46988,46989,46990,46991,46992,46993,46994,46995,46996,46997,46998,46999,47000,47001,47002,47003,47004,47005,47006,47007,47008,47009,47010,47011,47012,47013,47014,47015,47016,47017,47018,47019,47020,47021,47022,47023,47024,47025,47026,47027,47028,47029,47030,47031,47032,47033,47034,47035,47036,47037,47038,47039,47040,47041,47042,47043,47044,47045,47046,47047,47048,47049,47050,47051,47052,47053,47054,47055,47056,47057,47058,47059,47060,47061,47062,47063,47064,47065,47066,47067,47068,47069,47070,47071,47072,47073,47074,47075,47076,47077,47078,47079,47080,47081,47082,47083,47084,47085,47086,47087,47088,47089,47090,47091,47092,47093,47094,47095,47096,47097,47098,47099,47100,47101,47102,47103,47104,47105,47106,47107,47108,47109,47110,47111,47112,47113,47114,47115,47116,47117,47118,47119,47120,47121,47122,47123,47124,47125,47126,47127,47128,47129,47130,47131,47132,47133,47134,47135,47136,47137,47138,47139,47140,47141,47142,47143,47144,47145,47146,47147,47148,47149,47150,47151,47152,47153,47154,47155,47156,47157,47158,47159,47160,47161,47162,47163,47164,47165,47166,47167,47168,47169,47170,47171,47172,47173,47174,47175,47176,47177,47178,47179,47180,47181,47182,47183,47184,47185,47186,47187,47188,47189,47190,47191,47192,47193,47194,47195,47196,47197,47198,47199,47200,47201,47202,47203,47204,47205,47206,47207,47208,47209,47210,47211,47212,47213,47214,47215,47216,47217,47218,47219,47220,47221,47222,47223,47224,47225,47226,47227,47228,47229,47230,47231,47232,47233,47234,47235,47236,47237,47238,47239,47240,47241,47242,47243,47244,47245,47246,47247,47248,47249,47250,47251,47252,47253,47254,47255,47256,47257,47258,47259,47260,47261,47262,47263,47264,47265,47266,47267,47268,47269,47270,47271,47272,47273,47274,47275,47276,47277,47278,47279,47280,47281,47282,47283,47284,47285,47286,47287,47288,47289,47290,47291,47292,47293,47294,47295,47296,47297,47298,47299,47300,47301,47302,47303,47304,47305,47306,47307,47308,47309,47310,47311,47312,47313,47314,47315,47316,47317,47318,47319,47320,47321,47322,47323,47324,47325,47326,47327,47328,47329,47330,47331,47332,47333,47334,47335,47336,47337,47338,47339,47340,47341,47342,47343,47344,47345,47346,47347,47348,47349,47350,47351,47352,47353,47354,47355,47356,47357,47358,47359,47360,47361,47362,47363,47364,47365,47366,47367,47368,47369,47370,47371,47372,47373,47374,47375,47376,47377,47378,47379,47380,47381,47382,47383,47384,47385,47386,47387,47388,47389,47390,47391,47392,47393,47394,47395,47396,47397,47398,47399,47400,47401,47402,47403,47404,47405,47406,47407,47408,47409,47410,47411,47412,47413,47414,47415,47416,47417,47418,47419,47420,47421,47422,47423,47424,47425,47426,47427,47428,47429,47430,47431,47432,47433,47434,47435,47436,47437,47438,47439,47440,47441,47442,47443,47444,47445,47446,47447,47448,47449,47450,47451,47452,47453,47454,47455,47456,47457,47458,47459,47460,47461,47462,47463,47464,47465,47466,47467,47468,47469,47470,47471,47472,47473,47474,47475,47476,47477,47478,47479,47480,47481,47482,47483,47484,47485,47486,47487,47488,47489,47490,47491,47492,47493,47494,47495,47496,47497,47498,47499,47500,47501,47502,47503,47504,47505,47506,47507,47508,47509,47510,47511,47512,47513,47514,47515,47516,47517,47518,47519,47520,47521,47522,47523,47524,47525,47526,47527,47528,47529,47530,47531,47532,47533,47534,47535,47536,47537,47538,47539,47540,47541,47542,47543,47544,47545,47546,47547,47548,47549,47550,47551,47552,47553,47554,47555,47556,47557,47558,47559,47560,47561,47562,47563,47564,47565,47566,47567,47568,47569,47570,47571,47572,47573,47574,47575,47576,47577,47578,47579,47580,47581,47582,47583,47584,47585,47586,47587,47588,47589,47590,47591,47592,47593,47594,47595,47596,47597,47598,47599,47600,47601,47602,47603,47604,47605,47606,47607,47608,47609,47610,47611,47612,47613,47614,47615,47616,47617,47618,47619,47620,47621,47622,47623,47624,47625,47626,47627,47628,47629,47630,47631,47632,47633,47634,47635,47636,47637,47638,47639,47640,47641,47642,47643,47644,47645,47646,47647,47648,47649,47650,47651,47652,47653,47654,47655,47656,47657,47658,47659,47660,47661,47662,47663,47664,47665,47666,47667,47668,47669,47670,47671,47672,47673,47674,47675,47676,47677,47678,47679,47680,47681,47682,47683,47684,47685,47686,47687,47688,47689,47690,47691,47692,47693,47694,47695,47696,47697,47698,47699,47700,47701,47702,47703,47704,47705,47706,47707,47708,47709,47710,47711,47712,47713,47714,47715,47716,47717,47718,47719,47720,47721,47722,47723,47724,47725,47726,47727,47728,47729,47730,47731,47732,47733,47734,47735,47736,47737,47738,47739,47740,47741,47742,47743,47744,47745,47746,47747,47748,47749,47750,47751,47752,47753,47754,47755,47756,47757,47758,47759,47760,47761,47762,47763,47764,47765,47766,47767,47768,47769,47770,47771,47772,47773,47774,47775,47776,47777,47778,47779,47780,47781,47782,47783,47784,47785,47786,47787,47788,47789,47790,47791,47792,47793,47794,47795,47796,47797,47798,47799,47800,47801,47802,47803,47804,47805,47806,47807,47808,47809,47810,47811,47812,47813,47814,47815,47816,47817,47818,47819,47820,47821,47822,47823,47824,47825,47826,47827,47828,47829,47830,47831,47832,47833,47834,47835,47836,47837,47838,47839,47840,47841,47842,47843,47844,47845,47846,47847,47848,47849,47850,47851,47852,47853,47854,47855,47856,47857,47858,47859,47860,47861,47862,47863,47864,47865,47866,47867,47868,47869,47870,47871,47872,47873,47874,47875,47876,47877,47878,47879,47880,47881,47882,47883,47884,47885,47886,47887,47888,47889,47890,47891,47892,47893,47894,47895,47896,47897,47898,47899,47900,47901,47902,47903,47904,47905,47906,47907,47908,47909,47910,47911,47912,47913,47914,47915,47916,47917,47918,47919,47920,47921,47922,47923,47924,47925,47926,47927,47928,47929,47930,47931,47932,47933,47934,47935,47936,47937,47938,47939,47940,47941,47942,47943,47944,47945,47946,47947,47948,47949,47950,47951,47952,47953,47954,47955,47956,47957,47958,47959,47960,47961,47962,47963,47964,47965,47966,47967,47968,47969,47970,47971,47972,47973,47974,47975,47976,47977,47978,47979,47980,47981,47982,47983,47984,47985,47986,47987,47988,47989,47990,47991,47992,47993,47994,47995,47996,47997,47998,47999,48000,48001,48002,48003,48004,48005,48006,48007,48008,48009,48010,48011,48012,48013,48014,48015,48016,48017,48018,48019,48020,48021,48022,48023,48024,48025,48026,48027,48028,48029,48030,48031,48032,48033,48034,48035,48036,48037,48038,48039,48040,48041,48042,48043,48044,48045,48046,48047,48048,48049,48050,48051,48052,48053,48054,48055,48056,48057,48058,48059,48060,48061,48062,48063,48064,48065,48066,48067,48068,48069,48070,48071,48072,48073,48074,48075,48076,48077,48078,48079,48080,48081,48082,48083,48084,48085,48086,48087,48088,48089,48090,48091,48092,48093,48094,48095,48096,48097,48098,48099,48100,48101,48102,48103,48104,48105,48106,48107,48108,48109,48110,48111,48112,48113,48114,48115,48116,48117,48118,48119,48120,48121,48122,48123,48124,48125,48126,48127,48128,48129,48130,48131,48132,48133,48134,48135,48136,48137,48138,48139,48140,48141,48142,48143,48144,48145,48146,48147,48148,48149,48150,48151,48152,48153,48154,48155,48156,48157,48158,48159,48160,48161,48162,48163,48164,48165,48166,48167,48168,48169,48170,48171,48172,48173,48174,48175,48176,48177,48178,48179,48180,48181,48182,48183,48184,48185,48186,48187,48188,48189,48190,48191,48192,48193,48194,48195,48196,48197,48198,48199,48200,48201,48202,48203,48204,48205,48206,48207,48208,48209,48210,48211,48212,48213,48214,48215,48216,48217,48218,48219,48220,48221,48222,48223,48224,48225,48226,48227,48228,48229,48230,48231,48232,48233,48234,48235,48236,48237,48238,48239,48240,48241,48242,48243,48244,48245,48246,48247,48248,48249,48250,48251,48252,48253,48254,48255,48256,48257,48258,48259,48260,48261,48262,48263,48264,48265,48266,48267,48268,48269,48270,48271,48272,48273,48274,48275,48276,48277,48278,48279,48280,48281,48282,48283,48284,48285,48286,48287,48288,48289,48290,48291,48292,48293,48294,48295,48296,48297,48298,48299,48300,48301,48302,48303,48304,48305,48306,48307,48308,48309,48310,48311,48312,48313,48314,48315,48316,48317,48318,48319,48320,48321,48322,48323,48324,48325,48326,48327,48328,48329,48330,48331,48332,48333,48334,48335,48336,48337,48338,48339,48340,48341,48342,48343,48344,48345,48346,48347,48348,48349,48350,48351,48352,48353,48354,48355,48356,48357,48358,48359,48360,48361,48362,48363,48364,48365,48366,48367,48368,48369,48370,48371,48372,48373,48374,48375,48376,48377,48378,48379,48380,48381,48382,48383,48384,48385,48386,48387,48388,48389,48390,48391,48392,48393,48394,48395,48396,48397,48398,48399,48400,48401,48402,48403,48404,48405,48406,48407,48408,48409,48410,48411,48412,48413,48414,48415,48416,48417,48418,48419,48420,48421,48422,48423,48424,48425,48426,48427,48428,48429,48430,48431,48432,48433,48434,48435,48436,48437,48438,48439,48440,48441,48442,48443,48444,48445,48446,48447,48448,48449,48450,48451,48452,48453,48454,48455,48456,48457,48458,48459,48460,48461,48462,48463,48464,48465,48466,48467,48468,48469,48470,48471,48472,48473,48474,48475,48476,48477,48478,48479,48480,48481,48482,48483,48484,48485,48486,48487,48488,48489,48490,48491,48492,48493,48494,48495,48496,48497,48498,48499,48500,48501,48502,48503,48504,48505,48506,48507,48508,48509,48510,48511,48512,48513,48514,48515,48516,48517,48518,48519,48520,48521,48522,48523,48524,48525,48526,48527,48528,48529,48530,48531,48532,48533,48534,48535,48536,48537,48538,48539,48540,48541,48542,48543,48544,48545,48546,48547,48548,48549,48550,48551,48552,48553,48554,48555,48556,48557,48558,48559,48560,48561,48562,48563,48564,48565,48566,48567,48568,48569,48570,48571,48572,48573,48574,48575,48576,48577,48578,48579,48580,48581,48582,48583,48584,48585,48586,48587,48588,48589,48590,48591,48592,48593,48594,48595,48596,48597,48598,48599,48600,48601,48602,48603,48604,48605,48606,48607,48608,48609,48610,48611,48612,48613,48614,48615,48616,48617,48618,48619,48620,48621,48622,48623,48624,48625,48626,48627,48628,48629,48630,48631,48632,48633,48634,48635,48636,48637,48638,48639,48640,48641,48642,48643,48644,48645,48646,48647,48648,48649,48650,48651,48652,48653,48654,48655,48656,48657,48658,48659,48660,48661,48662,48663,48664,48665,48666,48667,48668,48669,48670,48671,48672,48673,48674,48675,48676,48677,48678,48679,48680,48681,48682,48683,48684,48685,48686,48687,48688,48689,48690,48691,48692,48693,48694,48695,48696,48697,48698,48699,48700,48701,48702,48703,48704,48705,48706,48707,48708,48709,48710,48711,48712,48713,48714,48715,48716,48717,48718,48719,48720,48721,48722,48723,48724,48725,48726,48727,48728,48729,48730,48731,48732,48733,48734,48735,48736,48737,48738,48739,48740,48741,48742,48743,48744,48745,48746,48747,48748,48749,48750,48751,48752,48753,48754,48755,48756,48757,48758,48759,48760,48761,48762,48763,48764,48765,48766,48767,48768,48769,48770,48771,48772,48773,48774,48775,48776,48777,48778,48779,48780,48781,48782,48783,48784,48785,48786,48787,48788,48789,48790,48791,48792,48793,48794,48795,48796,48797,48798,48799,48800,48801,48802,48803,48804,48805,48806,48807,48808,48809,48810,48811,48812,48813,48814,48815,48816,48817,48818,48819,48820,48821,48822,48823,48824,48825,48826,48827,48828,48829,48830,48831,48832,48833,48834,48835,48836,48837,48838,48839,48840,48841,48842,48843,48844,48845,48846,48847,48848,48849,48850,48851,48852,48853,48854,48855,48856,48857,48858,48859,48860,48861,48862,48863,48864,48865,48866,48867,48868,48869,48870,48871,48872,48873,48874,48875,48876,48877,48878,48879,48880,48881,48882,48883,48884,48885,48886,48887,48888,48889,48890,48891,48892,48893,48894,48895,48896,48897,48898,48899,48900,48901,48902,48903,48904,48905,48906,48907,48908,48909,48910,48911,48912,48913,48914,48915,48916,48917,48918,48919,48920,48921,48922,48923,48924,48925,48926,48927,48928,48929,48930,48931,48932,48933,48934,48935,48936,48937,48938,48939,48940,48941,48942,48943,48944,48945,48946,48947,48948,48949,48950,48951,48952,48953,48954,48955,48956,48957,48958,48959,48960,48961,48962,48963,48964,48965,48966,48967,48968,48969,48970,48971,48972,48973,48974,48975,48976,48977,48978,48979,48980,48981,48982,48983,48984,48985,48986,48987,48988,48989,48990,48991,48992,48993,48994,48995,48996,48997,48998,48999,49000,49001,49002,49003,49004,49005,49006,49007,49008,49009,49010,49011,49012,49013,49014,49015,49016,49017,49018,49019,49020,49021,49022,49023,49024,49025,49026,49027,49028,49029,49030,49031,49032,49033,49034,49035,49036,49037,49038,49039,49040,49041,49042,49043,49044,49045,49046,49047,49048,49049,49050,49051,49052,49053,49054,49055,49056,49057,49058,49059,49060,49061,49062,49063,49064,49065,49066,49067,49068,49069,49070,49071,49072,49073,49074,49075,49076,49077,49078,49079,49080,49081,49082,49083,49084,49085,49086,49087,49088,49089,49090,49091,49092,49093,49094,49095,49096,49097,49098,49099,49100,49101,49102,49103,49104,49105,49106,49107,49108,49109,49110,49111,49112,49113,49114,49115,49116,49117,49118,49119,49120,49121,49122,49123,49124,49125,49126,49127,49128,49129,49130,49131,49132,49133,49134,49135,49136,49137,49138,49139,49140,49141,49142,49143,49144,49145,49146,49147,49148,49149,49150,49151,49152,49153,49154,49155,49156,49157,49158,49159,49160,49161,49162,49163,49164,49165,49166,49167,49168,49169,49170,49171,49172,49173,49174,49175,49176,49177,49178,49179,49180,49181,49182,49183,49184,49185,49186,49187,49188,49189,49190,49191,49192,49193,49194,49195,49196,49197,49198,49199,49200,49201,49202,49203,49204,49205,49206,49207,49208,49209,49210,49211,49212,49213,49214,49215,49216,49217,49218,49219,49220,49221,49222,49223,49224,49225,49226,49227,49228,49229,49230,49231,49232,49233,49234,49235,49236,49237,49238,49239,49240,49241,49242,49243,49244,49245,49246,49247,49248,49249,49250,49251,49252,49253,49254,49255,49256,49257,49258,49259,49260,49261,49262,49263,49264,49265,49266,49267,49268,49269,49270,49271,49272,49273,49274,49275,49276,49277,49278,49279,49280,49281,49282,49283,49284,49285,49286,49287,49288,49289,49290,49291,49292,49293,49294,49295,49296,49297,49298,49299,49300,49301,49302,49303,49304,49305,49306,49307,49308,49309,49310,49311,49312,49313,49314,49315,49316,49317,49318,49319,49320,49321,49322,49323,49324,49325,49326,49327,49328,49329,49330,49331,49332,49333,49334,49335,49336,49337,49338,49339,49340,49341,49342,49343,49344,49345,49346,49347,49348,49349,49350,49351,49352,49353,49354,49355,49356,49357,49358,49359,49360,49361,49362,49363,49364,49365,49366,49367,49368,49369,49370,49371,49372,49373,49374,49375,49376,49377,49378,49379,49380,49381,49382,49383,49384,49385,49386,49387,49388,49389,49390,49391,49392,49393,49394,49395,49396,49397,49398,49399,49400,49401,49402,49403,49404,49405,49406,49407,49408,49409,49410,49411,49412,49413,49414,49415,49416,49417,49418,49419,49420,49421,49422,49423,49424,49425,49426,49427,49428,49429,49430,49431,49432,49433,49434,49435,49436,49437,49438,49439,49440,49441,49442,49443,49444,49445,49446,49447,49448,49449,49450,49451,49452,49453,49454,49455,49456,49457,49458,49459,49460,49461,49462,49463,49464,49465,49466,49467,49468,49469,49470,49471,49472,49473,49474,49475,49476,49477,49478,49479,49480,49481,49482,49483,49484,49485,49486,49487,49488,49489,49490,49491,49492,49493,49494,49495,49496,49497,49498,49499,49500,49501,49502,49503,49504,49505,49506,49507,49508,49509,49510,49511,49512,49513,49514,49515,49516,49517,49518,49519,49520,49521,49522,49523,49524,49525,49526,49527,49528,49529,49530,49531,49532,49533,49534,49535,49536,49537,49538,49539,49540,49541,49542,49543,49544,49545,49546,49547,49548,49549,49550,49551,49552,49553,49554,49555,49556,49557,49558,49559,49560,49561,49562,49563,49564,49565,49566,49567,49568,49569,49570,49571,49572,49573,49574,49575,49576,49577,49578,49579,49580,49581,49582,49583,49584,49585,49586,49587,49588,49589,49590,49591,49592,49593,49594,49595,49596,49597,49598,49599,49600,49601,49602,49603,49604,49605,49606,49607,49608,49609,49610,49611,49612,49613,49614,49615,49616,49617,49618,49619,49620,49621,49622,49623,49624,49625,49626,49627,49628,49629,49630,49631,49632,49633,49634,49635,49636,49637,49638,49639,49640,49641,49642,49643,49644,49645,49646,49647,49648,49649,49650,49651,49652,49653,49654,49655,49656,49657,49658,49659,49660,49661,49662,49663,49664,49665,49666,49667,49668,49669,49670,49671,49672,49673,49674,49675,49676,49677,49678,49679,49680,49681,49682,49683,49684,49685,49686,49687,49688,49689,49690,49691,49692,49693,49694,49695,49696,49697,49698,49699,49700,49701,49702,49703,49704,49705,49706,49707,49708,49709,49710,49711,49712,49713,49714,49715,49716,49717,49718,49719,49720,49721,49722,49723,49724,49725,49726,49727,49728,49729,49730,49731,49732,49733,49734,49735,49736,49737,49738,49739,49740,49741,49742,49743,49744,49745,49746,49747,49748,49749,49750,49751,49752,49753,49754,49755,49756,49757,49758,49759,49760,49761,49762,49763,49764,49765,49766,49767,49768,49769,49770,49771,49772,49773,49774,49775,49776,49777,49778,49779,49780,49781,49782,49783,49784,49785,49786,49787,49788,49789,49790,49791,49792,49793,49794,49795,49796,49797,49798,49799,49800,49801,49802,49803,49804,49805,49806,49807,49808,49809,49810,49811,49812,49813,49814,49815,49816,49817,49818,49819,49820,49821,49822,49823,49824,49825,49826,49827,49828,49829,49830,49831,49832,49833,49834,49835,49836,49837,49838,49839,49840,49841,49842,49843,49844,49845,49846,49847,49848,49849,49850,49851,49852,49853,49854,49855,49856,49857,49858,49859,49860,49861,49862,49863,49864,49865,49866,49867,49868,49869,49870,49871,49872,49873,49874,49875,49876,49877,49878,49879,49880,49881,49882,49883,49884,49885,49886,49887,49888,49889,49890,49891,49892,49893,49894,49895,49896,49897,49898,49899,49900,49901,49902,49903,49904,49905,49906,49907,49908,49909,49910,49911,49912,49913,49914,49915,49916,49917,49918,49919,49920,49921,49922,49923,49924,49925,49926,49927,49928,49929,49930,49931,49932,49933,49934,49935,49936,49937,49938,49939,49940,49941,49942,49943,49944,49945,49946,49947,49948,49949,49950,49951,49952,49953,49954,49955,49956,49957,49958,49959,49960,49961,49962,49963,49964,49965,49966,49967,49968,49969,49970,49971,49972,49973,49974,49975,49976,49977,49978,49979,49980,49981,49982,49983,49984,49985,49986,49987,49988,49989,49990,49991,49992,49993,49994,49995,49996,49997,49998,49999,50000,50001,50002,50003,50004,50005,50006,50007,50008,50009,50010,50011,50012,50013,50014,50015,50016,50017,50018,50019,50020,50021,50022,50023,50024,50025,50026,50027,50028,50029,50030,50031,50032,50033,50034,50035,50036,50037,50038,50039,50040,50041,50042,50043,50044,50045,50046,50047,50048,50049,50050,50051,50052,50053,50054,50055,50056,50057,50058,50059,50060,50061,50062,50063,50064,50065,50066,50067,50068,50069,50070,50071,50072,50073,50074,50075,50076,50077,50078,50079,50080,50081,50082,50083,50084,50085,50086,50087,50088,50089,50090,50091,50092,50093,50094,50095,50096,50097,50098,50099,50100,50101,50102,50103,50104,50105,50106,50107,50108,50109,50110,50111,50112,50113,50114,50115,50116,50117,50118,50119,50120,50121,50122,50123,50124,50125,50126,50127,50128,50129,50130,50131,50132,50133,50134,50135,50136,50137,50138,50139,50140,50141,50142,50143,50144,50145,50146,50147,50148,50149,50150,50151,50152,50153,50154,50155,50156,50157,50158,50159,50160,50161,50162,50163,50164,50165,50166,50167,50168,50169,50170,50171,50172,50173,50174,50175,50176,50177,50178,50179,50180,50181,50182,50183,50184,50185,50186,50187,50188,50189,50190,50191,50192,50193,50194,50195,50196,50197,50198,50199,50200,50201,50202,50203,50204,50205,50206,50207,50208,50209,50210,50211,50212,50213,50214,50215,50216,50217,50218,50219,50220,50221,50222,50223,50224,50225,50226,50227,50228,50229,50230,50231,50232,50233,50234,50235,50236,50237,50238,50239,50240,50241,50242,50243,50244,50245,50246,50247,50248,50249,50250,50251,50252,50253,50254,50255,50256,50257,50258,50259,50260,50261,50262,50263,50264,50265,50266,50267,50268,50269,50270,50271,50272,50273,50274,50275,50276,50277,50278,50279,50280,50281,50282,50283,50284,50285,50286,50287,50288,50289,50290,50291,50292,50293,50294,50295,50296,50297,50298,50299,50300,50301,50302,50303,50304,50305,50306,50307,50308,50309,50310,50311,50312,50313,50314,50315,50316,50317,50318,50319,50320,50321,50322,50323,50324,50325,50326,50327,50328,50329,50330,50331,50332,50333,50334,50335,50336,50337,50338,50339,50340,50341,50342,50343,50344,50345,50346,50347,50348,50349,50350,50351,50352,50353,50354,50355,50356,50357,50358,50359,50360,50361,50362,50363,50364,50365,50366,50367,50368,50369,50370,50371,50372,50373,50374,50375,50376,50377,50378,50379,50380,50381,50382,50383,50384,50385,50386,50387,50388,50389,50390,50391,50392,50393,50394,50395,50396,50397,50398,50399,50400,50401,50402,50403,50404,50405,50406,50407,50408,50409,50410,50411,50412,50413,50414,50415,50416,50417,50418,50419,50420,50421,50422,50423,50424,50425,50426,50427,50428,50429,50430,50431,50432,50433,50434,50435,50436,50437,50438,50439,50440,50441,50442,50443,50444,50445,50446,50447,50448,50449,50450,50451,50452,50453,50454,50455,50456,50457,50458,50459,50460,50461,50462,50463,50464,50465,50466,50467,50468,50469,50470,50471,50472,50473,50474,50475,50476,50477,50478,50479,50480,50481,50482,50483,50484,50485,50486,50487,50488,50489,50490,50491,50492,50493,50494,50495,50496,50497,50498,50499,50500,50501,50502,50503,50504,50505,50506,50507,50508,50509,50510,50511,50512,50513,50514,50515,50516,50517,50518,50519,50520,50521,50522,50523,50524,50525,50526,50527,50528,50529,50530,50531,50532,50533,50534,50535,50536,50537,50538,50539,50540,50541,50542,50543,50544,50545,50546,50547,50548,50549,50550,50551,50552,50553,50554,50555,50556,50557,50558,50559,50560,50561,50562,50563,50564,50565,50566,50567,50568,50569,50570,50571,50572,50573,50574,50575,50576,50577,50578,50579,50580,50581,50582,50583,50584,50585,50586,50587,50588,50589,50590,50591,50592,50593,50594,50595,50596,50597,50598,50599,50600,50601,50602,50603,50604,50605,50606,50607,50608,50609,50610,50611,50612,50613,50614,50615,50616,50617,50618,50619,50620,50621,50622,50623,50624,50625,50626,50627,50628,50629,50630,50631,50632,50633,50634,50635,50636,50637,50638,50639,50640,50641,50642,50643,50644,50645,50646,50647,50648,50649,50650,50651,50652,50653,50654,50655,50656,50657,50658,50659,50660,50661,50662,50663,50664,50665,50666,50667,50668,50669,50670,50671,50672,50673,50674,50675,50676,50677,50678,50679,50680,50681,50682,50683,50684,50685,50686,50687,50688,50689,50690,50691,50692,50693,50694,50695,50696,50697,50698,50699,50700,50701,50702,50703,50704,50705,50706,50707,50708,50709,50710,50711,50712,50713,50714,50715,50716,50717,50718,50719,50720,50721,50722,50723,50724,50725,50726,50727,50728,50729,50730,50731,50732,50733,50734,50735,50736,50737,50738,50739,50740,50741,50742,50743,50744,50745,50746,50747,50748,50749,50750,50751,50752,50753,50754,50755,50756,50757,50758,50759,50760,50761,50762,50763,50764,50765,50766,50767,50768,50769,50770,50771,50772,50773,50774,50775,50776,50777,50778,50779,50780,50781,50782,50783,50784,50785,50786,50787,50788,50789,50790,50791,50792,50793,50794,50795,50796,50797,50798,50799,50800,50801,50802,50803,50804,50805,50806,50807,50808,50809,50810,50811,50812,50813,50814,50815,50816,50817,50818,50819,50820,50821,50822,50823,50824,50825,50826,50827,50828,50829,50830,50831,50832,50833,50834,50835,50836,50837,50838,50839,50840,50841,50842,50843,50844,50845,50846,50847,50848,50849,50850,50851,50852,50853,50854,50855,50856,50857,50858,50859,50860,50861,50862,50863,50864,50865,50866,50867,50868,50869,50870,50871,50872,50873,50874,50875,50876,50877,50878,50879,50880,50881,50882,50883,50884,50885,50886,50887,50888,50889,50890,50891,50892,50893,50894,50895,50896,50897,50898,50899,50900,50901,50902,50903,50904,50905,50906,50907,50908,50909,50910,50911,50912,50913,50914,50915,50916,50917,50918,50919,50920,50921,50922,50923,50924,50925,50926,50927,50928,50929,50930,50931,50932,50933,50934,50935,50936,50937,50938,50939,50940,50941,50942,50943,50944,50945,50946,50947,50948,50949,50950,50951,50952,50953,50954,50955,50956,50957,50958,50959,50960,50961,50962,50963,50964,50965,50966,50967,50968,50969,50970,50971,50972,50973,50974,50975,50976,50977,50978,50979,50980,50981,50982,50983,50984,50985,50986,50987,50988,50989,50990,50991,50992,50993,50994,50995,50996,50997,50998,50999,51000,51001,51002,51003,51004,51005,51006,51007,51008,51009,51010,51011,51012,51013,51014,51015,51016,51017,51018,51019,51020,51021,51022,51023,51024,51025,51026,51027,51028,51029,51030,51031,51032,51033,51034,51035,51036,51037,51038,51039,51040,51041,51042,51043,51044,51045,51046,51047,51048,51049,51050,51051,51052,51053,51054,51055,51056,51057,51058,51059,51060,51061,51062,51063,51064,51065,51066,51067,51068,51069,51070,51071,51072,51073,51074,51075,51076,51077,51078,51079,51080,51081,51082,51083,51084,51085,51086,51087,51088,51089,51090,51091,51092,51093,51094,51095,51096,51097,51098,51099,51100,51101,51102,51103,51104,51105,51106,51107,51108,51109,51110,51111,51112,51113,51114,51115,51116,51117,51118,51119,51120,51121,51122,51123,51124,51125,51126,51127,51128,51129,51130,51131,51132,51133,51134,51135,51136,51137,51138,51139,51140,51141,51142,51143,51144,51145,51146,51147,51148,51149,51150,51151,51152,51153,51154,51155,51156,51157,51158,51159,51160,51161,51162,51163,51164,51165,51166,51167,51168,51169,51170,51171,51172,51173,51174,51175,51176,51177,51178,51179,51180,51181,51182,51183,51184,51185,51186,51187,51188,51189,51190,51191,51192,51193,51194,51195,51196,51197,51198,51199,51200,51201,51202,51203,51204,51205,51206,51207,51208,51209,51210,51211,51212,51213,51214,51215,51216,51217,51218,51219,51220,51221,51222,51223,51224,51225,51226,51227,51228,51229,51230,51231,51232,51233,51234,51235,51236,51237,51238,51239,51240,51241,51242,51243,51244,51245,51246,51247,51248,51249,51250,51251,51252,51253,51254,51255,51256,51257,51258,51259,51260,51261,51262,51263,51264,51265,51266,51267,51268,51269,51270,51271,51272,51273,51274,51275,51276,51277,51278,51279,51280,51281,51282,51283,51284,51285,51286,51287,51288,51289,51290,51291,51292,51293,51294,51295,51296,51297,51298,51299,51300,51301,51302,51303,51304,51305,51306,51307,51308,51309,51310,51311,51312,51313,51314,51315,51316,51317,51318,51319,51320,51321,51322,51323,51324,51325,51326,51327,51328,51329,51330,51331,51332,51333,51334,51335,51336,51337,51338,51339,51340,51341,51342,51343,51344,51345,51346,51347,51348,51349,51350,51351,51352,51353,51354,51355,51356,51357,51358,51359,51360,51361,51362,51363,51364,51365,51366,51367,51368,51369,51370,51371,51372,51373,51374,51375,51376,51377,51378,51379,51380,51381,51382,51383,51384,51385,51386,51387,51388,51389,51390,51391,51392,51393,51394,51395,51396,51397,51398,51399,51400,51401,51402,51403,51404,51405,51406,51407,51408,51409,51410,51411,51412,51413,51414,51415,51416,51417,51418,51419,51420,51421,51422,51423,51424,51425,51426,51427,51428,51429,51430,51431,51432,51433,51434,51435,51436,51437,51438,51439,51440,51441,51442,51443,51444,51445,51446,51447,51448,51449,51450,51451,51452,51453,51454,51455,51456,51457,51458,51459,51460,51461,51462,51463,51464,51465,51466,51467,51468,51469,51470,51471,51472,51473,51474,51475,51476,51477,51478,51479,51480,51481,51482,51483,51484,51485,51486,51487,51488,51489,51490,51491,51492,51493,51494,51495,51496,51497,51498,51499,51500,51501,51502,51503,51504,51505,51506,51507,51508,51509,51510,51511,51512,51513,51514,51515,51516,51517,51518,51519,51520,51521,51522,51523,51524,51525,51526,51527,51528,51529,51530,51531,51532,51533,51534,51535,51536,51537,51538,51539,51540,51541,51542,51543,51544,51545,51546,51547,51548,51549,51550,51551,51552,51553,51554,51555,51556,51557,51558,51559,51560,51561,51562,51563,51564,51565,51566,51567,51568,51569,51570,51571,51572,51573,51574,51575,51576,51577,51578,51579,51580,51581,51582,51583,51584,51585,51586,51587,51588,51589,51590,51591,51592,51593,51594,51595,51596,51597,51598,51599,51600,51601,51602,51603,51604,51605,51606,51607,51608,51609,51610,51611,51612,51613,51614,51615,51616,51617,51618,51619,51620,51621,51622,51623,51624,51625,51626,51627,51628,51629,51630,51631,51632,51633,51634,51635,51636,51637,51638,51639,51640,51641,51642,51643,51644,51645,51646,51647,51648,51649,51650,51651,51652,51653,51654,51655,51656,51657,51658,51659,51660,51661,51662,51663,51664,51665,51666,51667,51668,51669,51670,51671,51672,51673,51674,51675,51676,51677,51678,51679,51680,51681,51682,51683,51684,51685,51686,51687,51688,51689,51690,51691,51692,51693,51694,51695,51696,51697,51698,51699,51700,51701,51702,51703,51704,51705,51706,51707,51708,51709,51710,51711,51712,51713,51714,51715,51716,51717,51718,51719,51720,51721,51722,51723,51724,51725,51726,51727,51728,51729,51730,51731,51732,51733,51734,51735,51736,51737,51738,51739,51740,51741,51742,51743,51744,51745,51746,51747,51748,51749,51750,51751,51752,51753,51754,51755,51756,51757,51758,51759,51760,51761,51762,51763,51764,51765,51766,51767,51768,51769,51770,51771,51772,51773,51774,51775,51776,51777,51778,51779,51780,51781,51782,51783,51784,51785,51786,51787,51788,51789,51790,51791,51792,51793,51794,51795,51796,51797,51798,51799,51800,51801,51802,51803,51804,51805,51806,51807,51808,51809,51810,51811,51812,51813,51814,51815,51816,51817,51818,51819,51820,51821,51822,51823,51824,51825,51826,51827,51828,51829,51830,51831,51832,51833,51834,51835,51836,51837,51838,51839,51840,51841,51842,51843,51844,51845,51846,51847,51848,51849,51850,51851,51852,51853,51854,51855,51856,51857,51858,51859,51860,51861,51862,51863,51864,51865,51866,51867,51868,51869,51870,51871,51872,51873,51874,51875,51876,51877,51878,51879,51880,51881,51882,51883,51884,51885,51886,51887,51888,51889,51890,51891,51892,51893,51894,51895,51896,51897,51898,51899,51900,51901,51902,51903,51904,51905,51906,51907,51908,51909,51910,51911,51912,51913,51914,51915,51916,51917,51918,51919,51920,51921,51922,51923,51924,51925,51926,51927,51928,51929,51930,51931,51932,51933,51934,51935,51936,51937,51938,51939,51940,51941,51942,51943,51944,51945,51946,51947,51948,51949,51950,51951,51952,51953,51954,51955,51956,51957,51958,51959,51960,51961,51962,51963,51964,51965,51966,51967,51968,51969,51970,51971,51972,51973,51974,51975,51976,51977,51978,51979,51980,51981,51982,51983,51984,51985,51986,51987,51988,51989,51990,51991,51992,51993,51994,51995,51996,51997,51998,51999,52000,52001,52002,52003,52004,52005,52006,52007,52008,52009,52010,52011,52012,52013,52014,52015,52016,52017,52018,52019,52020,52021,52022,52023,52024,52025,52026,52027,52028,52029,52030,52031,52032,52033,52034,52035,52036,52037,52038,52039,52040,52041,52042,52043,52044,52045,52046,52047,52048,52049,52050,52051,52052,52053,52054,52055,52056,52057,52058,52059,52060,52061,52062,52063,52064,52065,52066,52067,52068,52069,52070,52071,52072,52073,52074,52075,52076,52077,52078,52079,52080,52081,52082,52083,52084,52085,52086,52087,52088,52089,52090,52091,52092,52093,52094,52095,52096,52097,52098,52099,52100,52101,52102,52103,52104,52105,52106,52107,52108,52109,52110,52111,52112,52113,52114,52115,52116,52117,52118,52119,52120,52121,52122,52123,52124,52125,52126,52127,52128,52129,52130,52131,52132,52133,52134,52135,52136,52137,52138,52139,52140,52141,52142,52143,52144,52145,52146,52147,52148,52149,52150,52151,52152,52153,52154,52155,52156,52157,52158,52159,52160,52161,52162,52163,52164,52165,52166,52167,52168,52169,52170,52171,52172,52173,52174,52175,52176,52177,52178,52179,52180,52181,52182,52183,52184,52185,52186,52187,52188,52189,52190,52191,52192,52193,52194,52195,52196,52197,52198,52199,52200,52201,52202,52203,52204,52205,52206,52207,52208,52209,52210,52211,52212,52213,52214,52215,52216,52217,52218,52219,52220,52221,52222,52223,52224,52225,52226,52227,52228,52229,52230,52231,52232,52233,52234,52235,52236,52237,52238,52239,52240,52241,52242,52243,52244,52245,52246,52247,52248,52249,52250,52251,52252,52253,52254,52255,52256,52257,52258,52259,52260,52261,52262,52263,52264,52265,52266,52267,52268,52269,52270,52271,52272,52273,52274,52275,52276,52277,52278,52279,52280,52281,52282,52283,52284,52285,52286,52287,52288,52289,52290,52291,52292,52293,52294,52295,52296,52297,52298,52299,52300,52301,52302,52303,52304,52305,52306,52307,52308,52309,52310,52311,52312,52313,52314,52315,52316,52317,52318,52319,52320,52321,52322,52323,52324,52325,52326,52327,52328,52329,52330,52331,52332,52333,52334,52335,52336,52337,52338,52339,52340,52341,52342,52343,52344,52345,52346,52347,52348,52349,52350,52351,52352,52353,52354,52355,52356,52357,52358,52359,52360,52361,52362,52363,52364,52365,52366,52367,52368,52369,52370,52371,52372,52373,52374,52375,52376,52377,52378,52379,52380,52381,52382,52383,52384,52385,52386,52387,52388,52389,52390,52391,52392,52393,52394,52395,52396,52397,52398,52399,52400,52401,52402,52403,52404,52405,52406,52407,52408,52409,52410,52411,52412,52413,52414,52415,52416,52417,52418,52419,52420,52421,52422,52423,52424,52425,52426,52427,52428,52429,52430,52431,52432,52433,52434,52435,52436,52437,52438,52439,52440,52441,52442,52443,52444,52445,52446,52447,52448,52449,52450,52451,52452,52453,52454,52455,52456,52457,52458,52459,52460,52461,52462,52463,52464,52465,52466,52467,52468,52469,52470,52471,52472,52473,52474,52475,52476,52477,52478,52479,52480,52481,52482,52483,52484,52485,52486,52487,52488,52489,52490,52491,52492,52493,52494,52495,52496,52497,52498,52499,52500,52501,52502,52503,52504,52505,52506,52507,52508,52509,52510,52511,52512,52513,52514,52515,52516,52517,52518,52519,52520,52521,52522,52523,52524,52525,52526,52527,52528,52529,52530,52531,52532,52533,52534,52535,52536,52537,52538,52539,52540,52541,52542,52543,52544,52545,52546,52547,52548,52549,52550,52551,52552,52553,52554,52555,52556,52557,52558,52559,52560,52561,52562,52563,52564,52565,52566,52567,52568,52569,52570,52571,52572,52573,52574,52575,52576,52577,52578,52579,52580,52581,52582,52583,52584,52585,52586,52587,52588,52589,52590,52591,52592,52593,52594,52595,52596,52597,52598,52599,52600,52601,52602,52603,52604,52605,52606,52607,52608,52609,52610,52611,52612,52613,52614,52615,52616,52617,52618,52619,52620,52621,52622,52623,52624,52625,52626,52627,52628,52629,52630,52631,52632,52633,52634,52635,52636,52637,52638,52639,52640,52641,52642,52643,52644,52645,52646,52647,52648,52649,52650,52651,52652,52653,52654,52655,52656,52657,52658,52659,52660,52661,52662,52663,52664,52665,52666,52667,52668,52669,52670,52671,52672,52673,52674,52675,52676,52677,52678,52679,52680,52681,52682,52683,52684,52685,52686,52687,52688,52689,52690,52691,52692,52693,52694,52695,52696,52697,52698,52699,52700,52701,52702,52703,52704,52705,52706,52707,52708,52709,52710,52711,52712,52713,52714,52715,52716,52717,52718,52719,52720,52721,52722,52723,52724,52725,52726,52727,52728,52729,52730,52731,52732,52733,52734,52735,52736,52737,52738,52739,52740,52741,52742,52743,52744,52745,52746,52747,52748,52749,52750,52751,52752,52753,52754,52755,52756,52757,52758,52759,52760,52761,52762,52763,52764,52765,52766,52767,52768,52769,52770,52771,52772,52773,52774,52775,52776,52777,52778,52779,52780,52781,52782,52783,52784,52785,52786,52787,52788,52789,52790,52791,52792,52793,52794,52795,52796,52797,52798,52799,52800,52801,52802,52803,52804,52805,52806,52807,52808,52809,52810,52811,52812,52813,52814,52815,52816,52817,52818,52819,52820,52821,52822,52823,52824,52825,52826,52827,52828,52829,52830,52831,52832,52833,52834,52835,52836,52837,52838,52839,52840,52841,52842,52843,52844,52845,52846,52847,52848,52849,52850,52851,52852,52853,52854,52855,52856,52857,52858,52859,52860,52861,52862,52863,52864,52865,52866,52867,52868,52869,52870,52871,52872,52873,52874,52875,52876,52877,52878,52879,52880,52881,52882,52883,52884,52885,52886,52887,52888,52889,52890,52891,52892,52893,52894,52895,52896,52897,52898,52899,52900,52901,52902,52903,52904,52905,52906,52907,52908,52909,52910,52911,52912,52913,52914,52915,52916,52917,52918,52919,52920,52921,52922,52923,52924,52925,52926,52927,52928,52929,52930,52931,52932,52933,52934,52935,52936,52937,52938,52939,52940,52941,52942,52943,52944,52945,52946,52947,52948,52949,52950,52951,52952,52953,52954,52955,52956,52957,52958,52959,52960,52961,52962,52963,52964,52965,52966,52967,52968,52969,52970,52971,52972,52973,52974,52975,52976,52977,52978,52979,52980,52981,52982,52983,52984,52985,52986,52987,52988,52989,52990,52991,52992,52993,52994,52995,52996,52997,52998,52999,53000,53001,53002,53003,53004,53005,53006,53007,53008,53009,53010,53011,53012,53013,53014,53015,53016,53017,53018,53019,53020,53021,53022,53023,53024,53025,53026,53027,53028,53029,53030,53031,53032,53033,53034,53035,53036,53037,53038,53039,53040,53041,53042,53043,53044,53045,53046,53047,53048,53049,53050,53051,53052,53053,53054,53055,53056,53057,53058,53059,53060,53061,53062,53063,53064,53065,53066,53067,53068,53069,53070,53071,53072,53073,53074,53075,53076,53077,53078,53079,53080,53081,53082,53083,53084,53085,53086,53087,53088,53089,53090,53091,53092,53093,53094,53095,53096,53097,53098,53099,53100,53101,53102,53103,53104,53105,53106,53107,53108,53109,53110,53111,53112,53113,53114,53115,53116,53117,53118,53119,53120,53121,53122,53123,53124,53125,53126,53127,53128,53129,53130,53131,53132,53133,53134,53135,53136,53137,53138,53139,53140,53141,53142,53143,53144,53145,53146,53147,53148,53149,53150,53151,53152,53153,53154,53155,53156,53157,53158,53159,53160,53161,53162,53163,53164,53165,53166,53167,53168,53169,53170,53171,53172,53173,53174,53175,53176,53177,53178,53179,53180,53181,53182,53183,53184,53185,53186,53187,53188,53189,53190,53191,53192,53193,53194,53195,53196,53197,53198,53199,53200,53201,53202,53203,53204,53205,53206,53207,53208,53209,53210,53211,53212,53213,53214,53215,53216,53217,53218,53219,53220,53221,53222,53223,53224,53225,53226,53227,53228,53229,53230,53231,53232,53233,53234,53235,53236,53237,53238,53239,53240,53241,53242,53243,53244,53245,53246,53247,53248,53249,53250,53251,53252,53253,53254,53255,53256,53257,53258,53259,53260,53261,53262,53263,53264,53265,53266,53267,53268,53269,53270,53271,53272,53273,53274,53275,53276,53277,53278,53279,53280,53281,53282,53283,53284,53285,53286,53287,53288,53289,53290,53291,53292,53293,53294,53295,53296,53297,53298,53299,53300,53301,53302,53303,53304,53305,53306,53307,53308,53309,53310,53311,53312,53313,53314,53315,53316,53317,53318,53319,53320,53321,53322,53323,53324,53325,53326,53327,53328,53329,53330,53331,53332,53333,53334,53335,53336,53337,53338,53339,53340,53341,53342,53343,53344,53345,53346,53347,53348,53349,53350,53351,53352,53353,53354,53355,53356,53357,53358,53359,53360,53361,53362,53363,53364,53365,53366,53367,53368,53369,53370,53371,53372,53373,53374,53375,53376,53377,53378,53379,53380,53381,53382,53383,53384,53385,53386,53387,53388,53389,53390,53391,53392,53393,53394,53395,53396,53397,53398,53399,53400,53401,53402,53403,53404,53405,53406,53407,53408,53409,53410,53411,53412,53413,53414,53415,53416,53417,53418,53419,53420,53421,53422,53423,53424,53425,53426,53427,53428,53429,53430,53431,53432,53433,53434,53435,53436,53437,53438,53439,53440,53441,53442,53443,53444,53445,53446,53447,53448,53449,53450,53451,53452,53453,53454,53455,53456,53457,53458,53459,53460,53461,53462,53463,53464,53465,53466,53467,53468,53469,53470,53471,53472,53473,53474,53475,53476,53477,53478,53479,53480,53481,53482,53483,53484,53485,53486,53487,53488,53489,53490,53491,53492,53493,53494,53495,53496,53497,53498,53499,53500,53501,53502,53503,53504,53505,53506,53507,53508,53509,53510,53511,53512,53513,53514,53515,53516,53517,53518,53519,53520,53521,53522,53523,53524,53525,53526,53527,53528,53529,53530,53531,53532,53533,53534,53535,53536,53537,53538,53539,53540,53541,53542,53543,53544,53545,53546,53547,53548,53549,53550,53551,53552,53553,53554,53555,53556,53557,53558,53559,53560,53561,53562,53563,53564,53565,53566,53567,53568,53569,53570,53571,53572,53573,53574,53575,53576,53577,53578,53579,53580,53581,53582,53583,53584,53585,53586,53587,53588,53589,53590,53591,53592,53593,53594,53595,53596,53597,53598,53599,53600,53601,53602,53603,53604,53605,53606,53607,53608,53609,53610,53611,53612,53613,53614,53615,53616,53617,53618,53619,53620,53621,53622,53623,53624,53625,53626,53627,53628,53629,53630,53631,53632,53633,53634,53635,53636,53637,53638,53639,53640,53641,53642,53643,53644,53645,53646,53647,53648,53649,53650,53651,53652,53653,53654,53655,53656,53657,53658,53659,53660,53661,53662,53663,53664,53665,53666,53667,53668,53669,53670,53671,53672,53673,53674,53675,53676,53677,53678,53679,53680,53681,53682,53683,53684,53685,53686,53687,53688,53689,53690,53691,53692,53693,53694,53695,53696,53697,53698,53699,53700,53701,53702,53703,53704,53705,53706,53707,53708,53709,53710,53711,53712,53713,53714,53715,53716,53717,53718,53719,53720,53721,53722,53723,53724,53725,53726,53727,53728,53729,53730,53731,53732,53733,53734,53735,53736,53737,53738,53739,53740,53741,53742,53743,53744,53745,53746,53747,53748,53749,53750,53751,53752,53753,53754,53755,53756,53757,53758,53759,53760,53761,53762,53763,53764,53765,53766,53767,53768,53769,53770,53771,53772,53773,53774,53775,53776,53777,53778,53779,53780,53781,53782,53783,53784,53785,53786,53787,53788,53789,53790,53791,53792,53793,53794,53795,53796,53797,53798,53799,53800,53801,53802,53803,53804,53805,53806,53807,53808,53809,53810,53811,53812,53813,53814,53815,53816,53817,53818,53819,53820,53821,53822,53823,53824,53825,53826,53827,53828,53829,53830,53831,53832,53833,53834,53835,53836,53837,53838,53839,53840,53841,53842,53843,53844,53845,53846,53847,53848,53849,53850,53851,53852,53853,53854,53855,53856,53857,53858,53859,53860,53861,53862,53863,53864,53865,53866,53867,53868,53869,53870,53871,53872,53873,53874,53875,53876,53877,53878,53879,53880,53881,53882,53883,53884,53885,53886,53887,53888,53889,53890,53891,53892,53893,53894,53895,53896,53897,53898,53899,53900,53901,53902,53903,53904,53905,53906,53907,53908,53909,53910,53911,53912,53913,53914,53915,53916,53917,53918,53919,53920,53921,53922,53923,53924,53925,53926,53927,53928,53929,53930,53931,53932,53933,53934,53935,53936,53937,53938,53939,53940,53941,53942,53943,53944,53945,53946,53947,53948,53949,53950,53951,53952,53953,53954,53955,53956,53957,53958,53959,53960,53961,53962,53963,53964,53965,53966,53967,53968,53969,53970,53971,53972,53973,53974,53975,53976,53977,53978,53979,53980,53981,53982,53983,53984,53985,53986,53987,53988,53989,53990,53991,53992,53993,53994,53995,53996,53997,53998,53999,54000,54001,54002,54003,54004,54005,54006,54007,54008,54009,54010,54011,54012,54013,54014,54015,54016,54017,54018,54019,54020,54021,54022,54023,54024,54025,54026,54027,54028,54029,54030,54031,54032,54033,54034,54035,54036,54037,54038,54039,54040,54041,54042,54043,54044,54045,54046,54047,54048,54049,54050,54051,54052,54053,54054,54055,54056,54057,54058,54059,54060,54061,54062,54063,54064,54065,54066,54067,54068,54069,54070,54071,54072,54073,54074,54075,54076,54077,54078,54079,54080,54081,54082,54083,54084,54085,54086,54087,54088,54089,54090,54091,54092,54093,54094,54095,54096,54097,54098,54099,54100,54101,54102,54103,54104,54105,54106,54107,54108,54109,54110,54111,54112,54113,54114,54115,54116,54117,54118,54119,54120,54121,54122,54123,54124,54125,54126,54127,54128,54129,54130,54131,54132,54133,54134,54135,54136,54137,54138,54139,54140,54141,54142,54143,54144,54145,54146,54147,54148,54149,54150,54151,54152,54153,54154,54155,54156,54157,54158,54159,54160,54161,54162,54163,54164,54165,54166,54167,54168,54169,54170,54171,54172,54173,54174,54175,54176,54177,54178,54179,54180,54181,54182,54183,54184,54185,54186,54187,54188,54189,54190,54191,54192,54193,54194,54195,54196,54197,54198,54199,54200,54201,54202,54203,54204,54205,54206,54207,54208,54209,54210,54211,54212,54213,54214,54215,54216,54217,54218,54219,54220,54221,54222,54223,54224,54225,54226,54227,54228,54229,54230,54231,54232,54233,54234,54235,54236,54237,54238,54239,54240,54241,54242,54243,54244,54245,54246,54247,54248,54249,54250,54251,54252,54253,54254,54255,54256,54257,54258,54259,54260,54261,54262,54263,54264,54265,54266,54267,54268,54269,54270,54271,54272,54273,54274,54275,54276,54277,54278,54279,54280,54281,54282,54283,54284,54285,54286,54287,54288,54289,54290,54291,54292,54293,54294,54295,54296,54297,54298,54299,54300,54301,54302,54303,54304,54305,54306,54307,54308,54309,54310,54311,54312,54313,54314,54315,54316,54317,54318,54319,54320,54321,54322,54323,54324,54325,54326,54327,54328,54329,54330,54331,54332,54333,54334,54335,54336,54337,54338,54339,54340,54341,54342,54343,54344,54345,54346,54347,54348,54349,54350,54351,54352,54353,54354,54355,54356,54357,54358,54359,54360,54361,54362,54363,54364,54365,54366,54367,54368,54369,54370,54371,54372,54373,54374,54375,54376,54377,54378,54379,54380,54381,54382,54383,54384,54385,54386,54387,54388,54389,54390,54391,54392,54393,54394,54395,54396,54397,54398,54399,54400,54401,54402,54403,54404,54405,54406,54407,54408,54409,54410,54411,54412,54413,54414,54415,54416,54417,54418,54419,54420,54421,54422,54423,54424,54425,54426,54427,54428,54429,54430,54431,54432,54433,54434,54435,54436,54437,54438,54439,54440,54441,54442,54443,54444,54445,54446,54447,54448,54449,54450,54451,54452,54453,54454,54455,54456,54457,54458,54459,54460,54461,54462,54463,54464,54465,54466,54467,54468,54469,54470,54471,54472,54473,54474,54475,54476,54477,54478,54479,54480,54481,54482,54483,54484,54485,54486,54487,54488,54489,54490,54491,54492,54493,54494,54495,54496,54497,54498,54499,54500,54501,54502,54503,54504,54505,54506,54507,54508,54509,54510,54511,54512,54513,54514,54515,54516,54517,54518,54519,54520,54521,54522,54523,54524,54525,54526,54527,54528,54529,54530,54531,54532,54533,54534,54535,54536,54537,54538,54539,54540,54541,54542,54543,54544,54545,54546,54547,54548,54549,54550,54551,54552,54553,54554,54555,54556,54557,54558,54559,54560,54561,54562,54563,54564,54565,54566,54567,54568,54569,54570,54571,54572,54573,54574,54575,54576,54577,54578,54579,54580,54581,54582,54583,54584,54585,54586,54587,54588,54589,54590,54591,54592,54593,54594,54595,54596,54597,54598,54599,54600,54601,54602,54603,54604,54605,54606,54607,54608,54609,54610,54611,54612,54613,54614,54615,54616,54617,54618,54619,54620,54621,54622,54623,54624,54625,54626,54627,54628,54629,54630,54631,54632,54633,54634,54635,54636,54637,54638,54639,54640,54641,54642,54643,54644,54645,54646,54647,54648,54649,54650,54651,54652,54653,54654,54655,54656,54657,54658,54659,54660,54661,54662,54663,54664,54665,54666,54667,54668,54669,54670,54671,54672,54673,54674,54675,54676,54677,54678,54679,54680,54681,54682,54683,54684,54685,54686,54687,54688,54689,54690,54691,54692,54693,54694,54695,54696,54697,54698,54699,54700,54701,54702,54703,54704,54705,54706,54707,54708,54709,54710,54711,54712,54713,54714,54715,54716,54717,54718,54719,54720,54721,54722,54723,54724,54725,54726,54727,54728,54729,54730,54731,54732,54733,54734,54735,54736,54737,54738,54739,54740,54741,54742,54743,54744,54745,54746,54747,54748,54749,54750,54751,54752,54753,54754,54755,54756,54757,54758,54759,54760,54761,54762,54763,54764,54765,54766,54767,54768,54769,54770,54771,54772,54773,54774,54775,54776,54777,54778,54779,54780,54781,54782,54783,54784,54785,54786,54787,54788,54789,54790,54791,54792,54793,54794,54795,54796,54797,54798,54799,54800,54801,54802,54803,54804,54805,54806,54807,54808,54809,54810,54811,54812,54813,54814,54815,54816,54817,54818,54819,54820,54821,54822,54823,54824,54825,54826,54827,54828,54829,54830,54831,54832,54833,54834,54835,54836,54837,54838,54839,54840,54841,54842,54843,54844,54845,54846,54847,54848,54849,54850,54851,54852,54853,54854,54855,54856,54857,54858,54859,54860,54861,54862,54863,54864,54865,54866,54867,54868,54869,54870,54871,54872,54873,54874,54875,54876,54877,54878,54879,54880,54881,54882,54883,54884,54885,54886,54887,54888,54889,54890,54891,54892,54893,54894,54895,54896,54897,54898,54899,54900,54901,54902,54903,54904,54905,54906,54907,54908,54909,54910,54911,54912,54913,54914,54915,54916,54917,54918,54919,54920,54921,54922,54923,54924,54925,54926,54927,54928,54929,54930,54931,54932,54933,54934,54935,54936,54937,54938,54939,54940,54941,54942,54943,54944,54945,54946,54947,54948,54949,54950,54951,54952,54953,54954,54955,54956,54957,54958,54959,54960,54961,54962,54963,54964,54965,54966,54967,54968,54969,54970,54971,54972,54973,54974,54975,54976,54977,54978,54979,54980,54981,54982,54983,54984,54985,54986,54987,54988,54989,54990,54991,54992,54993,54994,54995,54996,54997,54998,54999,55000,55001,55002,55003,55004,55005,55006,55007,55008,55009,55010,55011,55012,55013,55014,55015,55016,55017,55018,55019,55020,55021,55022,55023,55024,55025,55026,55027,55028,55029,55030,55031,55032,55033,55034,55035,55036,55037,55038,55039,55040,55041,55042,55043,55044,55045,55046,55047,55048,55049,55050,55051,55052,55053,55054,55055,55056,55057,55058,55059,55060,55061,55062,55063,55064,55065,55066,55067,55068,55069,55070,55071,55072,55073,55074,55075,55076,55077,55078,55079,55080,55081,55082,55083,55084,55085,55086,55087,55088,55089,55090,55091,55092,55093,55094,55095,55096,55097,55098,55099,55100,55101,55102,55103,55104,55105,55106,55107,55108,55109,55110,55111,55112,55113,55114,55115,55116,55117,55118,55119,55120,55121,55122,55123,55124,55125,55126,55127,55128,55129,55130,55131,55132,55133,55134,55135,55136,55137,55138,55139,55140,55141,55142,55143,55144,55145,55146,55147,55148,55149,55150,55151,55152,55153,55154,55155,55156,55157,55158,55159,55160,55161,55162,55163,55164,55165,55166,55167,55168,55169,55170,55171,55172,55173,55174,55175,55176,55177,55178,55179,55180,55181,55182,55183,55184,55185,55186,55187,55188,55189,55190,55191,55192,55193,55194,55195,55196,55197,55198,55199,55200,55201,55202,55203,55216,55217,55218,55219,55220,55221,55222,55223,55224,55225,55226,55227,55228,55229,55230,55231,55232,55233,55234,55235,55236,55237,55238,55243,55244,55245,55246,55247,55248,55249,55250,55251,55252,55253,55254,55255,55256,55257,55258,55259,55260,55261,55262,55263,55264,55265,55266,55267,55268,55269,55270,55271,55272,55273,55274,55275,55276,55277,55278,55279,55280,55281,55282,55283,55284,55285,55286,55287,55288,55289,55290,55291,63744,63745,63746,63747,63748,63749,63750,63751,63752,63753,63754,63755,63756,63757,63758,63759,63760,63761,63762,63763,63764,63765,63766,63767,63768,63769,63770,63771,63772,63773,63774,63775,63776,63777,63778,63779,63780,63781,63782,63783,63784,63785,63786,63787,63788,63789,63790,63791,63792,63793,63794,63795,63796,63797,63798,63799,63800,63801,63802,63803,63804,63805,63806,63807,63808,63809,63810,63811,63812,63813,63814,63815,63816,63817,63818,63819,63820,63821,63822,63823,63824,63825,63826,63827,63828,63829,63830,63831,63832,63833,63834,63835,63836,63837,63838,63839,63840,63841,63842,63843,63844,63845,63846,63847,63848,63849,63850,63851,63852,63853,63854,63855,63856,63857,63858,63859,63860,63861,63862,63863,63864,63865,63866,63867,63868,63869,63870,63871,63872,63873,63874,63875,63876,63877,63878,63879,63880,63881,63882,63883,63884,63885,63886,63887,63888,63889,63890,63891,63892,63893,63894,63895,63896,63897,63898,63899,63900,63901,63902,63903,63904,63905,63906,63907,63908,63909,63910,63911,63912,63913,63914,63915,63916,63917,63918,63919,63920,63921,63922,63923,63924,63925,63926,63927,63928,63929,63930,63931,63932,63933,63934,63935,63936,63937,63938,63939,63940,63941,63942,63943,63944,63945,63946,63947,63948,63949,63950,63951,63952,63953,63954,63955,63956,63957,63958,63959,63960,63961,63962,63963,63964,63965,63966,63967,63968,63969,63970,63971,63972,63973,63974,63975,63976,63977,63978,63979,63980,63981,63982,63983,63984,63985,63986,63987,63988,63989,63990,63991,63992,63993,63994,63995,63996,63997,63998,63999,64000,64001,64002,64003,64004,64005,64006,64007,64008,64009,64010,64011,64012,64013,64014,64015,64016,64017,64018,64019,64020,64021,64022,64023,64024,64025,64026,64027,64028,64029,64030,64031,64032,64033,64034,64035,64036,64037,64038,64039,64040,64041,64042,64043,64044,64045,64046,64047,64048,64049,64050,64051,64052,64053,64054,64055,64056,64057,64058,64059,64060,64061,64062,64063,64064,64065,64066,64067,64068,64069,64070,64071,64072,64073,64074,64075,64076,64077,64078,64079,64080,64081,64082,64083,64084,64085,64086,64087,64088,64089,64090,64091,64092,64093,64094,64095,64096,64097,64098,64099,64100,64101,64102,64103,64104,64105,64106,64107,64108,64109,64112,64113,64114,64115,64116,64117,64118,64119,64120,64121,64122,64123,64124,64125,64126,64127,64128,64129,64130,64131,64132,64133,64134,64135,64136,64137,64138,64139,64140,64141,64142,64143,64144,64145,64146,64147,64148,64149,64150,64151,64152,64153,64154,64155,64156,64157,64158,64159,64160,64161,64162,64163,64164,64165,64166,64167,64168,64169,64170,64171,64172,64173,64174,64175,64176,64177,64178,64179,64180,64181,64182,64183,64184,64185,64186,64187,64188,64189,64190,64191,64192,64193,64194,64195,64196,64197,64198,64199,64200,64201,64202,64203,64204,64205,64206,64207,64208,64209,64210,64211,64212,64213,64214,64215,64216,64217,64256,64257,64258,64259,64260,64261,64262,64275,64276,64277,64278,64279,64285,64287,64288,64289,64290,64291,64292,64293,64294,64295,64296,64298,64299,64300,64301,64302,64303,64304,64305,64306,64307,64308,64309,64310,64312,64313,64314,64315,64316,64318,64320,64321,64323,64324,64326,64327,64328,64329,64330,64331,64332,64333,64334,64335,64336,64337,64338,64339,64340,64341,64342,64343,64344,64345,64346,64347,64348,64349,64350,64351,64352,64353,64354,64355,64356,64357,64358,64359,64360,64361,64362,64363,64364,64365,64366,64367,64368,64369,64370,64371,64372,64373,64374,64375,64376,64377,64378,64379,64380,64381,64382,64383,64384,64385,64386,64387,64388,64389,64390,64391,64392,64393,64394,64395,64396,64397,64398,64399,64400,64401,64402,64403,64404,64405,64406,64407,64408,64409,64410,64411,64412,64413,64414,64415,64416,64417,64418,64419,64420,64421,64422,64423,64424,64425,64426,64427,64428,64429,64430,64431,64432,64433,64467,64468,64469,64470,64471,64472,64473,64474,64475,64476,64477,64478,64479,64480,64481,64482,64483,64484,64485,64486,64487,64488,64489,64490,64491,64492,64493,64494,64495,64496,64497,64498,64499,64500,64501,64502,64503,64504,64505,64506,64507,64508,64509,64510,64511,64512,64513,64514,64515,64516,64517,64518,64519,64520,64521,64522,64523,64524,64525,64526,64527,64528,64529,64530,64531,64532,64533,64534,64535,64536,64537,64538,64539,64540,64541,64542,64543,64544,64545,64546,64547,64548,64549,64550,64551,64552,64553,64554,64555,64556,64557,64558,64559,64560,64561,64562,64563,64564,64565,64566,64567,64568,64569,64570,64571,64572,64573,64574,64575,64576,64577,64578,64579,64580,64581,64582,64583,64584,64585,64586,64587,64588,64589,64590,64591,64592,64593,64594,64595,64596,64597,64598,64599,64600,64601,64602,64603,64604,64605,64606,64607,64608,64609,64610,64611,64612,64613,64614,64615,64616,64617,64618,64619,64620,64621,64622,64623,64624,64625,64626,64627,64628,64629,64630,64631,64632,64633,64634,64635,64636,64637,64638,64639,64640,64641,64642,64643,64644,64645,64646,64647,64648,64649,64650,64651,64652,64653,64654,64655,64656,64657,64658,64659,64660,64661,64662,64663,64664,64665,64666,64667,64668,64669,64670,64671,64672,64673,64674,64675,64676,64677,64678,64679,64680,64681,64682,64683,64684,64685,64686,64687,64688,64689,64690,64691,64692,64693,64694,64695,64696,64697,64698,64699,64700,64701,64702,64703,64704,64705,64706,64707,64708,64709,64710,64711,64712,64713,64714,64715,64716,64717,64718,64719,64720,64721,64722,64723,64724,64725,64726,64727,64728,64729,64730,64731,64732,64733,64734,64735,64736,64737,64738,64739,64740,64741,64742,64743,64744,64745,64746,64747,64748,64749,64750,64751,64752,64753,64754,64755,64756,64757,64758,64759,64760,64761,64762,64763,64764,64765,64766,64767,64768,64769,64770,64771,64772,64773,64774,64775,64776,64777,64778,64779,64780,64781,64782,64783,64784,64785,64786,64787,64788,64789,64790,64791,64792,64793,64794,64795,64796,64797,64798,64799,64800,64801,64802,64803,64804,64805,64806,64807,64808,64809,64810,64811,64812,64813,64814,64815,64816,64817,64818,64819,64820,64821,64822,64823,64824,64825,64826,64827,64828,64829,64848,64849,64850,64851,64852,64853,64854,64855,64856,64857,64858,64859,64860,64861,64862,64863,64864,64865,64866,64867,64868,64869,64870,64871,64872,64873,64874,64875,64876,64877,64878,64879,64880,64881,64882,64883,64884,64885,64886,64887,64888,64889,64890,64891,64892,64893,64894,64895,64896,64897,64898,64899,64900,64901,64902,64903,64904,64905,64906,64907,64908,64909,64910,64911,64914,64915,64916,64917,64918,64919,64920,64921,64922,64923,64924,64925,64926,64927,64928,64929,64930,64931,64932,64933,64934,64935,64936,64937,64938,64939,64940,64941,64942,64943,64944,64945,64946,64947,64948,64949,64950,64951,64952,64953,64954,64955,64956,64957,64958,64959,64960,64961,64962,64963,64964,64965,64966,64967,65008,65009,65010,65011,65012,65013,65014,65015,65016,65017,65018,65019,65136,65137,65138,65139,65140,65142,65143,65144,65145,65146,65147,65148,65149,65150,65151,65152,65153,65154,65155,65156,65157,65158,65159,65160,65161,65162,65163,65164,65165,65166,65167,65168,65169,65170,65171,65172,65173,65174,65175,65176,65177,65178,65179,65180,65181,65182,65183,65184,65185,65186,65187,65188,65189,65190,65191,65192,65193,65194,65195,65196,65197,65198,65199,65200,65201,65202,65203,65204,65205,65206,65207,65208,65209,65210,65211,65212,65213,65214,65215,65216,65217,65218,65219,65220,65221,65222,65223,65224,65225,65226,65227,65228,65229,65230,65231,65232,65233,65234,65235,65236,65237,65238,65239,65240,65241,65242,65243,65244,65245,65246,65247,65248,65249,65250,65251,65252,65253,65254,65255,65256,65257,65258,65259,65260,65261,65262,65263,65264,65265,65266,65267,65268,65269,65270,65271,65272,65273,65274,65275,65276,65313,65314,65315,65316,65317,65318,65319,65320,65321,65322,65323,65324,65325,65326,65327,65328,65329,65330,65331,65332,65333,65334,65335,65336,65337,65338,65345,65346,65347,65348,65349,65350,65351,65352,65353,65354,65355,65356,65357,65358,65359,65360,65361,65362,65363,65364,65365,65366,65367,65368,65369,65370,65382,65383,65384,65385,65386,65387,65388,65389,65390,65391,65392,65393,65394,65395,65396,65397,65398,65399,65400,65401,65402,65403,65404,65405,65406,65407,65408,65409,65410,65411,65412,65413,65414,65415,65416,65417,65418,65419,65420,65421,65422,65423,65424,65425,65426,65427,65428,65429,65430,65431,65432,65433,65434,65435,65436,65437,65438,65439,65440,65441,65442,65443,65444,65445,65446,65447,65448,65449,65450,65451,65452,65453,65454,65455,65456,65457,65458,65459,65460,65461,65462,65463,65464,65465,65466,65467,65468,65469,65470,65474,65475,65476,65477,65478,65479,65482,65483,65484,65485,65486,65487,65490,65491,65492,65493,65494,65495,65498,65499,65500';\nvar arr = str.split(',').map(function(code) {\n  return parseInt(code, 10);\n});\nmodule.exports = arr;\n},{}],5:[function(require,module,exports){\n// http://wiki.commonjs.org/wiki/Unit_Testing/1.0\n//\n// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!\n//\n// Originally from narwhal.js (http://narwhaljs.org)\n// Copyright (c) 2009 Thomas Robinson <280north.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the 'Software'), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// when used in node, this will actually load the util module we depend on\n// versus loading the builtin util module as happens otherwise\n// this is a bug in node module loading as far as I am concerned\nvar util = require('util/');\n\nvar pSlice = Array.prototype.slice;\nvar hasOwn = Object.prototype.hasOwnProperty;\n\n// 1. The assert module provides functions that throw\n// AssertionError's when particular conditions are not met. The\n// assert module must conform to the following interface.\n\nvar assert = module.exports = ok;\n\n// 2. The AssertionError is defined in assert.\n// new assert.AssertionError({ message: message,\n//                             actual: actual,\n//                             expected: expected })\n\nassert.AssertionError = function AssertionError(options) {\n  this.name = 'AssertionError';\n  this.actual = options.actual;\n  this.expected = options.expected;\n  this.operator = options.operator;\n  if (options.message) {\n    this.message = options.message;\n    this.generatedMessage = false;\n  } else {\n    this.message = getMessage(this);\n    this.generatedMessage = true;\n  }\n  var stackStartFunction = options.stackStartFunction || fail;\n\n  if (Error.captureStackTrace) {\n    Error.captureStackTrace(this, stackStartFunction);\n  }\n  else {\n    // non v8 browsers so we can have a stacktrace\n    var err = new Error();\n    if (err.stack) {\n      var out = err.stack;\n\n      // try to strip useless frames\n      var fn_name = stackStartFunction.name;\n      var idx = out.indexOf('\\n' + fn_name);\n      if (idx >= 0) {\n        // once we have located the function frame\n        // we need to strip out everything before it (and its line)\n        var next_line = out.indexOf('\\n', idx + 1);\n        out = out.substring(next_line + 1);\n      }\n\n      this.stack = out;\n    }\n  }\n};\n\n// assert.AssertionError instanceof Error\nutil.inherits(assert.AssertionError, Error);\n\nfunction replacer(key, value) {\n  if (util.isUndefined(value)) {\n    return '' + value;\n  }\n  if (util.isNumber(value) && !isFinite(value)) {\n    return value.toString();\n  }\n  if (util.isFunction(value) || util.isRegExp(value)) {\n    return value.toString();\n  }\n  return value;\n}\n\nfunction truncate(s, n) {\n  if (util.isString(s)) {\n    return s.length < n ? s : s.slice(0, n);\n  } else {\n    return s;\n  }\n}\n\nfunction getMessage(self) {\n  return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +\n         self.operator + ' ' +\n         truncate(JSON.stringify(self.expected, replacer), 128);\n}\n\n// At present only the three keys mentioned above are used and\n// understood by the spec. Implementations or sub modules can pass\n// other keys to the AssertionError's constructor - they will be\n// ignored.\n\n// 3. All of the following functions must throw an AssertionError\n// when a corresponding condition is not met, with a message that\n// may be undefined if not provided.  All assertion methods provide\n// both the actual and expected values to the assertion error for\n// display purposes.\n\nfunction fail(actual, expected, message, operator, stackStartFunction) {\n  throw new assert.AssertionError({\n    message: message,\n    actual: actual,\n    expected: expected,\n    operator: operator,\n    stackStartFunction: stackStartFunction\n  });\n}\n\n// EXTENSION! allows for well behaved errors defined elsewhere.\nassert.fail = fail;\n\n// 4. Pure assertion tests whether a value is truthy, as determined\n// by !!guard.\n// assert.ok(guard, message_opt);\n// This statement is equivalent to assert.equal(true, !!guard,\n// message_opt);. To test strictly for the value true, use\n// assert.strictEqual(true, guard, message_opt);.\n\nfunction ok(value, message) {\n  if (!value) fail(value, true, message, '==', assert.ok);\n}\nassert.ok = ok;\n\n// 5. The equality assertion tests shallow, coercive equality with\n// ==.\n// assert.equal(actual, expected, message_opt);\n\nassert.equal = function equal(actual, expected, message) {\n  if (actual != expected) fail(actual, expected, message, '==', assert.equal);\n};\n\n// 6. The non-equality assertion tests for whether two objects are not equal\n// with != assert.notEqual(actual, expected, message_opt);\n\nassert.notEqual = function notEqual(actual, expected, message) {\n  if (actual == expected) {\n    fail(actual, expected, message, '!=', assert.notEqual);\n  }\n};\n\n// 7. The equivalence assertion tests a deep equality relation.\n// assert.deepEqual(actual, expected, message_opt);\n\nassert.deepEqual = function deepEqual(actual, expected, message) {\n  if (!_deepEqual(actual, expected)) {\n    fail(actual, expected, message, 'deepEqual', assert.deepEqual);\n  }\n};\n\nfunction _deepEqual(actual, expected) {\n  // 7.1. All identical values are equivalent, as determined by ===.\n  if (actual === expected) {\n    return true;\n\n  } else if (util.isBuffer(actual) && util.isBuffer(expected)) {\n    if (actual.length != expected.length) return false;\n\n    for (var i = 0; i < actual.length; i++) {\n      if (actual[i] !== expected[i]) return false;\n    }\n\n    return true;\n\n  // 7.2. If the expected value is a Date object, the actual value is\n  // equivalent if it is also a Date object that refers to the same time.\n  } else if (util.isDate(actual) && util.isDate(expected)) {\n    return actual.getTime() === expected.getTime();\n\n  // 7.3 If the expected value is a RegExp object, the actual value is\n  // equivalent if it is also a RegExp object with the same source and\n  // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).\n  } else if (util.isRegExp(actual) && util.isRegExp(expected)) {\n    return actual.source === expected.source &&\n           actual.global === expected.global &&\n           actual.multiline === expected.multiline &&\n           actual.lastIndex === expected.lastIndex &&\n           actual.ignoreCase === expected.ignoreCase;\n\n  // 7.4. Other pairs that do not both pass typeof value == 'object',\n  // equivalence is determined by ==.\n  } else if (!util.isObject(actual) && !util.isObject(expected)) {\n    return actual == expected;\n\n  // 7.5 For all other Object pairs, including Array objects, equivalence is\n  // determined by having the same number of owned properties (as verified\n  // with Object.prototype.hasOwnProperty.call), the same set of keys\n  // (although not necessarily the same order), equivalent values for every\n  // corresponding key, and an identical 'prototype' property. Note: this\n  // accounts for both named and indexed properties on Arrays.\n  } else {\n    return objEquiv(actual, expected);\n  }\n}\n\nfunction isArguments(object) {\n  return Object.prototype.toString.call(object) == '[object Arguments]';\n}\n\nfunction objEquiv(a, b) {\n  if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))\n    return false;\n  // an identical 'prototype' property.\n  if (a.prototype !== b.prototype) return false;\n  // if one is a primitive, the other must be same\n  if (util.isPrimitive(a) || util.isPrimitive(b)) {\n    return a === b;\n  }\n  var aIsArgs = isArguments(a),\n      bIsArgs = isArguments(b);\n  if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))\n    return false;\n  if (aIsArgs) {\n    a = pSlice.call(a);\n    b = pSlice.call(b);\n    return _deepEqual(a, b);\n  }\n  var ka = objectKeys(a),\n      kb = objectKeys(b),\n      key, i;\n  // having the same number of owned properties (keys incorporates\n  // hasOwnProperty)\n  if (ka.length != kb.length)\n    return false;\n  //the same set of keys (although not necessarily the same order),\n  ka.sort();\n  kb.sort();\n  //~~~cheap key test\n  for (i = ka.length - 1; i >= 0; i--) {\n    if (ka[i] != kb[i])\n      return false;\n  }\n  //equivalent values for every corresponding key, and\n  //~~~possibly expensive deep test\n  for (i = ka.length - 1; i >= 0; i--) {\n    key = ka[i];\n    if (!_deepEqual(a[key], b[key])) return false;\n  }\n  return true;\n}\n\n// 8. The non-equivalence assertion tests for any deep inequality.\n// assert.notDeepEqual(actual, expected, message_opt);\n\nassert.notDeepEqual = function notDeepEqual(actual, expected, message) {\n  if (_deepEqual(actual, expected)) {\n    fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);\n  }\n};\n\n// 9. The strict equality assertion tests strict equality, as determined by ===.\n// assert.strictEqual(actual, expected, message_opt);\n\nassert.strictEqual = function strictEqual(actual, expected, message) {\n  if (actual !== expected) {\n    fail(actual, expected, message, '===', assert.strictEqual);\n  }\n};\n\n// 10. The strict non-equality assertion tests for strict inequality, as\n// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);\n\nassert.notStrictEqual = function notStrictEqual(actual, expected, message) {\n  if (actual === expected) {\n    fail(actual, expected, message, '!==', assert.notStrictEqual);\n  }\n};\n\nfunction expectedException(actual, expected) {\n  if (!actual || !expected) {\n    return false;\n  }\n\n  if (Object.prototype.toString.call(expected) == '[object RegExp]') {\n    return expected.test(actual);\n  } else if (actual instanceof expected) {\n    return true;\n  } else if (expected.call({}, actual) === true) {\n    return true;\n  }\n\n  return false;\n}\n\nfunction _throws(shouldThrow, block, expected, message) {\n  var actual;\n\n  if (util.isString(expected)) {\n    message = expected;\n    expected = null;\n  }\n\n  try {\n    block();\n  } catch (e) {\n    actual = e;\n  }\n\n  message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +\n            (message ? ' ' + message : '.');\n\n  if (shouldThrow && !actual) {\n    fail(actual, expected, 'Missing expected exception' + message);\n  }\n\n  if (!shouldThrow && expectedException(actual, expected)) {\n    fail(actual, expected, 'Got unwanted exception' + message);\n  }\n\n  if ((shouldThrow && actual && expected &&\n      !expectedException(actual, expected)) || (!shouldThrow && actual)) {\n    throw actual;\n  }\n}\n\n// 11. Expected to throw an error:\n// assert.throws(block, Error_opt, message_opt);\n\nassert.throws = function(block, /*optional*/error, /*optional*/message) {\n  _throws.apply(this, [true].concat(pSlice.call(arguments)));\n};\n\n// EXTENSION! This is annoying to write outside this module.\nassert.doesNotThrow = function(block, /*optional*/message) {\n  _throws.apply(this, [false].concat(pSlice.call(arguments)));\n};\n\nassert.ifError = function(err) { if (err) {throw err;}};\n\nvar objectKeys = Object.keys || function (obj) {\n  var keys = [];\n  for (var key in obj) {\n    if (hasOwn.call(obj, key)) keys.push(key);\n  }\n  return keys;\n};\n\n},{\"util/\":10}],6:[function(require,module,exports){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n  this._events = this._events || {};\n  this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n  if (!isNumber(n) || n < 0 || isNaN(n))\n    throw TypeError('n must be a positive number');\n  this._maxListeners = n;\n  return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n  var er, handler, len, args, i, listeners;\n\n  if (!this._events)\n    this._events = {};\n\n  // If there is no 'error' event listener then throw.\n  if (type === 'error') {\n    if (!this._events.error ||\n        (isObject(this._events.error) && !this._events.error.length)) {\n      er = arguments[1];\n      if (er instanceof Error) {\n        throw er; // Unhandled 'error' event\n      }\n      throw TypeError('Uncaught, unspecified \"error\" event.');\n    }\n  }\n\n  handler = this._events[type];\n\n  if (isUndefined(handler))\n    return false;\n\n  if (isFunction(handler)) {\n    switch (arguments.length) {\n      // fast cases\n      case 1:\n        handler.call(this);\n        break;\n      case 2:\n        handler.call(this, arguments[1]);\n        break;\n      case 3:\n        handler.call(this, arguments[1], arguments[2]);\n        break;\n      // slower\n      default:\n        len = arguments.length;\n        args = new Array(len - 1);\n        for (i = 1; i < len; i++)\n          args[i - 1] = arguments[i];\n        handler.apply(this, args);\n    }\n  } else if (isObject(handler)) {\n    len = arguments.length;\n    args = new Array(len - 1);\n    for (i = 1; i < len; i++)\n      args[i - 1] = arguments[i];\n\n    listeners = handler.slice();\n    len = listeners.length;\n    for (i = 0; i < len; i++)\n      listeners[i].apply(this, args);\n  }\n\n  return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n  var m;\n\n  if (!isFunction(listener))\n    throw TypeError('listener must be a function');\n\n  if (!this._events)\n    this._events = {};\n\n  // To avoid recursion in the case that type === \"newListener\"! Before\n  // adding it to the listeners, first emit \"newListener\".\n  if (this._events.newListener)\n    this.emit('newListener', type,\n              isFunction(listener.listener) ?\n              listener.listener : listener);\n\n  if (!this._events[type])\n    // Optimize the case of one listener. Don't need the extra array object.\n    this._events[type] = listener;\n  else if (isObject(this._events[type]))\n    // If we've already got an array, just append.\n    this._events[type].push(listener);\n  else\n    // Adding the second element, need to change to array.\n    this._events[type] = [this._events[type], listener];\n\n  // Check for listener leak\n  if (isObject(this._events[type]) && !this._events[type].warned) {\n    var m;\n    if (!isUndefined(this._maxListeners)) {\n      m = this._maxListeners;\n    } else {\n      m = EventEmitter.defaultMaxListeners;\n    }\n\n    if (m && m > 0 && this._events[type].length > m) {\n      this._events[type].warned = true;\n      console.error('(node) warning: possible EventEmitter memory ' +\n                    'leak detected. %d listeners added. ' +\n                    'Use emitter.setMaxListeners() to increase limit.',\n                    this._events[type].length);\n      if (typeof console.trace === 'function') {\n        // not supported in IE 10\n        console.trace();\n      }\n    }\n  }\n\n  return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n  if (!isFunction(listener))\n    throw TypeError('listener must be a function');\n\n  var fired = false;\n\n  function g() {\n    this.removeListener(type, g);\n\n    if (!fired) {\n      fired = true;\n      listener.apply(this, arguments);\n    }\n  }\n\n  g.listener = listener;\n  this.on(type, g);\n\n  return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n  var list, position, length, i;\n\n  if (!isFunction(listener))\n    throw TypeError('listener must be a function');\n\n  if (!this._events || !this._events[type])\n    return this;\n\n  list = this._events[type];\n  length = list.length;\n  position = -1;\n\n  if (list === listener ||\n      (isFunction(list.listener) && list.listener === listener)) {\n    delete this._events[type];\n    if (this._events.removeListener)\n      this.emit('removeListener', type, listener);\n\n  } else if (isObject(list)) {\n    for (i = length; i-- > 0;) {\n      if (list[i] === listener ||\n          (list[i].listener && list[i].listener === listener)) {\n        position = i;\n        break;\n      }\n    }\n\n    if (position < 0)\n      return this;\n\n    if (list.length === 1) {\n      list.length = 0;\n      delete this._events[type];\n    } else {\n      list.splice(position, 1);\n    }\n\n    if (this._events.removeListener)\n      this.emit('removeListener', type, listener);\n  }\n\n  return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n  var key, listeners;\n\n  if (!this._events)\n    return this;\n\n  // not listening for removeListener, no need to emit\n  if (!this._events.removeListener) {\n    if (arguments.length === 0)\n      this._events = {};\n    else if (this._events[type])\n      delete this._events[type];\n    return this;\n  }\n\n  // emit removeListener for all listeners on all events\n  if (arguments.length === 0) {\n    for (key in this._events) {\n      if (key === 'removeListener') continue;\n      this.removeAllListeners(key);\n    }\n    this.removeAllListeners('removeListener');\n    this._events = {};\n    return this;\n  }\n\n  listeners = this._events[type];\n\n  if (isFunction(listeners)) {\n    this.removeListener(type, listeners);\n  } else {\n    // LIFO order\n    while (listeners.length)\n      this.removeListener(type, listeners[listeners.length - 1]);\n  }\n  delete this._events[type];\n\n  return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n  var ret;\n  if (!this._events || !this._events[type])\n    ret = [];\n  else if (isFunction(this._events[type]))\n    ret = [this._events[type]];\n  else\n    ret = this._events[type].slice();\n  return ret;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n  var ret;\n  if (!emitter._events || !emitter._events[type])\n    ret = 0;\n  else if (isFunction(emitter._events[type]))\n    ret = 1;\n  else\n    ret = emitter._events[type].length;\n  return ret;\n};\n\nfunction isFunction(arg) {\n  return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n  return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n  return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n  return arg === void 0;\n}\n\n},{}],7:[function(require,module,exports){\n// shim for using process in browser\n\nvar process = module.exports = {};\nvar queue = [];\nvar draining = false;\n\nfunction drainQueue() {\n    if (draining) {\n        return;\n    }\n    draining = true;\n    var currentQueue;\n    var len = queue.length;\n    while(len) {\n        currentQueue = queue;\n        queue = [];\n        var i = -1;\n        while (++i < len) {\n            currentQueue[i]();\n        }\n        len = queue.length;\n    }\n    draining = false;\n}\nprocess.nextTick = function (fun) {\n    queue.push(fun);\n    if (!draining) {\n        setTimeout(drainQueue, 0);\n    }\n};\n\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\n\nprocess.binding = function (name) {\n    throw new Error('process.binding is not supported');\n};\n\n// TODO(shtylman)\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n    throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n},{}],8:[function(require,module,exports){\nif (typeof Object.create === 'function') {\n  // implementation from standard node.js 'util' module\n  module.exports = function inherits(ctor, superCtor) {\n    ctor.super_ = superCtor\n    ctor.prototype = Object.create(superCtor.prototype, {\n      constructor: {\n        value: ctor,\n        enumerable: false,\n        writable: true,\n        configurable: true\n      }\n    });\n  };\n} else {\n  // old school shim for old browsers\n  module.exports = function inherits(ctor, superCtor) {\n    ctor.super_ = superCtor\n    var TempCtor = function () {}\n    TempCtor.prototype = superCtor.prototype\n    ctor.prototype = new TempCtor()\n    ctor.prototype.constructor = ctor\n  }\n}\n\n},{}],9:[function(require,module,exports){\nmodule.exports = function isBuffer(arg) {\n  return arg && typeof arg === 'object'\n    && typeof arg.copy === 'function'\n    && typeof arg.fill === 'function'\n    && typeof arg.readUInt8 === 'function';\n}\n},{}],10:[function(require,module,exports){\n(function (process,global){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n  if (!isString(f)) {\n    var objects = [];\n    for (var i = 0; i < arguments.length; i++) {\n      objects.push(inspect(arguments[i]));\n    }\n    return objects.join(' ');\n  }\n\n  var i = 1;\n  var args = arguments;\n  var len = args.length;\n  var str = String(f).replace(formatRegExp, function(x) {\n    if (x === '%%') return '%';\n    if (i >= len) return x;\n    switch (x) {\n      case '%s': return String(args[i++]);\n      case '%d': return Number(args[i++]);\n      case '%j':\n        try {\n          return JSON.stringify(args[i++]);\n        } catch (_) {\n          return '[Circular]';\n        }\n      default:\n        return x;\n    }\n  });\n  for (var x = args[i]; i < len; x = args[++i]) {\n    if (isNull(x) || !isObject(x)) {\n      str += ' ' + x;\n    } else {\n      str += ' ' + inspect(x);\n    }\n  }\n  return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n  // Allow for deprecating things in the process of starting up.\n  if (isUndefined(global.process)) {\n    return function() {\n      return exports.deprecate(fn, msg).apply(this, arguments);\n    };\n  }\n\n  if (process.noDeprecation === true) {\n    return fn;\n  }\n\n  var warned = false;\n  function deprecated() {\n    if (!warned) {\n      if (process.throwDeprecation) {\n        throw new Error(msg);\n      } else if (process.traceDeprecation) {\n        console.trace(msg);\n      } else {\n        console.error(msg);\n      }\n      warned = true;\n    }\n    return fn.apply(this, arguments);\n  }\n\n  return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexports.debuglog = function(set) {\n  if (isUndefined(debugEnviron))\n    debugEnviron = process.env.NODE_DEBUG || '';\n  set = set.toUpperCase();\n  if (!debugs[set]) {\n    if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n      var pid = process.pid;\n      debugs[set] = function() {\n        var msg = exports.format.apply(exports, arguments);\n        console.error('%s %d: %s', set, pid, msg);\n      };\n    } else {\n      debugs[set] = function() {};\n    }\n  }\n  return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n  // default options\n  var ctx = {\n    seen: [],\n    stylize: stylizeNoColor\n  };\n  // legacy...\n  if (arguments.length >= 3) ctx.depth = arguments[2];\n  if (arguments.length >= 4) ctx.colors = arguments[3];\n  if (isBoolean(opts)) {\n    // legacy...\n    ctx.showHidden = opts;\n  } else if (opts) {\n    // got an \"options\" object\n    exports._extend(ctx, opts);\n  }\n  // set default options\n  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n  if (isUndefined(ctx.depth)) ctx.depth = 2;\n  if (isUndefined(ctx.colors)) ctx.colors = false;\n  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n  if (ctx.colors) ctx.stylize = stylizeWithColor;\n  return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n  'bold' : [1, 22],\n  'italic' : [3, 23],\n  'underline' : [4, 24],\n  'inverse' : [7, 27],\n  'white' : [37, 39],\n  'grey' : [90, 39],\n  'black' : [30, 39],\n  'blue' : [34, 39],\n  'cyan' : [36, 39],\n  'green' : [32, 39],\n  'magenta' : [35, 39],\n  'red' : [31, 39],\n  'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n  'special': 'cyan',\n  'number': 'yellow',\n  'boolean': 'yellow',\n  'undefined': 'grey',\n  'null': 'bold',\n  'string': 'green',\n  'date': 'magenta',\n  // \"name\": intentionally not styling\n  'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n  var style = inspect.styles[styleType];\n\n  if (style) {\n    return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n           '\\u001b[' + inspect.colors[style][1] + 'm';\n  } else {\n    return str;\n  }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n  return str;\n}\n\n\nfunction arrayToHash(array) {\n  var hash = {};\n\n  array.forEach(function(val, idx) {\n    hash[val] = true;\n  });\n\n  return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n  // Provide a hook for user-specified inspect functions.\n  // Check that value is an object with an inspect function on it\n  if (ctx.customInspect &&\n      value &&\n      isFunction(value.inspect) &&\n      // Filter out the util module, it's inspect function is special\n      value.inspect !== exports.inspect &&\n      // Also filter out any prototype objects using the circular check.\n      !(value.constructor && value.constructor.prototype === value)) {\n    var ret = value.inspect(recurseTimes, ctx);\n    if (!isString(ret)) {\n      ret = formatValue(ctx, ret, recurseTimes);\n    }\n    return ret;\n  }\n\n  // Primitive types cannot have properties\n  var primitive = formatPrimitive(ctx, value);\n  if (primitive) {\n    return primitive;\n  }\n\n  // Look up the keys of the object.\n  var keys = Object.keys(value);\n  var visibleKeys = arrayToHash(keys);\n\n  if (ctx.showHidden) {\n    keys = Object.getOwnPropertyNames(value);\n  }\n\n  // IE doesn't make error fields non-enumerable\n  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n  if (isError(value)\n      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n    return formatError(value);\n  }\n\n  // Some type of object without properties can be shortcutted.\n  if (keys.length === 0) {\n    if (isFunction(value)) {\n      var name = value.name ? ': ' + value.name : '';\n      return ctx.stylize('[Function' + name + ']', 'special');\n    }\n    if (isRegExp(value)) {\n      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n    }\n    if (isDate(value)) {\n      return ctx.stylize(Date.prototype.toString.call(value), 'date');\n    }\n    if (isError(value)) {\n      return formatError(value);\n    }\n  }\n\n  var base = '', array = false, braces = ['{', '}'];\n\n  // Make Array say that they are Array\n  if (isArray(value)) {\n    array = true;\n    braces = ['[', ']'];\n  }\n\n  // Make functions say that they are functions\n  if (isFunction(value)) {\n    var n = value.name ? ': ' + value.name : '';\n    base = ' [Function' + n + ']';\n  }\n\n  // Make RegExps say that they are RegExps\n  if (isRegExp(value)) {\n    base = ' ' + RegExp.prototype.toString.call(value);\n  }\n\n  // Make dates with properties first say the date\n  if (isDate(value)) {\n    base = ' ' + Date.prototype.toUTCString.call(value);\n  }\n\n  // Make error with message first say the error\n  if (isError(value)) {\n    base = ' ' + formatError(value);\n  }\n\n  if (keys.length === 0 && (!array || value.length == 0)) {\n    return braces[0] + base + braces[1];\n  }\n\n  if (recurseTimes < 0) {\n    if (isRegExp(value)) {\n      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n    } else {\n      return ctx.stylize('[Object]', 'special');\n    }\n  }\n\n  ctx.seen.push(value);\n\n  var output;\n  if (array) {\n    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n  } else {\n    output = keys.map(function(key) {\n      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n    });\n  }\n\n  ctx.seen.pop();\n\n  return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n  if (isUndefined(value))\n    return ctx.stylize('undefined', 'undefined');\n  if (isString(value)) {\n    var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n                                             .replace(/'/g, \"\\\\'\")\n                                             .replace(/\\\\\"/g, '\"') + '\\'';\n    return ctx.stylize(simple, 'string');\n  }\n  if (isNumber(value))\n    return ctx.stylize('' + value, 'number');\n  if (isBoolean(value))\n    return ctx.stylize('' + value, 'boolean');\n  // For some reason typeof null is \"object\", so special case here.\n  if (isNull(value))\n    return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n  return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n  var output = [];\n  for (var i = 0, l = value.length; i < l; ++i) {\n    if (hasOwnProperty(value, String(i))) {\n      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n          String(i), true));\n    } else {\n      output.push('');\n    }\n  }\n  keys.forEach(function(key) {\n    if (!key.match(/^\\d+$/)) {\n      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n          key, true));\n    }\n  });\n  return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n  var name, str, desc;\n  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n  if (desc.get) {\n    if (desc.set) {\n      str = ctx.stylize('[Getter/Setter]', 'special');\n    } else {\n      str = ctx.stylize('[Getter]', 'special');\n    }\n  } else {\n    if (desc.set) {\n      str = ctx.stylize('[Setter]', 'special');\n    }\n  }\n  if (!hasOwnProperty(visibleKeys, key)) {\n    name = '[' + key + ']';\n  }\n  if (!str) {\n    if (ctx.seen.indexOf(desc.value) < 0) {\n      if (isNull(recurseTimes)) {\n        str = formatValue(ctx, desc.value, null);\n      } else {\n        str = formatValue(ctx, desc.value, recurseTimes - 1);\n      }\n      if (str.indexOf('\\n') > -1) {\n        if (array) {\n          str = str.split('\\n').map(function(line) {\n            return '  ' + line;\n          }).join('\\n').substr(2);\n        } else {\n          str = '\\n' + str.split('\\n').map(function(line) {\n            return '   ' + line;\n          }).join('\\n');\n        }\n      }\n    } else {\n      str = ctx.stylize('[Circular]', 'special');\n    }\n  }\n  if (isUndefined(name)) {\n    if (array && key.match(/^\\d+$/)) {\n      return str;\n    }\n    name = JSON.stringify('' + key);\n    if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n      name = name.substr(1, name.length - 2);\n      name = ctx.stylize(name, 'name');\n    } else {\n      name = name.replace(/'/g, \"\\\\'\")\n                 .replace(/\\\\\"/g, '\"')\n                 .replace(/(^\"|\"$)/g, \"'\");\n      name = ctx.stylize(name, 'string');\n    }\n  }\n\n  return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n  var numLinesEst = 0;\n  var length = output.reduce(function(prev, cur) {\n    numLinesEst++;\n    if (cur.indexOf('\\n') >= 0) numLinesEst++;\n    return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n  }, 0);\n\n  if (length > 60) {\n    return braces[0] +\n           (base === '' ? '' : base + '\\n ') +\n           ' ' +\n           output.join(',\\n  ') +\n           ' ' +\n           braces[1];\n  }\n\n  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n  return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n  return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n  return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n  return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n  return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n  return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n  return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n  return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n  return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n  return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n  return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n  return isObject(e) &&\n      (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n  return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n  return arg === null ||\n         typeof arg === 'boolean' ||\n         typeof arg === 'number' ||\n         typeof arg === 'string' ||\n         typeof arg === 'symbol' ||  // ES6 symbol\n         typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n  return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n  return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n              'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n  var d = new Date();\n  var time = [pad(d.getHours()),\n              pad(d.getMinutes()),\n              pad(d.getSeconds())].join(':');\n  return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n *     prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n  // Don't do anything if add isn't an object\n  if (!add || !isObject(add)) return origin;\n\n  var keys = Object.keys(add);\n  var i = keys.length;\n  while (i--) {\n    origin[keys[i]] = add[keys[i]];\n  }\n  return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n  return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n}).call(this,require('_process'),typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"./support/isBuffer\":9,\"_process\":7,\"inherits\":8}],11:[function(require,module,exports){\n(function (global){\n/*global window, global*/\nvar util = require(\"util\")\nvar assert = require(\"assert\")\nvar now = require(\"date-now\")\n\nvar slice = Array.prototype.slice\nvar console\nvar times = {}\n\nif (typeof global !== \"undefined\" && global.console) {\n    console = global.console\n} else if (typeof window !== \"undefined\" && window.console) {\n    console = window.console\n} else {\n    console = {}\n}\n\nvar functions = [\n    [log, \"log\"],\n    [info, \"info\"],\n    [warn, \"warn\"],\n    [error, \"error\"],\n    [time, \"time\"],\n    [timeEnd, \"timeEnd\"],\n    [trace, \"trace\"],\n    [dir, \"dir\"],\n    [consoleAssert, \"assert\"]\n]\n\nfor (var i = 0; i < functions.length; i++) {\n    var tuple = functions[i]\n    var f = tuple[0]\n    var name = tuple[1]\n\n    if (!console[name]) {\n        console[name] = f\n    }\n}\n\nmodule.exports = console\n\nfunction log() {}\n\nfunction info() {\n    console.log.apply(console, arguments)\n}\n\nfunction warn() {\n    console.log.apply(console, arguments)\n}\n\nfunction error() {\n    console.warn.apply(console, arguments)\n}\n\nfunction time(label) {\n    times[label] = now()\n}\n\nfunction timeEnd(label) {\n    var time = times[label]\n    if (!time) {\n        throw new Error(\"No such label: \" + label)\n    }\n\n    var duration = now() - time\n    console.log(label + \": \" + duration + \"ms\")\n}\n\nfunction trace() {\n    var err = new Error()\n    err.name = \"Trace\"\n    err.message = util.format.apply(null, arguments)\n    console.error(err.stack)\n}\n\nfunction dir(object) {\n    console.log(util.inspect(object) + \"\\n\")\n}\n\nfunction consoleAssert(expression) {\n    if (!expression) {\n        var arr = slice.call(arguments, 1)\n        assert.ok(false, util.format.apply(null, arr))\n    }\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"assert\":5,\"date-now\":12,\"util\":10}],12:[function(require,module,exports){\nmodule.exports = now\n\nfunction now() {\n    return new Date().getTime()\n}\n\n},{}],13:[function(require,module,exports){\n(function (global){\n/**\n * @license\n * Lodash <https://lodash.com/>\n * Copyright JS Foundation and other contributors <https://js.foundation/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n;(function() {\n\n  /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n  var undefined;\n\n  /** Used as the semantic version number. */\n  var VERSION = '4.17.10';\n\n  /** Used as the size to enable large array optimizations. */\n  var LARGE_ARRAY_SIZE = 200;\n\n  /** Error message constants. */\n  var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',\n      FUNC_ERROR_TEXT = 'Expected a function';\n\n  /** Used to stand-in for `undefined` hash values. */\n  var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n  /** Used as the maximum memoize cache size. */\n  var MAX_MEMOIZE_SIZE = 500;\n\n  /** Used as the internal argument placeholder. */\n  var PLACEHOLDER = '__lodash_placeholder__';\n\n  /** Used to compose bitmasks for cloning. */\n  var CLONE_DEEP_FLAG = 1,\n      CLONE_FLAT_FLAG = 2,\n      CLONE_SYMBOLS_FLAG = 4;\n\n  /** Used to compose bitmasks for value comparisons. */\n  var COMPARE_PARTIAL_FLAG = 1,\n      COMPARE_UNORDERED_FLAG = 2;\n\n  /** Used to compose bitmasks for function metadata. */\n  var WRAP_BIND_FLAG = 1,\n      WRAP_BIND_KEY_FLAG = 2,\n      WRAP_CURRY_BOUND_FLAG = 4,\n      WRAP_CURRY_FLAG = 8,\n      WRAP_CURRY_RIGHT_FLAG = 16,\n      WRAP_PARTIAL_FLAG = 32,\n      WRAP_PARTIAL_RIGHT_FLAG = 64,\n      WRAP_ARY_FLAG = 128,\n      WRAP_REARG_FLAG = 256,\n      WRAP_FLIP_FLAG = 512;\n\n  /** Used as default options for `_.truncate`. */\n  var DEFAULT_TRUNC_LENGTH = 30,\n      DEFAULT_TRUNC_OMISSION = '...';\n\n  /** Used to detect hot functions by number of calls within a span of milliseconds. */\n  var HOT_COUNT = 800,\n      HOT_SPAN = 16;\n\n  /** Used to indicate the type of lazy iteratees. */\n  var LAZY_FILTER_FLAG = 1,\n      LAZY_MAP_FLAG = 2,\n      LAZY_WHILE_FLAG = 3;\n\n  /** Used as references for various `Number` constants. */\n  var INFINITY = 1 / 0,\n      MAX_SAFE_INTEGER = 9007199254740991,\n      MAX_INTEGER = 1.7976931348623157e+308,\n      NAN = 0 / 0;\n\n  /** Used as references for the maximum length and index of an array. */\n  var MAX_ARRAY_LENGTH = 4294967295,\n      MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n      HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n  /** Used to associate wrap methods with their bit flags. */\n  var wrapFlags = [\n    ['ary', WRAP_ARY_FLAG],\n    ['bind', WRAP_BIND_FLAG],\n    ['bindKey', WRAP_BIND_KEY_FLAG],\n    ['curry', WRAP_CURRY_FLAG],\n    ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n    ['flip', WRAP_FLIP_FLAG],\n    ['partial', WRAP_PARTIAL_FLAG],\n    ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n    ['rearg', WRAP_REARG_FLAG]\n  ];\n\n  /** `Object#toString` result references. */\n  var argsTag = '[object Arguments]',\n      arrayTag = '[object Array]',\n      asyncTag = '[object AsyncFunction]',\n      boolTag = '[object Boolean]',\n      dateTag = '[object Date]',\n      domExcTag = '[object DOMException]',\n      errorTag = '[object Error]',\n      funcTag = '[object Function]',\n      genTag = '[object GeneratorFunction]',\n      mapTag = '[object Map]',\n      numberTag = '[object Number]',\n      nullTag = '[object Null]',\n      objectTag = '[object Object]',\n      promiseTag = '[object Promise]',\n      proxyTag = '[object Proxy]',\n      regexpTag = '[object RegExp]',\n      setTag = '[object Set]',\n      stringTag = '[object String]',\n      symbolTag = '[object Symbol]',\n      undefinedTag = '[object Undefined]',\n      weakMapTag = '[object WeakMap]',\n      weakSetTag = '[object WeakSet]';\n\n  var arrayBufferTag = '[object ArrayBuffer]',\n      dataViewTag = '[object DataView]',\n      float32Tag = '[object Float32Array]',\n      float64Tag = '[object Float64Array]',\n      int8Tag = '[object Int8Array]',\n      int16Tag = '[object Int16Array]',\n      int32Tag = '[object Int32Array]',\n      uint8Tag = '[object Uint8Array]',\n      uint8ClampedTag = '[object Uint8ClampedArray]',\n      uint16Tag = '[object Uint16Array]',\n      uint32Tag = '[object Uint32Array]';\n\n  /** Used to match empty string literals in compiled template source. */\n  var reEmptyStringLeading = /\\b__p \\+= '';/g,\n      reEmptyStringMiddle = /\\b(__p \\+=) '' \\+/g,\n      reEmptyStringTrailing = /(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g;\n\n  /** Used to match HTML entities and HTML characters. */\n  var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,\n      reUnescapedHtml = /[&<>\"']/g,\n      reHasEscapedHtml = RegExp(reEscapedHtml.source),\n      reHasUnescapedHtml = RegExp(reUnescapedHtml.source);\n\n  /** Used to match template delimiters. */\n  var reEscape = /<%-([\\s\\S]+?)%>/g,\n      reEvaluate = /<%([\\s\\S]+?)%>/g,\n      reInterpolate = /<%=([\\s\\S]+?)%>/g;\n\n  /** Used to match property names within property paths. */\n  var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n      reIsPlainProp = /^\\w*$/,\n      rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n  /**\n   * Used to match `RegExp`\n   * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n   */\n  var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g,\n      reHasRegExpChar = RegExp(reRegExpChar.source);\n\n  /** Used to match leading and trailing whitespace. */\n  var reTrim = /^\\s+|\\s+$/g,\n      reTrimStart = /^\\s+/,\n      reTrimEnd = /\\s+$/;\n\n  /** Used to match wrap detail comments. */\n  var reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,\n      reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n      reSplitDetails = /,? & /;\n\n  /** Used to match words composed of alphanumeric characters. */\n  var reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n  /** Used to match backslashes in property paths. */\n  var reEscapeChar = /\\\\(\\\\)?/g;\n\n  /**\n   * Used to match\n   * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).\n   */\n  var reEsTemplate = /\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g;\n\n  /** Used to match `RegExp` flags from their coerced string values. */\n  var reFlags = /\\w*$/;\n\n  /** Used to detect bad signed hexadecimal string values. */\n  var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n  /** Used to detect binary string values. */\n  var reIsBinary = /^0b[01]+$/i;\n\n  /** Used to detect host constructors (Safari). */\n  var reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n  /** Used to detect octal string values. */\n  var reIsOctal = /^0o[0-7]+$/i;\n\n  /** Used to detect unsigned integer values. */\n  var reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n  /** Used to match Latin Unicode letters (excluding mathematical operators). */\n  var reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n  /** Used to ensure capturing order of template delimiters. */\n  var reNoMatch = /($^)/;\n\n  /** Used to match unescaped characters in compiled string literals. */\n  var reUnescapedString = /['\\n\\r\\u2028\\u2029\\\\]/g;\n\n  /** Used to compose unicode character classes. */\n  var rsAstralRange = '\\\\ud800-\\\\udfff',\n      rsComboMarksRange = '\\\\u0300-\\\\u036f',\n      reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n      rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n      rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n      rsDingbatRange = '\\\\u2700-\\\\u27bf',\n      rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n      rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n      rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n      rsPunctuationRange = '\\\\u2000-\\\\u206f',\n      rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n      rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n      rsVarRange = '\\\\ufe0e\\\\ufe0f',\n      rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n  /** Used to compose unicode capture groups. */\n  var rsApos = \"['\\u2019]\",\n      rsAstral = '[' + rsAstralRange + ']',\n      rsBreak = '[' + rsBreakRange + ']',\n      rsCombo = '[' + rsComboRange + ']',\n      rsDigits = '\\\\d+',\n      rsDingbat = '[' + rsDingbatRange + ']',\n      rsLower = '[' + rsLowerRange + ']',\n      rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n      rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n      rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n      rsNonAstral = '[^' + rsAstralRange + ']',\n      rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n      rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n      rsUpper = '[' + rsUpperRange + ']',\n      rsZWJ = '\\\\u200d';\n\n  /** Used to compose unicode regexes. */\n  var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n      rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n      rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n      rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n      reOptMod = rsModifier + '?',\n      rsOptVar = '[' + rsVarRange + ']?',\n      rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n      rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n      rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n      rsSeq = rsOptVar + reOptMod + rsOptJoin,\n      rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,\n      rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n  /** Used to match apostrophes. */\n  var reApos = RegExp(rsApos, 'g');\n\n  /**\n   * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n   * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n   */\n  var reComboMark = RegExp(rsCombo, 'g');\n\n  /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\n  var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n  /** Used to match complex or compound words. */\n  var reUnicodeWord = RegExp([\n    rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n    rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n    rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n    rsUpper + '+' + rsOptContrUpper,\n    rsOrdUpper,\n    rsOrdLower,\n    rsDigits,\n    rsEmoji\n  ].join('|'), 'g');\n\n  /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\n  var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange  + rsComboRange + rsVarRange + ']');\n\n  /** Used to detect strings that need a more robust regexp to match words. */\n  var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n  /** Used to assign default `context` object properties. */\n  var contextProps = [\n    'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',\n    'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',\n    'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',\n    'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',\n    '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'\n  ];\n\n  /** Used to make template sourceURLs easier to identify. */\n  var templateCounter = -1;\n\n  /** Used to identify `toStringTag` values of typed arrays. */\n  var typedArrayTags = {};\n  typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n  typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n  typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n  typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n  typedArrayTags[uint32Tag] = true;\n  typedArrayTags[argsTag] = typedArrayTags[arrayTag] =\n  typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n  typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\n  typedArrayTags[errorTag] = typedArrayTags[funcTag] =\n  typedArrayTags[mapTag] = typedArrayTags[numberTag] =\n  typedArrayTags[objectTag] = typedArrayTags[regexpTag] =\n  typedArrayTags[setTag] = typedArrayTags[stringTag] =\n  typedArrayTags[weakMapTag] = false;\n\n  /** Used to identify `toStringTag` values supported by `_.clone`. */\n  var cloneableTags = {};\n  cloneableTags[argsTag] = cloneableTags[arrayTag] =\n  cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\n  cloneableTags[boolTag] = cloneableTags[dateTag] =\n  cloneableTags[float32Tag] = cloneableTags[float64Tag] =\n  cloneableTags[int8Tag] = cloneableTags[int16Tag] =\n  cloneableTags[int32Tag] = cloneableTags[mapTag] =\n  cloneableTags[numberTag] = cloneableTags[objectTag] =\n  cloneableTags[regexpTag] = cloneableTags[setTag] =\n  cloneableTags[stringTag] = cloneableTags[symbolTag] =\n  cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\n  cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\n  cloneableTags[errorTag] = cloneableTags[funcTag] =\n  cloneableTags[weakMapTag] = false;\n\n  /** Used to map Latin Unicode letters to basic Latin letters. */\n  var deburredLetters = {\n    // Latin-1 Supplement block.\n    '\\xc0': 'A',  '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n    '\\xe0': 'a',  '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n    '\\xc7': 'C',  '\\xe7': 'c',\n    '\\xd0': 'D',  '\\xf0': 'd',\n    '\\xc8': 'E',  '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n    '\\xe8': 'e',  '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n    '\\xcc': 'I',  '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n    '\\xec': 'i',  '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n    '\\xd1': 'N',  '\\xf1': 'n',\n    '\\xd2': 'O',  '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n    '\\xf2': 'o',  '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n    '\\xd9': 'U',  '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n    '\\xf9': 'u',  '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n    '\\xdd': 'Y',  '\\xfd': 'y', '\\xff': 'y',\n    '\\xc6': 'Ae', '\\xe6': 'ae',\n    '\\xde': 'Th', '\\xfe': 'th',\n    '\\xdf': 'ss',\n    // Latin Extended-A block.\n    '\\u0100': 'A',  '\\u0102': 'A', '\\u0104': 'A',\n    '\\u0101': 'a',  '\\u0103': 'a', '\\u0105': 'a',\n    '\\u0106': 'C',  '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n    '\\u0107': 'c',  '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n    '\\u010e': 'D',  '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n    '\\u0112': 'E',  '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n    '\\u0113': 'e',  '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n    '\\u011c': 'G',  '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n    '\\u011d': 'g',  '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n    '\\u0124': 'H',  '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n    '\\u0128': 'I',  '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n    '\\u0129': 'i',  '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n    '\\u0134': 'J',  '\\u0135': 'j',\n    '\\u0136': 'K',  '\\u0137': 'k', '\\u0138': 'k',\n    '\\u0139': 'L',  '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n    '\\u013a': 'l',  '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n    '\\u0143': 'N',  '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n    '\\u0144': 'n',  '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n    '\\u014c': 'O',  '\\u014e': 'O', '\\u0150': 'O',\n    '\\u014d': 'o',  '\\u014f': 'o', '\\u0151': 'o',\n    '\\u0154': 'R',  '\\u0156': 'R', '\\u0158': 'R',\n    '\\u0155': 'r',  '\\u0157': 'r', '\\u0159': 'r',\n    '\\u015a': 'S',  '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n    '\\u015b': 's',  '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n    '\\u0162': 'T',  '\\u0164': 'T', '\\u0166': 'T',\n    '\\u0163': 't',  '\\u0165': 't', '\\u0167': 't',\n    '\\u0168': 'U',  '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n    '\\u0169': 'u',  '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n    '\\u0174': 'W',  '\\u0175': 'w',\n    '\\u0176': 'Y',  '\\u0177': 'y', '\\u0178': 'Y',\n    '\\u0179': 'Z',  '\\u017b': 'Z', '\\u017d': 'Z',\n    '\\u017a': 'z',  '\\u017c': 'z', '\\u017e': 'z',\n    '\\u0132': 'IJ', '\\u0133': 'ij',\n    '\\u0152': 'Oe', '\\u0153': 'oe',\n    '\\u0149': \"'n\", '\\u017f': 's'\n  };\n\n  /** Used to map characters to HTML entities. */\n  var htmlEscapes = {\n    '&': '&amp;',\n    '<': '&lt;',\n    '>': '&gt;',\n    '\"': '&quot;',\n    \"'\": '&#39;'\n  };\n\n  /** Used to map HTML entities to characters. */\n  var htmlUnescapes = {\n    '&amp;': '&',\n    '&lt;': '<',\n    '&gt;': '>',\n    '&quot;': '\"',\n    '&#39;': \"'\"\n  };\n\n  /** Used to escape characters for inclusion in compiled string literals. */\n  var stringEscapes = {\n    '\\\\': '\\\\',\n    \"'\": \"'\",\n    '\\n': 'n',\n    '\\r': 'r',\n    '\\u2028': 'u2028',\n    '\\u2029': 'u2029'\n  };\n\n  /** Built-in method references without a dependency on `root`. */\n  var freeParseFloat = parseFloat,\n      freeParseInt = parseInt;\n\n  /** Detect free variable `global` from Node.js. */\n  var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n  /** Detect free variable `self`. */\n  var freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n  /** Used as a reference to the global object. */\n  var root = freeGlobal || freeSelf || Function('return this')();\n\n  /** Detect free variable `exports`. */\n  var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n  /** Detect free variable `module`. */\n  var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n  /** Detect the popular CommonJS extension `module.exports`. */\n  var moduleExports = freeModule && freeModule.exports === freeExports;\n\n  /** Detect free variable `process` from Node.js. */\n  var freeProcess = moduleExports && freeGlobal.process;\n\n  /** Used to access faster Node.js helpers. */\n  var nodeUtil = (function() {\n    try {\n      // Use `util.types` for Node.js 10+.\n      var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n      if (types) {\n        return types;\n      }\n\n      // Legacy `process.binding('util')` for Node.js < 10.\n      return freeProcess && freeProcess.binding && freeProcess.binding('util');\n    } catch (e) {}\n  }());\n\n  /* Node.js helper references. */\n  var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,\n      nodeIsDate = nodeUtil && nodeUtil.isDate,\n      nodeIsMap = nodeUtil && nodeUtil.isMap,\n      nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,\n      nodeIsSet = nodeUtil && nodeUtil.isSet,\n      nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n  /*--------------------------------------------------------------------------*/\n\n  /**\n   * A faster alternative to `Function#apply`, this function invokes `func`\n   * with the `this` binding of `thisArg` and the arguments of `args`.\n   *\n   * @private\n   * @param {Function} func The function to invoke.\n   * @param {*} thisArg The `this` binding of `func`.\n   * @param {Array} args The arguments to invoke `func` with.\n   * @returns {*} Returns the result of `func`.\n   */\n  function apply(func, thisArg, args) {\n    switch (args.length) {\n      case 0: return func.call(thisArg);\n      case 1: return func.call(thisArg, args[0]);\n      case 2: return func.call(thisArg, args[0], args[1]);\n      case 3: return func.call(thisArg, args[0], args[1], args[2]);\n    }\n    return func.apply(thisArg, args);\n  }\n\n  /**\n   * A specialized version of `baseAggregator` for arrays.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} setter The function to set `accumulator` values.\n   * @param {Function} iteratee The iteratee to transform keys.\n   * @param {Object} accumulator The initial aggregated object.\n   * @returns {Function} Returns `accumulator`.\n   */\n  function arrayAggregator(array, setter, iteratee, accumulator) {\n    var index = -1,\n        length = array == null ? 0 : array.length;\n\n    while (++index < length) {\n      var value = array[index];\n      setter(accumulator, value, iteratee(value), array);\n    }\n    return accumulator;\n  }\n\n  /**\n   * A specialized version of `_.forEach` for arrays without support for\n   * iteratee shorthands.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @returns {Array} Returns `array`.\n   */\n  function arrayEach(array, iteratee) {\n    var index = -1,\n        length = array == null ? 0 : array.length;\n\n    while (++index < length) {\n      if (iteratee(array[index], index, array) === false) {\n        break;\n      }\n    }\n    return array;\n  }\n\n  /**\n   * A specialized version of `_.forEachRight` for arrays without support for\n   * iteratee shorthands.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @returns {Array} Returns `array`.\n   */\n  function arrayEachRight(array, iteratee) {\n    var length = array == null ? 0 : array.length;\n\n    while (length--) {\n      if (iteratee(array[length], length, array) === false) {\n        break;\n      }\n    }\n    return array;\n  }\n\n  /**\n   * A specialized version of `_.every` for arrays without support for\n   * iteratee shorthands.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} predicate The function invoked per iteration.\n   * @returns {boolean} Returns `true` if all elements pass the predicate check,\n   *  else `false`.\n   */\n  function arrayEvery(array, predicate) {\n    var index = -1,\n        length = array == null ? 0 : array.length;\n\n    while (++index < length) {\n      if (!predicate(array[index], index, array)) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  /**\n   * A specialized version of `_.filter` for arrays without support for\n   * iteratee shorthands.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} predicate The function invoked per iteration.\n   * @returns {Array} Returns the new filtered array.\n   */\n  function arrayFilter(array, predicate) {\n    var index = -1,\n        length = array == null ? 0 : array.length,\n        resIndex = 0,\n        result = [];\n\n    while (++index < length) {\n      var value = array[index];\n      if (predicate(value, index, array)) {\n        result[resIndex++] = value;\n      }\n    }\n    return result;\n  }\n\n  /**\n   * A specialized version of `_.includes` for arrays without support for\n   * specifying an index to search from.\n   *\n   * @private\n   * @param {Array} [array] The array to inspect.\n   * @param {*} target The value to search for.\n   * @returns {boolean} Returns `true` if `target` is found, else `false`.\n   */\n  function arrayIncludes(array, value) {\n    var length = array == null ? 0 : array.length;\n    return !!length && baseIndexOf(array, value, 0) > -1;\n  }\n\n  /**\n   * This function is like `arrayIncludes` except that it accepts a comparator.\n   *\n   * @private\n   * @param {Array} [array] The array to inspect.\n   * @param {*} target The value to search for.\n   * @param {Function} comparator The comparator invoked per element.\n   * @returns {boolean} Returns `true` if `target` is found, else `false`.\n   */\n  function arrayIncludesWith(array, value, comparator) {\n    var index = -1,\n        length = array == null ? 0 : array.length;\n\n    while (++index < length) {\n      if (comparator(value, array[index])) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * A specialized version of `_.map` for arrays without support for iteratee\n   * shorthands.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @returns {Array} Returns the new mapped array.\n   */\n  function arrayMap(array, iteratee) {\n    var index = -1,\n        length = array == null ? 0 : array.length,\n        result = Array(length);\n\n    while (++index < length) {\n      result[index] = iteratee(array[index], index, array);\n    }\n    return result;\n  }\n\n  /**\n   * Appends the elements of `values` to `array`.\n   *\n   * @private\n   * @param {Array} array The array to modify.\n   * @param {Array} values The values to append.\n   * @returns {Array} Returns `array`.\n   */\n  function arrayPush(array, values) {\n    var index = -1,\n        length = values.length,\n        offset = array.length;\n\n    while (++index < length) {\n      array[offset + index] = values[index];\n    }\n    return array;\n  }\n\n  /**\n   * A specialized version of `_.reduce` for arrays without support for\n   * iteratee shorthands.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @param {*} [accumulator] The initial value.\n   * @param {boolean} [initAccum] Specify using the first element of `array` as\n   *  the initial value.\n   * @returns {*} Returns the accumulated value.\n   */\n  function arrayReduce(array, iteratee, accumulator, initAccum) {\n    var index = -1,\n        length = array == null ? 0 : array.length;\n\n    if (initAccum && length) {\n      accumulator = array[++index];\n    }\n    while (++index < length) {\n      accumulator = iteratee(accumulator, array[index], index, array);\n    }\n    return accumulator;\n  }\n\n  /**\n   * A specialized version of `_.reduceRight` for arrays without support for\n   * iteratee shorthands.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @param {*} [accumulator] The initial value.\n   * @param {boolean} [initAccum] Specify using the last element of `array` as\n   *  the initial value.\n   * @returns {*} Returns the accumulated value.\n   */\n  function arrayReduceRight(array, iteratee, accumulator, initAccum) {\n    var length = array == null ? 0 : array.length;\n    if (initAccum && length) {\n      accumulator = array[--length];\n    }\n    while (length--) {\n      accumulator = iteratee(accumulator, array[length], length, array);\n    }\n    return accumulator;\n  }\n\n  /**\n   * A specialized version of `_.some` for arrays without support for iteratee\n   * shorthands.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} predicate The function invoked per iteration.\n   * @returns {boolean} Returns `true` if any element passes the predicate check,\n   *  else `false`.\n   */\n  function arraySome(array, predicate) {\n    var index = -1,\n        length = array == null ? 0 : array.length;\n\n    while (++index < length) {\n      if (predicate(array[index], index, array)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * Gets the size of an ASCII `string`.\n   *\n   * @private\n   * @param {string} string The string inspect.\n   * @returns {number} Returns the string size.\n   */\n  var asciiSize = baseProperty('length');\n\n  /**\n   * Converts an ASCII `string` to an array.\n   *\n   * @private\n   * @param {string} string The string to convert.\n   * @returns {Array} Returns the converted array.\n   */\n  function asciiToArray(string) {\n    return string.split('');\n  }\n\n  /**\n   * Splits an ASCII `string` into an array of its words.\n   *\n   * @private\n   * @param {string} The string to inspect.\n   * @returns {Array} Returns the words of `string`.\n   */\n  function asciiWords(string) {\n    return string.match(reAsciiWord) || [];\n  }\n\n  /**\n   * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n   * without support for iteratee shorthands, which iterates over `collection`\n   * using `eachFunc`.\n   *\n   * @private\n   * @param {Array|Object} collection The collection to inspect.\n   * @param {Function} predicate The function invoked per iteration.\n   * @param {Function} eachFunc The function to iterate over `collection`.\n   * @returns {*} Returns the found element or its key, else `undefined`.\n   */\n  function baseFindKey(collection, predicate, eachFunc) {\n    var result;\n    eachFunc(collection, function(value, key, collection) {\n      if (predicate(value, key, collection)) {\n        result = key;\n        return false;\n      }\n    });\n    return result;\n  }\n\n  /**\n   * The base implementation of `_.findIndex` and `_.findLastIndex` without\n   * support for iteratee shorthands.\n   *\n   * @private\n   * @param {Array} array The array to inspect.\n   * @param {Function} predicate The function invoked per iteration.\n   * @param {number} fromIndex The index to search from.\n   * @param {boolean} [fromRight] Specify iterating from right to left.\n   * @returns {number} Returns the index of the matched value, else `-1`.\n   */\n  function baseFindIndex(array, predicate, fromIndex, fromRight) {\n    var length = array.length,\n        index = fromIndex + (fromRight ? 1 : -1);\n\n    while ((fromRight ? index-- : ++index < length)) {\n      if (predicate(array[index], index, array)) {\n        return index;\n      }\n    }\n    return -1;\n  }\n\n  /**\n   * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n   *\n   * @private\n   * @param {Array} array The array to inspect.\n   * @param {*} value The value to search for.\n   * @param {number} fromIndex The index to search from.\n   * @returns {number} Returns the index of the matched value, else `-1`.\n   */\n  function baseIndexOf(array, value, fromIndex) {\n    return value === value\n      ? strictIndexOf(array, value, fromIndex)\n      : baseFindIndex(array, baseIsNaN, fromIndex);\n  }\n\n  /**\n   * This function is like `baseIndexOf` except that it accepts a comparator.\n   *\n   * @private\n   * @param {Array} array The array to inspect.\n   * @param {*} value The value to search for.\n   * @param {number} fromIndex The index to search from.\n   * @param {Function} comparator The comparator invoked per element.\n   * @returns {number} Returns the index of the matched value, else `-1`.\n   */\n  function baseIndexOfWith(array, value, fromIndex, comparator) {\n    var index = fromIndex - 1,\n        length = array.length;\n\n    while (++index < length) {\n      if (comparator(array[index], value)) {\n        return index;\n      }\n    }\n    return -1;\n  }\n\n  /**\n   * The base implementation of `_.isNaN` without support for number objects.\n   *\n   * @private\n   * @param {*} value The value to check.\n   * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n   */\n  function baseIsNaN(value) {\n    return value !== value;\n  }\n\n  /**\n   * The base implementation of `_.mean` and `_.meanBy` without support for\n   * iteratee shorthands.\n   *\n   * @private\n   * @param {Array} array The array to iterate over.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @returns {number} Returns the mean.\n   */\n  function baseMean(array, iteratee) {\n    var length = array == null ? 0 : array.length;\n    return length ? (baseSum(array, iteratee) / length) : NAN;\n  }\n\n  /**\n   * The base implementation of `_.property` without support for deep paths.\n   *\n   * @private\n   * @param {string} key The key of the property to get.\n   * @returns {Function} Returns the new accessor function.\n   */\n  function baseProperty(key) {\n    return function(object) {\n      return object == null ? undefined : object[key];\n    };\n  }\n\n  /**\n   * The base implementation of `_.propertyOf` without support for deep paths.\n   *\n   * @private\n   * @param {Object} object The object to query.\n   * @returns {Function} Returns the new accessor function.\n   */\n  function basePropertyOf(object) {\n    return function(key) {\n      return object == null ? undefined : object[key];\n    };\n  }\n\n  /**\n   * The base implementation of `_.reduce` and `_.reduceRight`, without support\n   * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n   *\n   * @private\n   * @param {Array|Object} collection The collection to iterate over.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @param {*} accumulator The initial value.\n   * @param {boolean} initAccum Specify using the first or last element of\n   *  `collection` as the initial value.\n   * @param {Function} eachFunc The function to iterate over `collection`.\n   * @returns {*} Returns the accumulated value.\n   */\n  function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n    eachFunc(collection, function(value, index, collection) {\n      accumulator = initAccum\n        ? (initAccum = false, value)\n        : iteratee(accumulator, value, index, collection);\n    });\n    return accumulator;\n  }\n\n  /**\n   * The base implementation of `_.sortBy` which uses `comparer` to define the\n   * sort order of `array` and replaces criteria objects with their corresponding\n   * values.\n   *\n   * @private\n   * @param {Array} array The array to sort.\n   * @param {Function} comparer The function to define sort order.\n   * @returns {Array} Returns `array`.\n   */\n  function baseSortBy(array, comparer) {\n    var length = array.length;\n\n    array.sort(comparer);\n    while (length--) {\n      array[length] = array[length].value;\n    }\n    return array;\n  }\n\n  /**\n   * The base implementation of `_.sum` and `_.sumBy` without support for\n   * iteratee shorthands.\n   *\n   * @private\n   * @param {Array} array The array to iterate over.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @returns {number} Returns the sum.\n   */\n  function baseSum(array, iteratee) {\n    var result,\n        index = -1,\n        length = array.length;\n\n    while (++index < length) {\n      var current = iteratee(array[index]);\n      if (current !== undefined) {\n        result = result === undefined ? current : (result + current);\n      }\n    }\n    return result;\n  }\n\n  /**\n   * The base implementation of `_.times` without support for iteratee shorthands\n   * or max array length checks.\n   *\n   * @private\n   * @param {number} n The number of times to invoke `iteratee`.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @returns {Array} Returns the array of results.\n   */\n  function baseTimes(n, iteratee) {\n    var index = -1,\n        result = Array(n);\n\n    while (++index < n) {\n      result[index] = iteratee(index);\n    }\n    return result;\n  }\n\n  /**\n   * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array\n   * of key-value pairs for `object` corresponding to the property names of `props`.\n   *\n   * @private\n   * @param {Object} object The object to query.\n   * @param {Array} props The property names to get values for.\n   * @returns {Object} Returns the key-value pairs.\n   */\n  function baseToPairs(object, props) {\n    return arrayMap(props, function(key) {\n      return [key, object[key]];\n    });\n  }\n\n  /**\n   * The base implementation of `_.unary` without support for storing metadata.\n   *\n   * @private\n   * @param {Function} func The function to cap arguments for.\n   * @returns {Function} Returns the new capped function.\n   */\n  function baseUnary(func) {\n    return function(value) {\n      return func(value);\n    };\n  }\n\n  /**\n   * The base implementation of `_.values` and `_.valuesIn` which creates an\n   * array of `object` property values corresponding to the property names\n   * of `props`.\n   *\n   * @private\n   * @param {Object} object The object to query.\n   * @param {Array} props The property names to get values for.\n   * @returns {Object} Returns the array of property values.\n   */\n  function baseValues(object, props) {\n    return arrayMap(props, function(key) {\n      return object[key];\n    });\n  }\n\n  /**\n   * Checks if a `cache` value for `key` exists.\n   *\n   * @private\n   * @param {Object} cache The cache to query.\n   * @param {string} key The key of the entry to check.\n   * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n   */\n  function cacheHas(cache, key) {\n    return cache.has(key);\n  }\n\n  /**\n   * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol\n   * that is not found in the character symbols.\n   *\n   * @private\n   * @param {Array} strSymbols The string symbols to inspect.\n   * @param {Array} chrSymbols The character symbols to find.\n   * @returns {number} Returns the index of the first unmatched string symbol.\n   */\n  function charsStartIndex(strSymbols, chrSymbols) {\n    var index = -1,\n        length = strSymbols.length;\n\n    while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n    return index;\n  }\n\n  /**\n   * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol\n   * that is not found in the character symbols.\n   *\n   * @private\n   * @param {Array} strSymbols The string symbols to inspect.\n   * @param {Array} chrSymbols The character symbols to find.\n   * @returns {number} Returns the index of the last unmatched string symbol.\n   */\n  function charsEndIndex(strSymbols, chrSymbols) {\n    var index = strSymbols.length;\n\n    while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n    return index;\n  }\n\n  /**\n   * Gets the number of `placeholder` occurrences in `array`.\n   *\n   * @private\n   * @param {Array} array The array to inspect.\n   * @param {*} placeholder The placeholder to search for.\n   * @returns {number} Returns the placeholder count.\n   */\n  function countHolders(array, placeholder) {\n    var length = array.length,\n        result = 0;\n\n    while (length--) {\n      if (array[length] === placeholder) {\n        ++result;\n      }\n    }\n    return result;\n  }\n\n  /**\n   * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n   * letters to basic Latin letters.\n   *\n   * @private\n   * @param {string} letter The matched letter to deburr.\n   * @returns {string} Returns the deburred letter.\n   */\n  var deburrLetter = basePropertyOf(deburredLetters);\n\n  /**\n   * Used by `_.escape` to convert characters to HTML entities.\n   *\n   * @private\n   * @param {string} chr The matched character to escape.\n   * @returns {string} Returns the escaped character.\n   */\n  var escapeHtmlChar = basePropertyOf(htmlEscapes);\n\n  /**\n   * Used by `_.template` to escape characters for inclusion in compiled string literals.\n   *\n   * @private\n   * @param {string} chr The matched character to escape.\n   * @returns {string} Returns the escaped character.\n   */\n  function escapeStringChar(chr) {\n    return '\\\\' + stringEscapes[chr];\n  }\n\n  /**\n   * Gets the value at `key` of `object`.\n   *\n   * @private\n   * @param {Object} [object] The object to query.\n   * @param {string} key The key of the property to get.\n   * @returns {*} Returns the property value.\n   */\n  function getValue(object, key) {\n    return object == null ? undefined : object[key];\n  }\n\n  /**\n   * Checks if `string` contains Unicode symbols.\n   *\n   * @private\n   * @param {string} string The string to inspect.\n   * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n   */\n  function hasUnicode(string) {\n    return reHasUnicode.test(string);\n  }\n\n  /**\n   * Checks if `string` contains a word composed of Unicode symbols.\n   *\n   * @private\n   * @param {string} string The string to inspect.\n   * @returns {boolean} Returns `true` if a word is found, else `false`.\n   */\n  function hasUnicodeWord(string) {\n    return reHasUnicodeWord.test(string);\n  }\n\n  /**\n   * Converts `iterator` to an array.\n   *\n   * @private\n   * @param {Object} iterator The iterator to convert.\n   * @returns {Array} Returns the converted array.\n   */\n  function iteratorToArray(iterator) {\n    var data,\n        result = [];\n\n    while (!(data = iterator.next()).done) {\n      result.push(data.value);\n    }\n    return result;\n  }\n\n  /**\n   * Converts `map` to its key-value pairs.\n   *\n   * @private\n   * @param {Object} map The map to convert.\n   * @returns {Array} Returns the key-value pairs.\n   */\n  function mapToArray(map) {\n    var index = -1,\n        result = Array(map.size);\n\n    map.forEach(function(value, key) {\n      result[++index] = [key, value];\n    });\n    return result;\n  }\n\n  /**\n   * Creates a unary function that invokes `func` with its argument transformed.\n   *\n   * @private\n   * @param {Function} func The function to wrap.\n   * @param {Function} transform The argument transform.\n   * @returns {Function} Returns the new function.\n   */\n  function overArg(func, transform) {\n    return function(arg) {\n      return func(transform(arg));\n    };\n  }\n\n  /**\n   * Replaces all `placeholder` elements in `array` with an internal placeholder\n   * and returns an array of their indexes.\n   *\n   * @private\n   * @param {Array} array The array to modify.\n   * @param {*} placeholder The placeholder to replace.\n   * @returns {Array} Returns the new array of placeholder indexes.\n   */\n  function replaceHolders(array, placeholder) {\n    var index = -1,\n        length = array.length,\n        resIndex = 0,\n        result = [];\n\n    while (++index < length) {\n      var value = array[index];\n      if (value === placeholder || value === PLACEHOLDER) {\n        array[index] = PLACEHOLDER;\n        result[resIndex++] = index;\n      }\n    }\n    return result;\n  }\n\n  /**\n   * Gets the value at `key`, unless `key` is \"__proto__\".\n   *\n   * @private\n   * @param {Object} object The object to query.\n   * @param {string} key The key of the property to get.\n   * @returns {*} Returns the property value.\n   */\n  function safeGet(object, key) {\n    return key == '__proto__'\n      ? undefined\n      : object[key];\n  }\n\n  /**\n   * Converts `set` to an array of its values.\n   *\n   * @private\n   * @param {Object} set The set to convert.\n   * @returns {Array} Returns the values.\n   */\n  function setToArray(set) {\n    var index = -1,\n        result = Array(set.size);\n\n    set.forEach(function(value) {\n      result[++index] = value;\n    });\n    return result;\n  }\n\n  /**\n   * Converts `set` to its value-value pairs.\n   *\n   * @private\n   * @param {Object} set The set to convert.\n   * @returns {Array} Returns the value-value pairs.\n   */\n  function setToPairs(set) {\n    var index = -1,\n        result = Array(set.size);\n\n    set.forEach(function(value) {\n      result[++index] = [value, value];\n    });\n    return result;\n  }\n\n  /**\n   * A specialized version of `_.indexOf` which performs strict equality\n   * comparisons of values, i.e. `===`.\n   *\n   * @private\n   * @param {Array} array The array to inspect.\n   * @param {*} value The value to search for.\n   * @param {number} fromIndex The index to search from.\n   * @returns {number} Returns the index of the matched value, else `-1`.\n   */\n  function strictIndexOf(array, value, fromIndex) {\n    var index = fromIndex - 1,\n        length = array.length;\n\n    while (++index < length) {\n      if (array[index] === value) {\n        return index;\n      }\n    }\n    return -1;\n  }\n\n  /**\n   * A specialized version of `_.lastIndexOf` which performs strict equality\n   * comparisons of values, i.e. `===`.\n   *\n   * @private\n   * @param {Array} array The array to inspect.\n   * @param {*} value The value to search for.\n   * @param {number} fromIndex The index to search from.\n   * @returns {number} Returns the index of the matched value, else `-1`.\n   */\n  function strictLastIndexOf(array, value, fromIndex) {\n    var index = fromIndex + 1;\n    while (index--) {\n      if (array[index] === value) {\n        return index;\n      }\n    }\n    return index;\n  }\n\n  /**\n   * Gets the number of symbols in `string`.\n   *\n   * @private\n   * @param {string} string The string to inspect.\n   * @returns {number} Returns the string size.\n   */\n  function stringSize(string) {\n    return hasUnicode(string)\n      ? unicodeSize(string)\n      : asciiSize(string);\n  }\n\n  /**\n   * Converts `string` to an array.\n   *\n   * @private\n   * @param {string} string The string to convert.\n   * @returns {Array} Returns the converted array.\n   */\n  function stringToArray(string) {\n    return hasUnicode(string)\n      ? unicodeToArray(string)\n      : asciiToArray(string);\n  }\n\n  /**\n   * Used by `_.unescape` to convert HTML entities to characters.\n   *\n   * @private\n   * @param {string} chr The matched character to unescape.\n   * @returns {string} Returns the unescaped character.\n   */\n  var unescapeHtmlChar = basePropertyOf(htmlUnescapes);\n\n  /**\n   * Gets the size of a Unicode `string`.\n   *\n   * @private\n   * @param {string} string The string inspect.\n   * @returns {number} Returns the string size.\n   */\n  function unicodeSize(string) {\n    var result = reUnicode.lastIndex = 0;\n    while (reUnicode.test(string)) {\n      ++result;\n    }\n    return result;\n  }\n\n  /**\n   * Converts a Unicode `string` to an array.\n   *\n   * @private\n   * @param {string} string The string to convert.\n   * @returns {Array} Returns the converted array.\n   */\n  function unicodeToArray(string) {\n    return string.match(reUnicode) || [];\n  }\n\n  /**\n   * Splits a Unicode `string` into an array of its words.\n   *\n   * @private\n   * @param {string} The string to inspect.\n   * @returns {Array} Returns the words of `string`.\n   */\n  function unicodeWords(string) {\n    return string.match(reUnicodeWord) || [];\n  }\n\n  /*--------------------------------------------------------------------------*/\n\n  /**\n   * Create a new pristine `lodash` function using the `context` object.\n   *\n   * @static\n   * @memberOf _\n   * @since 1.1.0\n   * @category Util\n   * @param {Object} [context=root] The context object.\n   * @returns {Function} Returns a new `lodash` function.\n   * @example\n   *\n   * _.mixin({ 'foo': _.constant('foo') });\n   *\n   * var lodash = _.runInContext();\n   * lodash.mixin({ 'bar': lodash.constant('bar') });\n   *\n   * _.isFunction(_.foo);\n   * // => true\n   * _.isFunction(_.bar);\n   * // => false\n   *\n   * lodash.isFunction(lodash.foo);\n   * // => false\n   * lodash.isFunction(lodash.bar);\n   * // => true\n   *\n   * // Create a suped-up `defer` in Node.js.\n   * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;\n   */\n  var runInContext = (function runInContext(context) {\n    context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));\n\n    /** Built-in constructor references. */\n    var Array = context.Array,\n        Date = context.Date,\n        Error = context.Error,\n        Function = context.Function,\n        Math = context.Math,\n        Object = context.Object,\n        RegExp = context.RegExp,\n        String = context.String,\n        TypeError = context.TypeError;\n\n    /** Used for built-in method references. */\n    var arrayProto = Array.prototype,\n        funcProto = Function.prototype,\n        objectProto = Object.prototype;\n\n    /** Used to detect overreaching core-js shims. */\n    var coreJsData = context['__core-js_shared__'];\n\n    /** Used to resolve the decompiled source of functions. */\n    var funcToString = funcProto.toString;\n\n    /** Used to check objects for own properties. */\n    var hasOwnProperty = objectProto.hasOwnProperty;\n\n    /** Used to generate unique IDs. */\n    var idCounter = 0;\n\n    /** Used to detect methods masquerading as native. */\n    var maskSrcKey = (function() {\n      var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n      return uid ? ('Symbol(src)_1.' + uid) : '';\n    }());\n\n    /**\n     * Used to resolve the\n     * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n     * of values.\n     */\n    var nativeObjectToString = objectProto.toString;\n\n    /** Used to infer the `Object` constructor. */\n    var objectCtorString = funcToString.call(Object);\n\n    /** Used to restore the original `_` reference in `_.noConflict`. */\n    var oldDash = root._;\n\n    /** Used to detect if a method is native. */\n    var reIsNative = RegExp('^' +\n      funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n      .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n    );\n\n    /** Built-in value references. */\n    var Buffer = moduleExports ? context.Buffer : undefined,\n        Symbol = context.Symbol,\n        Uint8Array = context.Uint8Array,\n        allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,\n        getPrototype = overArg(Object.getPrototypeOf, Object),\n        objectCreate = Object.create,\n        propertyIsEnumerable = objectProto.propertyIsEnumerable,\n        splice = arrayProto.splice,\n        spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,\n        symIterator = Symbol ? Symbol.iterator : undefined,\n        symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n    var defineProperty = (function() {\n      try {\n        var func = getNative(Object, 'defineProperty');\n        func({}, '', {});\n        return func;\n      } catch (e) {}\n    }());\n\n    /** Mocked built-ins. */\n    var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,\n        ctxNow = Date && Date.now !== root.Date.now && Date.now,\n        ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;\n\n    /* Built-in method references for those with the same name as other `lodash` methods. */\n    var nativeCeil = Math.ceil,\n        nativeFloor = Math.floor,\n        nativeGetSymbols = Object.getOwnPropertySymbols,\n        nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n        nativeIsFinite = context.isFinite,\n        nativeJoin = arrayProto.join,\n        nativeKeys = overArg(Object.keys, Object),\n        nativeMax = Math.max,\n        nativeMin = Math.min,\n        nativeNow = Date.now,\n        nativeParseInt = context.parseInt,\n        nativeRandom = Math.random,\n        nativeReverse = arrayProto.reverse;\n\n    /* Built-in method references that are verified to be native. */\n    var DataView = getNative(context, 'DataView'),\n        Map = getNative(context, 'Map'),\n        Promise = getNative(context, 'Promise'),\n        Set = getNative(context, 'Set'),\n        WeakMap = getNative(context, 'WeakMap'),\n        nativeCreate = getNative(Object, 'create');\n\n    /** Used to store function metadata. */\n    var metaMap = WeakMap && new WeakMap;\n\n    /** Used to lookup unminified function names. */\n    var realNames = {};\n\n    /** Used to detect maps, sets, and weakmaps. */\n    var dataViewCtorString = toSource(DataView),\n        mapCtorString = toSource(Map),\n        promiseCtorString = toSource(Promise),\n        setCtorString = toSource(Set),\n        weakMapCtorString = toSource(WeakMap);\n\n    /** Used to convert symbols to primitives and strings. */\n    var symbolProto = Symbol ? Symbol.prototype : undefined,\n        symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,\n        symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates a `lodash` object which wraps `value` to enable implicit method\n     * chain sequences. Methods that operate on and return arrays, collections,\n     * and functions can be chained together. Methods that retrieve a single value\n     * or may return a primitive value will automatically end the chain sequence\n     * and return the unwrapped value. Otherwise, the value must be unwrapped\n     * with `_#value`.\n     *\n     * Explicit chain sequences, which must be unwrapped with `_#value`, may be\n     * enabled using `_.chain`.\n     *\n     * The execution of chained methods is lazy, that is, it's deferred until\n     * `_#value` is implicitly or explicitly called.\n     *\n     * Lazy evaluation allows several methods to support shortcut fusion.\n     * Shortcut fusion is an optimization to merge iteratee calls; this avoids\n     * the creation of intermediate arrays and can greatly reduce the number of\n     * iteratee executions. Sections of a chain sequence qualify for shortcut\n     * fusion if the section is applied to an array and iteratees accept only\n     * one argument. The heuristic for whether a section qualifies for shortcut\n     * fusion is subject to change.\n     *\n     * Chaining is supported in custom builds as long as the `_#value` method is\n     * directly or indirectly included in the build.\n     *\n     * In addition to lodash methods, wrappers have `Array` and `String` methods.\n     *\n     * The wrapper `Array` methods are:\n     * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`\n     *\n     * The wrapper `String` methods are:\n     * `replace` and `split`\n     *\n     * The wrapper methods that support shortcut fusion are:\n     * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,\n     * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,\n     * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`\n     *\n     * The chainable wrapper methods are:\n     * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,\n     * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,\n     * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,\n     * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,\n     * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,\n     * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,\n     * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,\n     * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,\n     * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,\n     * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,\n     * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,\n     * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,\n     * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,\n     * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,\n     * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,\n     * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,\n     * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,\n     * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,\n     * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,\n     * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,\n     * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,\n     * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,\n     * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,\n     * `zipObject`, `zipObjectDeep`, and `zipWith`\n     *\n     * The wrapper methods that are **not** chainable by default are:\n     * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,\n     * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,\n     * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,\n     * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,\n     * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,\n     * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,\n     * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,\n     * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,\n     * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,\n     * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,\n     * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,\n     * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,\n     * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,\n     * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,\n     * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,\n     * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,\n     * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,\n     * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,\n     * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,\n     * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,\n     * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,\n     * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,\n     * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,\n     * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,\n     * `upperFirst`, `value`, and `words`\n     *\n     * @name _\n     * @constructor\n     * @category Seq\n     * @param {*} value The value to wrap in a `lodash` instance.\n     * @returns {Object} Returns the new `lodash` wrapper instance.\n     * @example\n     *\n     * function square(n) {\n     *   return n * n;\n     * }\n     *\n     * var wrapped = _([1, 2, 3]);\n     *\n     * // Returns an unwrapped value.\n     * wrapped.reduce(_.add);\n     * // => 6\n     *\n     * // Returns a wrapped value.\n     * var squares = wrapped.map(square);\n     *\n     * _.isArray(squares);\n     * // => false\n     *\n     * _.isArray(squares.value());\n     * // => true\n     */\n    function lodash(value) {\n      if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n        if (value instanceof LodashWrapper) {\n          return value;\n        }\n        if (hasOwnProperty.call(value, '__wrapped__')) {\n          return wrapperClone(value);\n        }\n      }\n      return new LodashWrapper(value);\n    }\n\n    /**\n     * The base implementation of `_.create` without support for assigning\n     * properties to the created object.\n     *\n     * @private\n     * @param {Object} proto The object to inherit from.\n     * @returns {Object} Returns the new object.\n     */\n    var baseCreate = (function() {\n      function object() {}\n      return function(proto) {\n        if (!isObject(proto)) {\n          return {};\n        }\n        if (objectCreate) {\n          return objectCreate(proto);\n        }\n        object.prototype = proto;\n        var result = new object;\n        object.prototype = undefined;\n        return result;\n      };\n    }());\n\n    /**\n     * The function whose prototype chain sequence wrappers inherit from.\n     *\n     * @private\n     */\n    function baseLodash() {\n      // No operation performed.\n    }\n\n    /**\n     * The base constructor for creating `lodash` wrapper objects.\n     *\n     * @private\n     * @param {*} value The value to wrap.\n     * @param {boolean} [chainAll] Enable explicit method chain sequences.\n     */\n    function LodashWrapper(value, chainAll) {\n      this.__wrapped__ = value;\n      this.__actions__ = [];\n      this.__chain__ = !!chainAll;\n      this.__index__ = 0;\n      this.__values__ = undefined;\n    }\n\n    /**\n     * By default, the template delimiters used by lodash are like those in\n     * embedded Ruby (ERB) as well as ES2015 template strings. Change the\n     * following template settings to use alternative delimiters.\n     *\n     * @static\n     * @memberOf _\n     * @type {Object}\n     */\n    lodash.templateSettings = {\n\n      /**\n       * Used to detect `data` property values to be HTML-escaped.\n       *\n       * @memberOf _.templateSettings\n       * @type {RegExp}\n       */\n      'escape': reEscape,\n\n      /**\n       * Used to detect code to be evaluated.\n       *\n       * @memberOf _.templateSettings\n       * @type {RegExp}\n       */\n      'evaluate': reEvaluate,\n\n      /**\n       * Used to detect `data` property values to inject.\n       *\n       * @memberOf _.templateSettings\n       * @type {RegExp}\n       */\n      'interpolate': reInterpolate,\n\n      /**\n       * Used to reference the data object in the template text.\n       *\n       * @memberOf _.templateSettings\n       * @type {string}\n       */\n      'variable': '',\n\n      /**\n       * Used to import variables into the compiled template.\n       *\n       * @memberOf _.templateSettings\n       * @type {Object}\n       */\n      'imports': {\n\n        /**\n         * A reference to the `lodash` function.\n         *\n         * @memberOf _.templateSettings.imports\n         * @type {Function}\n         */\n        '_': lodash\n      }\n    };\n\n    // Ensure wrappers are instances of `baseLodash`.\n    lodash.prototype = baseLodash.prototype;\n    lodash.prototype.constructor = lodash;\n\n    LodashWrapper.prototype = baseCreate(baseLodash.prototype);\n    LodashWrapper.prototype.constructor = LodashWrapper;\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n     *\n     * @private\n     * @constructor\n     * @param {*} value The value to wrap.\n     */\n    function LazyWrapper(value) {\n      this.__wrapped__ = value;\n      this.__actions__ = [];\n      this.__dir__ = 1;\n      this.__filtered__ = false;\n      this.__iteratees__ = [];\n      this.__takeCount__ = MAX_ARRAY_LENGTH;\n      this.__views__ = [];\n    }\n\n    /**\n     * Creates a clone of the lazy wrapper object.\n     *\n     * @private\n     * @name clone\n     * @memberOf LazyWrapper\n     * @returns {Object} Returns the cloned `LazyWrapper` object.\n     */\n    function lazyClone() {\n      var result = new LazyWrapper(this.__wrapped__);\n      result.__actions__ = copyArray(this.__actions__);\n      result.__dir__ = this.__dir__;\n      result.__filtered__ = this.__filtered__;\n      result.__iteratees__ = copyArray(this.__iteratees__);\n      result.__takeCount__ = this.__takeCount__;\n      result.__views__ = copyArray(this.__views__);\n      return result;\n    }\n\n    /**\n     * Reverses the direction of lazy iteration.\n     *\n     * @private\n     * @name reverse\n     * @memberOf LazyWrapper\n     * @returns {Object} Returns the new reversed `LazyWrapper` object.\n     */\n    function lazyReverse() {\n      if (this.__filtered__) {\n        var result = new LazyWrapper(this);\n        result.__dir__ = -1;\n        result.__filtered__ = true;\n      } else {\n        result = this.clone();\n        result.__dir__ *= -1;\n      }\n      return result;\n    }\n\n    /**\n     * Extracts the unwrapped value from its lazy wrapper.\n     *\n     * @private\n     * @name value\n     * @memberOf LazyWrapper\n     * @returns {*} Returns the unwrapped value.\n     */\n    function lazyValue() {\n      var array = this.__wrapped__.value(),\n          dir = this.__dir__,\n          isArr = isArray(array),\n          isRight = dir < 0,\n          arrLength = isArr ? array.length : 0,\n          view = getView(0, arrLength, this.__views__),\n          start = view.start,\n          end = view.end,\n          length = end - start,\n          index = isRight ? end : (start - 1),\n          iteratees = this.__iteratees__,\n          iterLength = iteratees.length,\n          resIndex = 0,\n          takeCount = nativeMin(length, this.__takeCount__);\n\n      if (!isArr || (!isRight && arrLength == length && takeCount == length)) {\n        return baseWrapperValue(array, this.__actions__);\n      }\n      var result = [];\n\n      outer:\n      while (length-- && resIndex < takeCount) {\n        index += dir;\n\n        var iterIndex = -1,\n            value = array[index];\n\n        while (++iterIndex < iterLength) {\n          var data = iteratees[iterIndex],\n              iteratee = data.iteratee,\n              type = data.type,\n              computed = iteratee(value);\n\n          if (type == LAZY_MAP_FLAG) {\n            value = computed;\n          } else if (!computed) {\n            if (type == LAZY_FILTER_FLAG) {\n              continue outer;\n            } else {\n              break outer;\n            }\n          }\n        }\n        result[resIndex++] = value;\n      }\n      return result;\n    }\n\n    // Ensure `LazyWrapper` is an instance of `baseLodash`.\n    LazyWrapper.prototype = baseCreate(baseLodash.prototype);\n    LazyWrapper.prototype.constructor = LazyWrapper;\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates a hash object.\n     *\n     * @private\n     * @constructor\n     * @param {Array} [entries] The key-value pairs to cache.\n     */\n    function Hash(entries) {\n      var index = -1,\n          length = entries == null ? 0 : entries.length;\n\n      this.clear();\n      while (++index < length) {\n        var entry = entries[index];\n        this.set(entry[0], entry[1]);\n      }\n    }\n\n    /**\n     * Removes all key-value entries from the hash.\n     *\n     * @private\n     * @name clear\n     * @memberOf Hash\n     */\n    function hashClear() {\n      this.__data__ = nativeCreate ? nativeCreate(null) : {};\n      this.size = 0;\n    }\n\n    /**\n     * Removes `key` and its value from the hash.\n     *\n     * @private\n     * @name delete\n     * @memberOf Hash\n     * @param {Object} hash The hash to modify.\n     * @param {string} key The key of the value to remove.\n     * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n     */\n    function hashDelete(key) {\n      var result = this.has(key) && delete this.__data__[key];\n      this.size -= result ? 1 : 0;\n      return result;\n    }\n\n    /**\n     * Gets the hash value for `key`.\n     *\n     * @private\n     * @name get\n     * @memberOf Hash\n     * @param {string} key The key of the value to get.\n     * @returns {*} Returns the entry value.\n     */\n    function hashGet(key) {\n      var data = this.__data__;\n      if (nativeCreate) {\n        var result = data[key];\n        return result === HASH_UNDEFINED ? undefined : result;\n      }\n      return hasOwnProperty.call(data, key) ? data[key] : undefined;\n    }\n\n    /**\n     * Checks if a hash value for `key` exists.\n     *\n     * @private\n     * @name has\n     * @memberOf Hash\n     * @param {string} key The key of the entry to check.\n     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n     */\n    function hashHas(key) {\n      var data = this.__data__;\n      return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n    }\n\n    /**\n     * Sets the hash `key` to `value`.\n     *\n     * @private\n     * @name set\n     * @memberOf Hash\n     * @param {string} key The key of the value to set.\n     * @param {*} value The value to set.\n     * @returns {Object} Returns the hash instance.\n     */\n    function hashSet(key, value) {\n      var data = this.__data__;\n      this.size += this.has(key) ? 0 : 1;\n      data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n      return this;\n    }\n\n    // Add methods to `Hash`.\n    Hash.prototype.clear = hashClear;\n    Hash.prototype['delete'] = hashDelete;\n    Hash.prototype.get = hashGet;\n    Hash.prototype.has = hashHas;\n    Hash.prototype.set = hashSet;\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates an list cache object.\n     *\n     * @private\n     * @constructor\n     * @param {Array} [entries] The key-value pairs to cache.\n     */\n    function ListCache(entries) {\n      var index = -1,\n          length = entries == null ? 0 : entries.length;\n\n      this.clear();\n      while (++index < length) {\n        var entry = entries[index];\n        this.set(entry[0], entry[1]);\n      }\n    }\n\n    /**\n     * Removes all key-value entries from the list cache.\n     *\n     * @private\n     * @name clear\n     * @memberOf ListCache\n     */\n    function listCacheClear() {\n      this.__data__ = [];\n      this.size = 0;\n    }\n\n    /**\n     * Removes `key` and its value from the list cache.\n     *\n     * @private\n     * @name delete\n     * @memberOf ListCache\n     * @param {string} key The key of the value to remove.\n     * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n     */\n    function listCacheDelete(key) {\n      var data = this.__data__,\n          index = assocIndexOf(data, key);\n\n      if (index < 0) {\n        return false;\n      }\n      var lastIndex = data.length - 1;\n      if (index == lastIndex) {\n        data.pop();\n      } else {\n        splice.call(data, index, 1);\n      }\n      --this.size;\n      return true;\n    }\n\n    /**\n     * Gets the list cache value for `key`.\n     *\n     * @private\n     * @name get\n     * @memberOf ListCache\n     * @param {string} key The key of the value to get.\n     * @returns {*} Returns the entry value.\n     */\n    function listCacheGet(key) {\n      var data = this.__data__,\n          index = assocIndexOf(data, key);\n\n      return index < 0 ? undefined : data[index][1];\n    }\n\n    /**\n     * Checks if a list cache value for `key` exists.\n     *\n     * @private\n     * @name has\n     * @memberOf ListCache\n     * @param {string} key The key of the entry to check.\n     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n     */\n    function listCacheHas(key) {\n      return assocIndexOf(this.__data__, key) > -1;\n    }\n\n    /**\n     * Sets the list cache `key` to `value`.\n     *\n     * @private\n     * @name set\n     * @memberOf ListCache\n     * @param {string} key The key of the value to set.\n     * @param {*} value The value to set.\n     * @returns {Object} Returns the list cache instance.\n     */\n    function listCacheSet(key, value) {\n      var data = this.__data__,\n          index = assocIndexOf(data, key);\n\n      if (index < 0) {\n        ++this.size;\n        data.push([key, value]);\n      } else {\n        data[index][1] = value;\n      }\n      return this;\n    }\n\n    // Add methods to `ListCache`.\n    ListCache.prototype.clear = listCacheClear;\n    ListCache.prototype['delete'] = listCacheDelete;\n    ListCache.prototype.get = listCacheGet;\n    ListCache.prototype.has = listCacheHas;\n    ListCache.prototype.set = listCacheSet;\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates a map cache object to store key-value pairs.\n     *\n     * @private\n     * @constructor\n     * @param {Array} [entries] The key-value pairs to cache.\n     */\n    function MapCache(entries) {\n      var index = -1,\n          length = entries == null ? 0 : entries.length;\n\n      this.clear();\n      while (++index < length) {\n        var entry = entries[index];\n        this.set(entry[0], entry[1]);\n      }\n    }\n\n    /**\n     * Removes all key-value entries from the map.\n     *\n     * @private\n     * @name clear\n     * @memberOf MapCache\n     */\n    function mapCacheClear() {\n      this.size = 0;\n      this.__data__ = {\n        'hash': new Hash,\n        'map': new (Map || ListCache),\n        'string': new Hash\n      };\n    }\n\n    /**\n     * Removes `key` and its value from the map.\n     *\n     * @private\n     * @name delete\n     * @memberOf MapCache\n     * @param {string} key The key of the value to remove.\n     * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n     */\n    function mapCacheDelete(key) {\n      var result = getMapData(this, key)['delete'](key);\n      this.size -= result ? 1 : 0;\n      return result;\n    }\n\n    /**\n     * Gets the map value for `key`.\n     *\n     * @private\n     * @name get\n     * @memberOf MapCache\n     * @param {string} key The key of the value to get.\n     * @returns {*} Returns the entry value.\n     */\n    function mapCacheGet(key) {\n      return getMapData(this, key).get(key);\n    }\n\n    /**\n     * Checks if a map value for `key` exists.\n     *\n     * @private\n     * @name has\n     * @memberOf MapCache\n     * @param {string} key The key of the entry to check.\n     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n     */\n    function mapCacheHas(key) {\n      return getMapData(this, key).has(key);\n    }\n\n    /**\n     * Sets the map `key` to `value`.\n     *\n     * @private\n     * @name set\n     * @memberOf MapCache\n     * @param {string} key The key of the value to set.\n     * @param {*} value The value to set.\n     * @returns {Object} Returns the map cache instance.\n     */\n    function mapCacheSet(key, value) {\n      var data = getMapData(this, key),\n          size = data.size;\n\n      data.set(key, value);\n      this.size += data.size == size ? 0 : 1;\n      return this;\n    }\n\n    // Add methods to `MapCache`.\n    MapCache.prototype.clear = mapCacheClear;\n    MapCache.prototype['delete'] = mapCacheDelete;\n    MapCache.prototype.get = mapCacheGet;\n    MapCache.prototype.has = mapCacheHas;\n    MapCache.prototype.set = mapCacheSet;\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     *\n     * Creates an array cache object to store unique values.\n     *\n     * @private\n     * @constructor\n     * @param {Array} [values] The values to cache.\n     */\n    function SetCache(values) {\n      var index = -1,\n          length = values == null ? 0 : values.length;\n\n      this.__data__ = new MapCache;\n      while (++index < length) {\n        this.add(values[index]);\n      }\n    }\n\n    /**\n     * Adds `value` to the array cache.\n     *\n     * @private\n     * @name add\n     * @memberOf SetCache\n     * @alias push\n     * @param {*} value The value to cache.\n     * @returns {Object} Returns the cache instance.\n     */\n    function setCacheAdd(value) {\n      this.__data__.set(value, HASH_UNDEFINED);\n      return this;\n    }\n\n    /**\n     * Checks if `value` is in the array cache.\n     *\n     * @private\n     * @name has\n     * @memberOf SetCache\n     * @param {*} value The value to search for.\n     * @returns {number} Returns `true` if `value` is found, else `false`.\n     */\n    function setCacheHas(value) {\n      return this.__data__.has(value);\n    }\n\n    // Add methods to `SetCache`.\n    SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\n    SetCache.prototype.has = setCacheHas;\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates a stack cache object to store key-value pairs.\n     *\n     * @private\n     * @constructor\n     * @param {Array} [entries] The key-value pairs to cache.\n     */\n    function Stack(entries) {\n      var data = this.__data__ = new ListCache(entries);\n      this.size = data.size;\n    }\n\n    /**\n     * Removes all key-value entries from the stack.\n     *\n     * @private\n     * @name clear\n     * @memberOf Stack\n     */\n    function stackClear() {\n      this.__data__ = new ListCache;\n      this.size = 0;\n    }\n\n    /**\n     * Removes `key` and its value from the stack.\n     *\n     * @private\n     * @name delete\n     * @memberOf Stack\n     * @param {string} key The key of the value to remove.\n     * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n     */\n    function stackDelete(key) {\n      var data = this.__data__,\n          result = data['delete'](key);\n\n      this.size = data.size;\n      return result;\n    }\n\n    /**\n     * Gets the stack value for `key`.\n     *\n     * @private\n     * @name get\n     * @memberOf Stack\n     * @param {string} key The key of the value to get.\n     * @returns {*} Returns the entry value.\n     */\n    function stackGet(key) {\n      return this.__data__.get(key);\n    }\n\n    /**\n     * Checks if a stack value for `key` exists.\n     *\n     * @private\n     * @name has\n     * @memberOf Stack\n     * @param {string} key The key of the entry to check.\n     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n     */\n    function stackHas(key) {\n      return this.__data__.has(key);\n    }\n\n    /**\n     * Sets the stack `key` to `value`.\n     *\n     * @private\n     * @name set\n     * @memberOf Stack\n     * @param {string} key The key of the value to set.\n     * @param {*} value The value to set.\n     * @returns {Object} Returns the stack cache instance.\n     */\n    function stackSet(key, value) {\n      var data = this.__data__;\n      if (data instanceof ListCache) {\n        var pairs = data.__data__;\n        if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n          pairs.push([key, value]);\n          this.size = ++data.size;\n          return this;\n        }\n        data = this.__data__ = new MapCache(pairs);\n      }\n      data.set(key, value);\n      this.size = data.size;\n      return this;\n    }\n\n    // Add methods to `Stack`.\n    Stack.prototype.clear = stackClear;\n    Stack.prototype['delete'] = stackDelete;\n    Stack.prototype.get = stackGet;\n    Stack.prototype.has = stackHas;\n    Stack.prototype.set = stackSet;\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates an array of the enumerable property names of the array-like `value`.\n     *\n     * @private\n     * @param {*} value The value to query.\n     * @param {boolean} inherited Specify returning inherited property names.\n     * @returns {Array} Returns the array of property names.\n     */\n    function arrayLikeKeys(value, inherited) {\n      var isArr = isArray(value),\n          isArg = !isArr && isArguments(value),\n          isBuff = !isArr && !isArg && isBuffer(value),\n          isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n          skipIndexes = isArr || isArg || isBuff || isType,\n          result = skipIndexes ? baseTimes(value.length, String) : [],\n          length = result.length;\n\n      for (var key in value) {\n        if ((inherited || hasOwnProperty.call(value, key)) &&\n            !(skipIndexes && (\n               // Safari 9 has enumerable `arguments.length` in strict mode.\n               key == 'length' ||\n               // Node.js 0.10 has enumerable non-index properties on buffers.\n               (isBuff && (key == 'offset' || key == 'parent')) ||\n               // PhantomJS 2 has enumerable non-index properties on typed arrays.\n               (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n               // Skip index properties.\n               isIndex(key, length)\n            ))) {\n          result.push(key);\n        }\n      }\n      return result;\n    }\n\n    /**\n     * A specialized version of `_.sample` for arrays.\n     *\n     * @private\n     * @param {Array} array The array to sample.\n     * @returns {*} Returns the random element.\n     */\n    function arraySample(array) {\n      var length = array.length;\n      return length ? array[baseRandom(0, length - 1)] : undefined;\n    }\n\n    /**\n     * A specialized version of `_.sampleSize` for arrays.\n     *\n     * @private\n     * @param {Array} array The array to sample.\n     * @param {number} n The number of elements to sample.\n     * @returns {Array} Returns the random elements.\n     */\n    function arraySampleSize(array, n) {\n      return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));\n    }\n\n    /**\n     * A specialized version of `_.shuffle` for arrays.\n     *\n     * @private\n     * @param {Array} array The array to shuffle.\n     * @returns {Array} Returns the new shuffled array.\n     */\n    function arrayShuffle(array) {\n      return shuffleSelf(copyArray(array));\n    }\n\n    /**\n     * This function is like `assignValue` except that it doesn't assign\n     * `undefined` values.\n     *\n     * @private\n     * @param {Object} object The object to modify.\n     * @param {string} key The key of the property to assign.\n     * @param {*} value The value to assign.\n     */\n    function assignMergeValue(object, key, value) {\n      if ((value !== undefined && !eq(object[key], value)) ||\n          (value === undefined && !(key in object))) {\n        baseAssignValue(object, key, value);\n      }\n    }\n\n    /**\n     * Assigns `value` to `key` of `object` if the existing value is not equivalent\n     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * for equality comparisons.\n     *\n     * @private\n     * @param {Object} object The object to modify.\n     * @param {string} key The key of the property to assign.\n     * @param {*} value The value to assign.\n     */\n    function assignValue(object, key, value) {\n      var objValue = object[key];\n      if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n          (value === undefined && !(key in object))) {\n        baseAssignValue(object, key, value);\n      }\n    }\n\n    /**\n     * Gets the index at which the `key` is found in `array` of key-value pairs.\n     *\n     * @private\n     * @param {Array} array The array to inspect.\n     * @param {*} key The key to search for.\n     * @returns {number} Returns the index of the matched value, else `-1`.\n     */\n    function assocIndexOf(array, key) {\n      var length = array.length;\n      while (length--) {\n        if (eq(array[length][0], key)) {\n          return length;\n        }\n      }\n      return -1;\n    }\n\n    /**\n     * Aggregates elements of `collection` on `accumulator` with keys transformed\n     * by `iteratee` and values set by `setter`.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} setter The function to set `accumulator` values.\n     * @param {Function} iteratee The iteratee to transform keys.\n     * @param {Object} accumulator The initial aggregated object.\n     * @returns {Function} Returns `accumulator`.\n     */\n    function baseAggregator(collection, setter, iteratee, accumulator) {\n      baseEach(collection, function(value, key, collection) {\n        setter(accumulator, value, iteratee(value), collection);\n      });\n      return accumulator;\n    }\n\n    /**\n     * The base implementation of `_.assign` without support for multiple sources\n     * or `customizer` functions.\n     *\n     * @private\n     * @param {Object} object The destination object.\n     * @param {Object} source The source object.\n     * @returns {Object} Returns `object`.\n     */\n    function baseAssign(object, source) {\n      return object && copyObject(source, keys(source), object);\n    }\n\n    /**\n     * The base implementation of `_.assignIn` without support for multiple sources\n     * or `customizer` functions.\n     *\n     * @private\n     * @param {Object} object The destination object.\n     * @param {Object} source The source object.\n     * @returns {Object} Returns `object`.\n     */\n    function baseAssignIn(object, source) {\n      return object && copyObject(source, keysIn(source), object);\n    }\n\n    /**\n     * The base implementation of `assignValue` and `assignMergeValue` without\n     * value checks.\n     *\n     * @private\n     * @param {Object} object The object to modify.\n     * @param {string} key The key of the property to assign.\n     * @param {*} value The value to assign.\n     */\n    function baseAssignValue(object, key, value) {\n      if (key == '__proto__' && defineProperty) {\n        defineProperty(object, key, {\n          'configurable': true,\n          'enumerable': true,\n          'value': value,\n          'writable': true\n        });\n      } else {\n        object[key] = value;\n      }\n    }\n\n    /**\n     * The base implementation of `_.at` without support for individual paths.\n     *\n     * @private\n     * @param {Object} object The object to iterate over.\n     * @param {string[]} paths The property paths to pick.\n     * @returns {Array} Returns the picked elements.\n     */\n    function baseAt(object, paths) {\n      var index = -1,\n          length = paths.length,\n          result = Array(length),\n          skip = object == null;\n\n      while (++index < length) {\n        result[index] = skip ? undefined : get(object, paths[index]);\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.clamp` which doesn't coerce arguments.\n     *\n     * @private\n     * @param {number} number The number to clamp.\n     * @param {number} [lower] The lower bound.\n     * @param {number} upper The upper bound.\n     * @returns {number} Returns the clamped number.\n     */\n    function baseClamp(number, lower, upper) {\n      if (number === number) {\n        if (upper !== undefined) {\n          number = number <= upper ? number : upper;\n        }\n        if (lower !== undefined) {\n          number = number >= lower ? number : lower;\n        }\n      }\n      return number;\n    }\n\n    /**\n     * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n     * traversed objects.\n     *\n     * @private\n     * @param {*} value The value to clone.\n     * @param {boolean} bitmask The bitmask flags.\n     *  1 - Deep clone\n     *  2 - Flatten inherited properties\n     *  4 - Clone symbols\n     * @param {Function} [customizer] The function to customize cloning.\n     * @param {string} [key] The key of `value`.\n     * @param {Object} [object] The parent object of `value`.\n     * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n     * @returns {*} Returns the cloned value.\n     */\n    function baseClone(value, bitmask, customizer, key, object, stack) {\n      var result,\n          isDeep = bitmask & CLONE_DEEP_FLAG,\n          isFlat = bitmask & CLONE_FLAT_FLAG,\n          isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n      if (customizer) {\n        result = object ? customizer(value, key, object, stack) : customizer(value);\n      }\n      if (result !== undefined) {\n        return result;\n      }\n      if (!isObject(value)) {\n        return value;\n      }\n      var isArr = isArray(value);\n      if (isArr) {\n        result = initCloneArray(value);\n        if (!isDeep) {\n          return copyArray(value, result);\n        }\n      } else {\n        var tag = getTag(value),\n            isFunc = tag == funcTag || tag == genTag;\n\n        if (isBuffer(value)) {\n          return cloneBuffer(value, isDeep);\n        }\n        if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n          result = (isFlat || isFunc) ? {} : initCloneObject(value);\n          if (!isDeep) {\n            return isFlat\n              ? copySymbolsIn(value, baseAssignIn(result, value))\n              : copySymbols(value, baseAssign(result, value));\n          }\n        } else {\n          if (!cloneableTags[tag]) {\n            return object ? value : {};\n          }\n          result = initCloneByTag(value, tag, isDeep);\n        }\n      }\n      // Check for circular references and return its corresponding clone.\n      stack || (stack = new Stack);\n      var stacked = stack.get(value);\n      if (stacked) {\n        return stacked;\n      }\n      stack.set(value, result);\n\n      if (isSet(value)) {\n        value.forEach(function(subValue) {\n          result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n        });\n\n        return result;\n      }\n\n      if (isMap(value)) {\n        value.forEach(function(subValue, key) {\n          result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n        });\n\n        return result;\n      }\n\n      var keysFunc = isFull\n        ? (isFlat ? getAllKeysIn : getAllKeys)\n        : (isFlat ? keysIn : keys);\n\n      var props = isArr ? undefined : keysFunc(value);\n      arrayEach(props || value, function(subValue, key) {\n        if (props) {\n          key = subValue;\n          subValue = value[key];\n        }\n        // Recursively populate clone (susceptible to call stack limits).\n        assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n      });\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.conforms` which doesn't clone `source`.\n     *\n     * @private\n     * @param {Object} source The object of property predicates to conform to.\n     * @returns {Function} Returns the new spec function.\n     */\n    function baseConforms(source) {\n      var props = keys(source);\n      return function(object) {\n        return baseConformsTo(object, source, props);\n      };\n    }\n\n    /**\n     * The base implementation of `_.conformsTo` which accepts `props` to check.\n     *\n     * @private\n     * @param {Object} object The object to inspect.\n     * @param {Object} source The object of property predicates to conform to.\n     * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n     */\n    function baseConformsTo(object, source, props) {\n      var length = props.length;\n      if (object == null) {\n        return !length;\n      }\n      object = Object(object);\n      while (length--) {\n        var key = props[length],\n            predicate = source[key],\n            value = object[key];\n\n        if ((value === undefined && !(key in object)) || !predicate(value)) {\n          return false;\n        }\n      }\n      return true;\n    }\n\n    /**\n     * The base implementation of `_.delay` and `_.defer` which accepts `args`\n     * to provide to `func`.\n     *\n     * @private\n     * @param {Function} func The function to delay.\n     * @param {number} wait The number of milliseconds to delay invocation.\n     * @param {Array} args The arguments to provide to `func`.\n     * @returns {number|Object} Returns the timer id or timeout object.\n     */\n    function baseDelay(func, wait, args) {\n      if (typeof func != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      return setTimeout(function() { func.apply(undefined, args); }, wait);\n    }\n\n    /**\n     * The base implementation of methods like `_.difference` without support\n     * for excluding multiple arrays or iteratee shorthands.\n     *\n     * @private\n     * @param {Array} array The array to inspect.\n     * @param {Array} values The values to exclude.\n     * @param {Function} [iteratee] The iteratee invoked per element.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns the new array of filtered values.\n     */\n    function baseDifference(array, values, iteratee, comparator) {\n      var index = -1,\n          includes = arrayIncludes,\n          isCommon = true,\n          length = array.length,\n          result = [],\n          valuesLength = values.length;\n\n      if (!length) {\n        return result;\n      }\n      if (iteratee) {\n        values = arrayMap(values, baseUnary(iteratee));\n      }\n      if (comparator) {\n        includes = arrayIncludesWith;\n        isCommon = false;\n      }\n      else if (values.length >= LARGE_ARRAY_SIZE) {\n        includes = cacheHas;\n        isCommon = false;\n        values = new SetCache(values);\n      }\n      outer:\n      while (++index < length) {\n        var value = array[index],\n            computed = iteratee == null ? value : iteratee(value);\n\n        value = (comparator || value !== 0) ? value : 0;\n        if (isCommon && computed === computed) {\n          var valuesIndex = valuesLength;\n          while (valuesIndex--) {\n            if (values[valuesIndex] === computed) {\n              continue outer;\n            }\n          }\n          result.push(value);\n        }\n        else if (!includes(values, computed, comparator)) {\n          result.push(value);\n        }\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.forEach` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} iteratee The function invoked per iteration.\n     * @returns {Array|Object} Returns `collection`.\n     */\n    var baseEach = createBaseEach(baseForOwn);\n\n    /**\n     * The base implementation of `_.forEachRight` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} iteratee The function invoked per iteration.\n     * @returns {Array|Object} Returns `collection`.\n     */\n    var baseEachRight = createBaseEach(baseForOwnRight, true);\n\n    /**\n     * The base implementation of `_.every` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} predicate The function invoked per iteration.\n     * @returns {boolean} Returns `true` if all elements pass the predicate check,\n     *  else `false`\n     */\n    function baseEvery(collection, predicate) {\n      var result = true;\n      baseEach(collection, function(value, index, collection) {\n        result = !!predicate(value, index, collection);\n        return result;\n      });\n      return result;\n    }\n\n    /**\n     * The base implementation of methods like `_.max` and `_.min` which accepts a\n     * `comparator` to determine the extremum value.\n     *\n     * @private\n     * @param {Array} array The array to iterate over.\n     * @param {Function} iteratee The iteratee invoked per iteration.\n     * @param {Function} comparator The comparator used to compare values.\n     * @returns {*} Returns the extremum value.\n     */\n    function baseExtremum(array, iteratee, comparator) {\n      var index = -1,\n          length = array.length;\n\n      while (++index < length) {\n        var value = array[index],\n            current = iteratee(value);\n\n        if (current != null && (computed === undefined\n              ? (current === current && !isSymbol(current))\n              : comparator(current, computed)\n            )) {\n          var computed = current,\n              result = value;\n        }\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.fill` without an iteratee call guard.\n     *\n     * @private\n     * @param {Array} array The array to fill.\n     * @param {*} value The value to fill `array` with.\n     * @param {number} [start=0] The start position.\n     * @param {number} [end=array.length] The end position.\n     * @returns {Array} Returns `array`.\n     */\n    function baseFill(array, value, start, end) {\n      var length = array.length;\n\n      start = toInteger(start);\n      if (start < 0) {\n        start = -start > length ? 0 : (length + start);\n      }\n      end = (end === undefined || end > length) ? length : toInteger(end);\n      if (end < 0) {\n        end += length;\n      }\n      end = start > end ? 0 : toLength(end);\n      while (start < end) {\n        array[start++] = value;\n      }\n      return array;\n    }\n\n    /**\n     * The base implementation of `_.filter` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} predicate The function invoked per iteration.\n     * @returns {Array} Returns the new filtered array.\n     */\n    function baseFilter(collection, predicate) {\n      var result = [];\n      baseEach(collection, function(value, index, collection) {\n        if (predicate(value, index, collection)) {\n          result.push(value);\n        }\n      });\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.flatten` with support for restricting flattening.\n     *\n     * @private\n     * @param {Array} array The array to flatten.\n     * @param {number} depth The maximum recursion depth.\n     * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n     * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n     * @param {Array} [result=[]] The initial result value.\n     * @returns {Array} Returns the new flattened array.\n     */\n    function baseFlatten(array, depth, predicate, isStrict, result) {\n      var index = -1,\n          length = array.length;\n\n      predicate || (predicate = isFlattenable);\n      result || (result = []);\n\n      while (++index < length) {\n        var value = array[index];\n        if (depth > 0 && predicate(value)) {\n          if (depth > 1) {\n            // Recursively flatten arrays (susceptible to call stack limits).\n            baseFlatten(value, depth - 1, predicate, isStrict, result);\n          } else {\n            arrayPush(result, value);\n          }\n        } else if (!isStrict) {\n          result[result.length] = value;\n        }\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `baseForOwn` which iterates over `object`\n     * properties returned by `keysFunc` and invokes `iteratee` for each property.\n     * Iteratee functions may exit iteration early by explicitly returning `false`.\n     *\n     * @private\n     * @param {Object} object The object to iterate over.\n     * @param {Function} iteratee The function invoked per iteration.\n     * @param {Function} keysFunc The function to get the keys of `object`.\n     * @returns {Object} Returns `object`.\n     */\n    var baseFor = createBaseFor();\n\n    /**\n     * This function is like `baseFor` except that it iterates over properties\n     * in the opposite order.\n     *\n     * @private\n     * @param {Object} object The object to iterate over.\n     * @param {Function} iteratee The function invoked per iteration.\n     * @param {Function} keysFunc The function to get the keys of `object`.\n     * @returns {Object} Returns `object`.\n     */\n    var baseForRight = createBaseFor(true);\n\n    /**\n     * The base implementation of `_.forOwn` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Object} object The object to iterate over.\n     * @param {Function} iteratee The function invoked per iteration.\n     * @returns {Object} Returns `object`.\n     */\n    function baseForOwn(object, iteratee) {\n      return object && baseFor(object, iteratee, keys);\n    }\n\n    /**\n     * The base implementation of `_.forOwnRight` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Object} object The object to iterate over.\n     * @param {Function} iteratee The function invoked per iteration.\n     * @returns {Object} Returns `object`.\n     */\n    function baseForOwnRight(object, iteratee) {\n      return object && baseForRight(object, iteratee, keys);\n    }\n\n    /**\n     * The base implementation of `_.functions` which creates an array of\n     * `object` function property names filtered from `props`.\n     *\n     * @private\n     * @param {Object} object The object to inspect.\n     * @param {Array} props The property names to filter.\n     * @returns {Array} Returns the function names.\n     */\n    function baseFunctions(object, props) {\n      return arrayFilter(props, function(key) {\n        return isFunction(object[key]);\n      });\n    }\n\n    /**\n     * The base implementation of `_.get` without support for default values.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @param {Array|string} path The path of the property to get.\n     * @returns {*} Returns the resolved value.\n     */\n    function baseGet(object, path) {\n      path = castPath(path, object);\n\n      var index = 0,\n          length = path.length;\n\n      while (object != null && index < length) {\n        object = object[toKey(path[index++])];\n      }\n      return (index && index == length) ? object : undefined;\n    }\n\n    /**\n     * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n     * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n     * symbols of `object`.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @param {Function} keysFunc The function to get the keys of `object`.\n     * @param {Function} symbolsFunc The function to get the symbols of `object`.\n     * @returns {Array} Returns the array of property names and symbols.\n     */\n    function baseGetAllKeys(object, keysFunc, symbolsFunc) {\n      var result = keysFunc(object);\n      return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n    }\n\n    /**\n     * The base implementation of `getTag` without fallbacks for buggy environments.\n     *\n     * @private\n     * @param {*} value The value to query.\n     * @returns {string} Returns the `toStringTag`.\n     */\n    function baseGetTag(value) {\n      if (value == null) {\n        return value === undefined ? undefinedTag : nullTag;\n      }\n      return (symToStringTag && symToStringTag in Object(value))\n        ? getRawTag(value)\n        : objectToString(value);\n    }\n\n    /**\n     * The base implementation of `_.gt` which doesn't coerce arguments.\n     *\n     * @private\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @returns {boolean} Returns `true` if `value` is greater than `other`,\n     *  else `false`.\n     */\n    function baseGt(value, other) {\n      return value > other;\n    }\n\n    /**\n     * The base implementation of `_.has` without support for deep paths.\n     *\n     * @private\n     * @param {Object} [object] The object to query.\n     * @param {Array|string} key The key to check.\n     * @returns {boolean} Returns `true` if `key` exists, else `false`.\n     */\n    function baseHas(object, key) {\n      return object != null && hasOwnProperty.call(object, key);\n    }\n\n    /**\n     * The base implementation of `_.hasIn` without support for deep paths.\n     *\n     * @private\n     * @param {Object} [object] The object to query.\n     * @param {Array|string} key The key to check.\n     * @returns {boolean} Returns `true` if `key` exists, else `false`.\n     */\n    function baseHasIn(object, key) {\n      return object != null && key in Object(object);\n    }\n\n    /**\n     * The base implementation of `_.inRange` which doesn't coerce arguments.\n     *\n     * @private\n     * @param {number} number The number to check.\n     * @param {number} start The start of the range.\n     * @param {number} end The end of the range.\n     * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n     */\n    function baseInRange(number, start, end) {\n      return number >= nativeMin(start, end) && number < nativeMax(start, end);\n    }\n\n    /**\n     * The base implementation of methods like `_.intersection`, without support\n     * for iteratee shorthands, that accepts an array of arrays to inspect.\n     *\n     * @private\n     * @param {Array} arrays The arrays to inspect.\n     * @param {Function} [iteratee] The iteratee invoked per element.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns the new array of shared values.\n     */\n    function baseIntersection(arrays, iteratee, comparator) {\n      var includes = comparator ? arrayIncludesWith : arrayIncludes,\n          length = arrays[0].length,\n          othLength = arrays.length,\n          othIndex = othLength,\n          caches = Array(othLength),\n          maxLength = Infinity,\n          result = [];\n\n      while (othIndex--) {\n        var array = arrays[othIndex];\n        if (othIndex && iteratee) {\n          array = arrayMap(array, baseUnary(iteratee));\n        }\n        maxLength = nativeMin(array.length, maxLength);\n        caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n          ? new SetCache(othIndex && array)\n          : undefined;\n      }\n      array = arrays[0];\n\n      var index = -1,\n          seen = caches[0];\n\n      outer:\n      while (++index < length && result.length < maxLength) {\n        var value = array[index],\n            computed = iteratee ? iteratee(value) : value;\n\n        value = (comparator || value !== 0) ? value : 0;\n        if (!(seen\n              ? cacheHas(seen, computed)\n              : includes(result, computed, comparator)\n            )) {\n          othIndex = othLength;\n          while (--othIndex) {\n            var cache = caches[othIndex];\n            if (!(cache\n                  ? cacheHas(cache, computed)\n                  : includes(arrays[othIndex], computed, comparator))\n                ) {\n              continue outer;\n            }\n          }\n          if (seen) {\n            seen.push(computed);\n          }\n          result.push(value);\n        }\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.invert` and `_.invertBy` which inverts\n     * `object` with values transformed by `iteratee` and set by `setter`.\n     *\n     * @private\n     * @param {Object} object The object to iterate over.\n     * @param {Function} setter The function to set `accumulator` values.\n     * @param {Function} iteratee The iteratee to transform values.\n     * @param {Object} accumulator The initial inverted object.\n     * @returns {Function} Returns `accumulator`.\n     */\n    function baseInverter(object, setter, iteratee, accumulator) {\n      baseForOwn(object, function(value, key, object) {\n        setter(accumulator, iteratee(value), key, object);\n      });\n      return accumulator;\n    }\n\n    /**\n     * The base implementation of `_.invoke` without support for individual\n     * method arguments.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @param {Array|string} path The path of the method to invoke.\n     * @param {Array} args The arguments to invoke the method with.\n     * @returns {*} Returns the result of the invoked method.\n     */\n    function baseInvoke(object, path, args) {\n      path = castPath(path, object);\n      object = parent(object, path);\n      var func = object == null ? object : object[toKey(last(path))];\n      return func == null ? undefined : apply(func, object, args);\n    }\n\n    /**\n     * The base implementation of `_.isArguments`.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n     */\n    function baseIsArguments(value) {\n      return isObjectLike(value) && baseGetTag(value) == argsTag;\n    }\n\n    /**\n     * The base implementation of `_.isArrayBuffer` without Node.js optimizations.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n     */\n    function baseIsArrayBuffer(value) {\n      return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;\n    }\n\n    /**\n     * The base implementation of `_.isDate` without Node.js optimizations.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n     */\n    function baseIsDate(value) {\n      return isObjectLike(value) && baseGetTag(value) == dateTag;\n    }\n\n    /**\n     * The base implementation of `_.isEqual` which supports partial comparisons\n     * and tracks traversed objects.\n     *\n     * @private\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @param {boolean} bitmask The bitmask flags.\n     *  1 - Unordered comparison\n     *  2 - Partial comparison\n     * @param {Function} [customizer] The function to customize comparisons.\n     * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n     */\n    function baseIsEqual(value, other, bitmask, customizer, stack) {\n      if (value === other) {\n        return true;\n      }\n      if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n        return value !== value && other !== other;\n      }\n      return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n    }\n\n    /**\n     * A specialized version of `baseIsEqual` for arrays and objects which performs\n     * deep comparisons and tracks traversed objects enabling objects with circular\n     * references to be compared.\n     *\n     * @private\n     * @param {Object} object The object to compare.\n     * @param {Object} other The other object to compare.\n     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n     * @param {Function} customizer The function to customize comparisons.\n     * @param {Function} equalFunc The function to determine equivalents of values.\n     * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n     * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n     */\n    function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n      var objIsArr = isArray(object),\n          othIsArr = isArray(other),\n          objTag = objIsArr ? arrayTag : getTag(object),\n          othTag = othIsArr ? arrayTag : getTag(other);\n\n      objTag = objTag == argsTag ? objectTag : objTag;\n      othTag = othTag == argsTag ? objectTag : othTag;\n\n      var objIsObj = objTag == objectTag,\n          othIsObj = othTag == objectTag,\n          isSameTag = objTag == othTag;\n\n      if (isSameTag && isBuffer(object)) {\n        if (!isBuffer(other)) {\n          return false;\n        }\n        objIsArr = true;\n        objIsObj = false;\n      }\n      if (isSameTag && !objIsObj) {\n        stack || (stack = new Stack);\n        return (objIsArr || isTypedArray(object))\n          ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n          : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n      }\n      if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n        var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n            othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n        if (objIsWrapped || othIsWrapped) {\n          var objUnwrapped = objIsWrapped ? object.value() : object,\n              othUnwrapped = othIsWrapped ? other.value() : other;\n\n          stack || (stack = new Stack);\n          return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n        }\n      }\n      if (!isSameTag) {\n        return false;\n      }\n      stack || (stack = new Stack);\n      return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n    }\n\n    /**\n     * The base implementation of `_.isMap` without Node.js optimizations.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n     */\n    function baseIsMap(value) {\n      return isObjectLike(value) && getTag(value) == mapTag;\n    }\n\n    /**\n     * The base implementation of `_.isMatch` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Object} object The object to inspect.\n     * @param {Object} source The object of property values to match.\n     * @param {Array} matchData The property names, values, and compare flags to match.\n     * @param {Function} [customizer] The function to customize comparisons.\n     * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n     */\n    function baseIsMatch(object, source, matchData, customizer) {\n      var index = matchData.length,\n          length = index,\n          noCustomizer = !customizer;\n\n      if (object == null) {\n        return !length;\n      }\n      object = Object(object);\n      while (index--) {\n        var data = matchData[index];\n        if ((noCustomizer && data[2])\n              ? data[1] !== object[data[0]]\n              : !(data[0] in object)\n            ) {\n          return false;\n        }\n      }\n      while (++index < length) {\n        data = matchData[index];\n        var key = data[0],\n            objValue = object[key],\n            srcValue = data[1];\n\n        if (noCustomizer && data[2]) {\n          if (objValue === undefined && !(key in object)) {\n            return false;\n          }\n        } else {\n          var stack = new Stack;\n          if (customizer) {\n            var result = customizer(objValue, srcValue, key, object, source, stack);\n          }\n          if (!(result === undefined\n                ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n                : result\n              )) {\n            return false;\n          }\n        }\n      }\n      return true;\n    }\n\n    /**\n     * The base implementation of `_.isNative` without bad shim checks.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a native function,\n     *  else `false`.\n     */\n    function baseIsNative(value) {\n      if (!isObject(value) || isMasked(value)) {\n        return false;\n      }\n      var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n      return pattern.test(toSource(value));\n    }\n\n    /**\n     * The base implementation of `_.isRegExp` without Node.js optimizations.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n     */\n    function baseIsRegExp(value) {\n      return isObjectLike(value) && baseGetTag(value) == regexpTag;\n    }\n\n    /**\n     * The base implementation of `_.isSet` without Node.js optimizations.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n     */\n    function baseIsSet(value) {\n      return isObjectLike(value) && getTag(value) == setTag;\n    }\n\n    /**\n     * The base implementation of `_.isTypedArray` without Node.js optimizations.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n     */\n    function baseIsTypedArray(value) {\n      return isObjectLike(value) &&\n        isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n    }\n\n    /**\n     * The base implementation of `_.iteratee`.\n     *\n     * @private\n     * @param {*} [value=_.identity] The value to convert to an iteratee.\n     * @returns {Function} Returns the iteratee.\n     */\n    function baseIteratee(value) {\n      // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n      // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n      if (typeof value == 'function') {\n        return value;\n      }\n      if (value == null) {\n        return identity;\n      }\n      if (typeof value == 'object') {\n        return isArray(value)\n          ? baseMatchesProperty(value[0], value[1])\n          : baseMatches(value);\n      }\n      return property(value);\n    }\n\n    /**\n     * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of property names.\n     */\n    function baseKeys(object) {\n      if (!isPrototype(object)) {\n        return nativeKeys(object);\n      }\n      var result = [];\n      for (var key in Object(object)) {\n        if (hasOwnProperty.call(object, key) && key != 'constructor') {\n          result.push(key);\n        }\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of property names.\n     */\n    function baseKeysIn(object) {\n      if (!isObject(object)) {\n        return nativeKeysIn(object);\n      }\n      var isProto = isPrototype(object),\n          result = [];\n\n      for (var key in object) {\n        if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n          result.push(key);\n        }\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.lt` which doesn't coerce arguments.\n     *\n     * @private\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @returns {boolean} Returns `true` if `value` is less than `other`,\n     *  else `false`.\n     */\n    function baseLt(value, other) {\n      return value < other;\n    }\n\n    /**\n     * The base implementation of `_.map` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} iteratee The function invoked per iteration.\n     * @returns {Array} Returns the new mapped array.\n     */\n    function baseMap(collection, iteratee) {\n      var index = -1,\n          result = isArrayLike(collection) ? Array(collection.length) : [];\n\n      baseEach(collection, function(value, key, collection) {\n        result[++index] = iteratee(value, key, collection);\n      });\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.matches` which doesn't clone `source`.\n     *\n     * @private\n     * @param {Object} source The object of property values to match.\n     * @returns {Function} Returns the new spec function.\n     */\n    function baseMatches(source) {\n      var matchData = getMatchData(source);\n      if (matchData.length == 1 && matchData[0][2]) {\n        return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n      }\n      return function(object) {\n        return object === source || baseIsMatch(object, source, matchData);\n      };\n    }\n\n    /**\n     * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n     *\n     * @private\n     * @param {string} path The path of the property to get.\n     * @param {*} srcValue The value to match.\n     * @returns {Function} Returns the new spec function.\n     */\n    function baseMatchesProperty(path, srcValue) {\n      if (isKey(path) && isStrictComparable(srcValue)) {\n        return matchesStrictComparable(toKey(path), srcValue);\n      }\n      return function(object) {\n        var objValue = get(object, path);\n        return (objValue === undefined && objValue === srcValue)\n          ? hasIn(object, path)\n          : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n      };\n    }\n\n    /**\n     * The base implementation of `_.merge` without support for multiple sources.\n     *\n     * @private\n     * @param {Object} object The destination object.\n     * @param {Object} source The source object.\n     * @param {number} srcIndex The index of `source`.\n     * @param {Function} [customizer] The function to customize merged values.\n     * @param {Object} [stack] Tracks traversed source values and their merged\n     *  counterparts.\n     */\n    function baseMerge(object, source, srcIndex, customizer, stack) {\n      if (object === source) {\n        return;\n      }\n      baseFor(source, function(srcValue, key) {\n        if (isObject(srcValue)) {\n          stack || (stack = new Stack);\n          baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n        }\n        else {\n          var newValue = customizer\n            ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n            : undefined;\n\n          if (newValue === undefined) {\n            newValue = srcValue;\n          }\n          assignMergeValue(object, key, newValue);\n        }\n      }, keysIn);\n    }\n\n    /**\n     * A specialized version of `baseMerge` for arrays and objects which performs\n     * deep merges and tracks traversed objects enabling objects with circular\n     * references to be merged.\n     *\n     * @private\n     * @param {Object} object The destination object.\n     * @param {Object} source The source object.\n     * @param {string} key The key of the value to merge.\n     * @param {number} srcIndex The index of `source`.\n     * @param {Function} mergeFunc The function to merge values.\n     * @param {Function} [customizer] The function to customize assigned values.\n     * @param {Object} [stack] Tracks traversed source values and their merged\n     *  counterparts.\n     */\n    function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n      var objValue = safeGet(object, key),\n          srcValue = safeGet(source, key),\n          stacked = stack.get(srcValue);\n\n      if (stacked) {\n        assignMergeValue(object, key, stacked);\n        return;\n      }\n      var newValue = customizer\n        ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n        : undefined;\n\n      var isCommon = newValue === undefined;\n\n      if (isCommon) {\n        var isArr = isArray(srcValue),\n            isBuff = !isArr && isBuffer(srcValue),\n            isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n        newValue = srcValue;\n        if (isArr || isBuff || isTyped) {\n          if (isArray(objValue)) {\n            newValue = objValue;\n          }\n          else if (isArrayLikeObject(objValue)) {\n            newValue = copyArray(objValue);\n          }\n          else if (isBuff) {\n            isCommon = false;\n            newValue = cloneBuffer(srcValue, true);\n          }\n          else if (isTyped) {\n            isCommon = false;\n            newValue = cloneTypedArray(srcValue, true);\n          }\n          else {\n            newValue = [];\n          }\n        }\n        else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n          newValue = objValue;\n          if (isArguments(objValue)) {\n            newValue = toPlainObject(objValue);\n          }\n          else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {\n            newValue = initCloneObject(srcValue);\n          }\n        }\n        else {\n          isCommon = false;\n        }\n      }\n      if (isCommon) {\n        // Recursively merge objects and arrays (susceptible to call stack limits).\n        stack.set(srcValue, newValue);\n        mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n        stack['delete'](srcValue);\n      }\n      assignMergeValue(object, key, newValue);\n    }\n\n    /**\n     * The base implementation of `_.nth` which doesn't coerce arguments.\n     *\n     * @private\n     * @param {Array} array The array to query.\n     * @param {number} n The index of the element to return.\n     * @returns {*} Returns the nth element of `array`.\n     */\n    function baseNth(array, n) {\n      var length = array.length;\n      if (!length) {\n        return;\n      }\n      n += n < 0 ? length : 0;\n      return isIndex(n, length) ? array[n] : undefined;\n    }\n\n    /**\n     * The base implementation of `_.orderBy` without param guards.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n     * @param {string[]} orders The sort orders of `iteratees`.\n     * @returns {Array} Returns the new sorted array.\n     */\n    function baseOrderBy(collection, iteratees, orders) {\n      var index = -1;\n      iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee()));\n\n      var result = baseMap(collection, function(value, key, collection) {\n        var criteria = arrayMap(iteratees, function(iteratee) {\n          return iteratee(value);\n        });\n        return { 'criteria': criteria, 'index': ++index, 'value': value };\n      });\n\n      return baseSortBy(result, function(object, other) {\n        return compareMultiple(object, other, orders);\n      });\n    }\n\n    /**\n     * The base implementation of `_.pick` without support for individual\n     * property identifiers.\n     *\n     * @private\n     * @param {Object} object The source object.\n     * @param {string[]} paths The property paths to pick.\n     * @returns {Object} Returns the new object.\n     */\n    function basePick(object, paths) {\n      return basePickBy(object, paths, function(value, path) {\n        return hasIn(object, path);\n      });\n    }\n\n    /**\n     * The base implementation of  `_.pickBy` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Object} object The source object.\n     * @param {string[]} paths The property paths to pick.\n     * @param {Function} predicate The function invoked per property.\n     * @returns {Object} Returns the new object.\n     */\n    function basePickBy(object, paths, predicate) {\n      var index = -1,\n          length = paths.length,\n          result = {};\n\n      while (++index < length) {\n        var path = paths[index],\n            value = baseGet(object, path);\n\n        if (predicate(value, path)) {\n          baseSet(result, castPath(path, object), value);\n        }\n      }\n      return result;\n    }\n\n    /**\n     * A specialized version of `baseProperty` which supports deep paths.\n     *\n     * @private\n     * @param {Array|string} path The path of the property to get.\n     * @returns {Function} Returns the new accessor function.\n     */\n    function basePropertyDeep(path) {\n      return function(object) {\n        return baseGet(object, path);\n      };\n    }\n\n    /**\n     * The base implementation of `_.pullAllBy` without support for iteratee\n     * shorthands.\n     *\n     * @private\n     * @param {Array} array The array to modify.\n     * @param {Array} values The values to remove.\n     * @param {Function} [iteratee] The iteratee invoked per element.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns `array`.\n     */\n    function basePullAll(array, values, iteratee, comparator) {\n      var indexOf = comparator ? baseIndexOfWith : baseIndexOf,\n          index = -1,\n          length = values.length,\n          seen = array;\n\n      if (array === values) {\n        values = copyArray(values);\n      }\n      if (iteratee) {\n        seen = arrayMap(array, baseUnary(iteratee));\n      }\n      while (++index < length) {\n        var fromIndex = 0,\n            value = values[index],\n            computed = iteratee ? iteratee(value) : value;\n\n        while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {\n          if (seen !== array) {\n            splice.call(seen, fromIndex, 1);\n          }\n          splice.call(array, fromIndex, 1);\n        }\n      }\n      return array;\n    }\n\n    /**\n     * The base implementation of `_.pullAt` without support for individual\n     * indexes or capturing the removed elements.\n     *\n     * @private\n     * @param {Array} array The array to modify.\n     * @param {number[]} indexes The indexes of elements to remove.\n     * @returns {Array} Returns `array`.\n     */\n    function basePullAt(array, indexes) {\n      var length = array ? indexes.length : 0,\n          lastIndex = length - 1;\n\n      while (length--) {\n        var index = indexes[length];\n        if (length == lastIndex || index !== previous) {\n          var previous = index;\n          if (isIndex(index)) {\n            splice.call(array, index, 1);\n          } else {\n            baseUnset(array, index);\n          }\n        }\n      }\n      return array;\n    }\n\n    /**\n     * The base implementation of `_.random` without support for returning\n     * floating-point numbers.\n     *\n     * @private\n     * @param {number} lower The lower bound.\n     * @param {number} upper The upper bound.\n     * @returns {number} Returns the random number.\n     */\n    function baseRandom(lower, upper) {\n      return lower + nativeFloor(nativeRandom() * (upper - lower + 1));\n    }\n\n    /**\n     * The base implementation of `_.range` and `_.rangeRight` which doesn't\n     * coerce arguments.\n     *\n     * @private\n     * @param {number} start The start of the range.\n     * @param {number} end The end of the range.\n     * @param {number} step The value to increment or decrement by.\n     * @param {boolean} [fromRight] Specify iterating from right to left.\n     * @returns {Array} Returns the range of numbers.\n     */\n    function baseRange(start, end, step, fromRight) {\n      var index = -1,\n          length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n          result = Array(length);\n\n      while (length--) {\n        result[fromRight ? length : ++index] = start;\n        start += step;\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.repeat` which doesn't coerce arguments.\n     *\n     * @private\n     * @param {string} string The string to repeat.\n     * @param {number} n The number of times to repeat the string.\n     * @returns {string} Returns the repeated string.\n     */\n    function baseRepeat(string, n) {\n      var result = '';\n      if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n        return result;\n      }\n      // Leverage the exponentiation by squaring algorithm for a faster repeat.\n      // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n      do {\n        if (n % 2) {\n          result += string;\n        }\n        n = nativeFloor(n / 2);\n        if (n) {\n          string += string;\n        }\n      } while (n);\n\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n     *\n     * @private\n     * @param {Function} func The function to apply a rest parameter to.\n     * @param {number} [start=func.length-1] The start position of the rest parameter.\n     * @returns {Function} Returns the new function.\n     */\n    function baseRest(func, start) {\n      return setToString(overRest(func, start, identity), func + '');\n    }\n\n    /**\n     * The base implementation of `_.sample`.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to sample.\n     * @returns {*} Returns the random element.\n     */\n    function baseSample(collection) {\n      return arraySample(values(collection));\n    }\n\n    /**\n     * The base implementation of `_.sampleSize` without param guards.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to sample.\n     * @param {number} n The number of elements to sample.\n     * @returns {Array} Returns the random elements.\n     */\n    function baseSampleSize(collection, n) {\n      var array = values(collection);\n      return shuffleSelf(array, baseClamp(n, 0, array.length));\n    }\n\n    /**\n     * The base implementation of `_.set`.\n     *\n     * @private\n     * @param {Object} object The object to modify.\n     * @param {Array|string} path The path of the property to set.\n     * @param {*} value The value to set.\n     * @param {Function} [customizer] The function to customize path creation.\n     * @returns {Object} Returns `object`.\n     */\n    function baseSet(object, path, value, customizer) {\n      if (!isObject(object)) {\n        return object;\n      }\n      path = castPath(path, object);\n\n      var index = -1,\n          length = path.length,\n          lastIndex = length - 1,\n          nested = object;\n\n      while (nested != null && ++index < length) {\n        var key = toKey(path[index]),\n            newValue = value;\n\n        if (index != lastIndex) {\n          var objValue = nested[key];\n          newValue = customizer ? customizer(objValue, key, nested) : undefined;\n          if (newValue === undefined) {\n            newValue = isObject(objValue)\n              ? objValue\n              : (isIndex(path[index + 1]) ? [] : {});\n          }\n        }\n        assignValue(nested, key, newValue);\n        nested = nested[key];\n      }\n      return object;\n    }\n\n    /**\n     * The base implementation of `setData` without support for hot loop shorting.\n     *\n     * @private\n     * @param {Function} func The function to associate metadata with.\n     * @param {*} data The metadata.\n     * @returns {Function} Returns `func`.\n     */\n    var baseSetData = !metaMap ? identity : function(func, data) {\n      metaMap.set(func, data);\n      return func;\n    };\n\n    /**\n     * The base implementation of `setToString` without support for hot loop shorting.\n     *\n     * @private\n     * @param {Function} func The function to modify.\n     * @param {Function} string The `toString` result.\n     * @returns {Function} Returns `func`.\n     */\n    var baseSetToString = !defineProperty ? identity : function(func, string) {\n      return defineProperty(func, 'toString', {\n        'configurable': true,\n        'enumerable': false,\n        'value': constant(string),\n        'writable': true\n      });\n    };\n\n    /**\n     * The base implementation of `_.shuffle`.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to shuffle.\n     * @returns {Array} Returns the new shuffled array.\n     */\n    function baseShuffle(collection) {\n      return shuffleSelf(values(collection));\n    }\n\n    /**\n     * The base implementation of `_.slice` without an iteratee call guard.\n     *\n     * @private\n     * @param {Array} array The array to slice.\n     * @param {number} [start=0] The start position.\n     * @param {number} [end=array.length] The end position.\n     * @returns {Array} Returns the slice of `array`.\n     */\n    function baseSlice(array, start, end) {\n      var index = -1,\n          length = array.length;\n\n      if (start < 0) {\n        start = -start > length ? 0 : (length + start);\n      }\n      end = end > length ? length : end;\n      if (end < 0) {\n        end += length;\n      }\n      length = start > end ? 0 : ((end - start) >>> 0);\n      start >>>= 0;\n\n      var result = Array(length);\n      while (++index < length) {\n        result[index] = array[index + start];\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.some` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} predicate The function invoked per iteration.\n     * @returns {boolean} Returns `true` if any element passes the predicate check,\n     *  else `false`.\n     */\n    function baseSome(collection, predicate) {\n      var result;\n\n      baseEach(collection, function(value, index, collection) {\n        result = predicate(value, index, collection);\n        return !result;\n      });\n      return !!result;\n    }\n\n    /**\n     * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which\n     * performs a binary search of `array` to determine the index at which `value`\n     * should be inserted into `array` in order to maintain its sort order.\n     *\n     * @private\n     * @param {Array} array The sorted array to inspect.\n     * @param {*} value The value to evaluate.\n     * @param {boolean} [retHighest] Specify returning the highest qualified index.\n     * @returns {number} Returns the index at which `value` should be inserted\n     *  into `array`.\n     */\n    function baseSortedIndex(array, value, retHighest) {\n      var low = 0,\n          high = array == null ? low : array.length;\n\n      if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {\n        while (low < high) {\n          var mid = (low + high) >>> 1,\n              computed = array[mid];\n\n          if (computed !== null && !isSymbol(computed) &&\n              (retHighest ? (computed <= value) : (computed < value))) {\n            low = mid + 1;\n          } else {\n            high = mid;\n          }\n        }\n        return high;\n      }\n      return baseSortedIndexBy(array, value, identity, retHighest);\n    }\n\n    /**\n     * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`\n     * which invokes `iteratee` for `value` and each element of `array` to compute\n     * their sort ranking. The iteratee is invoked with one argument; (value).\n     *\n     * @private\n     * @param {Array} array The sorted array to inspect.\n     * @param {*} value The value to evaluate.\n     * @param {Function} iteratee The iteratee invoked per element.\n     * @param {boolean} [retHighest] Specify returning the highest qualified index.\n     * @returns {number} Returns the index at which `value` should be inserted\n     *  into `array`.\n     */\n    function baseSortedIndexBy(array, value, iteratee, retHighest) {\n      value = iteratee(value);\n\n      var low = 0,\n          high = array == null ? 0 : array.length,\n          valIsNaN = value !== value,\n          valIsNull = value === null,\n          valIsSymbol = isSymbol(value),\n          valIsUndefined = value === undefined;\n\n      while (low < high) {\n        var mid = nativeFloor((low + high) / 2),\n            computed = iteratee(array[mid]),\n            othIsDefined = computed !== undefined,\n            othIsNull = computed === null,\n            othIsReflexive = computed === computed,\n            othIsSymbol = isSymbol(computed);\n\n        if (valIsNaN) {\n          var setLow = retHighest || othIsReflexive;\n        } else if (valIsUndefined) {\n          setLow = othIsReflexive && (retHighest || othIsDefined);\n        } else if (valIsNull) {\n          setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);\n        } else if (valIsSymbol) {\n          setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);\n        } else if (othIsNull || othIsSymbol) {\n          setLow = false;\n        } else {\n          setLow = retHighest ? (computed <= value) : (computed < value);\n        }\n        if (setLow) {\n          low = mid + 1;\n        } else {\n          high = mid;\n        }\n      }\n      return nativeMin(high, MAX_ARRAY_INDEX);\n    }\n\n    /**\n     * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without\n     * support for iteratee shorthands.\n     *\n     * @private\n     * @param {Array} array The array to inspect.\n     * @param {Function} [iteratee] The iteratee invoked per element.\n     * @returns {Array} Returns the new duplicate free array.\n     */\n    function baseSortedUniq(array, iteratee) {\n      var index = -1,\n          length = array.length,\n          resIndex = 0,\n          result = [];\n\n      while (++index < length) {\n        var value = array[index],\n            computed = iteratee ? iteratee(value) : value;\n\n        if (!index || !eq(computed, seen)) {\n          var seen = computed;\n          result[resIndex++] = value === 0 ? 0 : value;\n        }\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.toNumber` which doesn't ensure correct\n     * conversions of binary, hexadecimal, or octal string values.\n     *\n     * @private\n     * @param {*} value The value to process.\n     * @returns {number} Returns the number.\n     */\n    function baseToNumber(value) {\n      if (typeof value == 'number') {\n        return value;\n      }\n      if (isSymbol(value)) {\n        return NAN;\n      }\n      return +value;\n    }\n\n    /**\n     * The base implementation of `_.toString` which doesn't convert nullish\n     * values to empty strings.\n     *\n     * @private\n     * @param {*} value The value to process.\n     * @returns {string} Returns the string.\n     */\n    function baseToString(value) {\n      // Exit early for strings to avoid a performance hit in some environments.\n      if (typeof value == 'string') {\n        return value;\n      }\n      if (isArray(value)) {\n        // Recursively convert values (susceptible to call stack limits).\n        return arrayMap(value, baseToString) + '';\n      }\n      if (isSymbol(value)) {\n        return symbolToString ? symbolToString.call(value) : '';\n      }\n      var result = (value + '');\n      return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n    }\n\n    /**\n     * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Array} array The array to inspect.\n     * @param {Function} [iteratee] The iteratee invoked per element.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns the new duplicate free array.\n     */\n    function baseUniq(array, iteratee, comparator) {\n      var index = -1,\n          includes = arrayIncludes,\n          length = array.length,\n          isCommon = true,\n          result = [],\n          seen = result;\n\n      if (comparator) {\n        isCommon = false;\n        includes = arrayIncludesWith;\n      }\n      else if (length >= LARGE_ARRAY_SIZE) {\n        var set = iteratee ? null : createSet(array);\n        if (set) {\n          return setToArray(set);\n        }\n        isCommon = false;\n        includes = cacheHas;\n        seen = new SetCache;\n      }\n      else {\n        seen = iteratee ? [] : result;\n      }\n      outer:\n      while (++index < length) {\n        var value = array[index],\n            computed = iteratee ? iteratee(value) : value;\n\n        value = (comparator || value !== 0) ? value : 0;\n        if (isCommon && computed === computed) {\n          var seenIndex = seen.length;\n          while (seenIndex--) {\n            if (seen[seenIndex] === computed) {\n              continue outer;\n            }\n          }\n          if (iteratee) {\n            seen.push(computed);\n          }\n          result.push(value);\n        }\n        else if (!includes(seen, computed, comparator)) {\n          if (seen !== result) {\n            seen.push(computed);\n          }\n          result.push(value);\n        }\n      }\n      return result;\n    }\n\n    /**\n     * The base implementation of `_.unset`.\n     *\n     * @private\n     * @param {Object} object The object to modify.\n     * @param {Array|string} path The property path to unset.\n     * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n     */\n    function baseUnset(object, path) {\n      path = castPath(path, object);\n      object = parent(object, path);\n      return object == null || delete object[toKey(last(path))];\n    }\n\n    /**\n     * The base implementation of `_.update`.\n     *\n     * @private\n     * @param {Object} object The object to modify.\n     * @param {Array|string} path The path of the property to update.\n     * @param {Function} updater The function to produce the updated value.\n     * @param {Function} [customizer] The function to customize path creation.\n     * @returns {Object} Returns `object`.\n     */\n    function baseUpdate(object, path, updater, customizer) {\n      return baseSet(object, path, updater(baseGet(object, path)), customizer);\n    }\n\n    /**\n     * The base implementation of methods like `_.dropWhile` and `_.takeWhile`\n     * without support for iteratee shorthands.\n     *\n     * @private\n     * @param {Array} array The array to query.\n     * @param {Function} predicate The function invoked per iteration.\n     * @param {boolean} [isDrop] Specify dropping elements instead of taking them.\n     * @param {boolean} [fromRight] Specify iterating from right to left.\n     * @returns {Array} Returns the slice of `array`.\n     */\n    function baseWhile(array, predicate, isDrop, fromRight) {\n      var length = array.length,\n          index = fromRight ? length : -1;\n\n      while ((fromRight ? index-- : ++index < length) &&\n        predicate(array[index], index, array)) {}\n\n      return isDrop\n        ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))\n        : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));\n    }\n\n    /**\n     * The base implementation of `wrapperValue` which returns the result of\n     * performing a sequence of actions on the unwrapped `value`, where each\n     * successive action is supplied the return value of the previous.\n     *\n     * @private\n     * @param {*} value The unwrapped value.\n     * @param {Array} actions Actions to perform to resolve the unwrapped value.\n     * @returns {*} Returns the resolved value.\n     */\n    function baseWrapperValue(value, actions) {\n      var result = value;\n      if (result instanceof LazyWrapper) {\n        result = result.value();\n      }\n      return arrayReduce(actions, function(result, action) {\n        return action.func.apply(action.thisArg, arrayPush([result], action.args));\n      }, result);\n    }\n\n    /**\n     * The base implementation of methods like `_.xor`, without support for\n     * iteratee shorthands, that accepts an array of arrays to inspect.\n     *\n     * @private\n     * @param {Array} arrays The arrays to inspect.\n     * @param {Function} [iteratee] The iteratee invoked per element.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns the new array of values.\n     */\n    function baseXor(arrays, iteratee, comparator) {\n      var length = arrays.length;\n      if (length < 2) {\n        return length ? baseUniq(arrays[0]) : [];\n      }\n      var index = -1,\n          result = Array(length);\n\n      while (++index < length) {\n        var array = arrays[index],\n            othIndex = -1;\n\n        while (++othIndex < length) {\n          if (othIndex != index) {\n            result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);\n          }\n        }\n      }\n      return baseUniq(baseFlatten(result, 1), iteratee, comparator);\n    }\n\n    /**\n     * This base implementation of `_.zipObject` which assigns values using `assignFunc`.\n     *\n     * @private\n     * @param {Array} props The property identifiers.\n     * @param {Array} values The property values.\n     * @param {Function} assignFunc The function to assign values.\n     * @returns {Object} Returns the new object.\n     */\n    function baseZipObject(props, values, assignFunc) {\n      var index = -1,\n          length = props.length,\n          valsLength = values.length,\n          result = {};\n\n      while (++index < length) {\n        var value = index < valsLength ? values[index] : undefined;\n        assignFunc(result, props[index], value);\n      }\n      return result;\n    }\n\n    /**\n     * Casts `value` to an empty array if it's not an array like object.\n     *\n     * @private\n     * @param {*} value The value to inspect.\n     * @returns {Array|Object} Returns the cast array-like object.\n     */\n    function castArrayLikeObject(value) {\n      return isArrayLikeObject(value) ? value : [];\n    }\n\n    /**\n     * Casts `value` to `identity` if it's not a function.\n     *\n     * @private\n     * @param {*} value The value to inspect.\n     * @returns {Function} Returns cast function.\n     */\n    function castFunction(value) {\n      return typeof value == 'function' ? value : identity;\n    }\n\n    /**\n     * Casts `value` to a path array if it's not one.\n     *\n     * @private\n     * @param {*} value The value to inspect.\n     * @param {Object} [object] The object to query keys on.\n     * @returns {Array} Returns the cast property path array.\n     */\n    function castPath(value, object) {\n      if (isArray(value)) {\n        return value;\n      }\n      return isKey(value, object) ? [value] : stringToPath(toString(value));\n    }\n\n    /**\n     * A `baseRest` alias which can be replaced with `identity` by module\n     * replacement plugins.\n     *\n     * @private\n     * @type {Function}\n     * @param {Function} func The function to apply a rest parameter to.\n     * @returns {Function} Returns the new function.\n     */\n    var castRest = baseRest;\n\n    /**\n     * Casts `array` to a slice if it's needed.\n     *\n     * @private\n     * @param {Array} array The array to inspect.\n     * @param {number} start The start position.\n     * @param {number} [end=array.length] The end position.\n     * @returns {Array} Returns the cast slice.\n     */\n    function castSlice(array, start, end) {\n      var length = array.length;\n      end = end === undefined ? length : end;\n      return (!start && end >= length) ? array : baseSlice(array, start, end);\n    }\n\n    /**\n     * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).\n     *\n     * @private\n     * @param {number|Object} id The timer id or timeout object of the timer to clear.\n     */\n    var clearTimeout = ctxClearTimeout || function(id) {\n      return root.clearTimeout(id);\n    };\n\n    /**\n     * Creates a clone of  `buffer`.\n     *\n     * @private\n     * @param {Buffer} buffer The buffer to clone.\n     * @param {boolean} [isDeep] Specify a deep clone.\n     * @returns {Buffer} Returns the cloned buffer.\n     */\n    function cloneBuffer(buffer, isDeep) {\n      if (isDeep) {\n        return buffer.slice();\n      }\n      var length = buffer.length,\n          result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n      buffer.copy(result);\n      return result;\n    }\n\n    /**\n     * Creates a clone of `arrayBuffer`.\n     *\n     * @private\n     * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n     * @returns {ArrayBuffer} Returns the cloned array buffer.\n     */\n    function cloneArrayBuffer(arrayBuffer) {\n      var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n      new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n      return result;\n    }\n\n    /**\n     * Creates a clone of `dataView`.\n     *\n     * @private\n     * @param {Object} dataView The data view to clone.\n     * @param {boolean} [isDeep] Specify a deep clone.\n     * @returns {Object} Returns the cloned data view.\n     */\n    function cloneDataView(dataView, isDeep) {\n      var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n      return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n    }\n\n    /**\n     * Creates a clone of `regexp`.\n     *\n     * @private\n     * @param {Object} regexp The regexp to clone.\n     * @returns {Object} Returns the cloned regexp.\n     */\n    function cloneRegExp(regexp) {\n      var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n      result.lastIndex = regexp.lastIndex;\n      return result;\n    }\n\n    /**\n     * Creates a clone of the `symbol` object.\n     *\n     * @private\n     * @param {Object} symbol The symbol object to clone.\n     * @returns {Object} Returns the cloned symbol object.\n     */\n    function cloneSymbol(symbol) {\n      return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n    }\n\n    /**\n     * Creates a clone of `typedArray`.\n     *\n     * @private\n     * @param {Object} typedArray The typed array to clone.\n     * @param {boolean} [isDeep] Specify a deep clone.\n     * @returns {Object} Returns the cloned typed array.\n     */\n    function cloneTypedArray(typedArray, isDeep) {\n      var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n      return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n    }\n\n    /**\n     * Compares values to sort them in ascending order.\n     *\n     * @private\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @returns {number} Returns the sort order indicator for `value`.\n     */\n    function compareAscending(value, other) {\n      if (value !== other) {\n        var valIsDefined = value !== undefined,\n            valIsNull = value === null,\n            valIsReflexive = value === value,\n            valIsSymbol = isSymbol(value);\n\n        var othIsDefined = other !== undefined,\n            othIsNull = other === null,\n            othIsReflexive = other === other,\n            othIsSymbol = isSymbol(other);\n\n        if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n            (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n            (valIsNull && othIsDefined && othIsReflexive) ||\n            (!valIsDefined && othIsReflexive) ||\n            !valIsReflexive) {\n          return 1;\n        }\n        if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n            (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n            (othIsNull && valIsDefined && valIsReflexive) ||\n            (!othIsDefined && valIsReflexive) ||\n            !othIsReflexive) {\n          return -1;\n        }\n      }\n      return 0;\n    }\n\n    /**\n     * Used by `_.orderBy` to compare multiple properties of a value to another\n     * and stable sort them.\n     *\n     * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n     * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n     * of corresponding values.\n     *\n     * @private\n     * @param {Object} object The object to compare.\n     * @param {Object} other The other object to compare.\n     * @param {boolean[]|string[]} orders The order to sort by for each property.\n     * @returns {number} Returns the sort order indicator for `object`.\n     */\n    function compareMultiple(object, other, orders) {\n      var index = -1,\n          objCriteria = object.criteria,\n          othCriteria = other.criteria,\n          length = objCriteria.length,\n          ordersLength = orders.length;\n\n      while (++index < length) {\n        var result = compareAscending(objCriteria[index], othCriteria[index]);\n        if (result) {\n          if (index >= ordersLength) {\n            return result;\n          }\n          var order = orders[index];\n          return result * (order == 'desc' ? -1 : 1);\n        }\n      }\n      // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n      // that causes it, under certain circumstances, to provide the same value for\n      // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n      // for more details.\n      //\n      // This also ensures a stable sort in V8 and other engines.\n      // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n      return object.index - other.index;\n    }\n\n    /**\n     * Creates an array that is the composition of partially applied arguments,\n     * placeholders, and provided arguments into a single array of arguments.\n     *\n     * @private\n     * @param {Array} args The provided arguments.\n     * @param {Array} partials The arguments to prepend to those provided.\n     * @param {Array} holders The `partials` placeholder indexes.\n     * @params {boolean} [isCurried] Specify composing for a curried function.\n     * @returns {Array} Returns the new array of composed arguments.\n     */\n    function composeArgs(args, partials, holders, isCurried) {\n      var argsIndex = -1,\n          argsLength = args.length,\n          holdersLength = holders.length,\n          leftIndex = -1,\n          leftLength = partials.length,\n          rangeLength = nativeMax(argsLength - holdersLength, 0),\n          result = Array(leftLength + rangeLength),\n          isUncurried = !isCurried;\n\n      while (++leftIndex < leftLength) {\n        result[leftIndex] = partials[leftIndex];\n      }\n      while (++argsIndex < holdersLength) {\n        if (isUncurried || argsIndex < argsLength) {\n          result[holders[argsIndex]] = args[argsIndex];\n        }\n      }\n      while (rangeLength--) {\n        result[leftIndex++] = args[argsIndex++];\n      }\n      return result;\n    }\n\n    /**\n     * This function is like `composeArgs` except that the arguments composition\n     * is tailored for `_.partialRight`.\n     *\n     * @private\n     * @param {Array} args The provided arguments.\n     * @param {Array} partials The arguments to append to those provided.\n     * @param {Array} holders The `partials` placeholder indexes.\n     * @params {boolean} [isCurried] Specify composing for a curried function.\n     * @returns {Array} Returns the new array of composed arguments.\n     */\n    function composeArgsRight(args, partials, holders, isCurried) {\n      var argsIndex = -1,\n          argsLength = args.length,\n          holdersIndex = -1,\n          holdersLength = holders.length,\n          rightIndex = -1,\n          rightLength = partials.length,\n          rangeLength = nativeMax(argsLength - holdersLength, 0),\n          result = Array(rangeLength + rightLength),\n          isUncurried = !isCurried;\n\n      while (++argsIndex < rangeLength) {\n        result[argsIndex] = args[argsIndex];\n      }\n      var offset = argsIndex;\n      while (++rightIndex < rightLength) {\n        result[offset + rightIndex] = partials[rightIndex];\n      }\n      while (++holdersIndex < holdersLength) {\n        if (isUncurried || argsIndex < argsLength) {\n          result[offset + holders[holdersIndex]] = args[argsIndex++];\n        }\n      }\n      return result;\n    }\n\n    /**\n     * Copies the values of `source` to `array`.\n     *\n     * @private\n     * @param {Array} source The array to copy values from.\n     * @param {Array} [array=[]] The array to copy values to.\n     * @returns {Array} Returns `array`.\n     */\n    function copyArray(source, array) {\n      var index = -1,\n          length = source.length;\n\n      array || (array = Array(length));\n      while (++index < length) {\n        array[index] = source[index];\n      }\n      return array;\n    }\n\n    /**\n     * Copies properties of `source` to `object`.\n     *\n     * @private\n     * @param {Object} source The object to copy properties from.\n     * @param {Array} props The property identifiers to copy.\n     * @param {Object} [object={}] The object to copy properties to.\n     * @param {Function} [customizer] The function to customize copied values.\n     * @returns {Object} Returns `object`.\n     */\n    function copyObject(source, props, object, customizer) {\n      var isNew = !object;\n      object || (object = {});\n\n      var index = -1,\n          length = props.length;\n\n      while (++index < length) {\n        var key = props[index];\n\n        var newValue = customizer\n          ? customizer(object[key], source[key], key, object, source)\n          : undefined;\n\n        if (newValue === undefined) {\n          newValue = source[key];\n        }\n        if (isNew) {\n          baseAssignValue(object, key, newValue);\n        } else {\n          assignValue(object, key, newValue);\n        }\n      }\n      return object;\n    }\n\n    /**\n     * Copies own symbols of `source` to `object`.\n     *\n     * @private\n     * @param {Object} source The object to copy symbols from.\n     * @param {Object} [object={}] The object to copy symbols to.\n     * @returns {Object} Returns `object`.\n     */\n    function copySymbols(source, object) {\n      return copyObject(source, getSymbols(source), object);\n    }\n\n    /**\n     * Copies own and inherited symbols of `source` to `object`.\n     *\n     * @private\n     * @param {Object} source The object to copy symbols from.\n     * @param {Object} [object={}] The object to copy symbols to.\n     * @returns {Object} Returns `object`.\n     */\n    function copySymbolsIn(source, object) {\n      return copyObject(source, getSymbolsIn(source), object);\n    }\n\n    /**\n     * Creates a function like `_.groupBy`.\n     *\n     * @private\n     * @param {Function} setter The function to set accumulator values.\n     * @param {Function} [initializer] The accumulator object initializer.\n     * @returns {Function} Returns the new aggregator function.\n     */\n    function createAggregator(setter, initializer) {\n      return function(collection, iteratee) {\n        var func = isArray(collection) ? arrayAggregator : baseAggregator,\n            accumulator = initializer ? initializer() : {};\n\n        return func(collection, setter, getIteratee(iteratee, 2), accumulator);\n      };\n    }\n\n    /**\n     * Creates a function like `_.assign`.\n     *\n     * @private\n     * @param {Function} assigner The function to assign values.\n     * @returns {Function} Returns the new assigner function.\n     */\n    function createAssigner(assigner) {\n      return baseRest(function(object, sources) {\n        var index = -1,\n            length = sources.length,\n            customizer = length > 1 ? sources[length - 1] : undefined,\n            guard = length > 2 ? sources[2] : undefined;\n\n        customizer = (assigner.length > 3 && typeof customizer == 'function')\n          ? (length--, customizer)\n          : undefined;\n\n        if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n          customizer = length < 3 ? undefined : customizer;\n          length = 1;\n        }\n        object = Object(object);\n        while (++index < length) {\n          var source = sources[index];\n          if (source) {\n            assigner(object, source, index, customizer);\n          }\n        }\n        return object;\n      });\n    }\n\n    /**\n     * Creates a `baseEach` or `baseEachRight` function.\n     *\n     * @private\n     * @param {Function} eachFunc The function to iterate over a collection.\n     * @param {boolean} [fromRight] Specify iterating from right to left.\n     * @returns {Function} Returns the new base function.\n     */\n    function createBaseEach(eachFunc, fromRight) {\n      return function(collection, iteratee) {\n        if (collection == null) {\n          return collection;\n        }\n        if (!isArrayLike(collection)) {\n          return eachFunc(collection, iteratee);\n        }\n        var length = collection.length,\n            index = fromRight ? length : -1,\n            iterable = Object(collection);\n\n        while ((fromRight ? index-- : ++index < length)) {\n          if (iteratee(iterable[index], index, iterable) === false) {\n            break;\n          }\n        }\n        return collection;\n      };\n    }\n\n    /**\n     * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n     *\n     * @private\n     * @param {boolean} [fromRight] Specify iterating from right to left.\n     * @returns {Function} Returns the new base function.\n     */\n    function createBaseFor(fromRight) {\n      return function(object, iteratee, keysFunc) {\n        var index = -1,\n            iterable = Object(object),\n            props = keysFunc(object),\n            length = props.length;\n\n        while (length--) {\n          var key = props[fromRight ? length : ++index];\n          if (iteratee(iterable[key], key, iterable) === false) {\n            break;\n          }\n        }\n        return object;\n      };\n    }\n\n    /**\n     * Creates a function that wraps `func` to invoke it with the optional `this`\n     * binding of `thisArg`.\n     *\n     * @private\n     * @param {Function} func The function to wrap.\n     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n     * @param {*} [thisArg] The `this` binding of `func`.\n     * @returns {Function} Returns the new wrapped function.\n     */\n    function createBind(func, bitmask, thisArg) {\n      var isBind = bitmask & WRAP_BIND_FLAG,\n          Ctor = createCtor(func);\n\n      function wrapper() {\n        var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n        return fn.apply(isBind ? thisArg : this, arguments);\n      }\n      return wrapper;\n    }\n\n    /**\n     * Creates a function like `_.lowerFirst`.\n     *\n     * @private\n     * @param {string} methodName The name of the `String` case method to use.\n     * @returns {Function} Returns the new case function.\n     */\n    function createCaseFirst(methodName) {\n      return function(string) {\n        string = toString(string);\n\n        var strSymbols = hasUnicode(string)\n          ? stringToArray(string)\n          : undefined;\n\n        var chr = strSymbols\n          ? strSymbols[0]\n          : string.charAt(0);\n\n        var trailing = strSymbols\n          ? castSlice(strSymbols, 1).join('')\n          : string.slice(1);\n\n        return chr[methodName]() + trailing;\n      };\n    }\n\n    /**\n     * Creates a function like `_.camelCase`.\n     *\n     * @private\n     * @param {Function} callback The function to combine each word.\n     * @returns {Function} Returns the new compounder function.\n     */\n    function createCompounder(callback) {\n      return function(string) {\n        return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n      };\n    }\n\n    /**\n     * Creates a function that produces an instance of `Ctor` regardless of\n     * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n     *\n     * @private\n     * @param {Function} Ctor The constructor to wrap.\n     * @returns {Function} Returns the new wrapped function.\n     */\n    function createCtor(Ctor) {\n      return function() {\n        // Use a `switch` statement to work with class constructors. See\n        // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n        // for more details.\n        var args = arguments;\n        switch (args.length) {\n          case 0: return new Ctor;\n          case 1: return new Ctor(args[0]);\n          case 2: return new Ctor(args[0], args[1]);\n          case 3: return new Ctor(args[0], args[1], args[2]);\n          case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n          case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n          case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n          case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n        }\n        var thisBinding = baseCreate(Ctor.prototype),\n            result = Ctor.apply(thisBinding, args);\n\n        // Mimic the constructor's `return` behavior.\n        // See https://es5.github.io/#x13.2.2 for more details.\n        return isObject(result) ? result : thisBinding;\n      };\n    }\n\n    /**\n     * Creates a function that wraps `func` to enable currying.\n     *\n     * @private\n     * @param {Function} func The function to wrap.\n     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n     * @param {number} arity The arity of `func`.\n     * @returns {Function} Returns the new wrapped function.\n     */\n    function createCurry(func, bitmask, arity) {\n      var Ctor = createCtor(func);\n\n      function wrapper() {\n        var length = arguments.length,\n            args = Array(length),\n            index = length,\n            placeholder = getHolder(wrapper);\n\n        while (index--) {\n          args[index] = arguments[index];\n        }\n        var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n          ? []\n          : replaceHolders(args, placeholder);\n\n        length -= holders.length;\n        if (length < arity) {\n          return createRecurry(\n            func, bitmask, createHybrid, wrapper.placeholder, undefined,\n            args, holders, undefined, undefined, arity - length);\n        }\n        var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n        return apply(fn, this, args);\n      }\n      return wrapper;\n    }\n\n    /**\n     * Creates a `_.find` or `_.findLast` function.\n     *\n     * @private\n     * @param {Function} findIndexFunc The function to find the collection index.\n     * @returns {Function} Returns the new find function.\n     */\n    function createFind(findIndexFunc) {\n      return function(collection, predicate, fromIndex) {\n        var iterable = Object(collection);\n        if (!isArrayLike(collection)) {\n          var iteratee = getIteratee(predicate, 3);\n          collection = keys(collection);\n          predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n        }\n        var index = findIndexFunc(collection, predicate, fromIndex);\n        return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n      };\n    }\n\n    /**\n     * Creates a `_.flow` or `_.flowRight` function.\n     *\n     * @private\n     * @param {boolean} [fromRight] Specify iterating from right to left.\n     * @returns {Function} Returns the new flow function.\n     */\n    function createFlow(fromRight) {\n      return flatRest(function(funcs) {\n        var length = funcs.length,\n            index = length,\n            prereq = LodashWrapper.prototype.thru;\n\n        if (fromRight) {\n          funcs.reverse();\n        }\n        while (index--) {\n          var func = funcs[index];\n          if (typeof func != 'function') {\n            throw new TypeError(FUNC_ERROR_TEXT);\n          }\n          if (prereq && !wrapper && getFuncName(func) == 'wrapper') {\n            var wrapper = new LodashWrapper([], true);\n          }\n        }\n        index = wrapper ? index : length;\n        while (++index < length) {\n          func = funcs[index];\n\n          var funcName = getFuncName(func),\n              data = funcName == 'wrapper' ? getData(func) : undefined;\n\n          if (data && isLaziable(data[0]) &&\n                data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&\n                !data[4].length && data[9] == 1\n              ) {\n            wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);\n          } else {\n            wrapper = (func.length == 1 && isLaziable(func))\n              ? wrapper[funcName]()\n              : wrapper.thru(func);\n          }\n        }\n        return function() {\n          var args = arguments,\n              value = args[0];\n\n          if (wrapper && args.length == 1 && isArray(value)) {\n            return wrapper.plant(value).value();\n          }\n          var index = 0,\n              result = length ? funcs[index].apply(this, args) : value;\n\n          while (++index < length) {\n            result = funcs[index].call(this, result);\n          }\n          return result;\n        };\n      });\n    }\n\n    /**\n     * Creates a function that wraps `func` to invoke it with optional `this`\n     * binding of `thisArg`, partial application, and currying.\n     *\n     * @private\n     * @param {Function|string} func The function or method name to wrap.\n     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n     * @param {*} [thisArg] The `this` binding of `func`.\n     * @param {Array} [partials] The arguments to prepend to those provided to\n     *  the new function.\n     * @param {Array} [holders] The `partials` placeholder indexes.\n     * @param {Array} [partialsRight] The arguments to append to those provided\n     *  to the new function.\n     * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n     * @param {Array} [argPos] The argument positions of the new function.\n     * @param {number} [ary] The arity cap of `func`.\n     * @param {number} [arity] The arity of `func`.\n     * @returns {Function} Returns the new wrapped function.\n     */\n    function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n      var isAry = bitmask & WRAP_ARY_FLAG,\n          isBind = bitmask & WRAP_BIND_FLAG,\n          isBindKey = bitmask & WRAP_BIND_KEY_FLAG,\n          isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),\n          isFlip = bitmask & WRAP_FLIP_FLAG,\n          Ctor = isBindKey ? undefined : createCtor(func);\n\n      function wrapper() {\n        var length = arguments.length,\n            args = Array(length),\n            index = length;\n\n        while (index--) {\n          args[index] = arguments[index];\n        }\n        if (isCurried) {\n          var placeholder = getHolder(wrapper),\n              holdersCount = countHolders(args, placeholder);\n        }\n        if (partials) {\n          args = composeArgs(args, partials, holders, isCurried);\n        }\n        if (partialsRight) {\n          args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n        }\n        length -= holdersCount;\n        if (isCurried && length < arity) {\n          var newHolders = replaceHolders(args, placeholder);\n          return createRecurry(\n            func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n            args, newHolders, argPos, ary, arity - length\n          );\n        }\n        var thisBinding = isBind ? thisArg : this,\n            fn = isBindKey ? thisBinding[func] : func;\n\n        length = args.length;\n        if (argPos) {\n          args = reorder(args, argPos);\n        } else if (isFlip && length > 1) {\n          args.reverse();\n        }\n        if (isAry && ary < length) {\n          args.length = ary;\n        }\n        if (this && this !== root && this instanceof wrapper) {\n          fn = Ctor || createCtor(fn);\n        }\n        return fn.apply(thisBinding, args);\n      }\n      return wrapper;\n    }\n\n    /**\n     * Creates a function like `_.invertBy`.\n     *\n     * @private\n     * @param {Function} setter The function to set accumulator values.\n     * @param {Function} toIteratee The function to resolve iteratees.\n     * @returns {Function} Returns the new inverter function.\n     */\n    function createInverter(setter, toIteratee) {\n      return function(object, iteratee) {\n        return baseInverter(object, setter, toIteratee(iteratee), {});\n      };\n    }\n\n    /**\n     * Creates a function that performs a mathematical operation on two values.\n     *\n     * @private\n     * @param {Function} operator The function to perform the operation.\n     * @param {number} [defaultValue] The value used for `undefined` arguments.\n     * @returns {Function} Returns the new mathematical operation function.\n     */\n    function createMathOperation(operator, defaultValue) {\n      return function(value, other) {\n        var result;\n        if (value === undefined && other === undefined) {\n          return defaultValue;\n        }\n        if (value !== undefined) {\n          result = value;\n        }\n        if (other !== undefined) {\n          if (result === undefined) {\n            return other;\n          }\n          if (typeof value == 'string' || typeof other == 'string') {\n            value = baseToString(value);\n            other = baseToString(other);\n          } else {\n            value = baseToNumber(value);\n            other = baseToNumber(other);\n          }\n          result = operator(value, other);\n        }\n        return result;\n      };\n    }\n\n    /**\n     * Creates a function like `_.over`.\n     *\n     * @private\n     * @param {Function} arrayFunc The function to iterate over iteratees.\n     * @returns {Function} Returns the new over function.\n     */\n    function createOver(arrayFunc) {\n      return flatRest(function(iteratees) {\n        iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n        return baseRest(function(args) {\n          var thisArg = this;\n          return arrayFunc(iteratees, function(iteratee) {\n            return apply(iteratee, thisArg, args);\n          });\n        });\n      });\n    }\n\n    /**\n     * Creates the padding for `string` based on `length`. The `chars` string\n     * is truncated if the number of characters exceeds `length`.\n     *\n     * @private\n     * @param {number} length The padding length.\n     * @param {string} [chars=' '] The string used as padding.\n     * @returns {string} Returns the padding for `string`.\n     */\n    function createPadding(length, chars) {\n      chars = chars === undefined ? ' ' : baseToString(chars);\n\n      var charsLength = chars.length;\n      if (charsLength < 2) {\n        return charsLength ? baseRepeat(chars, length) : chars;\n      }\n      var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));\n      return hasUnicode(chars)\n        ? castSlice(stringToArray(result), 0, length).join('')\n        : result.slice(0, length);\n    }\n\n    /**\n     * Creates a function that wraps `func` to invoke it with the `this` binding\n     * of `thisArg` and `partials` prepended to the arguments it receives.\n     *\n     * @private\n     * @param {Function} func The function to wrap.\n     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n     * @param {*} thisArg The `this` binding of `func`.\n     * @param {Array} partials The arguments to prepend to those provided to\n     *  the new function.\n     * @returns {Function} Returns the new wrapped function.\n     */\n    function createPartial(func, bitmask, thisArg, partials) {\n      var isBind = bitmask & WRAP_BIND_FLAG,\n          Ctor = createCtor(func);\n\n      function wrapper() {\n        var argsIndex = -1,\n            argsLength = arguments.length,\n            leftIndex = -1,\n            leftLength = partials.length,\n            args = Array(leftLength + argsLength),\n            fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n        while (++leftIndex < leftLength) {\n          args[leftIndex] = partials[leftIndex];\n        }\n        while (argsLength--) {\n          args[leftIndex++] = arguments[++argsIndex];\n        }\n        return apply(fn, isBind ? thisArg : this, args);\n      }\n      return wrapper;\n    }\n\n    /**\n     * Creates a `_.range` or `_.rangeRight` function.\n     *\n     * @private\n     * @param {boolean} [fromRight] Specify iterating from right to left.\n     * @returns {Function} Returns the new range function.\n     */\n    function createRange(fromRight) {\n      return function(start, end, step) {\n        if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n          end = step = undefined;\n        }\n        // Ensure the sign of `-0` is preserved.\n        start = toFinite(start);\n        if (end === undefined) {\n          end = start;\n          start = 0;\n        } else {\n          end = toFinite(end);\n        }\n        step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n        return baseRange(start, end, step, fromRight);\n      };\n    }\n\n    /**\n     * Creates a function that performs a relational operation on two values.\n     *\n     * @private\n     * @param {Function} operator The function to perform the operation.\n     * @returns {Function} Returns the new relational operation function.\n     */\n    function createRelationalOperation(operator) {\n      return function(value, other) {\n        if (!(typeof value == 'string' && typeof other == 'string')) {\n          value = toNumber(value);\n          other = toNumber(other);\n        }\n        return operator(value, other);\n      };\n    }\n\n    /**\n     * Creates a function that wraps `func` to continue currying.\n     *\n     * @private\n     * @param {Function} func The function to wrap.\n     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n     * @param {Function} wrapFunc The function to create the `func` wrapper.\n     * @param {*} placeholder The placeholder value.\n     * @param {*} [thisArg] The `this` binding of `func`.\n     * @param {Array} [partials] The arguments to prepend to those provided to\n     *  the new function.\n     * @param {Array} [holders] The `partials` placeholder indexes.\n     * @param {Array} [argPos] The argument positions of the new function.\n     * @param {number} [ary] The arity cap of `func`.\n     * @param {number} [arity] The arity of `func`.\n     * @returns {Function} Returns the new wrapped function.\n     */\n    function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n      var isCurry = bitmask & WRAP_CURRY_FLAG,\n          newHolders = isCurry ? holders : undefined,\n          newHoldersRight = isCurry ? undefined : holders,\n          newPartials = isCurry ? partials : undefined,\n          newPartialsRight = isCurry ? undefined : partials;\n\n      bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);\n      bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);\n\n      if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {\n        bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);\n      }\n      var newData = [\n        func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,\n        newHoldersRight, argPos, ary, arity\n      ];\n\n      var result = wrapFunc.apply(undefined, newData);\n      if (isLaziable(func)) {\n        setData(result, newData);\n      }\n      result.placeholder = placeholder;\n      return setWrapToString(result, func, bitmask);\n    }\n\n    /**\n     * Creates a function like `_.round`.\n     *\n     * @private\n     * @param {string} methodName The name of the `Math` method to use when rounding.\n     * @returns {Function} Returns the new round function.\n     */\n    function createRound(methodName) {\n      var func = Math[methodName];\n      return function(number, precision) {\n        number = toNumber(number);\n        precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);\n        if (precision) {\n          // Shift with exponential notation to avoid floating-point issues.\n          // See [MDN](https://mdn.io/round#Examples) for more details.\n          var pair = (toString(number) + 'e').split('e'),\n              value = func(pair[0] + 'e' + (+pair[1] + precision));\n\n          pair = (toString(value) + 'e').split('e');\n          return +(pair[0] + 'e' + (+pair[1] - precision));\n        }\n        return func(number);\n      };\n    }\n\n    /**\n     * Creates a set object of `values`.\n     *\n     * @private\n     * @param {Array} values The values to add to the set.\n     * @returns {Object} Returns the new set.\n     */\n    var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n      return new Set(values);\n    };\n\n    /**\n     * Creates a `_.toPairs` or `_.toPairsIn` function.\n     *\n     * @private\n     * @param {Function} keysFunc The function to get the keys of a given object.\n     * @returns {Function} Returns the new pairs function.\n     */\n    function createToPairs(keysFunc) {\n      return function(object) {\n        var tag = getTag(object);\n        if (tag == mapTag) {\n          return mapToArray(object);\n        }\n        if (tag == setTag) {\n          return setToPairs(object);\n        }\n        return baseToPairs(object, keysFunc(object));\n      };\n    }\n\n    /**\n     * Creates a function that either curries or invokes `func` with optional\n     * `this` binding and partially applied arguments.\n     *\n     * @private\n     * @param {Function|string} func The function or method name to wrap.\n     * @param {number} bitmask The bitmask flags.\n     *    1 - `_.bind`\n     *    2 - `_.bindKey`\n     *    4 - `_.curry` or `_.curryRight` of a bound function\n     *    8 - `_.curry`\n     *   16 - `_.curryRight`\n     *   32 - `_.partial`\n     *   64 - `_.partialRight`\n     *  128 - `_.rearg`\n     *  256 - `_.ary`\n     *  512 - `_.flip`\n     * @param {*} [thisArg] The `this` binding of `func`.\n     * @param {Array} [partials] The arguments to be partially applied.\n     * @param {Array} [holders] The `partials` placeholder indexes.\n     * @param {Array} [argPos] The argument positions of the new function.\n     * @param {number} [ary] The arity cap of `func`.\n     * @param {number} [arity] The arity of `func`.\n     * @returns {Function} Returns the new wrapped function.\n     */\n    function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n      var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;\n      if (!isBindKey && typeof func != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      var length = partials ? partials.length : 0;\n      if (!length) {\n        bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);\n        partials = holders = undefined;\n      }\n      ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n      arity = arity === undefined ? arity : toInteger(arity);\n      length -= holders ? holders.length : 0;\n\n      if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {\n        var partialsRight = partials,\n            holdersRight = holders;\n\n        partials = holders = undefined;\n      }\n      var data = isBindKey ? undefined : getData(func);\n\n      var newData = [\n        func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n        argPos, ary, arity\n      ];\n\n      if (data) {\n        mergeData(newData, data);\n      }\n      func = newData[0];\n      bitmask = newData[1];\n      thisArg = newData[2];\n      partials = newData[3];\n      holders = newData[4];\n      arity = newData[9] = newData[9] === undefined\n        ? (isBindKey ? 0 : func.length)\n        : nativeMax(newData[9] - length, 0);\n\n      if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {\n        bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);\n      }\n      if (!bitmask || bitmask == WRAP_BIND_FLAG) {\n        var result = createBind(func, bitmask, thisArg);\n      } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {\n        result = createCurry(func, bitmask, arity);\n      } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {\n        result = createPartial(func, bitmask, thisArg, partials);\n      } else {\n        result = createHybrid.apply(undefined, newData);\n      }\n      var setter = data ? baseSetData : setData;\n      return setWrapToString(setter(result, newData), func, bitmask);\n    }\n\n    /**\n     * Used by `_.defaults` to customize its `_.assignIn` use to assign properties\n     * of source objects to the destination object for all destination properties\n     * that resolve to `undefined`.\n     *\n     * @private\n     * @param {*} objValue The destination value.\n     * @param {*} srcValue The source value.\n     * @param {string} key The key of the property to assign.\n     * @param {Object} object The parent object of `objValue`.\n     * @returns {*} Returns the value to assign.\n     */\n    function customDefaultsAssignIn(objValue, srcValue, key, object) {\n      if (objValue === undefined ||\n          (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n        return srcValue;\n      }\n      return objValue;\n    }\n\n    /**\n     * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source\n     * objects into destination objects that are passed thru.\n     *\n     * @private\n     * @param {*} objValue The destination value.\n     * @param {*} srcValue The source value.\n     * @param {string} key The key of the property to merge.\n     * @param {Object} object The parent object of `objValue`.\n     * @param {Object} source The parent object of `srcValue`.\n     * @param {Object} [stack] Tracks traversed source values and their merged\n     *  counterparts.\n     * @returns {*} Returns the value to assign.\n     */\n    function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {\n      if (isObject(objValue) && isObject(srcValue)) {\n        // Recursively merge objects and arrays (susceptible to call stack limits).\n        stack.set(srcValue, objValue);\n        baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);\n        stack['delete'](srcValue);\n      }\n      return objValue;\n    }\n\n    /**\n     * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n     * objects.\n     *\n     * @private\n     * @param {*} value The value to inspect.\n     * @param {string} key The key of the property to inspect.\n     * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n     */\n    function customOmitClone(value) {\n      return isPlainObject(value) ? undefined : value;\n    }\n\n    /**\n     * A specialized version of `baseIsEqualDeep` for arrays with support for\n     * partial deep comparisons.\n     *\n     * @private\n     * @param {Array} array The array to compare.\n     * @param {Array} other The other array to compare.\n     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n     * @param {Function} customizer The function to customize comparisons.\n     * @param {Function} equalFunc The function to determine equivalents of values.\n     * @param {Object} stack Tracks traversed `array` and `other` objects.\n     * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n     */\n    function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n      var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n          arrLength = array.length,\n          othLength = other.length;\n\n      if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n        return false;\n      }\n      // Assume cyclic values are equal.\n      var stacked = stack.get(array);\n      if (stacked && stack.get(other)) {\n        return stacked == other;\n      }\n      var index = -1,\n          result = true,\n          seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n      stack.set(array, other);\n      stack.set(other, array);\n\n      // Ignore non-index properties.\n      while (++index < arrLength) {\n        var arrValue = array[index],\n            othValue = other[index];\n\n        if (customizer) {\n          var compared = isPartial\n            ? customizer(othValue, arrValue, index, other, array, stack)\n            : customizer(arrValue, othValue, index, array, other, stack);\n        }\n        if (compared !== undefined) {\n          if (compared) {\n            continue;\n          }\n          result = false;\n          break;\n        }\n        // Recursively compare arrays (susceptible to call stack limits).\n        if (seen) {\n          if (!arraySome(other, function(othValue, othIndex) {\n                if (!cacheHas(seen, othIndex) &&\n                    (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n                  return seen.push(othIndex);\n                }\n              })) {\n            result = false;\n            break;\n          }\n        } else if (!(\n              arrValue === othValue ||\n                equalFunc(arrValue, othValue, bitmask, customizer, stack)\n            )) {\n          result = false;\n          break;\n        }\n      }\n      stack['delete'](array);\n      stack['delete'](other);\n      return result;\n    }\n\n    /**\n     * A specialized version of `baseIsEqualDeep` for comparing objects of\n     * the same `toStringTag`.\n     *\n     * **Note:** This function only supports comparing values with tags of\n     * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n     *\n     * @private\n     * @param {Object} object The object to compare.\n     * @param {Object} other The other object to compare.\n     * @param {string} tag The `toStringTag` of the objects to compare.\n     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n     * @param {Function} customizer The function to customize comparisons.\n     * @param {Function} equalFunc The function to determine equivalents of values.\n     * @param {Object} stack Tracks traversed `object` and `other` objects.\n     * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n     */\n    function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n      switch (tag) {\n        case dataViewTag:\n          if ((object.byteLength != other.byteLength) ||\n              (object.byteOffset != other.byteOffset)) {\n            return false;\n          }\n          object = object.buffer;\n          other = other.buffer;\n\n        case arrayBufferTag:\n          if ((object.byteLength != other.byteLength) ||\n              !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n            return false;\n          }\n          return true;\n\n        case boolTag:\n        case dateTag:\n        case numberTag:\n          // Coerce booleans to `1` or `0` and dates to milliseconds.\n          // Invalid dates are coerced to `NaN`.\n          return eq(+object, +other);\n\n        case errorTag:\n          return object.name == other.name && object.message == other.message;\n\n        case regexpTag:\n        case stringTag:\n          // Coerce regexes to strings and treat strings, primitives and objects,\n          // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n          // for more details.\n          return object == (other + '');\n\n        case mapTag:\n          var convert = mapToArray;\n\n        case setTag:\n          var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n          convert || (convert = setToArray);\n\n          if (object.size != other.size && !isPartial) {\n            return false;\n          }\n          // Assume cyclic values are equal.\n          var stacked = stack.get(object);\n          if (stacked) {\n            return stacked == other;\n          }\n          bitmask |= COMPARE_UNORDERED_FLAG;\n\n          // Recursively compare objects (susceptible to call stack limits).\n          stack.set(object, other);\n          var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n          stack['delete'](object);\n          return result;\n\n        case symbolTag:\n          if (symbolValueOf) {\n            return symbolValueOf.call(object) == symbolValueOf.call(other);\n          }\n      }\n      return false;\n    }\n\n    /**\n     * A specialized version of `baseIsEqualDeep` for objects with support for\n     * partial deep comparisons.\n     *\n     * @private\n     * @param {Object} object The object to compare.\n     * @param {Object} other The other object to compare.\n     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n     * @param {Function} customizer The function to customize comparisons.\n     * @param {Function} equalFunc The function to determine equivalents of values.\n     * @param {Object} stack Tracks traversed `object` and `other` objects.\n     * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n     */\n    function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n      var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n          objProps = getAllKeys(object),\n          objLength = objProps.length,\n          othProps = getAllKeys(other),\n          othLength = othProps.length;\n\n      if (objLength != othLength && !isPartial) {\n        return false;\n      }\n      var index = objLength;\n      while (index--) {\n        var key = objProps[index];\n        if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n          return false;\n        }\n      }\n      // Assume cyclic values are equal.\n      var stacked = stack.get(object);\n      if (stacked && stack.get(other)) {\n        return stacked == other;\n      }\n      var result = true;\n      stack.set(object, other);\n      stack.set(other, object);\n\n      var skipCtor = isPartial;\n      while (++index < objLength) {\n        key = objProps[index];\n        var objValue = object[key],\n            othValue = other[key];\n\n        if (customizer) {\n          var compared = isPartial\n            ? customizer(othValue, objValue, key, other, object, stack)\n            : customizer(objValue, othValue, key, object, other, stack);\n        }\n        // Recursively compare objects (susceptible to call stack limits).\n        if (!(compared === undefined\n              ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n              : compared\n            )) {\n          result = false;\n          break;\n        }\n        skipCtor || (skipCtor = key == 'constructor');\n      }\n      if (result && !skipCtor) {\n        var objCtor = object.constructor,\n            othCtor = other.constructor;\n\n        // Non `Object` object instances with different constructors are not equal.\n        if (objCtor != othCtor &&\n            ('constructor' in object && 'constructor' in other) &&\n            !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n              typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n          result = false;\n        }\n      }\n      stack['delete'](object);\n      stack['delete'](other);\n      return result;\n    }\n\n    /**\n     * A specialized version of `baseRest` which flattens the rest array.\n     *\n     * @private\n     * @param {Function} func The function to apply a rest parameter to.\n     * @returns {Function} Returns the new function.\n     */\n    function flatRest(func) {\n      return setToString(overRest(func, undefined, flatten), func + '');\n    }\n\n    /**\n     * Creates an array of own enumerable property names and symbols of `object`.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of property names and symbols.\n     */\n    function getAllKeys(object) {\n      return baseGetAllKeys(object, keys, getSymbols);\n    }\n\n    /**\n     * Creates an array of own and inherited enumerable property names and\n     * symbols of `object`.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of property names and symbols.\n     */\n    function getAllKeysIn(object) {\n      return baseGetAllKeys(object, keysIn, getSymbolsIn);\n    }\n\n    /**\n     * Gets metadata for `func`.\n     *\n     * @private\n     * @param {Function} func The function to query.\n     * @returns {*} Returns the metadata for `func`.\n     */\n    var getData = !metaMap ? noop : function(func) {\n      return metaMap.get(func);\n    };\n\n    /**\n     * Gets the name of `func`.\n     *\n     * @private\n     * @param {Function} func The function to query.\n     * @returns {string} Returns the function name.\n     */\n    function getFuncName(func) {\n      var result = (func.name + ''),\n          array = realNames[result],\n          length = hasOwnProperty.call(realNames, result) ? array.length : 0;\n\n      while (length--) {\n        var data = array[length],\n            otherFunc = data.func;\n        if (otherFunc == null || otherFunc == func) {\n          return data.name;\n        }\n      }\n      return result;\n    }\n\n    /**\n     * Gets the argument placeholder value for `func`.\n     *\n     * @private\n     * @param {Function} func The function to inspect.\n     * @returns {*} Returns the placeholder value.\n     */\n    function getHolder(func) {\n      var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;\n      return object.placeholder;\n    }\n\n    /**\n     * Gets the appropriate \"iteratee\" function. If `_.iteratee` is customized,\n     * this function returns the custom method, otherwise it returns `baseIteratee`.\n     * If arguments are provided, the chosen function is invoked with them and\n     * its result is returned.\n     *\n     * @private\n     * @param {*} [value] The value to convert to an iteratee.\n     * @param {number} [arity] The arity of the created iteratee.\n     * @returns {Function} Returns the chosen function or its result.\n     */\n    function getIteratee() {\n      var result = lodash.iteratee || iteratee;\n      result = result === iteratee ? baseIteratee : result;\n      return arguments.length ? result(arguments[0], arguments[1]) : result;\n    }\n\n    /**\n     * Gets the data for `map`.\n     *\n     * @private\n     * @param {Object} map The map to query.\n     * @param {string} key The reference key.\n     * @returns {*} Returns the map data.\n     */\n    function getMapData(map, key) {\n      var data = map.__data__;\n      return isKeyable(key)\n        ? data[typeof key == 'string' ? 'string' : 'hash']\n        : data.map;\n    }\n\n    /**\n     * Gets the property names, values, and compare flags of `object`.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the match data of `object`.\n     */\n    function getMatchData(object) {\n      var result = keys(object),\n          length = result.length;\n\n      while (length--) {\n        var key = result[length],\n            value = object[key];\n\n        result[length] = [key, value, isStrictComparable(value)];\n      }\n      return result;\n    }\n\n    /**\n     * Gets the native function at `key` of `object`.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @param {string} key The key of the method to get.\n     * @returns {*} Returns the function if it's native, else `undefined`.\n     */\n    function getNative(object, key) {\n      var value = getValue(object, key);\n      return baseIsNative(value) ? value : undefined;\n    }\n\n    /**\n     * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n     *\n     * @private\n     * @param {*} value The value to query.\n     * @returns {string} Returns the raw `toStringTag`.\n     */\n    function getRawTag(value) {\n      var isOwn = hasOwnProperty.call(value, symToStringTag),\n          tag = value[symToStringTag];\n\n      try {\n        value[symToStringTag] = undefined;\n        var unmasked = true;\n      } catch (e) {}\n\n      var result = nativeObjectToString.call(value);\n      if (unmasked) {\n        if (isOwn) {\n          value[symToStringTag] = tag;\n        } else {\n          delete value[symToStringTag];\n        }\n      }\n      return result;\n    }\n\n    /**\n     * Creates an array of the own enumerable symbols of `object`.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of symbols.\n     */\n    var getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n      if (object == null) {\n        return [];\n      }\n      object = Object(object);\n      return arrayFilter(nativeGetSymbols(object), function(symbol) {\n        return propertyIsEnumerable.call(object, symbol);\n      });\n    };\n\n    /**\n     * Creates an array of the own and inherited enumerable symbols of `object`.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of symbols.\n     */\n    var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n      var result = [];\n      while (object) {\n        arrayPush(result, getSymbols(object));\n        object = getPrototype(object);\n      }\n      return result;\n    };\n\n    /**\n     * Gets the `toStringTag` of `value`.\n     *\n     * @private\n     * @param {*} value The value to query.\n     * @returns {string} Returns the `toStringTag`.\n     */\n    var getTag = baseGetTag;\n\n    // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\n    if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n        (Map && getTag(new Map) != mapTag) ||\n        (Promise && getTag(Promise.resolve()) != promiseTag) ||\n        (Set && getTag(new Set) != setTag) ||\n        (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n      getTag = function(value) {\n        var result = baseGetTag(value),\n            Ctor = result == objectTag ? value.constructor : undefined,\n            ctorString = Ctor ? toSource(Ctor) : '';\n\n        if (ctorString) {\n          switch (ctorString) {\n            case dataViewCtorString: return dataViewTag;\n            case mapCtorString: return mapTag;\n            case promiseCtorString: return promiseTag;\n            case setCtorString: return setTag;\n            case weakMapCtorString: return weakMapTag;\n          }\n        }\n        return result;\n      };\n    }\n\n    /**\n     * Gets the view, applying any `transforms` to the `start` and `end` positions.\n     *\n     * @private\n     * @param {number} start The start of the view.\n     * @param {number} end The end of the view.\n     * @param {Array} transforms The transformations to apply to the view.\n     * @returns {Object} Returns an object containing the `start` and `end`\n     *  positions of the view.\n     */\n    function getView(start, end, transforms) {\n      var index = -1,\n          length = transforms.length;\n\n      while (++index < length) {\n        var data = transforms[index],\n            size = data.size;\n\n        switch (data.type) {\n          case 'drop':      start += size; break;\n          case 'dropRight': end -= size; break;\n          case 'take':      end = nativeMin(end, start + size); break;\n          case 'takeRight': start = nativeMax(start, end - size); break;\n        }\n      }\n      return { 'start': start, 'end': end };\n    }\n\n    /**\n     * Extracts wrapper details from the `source` body comment.\n     *\n     * @private\n     * @param {string} source The source to inspect.\n     * @returns {Array} Returns the wrapper details.\n     */\n    function getWrapDetails(source) {\n      var match = source.match(reWrapDetails);\n      return match ? match[1].split(reSplitDetails) : [];\n    }\n\n    /**\n     * Checks if `path` exists on `object`.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @param {Array|string} path The path to check.\n     * @param {Function} hasFunc The function to check properties.\n     * @returns {boolean} Returns `true` if `path` exists, else `false`.\n     */\n    function hasPath(object, path, hasFunc) {\n      path = castPath(path, object);\n\n      var index = -1,\n          length = path.length,\n          result = false;\n\n      while (++index < length) {\n        var key = toKey(path[index]);\n        if (!(result = object != null && hasFunc(object, key))) {\n          break;\n        }\n        object = object[key];\n      }\n      if (result || ++index != length) {\n        return result;\n      }\n      length = object == null ? 0 : object.length;\n      return !!length && isLength(length) && isIndex(key, length) &&\n        (isArray(object) || isArguments(object));\n    }\n\n    /**\n     * Initializes an array clone.\n     *\n     * @private\n     * @param {Array} array The array to clone.\n     * @returns {Array} Returns the initialized clone.\n     */\n    function initCloneArray(array) {\n      var length = array.length,\n          result = new array.constructor(length);\n\n      // Add properties assigned by `RegExp#exec`.\n      if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n        result.index = array.index;\n        result.input = array.input;\n      }\n      return result;\n    }\n\n    /**\n     * Initializes an object clone.\n     *\n     * @private\n     * @param {Object} object The object to clone.\n     * @returns {Object} Returns the initialized clone.\n     */\n    function initCloneObject(object) {\n      return (typeof object.constructor == 'function' && !isPrototype(object))\n        ? baseCreate(getPrototype(object))\n        : {};\n    }\n\n    /**\n     * Initializes an object clone based on its `toStringTag`.\n     *\n     * **Note:** This function only supports cloning values with tags of\n     * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n     *\n     * @private\n     * @param {Object} object The object to clone.\n     * @param {string} tag The `toStringTag` of the object to clone.\n     * @param {boolean} [isDeep] Specify a deep clone.\n     * @returns {Object} Returns the initialized clone.\n     */\n    function initCloneByTag(object, tag, isDeep) {\n      var Ctor = object.constructor;\n      switch (tag) {\n        case arrayBufferTag:\n          return cloneArrayBuffer(object);\n\n        case boolTag:\n        case dateTag:\n          return new Ctor(+object);\n\n        case dataViewTag:\n          return cloneDataView(object, isDeep);\n\n        case float32Tag: case float64Tag:\n        case int8Tag: case int16Tag: case int32Tag:\n        case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n          return cloneTypedArray(object, isDeep);\n\n        case mapTag:\n          return new Ctor;\n\n        case numberTag:\n        case stringTag:\n          return new Ctor(object);\n\n        case regexpTag:\n          return cloneRegExp(object);\n\n        case setTag:\n          return new Ctor;\n\n        case symbolTag:\n          return cloneSymbol(object);\n      }\n    }\n\n    /**\n     * Inserts wrapper `details` in a comment at the top of the `source` body.\n     *\n     * @private\n     * @param {string} source The source to modify.\n     * @returns {Array} details The details to insert.\n     * @returns {string} Returns the modified source.\n     */\n    function insertWrapDetails(source, details) {\n      var length = details.length;\n      if (!length) {\n        return source;\n      }\n      var lastIndex = length - 1;\n      details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n      details = details.join(length > 2 ? ', ' : ' ');\n      return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n    }\n\n    /**\n     * Checks if `value` is a flattenable `arguments` object or array.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n     */\n    function isFlattenable(value) {\n      return isArray(value) || isArguments(value) ||\n        !!(spreadableSymbol && value && value[spreadableSymbol]);\n    }\n\n    /**\n     * Checks if `value` is a valid array-like index.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n     * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n     */\n    function isIndex(value, length) {\n      var type = typeof value;\n      length = length == null ? MAX_SAFE_INTEGER : length;\n\n      return !!length &&\n        (type == 'number' ||\n          (type != 'symbol' && reIsUint.test(value))) &&\n            (value > -1 && value % 1 == 0 && value < length);\n    }\n\n    /**\n     * Checks if the given arguments are from an iteratee call.\n     *\n     * @private\n     * @param {*} value The potential iteratee value argument.\n     * @param {*} index The potential iteratee index or key argument.\n     * @param {*} object The potential iteratee object argument.\n     * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n     *  else `false`.\n     */\n    function isIterateeCall(value, index, object) {\n      if (!isObject(object)) {\n        return false;\n      }\n      var type = typeof index;\n      if (type == 'number'\n            ? (isArrayLike(object) && isIndex(index, object.length))\n            : (type == 'string' && index in object)\n          ) {\n        return eq(object[index], value);\n      }\n      return false;\n    }\n\n    /**\n     * Checks if `value` is a property name and not a property path.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @param {Object} [object] The object to query keys on.\n     * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n     */\n    function isKey(value, object) {\n      if (isArray(value)) {\n        return false;\n      }\n      var type = typeof value;\n      if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n          value == null || isSymbol(value)) {\n        return true;\n      }\n      return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n        (object != null && value in Object(object));\n    }\n\n    /**\n     * Checks if `value` is suitable for use as unique object key.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n     */\n    function isKeyable(value) {\n      var type = typeof value;\n      return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n        ? (value !== '__proto__')\n        : (value === null);\n    }\n\n    /**\n     * Checks if `func` has a lazy counterpart.\n     *\n     * @private\n     * @param {Function} func The function to check.\n     * @returns {boolean} Returns `true` if `func` has a lazy counterpart,\n     *  else `false`.\n     */\n    function isLaziable(func) {\n      var funcName = getFuncName(func),\n          other = lodash[funcName];\n\n      if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {\n        return false;\n      }\n      if (func === other) {\n        return true;\n      }\n      var data = getData(other);\n      return !!data && func === data[0];\n    }\n\n    /**\n     * Checks if `func` has its source masked.\n     *\n     * @private\n     * @param {Function} func The function to check.\n     * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n     */\n    function isMasked(func) {\n      return !!maskSrcKey && (maskSrcKey in func);\n    }\n\n    /**\n     * Checks if `func` is capable of being masked.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `func` is maskable, else `false`.\n     */\n    var isMaskable = coreJsData ? isFunction : stubFalse;\n\n    /**\n     * Checks if `value` is likely a prototype object.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n     */\n    function isPrototype(value) {\n      var Ctor = value && value.constructor,\n          proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n      return value === proto;\n    }\n\n    /**\n     * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n     *\n     * @private\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` if suitable for strict\n     *  equality comparisons, else `false`.\n     */\n    function isStrictComparable(value) {\n      return value === value && !isObject(value);\n    }\n\n    /**\n     * A specialized version of `matchesProperty` for source values suitable\n     * for strict equality comparisons, i.e. `===`.\n     *\n     * @private\n     * @param {string} key The key of the property to get.\n     * @param {*} srcValue The value to match.\n     * @returns {Function} Returns the new spec function.\n     */\n    function matchesStrictComparable(key, srcValue) {\n      return function(object) {\n        if (object == null) {\n          return false;\n        }\n        return object[key] === srcValue &&\n          (srcValue !== undefined || (key in Object(object)));\n      };\n    }\n\n    /**\n     * A specialized version of `_.memoize` which clears the memoized function's\n     * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n     *\n     * @private\n     * @param {Function} func The function to have its output memoized.\n     * @returns {Function} Returns the new memoized function.\n     */\n    function memoizeCapped(func) {\n      var result = memoize(func, function(key) {\n        if (cache.size === MAX_MEMOIZE_SIZE) {\n          cache.clear();\n        }\n        return key;\n      });\n\n      var cache = result.cache;\n      return result;\n    }\n\n    /**\n     * Merges the function metadata of `source` into `data`.\n     *\n     * Merging metadata reduces the number of wrappers used to invoke a function.\n     * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n     * may be applied regardless of execution order. Methods like `_.ary` and\n     * `_.rearg` modify function arguments, making the order in which they are\n     * executed important, preventing the merging of metadata. However, we make\n     * an exception for a safe combined case where curried functions have `_.ary`\n     * and or `_.rearg` applied.\n     *\n     * @private\n     * @param {Array} data The destination metadata.\n     * @param {Array} source The source metadata.\n     * @returns {Array} Returns `data`.\n     */\n    function mergeData(data, source) {\n      var bitmask = data[1],\n          srcBitmask = source[1],\n          newBitmask = bitmask | srcBitmask,\n          isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);\n\n      var isCombo =\n        ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||\n        ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||\n        ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));\n\n      // Exit early if metadata can't be merged.\n      if (!(isCommon || isCombo)) {\n        return data;\n      }\n      // Use source `thisArg` if available.\n      if (srcBitmask & WRAP_BIND_FLAG) {\n        data[2] = source[2];\n        // Set when currying a bound function.\n        newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;\n      }\n      // Compose partial arguments.\n      var value = source[3];\n      if (value) {\n        var partials = data[3];\n        data[3] = partials ? composeArgs(partials, value, source[4]) : value;\n        data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];\n      }\n      // Compose partial right arguments.\n      value = source[5];\n      if (value) {\n        partials = data[5];\n        data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;\n        data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];\n      }\n      // Use source `argPos` if available.\n      value = source[7];\n      if (value) {\n        data[7] = value;\n      }\n      // Use source `ary` if it's smaller.\n      if (srcBitmask & WRAP_ARY_FLAG) {\n        data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n      }\n      // Use source `arity` if one is not provided.\n      if (data[9] == null) {\n        data[9] = source[9];\n      }\n      // Use source `func` and merge bitmasks.\n      data[0] = source[0];\n      data[1] = newBitmask;\n\n      return data;\n    }\n\n    /**\n     * This function is like\n     * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n     * except that it includes inherited enumerable properties.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of property names.\n     */\n    function nativeKeysIn(object) {\n      var result = [];\n      if (object != null) {\n        for (var key in Object(object)) {\n          result.push(key);\n        }\n      }\n      return result;\n    }\n\n    /**\n     * Converts `value` to a string using `Object.prototype.toString`.\n     *\n     * @private\n     * @param {*} value The value to convert.\n     * @returns {string} Returns the converted string.\n     */\n    function objectToString(value) {\n      return nativeObjectToString.call(value);\n    }\n\n    /**\n     * A specialized version of `baseRest` which transforms the rest array.\n     *\n     * @private\n     * @param {Function} func The function to apply a rest parameter to.\n     * @param {number} [start=func.length-1] The start position of the rest parameter.\n     * @param {Function} transform The rest array transform.\n     * @returns {Function} Returns the new function.\n     */\n    function overRest(func, start, transform) {\n      start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n      return function() {\n        var args = arguments,\n            index = -1,\n            length = nativeMax(args.length - start, 0),\n            array = Array(length);\n\n        while (++index < length) {\n          array[index] = args[start + index];\n        }\n        index = -1;\n        var otherArgs = Array(start + 1);\n        while (++index < start) {\n          otherArgs[index] = args[index];\n        }\n        otherArgs[start] = transform(array);\n        return apply(func, this, otherArgs);\n      };\n    }\n\n    /**\n     * Gets the parent value at `path` of `object`.\n     *\n     * @private\n     * @param {Object} object The object to query.\n     * @param {Array} path The path to get the parent value of.\n     * @returns {*} Returns the parent value.\n     */\n    function parent(object, path) {\n      return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n    }\n\n    /**\n     * Reorder `array` according to the specified indexes where the element at\n     * the first index is assigned as the first element, the element at\n     * the second index is assigned as the second element, and so on.\n     *\n     * @private\n     * @param {Array} array The array to reorder.\n     * @param {Array} indexes The arranged array indexes.\n     * @returns {Array} Returns `array`.\n     */\n    function reorder(array, indexes) {\n      var arrLength = array.length,\n          length = nativeMin(indexes.length, arrLength),\n          oldArray = copyArray(array);\n\n      while (length--) {\n        var index = indexes[length];\n        array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n      }\n      return array;\n    }\n\n    /**\n     * Sets metadata for `func`.\n     *\n     * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n     * period of time, it will trip its breaker and transition to an identity\n     * function to avoid garbage collection pauses in V8. See\n     * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)\n     * for more details.\n     *\n     * @private\n     * @param {Function} func The function to associate metadata with.\n     * @param {*} data The metadata.\n     * @returns {Function} Returns `func`.\n     */\n    var setData = shortOut(baseSetData);\n\n    /**\n     * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).\n     *\n     * @private\n     * @param {Function} func The function to delay.\n     * @param {number} wait The number of milliseconds to delay invocation.\n     * @returns {number|Object} Returns the timer id or timeout object.\n     */\n    var setTimeout = ctxSetTimeout || function(func, wait) {\n      return root.setTimeout(func, wait);\n    };\n\n    /**\n     * Sets the `toString` method of `func` to return `string`.\n     *\n     * @private\n     * @param {Function} func The function to modify.\n     * @param {Function} string The `toString` result.\n     * @returns {Function} Returns `func`.\n     */\n    var setToString = shortOut(baseSetToString);\n\n    /**\n     * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n     * with wrapper details in a comment at the top of the source body.\n     *\n     * @private\n     * @param {Function} wrapper The function to modify.\n     * @param {Function} reference The reference function.\n     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n     * @returns {Function} Returns `wrapper`.\n     */\n    function setWrapToString(wrapper, reference, bitmask) {\n      var source = (reference + '');\n      return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));\n    }\n\n    /**\n     * Creates a function that'll short out and invoke `identity` instead\n     * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n     * milliseconds.\n     *\n     * @private\n     * @param {Function} func The function to restrict.\n     * @returns {Function} Returns the new shortable function.\n     */\n    function shortOut(func) {\n      var count = 0,\n          lastCalled = 0;\n\n      return function() {\n        var stamp = nativeNow(),\n            remaining = HOT_SPAN - (stamp - lastCalled);\n\n        lastCalled = stamp;\n        if (remaining > 0) {\n          if (++count >= HOT_COUNT) {\n            return arguments[0];\n          }\n        } else {\n          count = 0;\n        }\n        return func.apply(undefined, arguments);\n      };\n    }\n\n    /**\n     * A specialized version of `_.shuffle` which mutates and sets the size of `array`.\n     *\n     * @private\n     * @param {Array} array The array to shuffle.\n     * @param {number} [size=array.length] The size of `array`.\n     * @returns {Array} Returns `array`.\n     */\n    function shuffleSelf(array, size) {\n      var index = -1,\n          length = array.length,\n          lastIndex = length - 1;\n\n      size = size === undefined ? length : size;\n      while (++index < size) {\n        var rand = baseRandom(index, lastIndex),\n            value = array[rand];\n\n        array[rand] = array[index];\n        array[index] = value;\n      }\n      array.length = size;\n      return array;\n    }\n\n    /**\n     * Converts `string` to a property path array.\n     *\n     * @private\n     * @param {string} string The string to convert.\n     * @returns {Array} Returns the property path array.\n     */\n    var stringToPath = memoizeCapped(function(string) {\n      var result = [];\n      if (string.charCodeAt(0) === 46 /* . */) {\n        result.push('');\n      }\n      string.replace(rePropName, function(match, number, quote, subString) {\n        result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n      });\n      return result;\n    });\n\n    /**\n     * Converts `value` to a string key if it's not a string or symbol.\n     *\n     * @private\n     * @param {*} value The value to inspect.\n     * @returns {string|symbol} Returns the key.\n     */\n    function toKey(value) {\n      if (typeof value == 'string' || isSymbol(value)) {\n        return value;\n      }\n      var result = (value + '');\n      return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n    }\n\n    /**\n     * Converts `func` to its source code.\n     *\n     * @private\n     * @param {Function} func The function to convert.\n     * @returns {string} Returns the source code.\n     */\n    function toSource(func) {\n      if (func != null) {\n        try {\n          return funcToString.call(func);\n        } catch (e) {}\n        try {\n          return (func + '');\n        } catch (e) {}\n      }\n      return '';\n    }\n\n    /**\n     * Updates wrapper `details` based on `bitmask` flags.\n     *\n     * @private\n     * @returns {Array} details The details to modify.\n     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n     * @returns {Array} Returns `details`.\n     */\n    function updateWrapDetails(details, bitmask) {\n      arrayEach(wrapFlags, function(pair) {\n        var value = '_.' + pair[0];\n        if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n          details.push(value);\n        }\n      });\n      return details.sort();\n    }\n\n    /**\n     * Creates a clone of `wrapper`.\n     *\n     * @private\n     * @param {Object} wrapper The wrapper to clone.\n     * @returns {Object} Returns the cloned wrapper.\n     */\n    function wrapperClone(wrapper) {\n      if (wrapper instanceof LazyWrapper) {\n        return wrapper.clone();\n      }\n      var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);\n      result.__actions__ = copyArray(wrapper.__actions__);\n      result.__index__  = wrapper.__index__;\n      result.__values__ = wrapper.__values__;\n      return result;\n    }\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates an array of elements split into groups the length of `size`.\n     * If `array` can't be split evenly, the final chunk will be the remaining\n     * elements.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to process.\n     * @param {number} [size=1] The length of each chunk\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Array} Returns the new array of chunks.\n     * @example\n     *\n     * _.chunk(['a', 'b', 'c', 'd'], 2);\n     * // => [['a', 'b'], ['c', 'd']]\n     *\n     * _.chunk(['a', 'b', 'c', 'd'], 3);\n     * // => [['a', 'b', 'c'], ['d']]\n     */\n    function chunk(array, size, guard) {\n      if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {\n        size = 1;\n      } else {\n        size = nativeMax(toInteger(size), 0);\n      }\n      var length = array == null ? 0 : array.length;\n      if (!length || size < 1) {\n        return [];\n      }\n      var index = 0,\n          resIndex = 0,\n          result = Array(nativeCeil(length / size));\n\n      while (index < length) {\n        result[resIndex++] = baseSlice(array, index, (index += size));\n      }\n      return result;\n    }\n\n    /**\n     * Creates an array with all falsey values removed. The values `false`, `null`,\n     * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to compact.\n     * @returns {Array} Returns the new array of filtered values.\n     * @example\n     *\n     * _.compact([0, 1, false, 2, '', 3]);\n     * // => [1, 2, 3]\n     */\n    function compact(array) {\n      var index = -1,\n          length = array == null ? 0 : array.length,\n          resIndex = 0,\n          result = [];\n\n      while (++index < length) {\n        var value = array[index];\n        if (value) {\n          result[resIndex++] = value;\n        }\n      }\n      return result;\n    }\n\n    /**\n     * Creates a new array concatenating `array` with any additional arrays\n     * and/or values.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to concatenate.\n     * @param {...*} [values] The values to concatenate.\n     * @returns {Array} Returns the new concatenated array.\n     * @example\n     *\n     * var array = [1];\n     * var other = _.concat(array, 2, [3], [[4]]);\n     *\n     * console.log(other);\n     * // => [1, 2, 3, [4]]\n     *\n     * console.log(array);\n     * // => [1]\n     */\n    function concat() {\n      var length = arguments.length;\n      if (!length) {\n        return [];\n      }\n      var args = Array(length - 1),\n          array = arguments[0],\n          index = length;\n\n      while (index--) {\n        args[index - 1] = arguments[index];\n      }\n      return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));\n    }\n\n    /**\n     * Creates an array of `array` values not included in the other given arrays\n     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * for equality comparisons. The order and references of result values are\n     * determined by the first array.\n     *\n     * **Note:** Unlike `_.pullAll`, this method returns a new array.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {...Array} [values] The values to exclude.\n     * @returns {Array} Returns the new array of filtered values.\n     * @see _.without, _.xor\n     * @example\n     *\n     * _.difference([2, 1], [2, 3]);\n     * // => [1]\n     */\n    var difference = baseRest(function(array, values) {\n      return isArrayLikeObject(array)\n        ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n        : [];\n    });\n\n    /**\n     * This method is like `_.difference` except that it accepts `iteratee` which\n     * is invoked for each element of `array` and `values` to generate the criterion\n     * by which they're compared. The order and references of result values are\n     * determined by the first array. The iteratee is invoked with one argument:\n     * (value).\n     *\n     * **Note:** Unlike `_.pullAllBy`, this method returns a new array.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {...Array} [values] The values to exclude.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {Array} Returns the new array of filtered values.\n     * @example\n     *\n     * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n     * // => [1.2]\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');\n     * // => [{ 'x': 2 }]\n     */\n    var differenceBy = baseRest(function(array, values) {\n      var iteratee = last(values);\n      if (isArrayLikeObject(iteratee)) {\n        iteratee = undefined;\n      }\n      return isArrayLikeObject(array)\n        ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))\n        : [];\n    });\n\n    /**\n     * This method is like `_.difference` except that it accepts `comparator`\n     * which is invoked to compare elements of `array` to `values`. The order and\n     * references of result values are determined by the first array. The comparator\n     * is invoked with two arguments: (arrVal, othVal).\n     *\n     * **Note:** Unlike `_.pullAllWith`, this method returns a new array.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {...Array} [values] The values to exclude.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns the new array of filtered values.\n     * @example\n     *\n     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n     *\n     * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);\n     * // => [{ 'x': 2, 'y': 1 }]\n     */\n    var differenceWith = baseRest(function(array, values) {\n      var comparator = last(values);\n      if (isArrayLikeObject(comparator)) {\n        comparator = undefined;\n      }\n      return isArrayLikeObject(array)\n        ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)\n        : [];\n    });\n\n    /**\n     * Creates a slice of `array` with `n` elements dropped from the beginning.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.5.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @param {number} [n=1] The number of elements to drop.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * _.drop([1, 2, 3]);\n     * // => [2, 3]\n     *\n     * _.drop([1, 2, 3], 2);\n     * // => [3]\n     *\n     * _.drop([1, 2, 3], 5);\n     * // => []\n     *\n     * _.drop([1, 2, 3], 0);\n     * // => [1, 2, 3]\n     */\n    function drop(array, n, guard) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return [];\n      }\n      n = (guard || n === undefined) ? 1 : toInteger(n);\n      return baseSlice(array, n < 0 ? 0 : n, length);\n    }\n\n    /**\n     * Creates a slice of `array` with `n` elements dropped from the end.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @param {number} [n=1] The number of elements to drop.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * _.dropRight([1, 2, 3]);\n     * // => [1, 2]\n     *\n     * _.dropRight([1, 2, 3], 2);\n     * // => [1]\n     *\n     * _.dropRight([1, 2, 3], 5);\n     * // => []\n     *\n     * _.dropRight([1, 2, 3], 0);\n     * // => [1, 2, 3]\n     */\n    function dropRight(array, n, guard) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return [];\n      }\n      n = (guard || n === undefined) ? 1 : toInteger(n);\n      n = length - n;\n      return baseSlice(array, 0, n < 0 ? 0 : n);\n    }\n\n    /**\n     * Creates a slice of `array` excluding elements dropped from the end.\n     * Elements are dropped until `predicate` returns falsey. The predicate is\n     * invoked with three arguments: (value, index, array).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney',  'active': true },\n     *   { 'user': 'fred',    'active': false },\n     *   { 'user': 'pebbles', 'active': false }\n     * ];\n     *\n     * _.dropRightWhile(users, function(o) { return !o.active; });\n     * // => objects for ['barney']\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });\n     * // => objects for ['barney', 'fred']\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.dropRightWhile(users, ['active', false]);\n     * // => objects for ['barney']\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.dropRightWhile(users, 'active');\n     * // => objects for ['barney', 'fred', 'pebbles']\n     */\n    function dropRightWhile(array, predicate) {\n      return (array && array.length)\n        ? baseWhile(array, getIteratee(predicate, 3), true, true)\n        : [];\n    }\n\n    /**\n     * Creates a slice of `array` excluding elements dropped from the beginning.\n     * Elements are dropped until `predicate` returns falsey. The predicate is\n     * invoked with three arguments: (value, index, array).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney',  'active': false },\n     *   { 'user': 'fred',    'active': false },\n     *   { 'user': 'pebbles', 'active': true }\n     * ];\n     *\n     * _.dropWhile(users, function(o) { return !o.active; });\n     * // => objects for ['pebbles']\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.dropWhile(users, { 'user': 'barney', 'active': false });\n     * // => objects for ['fred', 'pebbles']\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.dropWhile(users, ['active', false]);\n     * // => objects for ['pebbles']\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.dropWhile(users, 'active');\n     * // => objects for ['barney', 'fred', 'pebbles']\n     */\n    function dropWhile(array, predicate) {\n      return (array && array.length)\n        ? baseWhile(array, getIteratee(predicate, 3), true)\n        : [];\n    }\n\n    /**\n     * Fills elements of `array` with `value` from `start` up to, but not\n     * including, `end`.\n     *\n     * **Note:** This method mutates `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.2.0\n     * @category Array\n     * @param {Array} array The array to fill.\n     * @param {*} value The value to fill `array` with.\n     * @param {number} [start=0] The start position.\n     * @param {number} [end=array.length] The end position.\n     * @returns {Array} Returns `array`.\n     * @example\n     *\n     * var array = [1, 2, 3];\n     *\n     * _.fill(array, 'a');\n     * console.log(array);\n     * // => ['a', 'a', 'a']\n     *\n     * _.fill(Array(3), 2);\n     * // => [2, 2, 2]\n     *\n     * _.fill([4, 6, 8, 10], '*', 1, 3);\n     * // => [4, '*', '*', 10]\n     */\n    function fill(array, value, start, end) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return [];\n      }\n      if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {\n        start = 0;\n        end = length;\n      }\n      return baseFill(array, value, start, end);\n    }\n\n    /**\n     * This method is like `_.find` except that it returns the index of the first\n     * element `predicate` returns truthy for instead of the element itself.\n     *\n     * @static\n     * @memberOf _\n     * @since 1.1.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @param {number} [fromIndex=0] The index to search from.\n     * @returns {number} Returns the index of the found element, else `-1`.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney',  'active': false },\n     *   { 'user': 'fred',    'active': false },\n     *   { 'user': 'pebbles', 'active': true }\n     * ];\n     *\n     * _.findIndex(users, function(o) { return o.user == 'barney'; });\n     * // => 0\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.findIndex(users, { 'user': 'fred', 'active': false });\n     * // => 1\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.findIndex(users, ['active', false]);\n     * // => 0\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.findIndex(users, 'active');\n     * // => 2\n     */\n    function findIndex(array, predicate, fromIndex) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return -1;\n      }\n      var index = fromIndex == null ? 0 : toInteger(fromIndex);\n      if (index < 0) {\n        index = nativeMax(length + index, 0);\n      }\n      return baseFindIndex(array, getIteratee(predicate, 3), index);\n    }\n\n    /**\n     * This method is like `_.findIndex` except that it iterates over elements\n     * of `collection` from right to left.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @param {number} [fromIndex=array.length-1] The index to search from.\n     * @returns {number} Returns the index of the found element, else `-1`.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney',  'active': true },\n     *   { 'user': 'fred',    'active': false },\n     *   { 'user': 'pebbles', 'active': false }\n     * ];\n     *\n     * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });\n     * // => 2\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.findLastIndex(users, { 'user': 'barney', 'active': true });\n     * // => 0\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.findLastIndex(users, ['active', false]);\n     * // => 2\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.findLastIndex(users, 'active');\n     * // => 0\n     */\n    function findLastIndex(array, predicate, fromIndex) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return -1;\n      }\n      var index = length - 1;\n      if (fromIndex !== undefined) {\n        index = toInteger(fromIndex);\n        index = fromIndex < 0\n          ? nativeMax(length + index, 0)\n          : nativeMin(index, length - 1);\n      }\n      return baseFindIndex(array, getIteratee(predicate, 3), index, true);\n    }\n\n    /**\n     * Flattens `array` a single level deep.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to flatten.\n     * @returns {Array} Returns the new flattened array.\n     * @example\n     *\n     * _.flatten([1, [2, [3, [4]], 5]]);\n     * // => [1, 2, [3, [4]], 5]\n     */\n    function flatten(array) {\n      var length = array == null ? 0 : array.length;\n      return length ? baseFlatten(array, 1) : [];\n    }\n\n    /**\n     * Recursively flattens `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to flatten.\n     * @returns {Array} Returns the new flattened array.\n     * @example\n     *\n     * _.flattenDeep([1, [2, [3, [4]], 5]]);\n     * // => [1, 2, 3, 4, 5]\n     */\n    function flattenDeep(array) {\n      var length = array == null ? 0 : array.length;\n      return length ? baseFlatten(array, INFINITY) : [];\n    }\n\n    /**\n     * Recursively flatten `array` up to `depth` times.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.4.0\n     * @category Array\n     * @param {Array} array The array to flatten.\n     * @param {number} [depth=1] The maximum recursion depth.\n     * @returns {Array} Returns the new flattened array.\n     * @example\n     *\n     * var array = [1, [2, [3, [4]], 5]];\n     *\n     * _.flattenDepth(array, 1);\n     * // => [1, 2, [3, [4]], 5]\n     *\n     * _.flattenDepth(array, 2);\n     * // => [1, 2, 3, [4], 5]\n     */\n    function flattenDepth(array, depth) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return [];\n      }\n      depth = depth === undefined ? 1 : toInteger(depth);\n      return baseFlatten(array, depth);\n    }\n\n    /**\n     * The inverse of `_.toPairs`; this method returns an object composed\n     * from key-value `pairs`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} pairs The key-value pairs.\n     * @returns {Object} Returns the new object.\n     * @example\n     *\n     * _.fromPairs([['a', 1], ['b', 2]]);\n     * // => { 'a': 1, 'b': 2 }\n     */\n    function fromPairs(pairs) {\n      var index = -1,\n          length = pairs == null ? 0 : pairs.length,\n          result = {};\n\n      while (++index < length) {\n        var pair = pairs[index];\n        result[pair[0]] = pair[1];\n      }\n      return result;\n    }\n\n    /**\n     * Gets the first element of `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @alias first\n     * @category Array\n     * @param {Array} array The array to query.\n     * @returns {*} Returns the first element of `array`.\n     * @example\n     *\n     * _.head([1, 2, 3]);\n     * // => 1\n     *\n     * _.head([]);\n     * // => undefined\n     */\n    function head(array) {\n      return (array && array.length) ? array[0] : undefined;\n    }\n\n    /**\n     * Gets the index at which the first occurrence of `value` is found in `array`\n     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * for equality comparisons. If `fromIndex` is negative, it's used as the\n     * offset from the end of `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {*} value The value to search for.\n     * @param {number} [fromIndex=0] The index to search from.\n     * @returns {number} Returns the index of the matched value, else `-1`.\n     * @example\n     *\n     * _.indexOf([1, 2, 1, 2], 2);\n     * // => 1\n     *\n     * // Search from the `fromIndex`.\n     * _.indexOf([1, 2, 1, 2], 2, 2);\n     * // => 3\n     */\n    function indexOf(array, value, fromIndex) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return -1;\n      }\n      var index = fromIndex == null ? 0 : toInteger(fromIndex);\n      if (index < 0) {\n        index = nativeMax(length + index, 0);\n      }\n      return baseIndexOf(array, value, index);\n    }\n\n    /**\n     * Gets all but the last element of `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * _.initial([1, 2, 3]);\n     * // => [1, 2]\n     */\n    function initial(array) {\n      var length = array == null ? 0 : array.length;\n      return length ? baseSlice(array, 0, -1) : [];\n    }\n\n    /**\n     * Creates an array of unique values that are included in all given arrays\n     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * for equality comparisons. The order and references of result values are\n     * determined by the first array.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to inspect.\n     * @returns {Array} Returns the new array of intersecting values.\n     * @example\n     *\n     * _.intersection([2, 1], [2, 3]);\n     * // => [2]\n     */\n    var intersection = baseRest(function(arrays) {\n      var mapped = arrayMap(arrays, castArrayLikeObject);\n      return (mapped.length && mapped[0] === arrays[0])\n        ? baseIntersection(mapped)\n        : [];\n    });\n\n    /**\n     * This method is like `_.intersection` except that it accepts `iteratee`\n     * which is invoked for each element of each `arrays` to generate the criterion\n     * by which they're compared. The order and references of result values are\n     * determined by the first array. The iteratee is invoked with one argument:\n     * (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to inspect.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {Array} Returns the new array of intersecting values.\n     * @example\n     *\n     * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n     * // => [2.1]\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n     * // => [{ 'x': 1 }]\n     */\n    var intersectionBy = baseRest(function(arrays) {\n      var iteratee = last(arrays),\n          mapped = arrayMap(arrays, castArrayLikeObject);\n\n      if (iteratee === last(mapped)) {\n        iteratee = undefined;\n      } else {\n        mapped.pop();\n      }\n      return (mapped.length && mapped[0] === arrays[0])\n        ? baseIntersection(mapped, getIteratee(iteratee, 2))\n        : [];\n    });\n\n    /**\n     * This method is like `_.intersection` except that it accepts `comparator`\n     * which is invoked to compare elements of `arrays`. The order and references\n     * of result values are determined by the first array. The comparator is\n     * invoked with two arguments: (arrVal, othVal).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to inspect.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns the new array of intersecting values.\n     * @example\n     *\n     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n     * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n     *\n     * _.intersectionWith(objects, others, _.isEqual);\n     * // => [{ 'x': 1, 'y': 2 }]\n     */\n    var intersectionWith = baseRest(function(arrays) {\n      var comparator = last(arrays),\n          mapped = arrayMap(arrays, castArrayLikeObject);\n\n      comparator = typeof comparator == 'function' ? comparator : undefined;\n      if (comparator) {\n        mapped.pop();\n      }\n      return (mapped.length && mapped[0] === arrays[0])\n        ? baseIntersection(mapped, undefined, comparator)\n        : [];\n    });\n\n    /**\n     * Converts all elements in `array` into a string separated by `separator`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to convert.\n     * @param {string} [separator=','] The element separator.\n     * @returns {string} Returns the joined string.\n     * @example\n     *\n     * _.join(['a', 'b', 'c'], '~');\n     * // => 'a~b~c'\n     */\n    function join(array, separator) {\n      return array == null ? '' : nativeJoin.call(array, separator);\n    }\n\n    /**\n     * Gets the last element of `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @returns {*} Returns the last element of `array`.\n     * @example\n     *\n     * _.last([1, 2, 3]);\n     * // => 3\n     */\n    function last(array) {\n      var length = array == null ? 0 : array.length;\n      return length ? array[length - 1] : undefined;\n    }\n\n    /**\n     * This method is like `_.indexOf` except that it iterates over elements of\n     * `array` from right to left.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {*} value The value to search for.\n     * @param {number} [fromIndex=array.length-1] The index to search from.\n     * @returns {number} Returns the index of the matched value, else `-1`.\n     * @example\n     *\n     * _.lastIndexOf([1, 2, 1, 2], 2);\n     * // => 3\n     *\n     * // Search from the `fromIndex`.\n     * _.lastIndexOf([1, 2, 1, 2], 2, 2);\n     * // => 1\n     */\n    function lastIndexOf(array, value, fromIndex) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return -1;\n      }\n      var index = length;\n      if (fromIndex !== undefined) {\n        index = toInteger(fromIndex);\n        index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);\n      }\n      return value === value\n        ? strictLastIndexOf(array, value, index)\n        : baseFindIndex(array, baseIsNaN, index, true);\n    }\n\n    /**\n     * Gets the element at index `n` of `array`. If `n` is negative, the nth\n     * element from the end is returned.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.11.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @param {number} [n=0] The index of the element to return.\n     * @returns {*} Returns the nth element of `array`.\n     * @example\n     *\n     * var array = ['a', 'b', 'c', 'd'];\n     *\n     * _.nth(array, 1);\n     * // => 'b'\n     *\n     * _.nth(array, -2);\n     * // => 'c';\n     */\n    function nth(array, n) {\n      return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;\n    }\n\n    /**\n     * Removes all given values from `array` using\n     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * for equality comparisons.\n     *\n     * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`\n     * to remove elements from an array by predicate.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @category Array\n     * @param {Array} array The array to modify.\n     * @param {...*} [values] The values to remove.\n     * @returns {Array} Returns `array`.\n     * @example\n     *\n     * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n     *\n     * _.pull(array, 'a', 'c');\n     * console.log(array);\n     * // => ['b', 'b']\n     */\n    var pull = baseRest(pullAll);\n\n    /**\n     * This method is like `_.pull` except that it accepts an array of values to remove.\n     *\n     * **Note:** Unlike `_.difference`, this method mutates `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to modify.\n     * @param {Array} values The values to remove.\n     * @returns {Array} Returns `array`.\n     * @example\n     *\n     * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n     *\n     * _.pullAll(array, ['a', 'c']);\n     * console.log(array);\n     * // => ['b', 'b']\n     */\n    function pullAll(array, values) {\n      return (array && array.length && values && values.length)\n        ? basePullAll(array, values)\n        : array;\n    }\n\n    /**\n     * This method is like `_.pullAll` except that it accepts `iteratee` which is\n     * invoked for each element of `array` and `values` to generate the criterion\n     * by which they're compared. The iteratee is invoked with one argument: (value).\n     *\n     * **Note:** Unlike `_.differenceBy`, this method mutates `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to modify.\n     * @param {Array} values The values to remove.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {Array} Returns `array`.\n     * @example\n     *\n     * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];\n     *\n     * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');\n     * console.log(array);\n     * // => [{ 'x': 2 }]\n     */\n    function pullAllBy(array, values, iteratee) {\n      return (array && array.length && values && values.length)\n        ? basePullAll(array, values, getIteratee(iteratee, 2))\n        : array;\n    }\n\n    /**\n     * This method is like `_.pullAll` except that it accepts `comparator` which\n     * is invoked to compare elements of `array` to `values`. The comparator is\n     * invoked with two arguments: (arrVal, othVal).\n     *\n     * **Note:** Unlike `_.differenceWith`, this method mutates `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.6.0\n     * @category Array\n     * @param {Array} array The array to modify.\n     * @param {Array} values The values to remove.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns `array`.\n     * @example\n     *\n     * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];\n     *\n     * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);\n     * console.log(array);\n     * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]\n     */\n    function pullAllWith(array, values, comparator) {\n      return (array && array.length && values && values.length)\n        ? basePullAll(array, values, undefined, comparator)\n        : array;\n    }\n\n    /**\n     * Removes elements from `array` corresponding to `indexes` and returns an\n     * array of removed elements.\n     *\n     * **Note:** Unlike `_.at`, this method mutates `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to modify.\n     * @param {...(number|number[])} [indexes] The indexes of elements to remove.\n     * @returns {Array} Returns the new array of removed elements.\n     * @example\n     *\n     * var array = ['a', 'b', 'c', 'd'];\n     * var pulled = _.pullAt(array, [1, 3]);\n     *\n     * console.log(array);\n     * // => ['a', 'c']\n     *\n     * console.log(pulled);\n     * // => ['b', 'd']\n     */\n    var pullAt = flatRest(function(array, indexes) {\n      var length = array == null ? 0 : array.length,\n          result = baseAt(array, indexes);\n\n      basePullAt(array, arrayMap(indexes, function(index) {\n        return isIndex(index, length) ? +index : index;\n      }).sort(compareAscending));\n\n      return result;\n    });\n\n    /**\n     * Removes all elements from `array` that `predicate` returns truthy for\n     * and returns an array of the removed elements. The predicate is invoked\n     * with three arguments: (value, index, array).\n     *\n     * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`\n     * to pull elements from an array by value.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @category Array\n     * @param {Array} array The array to modify.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the new array of removed elements.\n     * @example\n     *\n     * var array = [1, 2, 3, 4];\n     * var evens = _.remove(array, function(n) {\n     *   return n % 2 == 0;\n     * });\n     *\n     * console.log(array);\n     * // => [1, 3]\n     *\n     * console.log(evens);\n     * // => [2, 4]\n     */\n    function remove(array, predicate) {\n      var result = [];\n      if (!(array && array.length)) {\n        return result;\n      }\n      var index = -1,\n          indexes = [],\n          length = array.length;\n\n      predicate = getIteratee(predicate, 3);\n      while (++index < length) {\n        var value = array[index];\n        if (predicate(value, index, array)) {\n          result.push(value);\n          indexes.push(index);\n        }\n      }\n      basePullAt(array, indexes);\n      return result;\n    }\n\n    /**\n     * Reverses `array` so that the first element becomes the last, the second\n     * element becomes the second to last, and so on.\n     *\n     * **Note:** This method mutates `array` and is based on\n     * [`Array#reverse`](https://mdn.io/Array/reverse).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to modify.\n     * @returns {Array} Returns `array`.\n     * @example\n     *\n     * var array = [1, 2, 3];\n     *\n     * _.reverse(array);\n     * // => [3, 2, 1]\n     *\n     * console.log(array);\n     * // => [3, 2, 1]\n     */\n    function reverse(array) {\n      return array == null ? array : nativeReverse.call(array);\n    }\n\n    /**\n     * Creates a slice of `array` from `start` up to, but not including, `end`.\n     *\n     * **Note:** This method is used instead of\n     * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are\n     * returned.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to slice.\n     * @param {number} [start=0] The start position.\n     * @param {number} [end=array.length] The end position.\n     * @returns {Array} Returns the slice of `array`.\n     */\n    function slice(array, start, end) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return [];\n      }\n      if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {\n        start = 0;\n        end = length;\n      }\n      else {\n        start = start == null ? 0 : toInteger(start);\n        end = end === undefined ? length : toInteger(end);\n      }\n      return baseSlice(array, start, end);\n    }\n\n    /**\n     * Uses a binary search to determine the lowest index at which `value`\n     * should be inserted into `array` in order to maintain its sort order.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The sorted array to inspect.\n     * @param {*} value The value to evaluate.\n     * @returns {number} Returns the index at which `value` should be inserted\n     *  into `array`.\n     * @example\n     *\n     * _.sortedIndex([30, 50], 40);\n     * // => 1\n     */\n    function sortedIndex(array, value) {\n      return baseSortedIndex(array, value);\n    }\n\n    /**\n     * This method is like `_.sortedIndex` except that it accepts `iteratee`\n     * which is invoked for `value` and each element of `array` to compute their\n     * sort ranking. The iteratee is invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The sorted array to inspect.\n     * @param {*} value The value to evaluate.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {number} Returns the index at which `value` should be inserted\n     *  into `array`.\n     * @example\n     *\n     * var objects = [{ 'x': 4 }, { 'x': 5 }];\n     *\n     * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n     * // => 0\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.sortedIndexBy(objects, { 'x': 4 }, 'x');\n     * // => 0\n     */\n    function sortedIndexBy(array, value, iteratee) {\n      return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));\n    }\n\n    /**\n     * This method is like `_.indexOf` except that it performs a binary\n     * search on a sorted `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {*} value The value to search for.\n     * @returns {number} Returns the index of the matched value, else `-1`.\n     * @example\n     *\n     * _.sortedIndexOf([4, 5, 5, 5, 6], 5);\n     * // => 1\n     */\n    function sortedIndexOf(array, value) {\n      var length = array == null ? 0 : array.length;\n      if (length) {\n        var index = baseSortedIndex(array, value);\n        if (index < length && eq(array[index], value)) {\n          return index;\n        }\n      }\n      return -1;\n    }\n\n    /**\n     * This method is like `_.sortedIndex` except that it returns the highest\n     * index at which `value` should be inserted into `array` in order to\n     * maintain its sort order.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The sorted array to inspect.\n     * @param {*} value The value to evaluate.\n     * @returns {number} Returns the index at which `value` should be inserted\n     *  into `array`.\n     * @example\n     *\n     * _.sortedLastIndex([4, 5, 5, 5, 6], 5);\n     * // => 4\n     */\n    function sortedLastIndex(array, value) {\n      return baseSortedIndex(array, value, true);\n    }\n\n    /**\n     * This method is like `_.sortedLastIndex` except that it accepts `iteratee`\n     * which is invoked for `value` and each element of `array` to compute their\n     * sort ranking. The iteratee is invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The sorted array to inspect.\n     * @param {*} value The value to evaluate.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {number} Returns the index at which `value` should be inserted\n     *  into `array`.\n     * @example\n     *\n     * var objects = [{ 'x': 4 }, { 'x': 5 }];\n     *\n     * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n     * // => 1\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');\n     * // => 1\n     */\n    function sortedLastIndexBy(array, value, iteratee) {\n      return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);\n    }\n\n    /**\n     * This method is like `_.lastIndexOf` except that it performs a binary\n     * search on a sorted `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {*} value The value to search for.\n     * @returns {number} Returns the index of the matched value, else `-1`.\n     * @example\n     *\n     * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);\n     * // => 3\n     */\n    function sortedLastIndexOf(array, value) {\n      var length = array == null ? 0 : array.length;\n      if (length) {\n        var index = baseSortedIndex(array, value, true) - 1;\n        if (eq(array[index], value)) {\n          return index;\n        }\n      }\n      return -1;\n    }\n\n    /**\n     * This method is like `_.uniq` except that it's designed and optimized\n     * for sorted arrays.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @returns {Array} Returns the new duplicate free array.\n     * @example\n     *\n     * _.sortedUniq([1, 1, 2]);\n     * // => [1, 2]\n     */\n    function sortedUniq(array) {\n      return (array && array.length)\n        ? baseSortedUniq(array)\n        : [];\n    }\n\n    /**\n     * This method is like `_.uniqBy` except that it's designed and optimized\n     * for sorted arrays.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {Function} [iteratee] The iteratee invoked per element.\n     * @returns {Array} Returns the new duplicate free array.\n     * @example\n     *\n     * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);\n     * // => [1.1, 2.3]\n     */\n    function sortedUniqBy(array, iteratee) {\n      return (array && array.length)\n        ? baseSortedUniq(array, getIteratee(iteratee, 2))\n        : [];\n    }\n\n    /**\n     * Gets all but the first element of `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * _.tail([1, 2, 3]);\n     * // => [2, 3]\n     */\n    function tail(array) {\n      var length = array == null ? 0 : array.length;\n      return length ? baseSlice(array, 1, length) : [];\n    }\n\n    /**\n     * Creates a slice of `array` with `n` elements taken from the beginning.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @param {number} [n=1] The number of elements to take.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * _.take([1, 2, 3]);\n     * // => [1]\n     *\n     * _.take([1, 2, 3], 2);\n     * // => [1, 2]\n     *\n     * _.take([1, 2, 3], 5);\n     * // => [1, 2, 3]\n     *\n     * _.take([1, 2, 3], 0);\n     * // => []\n     */\n    function take(array, n, guard) {\n      if (!(array && array.length)) {\n        return [];\n      }\n      n = (guard || n === undefined) ? 1 : toInteger(n);\n      return baseSlice(array, 0, n < 0 ? 0 : n);\n    }\n\n    /**\n     * Creates a slice of `array` with `n` elements taken from the end.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @param {number} [n=1] The number of elements to take.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * _.takeRight([1, 2, 3]);\n     * // => [3]\n     *\n     * _.takeRight([1, 2, 3], 2);\n     * // => [2, 3]\n     *\n     * _.takeRight([1, 2, 3], 5);\n     * // => [1, 2, 3]\n     *\n     * _.takeRight([1, 2, 3], 0);\n     * // => []\n     */\n    function takeRight(array, n, guard) {\n      var length = array == null ? 0 : array.length;\n      if (!length) {\n        return [];\n      }\n      n = (guard || n === undefined) ? 1 : toInteger(n);\n      n = length - n;\n      return baseSlice(array, n < 0 ? 0 : n, length);\n    }\n\n    /**\n     * Creates a slice of `array` with elements taken from the end. Elements are\n     * taken until `predicate` returns falsey. The predicate is invoked with\n     * three arguments: (value, index, array).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney',  'active': true },\n     *   { 'user': 'fred',    'active': false },\n     *   { 'user': 'pebbles', 'active': false }\n     * ];\n     *\n     * _.takeRightWhile(users, function(o) { return !o.active; });\n     * // => objects for ['fred', 'pebbles']\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });\n     * // => objects for ['pebbles']\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.takeRightWhile(users, ['active', false]);\n     * // => objects for ['fred', 'pebbles']\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.takeRightWhile(users, 'active');\n     * // => []\n     */\n    function takeRightWhile(array, predicate) {\n      return (array && array.length)\n        ? baseWhile(array, getIteratee(predicate, 3), false, true)\n        : [];\n    }\n\n    /**\n     * Creates a slice of `array` with elements taken from the beginning. Elements\n     * are taken until `predicate` returns falsey. The predicate is invoked with\n     * three arguments: (value, index, array).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Array\n     * @param {Array} array The array to query.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the slice of `array`.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney',  'active': false },\n     *   { 'user': 'fred',    'active': false },\n     *   { 'user': 'pebbles', 'active': true }\n     * ];\n     *\n     * _.takeWhile(users, function(o) { return !o.active; });\n     * // => objects for ['barney', 'fred']\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.takeWhile(users, { 'user': 'barney', 'active': false });\n     * // => objects for ['barney']\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.takeWhile(users, ['active', false]);\n     * // => objects for ['barney', 'fred']\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.takeWhile(users, 'active');\n     * // => []\n     */\n    function takeWhile(array, predicate) {\n      return (array && array.length)\n        ? baseWhile(array, getIteratee(predicate, 3))\n        : [];\n    }\n\n    /**\n     * Creates an array of unique values, in order, from all given arrays using\n     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * for equality comparisons.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to inspect.\n     * @returns {Array} Returns the new array of combined values.\n     * @example\n     *\n     * _.union([2], [1, 2]);\n     * // => [2, 1]\n     */\n    var union = baseRest(function(arrays) {\n      return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n    });\n\n    /**\n     * This method is like `_.union` except that it accepts `iteratee` which is\n     * invoked for each element of each `arrays` to generate the criterion by\n     * which uniqueness is computed. Result values are chosen from the first\n     * array in which the value occurs. The iteratee is invoked with one argument:\n     * (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to inspect.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {Array} Returns the new array of combined values.\n     * @example\n     *\n     * _.unionBy([2.1], [1.2, 2.3], Math.floor);\n     * // => [2.1, 1.2]\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n     * // => [{ 'x': 1 }, { 'x': 2 }]\n     */\n    var unionBy = baseRest(function(arrays) {\n      var iteratee = last(arrays);\n      if (isArrayLikeObject(iteratee)) {\n        iteratee = undefined;\n      }\n      return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));\n    });\n\n    /**\n     * This method is like `_.union` except that it accepts `comparator` which\n     * is invoked to compare elements of `arrays`. Result values are chosen from\n     * the first array in which the value occurs. The comparator is invoked\n     * with two arguments: (arrVal, othVal).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to inspect.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns the new array of combined values.\n     * @example\n     *\n     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n     * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n     *\n     * _.unionWith(objects, others, _.isEqual);\n     * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n     */\n    var unionWith = baseRest(function(arrays) {\n      var comparator = last(arrays);\n      comparator = typeof comparator == 'function' ? comparator : undefined;\n      return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);\n    });\n\n    /**\n     * Creates a duplicate-free version of an array, using\n     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * for equality comparisons, in which only the first occurrence of each element\n     * is kept. The order of result values is determined by the order they occur\n     * in the array.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @returns {Array} Returns the new duplicate free array.\n     * @example\n     *\n     * _.uniq([2, 1, 2]);\n     * // => [2, 1]\n     */\n    function uniq(array) {\n      return (array && array.length) ? baseUniq(array) : [];\n    }\n\n    /**\n     * This method is like `_.uniq` except that it accepts `iteratee` which is\n     * invoked for each element in `array` to generate the criterion by which\n     * uniqueness is computed. The order of result values is determined by the\n     * order they occur in the array. The iteratee is invoked with one argument:\n     * (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {Array} Returns the new duplicate free array.\n     * @example\n     *\n     * _.uniqBy([2.1, 1.2, 2.3], Math.floor);\n     * // => [2.1, 1.2]\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n     * // => [{ 'x': 1 }, { 'x': 2 }]\n     */\n    function uniqBy(array, iteratee) {\n      return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];\n    }\n\n    /**\n     * This method is like `_.uniq` except that it accepts `comparator` which\n     * is invoked to compare elements of `array`. The order of result values is\n     * determined by the order they occur in the array.The comparator is invoked\n     * with two arguments: (arrVal, othVal).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns the new duplicate free array.\n     * @example\n     *\n     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n     *\n     * _.uniqWith(objects, _.isEqual);\n     * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n     */\n    function uniqWith(array, comparator) {\n      comparator = typeof comparator == 'function' ? comparator : undefined;\n      return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n    }\n\n    /**\n     * This method is like `_.zip` except that it accepts an array of grouped\n     * elements and creates an array regrouping the elements to their pre-zip\n     * configuration.\n     *\n     * @static\n     * @memberOf _\n     * @since 1.2.0\n     * @category Array\n     * @param {Array} array The array of grouped elements to process.\n     * @returns {Array} Returns the new array of regrouped elements.\n     * @example\n     *\n     * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);\n     * // => [['a', 1, true], ['b', 2, false]]\n     *\n     * _.unzip(zipped);\n     * // => [['a', 'b'], [1, 2], [true, false]]\n     */\n    function unzip(array) {\n      if (!(array && array.length)) {\n        return [];\n      }\n      var length = 0;\n      array = arrayFilter(array, function(group) {\n        if (isArrayLikeObject(group)) {\n          length = nativeMax(group.length, length);\n          return true;\n        }\n      });\n      return baseTimes(length, function(index) {\n        return arrayMap(array, baseProperty(index));\n      });\n    }\n\n    /**\n     * This method is like `_.unzip` except that it accepts `iteratee` to specify\n     * how regrouped values should be combined. The iteratee is invoked with the\n     * elements of each group: (...group).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.8.0\n     * @category Array\n     * @param {Array} array The array of grouped elements to process.\n     * @param {Function} [iteratee=_.identity] The function to combine\n     *  regrouped values.\n     * @returns {Array} Returns the new array of regrouped elements.\n     * @example\n     *\n     * var zipped = _.zip([1, 2], [10, 20], [100, 200]);\n     * // => [[1, 10, 100], [2, 20, 200]]\n     *\n     * _.unzipWith(zipped, _.add);\n     * // => [3, 30, 300]\n     */\n    function unzipWith(array, iteratee) {\n      if (!(array && array.length)) {\n        return [];\n      }\n      var result = unzip(array);\n      if (iteratee == null) {\n        return result;\n      }\n      return arrayMap(result, function(group) {\n        return apply(iteratee, undefined, group);\n      });\n    }\n\n    /**\n     * Creates an array excluding all given values using\n     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * for equality comparisons.\n     *\n     * **Note:** Unlike `_.pull`, this method returns a new array.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {Array} array The array to inspect.\n     * @param {...*} [values] The values to exclude.\n     * @returns {Array} Returns the new array of filtered values.\n     * @see _.difference, _.xor\n     * @example\n     *\n     * _.without([2, 1, 2, 3], 1, 2);\n     * // => [3]\n     */\n    var without = baseRest(function(array, values) {\n      return isArrayLikeObject(array)\n        ? baseDifference(array, values)\n        : [];\n    });\n\n    /**\n     * Creates an array of unique values that is the\n     * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)\n     * of the given arrays. The order of result values is determined by the order\n     * they occur in the arrays.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.4.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to inspect.\n     * @returns {Array} Returns the new array of filtered values.\n     * @see _.difference, _.without\n     * @example\n     *\n     * _.xor([2, 1], [2, 3]);\n     * // => [1, 3]\n     */\n    var xor = baseRest(function(arrays) {\n      return baseXor(arrayFilter(arrays, isArrayLikeObject));\n    });\n\n    /**\n     * This method is like `_.xor` except that it accepts `iteratee` which is\n     * invoked for each element of each `arrays` to generate the criterion by\n     * which by which they're compared. The order of result values is determined\n     * by the order they occur in the arrays. The iteratee is invoked with one\n     * argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to inspect.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {Array} Returns the new array of filtered values.\n     * @example\n     *\n     * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n     * // => [1.2, 3.4]\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n     * // => [{ 'x': 2 }]\n     */\n    var xorBy = baseRest(function(arrays) {\n      var iteratee = last(arrays);\n      if (isArrayLikeObject(iteratee)) {\n        iteratee = undefined;\n      }\n      return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));\n    });\n\n    /**\n     * This method is like `_.xor` except that it accepts `comparator` which is\n     * invoked to compare elements of `arrays`. The order of result values is\n     * determined by the order they occur in the arrays. The comparator is invoked\n     * with two arguments: (arrVal, othVal).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to inspect.\n     * @param {Function} [comparator] The comparator invoked per element.\n     * @returns {Array} Returns the new array of filtered values.\n     * @example\n     *\n     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n     * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n     *\n     * _.xorWith(objects, others, _.isEqual);\n     * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n     */\n    var xorWith = baseRest(function(arrays) {\n      var comparator = last(arrays);\n      comparator = typeof comparator == 'function' ? comparator : undefined;\n      return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);\n    });\n\n    /**\n     * Creates an array of grouped elements, the first of which contains the\n     * first elements of the given arrays, the second of which contains the\n     * second elements of the given arrays, and so on.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to process.\n     * @returns {Array} Returns the new array of grouped elements.\n     * @example\n     *\n     * _.zip(['a', 'b'], [1, 2], [true, false]);\n     * // => [['a', 1, true], ['b', 2, false]]\n     */\n    var zip = baseRest(unzip);\n\n    /**\n     * This method is like `_.fromPairs` except that it accepts two arrays,\n     * one of property identifiers and one of corresponding values.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.4.0\n     * @category Array\n     * @param {Array} [props=[]] The property identifiers.\n     * @param {Array} [values=[]] The property values.\n     * @returns {Object} Returns the new object.\n     * @example\n     *\n     * _.zipObject(['a', 'b'], [1, 2]);\n     * // => { 'a': 1, 'b': 2 }\n     */\n    function zipObject(props, values) {\n      return baseZipObject(props || [], values || [], assignValue);\n    }\n\n    /**\n     * This method is like `_.zipObject` except that it supports property paths.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.1.0\n     * @category Array\n     * @param {Array} [props=[]] The property identifiers.\n     * @param {Array} [values=[]] The property values.\n     * @returns {Object} Returns the new object.\n     * @example\n     *\n     * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);\n     * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }\n     */\n    function zipObjectDeep(props, values) {\n      return baseZipObject(props || [], values || [], baseSet);\n    }\n\n    /**\n     * This method is like `_.zip` except that it accepts `iteratee` to specify\n     * how grouped values should be combined. The iteratee is invoked with the\n     * elements of each group: (...group).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.8.0\n     * @category Array\n     * @param {...Array} [arrays] The arrays to process.\n     * @param {Function} [iteratee=_.identity] The function to combine\n     *  grouped values.\n     * @returns {Array} Returns the new array of grouped elements.\n     * @example\n     *\n     * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {\n     *   return a + b + c;\n     * });\n     * // => [111, 222]\n     */\n    var zipWith = baseRest(function(arrays) {\n      var length = arrays.length,\n          iteratee = length > 1 ? arrays[length - 1] : undefined;\n\n      iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;\n      return unzipWith(arrays, iteratee);\n    });\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates a `lodash` wrapper instance that wraps `value` with explicit method\n     * chain sequences enabled. The result of such sequences must be unwrapped\n     * with `_#value`.\n     *\n     * @static\n     * @memberOf _\n     * @since 1.3.0\n     * @category Seq\n     * @param {*} value The value to wrap.\n     * @returns {Object} Returns the new `lodash` wrapper instance.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney',  'age': 36 },\n     *   { 'user': 'fred',    'age': 40 },\n     *   { 'user': 'pebbles', 'age': 1 }\n     * ];\n     *\n     * var youngest = _\n     *   .chain(users)\n     *   .sortBy('age')\n     *   .map(function(o) {\n     *     return o.user + ' is ' + o.age;\n     *   })\n     *   .head()\n     *   .value();\n     * // => 'pebbles is 1'\n     */\n    function chain(value) {\n      var result = lodash(value);\n      result.__chain__ = true;\n      return result;\n    }\n\n    /**\n     * This method invokes `interceptor` and returns `value`. The interceptor\n     * is invoked with one argument; (value). The purpose of this method is to\n     * \"tap into\" a method chain sequence in order to modify intermediate results.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Seq\n     * @param {*} value The value to provide to `interceptor`.\n     * @param {Function} interceptor The function to invoke.\n     * @returns {*} Returns `value`.\n     * @example\n     *\n     * _([1, 2, 3])\n     *  .tap(function(array) {\n     *    // Mutate input array.\n     *    array.pop();\n     *  })\n     *  .reverse()\n     *  .value();\n     * // => [2, 1]\n     */\n    function tap(value, interceptor) {\n      interceptor(value);\n      return value;\n    }\n\n    /**\n     * This method is like `_.tap` except that it returns the result of `interceptor`.\n     * The purpose of this method is to \"pass thru\" values replacing intermediate\n     * results in a method chain sequence.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Seq\n     * @param {*} value The value to provide to `interceptor`.\n     * @param {Function} interceptor The function to invoke.\n     * @returns {*} Returns the result of `interceptor`.\n     * @example\n     *\n     * _('  abc  ')\n     *  .chain()\n     *  .trim()\n     *  .thru(function(value) {\n     *    return [value];\n     *  })\n     *  .value();\n     * // => ['abc']\n     */\n    function thru(value, interceptor) {\n      return interceptor(value);\n    }\n\n    /**\n     * This method is the wrapper version of `_.at`.\n     *\n     * @name at\n     * @memberOf _\n     * @since 1.0.0\n     * @category Seq\n     * @param {...(string|string[])} [paths] The property paths to pick.\n     * @returns {Object} Returns the new `lodash` wrapper instance.\n     * @example\n     *\n     * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n     *\n     * _(object).at(['a[0].b.c', 'a[1]']).value();\n     * // => [3, 4]\n     */\n    var wrapperAt = flatRest(function(paths) {\n      var length = paths.length,\n          start = length ? paths[0] : 0,\n          value = this.__wrapped__,\n          interceptor = function(object) { return baseAt(object, paths); };\n\n      if (length > 1 || this.__actions__.length ||\n          !(value instanceof LazyWrapper) || !isIndex(start)) {\n        return this.thru(interceptor);\n      }\n      value = value.slice(start, +start + (length ? 1 : 0));\n      value.__actions__.push({\n        'func': thru,\n        'args': [interceptor],\n        'thisArg': undefined\n      });\n      return new LodashWrapper(value, this.__chain__).thru(function(array) {\n        if (length && !array.length) {\n          array.push(undefined);\n        }\n        return array;\n      });\n    });\n\n    /**\n     * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.\n     *\n     * @name chain\n     * @memberOf _\n     * @since 0.1.0\n     * @category Seq\n     * @returns {Object} Returns the new `lodash` wrapper instance.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney', 'age': 36 },\n     *   { 'user': 'fred',   'age': 40 }\n     * ];\n     *\n     * // A sequence without explicit chaining.\n     * _(users).head();\n     * // => { 'user': 'barney', 'age': 36 }\n     *\n     * // A sequence with explicit chaining.\n     * _(users)\n     *   .chain()\n     *   .head()\n     *   .pick('user')\n     *   .value();\n     * // => { 'user': 'barney' }\n     */\n    function wrapperChain() {\n      return chain(this);\n    }\n\n    /**\n     * Executes the chain sequence and returns the wrapped result.\n     *\n     * @name commit\n     * @memberOf _\n     * @since 3.2.0\n     * @category Seq\n     * @returns {Object} Returns the new `lodash` wrapper instance.\n     * @example\n     *\n     * var array = [1, 2];\n     * var wrapped = _(array).push(3);\n     *\n     * console.log(array);\n     * // => [1, 2]\n     *\n     * wrapped = wrapped.commit();\n     * console.log(array);\n     * // => [1, 2, 3]\n     *\n     * wrapped.last();\n     * // => 3\n     *\n     * console.log(array);\n     * // => [1, 2, 3]\n     */\n    function wrapperCommit() {\n      return new LodashWrapper(this.value(), this.__chain__);\n    }\n\n    /**\n     * Gets the next value on a wrapped object following the\n     * [iterator protocol](https://mdn.io/iteration_protocols#iterator).\n     *\n     * @name next\n     * @memberOf _\n     * @since 4.0.0\n     * @category Seq\n     * @returns {Object} Returns the next iterator value.\n     * @example\n     *\n     * var wrapped = _([1, 2]);\n     *\n     * wrapped.next();\n     * // => { 'done': false, 'value': 1 }\n     *\n     * wrapped.next();\n     * // => { 'done': false, 'value': 2 }\n     *\n     * wrapped.next();\n     * // => { 'done': true, 'value': undefined }\n     */\n    function wrapperNext() {\n      if (this.__values__ === undefined) {\n        this.__values__ = toArray(this.value());\n      }\n      var done = this.__index__ >= this.__values__.length,\n          value = done ? undefined : this.__values__[this.__index__++];\n\n      return { 'done': done, 'value': value };\n    }\n\n    /**\n     * Enables the wrapper to be iterable.\n     *\n     * @name Symbol.iterator\n     * @memberOf _\n     * @since 4.0.0\n     * @category Seq\n     * @returns {Object} Returns the wrapper object.\n     * @example\n     *\n     * var wrapped = _([1, 2]);\n     *\n     * wrapped[Symbol.iterator]() === wrapped;\n     * // => true\n     *\n     * Array.from(wrapped);\n     * // => [1, 2]\n     */\n    function wrapperToIterator() {\n      return this;\n    }\n\n    /**\n     * Creates a clone of the chain sequence planting `value` as the wrapped value.\n     *\n     * @name plant\n     * @memberOf _\n     * @since 3.2.0\n     * @category Seq\n     * @param {*} value The value to plant.\n     * @returns {Object} Returns the new `lodash` wrapper instance.\n     * @example\n     *\n     * function square(n) {\n     *   return n * n;\n     * }\n     *\n     * var wrapped = _([1, 2]).map(square);\n     * var other = wrapped.plant([3, 4]);\n     *\n     * other.value();\n     * // => [9, 16]\n     *\n     * wrapped.value();\n     * // => [1, 4]\n     */\n    function wrapperPlant(value) {\n      var result,\n          parent = this;\n\n      while (parent instanceof baseLodash) {\n        var clone = wrapperClone(parent);\n        clone.__index__ = 0;\n        clone.__values__ = undefined;\n        if (result) {\n          previous.__wrapped__ = clone;\n        } else {\n          result = clone;\n        }\n        var previous = clone;\n        parent = parent.__wrapped__;\n      }\n      previous.__wrapped__ = value;\n      return result;\n    }\n\n    /**\n     * This method is the wrapper version of `_.reverse`.\n     *\n     * **Note:** This method mutates the wrapped array.\n     *\n     * @name reverse\n     * @memberOf _\n     * @since 0.1.0\n     * @category Seq\n     * @returns {Object} Returns the new `lodash` wrapper instance.\n     * @example\n     *\n     * var array = [1, 2, 3];\n     *\n     * _(array).reverse().value()\n     * // => [3, 2, 1]\n     *\n     * console.log(array);\n     * // => [3, 2, 1]\n     */\n    function wrapperReverse() {\n      var value = this.__wrapped__;\n      if (value instanceof LazyWrapper) {\n        var wrapped = value;\n        if (this.__actions__.length) {\n          wrapped = new LazyWrapper(this);\n        }\n        wrapped = wrapped.reverse();\n        wrapped.__actions__.push({\n          'func': thru,\n          'args': [reverse],\n          'thisArg': undefined\n        });\n        return new LodashWrapper(wrapped, this.__chain__);\n      }\n      return this.thru(reverse);\n    }\n\n    /**\n     * Executes the chain sequence to resolve the unwrapped value.\n     *\n     * @name value\n     * @memberOf _\n     * @since 0.1.0\n     * @alias toJSON, valueOf\n     * @category Seq\n     * @returns {*} Returns the resolved unwrapped value.\n     * @example\n     *\n     * _([1, 2, 3]).value();\n     * // => [1, 2, 3]\n     */\n    function wrapperValue() {\n      return baseWrapperValue(this.__wrapped__, this.__actions__);\n    }\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Creates an object composed of keys generated from the results of running\n     * each element of `collection` thru `iteratee`. The corresponding value of\n     * each key is the number of times the key was returned by `iteratee`. The\n     * iteratee is invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 0.5.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n     * @returns {Object} Returns the composed aggregate object.\n     * @example\n     *\n     * _.countBy([6.1, 4.2, 6.3], Math.floor);\n     * // => { '4': 1, '6': 2 }\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.countBy(['one', 'two', 'three'], 'length');\n     * // => { '3': 2, '5': 1 }\n     */\n    var countBy = createAggregator(function(result, value, key) {\n      if (hasOwnProperty.call(result, key)) {\n        ++result[key];\n      } else {\n        baseAssignValue(result, key, 1);\n      }\n    });\n\n    /**\n     * Checks if `predicate` returns truthy for **all** elements of `collection`.\n     * Iteration is stopped once `predicate` returns falsey. The predicate is\n     * invoked with three arguments: (value, index|key, collection).\n     *\n     * **Note:** This method returns `true` for\n     * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n     * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n     * elements of empty collections.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {boolean} Returns `true` if all elements pass the predicate check,\n     *  else `false`.\n     * @example\n     *\n     * _.every([true, 1, null, 'yes'], Boolean);\n     * // => false\n     *\n     * var users = [\n     *   { 'user': 'barney', 'age': 36, 'active': false },\n     *   { 'user': 'fred',   'age': 40, 'active': false }\n     * ];\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.every(users, { 'user': 'barney', 'active': false });\n     * // => false\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.every(users, ['active', false]);\n     * // => true\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.every(users, 'active');\n     * // => false\n     */\n    function every(collection, predicate, guard) {\n      var func = isArray(collection) ? arrayEvery : baseEvery;\n      if (guard && isIterateeCall(collection, predicate, guard)) {\n        predicate = undefined;\n      }\n      return func(collection, getIteratee(predicate, 3));\n    }\n\n    /**\n     * Iterates over elements of `collection`, returning an array of all elements\n     * `predicate` returns truthy for. The predicate is invoked with three\n     * arguments: (value, index|key, collection).\n     *\n     * **Note:** Unlike `_.remove`, this method returns a new array.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the new filtered array.\n     * @see _.reject\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney', 'age': 36, 'active': true },\n     *   { 'user': 'fred',   'age': 40, 'active': false }\n     * ];\n     *\n     * _.filter(users, function(o) { return !o.active; });\n     * // => objects for ['fred']\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.filter(users, { 'age': 36, 'active': true });\n     * // => objects for ['barney']\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.filter(users, ['active', false]);\n     * // => objects for ['fred']\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.filter(users, 'active');\n     * // => objects for ['barney']\n     */\n    function filter(collection, predicate) {\n      var func = isArray(collection) ? arrayFilter : baseFilter;\n      return func(collection, getIteratee(predicate, 3));\n    }\n\n    /**\n     * Iterates over elements of `collection`, returning the first element\n     * `predicate` returns truthy for. The predicate is invoked with three\n     * arguments: (value, index|key, collection).\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to inspect.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @param {number} [fromIndex=0] The index to search from.\n     * @returns {*} Returns the matched element, else `undefined`.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney',  'age': 36, 'active': true },\n     *   { 'user': 'fred',    'age': 40, 'active': false },\n     *   { 'user': 'pebbles', 'age': 1,  'active': true }\n     * ];\n     *\n     * _.find(users, function(o) { return o.age < 40; });\n     * // => object for 'barney'\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.find(users, { 'age': 1, 'active': true });\n     * // => object for 'pebbles'\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.find(users, ['active', false]);\n     * // => object for 'fred'\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.find(users, 'active');\n     * // => object for 'barney'\n     */\n    var find = createFind(findIndex);\n\n    /**\n     * This method is like `_.find` except that it iterates over elements of\n     * `collection` from right to left.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to inspect.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @param {number} [fromIndex=collection.length-1] The index to search from.\n     * @returns {*} Returns the matched element, else `undefined`.\n     * @example\n     *\n     * _.findLast([1, 2, 3, 4], function(n) {\n     *   return n % 2 == 1;\n     * });\n     * // => 3\n     */\n    var findLast = createFind(findLastIndex);\n\n    /**\n     * Creates a flattened array of values by running each element in `collection`\n     * thru `iteratee` and flattening the mapped results. The iteratee is invoked\n     * with three arguments: (value, index|key, collection).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the new flattened array.\n     * @example\n     *\n     * function duplicate(n) {\n     *   return [n, n];\n     * }\n     *\n     * _.flatMap([1, 2], duplicate);\n     * // => [1, 1, 2, 2]\n     */\n    function flatMap(collection, iteratee) {\n      return baseFlatten(map(collection, iteratee), 1);\n    }\n\n    /**\n     * This method is like `_.flatMap` except that it recursively flattens the\n     * mapped results.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.7.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the new flattened array.\n     * @example\n     *\n     * function duplicate(n) {\n     *   return [[[n, n]]];\n     * }\n     *\n     * _.flatMapDeep([1, 2], duplicate);\n     * // => [1, 1, 2, 2]\n     */\n    function flatMapDeep(collection, iteratee) {\n      return baseFlatten(map(collection, iteratee), INFINITY);\n    }\n\n    /**\n     * This method is like `_.flatMap` except that it recursively flattens the\n     * mapped results up to `depth` times.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.7.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @param {number} [depth=1] The maximum recursion depth.\n     * @returns {Array} Returns the new flattened array.\n     * @example\n     *\n     * function duplicate(n) {\n     *   return [[[n, n]]];\n     * }\n     *\n     * _.flatMapDepth([1, 2], duplicate, 2);\n     * // => [[1, 1], [2, 2]]\n     */\n    function flatMapDepth(collection, iteratee, depth) {\n      depth = depth === undefined ? 1 : toInteger(depth);\n      return baseFlatten(map(collection, iteratee), depth);\n    }\n\n    /**\n     * Iterates over elements of `collection` and invokes `iteratee` for each element.\n     * The iteratee is invoked with three arguments: (value, index|key, collection).\n     * Iteratee functions may exit iteration early by explicitly returning `false`.\n     *\n     * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n     * property are iterated like arrays. To avoid this behavior use `_.forIn`\n     * or `_.forOwn` for object iteration.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @alias each\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Array|Object} Returns `collection`.\n     * @see _.forEachRight\n     * @example\n     *\n     * _.forEach([1, 2], function(value) {\n     *   console.log(value);\n     * });\n     * // => Logs `1` then `2`.\n     *\n     * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n     *   console.log(key);\n     * });\n     * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n     */\n    function forEach(collection, iteratee) {\n      var func = isArray(collection) ? arrayEach : baseEach;\n      return func(collection, getIteratee(iteratee, 3));\n    }\n\n    /**\n     * This method is like `_.forEach` except that it iterates over elements of\n     * `collection` from right to left.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @alias eachRight\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Array|Object} Returns `collection`.\n     * @see _.forEach\n     * @example\n     *\n     * _.forEachRight([1, 2], function(value) {\n     *   console.log(value);\n     * });\n     * // => Logs `2` then `1`.\n     */\n    function forEachRight(collection, iteratee) {\n      var func = isArray(collection) ? arrayEachRight : baseEachRight;\n      return func(collection, getIteratee(iteratee, 3));\n    }\n\n    /**\n     * Creates an object composed of keys generated from the results of running\n     * each element of `collection` thru `iteratee`. The order of grouped values\n     * is determined by the order they occur in `collection`. The corresponding\n     * value of each key is an array of elements responsible for generating the\n     * key. The iteratee is invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n     * @returns {Object} Returns the composed aggregate object.\n     * @example\n     *\n     * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n     * // => { '4': [4.2], '6': [6.1, 6.3] }\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.groupBy(['one', 'two', 'three'], 'length');\n     * // => { '3': ['one', 'two'], '5': ['three'] }\n     */\n    var groupBy = createAggregator(function(result, value, key) {\n      if (hasOwnProperty.call(result, key)) {\n        result[key].push(value);\n      } else {\n        baseAssignValue(result, key, [value]);\n      }\n    });\n\n    /**\n     * Checks if `value` is in `collection`. If `collection` is a string, it's\n     * checked for a substring of `value`, otherwise\n     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * is used for equality comparisons. If `fromIndex` is negative, it's used as\n     * the offset from the end of `collection`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object|string} collection The collection to inspect.\n     * @param {*} value The value to search for.\n     * @param {number} [fromIndex=0] The index to search from.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n     * @returns {boolean} Returns `true` if `value` is found, else `false`.\n     * @example\n     *\n     * _.includes([1, 2, 3], 1);\n     * // => true\n     *\n     * _.includes([1, 2, 3], 1, 2);\n     * // => false\n     *\n     * _.includes({ 'a': 1, 'b': 2 }, 1);\n     * // => true\n     *\n     * _.includes('abcd', 'bc');\n     * // => true\n     */\n    function includes(collection, value, fromIndex, guard) {\n      collection = isArrayLike(collection) ? collection : values(collection);\n      fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n      var length = collection.length;\n      if (fromIndex < 0) {\n        fromIndex = nativeMax(length + fromIndex, 0);\n      }\n      return isString(collection)\n        ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n        : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n    }\n\n    /**\n     * Invokes the method at `path` of each element in `collection`, returning\n     * an array of the results of each invoked method. Any additional arguments\n     * are provided to each invoked method. If `path` is a function, it's invoked\n     * for, and `this` bound to, each element in `collection`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Array|Function|string} path The path of the method to invoke or\n     *  the function invoked per iteration.\n     * @param {...*} [args] The arguments to invoke each method with.\n     * @returns {Array} Returns the array of results.\n     * @example\n     *\n     * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');\n     * // => [[1, 5, 7], [1, 2, 3]]\n     *\n     * _.invokeMap([123, 456], String.prototype.split, '');\n     * // => [['1', '2', '3'], ['4', '5', '6']]\n     */\n    var invokeMap = baseRest(function(collection, path, args) {\n      var index = -1,\n          isFunc = typeof path == 'function',\n          result = isArrayLike(collection) ? Array(collection.length) : [];\n\n      baseEach(collection, function(value) {\n        result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);\n      });\n      return result;\n    });\n\n    /**\n     * Creates an object composed of keys generated from the results of running\n     * each element of `collection` thru `iteratee`. The corresponding value of\n     * each key is the last element responsible for generating the key. The\n     * iteratee is invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n     * @returns {Object} Returns the composed aggregate object.\n     * @example\n     *\n     * var array = [\n     *   { 'dir': 'left', 'code': 97 },\n     *   { 'dir': 'right', 'code': 100 }\n     * ];\n     *\n     * _.keyBy(array, function(o) {\n     *   return String.fromCharCode(o.code);\n     * });\n     * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n     *\n     * _.keyBy(array, 'dir');\n     * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n     */\n    var keyBy = createAggregator(function(result, value, key) {\n      baseAssignValue(result, key, value);\n    });\n\n    /**\n     * Creates an array of values by running each element in `collection` thru\n     * `iteratee`. The iteratee is invoked with three arguments:\n     * (value, index|key, collection).\n     *\n     * Many lodash methods are guarded to work as iteratees for methods like\n     * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n     *\n     * The guarded methods are:\n     * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n     * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n     * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n     * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the new mapped array.\n     * @example\n     *\n     * function square(n) {\n     *   return n * n;\n     * }\n     *\n     * _.map([4, 8], square);\n     * // => [16, 64]\n     *\n     * _.map({ 'a': 4, 'b': 8 }, square);\n     * // => [16, 64] (iteration order is not guaranteed)\n     *\n     * var users = [\n     *   { 'user': 'barney' },\n     *   { 'user': 'fred' }\n     * ];\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.map(users, 'user');\n     * // => ['barney', 'fred']\n     */\n    function map(collection, iteratee) {\n      var func = isArray(collection) ? arrayMap : baseMap;\n      return func(collection, getIteratee(iteratee, 3));\n    }\n\n    /**\n     * This method is like `_.sortBy` except that it allows specifying the sort\n     * orders of the iteratees to sort by. If `orders` is unspecified, all values\n     * are sorted in ascending order. Otherwise, specify an order of \"desc\" for\n     * descending or \"asc\" for ascending sort order of corresponding values.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]\n     *  The iteratees to sort by.\n     * @param {string[]} [orders] The sort orders of `iteratees`.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n     * @returns {Array} Returns the new sorted array.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'fred',   'age': 48 },\n     *   { 'user': 'barney', 'age': 34 },\n     *   { 'user': 'fred',   'age': 40 },\n     *   { 'user': 'barney', 'age': 36 }\n     * ];\n     *\n     * // Sort by `user` in ascending order and by `age` in descending order.\n     * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);\n     * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n     */\n    function orderBy(collection, iteratees, orders, guard) {\n      if (collection == null) {\n        return [];\n      }\n      if (!isArray(iteratees)) {\n        iteratees = iteratees == null ? [] : [iteratees];\n      }\n      orders = guard ? undefined : orders;\n      if (!isArray(orders)) {\n        orders = orders == null ? [] : [orders];\n      }\n      return baseOrderBy(collection, iteratees, orders);\n    }\n\n    /**\n     * Creates an array of elements split into two groups, the first of which\n     * contains elements `predicate` returns truthy for, the second of which\n     * contains elements `predicate` returns falsey for. The predicate is\n     * invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the array of grouped elements.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney',  'age': 36, 'active': false },\n     *   { 'user': 'fred',    'age': 40, 'active': true },\n     *   { 'user': 'pebbles', 'age': 1,  'active': false }\n     * ];\n     *\n     * _.partition(users, function(o) { return o.active; });\n     * // => objects for [['fred'], ['barney', 'pebbles']]\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.partition(users, { 'age': 1, 'active': false });\n     * // => objects for [['pebbles'], ['barney', 'fred']]\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.partition(users, ['active', false]);\n     * // => objects for [['barney', 'pebbles'], ['fred']]\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.partition(users, 'active');\n     * // => objects for [['fred'], ['barney', 'pebbles']]\n     */\n    var partition = createAggregator(function(result, value, key) {\n      result[key ? 0 : 1].push(value);\n    }, function() { return [[], []]; });\n\n    /**\n     * Reduces `collection` to a value which is the accumulated result of running\n     * each element in `collection` thru `iteratee`, where each successive\n     * invocation is supplied the return value of the previous. If `accumulator`\n     * is not given, the first element of `collection` is used as the initial\n     * value. The iteratee is invoked with four arguments:\n     * (accumulator, value, index|key, collection).\n     *\n     * Many lodash methods are guarded to work as iteratees for methods like\n     * `_.reduce`, `_.reduceRight`, and `_.transform`.\n     *\n     * The guarded methods are:\n     * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n     * and `sortBy`\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @param {*} [accumulator] The initial value.\n     * @returns {*} Returns the accumulated value.\n     * @see _.reduceRight\n     * @example\n     *\n     * _.reduce([1, 2], function(sum, n) {\n     *   return sum + n;\n     * }, 0);\n     * // => 3\n     *\n     * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n     *   (result[value] || (result[value] = [])).push(key);\n     *   return result;\n     * }, {});\n     * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n     */\n    function reduce(collection, iteratee, accumulator) {\n      var func = isArray(collection) ? arrayReduce : baseReduce,\n          initAccum = arguments.length < 3;\n\n      return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n    }\n\n    /**\n     * This method is like `_.reduce` except that it iterates over elements of\n     * `collection` from right to left.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @param {*} [accumulator] The initial value.\n     * @returns {*} Returns the accumulated value.\n     * @see _.reduce\n     * @example\n     *\n     * var array = [[0, 1], [2, 3], [4, 5]];\n     *\n     * _.reduceRight(array, function(flattened, other) {\n     *   return flattened.concat(other);\n     * }, []);\n     * // => [4, 5, 2, 3, 0, 1]\n     */\n    function reduceRight(collection, iteratee, accumulator) {\n      var func = isArray(collection) ? arrayReduceRight : baseReduce,\n          initAccum = arguments.length < 3;\n\n      return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);\n    }\n\n    /**\n     * The opposite of `_.filter`; this method returns the elements of `collection`\n     * that `predicate` does **not** return truthy for.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the new filtered array.\n     * @see _.filter\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney', 'age': 36, 'active': false },\n     *   { 'user': 'fred',   'age': 40, 'active': true }\n     * ];\n     *\n     * _.reject(users, function(o) { return !o.active; });\n     * // => objects for ['fred']\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.reject(users, { 'age': 40, 'active': true });\n     * // => objects for ['barney']\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.reject(users, ['active', false]);\n     * // => objects for ['fred']\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.reject(users, 'active');\n     * // => objects for ['barney']\n     */\n    function reject(collection, predicate) {\n      var func = isArray(collection) ? arrayFilter : baseFilter;\n      return func(collection, negate(getIteratee(predicate, 3)));\n    }\n\n    /**\n     * Gets a random element from `collection`.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to sample.\n     * @returns {*} Returns the random element.\n     * @example\n     *\n     * _.sample([1, 2, 3, 4]);\n     * // => 2\n     */\n    function sample(collection) {\n      var func = isArray(collection) ? arraySample : baseSample;\n      return func(collection);\n    }\n\n    /**\n     * Gets `n` random elements at unique keys from `collection` up to the\n     * size of `collection`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to sample.\n     * @param {number} [n=1] The number of elements to sample.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Array} Returns the random elements.\n     * @example\n     *\n     * _.sampleSize([1, 2, 3], 2);\n     * // => [3, 1]\n     *\n     * _.sampleSize([1, 2, 3], 4);\n     * // => [2, 3, 1]\n     */\n    function sampleSize(collection, n, guard) {\n      if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {\n        n = 1;\n      } else {\n        n = toInteger(n);\n      }\n      var func = isArray(collection) ? arraySampleSize : baseSampleSize;\n      return func(collection, n);\n    }\n\n    /**\n     * Creates an array of shuffled values, using a version of the\n     * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to shuffle.\n     * @returns {Array} Returns the new shuffled array.\n     * @example\n     *\n     * _.shuffle([1, 2, 3, 4]);\n     * // => [4, 1, 3, 2]\n     */\n    function shuffle(collection) {\n      var func = isArray(collection) ? arrayShuffle : baseShuffle;\n      return func(collection);\n    }\n\n    /**\n     * Gets the size of `collection` by returning its length for array-like\n     * values or the number of own enumerable string keyed properties for objects.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object|string} collection The collection to inspect.\n     * @returns {number} Returns the collection size.\n     * @example\n     *\n     * _.size([1, 2, 3]);\n     * // => 3\n     *\n     * _.size({ 'a': 1, 'b': 2 });\n     * // => 2\n     *\n     * _.size('pebbles');\n     * // => 7\n     */\n    function size(collection) {\n      if (collection == null) {\n        return 0;\n      }\n      if (isArrayLike(collection)) {\n        return isString(collection) ? stringSize(collection) : collection.length;\n      }\n      var tag = getTag(collection);\n      if (tag == mapTag || tag == setTag) {\n        return collection.size;\n      }\n      return baseKeys(collection).length;\n    }\n\n    /**\n     * Checks if `predicate` returns truthy for **any** element of `collection`.\n     * Iteration is stopped once `predicate` returns truthy. The predicate is\n     * invoked with three arguments: (value, index|key, collection).\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {boolean} Returns `true` if any element passes the predicate check,\n     *  else `false`.\n     * @example\n     *\n     * _.some([null, 0, 'yes', false], Boolean);\n     * // => true\n     *\n     * var users = [\n     *   { 'user': 'barney', 'active': true },\n     *   { 'user': 'fred',   'active': false }\n     * ];\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.some(users, { 'user': 'barney', 'active': false });\n     * // => false\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.some(users, ['active', false]);\n     * // => true\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.some(users, 'active');\n     * // => true\n     */\n    function some(collection, predicate, guard) {\n      var func = isArray(collection) ? arraySome : baseSome;\n      if (guard && isIterateeCall(collection, predicate, guard)) {\n        predicate = undefined;\n      }\n      return func(collection, getIteratee(predicate, 3));\n    }\n\n    /**\n     * Creates an array of elements, sorted in ascending order by the results of\n     * running each element in a collection thru each iteratee. This method\n     * performs a stable sort, that is, it preserves the original sort order of\n     * equal elements. The iteratees are invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Collection\n     * @param {Array|Object} collection The collection to iterate over.\n     * @param {...(Function|Function[])} [iteratees=[_.identity]]\n     *  The iteratees to sort by.\n     * @returns {Array} Returns the new sorted array.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'fred',   'age': 48 },\n     *   { 'user': 'barney', 'age': 36 },\n     *   { 'user': 'fred',   'age': 40 },\n     *   { 'user': 'barney', 'age': 34 }\n     * ];\n     *\n     * _.sortBy(users, [function(o) { return o.user; }]);\n     * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n     *\n     * _.sortBy(users, ['user', 'age']);\n     * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]\n     */\n    var sortBy = baseRest(function(collection, iteratees) {\n      if (collection == null) {\n        return [];\n      }\n      var length = iteratees.length;\n      if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n        iteratees = [];\n      } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n        iteratees = [iteratees[0]];\n      }\n      return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n    });\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Gets the timestamp of the number of milliseconds that have elapsed since\n     * the Unix epoch (1 January 1970 00:00:00 UTC).\n     *\n     * @static\n     * @memberOf _\n     * @since 2.4.0\n     * @category Date\n     * @returns {number} Returns the timestamp.\n     * @example\n     *\n     * _.defer(function(stamp) {\n     *   console.log(_.now() - stamp);\n     * }, _.now());\n     * // => Logs the number of milliseconds it took for the deferred invocation.\n     */\n    var now = ctxNow || function() {\n      return root.Date.now();\n    };\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * The opposite of `_.before`; this method creates a function that invokes\n     * `func` once it's called `n` or more times.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Function\n     * @param {number} n The number of calls before `func` is invoked.\n     * @param {Function} func The function to restrict.\n     * @returns {Function} Returns the new restricted function.\n     * @example\n     *\n     * var saves = ['profile', 'settings'];\n     *\n     * var done = _.after(saves.length, function() {\n     *   console.log('done saving!');\n     * });\n     *\n     * _.forEach(saves, function(type) {\n     *   asyncSave({ 'type': type, 'complete': done });\n     * });\n     * // => Logs 'done saving!' after the two async saves have completed.\n     */\n    function after(n, func) {\n      if (typeof func != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      n = toInteger(n);\n      return function() {\n        if (--n < 1) {\n          return func.apply(this, arguments);\n        }\n      };\n    }\n\n    /**\n     * Creates a function that invokes `func`, with up to `n` arguments,\n     * ignoring any additional arguments.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Function\n     * @param {Function} func The function to cap arguments for.\n     * @param {number} [n=func.length] The arity cap.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Function} Returns the new capped function.\n     * @example\n     *\n     * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n     * // => [6, 8, 10]\n     */\n    function ary(func, n, guard) {\n      n = guard ? undefined : n;\n      n = (func && n == null) ? func.length : n;\n      return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);\n    }\n\n    /**\n     * Creates a function that invokes `func`, with the `this` binding and arguments\n     * of the created function, while it's called less than `n` times. Subsequent\n     * calls to the created function return the result of the last `func` invocation.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Function\n     * @param {number} n The number of calls at which `func` is no longer invoked.\n     * @param {Function} func The function to restrict.\n     * @returns {Function} Returns the new restricted function.\n     * @example\n     *\n     * jQuery(element).on('click', _.before(5, addContactToList));\n     * // => Allows adding up to 4 contacts to the list.\n     */\n    function before(n, func) {\n      var result;\n      if (typeof func != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      n = toInteger(n);\n      return function() {\n        if (--n > 0) {\n          result = func.apply(this, arguments);\n        }\n        if (n <= 1) {\n          func = undefined;\n        }\n        return result;\n      };\n    }\n\n    /**\n     * Creates a function that invokes `func` with the `this` binding of `thisArg`\n     * and `partials` prepended to the arguments it receives.\n     *\n     * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,\n     * may be used as a placeholder for partially applied arguments.\n     *\n     * **Note:** Unlike native `Function#bind`, this method doesn't set the \"length\"\n     * property of bound functions.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Function\n     * @param {Function} func The function to bind.\n     * @param {*} thisArg The `this` binding of `func`.\n     * @param {...*} [partials] The arguments to be partially applied.\n     * @returns {Function} Returns the new bound function.\n     * @example\n     *\n     * function greet(greeting, punctuation) {\n     *   return greeting + ' ' + this.user + punctuation;\n     * }\n     *\n     * var object = { 'user': 'fred' };\n     *\n     * var bound = _.bind(greet, object, 'hi');\n     * bound('!');\n     * // => 'hi fred!'\n     *\n     * // Bound with placeholders.\n     * var bound = _.bind(greet, object, _, '!');\n     * bound('hi');\n     * // => 'hi fred!'\n     */\n    var bind = baseRest(function(func, thisArg, partials) {\n      var bitmask = WRAP_BIND_FLAG;\n      if (partials.length) {\n        var holders = replaceHolders(partials, getHolder(bind));\n        bitmask |= WRAP_PARTIAL_FLAG;\n      }\n      return createWrap(func, bitmask, thisArg, partials, holders);\n    });\n\n    /**\n     * Creates a function that invokes the method at `object[key]` with `partials`\n     * prepended to the arguments it receives.\n     *\n     * This method differs from `_.bind` by allowing bound functions to reference\n     * methods that may be redefined or don't yet exist. See\n     * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)\n     * for more details.\n     *\n     * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic\n     * builds, may be used as a placeholder for partially applied arguments.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.10.0\n     * @category Function\n     * @param {Object} object The object to invoke the method on.\n     * @param {string} key The key of the method.\n     * @param {...*} [partials] The arguments to be partially applied.\n     * @returns {Function} Returns the new bound function.\n     * @example\n     *\n     * var object = {\n     *   'user': 'fred',\n     *   'greet': function(greeting, punctuation) {\n     *     return greeting + ' ' + this.user + punctuation;\n     *   }\n     * };\n     *\n     * var bound = _.bindKey(object, 'greet', 'hi');\n     * bound('!');\n     * // => 'hi fred!'\n     *\n     * object.greet = function(greeting, punctuation) {\n     *   return greeting + 'ya ' + this.user + punctuation;\n     * };\n     *\n     * bound('!');\n     * // => 'hiya fred!'\n     *\n     * // Bound with placeholders.\n     * var bound = _.bindKey(object, 'greet', _, '!');\n     * bound('hi');\n     * // => 'hiya fred!'\n     */\n    var bindKey = baseRest(function(object, key, partials) {\n      var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;\n      if (partials.length) {\n        var holders = replaceHolders(partials, getHolder(bindKey));\n        bitmask |= WRAP_PARTIAL_FLAG;\n      }\n      return createWrap(key, bitmask, object, partials, holders);\n    });\n\n    /**\n     * Creates a function that accepts arguments of `func` and either invokes\n     * `func` returning its result, if at least `arity` number of arguments have\n     * been provided, or returns a function that accepts the remaining `func`\n     * arguments, and so on. The arity of `func` may be specified if `func.length`\n     * is not sufficient.\n     *\n     * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n     * may be used as a placeholder for provided arguments.\n     *\n     * **Note:** This method doesn't set the \"length\" property of curried functions.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @category Function\n     * @param {Function} func The function to curry.\n     * @param {number} [arity=func.length] The arity of `func`.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Function} Returns the new curried function.\n     * @example\n     *\n     * var abc = function(a, b, c) {\n     *   return [a, b, c];\n     * };\n     *\n     * var curried = _.curry(abc);\n     *\n     * curried(1)(2)(3);\n     * // => [1, 2, 3]\n     *\n     * curried(1, 2)(3);\n     * // => [1, 2, 3]\n     *\n     * curried(1, 2, 3);\n     * // => [1, 2, 3]\n     *\n     * // Curried with placeholders.\n     * curried(1)(_, 3)(2);\n     * // => [1, 2, 3]\n     */\n    function curry(func, arity, guard) {\n      arity = guard ? undefined : arity;\n      var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n      result.placeholder = curry.placeholder;\n      return result;\n    }\n\n    /**\n     * This method is like `_.curry` except that arguments are applied to `func`\n     * in the manner of `_.partialRight` instead of `_.partial`.\n     *\n     * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic\n     * builds, may be used as a placeholder for provided arguments.\n     *\n     * **Note:** This method doesn't set the \"length\" property of curried functions.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Function\n     * @param {Function} func The function to curry.\n     * @param {number} [arity=func.length] The arity of `func`.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Function} Returns the new curried function.\n     * @example\n     *\n     * var abc = function(a, b, c) {\n     *   return [a, b, c];\n     * };\n     *\n     * var curried = _.curryRight(abc);\n     *\n     * curried(3)(2)(1);\n     * // => [1, 2, 3]\n     *\n     * curried(2, 3)(1);\n     * // => [1, 2, 3]\n     *\n     * curried(1, 2, 3);\n     * // => [1, 2, 3]\n     *\n     * // Curried with placeholders.\n     * curried(3)(1, _)(2);\n     * // => [1, 2, 3]\n     */\n    function curryRight(func, arity, guard) {\n      arity = guard ? undefined : arity;\n      var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n      result.placeholder = curryRight.placeholder;\n      return result;\n    }\n\n    /**\n     * Creates a debounced function that delays invoking `func` until after `wait`\n     * milliseconds have elapsed since the last time the debounced function was\n     * invoked. The debounced function comes with a `cancel` method to cancel\n     * delayed `func` invocations and a `flush` method to immediately invoke them.\n     * Provide `options` to indicate whether `func` should be invoked on the\n     * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n     * with the last arguments provided to the debounced function. Subsequent\n     * calls to the debounced function return the result of the last `func`\n     * invocation.\n     *\n     * **Note:** If `leading` and `trailing` options are `true`, `func` is\n     * invoked on the trailing edge of the timeout only if the debounced function\n     * is invoked more than once during the `wait` timeout.\n     *\n     * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n     * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n     *\n     * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n     * for details over the differences between `_.debounce` and `_.throttle`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Function\n     * @param {Function} func The function to debounce.\n     * @param {number} [wait=0] The number of milliseconds to delay.\n     * @param {Object} [options={}] The options object.\n     * @param {boolean} [options.leading=false]\n     *  Specify invoking on the leading edge of the timeout.\n     * @param {number} [options.maxWait]\n     *  The maximum time `func` is allowed to be delayed before it's invoked.\n     * @param {boolean} [options.trailing=true]\n     *  Specify invoking on the trailing edge of the timeout.\n     * @returns {Function} Returns the new debounced function.\n     * @example\n     *\n     * // Avoid costly calculations while the window size is in flux.\n     * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n     *\n     * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n     * jQuery(element).on('click', _.debounce(sendMail, 300, {\n     *   'leading': true,\n     *   'trailing': false\n     * }));\n     *\n     * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n     * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n     * var source = new EventSource('/stream');\n     * jQuery(source).on('message', debounced);\n     *\n     * // Cancel the trailing debounced invocation.\n     * jQuery(window).on('popstate', debounced.cancel);\n     */\n    function debounce(func, wait, options) {\n      var lastArgs,\n          lastThis,\n          maxWait,\n          result,\n          timerId,\n          lastCallTime,\n          lastInvokeTime = 0,\n          leading = false,\n          maxing = false,\n          trailing = true;\n\n      if (typeof func != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      wait = toNumber(wait) || 0;\n      if (isObject(options)) {\n        leading = !!options.leading;\n        maxing = 'maxWait' in options;\n        maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n        trailing = 'trailing' in options ? !!options.trailing : trailing;\n      }\n\n      function invokeFunc(time) {\n        var args = lastArgs,\n            thisArg = lastThis;\n\n        lastArgs = lastThis = undefined;\n        lastInvokeTime = time;\n        result = func.apply(thisArg, args);\n        return result;\n      }\n\n      function leadingEdge(time) {\n        // Reset any `maxWait` timer.\n        lastInvokeTime = time;\n        // Start the timer for the trailing edge.\n        timerId = setTimeout(timerExpired, wait);\n        // Invoke the leading edge.\n        return leading ? invokeFunc(time) : result;\n      }\n\n      function remainingWait(time) {\n        var timeSinceLastCall = time - lastCallTime,\n            timeSinceLastInvoke = time - lastInvokeTime,\n            timeWaiting = wait - timeSinceLastCall;\n\n        return maxing\n          ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n          : timeWaiting;\n      }\n\n      function shouldInvoke(time) {\n        var timeSinceLastCall = time - lastCallTime,\n            timeSinceLastInvoke = time - lastInvokeTime;\n\n        // Either this is the first call, activity has stopped and we're at the\n        // trailing edge, the system time has gone backwards and we're treating\n        // it as the trailing edge, or we've hit the `maxWait` limit.\n        return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n          (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n      }\n\n      function timerExpired() {\n        var time = now();\n        if (shouldInvoke(time)) {\n          return trailingEdge(time);\n        }\n        // Restart the timer.\n        timerId = setTimeout(timerExpired, remainingWait(time));\n      }\n\n      function trailingEdge(time) {\n        timerId = undefined;\n\n        // Only invoke if we have `lastArgs` which means `func` has been\n        // debounced at least once.\n        if (trailing && lastArgs) {\n          return invokeFunc(time);\n        }\n        lastArgs = lastThis = undefined;\n        return result;\n      }\n\n      function cancel() {\n        if (timerId !== undefined) {\n          clearTimeout(timerId);\n        }\n        lastInvokeTime = 0;\n        lastArgs = lastCallTime = lastThis = timerId = undefined;\n      }\n\n      function flush() {\n        return timerId === undefined ? result : trailingEdge(now());\n      }\n\n      function debounced() {\n        var time = now(),\n            isInvoking = shouldInvoke(time);\n\n        lastArgs = arguments;\n        lastThis = this;\n        lastCallTime = time;\n\n        if (isInvoking) {\n          if (timerId === undefined) {\n            return leadingEdge(lastCallTime);\n          }\n          if (maxing) {\n            // Handle invocations in a tight loop.\n            timerId = setTimeout(timerExpired, wait);\n            return invokeFunc(lastCallTime);\n          }\n        }\n        if (timerId === undefined) {\n          timerId = setTimeout(timerExpired, wait);\n        }\n        return result;\n      }\n      debounced.cancel = cancel;\n      debounced.flush = flush;\n      return debounced;\n    }\n\n    /**\n     * Defers invoking the `func` until the current call stack has cleared. Any\n     * additional arguments are provided to `func` when it's invoked.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Function\n     * @param {Function} func The function to defer.\n     * @param {...*} [args] The arguments to invoke `func` with.\n     * @returns {number} Returns the timer id.\n     * @example\n     *\n     * _.defer(function(text) {\n     *   console.log(text);\n     * }, 'deferred');\n     * // => Logs 'deferred' after one millisecond.\n     */\n    var defer = baseRest(function(func, args) {\n      return baseDelay(func, 1, args);\n    });\n\n    /**\n     * Invokes `func` after `wait` milliseconds. Any additional arguments are\n     * provided to `func` when it's invoked.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Function\n     * @param {Function} func The function to delay.\n     * @param {number} wait The number of milliseconds to delay invocation.\n     * @param {...*} [args] The arguments to invoke `func` with.\n     * @returns {number} Returns the timer id.\n     * @example\n     *\n     * _.delay(function(text) {\n     *   console.log(text);\n     * }, 1000, 'later');\n     * // => Logs 'later' after one second.\n     */\n    var delay = baseRest(function(func, wait, args) {\n      return baseDelay(func, toNumber(wait) || 0, args);\n    });\n\n    /**\n     * Creates a function that invokes `func` with arguments reversed.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Function\n     * @param {Function} func The function to flip arguments for.\n     * @returns {Function} Returns the new flipped function.\n     * @example\n     *\n     * var flipped = _.flip(function() {\n     *   return _.toArray(arguments);\n     * });\n     *\n     * flipped('a', 'b', 'c', 'd');\n     * // => ['d', 'c', 'b', 'a']\n     */\n    function flip(func) {\n      return createWrap(func, WRAP_FLIP_FLAG);\n    }\n\n    /**\n     * Creates a function that memoizes the result of `func`. If `resolver` is\n     * provided, it determines the cache key for storing the result based on the\n     * arguments provided to the memoized function. By default, the first argument\n     * provided to the memoized function is used as the map cache key. The `func`\n     * is invoked with the `this` binding of the memoized function.\n     *\n     * **Note:** The cache is exposed as the `cache` property on the memoized\n     * function. Its creation may be customized by replacing the `_.memoize.Cache`\n     * constructor with one whose instances implement the\n     * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n     * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Function\n     * @param {Function} func The function to have its output memoized.\n     * @param {Function} [resolver] The function to resolve the cache key.\n     * @returns {Function} Returns the new memoized function.\n     * @example\n     *\n     * var object = { 'a': 1, 'b': 2 };\n     * var other = { 'c': 3, 'd': 4 };\n     *\n     * var values = _.memoize(_.values);\n     * values(object);\n     * // => [1, 2]\n     *\n     * values(other);\n     * // => [3, 4]\n     *\n     * object.a = 2;\n     * values(object);\n     * // => [1, 2]\n     *\n     * // Modify the result cache.\n     * values.cache.set(object, ['a', 'b']);\n     * values(object);\n     * // => ['a', 'b']\n     *\n     * // Replace `_.memoize.Cache`.\n     * _.memoize.Cache = WeakMap;\n     */\n    function memoize(func, resolver) {\n      if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      var memoized = function() {\n        var args = arguments,\n            key = resolver ? resolver.apply(this, args) : args[0],\n            cache = memoized.cache;\n\n        if (cache.has(key)) {\n          return cache.get(key);\n        }\n        var result = func.apply(this, args);\n        memoized.cache = cache.set(key, result) || cache;\n        return result;\n      };\n      memoized.cache = new (memoize.Cache || MapCache);\n      return memoized;\n    }\n\n    // Expose `MapCache`.\n    memoize.Cache = MapCache;\n\n    /**\n     * Creates a function that negates the result of the predicate `func`. The\n     * `func` predicate is invoked with the `this` binding and arguments of the\n     * created function.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Function\n     * @param {Function} predicate The predicate to negate.\n     * @returns {Function} Returns the new negated function.\n     * @example\n     *\n     * function isEven(n) {\n     *   return n % 2 == 0;\n     * }\n     *\n     * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n     * // => [1, 3, 5]\n     */\n    function negate(predicate) {\n      if (typeof predicate != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      return function() {\n        var args = arguments;\n        switch (args.length) {\n          case 0: return !predicate.call(this);\n          case 1: return !predicate.call(this, args[0]);\n          case 2: return !predicate.call(this, args[0], args[1]);\n          case 3: return !predicate.call(this, args[0], args[1], args[2]);\n        }\n        return !predicate.apply(this, args);\n      };\n    }\n\n    /**\n     * Creates a function that is restricted to invoking `func` once. Repeat calls\n     * to the function return the value of the first invocation. The `func` is\n     * invoked with the `this` binding and arguments of the created function.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Function\n     * @param {Function} func The function to restrict.\n     * @returns {Function} Returns the new restricted function.\n     * @example\n     *\n     * var initialize = _.once(createApplication);\n     * initialize();\n     * initialize();\n     * // => `createApplication` is invoked once\n     */\n    function once(func) {\n      return before(2, func);\n    }\n\n    /**\n     * Creates a function that invokes `func` with its arguments transformed.\n     *\n     * @static\n     * @since 4.0.0\n     * @memberOf _\n     * @category Function\n     * @param {Function} func The function to wrap.\n     * @param {...(Function|Function[])} [transforms=[_.identity]]\n     *  The argument transforms.\n     * @returns {Function} Returns the new function.\n     * @example\n     *\n     * function doubled(n) {\n     *   return n * 2;\n     * }\n     *\n     * function square(n) {\n     *   return n * n;\n     * }\n     *\n     * var func = _.overArgs(function(x, y) {\n     *   return [x, y];\n     * }, [square, doubled]);\n     *\n     * func(9, 3);\n     * // => [81, 6]\n     *\n     * func(10, 5);\n     * // => [100, 10]\n     */\n    var overArgs = castRest(function(func, transforms) {\n      transforms = (transforms.length == 1 && isArray(transforms[0]))\n        ? arrayMap(transforms[0], baseUnary(getIteratee()))\n        : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));\n\n      var funcsLength = transforms.length;\n      return baseRest(function(args) {\n        var index = -1,\n            length = nativeMin(args.length, funcsLength);\n\n        while (++index < length) {\n          args[index] = transforms[index].call(this, args[index]);\n        }\n        return apply(func, this, args);\n      });\n    });\n\n    /**\n     * Creates a function that invokes `func` with `partials` prepended to the\n     * arguments it receives. This method is like `_.bind` except it does **not**\n     * alter the `this` binding.\n     *\n     * The `_.partial.placeholder` value, which defaults to `_` in monolithic\n     * builds, may be used as a placeholder for partially applied arguments.\n     *\n     * **Note:** This method doesn't set the \"length\" property of partially\n     * applied functions.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.2.0\n     * @category Function\n     * @param {Function} func The function to partially apply arguments to.\n     * @param {...*} [partials] The arguments to be partially applied.\n     * @returns {Function} Returns the new partially applied function.\n     * @example\n     *\n     * function greet(greeting, name) {\n     *   return greeting + ' ' + name;\n     * }\n     *\n     * var sayHelloTo = _.partial(greet, 'hello');\n     * sayHelloTo('fred');\n     * // => 'hello fred'\n     *\n     * // Partially applied with placeholders.\n     * var greetFred = _.partial(greet, _, 'fred');\n     * greetFred('hi');\n     * // => 'hi fred'\n     */\n    var partial = baseRest(function(func, partials) {\n      var holders = replaceHolders(partials, getHolder(partial));\n      return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);\n    });\n\n    /**\n     * This method is like `_.partial` except that partially applied arguments\n     * are appended to the arguments it receives.\n     *\n     * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic\n     * builds, may be used as a placeholder for partially applied arguments.\n     *\n     * **Note:** This method doesn't set the \"length\" property of partially\n     * applied functions.\n     *\n     * @static\n     * @memberOf _\n     * @since 1.0.0\n     * @category Function\n     * @param {Function} func The function to partially apply arguments to.\n     * @param {...*} [partials] The arguments to be partially applied.\n     * @returns {Function} Returns the new partially applied function.\n     * @example\n     *\n     * function greet(greeting, name) {\n     *   return greeting + ' ' + name;\n     * }\n     *\n     * var greetFred = _.partialRight(greet, 'fred');\n     * greetFred('hi');\n     * // => 'hi fred'\n     *\n     * // Partially applied with placeholders.\n     * var sayHelloTo = _.partialRight(greet, 'hello', _);\n     * sayHelloTo('fred');\n     * // => 'hello fred'\n     */\n    var partialRight = baseRest(function(func, partials) {\n      var holders = replaceHolders(partials, getHolder(partialRight));\n      return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);\n    });\n\n    /**\n     * Creates a function that invokes `func` with arguments arranged according\n     * to the specified `indexes` where the argument value at the first index is\n     * provided as the first argument, the argument value at the second index is\n     * provided as the second argument, and so on.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Function\n     * @param {Function} func The function to rearrange arguments for.\n     * @param {...(number|number[])} indexes The arranged argument indexes.\n     * @returns {Function} Returns the new function.\n     * @example\n     *\n     * var rearged = _.rearg(function(a, b, c) {\n     *   return [a, b, c];\n     * }, [2, 0, 1]);\n     *\n     * rearged('b', 'c', 'a')\n     * // => ['a', 'b', 'c']\n     */\n    var rearg = flatRest(function(func, indexes) {\n      return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);\n    });\n\n    /**\n     * Creates a function that invokes `func` with the `this` binding of the\n     * created function and arguments from `start` and beyond provided as\n     * an array.\n     *\n     * **Note:** This method is based on the\n     * [rest parameter](https://mdn.io/rest_parameters).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Function\n     * @param {Function} func The function to apply a rest parameter to.\n     * @param {number} [start=func.length-1] The start position of the rest parameter.\n     * @returns {Function} Returns the new function.\n     * @example\n     *\n     * var say = _.rest(function(what, names) {\n     *   return what + ' ' + _.initial(names).join(', ') +\n     *     (_.size(names) > 1 ? ', & ' : '') + _.last(names);\n     * });\n     *\n     * say('hello', 'fred', 'barney', 'pebbles');\n     * // => 'hello fred, barney, & pebbles'\n     */\n    function rest(func, start) {\n      if (typeof func != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      start = start === undefined ? start : toInteger(start);\n      return baseRest(func, start);\n    }\n\n    /**\n     * Creates a function that invokes `func` with the `this` binding of the\n     * create function and an array of arguments much like\n     * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).\n     *\n     * **Note:** This method is based on the\n     * [spread operator](https://mdn.io/spread_operator).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.2.0\n     * @category Function\n     * @param {Function} func The function to spread arguments over.\n     * @param {number} [start=0] The start position of the spread.\n     * @returns {Function} Returns the new function.\n     * @example\n     *\n     * var say = _.spread(function(who, what) {\n     *   return who + ' says ' + what;\n     * });\n     *\n     * say(['fred', 'hello']);\n     * // => 'fred says hello'\n     *\n     * var numbers = Promise.all([\n     *   Promise.resolve(40),\n     *   Promise.resolve(36)\n     * ]);\n     *\n     * numbers.then(_.spread(function(x, y) {\n     *   return x + y;\n     * }));\n     * // => a Promise of 76\n     */\n    function spread(func, start) {\n      if (typeof func != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      start = start == null ? 0 : nativeMax(toInteger(start), 0);\n      return baseRest(function(args) {\n        var array = args[start],\n            otherArgs = castSlice(args, 0, start);\n\n        if (array) {\n          arrayPush(otherArgs, array);\n        }\n        return apply(func, this, otherArgs);\n      });\n    }\n\n    /**\n     * Creates a throttled function that only invokes `func` at most once per\n     * every `wait` milliseconds. The throttled function comes with a `cancel`\n     * method to cancel delayed `func` invocations and a `flush` method to\n     * immediately invoke them. Provide `options` to indicate whether `func`\n     * should be invoked on the leading and/or trailing edge of the `wait`\n     * timeout. The `func` is invoked with the last arguments provided to the\n     * throttled function. Subsequent calls to the throttled function return the\n     * result of the last `func` invocation.\n     *\n     * **Note:** If `leading` and `trailing` options are `true`, `func` is\n     * invoked on the trailing edge of the timeout only if the throttled function\n     * is invoked more than once during the `wait` timeout.\n     *\n     * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n     * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n     *\n     * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n     * for details over the differences between `_.throttle` and `_.debounce`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Function\n     * @param {Function} func The function to throttle.\n     * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n     * @param {Object} [options={}] The options object.\n     * @param {boolean} [options.leading=true]\n     *  Specify invoking on the leading edge of the timeout.\n     * @param {boolean} [options.trailing=true]\n     *  Specify invoking on the trailing edge of the timeout.\n     * @returns {Function} Returns the new throttled function.\n     * @example\n     *\n     * // Avoid excessively updating the position while scrolling.\n     * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n     *\n     * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n     * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n     * jQuery(element).on('click', throttled);\n     *\n     * // Cancel the trailing throttled invocation.\n     * jQuery(window).on('popstate', throttled.cancel);\n     */\n    function throttle(func, wait, options) {\n      var leading = true,\n          trailing = true;\n\n      if (typeof func != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      if (isObject(options)) {\n        leading = 'leading' in options ? !!options.leading : leading;\n        trailing = 'trailing' in options ? !!options.trailing : trailing;\n      }\n      return debounce(func, wait, {\n        'leading': leading,\n        'maxWait': wait,\n        'trailing': trailing\n      });\n    }\n\n    /**\n     * Creates a function that accepts up to one argument, ignoring any\n     * additional arguments.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Function\n     * @param {Function} func The function to cap arguments for.\n     * @returns {Function} Returns the new capped function.\n     * @example\n     *\n     * _.map(['6', '8', '10'], _.unary(parseInt));\n     * // => [6, 8, 10]\n     */\n    function unary(func) {\n      return ary(func, 1);\n    }\n\n    /**\n     * Creates a function that provides `value` to `wrapper` as its first\n     * argument. Any additional arguments provided to the function are appended\n     * to those provided to the `wrapper`. The wrapper is invoked with the `this`\n     * binding of the created function.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Function\n     * @param {*} value The value to wrap.\n     * @param {Function} [wrapper=identity] The wrapper function.\n     * @returns {Function} Returns the new function.\n     * @example\n     *\n     * var p = _.wrap(_.escape, function(func, text) {\n     *   return '<p>' + func(text) + '</p>';\n     * });\n     *\n     * p('fred, barney, & pebbles');\n     * // => '<p>fred, barney, &amp; pebbles</p>'\n     */\n    function wrap(value, wrapper) {\n      return partial(castFunction(wrapper), value);\n    }\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Casts `value` as an array if it's not one.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.4.0\n     * @category Lang\n     * @param {*} value The value to inspect.\n     * @returns {Array} Returns the cast array.\n     * @example\n     *\n     * _.castArray(1);\n     * // => [1]\n     *\n     * _.castArray({ 'a': 1 });\n     * // => [{ 'a': 1 }]\n     *\n     * _.castArray('abc');\n     * // => ['abc']\n     *\n     * _.castArray(null);\n     * // => [null]\n     *\n     * _.castArray(undefined);\n     * // => [undefined]\n     *\n     * _.castArray();\n     * // => []\n     *\n     * var array = [1, 2, 3];\n     * console.log(_.castArray(array) === array);\n     * // => true\n     */\n    function castArray() {\n      if (!arguments.length) {\n        return [];\n      }\n      var value = arguments[0];\n      return isArray(value) ? value : [value];\n    }\n\n    /**\n     * Creates a shallow clone of `value`.\n     *\n     * **Note:** This method is loosely based on the\n     * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n     * and supports cloning arrays, array buffers, booleans, date objects, maps,\n     * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n     * arrays. The own enumerable properties of `arguments` objects are cloned\n     * as plain objects. An empty object is returned for uncloneable values such\n     * as error objects, functions, DOM nodes, and WeakMaps.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to clone.\n     * @returns {*} Returns the cloned value.\n     * @see _.cloneDeep\n     * @example\n     *\n     * var objects = [{ 'a': 1 }, { 'b': 2 }];\n     *\n     * var shallow = _.clone(objects);\n     * console.log(shallow[0] === objects[0]);\n     * // => true\n     */\n    function clone(value) {\n      return baseClone(value, CLONE_SYMBOLS_FLAG);\n    }\n\n    /**\n     * This method is like `_.clone` except that it accepts `customizer` which\n     * is invoked to produce the cloned value. If `customizer` returns `undefined`,\n     * cloning is handled by the method instead. The `customizer` is invoked with\n     * up to four arguments; (value [, index|key, object, stack]).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to clone.\n     * @param {Function} [customizer] The function to customize cloning.\n     * @returns {*} Returns the cloned value.\n     * @see _.cloneDeepWith\n     * @example\n     *\n     * function customizer(value) {\n     *   if (_.isElement(value)) {\n     *     return value.cloneNode(false);\n     *   }\n     * }\n     *\n     * var el = _.cloneWith(document.body, customizer);\n     *\n     * console.log(el === document.body);\n     * // => false\n     * console.log(el.nodeName);\n     * // => 'BODY'\n     * console.log(el.childNodes.length);\n     * // => 0\n     */\n    function cloneWith(value, customizer) {\n      customizer = typeof customizer == 'function' ? customizer : undefined;\n      return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);\n    }\n\n    /**\n     * This method is like `_.clone` except that it recursively clones `value`.\n     *\n     * @static\n     * @memberOf _\n     * @since 1.0.0\n     * @category Lang\n     * @param {*} value The value to recursively clone.\n     * @returns {*} Returns the deep cloned value.\n     * @see _.clone\n     * @example\n     *\n     * var objects = [{ 'a': 1 }, { 'b': 2 }];\n     *\n     * var deep = _.cloneDeep(objects);\n     * console.log(deep[0] === objects[0]);\n     * // => false\n     */\n    function cloneDeep(value) {\n      return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n    }\n\n    /**\n     * This method is like `_.cloneWith` except that it recursively clones `value`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to recursively clone.\n     * @param {Function} [customizer] The function to customize cloning.\n     * @returns {*} Returns the deep cloned value.\n     * @see _.cloneWith\n     * @example\n     *\n     * function customizer(value) {\n     *   if (_.isElement(value)) {\n     *     return value.cloneNode(true);\n     *   }\n     * }\n     *\n     * var el = _.cloneDeepWith(document.body, customizer);\n     *\n     * console.log(el === document.body);\n     * // => false\n     * console.log(el.nodeName);\n     * // => 'BODY'\n     * console.log(el.childNodes.length);\n     * // => 20\n     */\n    function cloneDeepWith(value, customizer) {\n      customizer = typeof customizer == 'function' ? customizer : undefined;\n      return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);\n    }\n\n    /**\n     * Checks if `object` conforms to `source` by invoking the predicate\n     * properties of `source` with the corresponding property values of `object`.\n     *\n     * **Note:** This method is equivalent to `_.conforms` when `source` is\n     * partially applied.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.14.0\n     * @category Lang\n     * @param {Object} object The object to inspect.\n     * @param {Object} source The object of property predicates to conform to.\n     * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n     * @example\n     *\n     * var object = { 'a': 1, 'b': 2 };\n     *\n     * _.conformsTo(object, { 'b': function(n) { return n > 1; } });\n     * // => true\n     *\n     * _.conformsTo(object, { 'b': function(n) { return n > 2; } });\n     * // => false\n     */\n    function conformsTo(object, source) {\n      return source == null || baseConformsTo(object, source, keys(source));\n    }\n\n    /**\n     * Performs a\n     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n     * comparison between two values to determine if they are equivalent.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n     * @example\n     *\n     * var object = { 'a': 1 };\n     * var other = { 'a': 1 };\n     *\n     * _.eq(object, object);\n     * // => true\n     *\n     * _.eq(object, other);\n     * // => false\n     *\n     * _.eq('a', 'a');\n     * // => true\n     *\n     * _.eq('a', Object('a'));\n     * // => false\n     *\n     * _.eq(NaN, NaN);\n     * // => true\n     */\n    function eq(value, other) {\n      return value === other || (value !== value && other !== other);\n    }\n\n    /**\n     * Checks if `value` is greater than `other`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.9.0\n     * @category Lang\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @returns {boolean} Returns `true` if `value` is greater than `other`,\n     *  else `false`.\n     * @see _.lt\n     * @example\n     *\n     * _.gt(3, 1);\n     * // => true\n     *\n     * _.gt(3, 3);\n     * // => false\n     *\n     * _.gt(1, 3);\n     * // => false\n     */\n    var gt = createRelationalOperation(baseGt);\n\n    /**\n     * Checks if `value` is greater than or equal to `other`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.9.0\n     * @category Lang\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @returns {boolean} Returns `true` if `value` is greater than or equal to\n     *  `other`, else `false`.\n     * @see _.lte\n     * @example\n     *\n     * _.gte(3, 1);\n     * // => true\n     *\n     * _.gte(3, 3);\n     * // => true\n     *\n     * _.gte(1, 3);\n     * // => false\n     */\n    var gte = createRelationalOperation(function(value, other) {\n      return value >= other;\n    });\n\n    /**\n     * Checks if `value` is likely an `arguments` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n     *  else `false`.\n     * @example\n     *\n     * _.isArguments(function() { return arguments; }());\n     * // => true\n     *\n     * _.isArguments([1, 2, 3]);\n     * // => false\n     */\n    var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n      return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n        !propertyIsEnumerable.call(value, 'callee');\n    };\n\n    /**\n     * Checks if `value` is classified as an `Array` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n     * @example\n     *\n     * _.isArray([1, 2, 3]);\n     * // => true\n     *\n     * _.isArray(document.body.children);\n     * // => false\n     *\n     * _.isArray('abc');\n     * // => false\n     *\n     * _.isArray(_.noop);\n     * // => false\n     */\n    var isArray = Array.isArray;\n\n    /**\n     * Checks if `value` is classified as an `ArrayBuffer` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.3.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n     * @example\n     *\n     * _.isArrayBuffer(new ArrayBuffer(2));\n     * // => true\n     *\n     * _.isArrayBuffer(new Array(2));\n     * // => false\n     */\n    var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;\n\n    /**\n     * Checks if `value` is array-like. A value is considered array-like if it's\n     * not a function and has a `value.length` that's an integer greater than or\n     * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n     * @example\n     *\n     * _.isArrayLike([1, 2, 3]);\n     * // => true\n     *\n     * _.isArrayLike(document.body.children);\n     * // => true\n     *\n     * _.isArrayLike('abc');\n     * // => true\n     *\n     * _.isArrayLike(_.noop);\n     * // => false\n     */\n    function isArrayLike(value) {\n      return value != null && isLength(value.length) && !isFunction(value);\n    }\n\n    /**\n     * This method is like `_.isArrayLike` except that it also checks if `value`\n     * is an object.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is an array-like object,\n     *  else `false`.\n     * @example\n     *\n     * _.isArrayLikeObject([1, 2, 3]);\n     * // => true\n     *\n     * _.isArrayLikeObject(document.body.children);\n     * // => true\n     *\n     * _.isArrayLikeObject('abc');\n     * // => false\n     *\n     * _.isArrayLikeObject(_.noop);\n     * // => false\n     */\n    function isArrayLikeObject(value) {\n      return isObjectLike(value) && isArrayLike(value);\n    }\n\n    /**\n     * Checks if `value` is classified as a boolean primitive or object.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.\n     * @example\n     *\n     * _.isBoolean(false);\n     * // => true\n     *\n     * _.isBoolean(null);\n     * // => false\n     */\n    function isBoolean(value) {\n      return value === true || value === false ||\n        (isObjectLike(value) && baseGetTag(value) == boolTag);\n    }\n\n    /**\n     * Checks if `value` is a buffer.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.3.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n     * @example\n     *\n     * _.isBuffer(new Buffer(2));\n     * // => true\n     *\n     * _.isBuffer(new Uint8Array(2));\n     * // => false\n     */\n    var isBuffer = nativeIsBuffer || stubFalse;\n\n    /**\n     * Checks if `value` is classified as a `Date` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n     * @example\n     *\n     * _.isDate(new Date);\n     * // => true\n     *\n     * _.isDate('Mon April 23 2012');\n     * // => false\n     */\n    var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;\n\n    /**\n     * Checks if `value` is likely a DOM element.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.\n     * @example\n     *\n     * _.isElement(document.body);\n     * // => true\n     *\n     * _.isElement('<body>');\n     * // => false\n     */\n    function isElement(value) {\n      return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);\n    }\n\n    /**\n     * Checks if `value` is an empty object, collection, map, or set.\n     *\n     * Objects are considered empty if they have no own enumerable string keyed\n     * properties.\n     *\n     * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n     * jQuery-like collections are considered empty if they have a `length` of `0`.\n     * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n     * @example\n     *\n     * _.isEmpty(null);\n     * // => true\n     *\n     * _.isEmpty(true);\n     * // => true\n     *\n     * _.isEmpty(1);\n     * // => true\n     *\n     * _.isEmpty([1, 2, 3]);\n     * // => false\n     *\n     * _.isEmpty({ 'a': 1 });\n     * // => false\n     */\n    function isEmpty(value) {\n      if (value == null) {\n        return true;\n      }\n      if (isArrayLike(value) &&\n          (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n            isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n        return !value.length;\n      }\n      var tag = getTag(value);\n      if (tag == mapTag || tag == setTag) {\n        return !value.size;\n      }\n      if (isPrototype(value)) {\n        return !baseKeys(value).length;\n      }\n      for (var key in value) {\n        if (hasOwnProperty.call(value, key)) {\n          return false;\n        }\n      }\n      return true;\n    }\n\n    /**\n     * Performs a deep comparison between two values to determine if they are\n     * equivalent.\n     *\n     * **Note:** This method supports comparing arrays, array buffers, booleans,\n     * date objects, error objects, maps, numbers, `Object` objects, regexes,\n     * sets, strings, symbols, and typed arrays. `Object` objects are compared\n     * by their own, not inherited, enumerable properties. Functions and DOM\n     * nodes are compared by strict equality, i.e. `===`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n     * @example\n     *\n     * var object = { 'a': 1 };\n     * var other = { 'a': 1 };\n     *\n     * _.isEqual(object, other);\n     * // => true\n     *\n     * object === other;\n     * // => false\n     */\n    function isEqual(value, other) {\n      return baseIsEqual(value, other);\n    }\n\n    /**\n     * This method is like `_.isEqual` except that it accepts `customizer` which\n     * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n     * are handled by the method instead. The `customizer` is invoked with up to\n     * six arguments: (objValue, othValue [, index|key, object, other, stack]).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @param {Function} [customizer] The function to customize comparisons.\n     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n     * @example\n     *\n     * function isGreeting(value) {\n     *   return /^h(?:i|ello)$/.test(value);\n     * }\n     *\n     * function customizer(objValue, othValue) {\n     *   if (isGreeting(objValue) && isGreeting(othValue)) {\n     *     return true;\n     *   }\n     * }\n     *\n     * var array = ['hello', 'goodbye'];\n     * var other = ['hi', 'goodbye'];\n     *\n     * _.isEqualWith(array, other, customizer);\n     * // => true\n     */\n    function isEqualWith(value, other, customizer) {\n      customizer = typeof customizer == 'function' ? customizer : undefined;\n      var result = customizer ? customizer(value, other) : undefined;\n      return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;\n    }\n\n    /**\n     * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n     * `SyntaxError`, `TypeError`, or `URIError` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is an error object, else `false`.\n     * @example\n     *\n     * _.isError(new Error);\n     * // => true\n     *\n     * _.isError(Error);\n     * // => false\n     */\n    function isError(value) {\n      if (!isObjectLike(value)) {\n        return false;\n      }\n      var tag = baseGetTag(value);\n      return tag == errorTag || tag == domExcTag ||\n        (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));\n    }\n\n    /**\n     * Checks if `value` is a finite primitive number.\n     *\n     * **Note:** This method is based on\n     * [`Number.isFinite`](https://mdn.io/Number/isFinite).\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.\n     * @example\n     *\n     * _.isFinite(3);\n     * // => true\n     *\n     * _.isFinite(Number.MIN_VALUE);\n     * // => true\n     *\n     * _.isFinite(Infinity);\n     * // => false\n     *\n     * _.isFinite('3');\n     * // => false\n     */\n    function isFinite(value) {\n      return typeof value == 'number' && nativeIsFinite(value);\n    }\n\n    /**\n     * Checks if `value` is classified as a `Function` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n     * @example\n     *\n     * _.isFunction(_);\n     * // => true\n     *\n     * _.isFunction(/abc/);\n     * // => false\n     */\n    function isFunction(value) {\n      if (!isObject(value)) {\n        return false;\n      }\n      // The use of `Object#toString` avoids issues with the `typeof` operator\n      // in Safari 9 which returns 'object' for typed arrays and other constructors.\n      var tag = baseGetTag(value);\n      return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n    }\n\n    /**\n     * Checks if `value` is an integer.\n     *\n     * **Note:** This method is based on\n     * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n     * @example\n     *\n     * _.isInteger(3);\n     * // => true\n     *\n     * _.isInteger(Number.MIN_VALUE);\n     * // => false\n     *\n     * _.isInteger(Infinity);\n     * // => false\n     *\n     * _.isInteger('3');\n     * // => false\n     */\n    function isInteger(value) {\n      return typeof value == 'number' && value == toInteger(value);\n    }\n\n    /**\n     * Checks if `value` is a valid array-like length.\n     *\n     * **Note:** This method is loosely based on\n     * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n     * @example\n     *\n     * _.isLength(3);\n     * // => true\n     *\n     * _.isLength(Number.MIN_VALUE);\n     * // => false\n     *\n     * _.isLength(Infinity);\n     * // => false\n     *\n     * _.isLength('3');\n     * // => false\n     */\n    function isLength(value) {\n      return typeof value == 'number' &&\n        value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n    }\n\n    /**\n     * Checks if `value` is the\n     * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n     * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n     * @example\n     *\n     * _.isObject({});\n     * // => true\n     *\n     * _.isObject([1, 2, 3]);\n     * // => true\n     *\n     * _.isObject(_.noop);\n     * // => true\n     *\n     * _.isObject(null);\n     * // => false\n     */\n    function isObject(value) {\n      var type = typeof value;\n      return value != null && (type == 'object' || type == 'function');\n    }\n\n    /**\n     * Checks if `value` is object-like. A value is object-like if it's not `null`\n     * and has a `typeof` result of \"object\".\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n     * @example\n     *\n     * _.isObjectLike({});\n     * // => true\n     *\n     * _.isObjectLike([1, 2, 3]);\n     * // => true\n     *\n     * _.isObjectLike(_.noop);\n     * // => false\n     *\n     * _.isObjectLike(null);\n     * // => false\n     */\n    function isObjectLike(value) {\n      return value != null && typeof value == 'object';\n    }\n\n    /**\n     * Checks if `value` is classified as a `Map` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.3.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n     * @example\n     *\n     * _.isMap(new Map);\n     * // => true\n     *\n     * _.isMap(new WeakMap);\n     * // => false\n     */\n    var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\n    /**\n     * Performs a partial deep comparison between `object` and `source` to\n     * determine if `object` contains equivalent property values.\n     *\n     * **Note:** This method is equivalent to `_.matches` when `source` is\n     * partially applied.\n     *\n     * Partial comparisons will match empty array and empty object `source`\n     * values against any array or object value, respectively. See `_.isEqual`\n     * for a list of supported value comparisons.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Lang\n     * @param {Object} object The object to inspect.\n     * @param {Object} source The object of property values to match.\n     * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n     * @example\n     *\n     * var object = { 'a': 1, 'b': 2 };\n     *\n     * _.isMatch(object, { 'b': 2 });\n     * // => true\n     *\n     * _.isMatch(object, { 'b': 1 });\n     * // => false\n     */\n    function isMatch(object, source) {\n      return object === source || baseIsMatch(object, source, getMatchData(source));\n    }\n\n    /**\n     * This method is like `_.isMatch` except that it accepts `customizer` which\n     * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n     * are handled by the method instead. The `customizer` is invoked with five\n     * arguments: (objValue, srcValue, index|key, object, source).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {Object} object The object to inspect.\n     * @param {Object} source The object of property values to match.\n     * @param {Function} [customizer] The function to customize comparisons.\n     * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n     * @example\n     *\n     * function isGreeting(value) {\n     *   return /^h(?:i|ello)$/.test(value);\n     * }\n     *\n     * function customizer(objValue, srcValue) {\n     *   if (isGreeting(objValue) && isGreeting(srcValue)) {\n     *     return true;\n     *   }\n     * }\n     *\n     * var object = { 'greeting': 'hello' };\n     * var source = { 'greeting': 'hi' };\n     *\n     * _.isMatchWith(object, source, customizer);\n     * // => true\n     */\n    function isMatchWith(object, source, customizer) {\n      customizer = typeof customizer == 'function' ? customizer : undefined;\n      return baseIsMatch(object, source, getMatchData(source), customizer);\n    }\n\n    /**\n     * Checks if `value` is `NaN`.\n     *\n     * **Note:** This method is based on\n     * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as\n     * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for\n     * `undefined` and other non-number values.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n     * @example\n     *\n     * _.isNaN(NaN);\n     * // => true\n     *\n     * _.isNaN(new Number(NaN));\n     * // => true\n     *\n     * isNaN(undefined);\n     * // => true\n     *\n     * _.isNaN(undefined);\n     * // => false\n     */\n    function isNaN(value) {\n      // An `NaN` primitive is the only value that is not equal to itself.\n      // Perform the `toStringTag` check first to avoid errors with some\n      // ActiveX objects in IE.\n      return isNumber(value) && value != +value;\n    }\n\n    /**\n     * Checks if `value` is a pristine native function.\n     *\n     * **Note:** This method can't reliably detect native functions in the presence\n     * of the core-js package because core-js circumvents this kind of detection.\n     * Despite multiple requests, the core-js maintainer has made it clear: any\n     * attempt to fix the detection will be obstructed. As a result, we're left\n     * with little choice but to throw an error. Unfortunately, this also affects\n     * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),\n     * which rely on core-js.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a native function,\n     *  else `false`.\n     * @example\n     *\n     * _.isNative(Array.prototype.push);\n     * // => true\n     *\n     * _.isNative(_);\n     * // => false\n     */\n    function isNative(value) {\n      if (isMaskable(value)) {\n        throw new Error(CORE_ERROR_TEXT);\n      }\n      return baseIsNative(value);\n    }\n\n    /**\n     * Checks if `value` is `null`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is `null`, else `false`.\n     * @example\n     *\n     * _.isNull(null);\n     * // => true\n     *\n     * _.isNull(void 0);\n     * // => false\n     */\n    function isNull(value) {\n      return value === null;\n    }\n\n    /**\n     * Checks if `value` is `null` or `undefined`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n     * @example\n     *\n     * _.isNil(null);\n     * // => true\n     *\n     * _.isNil(void 0);\n     * // => true\n     *\n     * _.isNil(NaN);\n     * // => false\n     */\n    function isNil(value) {\n      return value == null;\n    }\n\n    /**\n     * Checks if `value` is classified as a `Number` primitive or object.\n     *\n     * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are\n     * classified as numbers, use the `_.isFinite` method.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a number, else `false`.\n     * @example\n     *\n     * _.isNumber(3);\n     * // => true\n     *\n     * _.isNumber(Number.MIN_VALUE);\n     * // => true\n     *\n     * _.isNumber(Infinity);\n     * // => true\n     *\n     * _.isNumber('3');\n     * // => false\n     */\n    function isNumber(value) {\n      return typeof value == 'number' ||\n        (isObjectLike(value) && baseGetTag(value) == numberTag);\n    }\n\n    /**\n     * Checks if `value` is a plain object, that is, an object created by the\n     * `Object` constructor or one with a `[[Prototype]]` of `null`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.8.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     * }\n     *\n     * _.isPlainObject(new Foo);\n     * // => false\n     *\n     * _.isPlainObject([1, 2, 3]);\n     * // => false\n     *\n     * _.isPlainObject({ 'x': 0, 'y': 0 });\n     * // => true\n     *\n     * _.isPlainObject(Object.create(null));\n     * // => true\n     */\n    function isPlainObject(value) {\n      if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n        return false;\n      }\n      var proto = getPrototype(value);\n      if (proto === null) {\n        return true;\n      }\n      var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n      return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n        funcToString.call(Ctor) == objectCtorString;\n    }\n\n    /**\n     * Checks if `value` is classified as a `RegExp` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.1.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n     * @example\n     *\n     * _.isRegExp(/abc/);\n     * // => true\n     *\n     * _.isRegExp('/abc/');\n     * // => false\n     */\n    var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\n    /**\n     * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754\n     * double precision number which isn't the result of a rounded unsafe integer.\n     *\n     * **Note:** This method is based on\n     * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.\n     * @example\n     *\n     * _.isSafeInteger(3);\n     * // => true\n     *\n     * _.isSafeInteger(Number.MIN_VALUE);\n     * // => false\n     *\n     * _.isSafeInteger(Infinity);\n     * // => false\n     *\n     * _.isSafeInteger('3');\n     * // => false\n     */\n    function isSafeInteger(value) {\n      return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;\n    }\n\n    /**\n     * Checks if `value` is classified as a `Set` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.3.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n     * @example\n     *\n     * _.isSet(new Set);\n     * // => true\n     *\n     * _.isSet(new WeakSet);\n     * // => false\n     */\n    var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\n    /**\n     * Checks if `value` is classified as a `String` primitive or object.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n     * @example\n     *\n     * _.isString('abc');\n     * // => true\n     *\n     * _.isString(1);\n     * // => false\n     */\n    function isString(value) {\n      return typeof value == 'string' ||\n        (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n    }\n\n    /**\n     * Checks if `value` is classified as a `Symbol` primitive or object.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n     * @example\n     *\n     * _.isSymbol(Symbol.iterator);\n     * // => true\n     *\n     * _.isSymbol('abc');\n     * // => false\n     */\n    function isSymbol(value) {\n      return typeof value == 'symbol' ||\n        (isObjectLike(value) && baseGetTag(value) == symbolTag);\n    }\n\n    /**\n     * Checks if `value` is classified as a typed array.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n     * @example\n     *\n     * _.isTypedArray(new Uint8Array);\n     * // => true\n     *\n     * _.isTypedArray([]);\n     * // => false\n     */\n    var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n    /**\n     * Checks if `value` is `undefined`.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n     * @example\n     *\n     * _.isUndefined(void 0);\n     * // => true\n     *\n     * _.isUndefined(null);\n     * // => false\n     */\n    function isUndefined(value) {\n      return value === undefined;\n    }\n\n    /**\n     * Checks if `value` is classified as a `WeakMap` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.3.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.\n     * @example\n     *\n     * _.isWeakMap(new WeakMap);\n     * // => true\n     *\n     * _.isWeakMap(new Map);\n     * // => false\n     */\n    function isWeakMap(value) {\n      return isObjectLike(value) && getTag(value) == weakMapTag;\n    }\n\n    /**\n     * Checks if `value` is classified as a `WeakSet` object.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.3.0\n     * @category Lang\n     * @param {*} value The value to check.\n     * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.\n     * @example\n     *\n     * _.isWeakSet(new WeakSet);\n     * // => true\n     *\n     * _.isWeakSet(new Set);\n     * // => false\n     */\n    function isWeakSet(value) {\n      return isObjectLike(value) && baseGetTag(value) == weakSetTag;\n    }\n\n    /**\n     * Checks if `value` is less than `other`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.9.0\n     * @category Lang\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @returns {boolean} Returns `true` if `value` is less than `other`,\n     *  else `false`.\n     * @see _.gt\n     * @example\n     *\n     * _.lt(1, 3);\n     * // => true\n     *\n     * _.lt(3, 3);\n     * // => false\n     *\n     * _.lt(3, 1);\n     * // => false\n     */\n    var lt = createRelationalOperation(baseLt);\n\n    /**\n     * Checks if `value` is less than or equal to `other`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.9.0\n     * @category Lang\n     * @param {*} value The value to compare.\n     * @param {*} other The other value to compare.\n     * @returns {boolean} Returns `true` if `value` is less than or equal to\n     *  `other`, else `false`.\n     * @see _.gte\n     * @example\n     *\n     * _.lte(1, 3);\n     * // => true\n     *\n     * _.lte(3, 3);\n     * // => true\n     *\n     * _.lte(3, 1);\n     * // => false\n     */\n    var lte = createRelationalOperation(function(value, other) {\n      return value <= other;\n    });\n\n    /**\n     * Converts `value` to an array.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Lang\n     * @param {*} value The value to convert.\n     * @returns {Array} Returns the converted array.\n     * @example\n     *\n     * _.toArray({ 'a': 1, 'b': 2 });\n     * // => [1, 2]\n     *\n     * _.toArray('abc');\n     * // => ['a', 'b', 'c']\n     *\n     * _.toArray(1);\n     * // => []\n     *\n     * _.toArray(null);\n     * // => []\n     */\n    function toArray(value) {\n      if (!value) {\n        return [];\n      }\n      if (isArrayLike(value)) {\n        return isString(value) ? stringToArray(value) : copyArray(value);\n      }\n      if (symIterator && value[symIterator]) {\n        return iteratorToArray(value[symIterator]());\n      }\n      var tag = getTag(value),\n          func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);\n\n      return func(value);\n    }\n\n    /**\n     * Converts `value` to a finite number.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.12.0\n     * @category Lang\n     * @param {*} value The value to convert.\n     * @returns {number} Returns the converted number.\n     * @example\n     *\n     * _.toFinite(3.2);\n     * // => 3.2\n     *\n     * _.toFinite(Number.MIN_VALUE);\n     * // => 5e-324\n     *\n     * _.toFinite(Infinity);\n     * // => 1.7976931348623157e+308\n     *\n     * _.toFinite('3.2');\n     * // => 3.2\n     */\n    function toFinite(value) {\n      if (!value) {\n        return value === 0 ? value : 0;\n      }\n      value = toNumber(value);\n      if (value === INFINITY || value === -INFINITY) {\n        var sign = (value < 0 ? -1 : 1);\n        return sign * MAX_INTEGER;\n      }\n      return value === value ? value : 0;\n    }\n\n    /**\n     * Converts `value` to an integer.\n     *\n     * **Note:** This method is loosely based on\n     * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to convert.\n     * @returns {number} Returns the converted integer.\n     * @example\n     *\n     * _.toInteger(3.2);\n     * // => 3\n     *\n     * _.toInteger(Number.MIN_VALUE);\n     * // => 0\n     *\n     * _.toInteger(Infinity);\n     * // => 1.7976931348623157e+308\n     *\n     * _.toInteger('3.2');\n     * // => 3\n     */\n    function toInteger(value) {\n      var result = toFinite(value),\n          remainder = result % 1;\n\n      return result === result ? (remainder ? result - remainder : result) : 0;\n    }\n\n    /**\n     * Converts `value` to an integer suitable for use as the length of an\n     * array-like object.\n     *\n     * **Note:** This method is based on\n     * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to convert.\n     * @returns {number} Returns the converted integer.\n     * @example\n     *\n     * _.toLength(3.2);\n     * // => 3\n     *\n     * _.toLength(Number.MIN_VALUE);\n     * // => 0\n     *\n     * _.toLength(Infinity);\n     * // => 4294967295\n     *\n     * _.toLength('3.2');\n     * // => 3\n     */\n    function toLength(value) {\n      return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;\n    }\n\n    /**\n     * Converts `value` to a number.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to process.\n     * @returns {number} Returns the number.\n     * @example\n     *\n     * _.toNumber(3.2);\n     * // => 3.2\n     *\n     * _.toNumber(Number.MIN_VALUE);\n     * // => 5e-324\n     *\n     * _.toNumber(Infinity);\n     * // => Infinity\n     *\n     * _.toNumber('3.2');\n     * // => 3.2\n     */\n    function toNumber(value) {\n      if (typeof value == 'number') {\n        return value;\n      }\n      if (isSymbol(value)) {\n        return NAN;\n      }\n      if (isObject(value)) {\n        var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n        value = isObject(other) ? (other + '') : other;\n      }\n      if (typeof value != 'string') {\n        return value === 0 ? value : +value;\n      }\n      value = value.replace(reTrim, '');\n      var isBinary = reIsBinary.test(value);\n      return (isBinary || reIsOctal.test(value))\n        ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n        : (reIsBadHex.test(value) ? NAN : +value);\n    }\n\n    /**\n     * Converts `value` to a plain object flattening inherited enumerable string\n     * keyed properties of `value` to own properties of the plain object.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Lang\n     * @param {*} value The value to convert.\n     * @returns {Object} Returns the converted plain object.\n     * @example\n     *\n     * function Foo() {\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.assign({ 'a': 1 }, new Foo);\n     * // => { 'a': 1, 'b': 2 }\n     *\n     * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n     * // => { 'a': 1, 'b': 2, 'c': 3 }\n     */\n    function toPlainObject(value) {\n      return copyObject(value, keysIn(value));\n    }\n\n    /**\n     * Converts `value` to a safe integer. A safe integer can be compared and\n     * represented correctly.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to convert.\n     * @returns {number} Returns the converted integer.\n     * @example\n     *\n     * _.toSafeInteger(3.2);\n     * // => 3\n     *\n     * _.toSafeInteger(Number.MIN_VALUE);\n     * // => 0\n     *\n     * _.toSafeInteger(Infinity);\n     * // => 9007199254740991\n     *\n     * _.toSafeInteger('3.2');\n     * // => 3\n     */\n    function toSafeInteger(value) {\n      return value\n        ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)\n        : (value === 0 ? value : 0);\n    }\n\n    /**\n     * Converts `value` to a string. An empty string is returned for `null`\n     * and `undefined` values. The sign of `-0` is preserved.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Lang\n     * @param {*} value The value to convert.\n     * @returns {string} Returns the converted string.\n     * @example\n     *\n     * _.toString(null);\n     * // => ''\n     *\n     * _.toString(-0);\n     * // => '-0'\n     *\n     * _.toString([1, 2, 3]);\n     * // => '1,2,3'\n     */\n    function toString(value) {\n      return value == null ? '' : baseToString(value);\n    }\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Assigns own enumerable string keyed properties of source objects to the\n     * destination object. Source objects are applied from left to right.\n     * Subsequent sources overwrite property assignments of previous sources.\n     *\n     * **Note:** This method mutates `object` and is loosely based on\n     * [`Object.assign`](https://mdn.io/Object/assign).\n     *\n     * @static\n     * @memberOf _\n     * @since 0.10.0\n     * @category Object\n     * @param {Object} object The destination object.\n     * @param {...Object} [sources] The source objects.\n     * @returns {Object} Returns `object`.\n     * @see _.assignIn\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     * }\n     *\n     * function Bar() {\n     *   this.c = 3;\n     * }\n     *\n     * Foo.prototype.b = 2;\n     * Bar.prototype.d = 4;\n     *\n     * _.assign({ 'a': 0 }, new Foo, new Bar);\n     * // => { 'a': 1, 'c': 3 }\n     */\n    var assign = createAssigner(function(object, source) {\n      if (isPrototype(source) || isArrayLike(source)) {\n        copyObject(source, keys(source), object);\n        return;\n      }\n      for (var key in source) {\n        if (hasOwnProperty.call(source, key)) {\n          assignValue(object, key, source[key]);\n        }\n      }\n    });\n\n    /**\n     * This method is like `_.assign` except that it iterates over own and\n     * inherited source properties.\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @alias extend\n     * @category Object\n     * @param {Object} object The destination object.\n     * @param {...Object} [sources] The source objects.\n     * @returns {Object} Returns `object`.\n     * @see _.assign\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     * }\n     *\n     * function Bar() {\n     *   this.c = 3;\n     * }\n     *\n     * Foo.prototype.b = 2;\n     * Bar.prototype.d = 4;\n     *\n     * _.assignIn({ 'a': 0 }, new Foo, new Bar);\n     * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }\n     */\n    var assignIn = createAssigner(function(object, source) {\n      copyObject(source, keysIn(source), object);\n    });\n\n    /**\n     * This method is like `_.assignIn` except that it accepts `customizer`\n     * which is invoked to produce the assigned values. If `customizer` returns\n     * `undefined`, assignment is handled by the method instead. The `customizer`\n     * is invoked with five arguments: (objValue, srcValue, key, object, source).\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @alias extendWith\n     * @category Object\n     * @param {Object} object The destination object.\n     * @param {...Object} sources The source objects.\n     * @param {Function} [customizer] The function to customize assigned values.\n     * @returns {Object} Returns `object`.\n     * @see _.assignWith\n     * @example\n     *\n     * function customizer(objValue, srcValue) {\n     *   return _.isUndefined(objValue) ? srcValue : objValue;\n     * }\n     *\n     * var defaults = _.partialRight(_.assignInWith, customizer);\n     *\n     * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n     * // => { 'a': 1, 'b': 2 }\n     */\n    var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {\n      copyObject(source, keysIn(source), object, customizer);\n    });\n\n    /**\n     * This method is like `_.assign` except that it accepts `customizer`\n     * which is invoked to produce the assigned values. If `customizer` returns\n     * `undefined`, assignment is handled by the method instead. The `customizer`\n     * is invoked with five arguments: (objValue, srcValue, key, object, source).\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Object\n     * @param {Object} object The destination object.\n     * @param {...Object} sources The source objects.\n     * @param {Function} [customizer] The function to customize assigned values.\n     * @returns {Object} Returns `object`.\n     * @see _.assignInWith\n     * @example\n     *\n     * function customizer(objValue, srcValue) {\n     *   return _.isUndefined(objValue) ? srcValue : objValue;\n     * }\n     *\n     * var defaults = _.partialRight(_.assignWith, customizer);\n     *\n     * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n     * // => { 'a': 1, 'b': 2 }\n     */\n    var assignWith = createAssigner(function(object, source, srcIndex, customizer) {\n      copyObject(source, keys(source), object, customizer);\n    });\n\n    /**\n     * Creates an array of values corresponding to `paths` of `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 1.0.0\n     * @category Object\n     * @param {Object} object The object to iterate over.\n     * @param {...(string|string[])} [paths] The property paths to pick.\n     * @returns {Array} Returns the picked values.\n     * @example\n     *\n     * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n     *\n     * _.at(object, ['a[0].b.c', 'a[1]']);\n     * // => [3, 4]\n     */\n    var at = flatRest(baseAt);\n\n    /**\n     * Creates an object that inherits from the `prototype` object. If a\n     * `properties` object is given, its own enumerable string keyed properties\n     * are assigned to the created object.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.3.0\n     * @category Object\n     * @param {Object} prototype The object to inherit from.\n     * @param {Object} [properties] The properties to assign to the object.\n     * @returns {Object} Returns the new object.\n     * @example\n     *\n     * function Shape() {\n     *   this.x = 0;\n     *   this.y = 0;\n     * }\n     *\n     * function Circle() {\n     *   Shape.call(this);\n     * }\n     *\n     * Circle.prototype = _.create(Shape.prototype, {\n     *   'constructor': Circle\n     * });\n     *\n     * var circle = new Circle;\n     * circle instanceof Circle;\n     * // => true\n     *\n     * circle instanceof Shape;\n     * // => true\n     */\n    function create(prototype, properties) {\n      var result = baseCreate(prototype);\n      return properties == null ? result : baseAssign(result, properties);\n    }\n\n    /**\n     * Assigns own and inherited enumerable string keyed properties of source\n     * objects to the destination object for all destination properties that\n     * resolve to `undefined`. Source objects are applied from left to right.\n     * Once a property is set, additional values of the same property are ignored.\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Object\n     * @param {Object} object The destination object.\n     * @param {...Object} [sources] The source objects.\n     * @returns {Object} Returns `object`.\n     * @see _.defaultsDeep\n     * @example\n     *\n     * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n     * // => { 'a': 1, 'b': 2 }\n     */\n    var defaults = baseRest(function(object, sources) {\n      object = Object(object);\n\n      var index = -1;\n      var length = sources.length;\n      var guard = length > 2 ? sources[2] : undefined;\n\n      if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n        length = 1;\n      }\n\n      while (++index < length) {\n        var source = sources[index];\n        var props = keysIn(source);\n        var propsIndex = -1;\n        var propsLength = props.length;\n\n        while (++propsIndex < propsLength) {\n          var key = props[propsIndex];\n          var value = object[key];\n\n          if (value === undefined ||\n              (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n            object[key] = source[key];\n          }\n        }\n      }\n\n      return object;\n    });\n\n    /**\n     * This method is like `_.defaults` except that it recursively assigns\n     * default properties.\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.10.0\n     * @category Object\n     * @param {Object} object The destination object.\n     * @param {...Object} [sources] The source objects.\n     * @returns {Object} Returns `object`.\n     * @see _.defaults\n     * @example\n     *\n     * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });\n     * // => { 'a': { 'b': 2, 'c': 3 } }\n     */\n    var defaultsDeep = baseRest(function(args) {\n      args.push(undefined, customDefaultsMerge);\n      return apply(mergeWith, undefined, args);\n    });\n\n    /**\n     * This method is like `_.find` except that it returns the key of the first\n     * element `predicate` returns truthy for instead of the element itself.\n     *\n     * @static\n     * @memberOf _\n     * @since 1.1.0\n     * @category Object\n     * @param {Object} object The object to inspect.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {string|undefined} Returns the key of the matched element,\n     *  else `undefined`.\n     * @example\n     *\n     * var users = {\n     *   'barney':  { 'age': 36, 'active': true },\n     *   'fred':    { 'age': 40, 'active': false },\n     *   'pebbles': { 'age': 1,  'active': true }\n     * };\n     *\n     * _.findKey(users, function(o) { return o.age < 40; });\n     * // => 'barney' (iteration order is not guaranteed)\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.findKey(users, { 'age': 1, 'active': true });\n     * // => 'pebbles'\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.findKey(users, ['active', false]);\n     * // => 'fred'\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.findKey(users, 'active');\n     * // => 'barney'\n     */\n    function findKey(object, predicate) {\n      return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);\n    }\n\n    /**\n     * This method is like `_.findKey` except that it iterates over elements of\n     * a collection in the opposite order.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @category Object\n     * @param {Object} object The object to inspect.\n     * @param {Function} [predicate=_.identity] The function invoked per iteration.\n     * @returns {string|undefined} Returns the key of the matched element,\n     *  else `undefined`.\n     * @example\n     *\n     * var users = {\n     *   'barney':  { 'age': 36, 'active': true },\n     *   'fred':    { 'age': 40, 'active': false },\n     *   'pebbles': { 'age': 1,  'active': true }\n     * };\n     *\n     * _.findLastKey(users, function(o) { return o.age < 40; });\n     * // => returns 'pebbles' assuming `_.findKey` returns 'barney'\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.findLastKey(users, { 'age': 36, 'active': true });\n     * // => 'barney'\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.findLastKey(users, ['active', false]);\n     * // => 'fred'\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.findLastKey(users, 'active');\n     * // => 'pebbles'\n     */\n    function findLastKey(object, predicate) {\n      return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);\n    }\n\n    /**\n     * Iterates over own and inherited enumerable string keyed properties of an\n     * object and invokes `iteratee` for each property. The iteratee is invoked\n     * with three arguments: (value, key, object). Iteratee functions may exit\n     * iteration early by explicitly returning `false`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.3.0\n     * @category Object\n     * @param {Object} object The object to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Object} Returns `object`.\n     * @see _.forInRight\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.forIn(new Foo, function(value, key) {\n     *   console.log(key);\n     * });\n     * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).\n     */\n    function forIn(object, iteratee) {\n      return object == null\n        ? object\n        : baseFor(object, getIteratee(iteratee, 3), keysIn);\n    }\n\n    /**\n     * This method is like `_.forIn` except that it iterates over properties of\n     * `object` in the opposite order.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @category Object\n     * @param {Object} object The object to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Object} Returns `object`.\n     * @see _.forIn\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.forInRight(new Foo, function(value, key) {\n     *   console.log(key);\n     * });\n     * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.\n     */\n    function forInRight(object, iteratee) {\n      return object == null\n        ? object\n        : baseForRight(object, getIteratee(iteratee, 3), keysIn);\n    }\n\n    /**\n     * Iterates over own enumerable string keyed properties of an object and\n     * invokes `iteratee` for each property. The iteratee is invoked with three\n     * arguments: (value, key, object). Iteratee functions may exit iteration\n     * early by explicitly returning `false`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.3.0\n     * @category Object\n     * @param {Object} object The object to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Object} Returns `object`.\n     * @see _.forOwnRight\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.forOwn(new Foo, function(value, key) {\n     *   console.log(key);\n     * });\n     * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n     */\n    function forOwn(object, iteratee) {\n      return object && baseForOwn(object, getIteratee(iteratee, 3));\n    }\n\n    /**\n     * This method is like `_.forOwn` except that it iterates over properties of\n     * `object` in the opposite order.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.0.0\n     * @category Object\n     * @param {Object} object The object to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Object} Returns `object`.\n     * @see _.forOwn\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.forOwnRight(new Foo, function(value, key) {\n     *   console.log(key);\n     * });\n     * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.\n     */\n    function forOwnRight(object, iteratee) {\n      return object && baseForOwnRight(object, getIteratee(iteratee, 3));\n    }\n\n    /**\n     * Creates an array of function property names from own enumerable properties\n     * of `object`.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Object\n     * @param {Object} object The object to inspect.\n     * @returns {Array} Returns the function names.\n     * @see _.functionsIn\n     * @example\n     *\n     * function Foo() {\n     *   this.a = _.constant('a');\n     *   this.b = _.constant('b');\n     * }\n     *\n     * Foo.prototype.c = _.constant('c');\n     *\n     * _.functions(new Foo);\n     * // => ['a', 'b']\n     */\n    function functions(object) {\n      return object == null ? [] : baseFunctions(object, keys(object));\n    }\n\n    /**\n     * Creates an array of function property names from own and inherited\n     * enumerable properties of `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Object\n     * @param {Object} object The object to inspect.\n     * @returns {Array} Returns the function names.\n     * @see _.functions\n     * @example\n     *\n     * function Foo() {\n     *   this.a = _.constant('a');\n     *   this.b = _.constant('b');\n     * }\n     *\n     * Foo.prototype.c = _.constant('c');\n     *\n     * _.functionsIn(new Foo);\n     * // => ['a', 'b', 'c']\n     */\n    function functionsIn(object) {\n      return object == null ? [] : baseFunctions(object, keysIn(object));\n    }\n\n    /**\n     * Gets the value at `path` of `object`. If the resolved value is\n     * `undefined`, the `defaultValue` is returned in its place.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.7.0\n     * @category Object\n     * @param {Object} object The object to query.\n     * @param {Array|string} path The path of the property to get.\n     * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n     * @returns {*} Returns the resolved value.\n     * @example\n     *\n     * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n     *\n     * _.get(object, 'a[0].b.c');\n     * // => 3\n     *\n     * _.get(object, ['a', '0', 'b', 'c']);\n     * // => 3\n     *\n     * _.get(object, 'a.b.c', 'default');\n     * // => 'default'\n     */\n    function get(object, path, defaultValue) {\n      var result = object == null ? undefined : baseGet(object, path);\n      return result === undefined ? defaultValue : result;\n    }\n\n    /**\n     * Checks if `path` is a direct property of `object`.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Object\n     * @param {Object} object The object to query.\n     * @param {Array|string} path The path to check.\n     * @returns {boolean} Returns `true` if `path` exists, else `false`.\n     * @example\n     *\n     * var object = { 'a': { 'b': 2 } };\n     * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n     *\n     * _.has(object, 'a');\n     * // => true\n     *\n     * _.has(object, 'a.b');\n     * // => true\n     *\n     * _.has(object, ['a', 'b']);\n     * // => true\n     *\n     * _.has(other, 'a');\n     * // => false\n     */\n    function has(object, path) {\n      return object != null && hasPath(object, path, baseHas);\n    }\n\n    /**\n     * Checks if `path` is a direct or inherited property of `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Object\n     * @param {Object} object The object to query.\n     * @param {Array|string} path The path to check.\n     * @returns {boolean} Returns `true` if `path` exists, else `false`.\n     * @example\n     *\n     * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n     *\n     * _.hasIn(object, 'a');\n     * // => true\n     *\n     * _.hasIn(object, 'a.b');\n     * // => true\n     *\n     * _.hasIn(object, ['a', 'b']);\n     * // => true\n     *\n     * _.hasIn(object, 'b');\n     * // => false\n     */\n    function hasIn(object, path) {\n      return object != null && hasPath(object, path, baseHasIn);\n    }\n\n    /**\n     * Creates an object composed of the inverted keys and values of `object`.\n     * If `object` contains duplicate values, subsequent values overwrite\n     * property assignments of previous values.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.7.0\n     * @category Object\n     * @param {Object} object The object to invert.\n     * @returns {Object} Returns the new inverted object.\n     * @example\n     *\n     * var object = { 'a': 1, 'b': 2, 'c': 1 };\n     *\n     * _.invert(object);\n     * // => { '1': 'c', '2': 'b' }\n     */\n    var invert = createInverter(function(result, value, key) {\n      if (value != null &&\n          typeof value.toString != 'function') {\n        value = nativeObjectToString.call(value);\n      }\n\n      result[value] = key;\n    }, constant(identity));\n\n    /**\n     * This method is like `_.invert` except that the inverted object is generated\n     * from the results of running each element of `object` thru `iteratee`. The\n     * corresponding inverted value of each inverted key is an array of keys\n     * responsible for generating the inverted value. The iteratee is invoked\n     * with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.1.0\n     * @category Object\n     * @param {Object} object The object to invert.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {Object} Returns the new inverted object.\n     * @example\n     *\n     * var object = { 'a': 1, 'b': 2, 'c': 1 };\n     *\n     * _.invertBy(object);\n     * // => { '1': ['a', 'c'], '2': ['b'] }\n     *\n     * _.invertBy(object, function(value) {\n     *   return 'group' + value;\n     * });\n     * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n     */\n    var invertBy = createInverter(function(result, value, key) {\n      if (value != null &&\n          typeof value.toString != 'function') {\n        value = nativeObjectToString.call(value);\n      }\n\n      if (hasOwnProperty.call(result, value)) {\n        result[value].push(key);\n      } else {\n        result[value] = [key];\n      }\n    }, getIteratee);\n\n    /**\n     * Invokes the method at `path` of `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Object\n     * @param {Object} object The object to query.\n     * @param {Array|string} path The path of the method to invoke.\n     * @param {...*} [args] The arguments to invoke the method with.\n     * @returns {*} Returns the result of the invoked method.\n     * @example\n     *\n     * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n     *\n     * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n     * // => [2, 3]\n     */\n    var invoke = baseRest(baseInvoke);\n\n    /**\n     * Creates an array of the own enumerable property names of `object`.\n     *\n     * **Note:** Non-object values are coerced to objects. See the\n     * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n     * for more details.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Object\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of property names.\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.keys(new Foo);\n     * // => ['a', 'b'] (iteration order is not guaranteed)\n     *\n     * _.keys('hi');\n     * // => ['0', '1']\n     */\n    function keys(object) {\n      return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n    }\n\n    /**\n     * Creates an array of the own and inherited enumerable property names of `object`.\n     *\n     * **Note:** Non-object values are coerced to objects.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Object\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of property names.\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.keysIn(new Foo);\n     * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n     */\n    function keysIn(object) {\n      return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n    }\n\n    /**\n     * The opposite of `_.mapValues`; this method creates an object with the\n     * same values as `object` and keys generated by running each own enumerable\n     * string keyed property of `object` thru `iteratee`. The iteratee is invoked\n     * with three arguments: (value, key, object).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.8.0\n     * @category Object\n     * @param {Object} object The object to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Object} Returns the new mapped object.\n     * @see _.mapValues\n     * @example\n     *\n     * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {\n     *   return key + value;\n     * });\n     * // => { 'a1': 1, 'b2': 2 }\n     */\n    function mapKeys(object, iteratee) {\n      var result = {};\n      iteratee = getIteratee(iteratee, 3);\n\n      baseForOwn(object, function(value, key, object) {\n        baseAssignValue(result, iteratee(value, key, object), value);\n      });\n      return result;\n    }\n\n    /**\n     * Creates an object with the same keys as `object` and values generated\n     * by running each own enumerable string keyed property of `object` thru\n     * `iteratee`. The iteratee is invoked with three arguments:\n     * (value, key, object).\n     *\n     * @static\n     * @memberOf _\n     * @since 2.4.0\n     * @category Object\n     * @param {Object} object The object to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Object} Returns the new mapped object.\n     * @see _.mapKeys\n     * @example\n     *\n     * var users = {\n     *   'fred':    { 'user': 'fred',    'age': 40 },\n     *   'pebbles': { 'user': 'pebbles', 'age': 1 }\n     * };\n     *\n     * _.mapValues(users, function(o) { return o.age; });\n     * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.mapValues(users, 'age');\n     * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n     */\n    function mapValues(object, iteratee) {\n      var result = {};\n      iteratee = getIteratee(iteratee, 3);\n\n      baseForOwn(object, function(value, key, object) {\n        baseAssignValue(result, key, iteratee(value, key, object));\n      });\n      return result;\n    }\n\n    /**\n     * This method is like `_.assign` except that it recursively merges own and\n     * inherited enumerable string keyed properties of source objects into the\n     * destination object. Source properties that resolve to `undefined` are\n     * skipped if a destination value exists. Array and plain object properties\n     * are merged recursively. Other objects and value types are overridden by\n     * assignment. Source objects are applied from left to right. Subsequent\n     * sources overwrite property assignments of previous sources.\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.5.0\n     * @category Object\n     * @param {Object} object The destination object.\n     * @param {...Object} [sources] The source objects.\n     * @returns {Object} Returns `object`.\n     * @example\n     *\n     * var object = {\n     *   'a': [{ 'b': 2 }, { 'd': 4 }]\n     * };\n     *\n     * var other = {\n     *   'a': [{ 'c': 3 }, { 'e': 5 }]\n     * };\n     *\n     * _.merge(object, other);\n     * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n     */\n    var merge = createAssigner(function(object, source, srcIndex) {\n      baseMerge(object, source, srcIndex);\n    });\n\n    /**\n     * This method is like `_.merge` except that it accepts `customizer` which\n     * is invoked to produce the merged values of the destination and source\n     * properties. If `customizer` returns `undefined`, merging is handled by the\n     * method instead. The `customizer` is invoked with six arguments:\n     * (objValue, srcValue, key, object, source, stack).\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Object\n     * @param {Object} object The destination object.\n     * @param {...Object} sources The source objects.\n     * @param {Function} customizer The function to customize assigned values.\n     * @returns {Object} Returns `object`.\n     * @example\n     *\n     * function customizer(objValue, srcValue) {\n     *   if (_.isArray(objValue)) {\n     *     return objValue.concat(srcValue);\n     *   }\n     * }\n     *\n     * var object = { 'a': [1], 'b': [2] };\n     * var other = { 'a': [3], 'b': [4] };\n     *\n     * _.mergeWith(object, other, customizer);\n     * // => { 'a': [1, 3], 'b': [2, 4] }\n     */\n    var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n      baseMerge(object, source, srcIndex, customizer);\n    });\n\n    /**\n     * The opposite of `_.pick`; this method creates an object composed of the\n     * own and inherited enumerable property paths of `object` that are not omitted.\n     *\n     * **Note:** This method is considerably slower than `_.pick`.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Object\n     * @param {Object} object The source object.\n     * @param {...(string|string[])} [paths] The property paths to omit.\n     * @returns {Object} Returns the new object.\n     * @example\n     *\n     * var object = { 'a': 1, 'b': '2', 'c': 3 };\n     *\n     * _.omit(object, ['a', 'c']);\n     * // => { 'b': '2' }\n     */\n    var omit = flatRest(function(object, paths) {\n      var result = {};\n      if (object == null) {\n        return result;\n      }\n      var isDeep = false;\n      paths = arrayMap(paths, function(path) {\n        path = castPath(path, object);\n        isDeep || (isDeep = path.length > 1);\n        return path;\n      });\n      copyObject(object, getAllKeysIn(object), result);\n      if (isDeep) {\n        result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n      }\n      var length = paths.length;\n      while (length--) {\n        baseUnset(result, paths[length]);\n      }\n      return result;\n    });\n\n    /**\n     * The opposite of `_.pickBy`; this method creates an object composed of\n     * the own and inherited enumerable string keyed properties of `object` that\n     * `predicate` doesn't return truthy for. The predicate is invoked with two\n     * arguments: (value, key).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Object\n     * @param {Object} object The source object.\n     * @param {Function} [predicate=_.identity] The function invoked per property.\n     * @returns {Object} Returns the new object.\n     * @example\n     *\n     * var object = { 'a': 1, 'b': '2', 'c': 3 };\n     *\n     * _.omitBy(object, _.isNumber);\n     * // => { 'b': '2' }\n     */\n    function omitBy(object, predicate) {\n      return pickBy(object, negate(getIteratee(predicate)));\n    }\n\n    /**\n     * Creates an object composed of the picked `object` properties.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Object\n     * @param {Object} object The source object.\n     * @param {...(string|string[])} [paths] The property paths to pick.\n     * @returns {Object} Returns the new object.\n     * @example\n     *\n     * var object = { 'a': 1, 'b': '2', 'c': 3 };\n     *\n     * _.pick(object, ['a', 'c']);\n     * // => { 'a': 1, 'c': 3 }\n     */\n    var pick = flatRest(function(object, paths) {\n      return object == null ? {} : basePick(object, paths);\n    });\n\n    /**\n     * Creates an object composed of the `object` properties `predicate` returns\n     * truthy for. The predicate is invoked with two arguments: (value, key).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Object\n     * @param {Object} object The source object.\n     * @param {Function} [predicate=_.identity] The function invoked per property.\n     * @returns {Object} Returns the new object.\n     * @example\n     *\n     * var object = { 'a': 1, 'b': '2', 'c': 3 };\n     *\n     * _.pickBy(object, _.isNumber);\n     * // => { 'a': 1, 'c': 3 }\n     */\n    function pickBy(object, predicate) {\n      if (object == null) {\n        return {};\n      }\n      var props = arrayMap(getAllKeysIn(object), function(prop) {\n        return [prop];\n      });\n      predicate = getIteratee(predicate);\n      return basePickBy(object, props, function(value, path) {\n        return predicate(value, path[0]);\n      });\n    }\n\n    /**\n     * This method is like `_.get` except that if the resolved value is a\n     * function it's invoked with the `this` binding of its parent object and\n     * its result is returned.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Object\n     * @param {Object} object The object to query.\n     * @param {Array|string} path The path of the property to resolve.\n     * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n     * @returns {*} Returns the resolved value.\n     * @example\n     *\n     * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };\n     *\n     * _.result(object, 'a[0].b.c1');\n     * // => 3\n     *\n     * _.result(object, 'a[0].b.c2');\n     * // => 4\n     *\n     * _.result(object, 'a[0].b.c3', 'default');\n     * // => 'default'\n     *\n     * _.result(object, 'a[0].b.c3', _.constant('default'));\n     * // => 'default'\n     */\n    function result(object, path, defaultValue) {\n      path = castPath(path, object);\n\n      var index = -1,\n          length = path.length;\n\n      // Ensure the loop is entered when path is empty.\n      if (!length) {\n        length = 1;\n        object = undefined;\n      }\n      while (++index < length) {\n        var value = object == null ? undefined : object[toKey(path[index])];\n        if (value === undefined) {\n          index = length;\n          value = defaultValue;\n        }\n        object = isFunction(value) ? value.call(object) : value;\n      }\n      return object;\n    }\n\n    /**\n     * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n     * it's created. Arrays are created for missing index properties while objects\n     * are created for all other missing properties. Use `_.setWith` to customize\n     * `path` creation.\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.7.0\n     * @category Object\n     * @param {Object} object The object to modify.\n     * @param {Array|string} path The path of the property to set.\n     * @param {*} value The value to set.\n     * @returns {Object} Returns `object`.\n     * @example\n     *\n     * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n     *\n     * _.set(object, 'a[0].b.c', 4);\n     * console.log(object.a[0].b.c);\n     * // => 4\n     *\n     * _.set(object, ['x', '0', 'y', 'z'], 5);\n     * console.log(object.x[0].y.z);\n     * // => 5\n     */\n    function set(object, path, value) {\n      return object == null ? object : baseSet(object, path, value);\n    }\n\n    /**\n     * This method is like `_.set` except that it accepts `customizer` which is\n     * invoked to produce the objects of `path`.  If `customizer` returns `undefined`\n     * path creation is handled by the method instead. The `customizer` is invoked\n     * with three arguments: (nsValue, key, nsObject).\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Object\n     * @param {Object} object The object to modify.\n     * @param {Array|string} path The path of the property to set.\n     * @param {*} value The value to set.\n     * @param {Function} [customizer] The function to customize assigned values.\n     * @returns {Object} Returns `object`.\n     * @example\n     *\n     * var object = {};\n     *\n     * _.setWith(object, '[0][1]', 'a', Object);\n     * // => { '0': { '1': 'a' } }\n     */\n    function setWith(object, path, value, customizer) {\n      customizer = typeof customizer == 'function' ? customizer : undefined;\n      return object == null ? object : baseSet(object, path, value, customizer);\n    }\n\n    /**\n     * Creates an array of own enumerable string keyed-value pairs for `object`\n     * which can be consumed by `_.fromPairs`. If `object` is a map or set, its\n     * entries are returned.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @alias entries\n     * @category Object\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the key-value pairs.\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.toPairs(new Foo);\n     * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)\n     */\n    var toPairs = createToPairs(keys);\n\n    /**\n     * Creates an array of own and inherited enumerable string keyed-value pairs\n     * for `object` which can be consumed by `_.fromPairs`. If `object` is a map\n     * or set, its entries are returned.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @alias entriesIn\n     * @category Object\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the key-value pairs.\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.toPairsIn(new Foo);\n     * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)\n     */\n    var toPairsIn = createToPairs(keysIn);\n\n    /**\n     * An alternative to `_.reduce`; this method transforms `object` to a new\n     * `accumulator` object which is the result of running each of its own\n     * enumerable string keyed properties thru `iteratee`, with each invocation\n     * potentially mutating the `accumulator` object. If `accumulator` is not\n     * provided, a new object with the same `[[Prototype]]` will be used. The\n     * iteratee is invoked with four arguments: (accumulator, value, key, object).\n     * Iteratee functions may exit iteration early by explicitly returning `false`.\n     *\n     * @static\n     * @memberOf _\n     * @since 1.3.0\n     * @category Object\n     * @param {Object} object The object to iterate over.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @param {*} [accumulator] The custom accumulator value.\n     * @returns {*} Returns the accumulated value.\n     * @example\n     *\n     * _.transform([2, 3, 4], function(result, n) {\n     *   result.push(n *= n);\n     *   return n % 2 == 0;\n     * }, []);\n     * // => [4, 9]\n     *\n     * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n     *   (result[value] || (result[value] = [])).push(key);\n     * }, {});\n     * // => { '1': ['a', 'c'], '2': ['b'] }\n     */\n    function transform(object, iteratee, accumulator) {\n      var isArr = isArray(object),\n          isArrLike = isArr || isBuffer(object) || isTypedArray(object);\n\n      iteratee = getIteratee(iteratee, 4);\n      if (accumulator == null) {\n        var Ctor = object && object.constructor;\n        if (isArrLike) {\n          accumulator = isArr ? new Ctor : [];\n        }\n        else if (isObject(object)) {\n          accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};\n        }\n        else {\n          accumulator = {};\n        }\n      }\n      (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {\n        return iteratee(accumulator, value, index, object);\n      });\n      return accumulator;\n    }\n\n    /**\n     * Removes the property at `path` of `object`.\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Object\n     * @param {Object} object The object to modify.\n     * @param {Array|string} path The path of the property to unset.\n     * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n     * @example\n     *\n     * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n     * _.unset(object, 'a[0].b.c');\n     * // => true\n     *\n     * console.log(object);\n     * // => { 'a': [{ 'b': {} }] };\n     *\n     * _.unset(object, ['a', '0', 'b', 'c']);\n     * // => true\n     *\n     * console.log(object);\n     * // => { 'a': [{ 'b': {} }] };\n     */\n    function unset(object, path) {\n      return object == null ? true : baseUnset(object, path);\n    }\n\n    /**\n     * This method is like `_.set` except that accepts `updater` to produce the\n     * value to set. Use `_.updateWith` to customize `path` creation. The `updater`\n     * is invoked with one argument: (value).\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.6.0\n     * @category Object\n     * @param {Object} object The object to modify.\n     * @param {Array|string} path The path of the property to set.\n     * @param {Function} updater The function to produce the updated value.\n     * @returns {Object} Returns `object`.\n     * @example\n     *\n     * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n     *\n     * _.update(object, 'a[0].b.c', function(n) { return n * n; });\n     * console.log(object.a[0].b.c);\n     * // => 9\n     *\n     * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });\n     * console.log(object.x[0].y.z);\n     * // => 0\n     */\n    function update(object, path, updater) {\n      return object == null ? object : baseUpdate(object, path, castFunction(updater));\n    }\n\n    /**\n     * This method is like `_.update` except that it accepts `customizer` which is\n     * invoked to produce the objects of `path`.  If `customizer` returns `undefined`\n     * path creation is handled by the method instead. The `customizer` is invoked\n     * with three arguments: (nsValue, key, nsObject).\n     *\n     * **Note:** This method mutates `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.6.0\n     * @category Object\n     * @param {Object} object The object to modify.\n     * @param {Array|string} path The path of the property to set.\n     * @param {Function} updater The function to produce the updated value.\n     * @param {Function} [customizer] The function to customize assigned values.\n     * @returns {Object} Returns `object`.\n     * @example\n     *\n     * var object = {};\n     *\n     * _.updateWith(object, '[0][1]', _.constant('a'), Object);\n     * // => { '0': { '1': 'a' } }\n     */\n    function updateWith(object, path, updater, customizer) {\n      customizer = typeof customizer == 'function' ? customizer : undefined;\n      return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);\n    }\n\n    /**\n     * Creates an array of the own enumerable string keyed property values of `object`.\n     *\n     * **Note:** Non-object values are coerced to objects.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Object\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of property values.\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.values(new Foo);\n     * // => [1, 2] (iteration order is not guaranteed)\n     *\n     * _.values('hi');\n     * // => ['h', 'i']\n     */\n    function values(object) {\n      return object == null ? [] : baseValues(object, keys(object));\n    }\n\n    /**\n     * Creates an array of the own and inherited enumerable string keyed property\n     * values of `object`.\n     *\n     * **Note:** Non-object values are coerced to objects.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Object\n     * @param {Object} object The object to query.\n     * @returns {Array} Returns the array of property values.\n     * @example\n     *\n     * function Foo() {\n     *   this.a = 1;\n     *   this.b = 2;\n     * }\n     *\n     * Foo.prototype.c = 3;\n     *\n     * _.valuesIn(new Foo);\n     * // => [1, 2, 3] (iteration order is not guaranteed)\n     */\n    function valuesIn(object) {\n      return object == null ? [] : baseValues(object, keysIn(object));\n    }\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Clamps `number` within the inclusive `lower` and `upper` bounds.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Number\n     * @param {number} number The number to clamp.\n     * @param {number} [lower] The lower bound.\n     * @param {number} upper The upper bound.\n     * @returns {number} Returns the clamped number.\n     * @example\n     *\n     * _.clamp(-10, -5, 5);\n     * // => -5\n     *\n     * _.clamp(10, -5, 5);\n     * // => 5\n     */\n    function clamp(number, lower, upper) {\n      if (upper === undefined) {\n        upper = lower;\n        lower = undefined;\n      }\n      if (upper !== undefined) {\n        upper = toNumber(upper);\n        upper = upper === upper ? upper : 0;\n      }\n      if (lower !== undefined) {\n        lower = toNumber(lower);\n        lower = lower === lower ? lower : 0;\n      }\n      return baseClamp(toNumber(number), lower, upper);\n    }\n\n    /**\n     * Checks if `n` is between `start` and up to, but not including, `end`. If\n     * `end` is not specified, it's set to `start` with `start` then set to `0`.\n     * If `start` is greater than `end` the params are swapped to support\n     * negative ranges.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.3.0\n     * @category Number\n     * @param {number} number The number to check.\n     * @param {number} [start=0] The start of the range.\n     * @param {number} end The end of the range.\n     * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n     * @see _.range, _.rangeRight\n     * @example\n     *\n     * _.inRange(3, 2, 4);\n     * // => true\n     *\n     * _.inRange(4, 8);\n     * // => true\n     *\n     * _.inRange(4, 2);\n     * // => false\n     *\n     * _.inRange(2, 2);\n     * // => false\n     *\n     * _.inRange(1.2, 2);\n     * // => true\n     *\n     * _.inRange(5.2, 4);\n     * // => false\n     *\n     * _.inRange(-3, -2, -6);\n     * // => true\n     */\n    function inRange(number, start, end) {\n      start = toFinite(start);\n      if (end === undefined) {\n        end = start;\n        start = 0;\n      } else {\n        end = toFinite(end);\n      }\n      number = toNumber(number);\n      return baseInRange(number, start, end);\n    }\n\n    /**\n     * Produces a random number between the inclusive `lower` and `upper` bounds.\n     * If only one argument is provided a number between `0` and the given number\n     * is returned. If `floating` is `true`, or either `lower` or `upper` are\n     * floats, a floating-point number is returned instead of an integer.\n     *\n     * **Note:** JavaScript follows the IEEE-754 standard for resolving\n     * floating-point values which can produce unexpected results.\n     *\n     * @static\n     * @memberOf _\n     * @since 0.7.0\n     * @category Number\n     * @param {number} [lower=0] The lower bound.\n     * @param {number} [upper=1] The upper bound.\n     * @param {boolean} [floating] Specify returning a floating-point number.\n     * @returns {number} Returns the random number.\n     * @example\n     *\n     * _.random(0, 5);\n     * // => an integer between 0 and 5\n     *\n     * _.random(5);\n     * // => also an integer between 0 and 5\n     *\n     * _.random(5, true);\n     * // => a floating-point number between 0 and 5\n     *\n     * _.random(1.2, 5.2);\n     * // => a floating-point number between 1.2 and 5.2\n     */\n    function random(lower, upper, floating) {\n      if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {\n        upper = floating = undefined;\n      }\n      if (floating === undefined) {\n        if (typeof upper == 'boolean') {\n          floating = upper;\n          upper = undefined;\n        }\n        else if (typeof lower == 'boolean') {\n          floating = lower;\n          lower = undefined;\n        }\n      }\n      if (lower === undefined && upper === undefined) {\n        lower = 0;\n        upper = 1;\n      }\n      else {\n        lower = toFinite(lower);\n        if (upper === undefined) {\n          upper = lower;\n          lower = 0;\n        } else {\n          upper = toFinite(upper);\n        }\n      }\n      if (lower > upper) {\n        var temp = lower;\n        lower = upper;\n        upper = temp;\n      }\n      if (floating || lower % 1 || upper % 1) {\n        var rand = nativeRandom();\n        return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);\n      }\n      return baseRandom(lower, upper);\n    }\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the camel cased string.\n     * @example\n     *\n     * _.camelCase('Foo Bar');\n     * // => 'fooBar'\n     *\n     * _.camelCase('--foo-bar--');\n     * // => 'fooBar'\n     *\n     * _.camelCase('__FOO_BAR__');\n     * // => 'fooBar'\n     */\n    var camelCase = createCompounder(function(result, word, index) {\n      word = word.toLowerCase();\n      return result + (index ? capitalize(word) : word);\n    });\n\n    /**\n     * Converts the first character of `string` to upper case and the remaining\n     * to lower case.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to capitalize.\n     * @returns {string} Returns the capitalized string.\n     * @example\n     *\n     * _.capitalize('FRED');\n     * // => 'Fred'\n     */\n    function capitalize(string) {\n      return upperFirst(toString(string).toLowerCase());\n    }\n\n    /**\n     * Deburrs `string` by converting\n     * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n     * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n     * letters to basic Latin letters and removing\n     * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to deburr.\n     * @returns {string} Returns the deburred string.\n     * @example\n     *\n     * _.deburr('déjà vu');\n     * // => 'deja vu'\n     */\n    function deburr(string) {\n      string = toString(string);\n      return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n    }\n\n    /**\n     * Checks if `string` ends with the given target string.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to inspect.\n     * @param {string} [target] The string to search for.\n     * @param {number} [position=string.length] The position to search up to.\n     * @returns {boolean} Returns `true` if `string` ends with `target`,\n     *  else `false`.\n     * @example\n     *\n     * _.endsWith('abc', 'c');\n     * // => true\n     *\n     * _.endsWith('abc', 'b');\n     * // => false\n     *\n     * _.endsWith('abc', 'b', 2);\n     * // => true\n     */\n    function endsWith(string, target, position) {\n      string = toString(string);\n      target = baseToString(target);\n\n      var length = string.length;\n      position = position === undefined\n        ? length\n        : baseClamp(toInteger(position), 0, length);\n\n      var end = position;\n      position -= target.length;\n      return position >= 0 && string.slice(position, end) == target;\n    }\n\n    /**\n     * Converts the characters \"&\", \"<\", \">\", '\"', and \"'\" in `string` to their\n     * corresponding HTML entities.\n     *\n     * **Note:** No other characters are escaped. To escape additional\n     * characters use a third-party library like [_he_](https://mths.be/he).\n     *\n     * Though the \">\" character is escaped for symmetry, characters like\n     * \">\" and \"/\" don't need escaping in HTML and have no special meaning\n     * unless they're part of a tag or unquoted attribute value. See\n     * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)\n     * (under \"semi-related fun fact\") for more details.\n     *\n     * When working with HTML you should always\n     * [quote attribute values](http://wonko.com/post/html-escaping) to reduce\n     * XSS vectors.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category String\n     * @param {string} [string=''] The string to escape.\n     * @returns {string} Returns the escaped string.\n     * @example\n     *\n     * _.escape('fred, barney, & pebbles');\n     * // => 'fred, barney, &amp; pebbles'\n     */\n    function escape(string) {\n      string = toString(string);\n      return (string && reHasUnescapedHtml.test(string))\n        ? string.replace(reUnescapedHtml, escapeHtmlChar)\n        : string;\n    }\n\n    /**\n     * Escapes the `RegExp` special characters \"^\", \"$\", \"\\\", \".\", \"*\", \"+\",\n     * \"?\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", and \"|\" in `string`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to escape.\n     * @returns {string} Returns the escaped string.\n     * @example\n     *\n     * _.escapeRegExp('[lodash](https://lodash.com/)');\n     * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n     */\n    function escapeRegExp(string) {\n      string = toString(string);\n      return (string && reHasRegExpChar.test(string))\n        ? string.replace(reRegExpChar, '\\\\$&')\n        : string;\n    }\n\n    /**\n     * Converts `string` to\n     * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the kebab cased string.\n     * @example\n     *\n     * _.kebabCase('Foo Bar');\n     * // => 'foo-bar'\n     *\n     * _.kebabCase('fooBar');\n     * // => 'foo-bar'\n     *\n     * _.kebabCase('__FOO_BAR__');\n     * // => 'foo-bar'\n     */\n    var kebabCase = createCompounder(function(result, word, index) {\n      return result + (index ? '-' : '') + word.toLowerCase();\n    });\n\n    /**\n     * Converts `string`, as space separated words, to lower case.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the lower cased string.\n     * @example\n     *\n     * _.lowerCase('--Foo-Bar--');\n     * // => 'foo bar'\n     *\n     * _.lowerCase('fooBar');\n     * // => 'foo bar'\n     *\n     * _.lowerCase('__FOO_BAR__');\n     * // => 'foo bar'\n     */\n    var lowerCase = createCompounder(function(result, word, index) {\n      return result + (index ? ' ' : '') + word.toLowerCase();\n    });\n\n    /**\n     * Converts the first character of `string` to lower case.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the converted string.\n     * @example\n     *\n     * _.lowerFirst('Fred');\n     * // => 'fred'\n     *\n     * _.lowerFirst('FRED');\n     * // => 'fRED'\n     */\n    var lowerFirst = createCaseFirst('toLowerCase');\n\n    /**\n     * Pads `string` on the left and right sides if it's shorter than `length`.\n     * Padding characters are truncated if they can't be evenly divided by `length`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to pad.\n     * @param {number} [length=0] The padding length.\n     * @param {string} [chars=' '] The string used as padding.\n     * @returns {string} Returns the padded string.\n     * @example\n     *\n     * _.pad('abc', 8);\n     * // => '  abc   '\n     *\n     * _.pad('abc', 8, '_-');\n     * // => '_-abc_-_'\n     *\n     * _.pad('abc', 3);\n     * // => 'abc'\n     */\n    function pad(string, length, chars) {\n      string = toString(string);\n      length = toInteger(length);\n\n      var strLength = length ? stringSize(string) : 0;\n      if (!length || strLength >= length) {\n        return string;\n      }\n      var mid = (length - strLength) / 2;\n      return (\n        createPadding(nativeFloor(mid), chars) +\n        string +\n        createPadding(nativeCeil(mid), chars)\n      );\n    }\n\n    /**\n     * Pads `string` on the right side if it's shorter than `length`. Padding\n     * characters are truncated if they exceed `length`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to pad.\n     * @param {number} [length=0] The padding length.\n     * @param {string} [chars=' '] The string used as padding.\n     * @returns {string} Returns the padded string.\n     * @example\n     *\n     * _.padEnd('abc', 6);\n     * // => 'abc   '\n     *\n     * _.padEnd('abc', 6, '_-');\n     * // => 'abc_-_'\n     *\n     * _.padEnd('abc', 3);\n     * // => 'abc'\n     */\n    function padEnd(string, length, chars) {\n      string = toString(string);\n      length = toInteger(length);\n\n      var strLength = length ? stringSize(string) : 0;\n      return (length && strLength < length)\n        ? (string + createPadding(length - strLength, chars))\n        : string;\n    }\n\n    /**\n     * Pads `string` on the left side if it's shorter than `length`. Padding\n     * characters are truncated if they exceed `length`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to pad.\n     * @param {number} [length=0] The padding length.\n     * @param {string} [chars=' '] The string used as padding.\n     * @returns {string} Returns the padded string.\n     * @example\n     *\n     * _.padStart('abc', 6);\n     * // => '   abc'\n     *\n     * _.padStart('abc', 6, '_-');\n     * // => '_-_abc'\n     *\n     * _.padStart('abc', 3);\n     * // => 'abc'\n     */\n    function padStart(string, length, chars) {\n      string = toString(string);\n      length = toInteger(length);\n\n      var strLength = length ? stringSize(string) : 0;\n      return (length && strLength < length)\n        ? (createPadding(length - strLength, chars) + string)\n        : string;\n    }\n\n    /**\n     * Converts `string` to an integer of the specified radix. If `radix` is\n     * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n     * hexadecimal, in which case a `radix` of `16` is used.\n     *\n     * **Note:** This method aligns with the\n     * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n     *\n     * @static\n     * @memberOf _\n     * @since 1.1.0\n     * @category String\n     * @param {string} string The string to convert.\n     * @param {number} [radix=10] The radix to interpret `value` by.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {number} Returns the converted integer.\n     * @example\n     *\n     * _.parseInt('08');\n     * // => 8\n     *\n     * _.map(['6', '08', '10'], _.parseInt);\n     * // => [6, 8, 10]\n     */\n    function parseInt(string, radix, guard) {\n      if (guard || radix == null) {\n        radix = 0;\n      } else if (radix) {\n        radix = +radix;\n      }\n      return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n    }\n\n    /**\n     * Repeats the given string `n` times.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to repeat.\n     * @param {number} [n=1] The number of times to repeat the string.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {string} Returns the repeated string.\n     * @example\n     *\n     * _.repeat('*', 3);\n     * // => '***'\n     *\n     * _.repeat('abc', 2);\n     * // => 'abcabc'\n     *\n     * _.repeat('abc', 0);\n     * // => ''\n     */\n    function repeat(string, n, guard) {\n      if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {\n        n = 1;\n      } else {\n        n = toInteger(n);\n      }\n      return baseRepeat(toString(string), n);\n    }\n\n    /**\n     * Replaces matches for `pattern` in `string` with `replacement`.\n     *\n     * **Note:** This method is based on\n     * [`String#replace`](https://mdn.io/String/replace).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to modify.\n     * @param {RegExp|string} pattern The pattern to replace.\n     * @param {Function|string} replacement The match replacement.\n     * @returns {string} Returns the modified string.\n     * @example\n     *\n     * _.replace('Hi Fred', 'Fred', 'Barney');\n     * // => 'Hi Barney'\n     */\n    function replace() {\n      var args = arguments,\n          string = toString(args[0]);\n\n      return args.length < 3 ? string : string.replace(args[1], args[2]);\n    }\n\n    /**\n     * Converts `string` to\n     * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the snake cased string.\n     * @example\n     *\n     * _.snakeCase('Foo Bar');\n     * // => 'foo_bar'\n     *\n     * _.snakeCase('fooBar');\n     * // => 'foo_bar'\n     *\n     * _.snakeCase('--FOO-BAR--');\n     * // => 'foo_bar'\n     */\n    var snakeCase = createCompounder(function(result, word, index) {\n      return result + (index ? '_' : '') + word.toLowerCase();\n    });\n\n    /**\n     * Splits `string` by `separator`.\n     *\n     * **Note:** This method is based on\n     * [`String#split`](https://mdn.io/String/split).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to split.\n     * @param {RegExp|string} separator The separator pattern to split by.\n     * @param {number} [limit] The length to truncate results to.\n     * @returns {Array} Returns the string segments.\n     * @example\n     *\n     * _.split('a-b-c', '-', 2);\n     * // => ['a', 'b']\n     */\n    function split(string, separator, limit) {\n      if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {\n        separator = limit = undefined;\n      }\n      limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;\n      if (!limit) {\n        return [];\n      }\n      string = toString(string);\n      if (string && (\n            typeof separator == 'string' ||\n            (separator != null && !isRegExp(separator))\n          )) {\n        separator = baseToString(separator);\n        if (!separator && hasUnicode(string)) {\n          return castSlice(stringToArray(string), 0, limit);\n        }\n      }\n      return string.split(separator, limit);\n    }\n\n    /**\n     * Converts `string` to\n     * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).\n     *\n     * @static\n     * @memberOf _\n     * @since 3.1.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the start cased string.\n     * @example\n     *\n     * _.startCase('--foo-bar--');\n     * // => 'Foo Bar'\n     *\n     * _.startCase('fooBar');\n     * // => 'Foo Bar'\n     *\n     * _.startCase('__FOO_BAR__');\n     * // => 'FOO BAR'\n     */\n    var startCase = createCompounder(function(result, word, index) {\n      return result + (index ? ' ' : '') + upperFirst(word);\n    });\n\n    /**\n     * Checks if `string` starts with the given target string.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to inspect.\n     * @param {string} [target] The string to search for.\n     * @param {number} [position=0] The position to search from.\n     * @returns {boolean} Returns `true` if `string` starts with `target`,\n     *  else `false`.\n     * @example\n     *\n     * _.startsWith('abc', 'a');\n     * // => true\n     *\n     * _.startsWith('abc', 'b');\n     * // => false\n     *\n     * _.startsWith('abc', 'b', 1);\n     * // => true\n     */\n    function startsWith(string, target, position) {\n      string = toString(string);\n      position = position == null\n        ? 0\n        : baseClamp(toInteger(position), 0, string.length);\n\n      target = baseToString(target);\n      return string.slice(position, position + target.length) == target;\n    }\n\n    /**\n     * Creates a compiled template function that can interpolate data properties\n     * in \"interpolate\" delimiters, HTML-escape interpolated data properties in\n     * \"escape\" delimiters, and execute JavaScript in \"evaluate\" delimiters. Data\n     * properties may be accessed as free variables in the template. If a setting\n     * object is given, it takes precedence over `_.templateSettings` values.\n     *\n     * **Note:** In the development build `_.template` utilizes\n     * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)\n     * for easier debugging.\n     *\n     * For more information on precompiling templates see\n     * [lodash's custom builds documentation](https://lodash.com/custom-builds).\n     *\n     * For more information on Chrome extension sandboxes see\n     * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category String\n     * @param {string} [string=''] The template string.\n     * @param {Object} [options={}] The options object.\n     * @param {RegExp} [options.escape=_.templateSettings.escape]\n     *  The HTML \"escape\" delimiter.\n     * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]\n     *  The \"evaluate\" delimiter.\n     * @param {Object} [options.imports=_.templateSettings.imports]\n     *  An object to import into the template as free variables.\n     * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]\n     *  The \"interpolate\" delimiter.\n     * @param {string} [options.sourceURL='lodash.templateSources[n]']\n     *  The sourceURL of the compiled template.\n     * @param {string} [options.variable='obj']\n     *  The data object variable name.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Function} Returns the compiled template function.\n     * @example\n     *\n     * // Use the \"interpolate\" delimiter to create a compiled template.\n     * var compiled = _.template('hello <%= user %>!');\n     * compiled({ 'user': 'fred' });\n     * // => 'hello fred!'\n     *\n     * // Use the HTML \"escape\" delimiter to escape data property values.\n     * var compiled = _.template('<b><%- value %></b>');\n     * compiled({ 'value': '<script>' });\n     * // => '<b>&lt;script&gt;</b>'\n     *\n     * // Use the \"evaluate\" delimiter to execute JavaScript and generate HTML.\n     * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');\n     * compiled({ 'users': ['fred', 'barney'] });\n     * // => '<li>fred</li><li>barney</li>'\n     *\n     * // Use the internal `print` function in \"evaluate\" delimiters.\n     * var compiled = _.template('<% print(\"hello \" + user); %>!');\n     * compiled({ 'user': 'barney' });\n     * // => 'hello barney!'\n     *\n     * // Use the ES template literal delimiter as an \"interpolate\" delimiter.\n     * // Disable support by replacing the \"interpolate\" delimiter.\n     * var compiled = _.template('hello ${ user }!');\n     * compiled({ 'user': 'pebbles' });\n     * // => 'hello pebbles!'\n     *\n     * // Use backslashes to treat delimiters as plain text.\n     * var compiled = _.template('<%= \"\\\\<%- value %\\\\>\" %>');\n     * compiled({ 'value': 'ignored' });\n     * // => '<%- value %>'\n     *\n     * // Use the `imports` option to import `jQuery` as `jq`.\n     * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';\n     * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });\n     * compiled({ 'users': ['fred', 'barney'] });\n     * // => '<li>fred</li><li>barney</li>'\n     *\n     * // Use the `sourceURL` option to specify a custom sourceURL for the template.\n     * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });\n     * compiled(data);\n     * // => Find the source of \"greeting.jst\" under the Sources tab or Resources panel of the web inspector.\n     *\n     * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.\n     * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });\n     * compiled.source;\n     * // => function(data) {\n     * //   var __t, __p = '';\n     * //   __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';\n     * //   return __p;\n     * // }\n     *\n     * // Use custom template delimiters.\n     * _.templateSettings.interpolate = /{{([\\s\\S]+?)}}/g;\n     * var compiled = _.template('hello {{ user }}!');\n     * compiled({ 'user': 'mustache' });\n     * // => 'hello mustache!'\n     *\n     * // Use the `source` property to inline compiled templates for meaningful\n     * // line numbers in error messages and stack traces.\n     * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\\\n     *   var JST = {\\\n     *     \"main\": ' + _.template(mainText).source + '\\\n     *   };\\\n     * ');\n     */\n    function template(string, options, guard) {\n      // Based on John Resig's `tmpl` implementation\n      // (http://ejohn.org/blog/javascript-micro-templating/)\n      // and Laura Doktorova's doT.js (https://github.com/olado/doT).\n      var settings = lodash.templateSettings;\n\n      if (guard && isIterateeCall(string, options, guard)) {\n        options = undefined;\n      }\n      string = toString(string);\n      options = assignInWith({}, options, settings, customDefaultsAssignIn);\n\n      var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),\n          importsKeys = keys(imports),\n          importsValues = baseValues(imports, importsKeys);\n\n      var isEscaping,\n          isEvaluating,\n          index = 0,\n          interpolate = options.interpolate || reNoMatch,\n          source = \"__p += '\";\n\n      // Compile the regexp to match each delimiter.\n      var reDelimiters = RegExp(\n        (options.escape || reNoMatch).source + '|' +\n        interpolate.source + '|' +\n        (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +\n        (options.evaluate || reNoMatch).source + '|$'\n      , 'g');\n\n      // Use a sourceURL for easier debugging.\n      var sourceURL = '//# sourceURL=' +\n        ('sourceURL' in options\n          ? options.sourceURL\n          : ('lodash.templateSources[' + (++templateCounter) + ']')\n        ) + '\\n';\n\n      string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {\n        interpolateValue || (interpolateValue = esTemplateValue);\n\n        // Escape characters that can't be included in string literals.\n        source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);\n\n        // Replace delimiters with snippets.\n        if (escapeValue) {\n          isEscaping = true;\n          source += \"' +\\n__e(\" + escapeValue + \") +\\n'\";\n        }\n        if (evaluateValue) {\n          isEvaluating = true;\n          source += \"';\\n\" + evaluateValue + \";\\n__p += '\";\n        }\n        if (interpolateValue) {\n          source += \"' +\\n((__t = (\" + interpolateValue + \")) == null ? '' : __t) +\\n'\";\n        }\n        index = offset + match.length;\n\n        // The JS engine embedded in Adobe products needs `match` returned in\n        // order to produce the correct `offset` value.\n        return match;\n      });\n\n      source += \"';\\n\";\n\n      // If `variable` is not specified wrap a with-statement around the generated\n      // code to add the data object to the top of the scope chain.\n      var variable = options.variable;\n      if (!variable) {\n        source = 'with (obj) {\\n' + source + '\\n}\\n';\n      }\n      // Cleanup code by stripping empty strings.\n      source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)\n        .replace(reEmptyStringMiddle, '$1')\n        .replace(reEmptyStringTrailing, '$1;');\n\n      // Frame code as the function body.\n      source = 'function(' + (variable || 'obj') + ') {\\n' +\n        (variable\n          ? ''\n          : 'obj || (obj = {});\\n'\n        ) +\n        \"var __t, __p = ''\" +\n        (isEscaping\n           ? ', __e = _.escape'\n           : ''\n        ) +\n        (isEvaluating\n          ? ', __j = Array.prototype.join;\\n' +\n            \"function print() { __p += __j.call(arguments, '') }\\n\"\n          : ';\\n'\n        ) +\n        source +\n        'return __p\\n}';\n\n      var result = attempt(function() {\n        return Function(importsKeys, sourceURL + 'return ' + source)\n          .apply(undefined, importsValues);\n      });\n\n      // Provide the compiled function's source by its `toString` method or\n      // the `source` property as a convenience for inlining compiled templates.\n      result.source = source;\n      if (isError(result)) {\n        throw result;\n      }\n      return result;\n    }\n\n    /**\n     * Converts `string`, as a whole, to lower case just like\n     * [String#toLowerCase](https://mdn.io/toLowerCase).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the lower cased string.\n     * @example\n     *\n     * _.toLower('--Foo-Bar--');\n     * // => '--foo-bar--'\n     *\n     * _.toLower('fooBar');\n     * // => 'foobar'\n     *\n     * _.toLower('__FOO_BAR__');\n     * // => '__foo_bar__'\n     */\n    function toLower(value) {\n      return toString(value).toLowerCase();\n    }\n\n    /**\n     * Converts `string`, as a whole, to upper case just like\n     * [String#toUpperCase](https://mdn.io/toUpperCase).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the upper cased string.\n     * @example\n     *\n     * _.toUpper('--foo-bar--');\n     * // => '--FOO-BAR--'\n     *\n     * _.toUpper('fooBar');\n     * // => 'FOOBAR'\n     *\n     * _.toUpper('__foo_bar__');\n     * // => '__FOO_BAR__'\n     */\n    function toUpper(value) {\n      return toString(value).toUpperCase();\n    }\n\n    /**\n     * Removes leading and trailing whitespace or specified characters from `string`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to trim.\n     * @param {string} [chars=whitespace] The characters to trim.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {string} Returns the trimmed string.\n     * @example\n     *\n     * _.trim('  abc  ');\n     * // => 'abc'\n     *\n     * _.trim('-_-abc-_-', '_-');\n     * // => 'abc'\n     *\n     * _.map(['  foo  ', '  bar  '], _.trim);\n     * // => ['foo', 'bar']\n     */\n    function trim(string, chars, guard) {\n      string = toString(string);\n      if (string && (guard || chars === undefined)) {\n        return string.replace(reTrim, '');\n      }\n      if (!string || !(chars = baseToString(chars))) {\n        return string;\n      }\n      var strSymbols = stringToArray(string),\n          chrSymbols = stringToArray(chars),\n          start = charsStartIndex(strSymbols, chrSymbols),\n          end = charsEndIndex(strSymbols, chrSymbols) + 1;\n\n      return castSlice(strSymbols, start, end).join('');\n    }\n\n    /**\n     * Removes trailing whitespace or specified characters from `string`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to trim.\n     * @param {string} [chars=whitespace] The characters to trim.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {string} Returns the trimmed string.\n     * @example\n     *\n     * _.trimEnd('  abc  ');\n     * // => '  abc'\n     *\n     * _.trimEnd('-_-abc-_-', '_-');\n     * // => '-_-abc'\n     */\n    function trimEnd(string, chars, guard) {\n      string = toString(string);\n      if (string && (guard || chars === undefined)) {\n        return string.replace(reTrimEnd, '');\n      }\n      if (!string || !(chars = baseToString(chars))) {\n        return string;\n      }\n      var strSymbols = stringToArray(string),\n          end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;\n\n      return castSlice(strSymbols, 0, end).join('');\n    }\n\n    /**\n     * Removes leading whitespace or specified characters from `string`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to trim.\n     * @param {string} [chars=whitespace] The characters to trim.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {string} Returns the trimmed string.\n     * @example\n     *\n     * _.trimStart('  abc  ');\n     * // => 'abc  '\n     *\n     * _.trimStart('-_-abc-_-', '_-');\n     * // => 'abc-_-'\n     */\n    function trimStart(string, chars, guard) {\n      string = toString(string);\n      if (string && (guard || chars === undefined)) {\n        return string.replace(reTrimStart, '');\n      }\n      if (!string || !(chars = baseToString(chars))) {\n        return string;\n      }\n      var strSymbols = stringToArray(string),\n          start = charsStartIndex(strSymbols, stringToArray(chars));\n\n      return castSlice(strSymbols, start).join('');\n    }\n\n    /**\n     * Truncates `string` if it's longer than the given maximum string length.\n     * The last characters of the truncated string are replaced with the omission\n     * string which defaults to \"...\".\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to truncate.\n     * @param {Object} [options={}] The options object.\n     * @param {number} [options.length=30] The maximum string length.\n     * @param {string} [options.omission='...'] The string to indicate text is omitted.\n     * @param {RegExp|string} [options.separator] The separator pattern to truncate to.\n     * @returns {string} Returns the truncated string.\n     * @example\n     *\n     * _.truncate('hi-diddly-ho there, neighborino');\n     * // => 'hi-diddly-ho there, neighbo...'\n     *\n     * _.truncate('hi-diddly-ho there, neighborino', {\n     *   'length': 24,\n     *   'separator': ' '\n     * });\n     * // => 'hi-diddly-ho there,...'\n     *\n     * _.truncate('hi-diddly-ho there, neighborino', {\n     *   'length': 24,\n     *   'separator': /,? +/\n     * });\n     * // => 'hi-diddly-ho there...'\n     *\n     * _.truncate('hi-diddly-ho there, neighborino', {\n     *   'omission': ' [...]'\n     * });\n     * // => 'hi-diddly-ho there, neig [...]'\n     */\n    function truncate(string, options) {\n      var length = DEFAULT_TRUNC_LENGTH,\n          omission = DEFAULT_TRUNC_OMISSION;\n\n      if (isObject(options)) {\n        var separator = 'separator' in options ? options.separator : separator;\n        length = 'length' in options ? toInteger(options.length) : length;\n        omission = 'omission' in options ? baseToString(options.omission) : omission;\n      }\n      string = toString(string);\n\n      var strLength = string.length;\n      if (hasUnicode(string)) {\n        var strSymbols = stringToArray(string);\n        strLength = strSymbols.length;\n      }\n      if (length >= strLength) {\n        return string;\n      }\n      var end = length - stringSize(omission);\n      if (end < 1) {\n        return omission;\n      }\n      var result = strSymbols\n        ? castSlice(strSymbols, 0, end).join('')\n        : string.slice(0, end);\n\n      if (separator === undefined) {\n        return result + omission;\n      }\n      if (strSymbols) {\n        end += (result.length - end);\n      }\n      if (isRegExp(separator)) {\n        if (string.slice(end).search(separator)) {\n          var match,\n              substring = result;\n\n          if (!separator.global) {\n            separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');\n          }\n          separator.lastIndex = 0;\n          while ((match = separator.exec(substring))) {\n            var newEnd = match.index;\n          }\n          result = result.slice(0, newEnd === undefined ? end : newEnd);\n        }\n      } else if (string.indexOf(baseToString(separator), end) != end) {\n        var index = result.lastIndexOf(separator);\n        if (index > -1) {\n          result = result.slice(0, index);\n        }\n      }\n      return result + omission;\n    }\n\n    /**\n     * The inverse of `_.escape`; this method converts the HTML entities\n     * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to\n     * their corresponding characters.\n     *\n     * **Note:** No other HTML entities are unescaped. To unescape additional\n     * HTML entities use a third-party library like [_he_](https://mths.be/he).\n     *\n     * @static\n     * @memberOf _\n     * @since 0.6.0\n     * @category String\n     * @param {string} [string=''] The string to unescape.\n     * @returns {string} Returns the unescaped string.\n     * @example\n     *\n     * _.unescape('fred, barney, &amp; pebbles');\n     * // => 'fred, barney, & pebbles'\n     */\n    function unescape(string) {\n      string = toString(string);\n      return (string && reHasEscapedHtml.test(string))\n        ? string.replace(reEscapedHtml, unescapeHtmlChar)\n        : string;\n    }\n\n    /**\n     * Converts `string`, as space separated words, to upper case.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the upper cased string.\n     * @example\n     *\n     * _.upperCase('--foo-bar');\n     * // => 'FOO BAR'\n     *\n     * _.upperCase('fooBar');\n     * // => 'FOO BAR'\n     *\n     * _.upperCase('__foo_bar__');\n     * // => 'FOO BAR'\n     */\n    var upperCase = createCompounder(function(result, word, index) {\n      return result + (index ? ' ' : '') + word.toUpperCase();\n    });\n\n    /**\n     * Converts the first character of `string` to upper case.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category String\n     * @param {string} [string=''] The string to convert.\n     * @returns {string} Returns the converted string.\n     * @example\n     *\n     * _.upperFirst('fred');\n     * // => 'Fred'\n     *\n     * _.upperFirst('FRED');\n     * // => 'FRED'\n     */\n    var upperFirst = createCaseFirst('toUpperCase');\n\n    /**\n     * Splits `string` into an array of its words.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category String\n     * @param {string} [string=''] The string to inspect.\n     * @param {RegExp|string} [pattern] The pattern to match words.\n     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n     * @returns {Array} Returns the words of `string`.\n     * @example\n     *\n     * _.words('fred, barney, & pebbles');\n     * // => ['fred', 'barney', 'pebbles']\n     *\n     * _.words('fred, barney, & pebbles', /[^, ]+/g);\n     * // => ['fred', 'barney', '&', 'pebbles']\n     */\n    function words(string, pattern, guard) {\n      string = toString(string);\n      pattern = guard ? undefined : pattern;\n\n      if (pattern === undefined) {\n        return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);\n      }\n      return string.match(pattern) || [];\n    }\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Attempts to invoke `func`, returning either the result or the caught error\n     * object. Any additional arguments are provided to `func` when it's invoked.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Util\n     * @param {Function} func The function to attempt.\n     * @param {...*} [args] The arguments to invoke `func` with.\n     * @returns {*} Returns the `func` result or error object.\n     * @example\n     *\n     * // Avoid throwing errors for invalid selectors.\n     * var elements = _.attempt(function(selector) {\n     *   return document.querySelectorAll(selector);\n     * }, '>_>');\n     *\n     * if (_.isError(elements)) {\n     *   elements = [];\n     * }\n     */\n    var attempt = baseRest(function(func, args) {\n      try {\n        return apply(func, undefined, args);\n      } catch (e) {\n        return isError(e) ? e : new Error(e);\n      }\n    });\n\n    /**\n     * Binds methods of an object to the object itself, overwriting the existing\n     * method.\n     *\n     * **Note:** This method doesn't set the \"length\" property of bound functions.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Util\n     * @param {Object} object The object to bind and assign the bound methods to.\n     * @param {...(string|string[])} methodNames The object method names to bind.\n     * @returns {Object} Returns `object`.\n     * @example\n     *\n     * var view = {\n     *   'label': 'docs',\n     *   'click': function() {\n     *     console.log('clicked ' + this.label);\n     *   }\n     * };\n     *\n     * _.bindAll(view, ['click']);\n     * jQuery(element).on('click', view.click);\n     * // => Logs 'clicked docs' when clicked.\n     */\n    var bindAll = flatRest(function(object, methodNames) {\n      arrayEach(methodNames, function(key) {\n        key = toKey(key);\n        baseAssignValue(object, key, bind(object[key], object));\n      });\n      return object;\n    });\n\n    /**\n     * Creates a function that iterates over `pairs` and invokes the corresponding\n     * function of the first predicate to return truthy. The predicate-function\n     * pairs are invoked with the `this` binding and arguments of the created\n     * function.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Util\n     * @param {Array} pairs The predicate-function pairs.\n     * @returns {Function} Returns the new composite function.\n     * @example\n     *\n     * var func = _.cond([\n     *   [_.matches({ 'a': 1 }),           _.constant('matches A')],\n     *   [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],\n     *   [_.stubTrue,                      _.constant('no match')]\n     * ]);\n     *\n     * func({ 'a': 1, 'b': 2 });\n     * // => 'matches A'\n     *\n     * func({ 'a': 0, 'b': 1 });\n     * // => 'matches B'\n     *\n     * func({ 'a': '1', 'b': '2' });\n     * // => 'no match'\n     */\n    function cond(pairs) {\n      var length = pairs == null ? 0 : pairs.length,\n          toIteratee = getIteratee();\n\n      pairs = !length ? [] : arrayMap(pairs, function(pair) {\n        if (typeof pair[1] != 'function') {\n          throw new TypeError(FUNC_ERROR_TEXT);\n        }\n        return [toIteratee(pair[0]), pair[1]];\n      });\n\n      return baseRest(function(args) {\n        var index = -1;\n        while (++index < length) {\n          var pair = pairs[index];\n          if (apply(pair[0], this, args)) {\n            return apply(pair[1], this, args);\n          }\n        }\n      });\n    }\n\n    /**\n     * Creates a function that invokes the predicate properties of `source` with\n     * the corresponding property values of a given object, returning `true` if\n     * all predicates return truthy, else `false`.\n     *\n     * **Note:** The created function is equivalent to `_.conformsTo` with\n     * `source` partially applied.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Util\n     * @param {Object} source The object of property predicates to conform to.\n     * @returns {Function} Returns the new spec function.\n     * @example\n     *\n     * var objects = [\n     *   { 'a': 2, 'b': 1 },\n     *   { 'a': 1, 'b': 2 }\n     * ];\n     *\n     * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));\n     * // => [{ 'a': 1, 'b': 2 }]\n     */\n    function conforms(source) {\n      return baseConforms(baseClone(source, CLONE_DEEP_FLAG));\n    }\n\n    /**\n     * Creates a function that returns `value`.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.4.0\n     * @category Util\n     * @param {*} value The value to return from the new function.\n     * @returns {Function} Returns the new constant function.\n     * @example\n     *\n     * var objects = _.times(2, _.constant({ 'a': 1 }));\n     *\n     * console.log(objects);\n     * // => [{ 'a': 1 }, { 'a': 1 }]\n     *\n     * console.log(objects[0] === objects[1]);\n     * // => true\n     */\n    function constant(value) {\n      return function() {\n        return value;\n      };\n    }\n\n    /**\n     * Checks `value` to determine whether a default value should be returned in\n     * its place. The `defaultValue` is returned if `value` is `NaN`, `null`,\n     * or `undefined`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.14.0\n     * @category Util\n     * @param {*} value The value to check.\n     * @param {*} defaultValue The default value.\n     * @returns {*} Returns the resolved value.\n     * @example\n     *\n     * _.defaultTo(1, 10);\n     * // => 1\n     *\n     * _.defaultTo(undefined, 10);\n     * // => 10\n     */\n    function defaultTo(value, defaultValue) {\n      return (value == null || value !== value) ? defaultValue : value;\n    }\n\n    /**\n     * Creates a function that returns the result of invoking the given functions\n     * with the `this` binding of the created function, where each successive\n     * invocation is supplied the return value of the previous.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Util\n     * @param {...(Function|Function[])} [funcs] The functions to invoke.\n     * @returns {Function} Returns the new composite function.\n     * @see _.flowRight\n     * @example\n     *\n     * function square(n) {\n     *   return n * n;\n     * }\n     *\n     * var addSquare = _.flow([_.add, square]);\n     * addSquare(1, 2);\n     * // => 9\n     */\n    var flow = createFlow();\n\n    /**\n     * This method is like `_.flow` except that it creates a function that\n     * invokes the given functions from right to left.\n     *\n     * @static\n     * @since 3.0.0\n     * @memberOf _\n     * @category Util\n     * @param {...(Function|Function[])} [funcs] The functions to invoke.\n     * @returns {Function} Returns the new composite function.\n     * @see _.flow\n     * @example\n     *\n     * function square(n) {\n     *   return n * n;\n     * }\n     *\n     * var addSquare = _.flowRight([square, _.add]);\n     * addSquare(1, 2);\n     * // => 9\n     */\n    var flowRight = createFlow(true);\n\n    /**\n     * This method returns the first argument it receives.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Util\n     * @param {*} value Any value.\n     * @returns {*} Returns `value`.\n     * @example\n     *\n     * var object = { 'a': 1 };\n     *\n     * console.log(_.identity(object) === object);\n     * // => true\n     */\n    function identity(value) {\n      return value;\n    }\n\n    /**\n     * Creates a function that invokes `func` with the arguments of the created\n     * function. If `func` is a property name, the created function returns the\n     * property value for a given element. If `func` is an array or object, the\n     * created function returns `true` for elements that contain the equivalent\n     * source properties, otherwise it returns `false`.\n     *\n     * @static\n     * @since 4.0.0\n     * @memberOf _\n     * @category Util\n     * @param {*} [func=_.identity] The value to convert to a callback.\n     * @returns {Function} Returns the callback.\n     * @example\n     *\n     * var users = [\n     *   { 'user': 'barney', 'age': 36, 'active': true },\n     *   { 'user': 'fred',   'age': 40, 'active': false }\n     * ];\n     *\n     * // The `_.matches` iteratee shorthand.\n     * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));\n     * // => [{ 'user': 'barney', 'age': 36, 'active': true }]\n     *\n     * // The `_.matchesProperty` iteratee shorthand.\n     * _.filter(users, _.iteratee(['user', 'fred']));\n     * // => [{ 'user': 'fred', 'age': 40 }]\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.map(users, _.iteratee('user'));\n     * // => ['barney', 'fred']\n     *\n     * // Create custom iteratee shorthands.\n     * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {\n     *   return !_.isRegExp(func) ? iteratee(func) : function(string) {\n     *     return func.test(string);\n     *   };\n     * });\n     *\n     * _.filter(['abc', 'def'], /ef/);\n     * // => ['def']\n     */\n    function iteratee(func) {\n      return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));\n    }\n\n    /**\n     * Creates a function that performs a partial deep comparison between a given\n     * object and `source`, returning `true` if the given object has equivalent\n     * property values, else `false`.\n     *\n     * **Note:** The created function is equivalent to `_.isMatch` with `source`\n     * partially applied.\n     *\n     * Partial comparisons will match empty array and empty object `source`\n     * values against any array or object value, respectively. See `_.isEqual`\n     * for a list of supported value comparisons.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Util\n     * @param {Object} source The object of property values to match.\n     * @returns {Function} Returns the new spec function.\n     * @example\n     *\n     * var objects = [\n     *   { 'a': 1, 'b': 2, 'c': 3 },\n     *   { 'a': 4, 'b': 5, 'c': 6 }\n     * ];\n     *\n     * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));\n     * // => [{ 'a': 4, 'b': 5, 'c': 6 }]\n     */\n    function matches(source) {\n      return baseMatches(baseClone(source, CLONE_DEEP_FLAG));\n    }\n\n    /**\n     * Creates a function that performs a partial deep comparison between the\n     * value at `path` of a given object to `srcValue`, returning `true` if the\n     * object value is equivalent, else `false`.\n     *\n     * **Note:** Partial comparisons will match empty array and empty object\n     * `srcValue` values against any array or object value, respectively. See\n     * `_.isEqual` for a list of supported value comparisons.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.2.0\n     * @category Util\n     * @param {Array|string} path The path of the property to get.\n     * @param {*} srcValue The value to match.\n     * @returns {Function} Returns the new spec function.\n     * @example\n     *\n     * var objects = [\n     *   { 'a': 1, 'b': 2, 'c': 3 },\n     *   { 'a': 4, 'b': 5, 'c': 6 }\n     * ];\n     *\n     * _.find(objects, _.matchesProperty('a', 4));\n     * // => { 'a': 4, 'b': 5, 'c': 6 }\n     */\n    function matchesProperty(path, srcValue) {\n      return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));\n    }\n\n    /**\n     * Creates a function that invokes the method at `path` of a given object.\n     * Any additional arguments are provided to the invoked method.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.7.0\n     * @category Util\n     * @param {Array|string} path The path of the method to invoke.\n     * @param {...*} [args] The arguments to invoke the method with.\n     * @returns {Function} Returns the new invoker function.\n     * @example\n     *\n     * var objects = [\n     *   { 'a': { 'b': _.constant(2) } },\n     *   { 'a': { 'b': _.constant(1) } }\n     * ];\n     *\n     * _.map(objects, _.method('a.b'));\n     * // => [2, 1]\n     *\n     * _.map(objects, _.method(['a', 'b']));\n     * // => [2, 1]\n     */\n    var method = baseRest(function(path, args) {\n      return function(object) {\n        return baseInvoke(object, path, args);\n      };\n    });\n\n    /**\n     * The opposite of `_.method`; this method creates a function that invokes\n     * the method at a given path of `object`. Any additional arguments are\n     * provided to the invoked method.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.7.0\n     * @category Util\n     * @param {Object} object The object to query.\n     * @param {...*} [args] The arguments to invoke the method with.\n     * @returns {Function} Returns the new invoker function.\n     * @example\n     *\n     * var array = _.times(3, _.constant),\n     *     object = { 'a': array, 'b': array, 'c': array };\n     *\n     * _.map(['a[2]', 'c[0]'], _.methodOf(object));\n     * // => [2, 0]\n     *\n     * _.map([['a', '2'], ['c', '0']], _.methodOf(object));\n     * // => [2, 0]\n     */\n    var methodOf = baseRest(function(object, args) {\n      return function(path) {\n        return baseInvoke(object, path, args);\n      };\n    });\n\n    /**\n     * Adds all own enumerable string keyed function properties of a source\n     * object to the destination object. If `object` is a function, then methods\n     * are added to its prototype as well.\n     *\n     * **Note:** Use `_.runInContext` to create a pristine `lodash` function to\n     * avoid conflicts caused by modifying the original.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Util\n     * @param {Function|Object} [object=lodash] The destination object.\n     * @param {Object} source The object of functions to add.\n     * @param {Object} [options={}] The options object.\n     * @param {boolean} [options.chain=true] Specify whether mixins are chainable.\n     * @returns {Function|Object} Returns `object`.\n     * @example\n     *\n     * function vowels(string) {\n     *   return _.filter(string, function(v) {\n     *     return /[aeiou]/i.test(v);\n     *   });\n     * }\n     *\n     * _.mixin({ 'vowels': vowels });\n     * _.vowels('fred');\n     * // => ['e']\n     *\n     * _('fred').vowels().value();\n     * // => ['e']\n     *\n     * _.mixin({ 'vowels': vowels }, { 'chain': false });\n     * _('fred').vowels();\n     * // => ['e']\n     */\n    function mixin(object, source, options) {\n      var props = keys(source),\n          methodNames = baseFunctions(source, props);\n\n      if (options == null &&\n          !(isObject(source) && (methodNames.length || !props.length))) {\n        options = source;\n        source = object;\n        object = this;\n        methodNames = baseFunctions(source, keys(source));\n      }\n      var chain = !(isObject(options) && 'chain' in options) || !!options.chain,\n          isFunc = isFunction(object);\n\n      arrayEach(methodNames, function(methodName) {\n        var func = source[methodName];\n        object[methodName] = func;\n        if (isFunc) {\n          object.prototype[methodName] = function() {\n            var chainAll = this.__chain__;\n            if (chain || chainAll) {\n              var result = object(this.__wrapped__),\n                  actions = result.__actions__ = copyArray(this.__actions__);\n\n              actions.push({ 'func': func, 'args': arguments, 'thisArg': object });\n              result.__chain__ = chainAll;\n              return result;\n            }\n            return func.apply(object, arrayPush([this.value()], arguments));\n          };\n        }\n      });\n\n      return object;\n    }\n\n    /**\n     * Reverts the `_` variable to its previous value and returns a reference to\n     * the `lodash` function.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Util\n     * @returns {Function} Returns the `lodash` function.\n     * @example\n     *\n     * var lodash = _.noConflict();\n     */\n    function noConflict() {\n      if (root._ === this) {\n        root._ = oldDash;\n      }\n      return this;\n    }\n\n    /**\n     * This method returns `undefined`.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.3.0\n     * @category Util\n     * @example\n     *\n     * _.times(2, _.noop);\n     * // => [undefined, undefined]\n     */\n    function noop() {\n      // No operation performed.\n    }\n\n    /**\n     * Creates a function that gets the argument at index `n`. If `n` is negative,\n     * the nth argument from the end is returned.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Util\n     * @param {number} [n=0] The index of the argument to return.\n     * @returns {Function} Returns the new pass-thru function.\n     * @example\n     *\n     * var func = _.nthArg(1);\n     * func('a', 'b', 'c', 'd');\n     * // => 'b'\n     *\n     * var func = _.nthArg(-2);\n     * func('a', 'b', 'c', 'd');\n     * // => 'c'\n     */\n    function nthArg(n) {\n      n = toInteger(n);\n      return baseRest(function(args) {\n        return baseNth(args, n);\n      });\n    }\n\n    /**\n     * Creates a function that invokes `iteratees` with the arguments it receives\n     * and returns their results.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Util\n     * @param {...(Function|Function[])} [iteratees=[_.identity]]\n     *  The iteratees to invoke.\n     * @returns {Function} Returns the new function.\n     * @example\n     *\n     * var func = _.over([Math.max, Math.min]);\n     *\n     * func(1, 2, 3, 4);\n     * // => [4, 1]\n     */\n    var over = createOver(arrayMap);\n\n    /**\n     * Creates a function that checks if **all** of the `predicates` return\n     * truthy when invoked with the arguments it receives.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Util\n     * @param {...(Function|Function[])} [predicates=[_.identity]]\n     *  The predicates to check.\n     * @returns {Function} Returns the new function.\n     * @example\n     *\n     * var func = _.overEvery([Boolean, isFinite]);\n     *\n     * func('1');\n     * // => true\n     *\n     * func(null);\n     * // => false\n     *\n     * func(NaN);\n     * // => false\n     */\n    var overEvery = createOver(arrayEvery);\n\n    /**\n     * Creates a function that checks if **any** of the `predicates` return\n     * truthy when invoked with the arguments it receives.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Util\n     * @param {...(Function|Function[])} [predicates=[_.identity]]\n     *  The predicates to check.\n     * @returns {Function} Returns the new function.\n     * @example\n     *\n     * var func = _.overSome([Boolean, isFinite]);\n     *\n     * func('1');\n     * // => true\n     *\n     * func(null);\n     * // => true\n     *\n     * func(NaN);\n     * // => false\n     */\n    var overSome = createOver(arraySome);\n\n    /**\n     * Creates a function that returns the value at `path` of a given object.\n     *\n     * @static\n     * @memberOf _\n     * @since 2.4.0\n     * @category Util\n     * @param {Array|string} path The path of the property to get.\n     * @returns {Function} Returns the new accessor function.\n     * @example\n     *\n     * var objects = [\n     *   { 'a': { 'b': 2 } },\n     *   { 'a': { 'b': 1 } }\n     * ];\n     *\n     * _.map(objects, _.property('a.b'));\n     * // => [2, 1]\n     *\n     * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n     * // => [1, 2]\n     */\n    function property(path) {\n      return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n    }\n\n    /**\n     * The opposite of `_.property`; this method creates a function that returns\n     * the value at a given path of `object`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.0.0\n     * @category Util\n     * @param {Object} object The object to query.\n     * @returns {Function} Returns the new accessor function.\n     * @example\n     *\n     * var array = [0, 1, 2],\n     *     object = { 'a': array, 'b': array, 'c': array };\n     *\n     * _.map(['a[2]', 'c[0]'], _.propertyOf(object));\n     * // => [2, 0]\n     *\n     * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));\n     * // => [2, 0]\n     */\n    function propertyOf(object) {\n      return function(path) {\n        return object == null ? undefined : baseGet(object, path);\n      };\n    }\n\n    /**\n     * Creates an array of numbers (positive and/or negative) progressing from\n     * `start` up to, but not including, `end`. A step of `-1` is used if a negative\n     * `start` is specified without an `end` or `step`. If `end` is not specified,\n     * it's set to `start` with `start` then set to `0`.\n     *\n     * **Note:** JavaScript follows the IEEE-754 standard for resolving\n     * floating-point values which can produce unexpected results.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Util\n     * @param {number} [start=0] The start of the range.\n     * @param {number} end The end of the range.\n     * @param {number} [step=1] The value to increment or decrement by.\n     * @returns {Array} Returns the range of numbers.\n     * @see _.inRange, _.rangeRight\n     * @example\n     *\n     * _.range(4);\n     * // => [0, 1, 2, 3]\n     *\n     * _.range(-4);\n     * // => [0, -1, -2, -3]\n     *\n     * _.range(1, 5);\n     * // => [1, 2, 3, 4]\n     *\n     * _.range(0, 20, 5);\n     * // => [0, 5, 10, 15]\n     *\n     * _.range(0, -4, -1);\n     * // => [0, -1, -2, -3]\n     *\n     * _.range(1, 4, 0);\n     * // => [1, 1, 1]\n     *\n     * _.range(0);\n     * // => []\n     */\n    var range = createRange();\n\n    /**\n     * This method is like `_.range` except that it populates values in\n     * descending order.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Util\n     * @param {number} [start=0] The start of the range.\n     * @param {number} end The end of the range.\n     * @param {number} [step=1] The value to increment or decrement by.\n     * @returns {Array} Returns the range of numbers.\n     * @see _.inRange, _.range\n     * @example\n     *\n     * _.rangeRight(4);\n     * // => [3, 2, 1, 0]\n     *\n     * _.rangeRight(-4);\n     * // => [-3, -2, -1, 0]\n     *\n     * _.rangeRight(1, 5);\n     * // => [4, 3, 2, 1]\n     *\n     * _.rangeRight(0, 20, 5);\n     * // => [15, 10, 5, 0]\n     *\n     * _.rangeRight(0, -4, -1);\n     * // => [-3, -2, -1, 0]\n     *\n     * _.rangeRight(1, 4, 0);\n     * // => [1, 1, 1]\n     *\n     * _.rangeRight(0);\n     * // => []\n     */\n    var rangeRight = createRange(true);\n\n    /**\n     * This method returns a new empty array.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.13.0\n     * @category Util\n     * @returns {Array} Returns the new empty array.\n     * @example\n     *\n     * var arrays = _.times(2, _.stubArray);\n     *\n     * console.log(arrays);\n     * // => [[], []]\n     *\n     * console.log(arrays[0] === arrays[1]);\n     * // => false\n     */\n    function stubArray() {\n      return [];\n    }\n\n    /**\n     * This method returns `false`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.13.0\n     * @category Util\n     * @returns {boolean} Returns `false`.\n     * @example\n     *\n     * _.times(2, _.stubFalse);\n     * // => [false, false]\n     */\n    function stubFalse() {\n      return false;\n    }\n\n    /**\n     * This method returns a new empty object.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.13.0\n     * @category Util\n     * @returns {Object} Returns the new empty object.\n     * @example\n     *\n     * var objects = _.times(2, _.stubObject);\n     *\n     * console.log(objects);\n     * // => [{}, {}]\n     *\n     * console.log(objects[0] === objects[1]);\n     * // => false\n     */\n    function stubObject() {\n      return {};\n    }\n\n    /**\n     * This method returns an empty string.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.13.0\n     * @category Util\n     * @returns {string} Returns the empty string.\n     * @example\n     *\n     * _.times(2, _.stubString);\n     * // => ['', '']\n     */\n    function stubString() {\n      return '';\n    }\n\n    /**\n     * This method returns `true`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.13.0\n     * @category Util\n     * @returns {boolean} Returns `true`.\n     * @example\n     *\n     * _.times(2, _.stubTrue);\n     * // => [true, true]\n     */\n    function stubTrue() {\n      return true;\n    }\n\n    /**\n     * Invokes the iteratee `n` times, returning an array of the results of\n     * each invocation. The iteratee is invoked with one argument; (index).\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Util\n     * @param {number} n The number of times to invoke `iteratee`.\n     * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n     * @returns {Array} Returns the array of results.\n     * @example\n     *\n     * _.times(3, String);\n     * // => ['0', '1', '2']\n     *\n     *  _.times(4, _.constant(0));\n     * // => [0, 0, 0, 0]\n     */\n    function times(n, iteratee) {\n      n = toInteger(n);\n      if (n < 1 || n > MAX_SAFE_INTEGER) {\n        return [];\n      }\n      var index = MAX_ARRAY_LENGTH,\n          length = nativeMin(n, MAX_ARRAY_LENGTH);\n\n      iteratee = getIteratee(iteratee);\n      n -= MAX_ARRAY_LENGTH;\n\n      var result = baseTimes(length, iteratee);\n      while (++index < n) {\n        iteratee(index);\n      }\n      return result;\n    }\n\n    /**\n     * Converts `value` to a property path array.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Util\n     * @param {*} value The value to convert.\n     * @returns {Array} Returns the new property path array.\n     * @example\n     *\n     * _.toPath('a.b.c');\n     * // => ['a', 'b', 'c']\n     *\n     * _.toPath('a[0].b.c');\n     * // => ['a', '0', 'b', 'c']\n     */\n    function toPath(value) {\n      if (isArray(value)) {\n        return arrayMap(value, toKey);\n      }\n      return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));\n    }\n\n    /**\n     * Generates a unique ID. If `prefix` is given, the ID is appended to it.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Util\n     * @param {string} [prefix=''] The value to prefix the ID with.\n     * @returns {string} Returns the unique ID.\n     * @example\n     *\n     * _.uniqueId('contact_');\n     * // => 'contact_104'\n     *\n     * _.uniqueId();\n     * // => '105'\n     */\n    function uniqueId(prefix) {\n      var id = ++idCounter;\n      return toString(prefix) + id;\n    }\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * Adds two numbers.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.4.0\n     * @category Math\n     * @param {number} augend The first number in an addition.\n     * @param {number} addend The second number in an addition.\n     * @returns {number} Returns the total.\n     * @example\n     *\n     * _.add(6, 4);\n     * // => 10\n     */\n    var add = createMathOperation(function(augend, addend) {\n      return augend + addend;\n    }, 0);\n\n    /**\n     * Computes `number` rounded up to `precision`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.10.0\n     * @category Math\n     * @param {number} number The number to round up.\n     * @param {number} [precision=0] The precision to round up to.\n     * @returns {number} Returns the rounded up number.\n     * @example\n     *\n     * _.ceil(4.006);\n     * // => 5\n     *\n     * _.ceil(6.004, 2);\n     * // => 6.01\n     *\n     * _.ceil(6040, -2);\n     * // => 6100\n     */\n    var ceil = createRound('ceil');\n\n    /**\n     * Divide two numbers.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.7.0\n     * @category Math\n     * @param {number} dividend The first number in a division.\n     * @param {number} divisor The second number in a division.\n     * @returns {number} Returns the quotient.\n     * @example\n     *\n     * _.divide(6, 4);\n     * // => 1.5\n     */\n    var divide = createMathOperation(function(dividend, divisor) {\n      return dividend / divisor;\n    }, 1);\n\n    /**\n     * Computes `number` rounded down to `precision`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.10.0\n     * @category Math\n     * @param {number} number The number to round down.\n     * @param {number} [precision=0] The precision to round down to.\n     * @returns {number} Returns the rounded down number.\n     * @example\n     *\n     * _.floor(4.006);\n     * // => 4\n     *\n     * _.floor(0.046, 2);\n     * // => 0.04\n     *\n     * _.floor(4060, -2);\n     * // => 4000\n     */\n    var floor = createRound('floor');\n\n    /**\n     * Computes the maximum value of `array`. If `array` is empty or falsey,\n     * `undefined` is returned.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Math\n     * @param {Array} array The array to iterate over.\n     * @returns {*} Returns the maximum value.\n     * @example\n     *\n     * _.max([4, 2, 8, 6]);\n     * // => 8\n     *\n     * _.max([]);\n     * // => undefined\n     */\n    function max(array) {\n      return (array && array.length)\n        ? baseExtremum(array, identity, baseGt)\n        : undefined;\n    }\n\n    /**\n     * This method is like `_.max` except that it accepts `iteratee` which is\n     * invoked for each element in `array` to generate the criterion by which\n     * the value is ranked. The iteratee is invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Math\n     * @param {Array} array The array to iterate over.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {*} Returns the maximum value.\n     * @example\n     *\n     * var objects = [{ 'n': 1 }, { 'n': 2 }];\n     *\n     * _.maxBy(objects, function(o) { return o.n; });\n     * // => { 'n': 2 }\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.maxBy(objects, 'n');\n     * // => { 'n': 2 }\n     */\n    function maxBy(array, iteratee) {\n      return (array && array.length)\n        ? baseExtremum(array, getIteratee(iteratee, 2), baseGt)\n        : undefined;\n    }\n\n    /**\n     * Computes the mean of the values in `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Math\n     * @param {Array} array The array to iterate over.\n     * @returns {number} Returns the mean.\n     * @example\n     *\n     * _.mean([4, 2, 8, 6]);\n     * // => 5\n     */\n    function mean(array) {\n      return baseMean(array, identity);\n    }\n\n    /**\n     * This method is like `_.mean` except that it accepts `iteratee` which is\n     * invoked for each element in `array` to generate the value to be averaged.\n     * The iteratee is invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.7.0\n     * @category Math\n     * @param {Array} array The array to iterate over.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {number} Returns the mean.\n     * @example\n     *\n     * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];\n     *\n     * _.meanBy(objects, function(o) { return o.n; });\n     * // => 5\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.meanBy(objects, 'n');\n     * // => 5\n     */\n    function meanBy(array, iteratee) {\n      return baseMean(array, getIteratee(iteratee, 2));\n    }\n\n    /**\n     * Computes the minimum value of `array`. If `array` is empty or falsey,\n     * `undefined` is returned.\n     *\n     * @static\n     * @since 0.1.0\n     * @memberOf _\n     * @category Math\n     * @param {Array} array The array to iterate over.\n     * @returns {*} Returns the minimum value.\n     * @example\n     *\n     * _.min([4, 2, 8, 6]);\n     * // => 2\n     *\n     * _.min([]);\n     * // => undefined\n     */\n    function min(array) {\n      return (array && array.length)\n        ? baseExtremum(array, identity, baseLt)\n        : undefined;\n    }\n\n    /**\n     * This method is like `_.min` except that it accepts `iteratee` which is\n     * invoked for each element in `array` to generate the criterion by which\n     * the value is ranked. The iteratee is invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Math\n     * @param {Array} array The array to iterate over.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {*} Returns the minimum value.\n     * @example\n     *\n     * var objects = [{ 'n': 1 }, { 'n': 2 }];\n     *\n     * _.minBy(objects, function(o) { return o.n; });\n     * // => { 'n': 1 }\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.minBy(objects, 'n');\n     * // => { 'n': 1 }\n     */\n    function minBy(array, iteratee) {\n      return (array && array.length)\n        ? baseExtremum(array, getIteratee(iteratee, 2), baseLt)\n        : undefined;\n    }\n\n    /**\n     * Multiply two numbers.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.7.0\n     * @category Math\n     * @param {number} multiplier The first number in a multiplication.\n     * @param {number} multiplicand The second number in a multiplication.\n     * @returns {number} Returns the product.\n     * @example\n     *\n     * _.multiply(6, 4);\n     * // => 24\n     */\n    var multiply = createMathOperation(function(multiplier, multiplicand) {\n      return multiplier * multiplicand;\n    }, 1);\n\n    /**\n     * Computes `number` rounded to `precision`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.10.0\n     * @category Math\n     * @param {number} number The number to round.\n     * @param {number} [precision=0] The precision to round to.\n     * @returns {number} Returns the rounded number.\n     * @example\n     *\n     * _.round(4.006);\n     * // => 4\n     *\n     * _.round(4.006, 2);\n     * // => 4.01\n     *\n     * _.round(4060, -2);\n     * // => 4100\n     */\n    var round = createRound('round');\n\n    /**\n     * Subtract two numbers.\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Math\n     * @param {number} minuend The first number in a subtraction.\n     * @param {number} subtrahend The second number in a subtraction.\n     * @returns {number} Returns the difference.\n     * @example\n     *\n     * _.subtract(6, 4);\n     * // => 2\n     */\n    var subtract = createMathOperation(function(minuend, subtrahend) {\n      return minuend - subtrahend;\n    }, 0);\n\n    /**\n     * Computes the sum of the values in `array`.\n     *\n     * @static\n     * @memberOf _\n     * @since 3.4.0\n     * @category Math\n     * @param {Array} array The array to iterate over.\n     * @returns {number} Returns the sum.\n     * @example\n     *\n     * _.sum([4, 2, 8, 6]);\n     * // => 20\n     */\n    function sum(array) {\n      return (array && array.length)\n        ? baseSum(array, identity)\n        : 0;\n    }\n\n    /**\n     * This method is like `_.sum` except that it accepts `iteratee` which is\n     * invoked for each element in `array` to generate the value to be summed.\n     * The iteratee is invoked with one argument: (value).\n     *\n     * @static\n     * @memberOf _\n     * @since 4.0.0\n     * @category Math\n     * @param {Array} array The array to iterate over.\n     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n     * @returns {number} Returns the sum.\n     * @example\n     *\n     * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];\n     *\n     * _.sumBy(objects, function(o) { return o.n; });\n     * // => 20\n     *\n     * // The `_.property` iteratee shorthand.\n     * _.sumBy(objects, 'n');\n     * // => 20\n     */\n    function sumBy(array, iteratee) {\n      return (array && array.length)\n        ? baseSum(array, getIteratee(iteratee, 2))\n        : 0;\n    }\n\n    /*------------------------------------------------------------------------*/\n\n    // Add methods that return wrapped values in chain sequences.\n    lodash.after = after;\n    lodash.ary = ary;\n    lodash.assign = assign;\n    lodash.assignIn = assignIn;\n    lodash.assignInWith = assignInWith;\n    lodash.assignWith = assignWith;\n    lodash.at = at;\n    lodash.before = before;\n    lodash.bind = bind;\n    lodash.bindAll = bindAll;\n    lodash.bindKey = bindKey;\n    lodash.castArray = castArray;\n    lodash.chain = chain;\n    lodash.chunk = chunk;\n    lodash.compact = compact;\n    lodash.concat = concat;\n    lodash.cond = cond;\n    lodash.conforms = conforms;\n    lodash.constant = constant;\n    lodash.countBy = countBy;\n    lodash.create = create;\n    lodash.curry = curry;\n    lodash.curryRight = curryRight;\n    lodash.debounce = debounce;\n    lodash.defaults = defaults;\n    lodash.defaultsDeep = defaultsDeep;\n    lodash.defer = defer;\n    lodash.delay = delay;\n    lodash.difference = difference;\n    lodash.differenceBy = differenceBy;\n    lodash.differenceWith = differenceWith;\n    lodash.drop = drop;\n    lodash.dropRight = dropRight;\n    lodash.dropRightWhile = dropRightWhile;\n    lodash.dropWhile = dropWhile;\n    lodash.fill = fill;\n    lodash.filter = filter;\n    lodash.flatMap = flatMap;\n    lodash.flatMapDeep = flatMapDeep;\n    lodash.flatMapDepth = flatMapDepth;\n    lodash.flatten = flatten;\n    lodash.flattenDeep = flattenDeep;\n    lodash.flattenDepth = flattenDepth;\n    lodash.flip = flip;\n    lodash.flow = flow;\n    lodash.flowRight = flowRight;\n    lodash.fromPairs = fromPairs;\n    lodash.functions = functions;\n    lodash.functionsIn = functionsIn;\n    lodash.groupBy = groupBy;\n    lodash.initial = initial;\n    lodash.intersection = intersection;\n    lodash.intersectionBy = intersectionBy;\n    lodash.intersectionWith = intersectionWith;\n    lodash.invert = invert;\n    lodash.invertBy = invertBy;\n    lodash.invokeMap = invokeMap;\n    lodash.iteratee = iteratee;\n    lodash.keyBy = keyBy;\n    lodash.keys = keys;\n    lodash.keysIn = keysIn;\n    lodash.map = map;\n    lodash.mapKeys = mapKeys;\n    lodash.mapValues = mapValues;\n    lodash.matches = matches;\n    lodash.matchesProperty = matchesProperty;\n    lodash.memoize = memoize;\n    lodash.merge = merge;\n    lodash.mergeWith = mergeWith;\n    lodash.method = method;\n    lodash.methodOf = methodOf;\n    lodash.mixin = mixin;\n    lodash.negate = negate;\n    lodash.nthArg = nthArg;\n    lodash.omit = omit;\n    lodash.omitBy = omitBy;\n    lodash.once = once;\n    lodash.orderBy = orderBy;\n    lodash.over = over;\n    lodash.overArgs = overArgs;\n    lodash.overEvery = overEvery;\n    lodash.overSome = overSome;\n    lodash.partial = partial;\n    lodash.partialRight = partialRight;\n    lodash.partition = partition;\n    lodash.pick = pick;\n    lodash.pickBy = pickBy;\n    lodash.property = property;\n    lodash.propertyOf = propertyOf;\n    lodash.pull = pull;\n    lodash.pullAll = pullAll;\n    lodash.pullAllBy = pullAllBy;\n    lodash.pullAllWith = pullAllWith;\n    lodash.pullAt = pullAt;\n    lodash.range = range;\n    lodash.rangeRight = rangeRight;\n    lodash.rearg = rearg;\n    lodash.reject = reject;\n    lodash.remove = remove;\n    lodash.rest = rest;\n    lodash.reverse = reverse;\n    lodash.sampleSize = sampleSize;\n    lodash.set = set;\n    lodash.setWith = setWith;\n    lodash.shuffle = shuffle;\n    lodash.slice = slice;\n    lodash.sortBy = sortBy;\n    lodash.sortedUniq = sortedUniq;\n    lodash.sortedUniqBy = sortedUniqBy;\n    lodash.split = split;\n    lodash.spread = spread;\n    lodash.tail = tail;\n    lodash.take = take;\n    lodash.takeRight = takeRight;\n    lodash.takeRightWhile = takeRightWhile;\n    lodash.takeWhile = takeWhile;\n    lodash.tap = tap;\n    lodash.throttle = throttle;\n    lodash.thru = thru;\n    lodash.toArray = toArray;\n    lodash.toPairs = toPairs;\n    lodash.toPairsIn = toPairsIn;\n    lodash.toPath = toPath;\n    lodash.toPlainObject = toPlainObject;\n    lodash.transform = transform;\n    lodash.unary = unary;\n    lodash.union = union;\n    lodash.unionBy = unionBy;\n    lodash.unionWith = unionWith;\n    lodash.uniq = uniq;\n    lodash.uniqBy = uniqBy;\n    lodash.uniqWith = uniqWith;\n    lodash.unset = unset;\n    lodash.unzip = unzip;\n    lodash.unzipWith = unzipWith;\n    lodash.update = update;\n    lodash.updateWith = updateWith;\n    lodash.values = values;\n    lodash.valuesIn = valuesIn;\n    lodash.without = without;\n    lodash.words = words;\n    lodash.wrap = wrap;\n    lodash.xor = xor;\n    lodash.xorBy = xorBy;\n    lodash.xorWith = xorWith;\n    lodash.zip = zip;\n    lodash.zipObject = zipObject;\n    lodash.zipObjectDeep = zipObjectDeep;\n    lodash.zipWith = zipWith;\n\n    // Add aliases.\n    lodash.entries = toPairs;\n    lodash.entriesIn = toPairsIn;\n    lodash.extend = assignIn;\n    lodash.extendWith = assignInWith;\n\n    // Add methods to `lodash.prototype`.\n    mixin(lodash, lodash);\n\n    /*------------------------------------------------------------------------*/\n\n    // Add methods that return unwrapped values in chain sequences.\n    lodash.add = add;\n    lodash.attempt = attempt;\n    lodash.camelCase = camelCase;\n    lodash.capitalize = capitalize;\n    lodash.ceil = ceil;\n    lodash.clamp = clamp;\n    lodash.clone = clone;\n    lodash.cloneDeep = cloneDeep;\n    lodash.cloneDeepWith = cloneDeepWith;\n    lodash.cloneWith = cloneWith;\n    lodash.conformsTo = conformsTo;\n    lodash.deburr = deburr;\n    lodash.defaultTo = defaultTo;\n    lodash.divide = divide;\n    lodash.endsWith = endsWith;\n    lodash.eq = eq;\n    lodash.escape = escape;\n    lodash.escapeRegExp = escapeRegExp;\n    lodash.every = every;\n    lodash.find = find;\n    lodash.findIndex = findIndex;\n    lodash.findKey = findKey;\n    lodash.findLast = findLast;\n    lodash.findLastIndex = findLastIndex;\n    lodash.findLastKey = findLastKey;\n    lodash.floor = floor;\n    lodash.forEach = forEach;\n    lodash.forEachRight = forEachRight;\n    lodash.forIn = forIn;\n    lodash.forInRight = forInRight;\n    lodash.forOwn = forOwn;\n    lodash.forOwnRight = forOwnRight;\n    lodash.get = get;\n    lodash.gt = gt;\n    lodash.gte = gte;\n    lodash.has = has;\n    lodash.hasIn = hasIn;\n    lodash.head = head;\n    lodash.identity = identity;\n    lodash.includes = includes;\n    lodash.indexOf = indexOf;\n    lodash.inRange = inRange;\n    lodash.invoke = invoke;\n    lodash.isArguments = isArguments;\n    lodash.isArray = isArray;\n    lodash.isArrayBuffer = isArrayBuffer;\n    lodash.isArrayLike = isArrayLike;\n    lodash.isArrayLikeObject = isArrayLikeObject;\n    lodash.isBoolean = isBoolean;\n    lodash.isBuffer = isBuffer;\n    lodash.isDate = isDate;\n    lodash.isElement = isElement;\n    lodash.isEmpty = isEmpty;\n    lodash.isEqual = isEqual;\n    lodash.isEqualWith = isEqualWith;\n    lodash.isError = isError;\n    lodash.isFinite = isFinite;\n    lodash.isFunction = isFunction;\n    lodash.isInteger = isInteger;\n    lodash.isLength = isLength;\n    lodash.isMap = isMap;\n    lodash.isMatch = isMatch;\n    lodash.isMatchWith = isMatchWith;\n    lodash.isNaN = isNaN;\n    lodash.isNative = isNative;\n    lodash.isNil = isNil;\n    lodash.isNull = isNull;\n    lodash.isNumber = isNumber;\n    lodash.isObject = isObject;\n    lodash.isObjectLike = isObjectLike;\n    lodash.isPlainObject = isPlainObject;\n    lodash.isRegExp = isRegExp;\n    lodash.isSafeInteger = isSafeInteger;\n    lodash.isSet = isSet;\n    lodash.isString = isString;\n    lodash.isSymbol = isSymbol;\n    lodash.isTypedArray = isTypedArray;\n    lodash.isUndefined = isUndefined;\n    lodash.isWeakMap = isWeakMap;\n    lodash.isWeakSet = isWeakSet;\n    lodash.join = join;\n    lodash.kebabCase = kebabCase;\n    lodash.last = last;\n    lodash.lastIndexOf = lastIndexOf;\n    lodash.lowerCase = lowerCase;\n    lodash.lowerFirst = lowerFirst;\n    lodash.lt = lt;\n    lodash.lte = lte;\n    lodash.max = max;\n    lodash.maxBy = maxBy;\n    lodash.mean = mean;\n    lodash.meanBy = meanBy;\n    lodash.min = min;\n    lodash.minBy = minBy;\n    lodash.stubArray = stubArray;\n    lodash.stubFalse = stubFalse;\n    lodash.stubObject = stubObject;\n    lodash.stubString = stubString;\n    lodash.stubTrue = stubTrue;\n    lodash.multiply = multiply;\n    lodash.nth = nth;\n    lodash.noConflict = noConflict;\n    lodash.noop = noop;\n    lodash.now = now;\n    lodash.pad = pad;\n    lodash.padEnd = padEnd;\n    lodash.padStart = padStart;\n    lodash.parseInt = parseInt;\n    lodash.random = random;\n    lodash.reduce = reduce;\n    lodash.reduceRight = reduceRight;\n    lodash.repeat = repeat;\n    lodash.replace = replace;\n    lodash.result = result;\n    lodash.round = round;\n    lodash.runInContext = runInContext;\n    lodash.sample = sample;\n    lodash.size = size;\n    lodash.snakeCase = snakeCase;\n    lodash.some = some;\n    lodash.sortedIndex = sortedIndex;\n    lodash.sortedIndexBy = sortedIndexBy;\n    lodash.sortedIndexOf = sortedIndexOf;\n    lodash.sortedLastIndex = sortedLastIndex;\n    lodash.sortedLastIndexBy = sortedLastIndexBy;\n    lodash.sortedLastIndexOf = sortedLastIndexOf;\n    lodash.startCase = startCase;\n    lodash.startsWith = startsWith;\n    lodash.subtract = subtract;\n    lodash.sum = sum;\n    lodash.sumBy = sumBy;\n    lodash.template = template;\n    lodash.times = times;\n    lodash.toFinite = toFinite;\n    lodash.toInteger = toInteger;\n    lodash.toLength = toLength;\n    lodash.toLower = toLower;\n    lodash.toNumber = toNumber;\n    lodash.toSafeInteger = toSafeInteger;\n    lodash.toString = toString;\n    lodash.toUpper = toUpper;\n    lodash.trim = trim;\n    lodash.trimEnd = trimEnd;\n    lodash.trimStart = trimStart;\n    lodash.truncate = truncate;\n    lodash.unescape = unescape;\n    lodash.uniqueId = uniqueId;\n    lodash.upperCase = upperCase;\n    lodash.upperFirst = upperFirst;\n\n    // Add aliases.\n    lodash.each = forEach;\n    lodash.eachRight = forEachRight;\n    lodash.first = head;\n\n    mixin(lodash, (function() {\n      var source = {};\n      baseForOwn(lodash, function(func, methodName) {\n        if (!hasOwnProperty.call(lodash.prototype, methodName)) {\n          source[methodName] = func;\n        }\n      });\n      return source;\n    }()), { 'chain': false });\n\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * The semantic version number.\n     *\n     * @static\n     * @memberOf _\n     * @type {string}\n     */\n    lodash.VERSION = VERSION;\n\n    // Assign default placeholders.\n    arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {\n      lodash[methodName].placeholder = lodash;\n    });\n\n    // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.\n    arrayEach(['drop', 'take'], function(methodName, index) {\n      LazyWrapper.prototype[methodName] = function(n) {\n        n = n === undefined ? 1 : nativeMax(toInteger(n), 0);\n\n        var result = (this.__filtered__ && !index)\n          ? new LazyWrapper(this)\n          : this.clone();\n\n        if (result.__filtered__) {\n          result.__takeCount__ = nativeMin(n, result.__takeCount__);\n        } else {\n          result.__views__.push({\n            'size': nativeMin(n, MAX_ARRAY_LENGTH),\n            'type': methodName + (result.__dir__ < 0 ? 'Right' : '')\n          });\n        }\n        return result;\n      };\n\n      LazyWrapper.prototype[methodName + 'Right'] = function(n) {\n        return this.reverse()[methodName](n).reverse();\n      };\n    });\n\n    // Add `LazyWrapper` methods that accept an `iteratee` value.\n    arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {\n      var type = index + 1,\n          isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;\n\n      LazyWrapper.prototype[methodName] = function(iteratee) {\n        var result = this.clone();\n        result.__iteratees__.push({\n          'iteratee': getIteratee(iteratee, 3),\n          'type': type\n        });\n        result.__filtered__ = result.__filtered__ || isFilter;\n        return result;\n      };\n    });\n\n    // Add `LazyWrapper` methods for `_.head` and `_.last`.\n    arrayEach(['head', 'last'], function(methodName, index) {\n      var takeName = 'take' + (index ? 'Right' : '');\n\n      LazyWrapper.prototype[methodName] = function() {\n        return this[takeName](1).value()[0];\n      };\n    });\n\n    // Add `LazyWrapper` methods for `_.initial` and `_.tail`.\n    arrayEach(['initial', 'tail'], function(methodName, index) {\n      var dropName = 'drop' + (index ? '' : 'Right');\n\n      LazyWrapper.prototype[methodName] = function() {\n        return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);\n      };\n    });\n\n    LazyWrapper.prototype.compact = function() {\n      return this.filter(identity);\n    };\n\n    LazyWrapper.prototype.find = function(predicate) {\n      return this.filter(predicate).head();\n    };\n\n    LazyWrapper.prototype.findLast = function(predicate) {\n      return this.reverse().find(predicate);\n    };\n\n    LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {\n      if (typeof path == 'function') {\n        return new LazyWrapper(this);\n      }\n      return this.map(function(value) {\n        return baseInvoke(value, path, args);\n      });\n    });\n\n    LazyWrapper.prototype.reject = function(predicate) {\n      return this.filter(negate(getIteratee(predicate)));\n    };\n\n    LazyWrapper.prototype.slice = function(start, end) {\n      start = toInteger(start);\n\n      var result = this;\n      if (result.__filtered__ && (start > 0 || end < 0)) {\n        return new LazyWrapper(result);\n      }\n      if (start < 0) {\n        result = result.takeRight(-start);\n      } else if (start) {\n        result = result.drop(start);\n      }\n      if (end !== undefined) {\n        end = toInteger(end);\n        result = end < 0 ? result.dropRight(-end) : result.take(end - start);\n      }\n      return result;\n    };\n\n    LazyWrapper.prototype.takeRightWhile = function(predicate) {\n      return this.reverse().takeWhile(predicate).reverse();\n    };\n\n    LazyWrapper.prototype.toArray = function() {\n      return this.take(MAX_ARRAY_LENGTH);\n    };\n\n    // Add `LazyWrapper` methods to `lodash.prototype`.\n    baseForOwn(LazyWrapper.prototype, function(func, methodName) {\n      var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),\n          isTaker = /^(?:head|last)$/.test(methodName),\n          lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],\n          retUnwrapped = isTaker || /^find/.test(methodName);\n\n      if (!lodashFunc) {\n        return;\n      }\n      lodash.prototype[methodName] = function() {\n        var value = this.__wrapped__,\n            args = isTaker ? [1] : arguments,\n            isLazy = value instanceof LazyWrapper,\n            iteratee = args[0],\n            useLazy = isLazy || isArray(value);\n\n        var interceptor = function(value) {\n          var result = lodashFunc.apply(lodash, arrayPush([value], args));\n          return (isTaker && chainAll) ? result[0] : result;\n        };\n\n        if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {\n          // Avoid lazy use if the iteratee has a \"length\" value other than `1`.\n          isLazy = useLazy = false;\n        }\n        var chainAll = this.__chain__,\n            isHybrid = !!this.__actions__.length,\n            isUnwrapped = retUnwrapped && !chainAll,\n            onlyLazy = isLazy && !isHybrid;\n\n        if (!retUnwrapped && useLazy) {\n          value = onlyLazy ? value : new LazyWrapper(this);\n          var result = func.apply(value, args);\n          result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });\n          return new LodashWrapper(result, chainAll);\n        }\n        if (isUnwrapped && onlyLazy) {\n          return func.apply(this, args);\n        }\n        result = this.thru(interceptor);\n        return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;\n      };\n    });\n\n    // Add `Array` methods to `lodash.prototype`.\n    arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {\n      var func = arrayProto[methodName],\n          chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',\n          retUnwrapped = /^(?:pop|shift)$/.test(methodName);\n\n      lodash.prototype[methodName] = function() {\n        var args = arguments;\n        if (retUnwrapped && !this.__chain__) {\n          var value = this.value();\n          return func.apply(isArray(value) ? value : [], args);\n        }\n        return this[chainName](function(value) {\n          return func.apply(isArray(value) ? value : [], args);\n        });\n      };\n    });\n\n    // Map minified method names to their real names.\n    baseForOwn(LazyWrapper.prototype, function(func, methodName) {\n      var lodashFunc = lodash[methodName];\n      if (lodashFunc) {\n        var key = (lodashFunc.name + ''),\n            names = realNames[key] || (realNames[key] = []);\n\n        names.push({ 'name': methodName, 'func': lodashFunc });\n      }\n    });\n\n    realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{\n      'name': 'wrapper',\n      'func': undefined\n    }];\n\n    // Add methods to `LazyWrapper`.\n    LazyWrapper.prototype.clone = lazyClone;\n    LazyWrapper.prototype.reverse = lazyReverse;\n    LazyWrapper.prototype.value = lazyValue;\n\n    // Add chain sequence methods to the `lodash` wrapper.\n    lodash.prototype.at = wrapperAt;\n    lodash.prototype.chain = wrapperChain;\n    lodash.prototype.commit = wrapperCommit;\n    lodash.prototype.next = wrapperNext;\n    lodash.prototype.plant = wrapperPlant;\n    lodash.prototype.reverse = wrapperReverse;\n    lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;\n\n    // Add lazy aliases.\n    lodash.prototype.first = lodash.prototype.head;\n\n    if (symIterator) {\n      lodash.prototype[symIterator] = wrapperToIterator;\n    }\n    return lodash;\n  });\n\n  /*--------------------------------------------------------------------------*/\n\n  // Export lodash.\n  var _ = runInContext();\n\n  // Some AMD build optimizers, like r.js, check for condition patterns like:\n  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {\n    // Expose Lodash on the global object to prevent errors when Lodash is\n    // loaded by a script tag in the presence of an AMD loader.\n    // See http://requirejs.org/docs/errors.html#mismatch for more details.\n    // Use `_.noConflict` to remove Lodash from the global object.\n    root._ = _;\n\n    // Define as an anonymous module so, through path mapping, it can be\n    // referenced as the \"underscore\" module.\n    define(function() {\n      return _;\n    });\n  }\n  // Check for `exports` after `define` in case a build optimizer adds it.\n  else if (freeModule) {\n    // Export for Node.js.\n    (freeModule.exports = _)._ = _;\n    // Export for CommonJS support.\n    freeExports._ = _;\n  }\n  else {\n    // Export to the global object.\n    root._ = _;\n  }\n}.call(this));\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{}],14:[function(require,module,exports){\n/*\n * Lexical analysis and token construction.\n */\n\n\"use strict\";\n\nvar _      = require(\"lodash\");\nvar events = require(\"events\");\nvar reg    = require(\"./reg.js\");\nvar state  = require(\"./state.js\").state;\n\nvar unicodeData = require(\"../data/ascii-identifier-data.js\");\nvar asciiIdentifierStartTable = unicodeData.asciiIdentifierStartTable;\nvar asciiIdentifierPartTable = unicodeData.asciiIdentifierPartTable;\nvar nonAsciiIdentifierStartTable = require(\"../data/non-ascii-identifier-start.js\");\nvar nonAsciiIdentifierPartTable = require(\"../data/non-ascii-identifier-part-only.js\");\n// Loading of this module is deferred as an optimization for ES2015 input\nvar es5IdentifierNames;\n\n// Some of these token types are from JavaScript Parser API\n// while others are specific to JSHint parser.\n// JS Parser API: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API\n\nvar Token = {\n  Identifier: 1,\n  Punctuator: 2,\n  NumericLiteral: 3,\n  StringLiteral: 4,\n  Comment: 5,\n  Keyword: 6,\n  RegExp: 9,\n  TemplateHead: 10,\n  TemplateMiddle: 11,\n  TemplateTail: 12,\n  NoSubstTemplate: 13\n};\n\nvar Context = {\n  Block: 1,\n  Template: 2\n};\n\nfunction isHex(str) {\n  return /^[0-9a-fA-F]+$/.test(str);\n}\n\nfunction isHexDigit(str) {\n  return str.length === 1 && isHex(str);\n}\n\n// Object that handles postponed lexing verifications that checks the parsed\n// environment state.\n\nfunction asyncTrigger() {\n  var _checks = [];\n\n  return {\n    push: function(fn) {\n      _checks.push(fn);\n    },\n\n    check: function() {\n      for (var check = 0; check < _checks.length; ++check) {\n        _checks[check]();\n      }\n\n      _checks.splice(0, _checks.length);\n    }\n  };\n}\n\n/*\n * Lexer for JSHint.\n *\n * This object does a char-by-char scan of the provided source code\n * and produces a sequence of tokens.\n *\n *   var lex = new Lexer(\"var i = 0;\");\n *   lex.start();\n *   lex.token(); // returns the next token\n *\n * You have to use the token() method to move the lexer forward\n * but you don't have to use its return value to get tokens. In addition\n * to token() method returning the next token, the Lexer object also\n * emits events.\n *\n *   lex.on(\"Identifier\", function(data) {\n *     if (data.name.indexOf(\"_\") >= 0) {\n *       // Produce a warning.\n *     }\n *   });\n *\n * Note that the token() method returns tokens in a JSLint-compatible\n * format while the event emitter uses a slightly modified version of\n * Mozilla's JavaScript Parser API. Eventually, we will move away from\n * JSLint format.\n */\nfunction Lexer(source) {\n  var lines = source;\n\n  if (typeof lines === \"string\") {\n    lines = lines\n      .replace(/\\r\\n/g, \"\\n\")\n      .replace(/\\r/g, \"\\n\")\n      .split(\"\\n\");\n  }\n\n  // If the first line is a shebang (#!), make it a blank and move on.\n  // Shebangs are used by Node scripts.\n\n  if (lines[0] && lines[0].substr(0, 2) === \"#!\") {\n    if (lines[0].indexOf(\"node\") !== -1) {\n      state.option.node = true;\n    }\n    lines[0] = \"\";\n  }\n\n  this.emitter = new events.EventEmitter();\n  this.source = source;\n  this.setLines(lines);\n  this.prereg = true;\n\n  this.line = 0;\n  this.char = 1;\n  this.from = 1;\n  this.input = \"\";\n  this.inComment = false;\n  this.context = [];\n  this.templateStarts = [];\n\n  for (var i = 0; i < state.option.indent; i += 1) {\n    state.tab += \" \";\n  }\n}\n\nLexer.prototype = {\n  _lines: [],\n\n  inContext: function(ctxType) {\n    return this.context.length > 0 && this.context[this.context.length - 1].type === ctxType;\n  },\n\n  pushContext: function(ctxType) {\n    this.context.push({ type: ctxType });\n  },\n\n  popContext: function() {\n    return this.context.pop();\n  },\n\n  currentContext: function() {\n    return this.context.length > 0 && this.context[this.context.length - 1];\n  },\n\n  getLines: function() {\n    this._lines = state.lines;\n    return this._lines;\n  },\n\n  setLines: function(val) {\n    this._lines = val;\n    state.lines = this._lines;\n  },\n\n  /*\n   * Return the next i character without actually moving the\n   * char pointer.\n   */\n  peek: function(i) {\n    return this.input.charAt(i || 0);\n  },\n\n  /*\n   * Move the char pointer forward i times.\n   */\n  skip: function(i) {\n    i = i || 1;\n    this.char += i;\n    this.input = this.input.slice(i);\n  },\n\n  /*\n   * Subscribe to a token event. The API for this method is similar\n   * Underscore.js i.e. you can subscribe to multiple events with\n   * one call:\n   *\n   *   lex.on(\"Identifier Number\", function(data) {\n   *     // ...\n   *   });\n   */\n  on: function(names, listener) {\n    names.split(\" \").forEach(function(name) {\n      this.emitter.on(name, listener);\n    }.bind(this));\n  },\n\n  /*\n   * Trigger a token event. All arguments will be passed to each\n   * listener.\n   */\n  trigger: function() {\n    this.emitter.emit.apply(this.emitter, Array.prototype.slice.call(arguments));\n  },\n\n  /*\n   * Postpone a token event. the checking condition is set as\n   * last parameter, and the trigger function is called in a\n   * stored callback. To be later called using the check() function\n   * by the parser. This avoids parser's peek() to give the lexer\n   * a false context.\n   */\n  triggerAsync: function(type, args, checks, fn) {\n    checks.push(function() {\n      if (fn()) {\n        this.trigger(type, args);\n      }\n    }.bind(this));\n  },\n\n  /*\n   * Extract a punctuator out of the next sequence of characters\n   * or return 'null' if its not possible.\n   *\n   * This method's implementation was heavily influenced by the\n   * scanPunctuator function in the Esprima parser's source code.\n   */\n  scanPunctuator: function() {\n    var ch1 = this.peek();\n    var ch2, ch3, ch4;\n\n    switch (ch1) {\n    // Most common single-character punctuators\n    case \".\":\n      if ((/^[0-9]$/).test(this.peek(1))) {\n        return null;\n      }\n      if (this.peek(1) === \".\" && this.peek(2) === \".\") {\n        return {\n          type: Token.Punctuator,\n          value: \"...\"\n        };\n      }\n      /* falls through */\n    case \"(\":\n    case \")\":\n    case \";\":\n    case \",\":\n    case \"[\":\n    case \"]\":\n    case \":\":\n    case \"~\":\n    case \"?\":\n      return {\n        type: Token.Punctuator,\n        value: ch1\n      };\n\n    // A block/object opener\n    case \"{\":\n      this.pushContext(Context.Block);\n      return {\n        type: Token.Punctuator,\n        value: ch1\n      };\n\n    // A block/object closer\n    case \"}\":\n      if (this.inContext(Context.Block)) {\n        this.popContext();\n      }\n      return {\n        type: Token.Punctuator,\n        value: ch1\n      };\n\n    // A pound sign (for Node shebangs)\n    case \"#\":\n      return {\n        type: Token.Punctuator,\n        value: ch1\n      };\n\n    // We're at the end of input\n    case \"\":\n      return null;\n    }\n\n    // Peek more characters\n\n    ch2 = this.peek(1);\n    ch3 = this.peek(2);\n    ch4 = this.peek(3);\n\n    // 4-character punctuator: >>>=\n\n    if (ch1 === \">\" && ch2 === \">\" && ch3 === \">\" && ch4 === \"=\") {\n      return {\n        type: Token.Punctuator,\n        value: \">>>=\"\n      };\n    }\n\n    // 3-character punctuators: === !== >>> <<= >>=\n\n    if (ch1 === \"=\" && ch2 === \"=\" && ch3 === \"=\") {\n      return {\n        type: Token.Punctuator,\n        value: \"===\"\n      };\n    }\n\n    if (ch1 === \"!\" && ch2 === \"=\" && ch3 === \"=\") {\n      return {\n        type: Token.Punctuator,\n        value: \"!==\"\n      };\n    }\n\n    if (ch1 === \">\" && ch2 === \">\" && ch3 === \">\") {\n      return {\n        type: Token.Punctuator,\n        value: \">>>\"\n      };\n    }\n\n    if (ch1 === \"<\" && ch2 === \"<\" && ch3 === \"=\") {\n      return {\n        type: Token.Punctuator,\n        value: \"<<=\"\n      };\n    }\n\n    if (ch1 === \">\" && ch2 === \">\" && ch3 === \"=\") {\n      return {\n        type: Token.Punctuator,\n        value: \">>=\"\n      };\n    }\n\n    // Fat arrow punctuator\n    if (ch1 === \"=\" && ch2 === \">\") {\n      return {\n        type: Token.Punctuator,\n        value: ch1 + ch2\n      };\n    }\n\n    // 2-character punctuators: <= >= == != ++ -- << >> && ||\n    // += -= *= %= &= |= ^= /=\n    if (ch1 === ch2 && (\"+-<>&|\".indexOf(ch1) >= 0)) {\n      return {\n        type: Token.Punctuator,\n        value: ch1 + ch2\n      };\n    }\n\n    if (\"<>=!+-*%&|^/\".indexOf(ch1) >= 0) {\n      if (ch2 === \"=\") {\n        return {\n          type: Token.Punctuator,\n          value: ch1 + ch2\n        };\n      }\n\n      return {\n        type: Token.Punctuator,\n        value: ch1\n      };\n    }\n\n    return null;\n  },\n\n  /*\n   * Extract a comment out of the next sequence of characters and/or\n   * lines or return 'null' if its not possible. Since comments can\n   * span across multiple lines this method has to move the char\n   * pointer.\n   *\n   * In addition to normal JavaScript comments (// and /*) this method\n   * also recognizes JSHint- and JSLint-specific comments such as\n   * /*jshint, /*jslint, /*globals and so on.\n   */\n  scanComments: function(checks) {\n    var ch1 = this.peek();\n    var ch2 = this.peek(1);\n    var rest = this.input.substr(2);\n    var startLine = this.line;\n    var startChar = this.char;\n    var self = this;\n\n    // Create a comment token object and make sure it\n    // has all the data JSHint needs to work with special\n    // comments.\n\n    function commentToken(label, body, opt) {\n      var special = [\"jshint\", \"jslint\", \"members\", \"member\", \"globals\", \"global\", \"exported\"];\n      var isSpecial = false;\n      var value = label + body;\n      var commentType = \"plain\";\n      opt = opt || {};\n\n      if (opt.isMultiline) {\n        value += \"*/\";\n      }\n\n      body = body.replace(/\\n/g, \" \");\n\n      if (label === \"/*\" && reg.fallsThrough.test(body)) {\n        isSpecial = true;\n        commentType = \"falls through\";\n      }\n\n      special.forEach(function(str) {\n        if (isSpecial) {\n          return;\n        }\n\n        // Don't recognize any special comments other than jshint for single-line\n        // comments. This introduced many problems with legit comments.\n        if (label === \"//\" && str !== \"jshint\") {\n          return;\n        }\n\n        if (body.charAt(str.length) === \" \" && body.substr(0, str.length) === str) {\n          isSpecial = true;\n          label = label + str;\n          body = body.substr(str.length);\n        }\n\n        if (!isSpecial && body.charAt(0) === \" \" && body.charAt(str.length + 1) === \" \" &&\n          body.substr(1, str.length) === str) {\n          isSpecial = true;\n          label = label + \" \" + str;\n          body = body.substr(str.length + 1);\n        }\n\n        // To handle rarer case when special word is separated from label by\n        // multiple spaces or tabs\n        var strIndex = body.indexOf(str);\n        if (!isSpecial && strIndex >= 0 && body.charAt(strIndex + str.length) === \" \") {\n          var isAllWhitespace = body.substr(0, strIndex).trim().length === 0;\n          if (isAllWhitespace) {\n            isSpecial = true;\n            body = body.substr(str.length + strIndex);\n          }\n        }\n\n        if (!isSpecial) {\n          return;\n        }\n\n        switch (str) {\n        case \"member\":\n          commentType = \"members\";\n          break;\n        case \"global\":\n          commentType = \"globals\";\n          break;\n        default:\n          var options = body.split(\":\").map(function(v) {\n            return v.replace(/^\\s+/, \"\").replace(/\\s+$/, \"\");\n          });\n\n          if (options.length === 2) {\n            switch (options[0]) {\n            case \"ignore\":\n              switch (options[1]) {\n              case \"start\":\n                self.ignoringLinterErrors = true;\n                isSpecial = false;\n                break;\n              case \"end\":\n                self.ignoringLinterErrors = false;\n                isSpecial = false;\n                break;\n              }\n            }\n          }\n\n          commentType = str;\n        }\n      });\n\n      return {\n        type: Token.Comment,\n        commentType: commentType,\n        value: value,\n        body: body,\n        isSpecial: isSpecial,\n        isMalformed: opt.isMalformed || false\n      };\n    }\n\n    // End of unbegun comment. Raise an error and skip that input.\n    if (ch1 === \"*\" && ch2 === \"/\") {\n      this.trigger(\"error\", {\n        code: \"E018\",\n        line: startLine,\n        character: startChar\n      });\n\n      this.skip(2);\n      return null;\n    }\n\n    // Comments must start either with // or /*\n    if (ch1 !== \"/\" || (ch2 !== \"*\" && ch2 !== \"/\")) {\n      return null;\n    }\n\n    // One-line comment\n    if (ch2 === \"/\") {\n      this.skip(this.input.length); // Skip to the EOL.\n      return commentToken(\"//\", rest);\n    }\n\n    var body = \"\";\n\n    /* Multi-line comment */\n    if (ch2 === \"*\") {\n      this.inComment = true;\n      this.skip(2);\n\n      while (this.peek() !== \"*\" || this.peek(1) !== \"/\") {\n        if (this.peek() === \"\") { // End of Line\n          body += \"\\n\";\n\n          // If we hit EOF and our comment is still unclosed,\n          // trigger an error and end the comment implicitly.\n          if (!this.nextLine(checks)) {\n            this.trigger(\"error\", {\n              code: \"E017\",\n              line: startLine,\n              character: startChar\n            });\n\n            this.inComment = false;\n            return commentToken(\"/*\", body, {\n              isMultiline: true,\n              isMalformed: true\n            });\n          }\n        } else {\n          body += this.peek();\n          this.skip();\n        }\n      }\n\n      this.skip(2);\n      this.inComment = false;\n      return commentToken(\"/*\", body, { isMultiline: true });\n    }\n  },\n\n  /*\n   * Extract a keyword out of the next sequence of characters or\n   * return 'null' if its not possible.\n   */\n  scanKeyword: function() {\n    var result = /^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input);\n    var keywords = [\n      \"if\", \"in\", \"do\", \"var\", \"for\", \"new\",\n      \"try\", \"let\", \"this\", \"else\", \"case\",\n      \"void\", \"with\", \"enum\", \"while\", \"break\",\n      \"catch\", \"throw\", \"const\", \"yield\", \"class\",\n      \"super\", \"return\", \"typeof\", \"delete\",\n      \"switch\", \"export\", \"import\", \"default\",\n      \"finally\", \"extends\", \"function\", \"continue\",\n      \"debugger\", \"instanceof\", \"true\", \"false\", \"null\"\n    ];\n\n    if (result && keywords.indexOf(result[0]) >= 0) {\n      return {\n        type: Token.Keyword,\n        value: result[0]\n      };\n    }\n\n    return null;\n  },\n\n  /*\n   * Extract a JavaScript identifier out of the next sequence of\n   * characters or return 'null' if its not possible.\n   */\n  scanIdentifier: function(checks) {\n    var id = \"\";\n    var index = 0;\n    var char, value;\n\n    function isNonAsciiIdentifierStart(code) {\n      return nonAsciiIdentifierStartTable.indexOf(code) > -1;\n    }\n\n    function isNonAsciiIdentifierPart(code) {\n      return isNonAsciiIdentifierStart(code) || nonAsciiIdentifierPartTable.indexOf(code) > -1;\n    }\n\n    var readUnicodeEscapeSequence = function() {\n      /*jshint validthis:true */\n      index += 1;\n\n      if (this.peek(index) !== \"u\") {\n        return null;\n      }\n\n      var sequence = this.peek(index + 1) + this.peek(index + 2) +\n        this.peek(index + 3) + this.peek(index + 4);\n      var code;\n\n      if (isHex(sequence)) {\n        code = parseInt(sequence, 16);\n\n        if (asciiIdentifierPartTable[code] || isNonAsciiIdentifierPart(code)) {\n          index += 5;\n          return \"\\\\u\" + sequence;\n        }\n\n        return null;\n      }\n\n      return null;\n    }.bind(this);\n\n    var getIdentifierStart = function() {\n      /*jshint validthis:true */\n      var chr = this.peek(index);\n      var code = chr.charCodeAt(0);\n\n      if (code === 92) {\n        return readUnicodeEscapeSequence();\n      }\n\n      if (code < 128) {\n        if (asciiIdentifierStartTable[code]) {\n          index += 1;\n          return chr;\n        }\n\n        return null;\n      }\n\n      if (isNonAsciiIdentifierStart(code)) {\n        index += 1;\n        return chr;\n      }\n\n      return null;\n    }.bind(this);\n\n    var getIdentifierPart = function() {\n      /*jshint validthis:true */\n      var chr = this.peek(index);\n      var code = chr.charCodeAt(0);\n\n      if (code === 92) {\n        return readUnicodeEscapeSequence();\n      }\n\n      if (code < 128) {\n        if (asciiIdentifierPartTable[code]) {\n          index += 1;\n          return chr;\n        }\n\n        return null;\n      }\n\n      if (isNonAsciiIdentifierPart(code)) {\n        index += 1;\n        return chr;\n      }\n\n      return null;\n    }.bind(this);\n\n    function removeEscapeSequences(id) {\n      return id.replace(/\\\\u([0-9a-fA-F]{4})/g, function(m0, codepoint) {\n        return String.fromCharCode(parseInt(codepoint, 16));\n      });\n    }\n\n    char = getIdentifierStart();\n    if (char === null) {\n      return null;\n    }\n\n    id = char;\n    for (;;) {\n      char = getIdentifierPart();\n\n      if (char === null) {\n        break;\n      }\n\n      id += char;\n    }\n\n    value = removeEscapeSequences(id);\n\n    if (!state.inES6(true)) {\n      es5IdentifierNames = require(\"../data/es5-identifier-names.js\");\n\n      if (!es5IdentifierNames.test(value)) {\n        this.triggerAsync(\n          \"warning\",\n          {\n            code: \"W119\",\n            line: this.line,\n            character: this.char,\n            data: [\"unicode 8\", \"6\"]\n          },\n          checks,\n          function() { return true; }\n        );\n      }\n    }\n\n    return {\n      type: Token.Identifier,\n      value: value,\n      text: id,\n      tokenLength: id.length\n    };\n  },\n\n  /*\n   * Extract a numeric literal out of the next sequence of\n   * characters or return 'null' if its not possible. This method\n   * supports all numeric literals described in section 7.8.3\n   * of the EcmaScript 5 specification.\n   *\n   * This method's implementation was heavily influenced by the\n   * scanNumericLiteral function in the Esprima parser's source code.\n   */\n  scanNumericLiteral: function(checks) {\n    var index = 0;\n    var value = \"\";\n    var length = this.input.length;\n    var char = this.peek(index);\n    var isAllowedDigit = isDecimalDigit;\n    var base = 10;\n    var isLegacy = false;\n\n    function isDecimalDigit(str) {\n      return (/^[0-9]$/).test(str);\n    }\n\n    function isOctalDigit(str) {\n      return (/^[0-7]$/).test(str);\n    }\n\n    function isBinaryDigit(str) {\n      return (/^[01]$/).test(str);\n    }\n\n    function isIdentifierStart(ch) {\n      return (ch === \"$\") || (ch === \"_\") || (ch === \"\\\\\") ||\n        (ch >= \"a\" && ch <= \"z\") || (ch >= \"A\" && ch <= \"Z\");\n    }\n\n    // Numbers must start either with a decimal digit or a point.\n\n    if (char !== \".\" && !isDecimalDigit(char)) {\n      return null;\n    }\n\n    if (char !== \".\") {\n      value = this.peek(index);\n      index += 1;\n      char = this.peek(index);\n\n      if (value === \"0\") {\n        // Base-16 numbers.\n        if (char === \"x\" || char === \"X\") {\n          isAllowedDigit = isHexDigit;\n          base = 16;\n\n          index += 1;\n          value += char;\n        }\n\n        // Base-8 numbers.\n        if (char === \"o\" || char === \"O\") {\n          isAllowedDigit = isOctalDigit;\n          base = 8;\n\n          if (!state.inES6(true)) {\n            this.triggerAsync(\n              \"warning\",\n              {\n                code: \"W119\",\n                line: this.line,\n                character: this.char,\n                data: [ \"Octal integer literal\", \"6\" ]\n              },\n              checks,\n              function() { return true; }\n            );\n          }\n\n          index += 1;\n          value += char;\n        }\n\n        // Base-2 numbers.\n        if (char === \"b\" || char === \"B\") {\n          isAllowedDigit = isBinaryDigit;\n          base = 2;\n\n          if (!state.inES6(true)) {\n            this.triggerAsync(\n              \"warning\",\n              {\n                code: \"W119\",\n                line: this.line,\n                character: this.char,\n                data: [ \"Binary integer literal\", \"6\" ]\n              },\n              checks,\n              function() { return true; }\n            );\n          }\n\n          index += 1;\n          value += char;\n        }\n\n        // Legacy base-8 numbers.\n        if (isOctalDigit(char)) {\n          isAllowedDigit = isOctalDigit;\n          base = 8;\n          isLegacy = true;\n\n          index += 1;\n          value += char;\n        }\n\n        // Decimal numbers that start with '0' such as '09' are illegal\n        // but we still parse them and return as malformed.\n\n        if (!isOctalDigit(char) && isDecimalDigit(char)) {\n          index += 1;\n          value += char;\n        }\n      }\n\n      while (index < length) {\n        char = this.peek(index);\n\n        // Numbers like '019' (note the 9) are not valid octals\n        // but we still parse them and mark as malformed.\n        if (!(isLegacy && isDecimalDigit(char)) && !isAllowedDigit(char)) {\n          break;\n        }\n        value += char;\n        index += 1;\n      }\n\n      if (isAllowedDigit !== isDecimalDigit) {\n        if (!isLegacy && value.length <= 2) { // 0x\n          return {\n            type: Token.NumericLiteral,\n            value: value,\n            isMalformed: true\n          };\n        }\n\n        if (index < length) {\n          char = this.peek(index);\n          if (isIdentifierStart(char)) {\n            return null;\n          }\n        }\n\n        return {\n          type: Token.NumericLiteral,\n          value: value,\n          base: base,\n          isLegacy: isLegacy,\n          isMalformed: false\n        };\n      }\n    }\n\n    // Decimal digits.\n\n    if (char === \".\") {\n      value += char;\n      index += 1;\n\n      while (index < length) {\n        char = this.peek(index);\n        if (!isDecimalDigit(char)) {\n          break;\n        }\n        value += char;\n        index += 1;\n      }\n    }\n\n    // Exponent part.\n\n    if (char === \"e\" || char === \"E\") {\n      value += char;\n      index += 1;\n      char = this.peek(index);\n\n      if (char === \"+\" || char === \"-\") {\n        value += this.peek(index);\n        index += 1;\n      }\n\n      char = this.peek(index);\n      if (isDecimalDigit(char)) {\n        value += char;\n        index += 1;\n\n        while (index < length) {\n          char = this.peek(index);\n          if (!isDecimalDigit(char)) {\n            break;\n          }\n          value += char;\n          index += 1;\n        }\n      } else {\n        return null;\n      }\n    }\n\n    if (index < length) {\n      char = this.peek(index);\n      if (isIdentifierStart(char)) {\n        return null;\n      }\n    }\n\n    return {\n      type: Token.NumericLiteral,\n      value: value,\n      base: base,\n      isMalformed: !isFinite(value)\n    };\n  },\n\n\n  // Assumes previously parsed character was \\ (=== '\\\\') and was not skipped.\n  scanEscapeSequence: function(checks) {\n    var allowNewLine = false;\n    var jump = 1;\n    this.skip();\n    var char = this.peek();\n\n    switch (char) {\n    case \"'\":\n      this.triggerAsync(\"warning\", {\n        code: \"W114\",\n        line: this.line,\n        character: this.char,\n        data: [ \"\\\\'\" ]\n      }, checks, function() {return state.jsonMode; });\n      break;\n    case \"b\":\n      char = \"\\\\b\";\n      break;\n    case \"f\":\n      char = \"\\\\f\";\n      break;\n    case \"n\":\n      char = \"\\\\n\";\n      break;\n    case \"r\":\n      char = \"\\\\r\";\n      break;\n    case \"t\":\n      char = \"\\\\t\";\n      break;\n    case \"0\":\n      char = \"\\\\0\";\n\n      // Octal literals fail in strict mode.\n      // Check if the number is between 00 and 07.\n      var n = parseInt(this.peek(1), 10);\n      this.triggerAsync(\"warning\", {\n        code: \"W115\",\n        line: this.line,\n        character: this.char\n      }, checks,\n      function() { return n >= 0 && n <= 7 && state.isStrict(); });\n      break;\n    case \"1\":\n    case \"2\":\n    case \"3\":\n    case \"4\":\n    case \"5\":\n    case \"6\":\n    case \"7\":\n      char = \"\\\\\" + char;\n      this.triggerAsync(\"warning\", {\n        code: \"W115\",\n        line: this.line,\n        character: this.char\n      }, checks,\n      function() { return state.isStrict(); });\n      break;\n    case \"u\":\n      var sequence = this.input.substr(1, 4);\n      var code = parseInt(sequence, 16);\n      if (!isHex(sequence)) {\n        // This condition unequivocally describes a syntax error.\n        // TODO: Re-factor as an \"error\" (not a \"warning\").\n        this.trigger(\"warning\", {\n          code: \"W052\",\n          line: this.line,\n          character: this.char,\n          data: [ \"u\" + sequence ]\n        });\n      }\n      char = String.fromCharCode(code);\n      jump = 5;\n      break;\n    case \"v\":\n      this.triggerAsync(\"warning\", {\n        code: \"W114\",\n        line: this.line,\n        character: this.char,\n        data: [ \"\\\\v\" ]\n      }, checks, function() { return state.jsonMode; });\n\n      char = \"\\v\";\n      break;\n    case \"x\":\n      var  x = parseInt(this.input.substr(1, 2), 16);\n\n      this.triggerAsync(\"warning\", {\n        code: \"W114\",\n        line: this.line,\n        character: this.char,\n        data: [ \"\\\\x-\" ]\n      }, checks, function() { return state.jsonMode; });\n\n      char = String.fromCharCode(x);\n      jump = 3;\n      break;\n    case \"\\\\\":\n      char = \"\\\\\\\\\";\n      break;\n    case \"\\\"\":\n      char = \"\\\\\\\"\";\n      break;\n    case \"/\":\n      break;\n    case \"\":\n      allowNewLine = true;\n      char = \"\";\n      break;\n    }\n\n    return { char: char, jump: jump, allowNewLine: allowNewLine };\n  },\n\n  /*\n   * Extract a template literal out of the next sequence of characters\n   * and/or lines or return 'null' if its not possible. Since template\n   * literals can span across multiple lines, this method has to move\n   * the char pointer.\n   */\n  scanTemplateLiteral: function(checks) {\n    var tokenType;\n    var value = \"\";\n    var ch;\n    var startLine = this.line;\n    var startChar = this.char;\n    var depth = this.templateStarts.length;\n\n    if (this.peek() === \"`\") {\n      if (!state.inES6(true)) {\n        this.triggerAsync(\n          \"warning\",\n          {\n            code: \"W119\",\n            line: this.line,\n            character: this.char,\n            data: [\"template literal syntax\", \"6\"]\n          },\n          checks,\n          function() { return true; }\n        );\n      }\n      // Template must start with a backtick.\n      tokenType = Token.TemplateHead;\n      this.templateStarts.push({ line: this.line, char: this.char });\n      depth = this.templateStarts.length;\n      this.skip(1);\n      this.pushContext(Context.Template);\n    } else if (this.inContext(Context.Template) && this.peek() === \"}\") {\n      // If we're in a template context, and we have a '}', lex a TemplateMiddle.\n      tokenType = Token.TemplateMiddle;\n    } else {\n      // Go lex something else.\n      return null;\n    }\n\n    while (this.peek() !== \"`\") {\n      while ((ch = this.peek()) === \"\") {\n        value += \"\\n\";\n        if (!this.nextLine(checks)) {\n          // Unclosed template literal --- point to the starting \"`\"\n          var startPos = this.templateStarts.pop();\n          this.trigger(\"error\", {\n            code: \"E052\",\n            line: startPos.line,\n            character: startPos.char\n          });\n          return {\n            type: tokenType,\n            value: value,\n            startLine: startLine,\n            startChar: startChar,\n            isUnclosed: true,\n            depth: depth,\n            context: this.popContext()\n          };\n        }\n      }\n\n      if (ch === '$' && this.peek(1) === '{') {\n        value += '${';\n        this.skip(2);\n        return {\n          type: tokenType,\n          value: value,\n          startLine: startLine,\n          startChar: startChar,\n          isUnclosed: false,\n          depth: depth,\n          context: this.currentContext()\n        };\n      } else if (ch === '\\\\') {\n        var escape = this.scanEscapeSequence(checks);\n        value += escape.char;\n        this.skip(escape.jump);\n      } else if (ch !== '`') {\n        // Otherwise, append the value and continue.\n        value += ch;\n        this.skip(1);\n      }\n    }\n\n    // Final value is either NoSubstTemplate or TemplateTail\n    tokenType = tokenType === Token.TemplateHead ? Token.NoSubstTemplate : Token.TemplateTail;\n    this.skip(1);\n    this.templateStarts.pop();\n\n    return {\n      type: tokenType,\n      value: value,\n      startLine: startLine,\n      startChar: startChar,\n      isUnclosed: false,\n      depth: depth,\n      context: this.popContext()\n    };\n  },\n\n  /*\n   * Extract a string out of the next sequence of characters and/or\n   * lines or return 'null' if its not possible. Since strings can\n   * span across multiple lines this method has to move the char\n   * pointer.\n   *\n   * This method recognizes pseudo-multiline JavaScript strings:\n   *\n   *   var str = \"hello\\\n   *   world\";\n   */\n  scanStringLiteral: function(checks) {\n    /*jshint loopfunc:true */\n    var quote = this.peek();\n\n    // String must start with a quote.\n    if (quote !== \"\\\"\" && quote !== \"'\") {\n      return null;\n    }\n\n    // In JSON strings must always use double quotes.\n    this.triggerAsync(\"warning\", {\n      code: \"W108\",\n      line: this.line,\n      character: this.char // +1?\n    }, checks, function() { return state.jsonMode && quote !== \"\\\"\"; });\n\n    var value = \"\";\n    var startLine = this.line;\n    var startChar = this.char;\n    var allowNewLine = false;\n\n    this.skip();\n\n    while (this.peek() !== quote) {\n      if (this.peek() === \"\") { // End Of Line\n\n        // If an EOL is not preceded by a backslash, show a warning\n        // and proceed like it was a legit multi-line string where\n        // author simply forgot to escape the newline symbol.\n        //\n        // Another approach is to implicitly close a string on EOL\n        // but it generates too many false positives.\n\n        if (!allowNewLine) {\n          // This condition unequivocally describes a syntax error.\n          // TODO: Emit error E029 and remove W112.\n          this.trigger(\"warning\", {\n            code: \"W112\",\n            line: this.line,\n            character: this.char\n          });\n        } else {\n          allowNewLine = false;\n\n          // Otherwise show a warning if multistr option was not set.\n          // For JSON, show warning no matter what.\n\n          this.triggerAsync(\"warning\", {\n            code: \"W043\",\n            line: this.line,\n            character: this.char\n          }, checks, function() { return !state.option.multistr; });\n\n          this.triggerAsync(\"warning\", {\n            code: \"W042\",\n            line: this.line,\n            character: this.char\n          }, checks, function() { return state.jsonMode && state.option.multistr; });\n        }\n\n        // If we get an EOF inside of an unclosed string, show an\n        // error and implicitly close it at the EOF point.\n\n        if (!this.nextLine(checks)) {\n          return {\n            type: Token.StringLiteral,\n            value: value,\n            startLine: startLine,\n            startChar: startChar,\n            isUnclosed: true,\n            quote: quote\n          };\n        }\n\n      } else { // Any character other than End Of Line\n\n        allowNewLine = false;\n        var char = this.peek();\n        var jump = 1; // A length of a jump, after we're done\n                      // parsing this character.\n\n        if (char < \" \") {\n          // Warn about a control character in a string.\n          this.triggerAsync(\n            \"warning\",\n            {\n              code: \"W113\",\n              line: this.line,\n              character: this.char,\n              data: [ \"<non-printable>\" ]\n            },\n            checks,\n            function() { return true; }\n          );\n        }\n\n        // Special treatment for some escaped characters.\n        if (char === \"\\\\\") {\n          var parsed = this.scanEscapeSequence(checks);\n          char = parsed.char;\n          jump = parsed.jump;\n          allowNewLine = parsed.allowNewLine;\n        }\n\n        // If char is the empty string, end of the line has been reached. In\n        // this case, `this.char` should not be incremented so that warnings\n        // and errors reported in the subsequent loop iteration have the\n        // correct character column offset.\n        if (char !== \"\") {\n          value += char;\n          this.skip(jump);\n        }\n      }\n    }\n\n    this.skip();\n    return {\n      type: Token.StringLiteral,\n      value: value,\n      startLine: startLine,\n      startChar: startChar,\n      isUnclosed: false,\n      quote: quote\n    };\n  },\n\n  /*\n   * Extract a regular expression out of the next sequence of\n   * characters and/or lines or return 'null' if its not possible.\n   *\n   * This method is platform dependent: it accepts almost any\n   * regular expression values but then tries to compile and run\n   * them using system's RegExp object. This means that there are\n   * rare edge cases where one JavaScript engine complains about\n   * your regular expression while others don't.\n   */\n  scanRegExp: function(checks) {\n    var index = 0;\n    var length = this.input.length;\n    var char = this.peek();\n    var value = char;\n    var body = \"\";\n    var flags = [];\n    var malformed = false;\n    var isCharSet = false;\n    var terminated, malformedDesc;\n\n    var scanUnexpectedChars = function() {\n      // Unexpected control character\n      if (char < \" \") {\n        malformed = true;\n        this.triggerAsync(\n          \"warning\",\n          {\n            code: \"W048\",\n            line: this.line,\n            character: this.char\n          },\n          checks,\n          function() { return true; }\n        );\n      }\n\n      // Unexpected escaped character\n      if (char === \"<\") {\n        malformed = true;\n        this.triggerAsync(\n          \"warning\",\n          {\n            code: \"W049\",\n            line: this.line,\n            character: this.char,\n            data: [ char ]\n          },\n          checks,\n          function() { return true; }\n        );\n      }\n    }.bind(this);\n\n    // Regular expressions must start with '/'\n    if (!this.prereg || char !== \"/\") {\n      return null;\n    }\n\n    index += 1;\n    terminated = false;\n\n    // Try to get everything in between slashes. A couple of\n    // cases aside (see scanUnexpectedChars) we don't really\n    // care whether the resulting expression is valid or not.\n    // We will check that later using the RegExp object.\n\n    while (index < length) {\n      char = this.peek(index);\n      value += char;\n      body += char;\n\n      if (isCharSet) {\n        if (char === \"]\") {\n          if (this.peek(index - 1) !== \"\\\\\" || this.peek(index - 2) === \"\\\\\") {\n            isCharSet = false;\n          }\n        }\n\n        if (char === \"\\\\\") {\n          index += 1;\n          char = this.peek(index);\n          body += char;\n          value += char;\n\n          scanUnexpectedChars();\n        }\n\n        index += 1;\n        continue;\n      }\n\n      if (char === \"\\\\\") {\n        index += 1;\n        char = this.peek(index);\n        body += char;\n        value += char;\n\n        scanUnexpectedChars();\n\n        if (char === \"/\") {\n          index += 1;\n          continue;\n        }\n\n        if (char === \"[\") {\n          index += 1;\n          continue;\n        }\n      }\n\n      if (char === \"[\") {\n        isCharSet = true;\n        index += 1;\n        continue;\n      }\n\n      if (char === \"/\") {\n        body = body.substr(0, body.length - 1);\n        terminated = true;\n        index += 1;\n        break;\n      }\n\n      index += 1;\n    }\n\n    // A regular expression that was never closed is an\n    // error from which we cannot recover.\n\n    if (!terminated) {\n      this.trigger(\"error\", {\n        code: \"E015\",\n        line: this.line,\n        character: this.from\n      });\n\n      return void this.trigger(\"fatal\", {\n        line: this.line,\n        from: this.from\n      });\n    }\n\n    // Parse flags (if any).\n\n    while (index < length) {\n      char = this.peek(index);\n      if (!/[gimy]/.test(char)) {\n        break;\n      }\n      if (char === \"y\") {\n        if (!state.inES6(true)) {\n          this.triggerAsync(\n            \"warning\",\n            {\n              code: \"W119\",\n              line: this.line,\n              character: this.char,\n              data: [ \"Sticky RegExp flag\", \"6\" ]\n            },\n            checks,\n            function() { return true; }\n          );\n        }\n        if (value.indexOf(\"y\") > -1) {\n          malformedDesc = \"Duplicate RegExp flag\";\n        }\n      } else {\n        flags.push(char);\n      }\n      value += char;\n      index += 1;\n    }\n\n    // Check regular expression for correctness.\n\n    try {\n      new RegExp(body, flags.join(\"\"));\n    } catch (err) {\n      /**\n       * Because JSHint relies on the current engine's RegExp parser to\n       * validate RegExp literals, the description (exposed as the \"data\"\n       * property on the error object) is platform dependent.\n       */\n      malformedDesc = err.message;\n    }\n\n    if (malformedDesc) {\n      malformed = true;\n      this.trigger(\"error\", {\n        code: \"E016\",\n        line: this.line,\n        character: this.char,\n        data: [ malformedDesc ]\n      });\n    }\n\n    return {\n      type: Token.RegExp,\n      value: value,\n      isMalformed: malformed\n    };\n  },\n\n  /*\n   * Scan for any occurrence of non-breaking spaces. Non-breaking spaces\n   * can be mistakenly typed on OS X with option-space. Non UTF-8 web\n   * pages with non-breaking pages produce syntax errors.\n   */\n  scanNonBreakingSpaces: function() {\n    return state.option.nonbsp ?\n      this.input.search(/(\\u00A0)/) : -1;\n  },\n\n  /*\n   * Produce the next raw token or return 'null' if no tokens can be matched.\n   * This method skips over all space characters.\n   */\n  next: function(checks) {\n    this.from = this.char;\n\n    // Move to the next non-space character.\n    while (reg.whitespace.test(this.peek())) {\n      this.from += 1;\n      this.skip();\n    }\n\n    // Methods that work with multi-line structures and move the\n    // character pointer.\n\n    var match = this.scanComments(checks) ||\n      this.scanStringLiteral(checks) ||\n      this.scanTemplateLiteral(checks);\n\n    if (match) {\n      return match;\n    }\n\n    // Methods that don't move the character pointer.\n\n    match =\n      this.scanRegExp(checks) ||\n      this.scanPunctuator() ||\n      this.scanKeyword() ||\n      this.scanIdentifier(checks) ||\n      this.scanNumericLiteral(checks);\n\n    if (match) {\n      this.skip(match.tokenLength || match.value.length);\n      return match;\n    }\n\n    // No token could be matched, give up.\n\n    return null;\n  },\n\n  /*\n   * Switch to the next line and reset all char pointers. Once\n   * switched, this method also checks for other minor warnings.\n   */\n  nextLine: function(checks) {\n    var char;\n\n    if (this.line >= this.getLines().length) {\n      return false;\n    }\n\n    this.input = this.getLines()[this.line];\n    this.line += 1;\n    this.char = 1;\n    this.from = 1;\n\n    var inputTrimmed = this.input.trim();\n\n    var startsWith = function() {\n      return _.some(arguments, function(prefix) {\n        return inputTrimmed.indexOf(prefix) === 0;\n      });\n    };\n\n    var endsWith = function() {\n      return _.some(arguments, function(suffix) {\n        return inputTrimmed.indexOf(suffix, inputTrimmed.length - suffix.length) !== -1;\n      });\n    };\n\n    // If we are ignoring linter errors, replace the input with empty string\n    // if it doesn't already at least start or end a multi-line comment\n    if (this.ignoringLinterErrors === true) {\n      if (!startsWith(\"/*\", \"//\") && !(this.inComment && endsWith(\"*/\"))) {\n        this.input = \"\";\n      }\n    }\n\n    char = this.scanNonBreakingSpaces();\n    if (char >= 0) {\n      this.triggerAsync(\n        \"warning\",\n        { code: \"W125\", line: this.line, character: char + 1 },\n        checks,\n        function() { return true; }\n      );\n    }\n\n    this.input = this.input.replace(/\\t/g, state.tab);\n\n    // If there is a limit on line length, warn when lines get too\n    // long.\n\n    if (!this.ignoringLinterErrors && state.option.maxlen &&\n      state.option.maxlen < this.input.length) {\n      var inComment = this.inComment ||\n        startsWith.call(inputTrimmed, \"//\") ||\n        startsWith.call(inputTrimmed, \"/*\");\n\n      var shouldTriggerError = !inComment || !reg.maxlenException.test(inputTrimmed);\n\n      if (shouldTriggerError) {\n        this.triggerAsync(\n          \"warning\",\n          { code: \"W101\", line: this.line, character: this.input.length },\n          checks,\n          function() { return true; }\n        );\n      }\n    }\n\n    return true;\n  },\n\n  /*\n   * Produce the next token. This function is called by advance() to get\n   * the next token. It returns a token in a JSLint-compatible format.\n   */\n  token: function() {\n    /*jshint loopfunc:true */\n    var checks = asyncTrigger();\n    var token;\n\n\n    function isReserved(token, isProperty) {\n      // At present all current identifiers have reserved set.\n      // Preserving check anyway, for future-proofing.\n      /* istanbul ignore if */\n      if (!token.reserved) {\n        return false;\n      }\n      var meta = token.meta;\n\n      if (meta && meta.isFutureReservedWord && state.inES5()) {\n        // ES3 FutureReservedWord in an ES5 environment.\n        if (!meta.es5) {\n          return false;\n        }\n\n        // Some ES5 FutureReservedWord identifiers are active only\n        // within a strict mode environment.\n        if (meta.strictOnly) {\n          if (!state.option.strict && !state.isStrict()) {\n            return false;\n          }\n        }\n\n        if (isProperty) {\n          return false;\n        }\n      }\n\n      return true;\n    }\n\n    // Produce a token object.\n    var create = function(type, value, isProperty, token) {\n      /*jshint validthis:true */\n      var obj;\n\n      if (type !== \"(endline)\" && type !== \"(end)\") {\n        this.prereg = false;\n      }\n\n      if (type === \"(punctuator)\") {\n        switch (value) {\n        case \".\":\n        case \")\":\n        case \"~\":\n        case \"#\":\n        case \"]\":\n        case \"}\":\n        case \"++\":\n        case \"--\":\n          this.prereg = false;\n          break;\n        default:\n          this.prereg = true;\n        }\n\n        obj = Object.create(state.syntax[value] || state.syntax[\"(error)\"]);\n      }\n\n      if (type === \"(identifier)\") {\n        if (value === \"return\" || value === \"case\" || value === \"yield\" ||\n            value === \"typeof\" || value === \"instanceof\" || value === \"void\") {\n          this.prereg = true;\n        }\n\n        if (_.has(state.syntax, value)) {\n          obj = Object.create(state.syntax[value]);\n          // If this can't be a reserved keyword, reset the object.\n          if (!isReserved(obj, isProperty && type === \"(identifier)\")) {\n            obj = null;\n          }\n        }\n      }\n\n      if (type === \"(template)\" || type === \"(template middle)\") {\n        this.prereg = true;\n      }\n\n      if (!obj) {\n        obj = Object.create(state.syntax[type]);\n      }\n\n      obj.identifier = (type === \"(identifier)\");\n      obj.type = obj.type || type;\n      obj.value = value;\n      obj.line = this.line;\n      obj.character = this.char;\n      obj.from = this.from;\n      if (obj.identifier && token) obj.raw_text = token.text || token.value;\n      if (token && token.startLine && token.startLine !== this.line) {\n        obj.startLine = token.startLine;\n      }\n      if (token && token.context) {\n        // Context of current token\n        obj.context = token.context;\n      }\n      if (token && token.depth) {\n        // Nested template depth\n        obj.depth = token.depth;\n      }\n      if (token && token.isUnclosed) {\n        // Mark token as unclosed string / template literal\n        obj.isUnclosed = token.isUnclosed;\n      }\n\n      if (isProperty && obj.identifier) {\n        obj.isProperty = isProperty;\n      }\n\n      obj.check = checks.check;\n\n      return obj;\n    }.bind(this);\n\n    for (;;) {\n      if (!this.input.length) {\n        if (this.nextLine(checks)) {\n          return create(\"(endline)\", \"\");\n        }\n\n        if (this.exhausted) {\n          return null;\n        }\n\n        this.exhausted = true;\n        return create(\"(end)\", \"\");\n      }\n\n      token = this.next(checks);\n\n      if (!token) {\n        if (this.input.length) {\n          // Unexpected character.\n          this.trigger(\"error\", {\n            code: \"E024\",\n            line: this.line,\n            character: this.char,\n            data: [ this.peek() ]\n          });\n\n          this.input = \"\";\n        }\n\n        continue;\n      }\n\n      switch (token.type) {\n      case Token.StringLiteral:\n        this.triggerAsync(\"String\", {\n          line: this.line,\n          char: this.char,\n          from: this.from,\n          startLine: token.startLine,\n          startChar: token.startChar,\n          value: token.value,\n          quote: token.quote\n        }, checks, function() { return true; });\n\n        return create(\"(string)\", token.value, null, token);\n\n      case Token.TemplateHead:\n        this.trigger(\"TemplateHead\", {\n          line: this.line,\n          char: this.char,\n          from: this.from,\n          startLine: token.startLine,\n          startChar: token.startChar,\n          value: token.value\n        });\n        return create(\"(template)\", token.value, null, token);\n\n      case Token.TemplateMiddle:\n        this.trigger(\"TemplateMiddle\", {\n          line: this.line,\n          char: this.char,\n          from: this.from,\n          startLine: token.startLine,\n          startChar: token.startChar,\n          value: token.value\n        });\n        return create(\"(template middle)\", token.value, null, token);\n\n      case Token.TemplateTail:\n        this.trigger(\"TemplateTail\", {\n          line: this.line,\n          char: this.char,\n          from: this.from,\n          startLine: token.startLine,\n          startChar: token.startChar,\n          value: token.value\n        });\n        return create(\"(template tail)\", token.value, null, token);\n\n      case Token.NoSubstTemplate:\n        this.trigger(\"NoSubstTemplate\", {\n          line: this.line,\n          char: this.char,\n          from: this.from,\n          startLine: token.startLine,\n          startChar: token.startChar,\n          value: token.value\n        });\n        return create(\"(no subst template)\", token.value, null, token);\n\n      case Token.Identifier:\n        this.triggerAsync(\"Identifier\", {\n          line: this.line,\n          char: this.char,\n          from: this.from,\n          name: token.value,\n          raw_name: token.text,\n          isProperty: state.tokens.curr.id === \".\"\n        }, checks, function() { return true; });\n\n        /* falls through */\n      case Token.Keyword:\n        return create(\"(identifier)\", token.value, state.tokens.curr.id === \".\", token);\n\n      case Token.NumericLiteral:\n        if (token.isMalformed) {\n          // This condition unequivocally describes a syntax error.\n          // TODO: Re-factor as an \"error\" (not a \"warning\").\n          this.trigger(\"warning\", {\n            code: \"W045\",\n            line: this.line,\n            character: this.char,\n            data: [ token.value ]\n          });\n        }\n\n        this.triggerAsync(\"warning\", {\n          code: \"W114\",\n          line: this.line,\n          character: this.char,\n          data: [ \"0x-\" ]\n        }, checks, function() { return token.base === 16 && state.jsonMode; });\n\n        this.triggerAsync(\"warning\", {\n          code: \"W115\",\n          line: this.line,\n          character: this.char\n        }, checks, function() {\n          return state.isStrict() && token.base === 8 && token.isLegacy;\n        });\n\n        this.trigger(\"Number\", {\n          line: this.line,\n          char: this.char,\n          from: this.from,\n          value: token.value,\n          base: token.base,\n          isMalformed: token.isMalformed\n        });\n\n        return create(\"(number)\", token.value);\n\n      case Token.RegExp:\n        return create(\"(regexp)\", token.value);\n\n      case Token.Comment:\n        if (token.isSpecial) {\n          return {\n            id: '(comment)',\n            value: token.value,\n            body: token.body,\n            type: token.commentType,\n            isSpecial: token.isSpecial,\n            line: this.line,\n            character: this.char,\n            from: this.from\n          };\n        }\n\n        break;\n\n      default:\n        return create(\"(punctuator)\", token.value);\n      }\n    }\n  }\n};\n\nexports.Lexer = Lexer;\nexports.Context = Context;\n\n},{\"../data/ascii-identifier-data.js\":1,\"../data/es5-identifier-names.js\":2,\"../data/non-ascii-identifier-part-only.js\":3,\"../data/non-ascii-identifier-start.js\":4,\"./reg.js\":18,\"./state.js\":20,\"events\":6,\"lodash\":13}],15:[function(require,module,exports){\n\"use strict\";\n\nvar _ = require(\"lodash\");\n\nvar errors = {\n  // JSHint options\n  E001: \"Bad option: '{a}'.\",\n  E002: \"Bad option value.\",\n\n  // JSHint input\n  E003: \"Expected a JSON value.\",\n  E004: \"Input is neither a string nor an array of strings.\",\n  E005: \"Input is empty.\",\n  E006: \"Unexpected early end of program.\",\n\n  // Strict mode\n  E007: \"Missing \\\"use strict\\\" statement.\",\n  E008: \"Strict violation.\",\n  E009: \"Option 'validthis' can't be used in a global scope.\",\n  E010: \"'with' is not allowed in strict mode.\",\n\n  // Constants\n  E011: \"'{a}' has already been declared.\",\n  E012: \"const '{a}' is initialized to 'undefined'.\",\n  E013: \"Attempting to override '{a}' which is a constant.\",\n\n  // Regular expressions\n  E014: \"A regular expression literal can be confused with '/='.\",\n  E015: \"Unclosed regular expression.\",\n  E016: \"Invalid regular expression.\",\n\n  // Tokens\n  E017: \"Unclosed comment.\",\n  E018: \"Unbegun comment.\",\n  E019: \"Unmatched '{a}'.\",\n  E020: \"Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.\",\n  E021: \"Expected '{a}' and instead saw '{b}'.\",\n  E022: \"Line breaking error '{a}'.\",\n  E023: \"Missing '{a}'.\",\n  E024: \"Unexpected '{a}'.\",\n  E025: \"Missing ':' on a case clause.\",\n  E026: \"Missing '}' to match '{' from line {a}.\",\n  E027: \"Missing ']' to match '[' from line {a}.\",\n  E028: \"Illegal comma.\",\n  E029: \"Unclosed string.\",\n\n  // Everything else\n  E030: \"Expected an identifier and instead saw '{a}'.\",\n  E031: \"Bad assignment.\", // FIXME: Rephrase\n  E032: \"Expected a small integer or 'false' and instead saw '{a}'.\",\n  E033: \"Expected an operator and instead saw '{a}'.\",\n  E034: \"get/set are ES5 features.\",\n  E035: \"Missing property name.\",\n  E036: \"Expected to see a statement and instead saw a block.\",\n  E037: null,\n  E038: null,\n  E039: \"Function declarations are not invocable. Wrap the whole function invocation in parens.\",\n  E040: \"Each value should have its own case label.\",\n  E041: \"Unrecoverable syntax error.\",\n  E042: \"Stopping.\",\n  E043: \"Too many errors.\",\n  E044: null,\n  E045: \"Invalid for each loop.\",\n  E046: \"Yield expressions may only occur within generator functions.\",\n  E047: null,\n  E048: \"{a} declaration not directly within block.\",\n  E049: \"A {a} cannot be named '{b}'.\",\n  E050: \"Mozilla requires the yield expression to be parenthesized here.\",\n  E051: null,\n  E052: \"Unclosed template literal.\",\n  E053: \"{a} declarations are only allowed at the top level of module scope.\",\n  E054: \"Class properties must be methods. Expected '(' but instead saw '{a}'.\",\n  E055: \"The '{a}' option cannot be set after any executable code.\",\n  E056: \"'{a}' was used before it was declared, which is illegal for '{b}' variables.\",\n  E057: \"Invalid meta property: '{a}.{b}'.\",\n  E058: \"Missing semicolon.\",\n  E059: \"Incompatible values for the '{a}' and '{b}' linting options.\",\n  E060: \"Non-callable values cannot be used as the second operand to instanceof.\",\n  E061: \"Invalid position for 'yield' expression (consider wrapping in parenthesis).\",\n  E062: \"Rest parameter does not a support default value.\",\n  E063: \"Super property may only be used within method bodies.\",\n  E064: \"Super call may only be used within class method bodies.\"\n};\n\nvar warnings = {\n  W001: \"'hasOwnProperty' is a really bad name.\",\n  W002: \"Value of '{a}' may be overwritten in IE 8 and earlier.\",\n  W003: \"'{a}' was used before it was defined.\",\n  W004: \"'{a}' is already defined.\",\n  W005: \"A dot following a number can be confused with a decimal point.\",\n  W006: \"Confusing minuses.\",\n  W007: \"Confusing plusses.\",\n  W008: \"A leading decimal point can be confused with a dot: '{a}'.\",\n  W009: \"The array literal notation [] is preferable.\",\n  W010: \"The object literal notation {} is preferable.\",\n  W011: null,\n  W012: null,\n  W013: null,\n  W014: \"Misleading line break before '{a}'; readers may interpret this as an expression boundary.\",\n  W015: null,\n  W016: \"Unexpected use of '{a}'.\",\n  W017: \"Bad operand.\",\n  W018: \"Confusing use of '{a}'.\",\n  W019: \"Use the isNaN function to compare with NaN.\",\n  W020: \"Read only.\",\n  W021: \"Reassignment of '{a}', which is a {b}. \" +\n    \"Use 'var' or 'let' to declare bindings that may change.\",\n  W022: \"Do not assign to the exception parameter.\",\n  W023: null,\n  W024: \"Expected an identifier and instead saw '{a}' (a reserved word).\",\n  W025: \"Missing name in function declaration.\",\n  W026: \"Inner functions should be listed at the top of the outer function.\",\n  W027: \"Unreachable '{a}' after '{b}'.\",\n  W028: \"Label '{a}' on {b} statement.\",\n  W030: \"Expected an assignment or function call and instead saw an expression.\",\n  W031: \"Do not use 'new' for side effects.\",\n  W032: \"Unnecessary semicolon.\",\n  W033: \"Missing semicolon.\",\n  W034: \"Unnecessary directive \\\"{a}\\\".\",\n  W035: \"Empty block.\",\n  W036: \"Unexpected /*member '{a}'.\",\n  W037: \"'{a}' is a statement label.\",\n  W038: \"'{a}' used out of scope.\",\n  W039: \"'{a}' is not allowed.\",\n  W040: \"If a strict mode function is executed using function invocation, \" +\n    \"its 'this' value will be undefined.\",\n  W041: null,\n  W042: \"Avoid EOL escaping.\",\n  W043: \"Bad escaping of EOL. Use option multistr if needed.\",\n  W044: \"Bad or unnecessary escaping.\", /* TODO(caitp): remove W044 */\n  W045: \"Bad number '{a}'.\",\n  W046: \"Don't use extra leading zeros '{a}'.\",\n  W047: \"A trailing decimal point can be confused with a dot: '{a}'.\",\n  W048: \"Unexpected control character in regular expression.\",\n  W049: \"Unexpected escaped character '{a}' in regular expression.\",\n  W050: \"JavaScript URL.\",\n  W051: \"Variables should not be deleted.\",\n  W052: \"Unexpected '{a}'.\",\n  W053: \"Do not use {a} as a constructor.\",\n  W054: \"The Function constructor is a form of eval.\",\n  W055: \"A constructor name should start with an uppercase letter.\",\n  W056: \"Bad constructor.\",\n  W057: \"Weird construction. Is 'new' necessary?\",\n  W058: \"Missing '()' invoking a constructor.\",\n  W059: \"Avoid arguments.{a}.\",\n  W060: \"document.write can be a form of eval.\",\n  W061: \"eval can be harmful.\",\n  W062: \"Wrap an immediate function invocation in parens \" +\n    \"to assist the reader in understanding that the expression \" +\n    \"is the result of a function, and not the function itself.\",\n  W063: \"Math is not a function.\",\n  W064: \"Missing 'new' prefix when invoking a constructor.\",\n  W065: \"Missing radix parameter.\",\n  W066: \"Implied eval. Consider passing a function instead of a string.\",\n  W067: \"Bad invocation.\",\n  W068: \"Wrapping non-IIFE function literals in parens is unnecessary.\",\n  W069: \"['{a}'] is better written in dot notation.\",\n  W070: \"Extra comma. (it breaks older versions of IE)\",\n  W071: \"This function has too many statements. ({a})\",\n  W072: \"This function has too many parameters. ({a})\",\n  W073: \"Blocks are nested too deeply. ({a})\",\n  W074: \"This function's cyclomatic complexity is too high. ({a})\",\n  W075: \"Duplicate {a} '{b}'.\",\n  W076: \"Unexpected parameter '{a}' in get {b} function.\",\n  W077: \"Expected a single parameter in set {a} function.\",\n  W078: \"Setter is defined without getter.\",\n  W079: \"Redefinition of '{a}'.\",\n  W080: \"It's not necessary to initialize '{a}' to 'undefined'.\",\n  W081: null,\n  W082: \"Function declarations should not be placed in blocks. \" +\n    \"Use a function expression or move the statement to the top of \" +\n    \"the outer function.\",\n  W083: \"Functions declared within loops referencing an outer scoped \" +\n    \"variable may lead to confusing semantics. ({a})\",\n  W084: \"Expected a conditional expression and instead saw an assignment.\",\n  W085: \"Don't use 'with'.\",\n  W086: \"Expected a 'break' statement before '{a}'.\",\n  W087: \"Forgotten 'debugger' statement?\",\n  W088: \"Creating global 'for' variable. Should be 'for (var {a} ...'.\",\n  W089: \"The body of a for in should be wrapped in an if statement to filter \" +\n    \"unwanted properties from the prototype.\",\n  W090: \"'{a}' is not a statement label.\",\n  W091: null,\n  W093: \"Did you mean to return a conditional instead of an assignment?\",\n  W094: \"Unexpected comma.\",\n  W095: \"Expected a string and instead saw {a}.\",\n  W096: \"The '{a}' key may produce unexpected results.\",\n  W097: \"Use the function form of \\\"use strict\\\".\",\n  W098: \"'{a}' is defined but never used.\",\n  W099: null,\n  W100: null,\n  W101: \"Line is too long.\",\n  W102: null,\n  W103: \"The '{a}' property is deprecated.\",\n  W104: \"'{a}' is available in ES{b} (use 'esversion: {b}') or Mozilla JS extensions (use moz).\",\n  W105: \"Unexpected {a} in '{b}'.\",\n  W106: \"Identifier '{a}' is not in camel case.\",\n  W107: \"Script URL.\",\n  W108: \"Strings must use doublequote.\",\n  W109: \"Strings must use singlequote.\",\n  W110: \"Mixed double and single quotes.\",\n  W112: \"Unclosed string.\",\n  W113: \"Control character in string: {a}.\",\n  W114: \"Avoid {a}.\",\n  W115: \"Octal literals are not allowed in strict mode.\",\n  W116: \"Expected '{a}' and instead saw '{b}'.\",\n  W117: \"'{a}' is not defined.\",\n  W118: \"'{a}' is only available in Mozilla JavaScript extensions (use moz option).\",\n  W119: \"'{a}' is only available in ES{b} (use 'esversion: {b}').\",\n  W120: \"You might be leaking a variable ({a}) here.\",\n  W121: \"Extending prototype of native object: '{a}'.\",\n  W122: \"Invalid typeof value '{a}'\",\n  W123: \"'{a}' is already defined in outer scope.\",\n  W124: \"A generator function should contain at least one yield expression.\",\n  W125: \"This line contains non-breaking spaces: http://jshint.com/docs/options/#nonbsp\",\n  W126: \"Unnecessary grouping operator.\",\n  W127: \"Unexpected use of a comma operator.\",\n  W128: \"Empty array elements require elision=true.\",\n  W129: \"'{a}' is defined in a future version of JavaScript. Use a \" +\n    \"different variable name to avoid migration issues.\",\n  W130: \"Invalid element after rest element.\",\n  W131: \"Invalid parameter after rest parameter.\",\n  W132: \"`var` declarations are forbidden. Use `let` or `const` instead.\",\n  W133: \"Invalid for-{a} loop left-hand-side: {b}.\",\n  W134: \"The '{a}' option is only available when linting ECMAScript {b} code.\",\n  W135: \"{a} may not be supported by non-browser environments.\",\n  W136: \"'{a}' must be in function scope.\",\n  W137: \"Empty destructuring: this is unnecessary and can be removed.\",\n  W138: \"Regular parameters should not come after default parameters.\",\n  W139: \"Function expressions should not be used as the second operand to instanceof.\",\n  W140: \"Missing comma.\",\n  W141: \"Empty {a}: this is unnecessary and can be removed.\",\n  W142: \"Empty {a}: consider replacing with `import '{b}';`.\",\n  W143: \"Assignment to properties of a mapped arguments object may cause \" +\n    \"unexpected changes to formal parameters.\"\n};\n\nvar info = {\n  I001: \"Comma warnings can be turned off with 'laxcomma'.\",\n  I002: null,\n  I003: \"ES5 option is now set per default\"\n};\n\nexports.errors = {};\nexports.warnings = {};\nexports.info = {};\n\n_.each(errors, function(desc, code) {\n  exports.errors[code] = { code: code, desc: desc };\n});\n\n_.each(warnings, function(desc, code) {\n  exports.warnings[code] = { code: code, desc: desc };\n});\n\n_.each(info, function(desc, code) {\n  exports.info[code] = { code: code, desc: desc };\n});\n\n},{\"lodash\":13}],16:[function(require,module,exports){\n\"use strict\";\n\nfunction NameStack() {\n  this._stack = [];\n}\n\nObject.defineProperty(NameStack.prototype, \"length\", {\n  get: function() {\n    return this._stack.length;\n  }\n});\n\n/**\n * Create a new entry in the stack. Useful for tracking names across\n * expressions.\n */\nNameStack.prototype.push = function() {\n  this._stack.push(null);\n};\n\n/**\n * Discard the most recently-created name on the stack.\n */\nNameStack.prototype.pop = function() {\n  this._stack.pop();\n};\n\n/**\n * Update the most recent name on the top of the stack.\n *\n * @param {object} token The token to consider as the source for the most\n *                       recent name.\n */\nNameStack.prototype.set = function(token) {\n  this._stack[this.length - 1] = token;\n};\n\n/**\n * Generate a string representation of the most recent name.\n *\n * @returns {string}\n */\nNameStack.prototype.infer = function() {\n  var nameToken = this._stack[this.length - 1];\n  var prefix = \"\";\n  var type;\n\n  // During expected operation, the topmost entry on the stack will only\n  // reflect the current function's name when the function is declared without\n  // the `function` keyword (i.e. for in-line accessor methods). In other\n  // cases, the `function` expression itself will introduce an empty entry on\n  // the top of the stack, and this should be ignored.\n  if (!nameToken || nameToken.type === \"class\") {\n    nameToken = this._stack[this.length - 2];\n  }\n\n  if (!nameToken) {\n    return \"(empty)\";\n  }\n\n  type = nameToken.type;\n\n  if (type !== \"(string)\" && type !== \"(number)\" && type !== \"(identifier)\" && type !== \"default\") {\n    return \"(expression)\";\n  }\n\n  if (nameToken.accessorType) {\n    prefix = nameToken.accessorType + \" \";\n  }\n\n  return prefix + nameToken.value;\n};\n\nmodule.exports = NameStack;\n\n},{}],17:[function(require,module,exports){\n\"use strict\";\n\n// These are the JSHint boolean options.\nexports.bool = {\n  enforcing: {\n\n    /**\n     * This option prohibits the use of bitwise operators such as `^` (XOR),\n     * `|` (OR) and others. Bitwise operators are very rare in JavaScript\n     * programs and quite often `&` is simply a mistyped `&&`.\n     */\n    bitwise     : true,\n\n    /**\n     *\n     * This options prohibits overwriting prototypes of native objects such as\n     * `Array`, `Date` and so on.\n     *\n     *     // jshint freeze:true\n     *     Array.prototype.count = function (value) { return 4; };\n     *     // -> Warning: Extending prototype of native object: 'Array'.\n     */\n    freeze      : true,\n\n    /**\n     * This option allows you to force all variable names to use either\n     * camelCase style or UPPER_CASE with underscores.\n     *\n     * @deprecated JSHint is limiting its scope to issues of code correctness.\n     *             If you would like to enforce rules relating to code style,\n     *             check out [the JSCS\n     *             project](https://github.com/jscs-dev/node-jscs).\n     */\n    camelcase   : true,\n\n    /**\n     * This option requires you to always put curly braces around blocks in\n     * loops and conditionals. JavaScript allows you to omit curly braces when\n     * the block consists of only one statement, for example:\n     *\n     *     while (day)\n     *       shuffle();\n     *\n     * However, in some circumstances, it can lead to bugs (you'd think that\n     * `sleep()` is a part of the loop while in reality it is not):\n     *\n     *     while (day)\n     *       shuffle();\n     *       sleep();\n     */\n    curly       : true,\n\n    /**\n     * This options prohibits the use of `==` and `!=` in favor of `===` and\n     * `!==`. The former try to coerce values before comparing them which can\n     * lead to some unexpected results. The latter don't do any coercion so\n     * they are generally safer. If you would like to learn more about type\n     * coercion in JavaScript, we recommend [Truth, Equality and\n     * JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/)\n     * by Angus Croll.\n     */\n    eqeqeq      : true,\n\n    /**\n     * This option enables warnings about the use of identifiers which are\n     * defined in future versions of JavaScript. Although overwriting them has\n     * no effect in contexts where they are not implemented, this practice can\n     * cause issues when migrating codebases to newer versions of the language.\n     */\n    futurehostile: true,\n\n    /**\n     * This option tells JSHint that your code needs to adhere to ECMAScript 3\n     * specification. Use this option if you need your program to be executable\n     * in older browsers—such as Internet Explorer 6/7/8/9—and other legacy\n     * JavaScript environments.\n     *\n     * @deprecated Use `esversion: 3` instead.\n     */\n    es3         : true,\n\n    /**\n     * This option enables syntax first defined in [the ECMAScript 5.1\n     * specification](http://es5.github.io/). This includes allowing reserved\n     * keywords as object properties.\n     *\n     * @deprecated Use `esversion: 5` instead.\n     */\n    es5         : true,\n\n    /**\n     * This option requires all `for in` loops to filter object's items. The\n     * for in statement allows for looping through the names of all of the\n     * properties of an object including those inherited through the prototype\n     * chain. This behavior can lead to unexpected items in your object so it\n     * is generally safer to always filter inherited properties out as shown in\n     * the example:\n     *\n     *     for (key in obj) {\n     *       if (obj.hasOwnProperty(key)) {\n     *         // We are sure that obj[key] belongs to the object and was not inherited.\n     *       }\n     *     }\n     *\n     * For more in-depth understanding of `for in` loops in JavaScript, read\n     * [Exploring JavaScript for-in\n     * loops](http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/)\n     * by Angus Croll.\n     */\n    forin       : true,\n\n    /**\n     * This option prohibits the use of immediate function invocations without\n     * wrapping them in parentheses. Wrapping parentheses assists readers of\n     * your code in understanding that the expression is the result of a\n     * function, and not the function itself.\n     *\n     * @deprecated JSHint is limiting its scope to issues of code correctness.\n     *             If you would like to enforce rules relating to code style,\n     *             check out [the JSCS\n     *             project](https://github.com/jscs-dev/node-jscs).\n     */\n    immed       : true,\n\n    /**\n     * This option requires you to capitalize names of constructor functions.\n     * Capitalizing functions that are intended to be used with `new` operator\n     * is just a convention that helps programmers to visually distinguish\n     * constructor functions from other types of functions to help spot\n     * mistakes when using `this`.\n     *\n     * Not doing so won't break your code in any browsers or environments but\n     * it will be a bit harder to figure out—by reading the code—if the\n     * function was supposed to be used with or without new. And this is\n     * important because when the function that was intended to be used with\n     * `new` is used without it, `this` will point to the global object instead\n     * of a new object.\n     *\n     * @deprecated JSHint is limiting its scope to issues of code correctness.\n     *             If you would like to enforce rules relating to code style,\n     *             check out [the JSCS\n     *             project](https://github.com/jscs-dev/node-jscs).\n     */\n    newcap      : true,\n\n    /**\n     * This option prohibits the use of `arguments.caller` and\n     * `arguments.callee`.  Both `.caller` and `.callee` make quite a few\n     * optimizations impossible so they were deprecated in future versions of\n     * JavaScript. In fact, ECMAScript 5 forbids the use of `arguments.callee`\n     * in strict mode.\n     */\n    noarg       : true,\n\n    /**\n     * This option prohibits the use of the comma operator. When misused, the\n     * comma operator can obscure the value of a statement and promote\n     * incorrect code.\n     */\n    nocomma     : true,\n\n    /**\n     * This option warns when you have an empty block in your code. JSLint was\n     * originally warning for all empty blocks and we simply made it optional.\n     * There were no studies reporting that empty blocks in JavaScript break\n     * your code in any way.\n     *\n     * @deprecated JSHint is limiting its scope to issues of code correctness.\n     *             If you would like to enforce rules relating to code style,\n     *             check out [the JSCS\n     *             project](https://github.com/jscs-dev/node-jscs).\n     */\n    noempty     : true,\n\n    /**\n     * This option warns about \"non-breaking whitespace\" characters. These\n     * characters can be entered with option-space on Mac computers and have a\n     * potential of breaking non-UTF8 web pages.\n     */\n    nonbsp      : true,\n\n    /**\n     * This option prohibits the use of constructor functions for side-effects.\n     * Some people like to call constructor functions without assigning its\n     * result to any variable:\n     *\n     *     new MyConstructor();\n     *\n     * There is no advantage in this approach over simply calling\n     * `MyConstructor` since the object that the operator `new` creates isn't\n     * used anywhere so you should generally avoid constructors like this one.\n     */\n    nonew       : true,\n\n    /**\n     * This option prohibits the use of explicitly undeclared variables. This\n     * option is very useful for spotting leaking and mistyped variables.\n     *\n     *     // jshint undef:true\n     *\n     *     function test() {\n     *       var myVar = 'Hello, World';\n     *       console.log(myvar); // Oops, typoed here. JSHint with undef will complain\n     *     }\n     *\n     * If your variable is defined in another file, you can use the `global`\n     * directive to tell JSHint about it.\n     */\n    undef       : true,\n\n    /**\n     * This option prohibits the use of the grouping operator when it is not\n     * strictly required. Such usage commonly reflects a misunderstanding of\n     * unary operators, for example:\n     *\n     *     // jshint singleGroups: true\n     *\n     *     delete(obj.attr); // Warning: Unnecessary grouping operator.\n     */\n    singleGroups: false,\n\n    /**\n     * When set to true, the use of VariableStatements are forbidden.\n     * For example:\n     *\n     *     // jshint varstmt: true\n     *\n     *     var a; // Warning: `var` declarations are forbidden. Use `let` or `const` instead.\n     */\n    varstmt: false,\n\n    /**\n     * This option is a short hand for the most strict JSHint configuration as\n     * available in JSHint version 2.6.3. It enables all enforcing options and\n     * disables all relaxing options that were defined in that release.\n     *\n     * @deprecated The option cannot be maintained without automatically opting\n     *             users in to new features. This can lead to unexpected\n     *             warnings/errors in when upgrading between minor versions of\n     *             JSHint.\n     */\n    enforceall : false,\n\n    /**\n     * This option warns when a comma is not placed after the last element in an\n     * array or object literal. Due to bugs in old versions of IE, trailing\n     * commas used to be discouraged, but since ES5 their semantics were\n     * standardized. (See\n     * [#11.1.4](http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.4) and\n     * [#11.1.5](http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5).)\n     * Now, they help to prevent the same [visual\n     * ambiguities](http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.2)\n     * that the strict usage of semicolons helps prevent.\n     *\n     * For example, this code might have worked last Tuesday:\n     *\n     *     [\n     *         b + c\n     *     ].forEach(print);\n     *\n     * But if one adds an element to the array and forgets to compensate for the\n     * missing comma, no syntax error is thrown, and a linter cannot determine\n     * if this was a mistake or an intentional function invocation.\n     *\n     *     [\n     *         b + c\n     *         (d + e)\n     *     ].forEach(print);\n     *\n     * If one always appends a list item with a comma, this ambiguity cannot\n     * occur:\n     *\n     *     [\n     *         b + c,\n     *     ].forEach(print);\n     *\n     *     [\n     *         b + c,\n     *         (d + e),\n     *     ].forEach(print);\n     */\n    trailingcomma: false\n  },\n  relaxing: {\n\n    /**\n     * This option suppresses warnings about missing semicolons. There is a lot\n     * of FUD about semicolon spread by quite a few people in the community.\n     * The common myths are that semicolons are required all the time (they are\n     * not) and that they are unreliable. JavaScript has rules about semicolons\n     * which are followed by *all* browsers so it is up to you to decide\n     * whether you should or should not use semicolons in your code.\n     *\n     * For more information about semicolons in JavaScript read [An Open Letter\n     * to JavaScript Leaders Regarding\n     * Semicolons](http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding)\n     * by Isaac Schlueter and [JavaScript Semicolon\n     * Insertion](http://inimino.org/~inimino/blog/javascript_semicolons).\n     */\n    asi         : true,\n\n    /**\n     * This option suppresses warnings about multi-line strings. Multi-line\n     * strings can be dangerous in JavaScript because all hell breaks loose if\n     * you accidentally put a whitespace in between the escape character (`\\`)\n     * and a new line.\n     *\n     * Note that even though this option allows correct multi-line strings, it\n     * still warns about multi-line strings without escape characters or with\n     * anything in between the escape character and a whitespace.\n     *\n     *     // jshint multistr:true\n     *\n     *     var text = \"Hello\\\n     *     World\"; // All good.\n     *\n     *     text = \"Hello\n     *     World\"; // Warning, no escape character.\n     *\n     *     text = \"Hello\\\n     *     World\"; // Warning, there is a space after \\\n     *\n     * @deprecated JSHint is limiting its scope to issues of code correctness.\n     *             If you would like to enforce rules relating to code style,\n     *             check out [the JSCS\n     *             project](https://github.com/jscs-dev/node-jscs).\n     */\n    multistr    : true,\n\n    /**\n     * This option suppresses warnings about the `debugger` statements in your\n     * code.\n     */\n    debug       : true,\n\n    /**\n     * This option suppresses warnings about the use of assignments in cases\n     * where comparisons are expected. More often than not, code like `if (a =\n     * 10) {}` is a typo. However, it can be useful in cases like this one:\n     *\n     *     for (var i = 0, person; person = people[i]; i++) {}\n     *\n     * You can silence this error on a per-use basis by surrounding the assignment\n     * with parenthesis, such as:\n     *\n     *     for (var i = 0, person; (person = people[i]); i++) {}\n     */\n    boss        : true,\n\n    /**\n     * This option suppresses warnings about the use of `eval`. The use of\n     * `eval` is discouraged because it can make your code vulnerable to\n     * various injection attacks and it makes it hard for JavaScript\n     * interpreter to do certain optimizations.\n    */\n    evil        : true,\n\n    /**\n     * This option suppresses warnings about declaring variables inside\n     * of control structures while accessing them later from the outside.\n     * Even though identifiers declared with `var` have two real scopes—global\n     * and function—such practice leads to confusion among people new to\n     * the language and hard-to-debug bugs. This is why, by default, JSHint\n     * warns about variables that are used outside of their intended scope.\n     *\n     *     function test() {\n     *       if (true) {\n     *         var x = 0;\n     *       }\n     *\n     *       x += 1; // Default: 'x' used out of scope.\n     *                 // No warning when funcscope:true\n     *     }\n     */\n    funcscope   : true,\n\n    /**\n     * This option suppresses warnings about the use of global strict mode.\n     * Global strict mode can break third-party widgets so it is not\n     * recommended.\n     *\n     * For more info about strict mode see the `strict` option.\n     *\n     * @deprecated Use `strict: \"global\"`.\n     */\n    globalstrict: true,\n\n    /**\n     * This option suppresses warnings about the `__iterator__` property. This\n     * property is not supported by all browsers so use it carefully.\n     */\n    iterator    : true,\n\n     /**\n     * This option suppresses warnings about invalid `typeof` operator values.\n     * This operator has only [a limited set of possible return\n     * values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof).\n     * By default, JSHint warns when you compare its result with an invalid\n     * value which often can be a typo.\n     *\n     *     // 'fuction' instead of 'function'\n     *     if (typeof a == \"fuction\") { // Invalid typeof value 'fuction'\n     *       // ...\n     *     }\n     *\n     * Do not use this option unless you're absolutely sure you don't want\n     * these checks.\n     */\n    notypeof    : true,\n\n    /**\n     * This option prohibits the use of unary increment and decrement\n     * operators.  Some people think that `++` and `--` reduces the quality of\n     * their coding styles and there are programming languages—such as\n     * Python—that go completely without these operators.\n     */\n    plusplus    : true,\n\n    /**\n     * This option suppresses warnings about the `__proto__` property.\n     */\n    proto       : true,\n\n    /**\n     * This option suppresses warnings about the use of script-targeted\n     * URLs—such as `javascript:...`.\n     */\n    scripturl   : true,\n\n    /**\n     * This option suppresses warnings about using `[]` notation when it can be\n     * expressed in dot notation: `person['name']` vs. `person.name`.\n     *\n     * @deprecated JSHint is limiting its scope to issues of code correctness.\n     *             If you would like to enforce rules relating to code style,\n     *             check out [the JSCS\n     *             project](https://github.com/jscs-dev/node-jscs).\n     */\n    sub         : true,\n\n    /**\n     * This option suppresses warnings about \"weird\" constructions like\n     * `new function () { ... }` and `new Object;`. Such constructions are\n     * sometimes used to produce singletons in JavaScript:\n     *\n     *     var singleton = new function() {\n     *       var privateVar;\n     *\n     *       this.publicMethod  = function () {}\n     *       this.publicMethod2 = function () {}\n     *     };\n     */\n    supernew    : true,\n\n    /**\n     * This option suppresses most of the warnings about possibly unsafe line\n     * breakings in your code. It doesn't suppress warnings about comma-first\n     * coding style. To suppress those you have to use `laxcomma` (see below).\n     *\n     * @deprecated JSHint is limiting its scope to issues of code correctness.\n     *             If you would like to enforce rules relating to code style,\n     *             check out [the JSCS\n     *             project](https://github.com/jscs-dev/node-jscs).\n     */\n    laxbreak    : true,\n\n    /**\n     * This option suppresses warnings about comma-first coding style:\n     *\n     *     var obj = {\n     *         name: 'Anton'\n     *       , handle: 'valueof'\n     *       , role: 'SW Engineer'\n     *     };\n     *\n     * @deprecated JSHint is limiting its scope to issues of code correctness.\n     *             If you would like to enforce rules relating to code style,\n     *             check out [the JSCS\n     *             project](https://github.com/jscs-dev/node-jscs).\n     */\n    laxcomma    : true,\n\n    /**\n     * This option suppresses warnings about possible strict violations when\n     * the code is running in strict mode and you use `this` in a\n     * non-constructor function. You should use this option—in a function scope\n     * only—when you are positive that your use of `this` is valid in the\n     * strict mode (for example, if you call your function using\n     * `Function.call`).\n     *\n     * **Note:** This option can be used only inside of a function scope.\n     * JSHint will fail with an error if you will try to set this option\n     * globally.\n     */\n    validthis   : true,\n\n    /**\n     * This option suppresses warnings about the use of the `with` statement.\n     * The semantics of the `with` statement can cause confusion among\n     * developers and accidental definition of global variables.\n     *\n     * More info:\n     *\n     * * [with Statement Considered\n     *   Harmful](http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/)\n     */\n    withstmt    : true,\n\n    /**\n     * This options tells JSHint that your code uses Mozilla JavaScript\n     * extensions. Unless you develop specifically for the Firefox web browser\n     * you don't need this option.\n     *\n     * More info:\n     *\n     * * [New in JavaScript\n     *   1.7](https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7)\n     */\n    moz         : true,\n\n    /**\n     * This option suppresses warnings about generator functions with no\n     * `yield` statement in them.\n     */\n    noyield     : true,\n\n    /**\n     * This option suppresses warnings about `== null` comparisons. Such\n     * comparisons are often useful when you want to check if a variable is\n     * `null` or `undefined`.\n     */\n    eqnull      : true,\n\n    /**\n     * This option suppresses warnings about missing semicolons, but only when\n     * the semicolon is omitted for the last statement in a one-line block:\n     *\n     *     var name = (function() { return 'Anton' }());\n     *\n     * This is a very niche use case that is useful only when you use automatic\n     * JavaScript code generators.\n     */\n    lastsemic   : true,\n\n    /**\n     * This option suppresses warnings about functions inside of loops.\n     * Defining functions inside of loops can lead to bugs such as this one:\n     *\n     *     var nums = [];\n     *\n     *     for (var i = 0; i < 10; i++) {\n     *       nums[i] = function (j) {\n     *         return i + j;\n     *       };\n     *     }\n     *\n     *     nums[0](2); // Prints 12 instead of 2\n     *\n     * To fix the code above you need to copy the value of `i`:\n     *\n     *     var nums = [];\n     *\n     *     for (var i = 0; i < 10; i++) {\n     *       (function (i) {\n     *         nums[i] = function (j) {\n     *             return i + j;\n     *         };\n     *       }(i));\n     *     }\n     */\n    loopfunc    : true,\n\n    /**\n     * This option suppresses warnings about the use of expressions where\n     * normally you would expect to see assignments or function calls. Most of\n     * the time, such code is a typo. However, it is not forbidden by the spec\n     * and that's why this warning is optional.\n     */\n    expr        : true,\n\n    /**\n     * This option tells JSHint that your code uses ECMAScript 6 specific\n     * syntax. Note that not all browsers implement these features.\n     *\n     * More info:\n     *\n     * * [Specification for ECMAScript\n     *   6](http://www.ecma-international.org/ecma-262/6.0/index.html)\n     *\n     * @deprecated Use `esversion: 6` instead.\n     */\n    esnext      : true,\n\n    /**\n     * This option tells JSHint that your code uses ES3 array elision elements,\n     * or empty elements (for example, `[1, , , 4, , , 7]`).\n     */\n    elision     : true,\n  },\n\n  // Third party globals\n  environments: {\n\n    /**\n     * This option defines globals exposed by the\n     * [MooTools](http://mootools.net/) JavaScript framework.\n     */\n    mootools    : true,\n\n    /**\n     * This option defines globals exposed by\n     * [CouchDB](http://couchdb.apache.org/). CouchDB is a document-oriented\n     * database that can be queried and indexed in a MapReduce fashion using\n     * JavaScript.\n     */\n    couch       : true,\n\n    /**\n     * This option defines globals exposed by [the Jasmine unit testing\n     * framework](https://jasmine.github.io/).\n     */\n    jasmine     : true,\n\n    /**\n     * This option defines globals exposed by the [jQuery](http://jquery.com/)\n     * JavaScript library.\n     */\n    jquery      : true,\n\n    /**\n     * This option defines globals available when your code is running inside\n     * of the Node runtime environment. [Node.js](http://nodejs.org/) is a\n     * server-side JavaScript environment that uses an asynchronous\n     * event-driven model. This option also skips some warnings that make sense\n     * in the browser environments but don't make sense in Node such as\n     * file-level `use strict` pragmas and `console.log` statements.\n     */\n    node        : true,\n\n    /**\n     * This option defines globals exposed by [the QUnit unit testing\n     * framework](http://qunitjs.com/).\n     */\n    qunit       : true,\n\n    /**\n     * This option defines globals available when your code is running inside\n     * of the Rhino runtime environment. [Rhino](http://www.mozilla.org/rhino/)\n     * is an open-source implementation of JavaScript written entirely in Java.\n     */\n    rhino       : true,\n\n    /**\n     * This option defines globals exposed by [the ShellJS\n     * library](http://documentup.com/arturadib/shelljs).\n     */\n    shelljs     : true,\n\n    /**\n     * This option defines globals exposed by the\n     * [Prototype](http://www.prototypejs.org/) JavaScript framework.\n     */\n    prototypejs : true,\n\n    /**\n     * This option defines globals exposed by the [YUI](http://yuilibrary.com/)\n     * JavaScript framework.\n     */\n    yui         : true,\n\n    /**\n     * This option defines globals exposed by the \"BDD\" and \"TDD\" UIs of the\n     * [Mocha unit testing framework](http://mochajs.org/).\n     */\n    mocha       : true,\n\n    /**\n     * This option informs JSHint that the input code describes an ECMAScript 6\n     * module. All module code is interpreted as strict mode code.\n     */\n    module      : true,\n\n    /**\n     * This option defines globals available when your code is running as a\n     * script for the [Windows Script\n     * Host](http://en.wikipedia.org/wiki/Windows_Script_Host).\n     */\n    wsh         : true,\n\n    /**\n     * This option defines globals available when your code is running inside\n     * of a Web Worker. [Web\n     * Workers](https://developer.mozilla.org/en/Using_web_workers) provide a\n     * simple means for web content to run scripts in background threads.\n     */\n    worker      : true,\n\n    /**\n     * This option defines non-standard but widely adopted globals such as\n     * `escape` and `unescape`.\n     */\n    nonstandard : true,\n\n    /**\n     * This option defines globals exposed by modern browsers: all the way from\n     * good old `document` and `navigator` to the HTML5 `FileReader` and other\n     * new developments in the browser world.\n     *\n     * **Note:** This option doesn't expose variables like `alert` or\n     * `console`. See option `devel` for more information.\n     */\n    browser     : true,\n\n    /**\n     * This option defines globals available when using [the Browserify\n     * tool](http://browserify.org/) to build a project.\n     */\n    browserify  : true,\n\n    /**\n     * This option defines globals that are usually used for logging poor-man's\n     * debugging: `console`, `alert`, etc. It is usually a good idea to not\n     * ship them in production because, for example, `console.log` breaks in\n     * legacy versions of Internet Explorer.\n     */\n    devel       : true,\n\n    /**\n     * This option defines globals exposed by the [Dojo\n     * Toolkit](http://dojotoolkit.org/).\n     */\n    dojo        : true,\n\n    /**\n     * This option defines globals for typed array constructors.\n     *\n     * More info:\n     *\n     * * [JavaScript typed\n     *   arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)\n     */\n    typed       : true,\n\n    /**\n     * This option defines globals available when your core is running inside\n     * of the PhantomJS runtime environment. [PhantomJS](http://phantomjs.org/)\n     * is a headless WebKit scriptable with a JavaScript API. It has fast and\n     * native support for various web standards: DOM handling, CSS selector,\n     * JSON, Canvas, and SVG.\n     */\n    phantom     : true\n  },\n\n  // Obsolete options\n  obsolete: {\n    onecase     : true, // if one case switch statements should be allowed\n    regexp      : true, // if the . should not be allowed in regexp literals\n    regexdash   : true  // if unescaped first/last dash (-) inside brackets\n                        // should be tolerated\n  }\n};\n\n// These are the JSHint options that can take any value\n// (we use this object to detect invalid options)\nexports.val = {\n\n  /**\n   * This option lets you set the maximum length of a line.\n   *\n   * @deprecated JSHint is limiting its scope to issues of code correctness. If\n   *             you would like to enforce rules relating to code style, check\n   *             out [the JSCS project](https://github.com/jscs-dev/node-jscs).\n   */\n  maxlen       : false,\n\n  /**\n   * This option sets a specific tab width for your code.\n   *\n   * @deprecated JSHint is limiting its scope to issues of code correctness. If\n   *             you would like to enforce rules relating to code style, check\n   *             out [the JSCS project](https://github.com/jscs-dev/node-jscs).\n   */\n  indent       : false,\n\n  /**\n   * This options allows you to set the maximum amount of warnings JSHint will\n   * produce before giving up. Default is 50.\n   */\n  maxerr       : false,\n\n  /**\n   * This option allows you to control which variables JSHint considers to be\n   * implicitly defined in the environment. Configure it with an array of\n   * string values. Prefixing a variable name with a hyphen (-) character will\n   * remove that name from the collection of predefined variables.\n   *\n   * JSHint will consider variables declared in this way to be read-only.\n   *\n   * This option cannot be specified in-line; it may only be used via the\n   * JavaScript API or from an external configuration file.\n   */\n  predef       : false,\n\n  /**\n   * This option can be used to specify a white list of global variables that\n   * are not formally defined in the source code. This is most useful when\n   * combined with the `undef` option in order to suppress warnings for\n   * project-specific global variables.\n   *\n   * Setting an entry to `true` enables reading and writing to that variable.\n   * Setting it to `false` will trigger JSHint to consider that variable\n   * read-only.\n   *\n   * See also the \"environment\" options: a set of options to be used as short\n   * hand for enabling global variables defined in common JavaScript\n   * environments.\n   *\n   * To configure `globals` within an individual file, see [Inline\n   * Configuration](http://jshint.com/docs/#inline-configuration).\n   */\n  globals      : false,\n\n  /**\n   * This option enforces the consistency of quotation marks used throughout\n   * your code. It accepts three values: `true` if you don't want to enforce\n   * one particular style but want some consistency, `\"single\"` if you want to\n   * allow only single quotes and `\"double\"` if you want to allow only double\n   * quotes.\n   *\n   * @deprecated JSHint is limiting its scope to issues of code correctness. If\n   *             you would like to enforce rules relating to code style, check\n   *             out [the JSCS project](https://github.com/jscs-dev/node-jscs).\n   */\n  quotmark     : false,\n\n  scope        : false,\n\n  /**\n   * This option lets you set the max number of statements allowed per function:\n   *\n   *     // jshint maxstatements:4\n   *\n   *     function main() {\n   *       var i = 0;\n   *       var j = 0;\n   *\n   *       // Function declarations count as one statement. Their bodies\n   *       // don't get taken into account for the outer function.\n   *       function inner() {\n   *         var i2 = 1;\n   *         var j2 = 1;\n   *\n   *         return i2 + j2;\n   *       }\n   *\n   *       j = i + j;\n   *       return j; // JSHint: Too many statements per function. (5)\n   *     }\n   */\n  maxstatements: false,\n\n  /**\n   * This option lets you control how nested do you want your blocks to be:\n   *\n   *     // jshint maxdepth:2\n   *\n   *     function main(meaning) {\n   *       var day = true;\n   *\n   *       if (meaning === 42) {\n   *         while (day) {\n   *           shuffle();\n   *\n   *           if (tired) { // JSHint: Blocks are nested too deeply (3).\n   *               sleep();\n   *           }\n   *         }\n   *       }\n   *     }\n   */\n  maxdepth     : false,\n\n  /**\n   * This option lets you set the max number of formal parameters allowed per\n   * function:\n   *\n   *     // jshint maxparams:3\n   *\n   *     function login(request, onSuccess) {\n   *       // ...\n   *     }\n   *\n   *     // JSHint: Too many parameters per function (4).\n   *     function logout(request, isManual, whereAmI, onSuccess) {\n   *       // ...\n   *     }\n   */\n  maxparams    : false,\n\n  /**\n   * This option lets you control cyclomatic complexity throughout your code.\n   * Cyclomatic complexity measures the number of linearly independent paths\n   * through a program's source code. Read more about [cyclomatic complexity on\n   * Wikipedia](http://en.wikipedia.org/wiki/Cyclomatic_complexity).\n   */\n  maxcomplexity: false,\n\n  /**\n   * This option suppresses warnings about variable shadowing i.e. declaring a\n   * variable that had been already declared somewhere in the outer scope.\n   *\n   * - \"inner\"  - check for variables defined in the same scope only\n   * - \"outer\"  - check for variables defined in outer scopes as well\n   * - false    - same as inner\n   * - true     - allow variable shadowing\n   */\n  shadow       : false,\n\n  /**\n   * This option requires the code to run in ECMAScript 5's strict mode.\n   * [Strict mode](https://developer.mozilla.org/en/JavaScript/Strict_mode)\n   * is a way to opt in to a restricted variant of JavaScript. Strict mode\n   * eliminates some JavaScript pitfalls that didn't cause errors by changing\n   * them to produce errors.  It also fixes mistakes that made it difficult\n   * for the JavaScript engines to perform certain optimizations.\n   *\n   * - \"global\"  - there must be a `\"use strict\";` directive at global level\n   * - \"implied\" - lint the code as if there is the `\"use strict\";` directive\n   * - false     - disable warnings about strict mode\n   * - true      - there must be a `\"use strict\";` directive at function level;\n   *               this is preferable for scripts intended to be loaded in web\n   *               browsers directly because enabling strict mode globally\n   *               could adversely effect other scripts running on the same\n   *               page\n   */\n  strict      : true,\n\n  /**\n   * This option warns when you define and never use your variables. It is very\n   * useful for general code cleanup, especially when used in addition to\n   * `undef`.\n   *\n   *     // jshint unused:true\n   *\n   *     function test(a, b) {\n   *       var c, d = 2;\n   *\n   *       return a + d;\n   *     }\n   *\n   *     test(1, 2);\n   *\n   *     // Line 3: 'b' was defined but never used.\n   *     // Line 4: 'c' was defined but never used.\n   *\n   * In addition to that, this option will warn you about unused global\n   * variables declared via the `global` directive.\n   *\n   * When set to `true`, unused parameters that are followed by a used\n   * parameter will not produce warnings. This option can be set to `vars` to\n   * only check for variables, not function parameters, or `strict` to check\n   * all variables and parameters.\n   */\n  unused       : true,\n\n  /**\n   * This option prohibits the use of a variable before it was defined.\n   * JavaScript has function scope only and, in addition to that, all variables\n   * are always moved—or hoisted— to the top of the function. This behavior can\n   * lead to some very nasty bugs and that's why it is safer to always use\n   * variable only after they have been explicitly defined.\n   *\n   * Setting this option to \"nofunc\" will allow function declarations to be\n   * ignored.\n   *\n   * For more in-depth understanding of scoping and hoisting in JavaScript,\n   * read [JavaScript Scoping and\n   * Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting)\n   * by Ben Cherry.\n   */\n  latedef      : false,\n\n  ignore       : false, // start/end ignoring lines of code, bypassing the lexer\n                        //   start    - start ignoring lines, including the current line\n                        //   end      - stop ignoring lines, starting on the next line\n                        //   line     - ignore warnings / errors for just a single line\n                        //              (this option does not bypass the lexer)\n\n  ignoreDelimiters: false, // array of start/end delimiters used to ignore\n                           // certain chunks from code\n\n  /**\n   * This option is used to specify the ECMAScript version to which the code\n   * must adhere. It can assume one of the following values:\n   *  - `3` - If you need your program to be executable\n   *    in older browsers—such as Internet Explorer 6/7/8/9—and other legacy\n   *    JavaScript environments\n   *  - `5` - To enable syntax first defined in [the ECMAScript 5.1\n   *    specification](http://www.ecma-international.org/ecma-262/5.1/index.html).\n   *    This includes allowing reserved keywords as object properties.\n   *  - `6` - To tell JSHint that your code uses [ECMAScript\n   *    6](http://www.ecma-international.org/ecma-262/6.0/index.html) specific\n   *    syntax. Note that not all browsers implement them.\n   */\n  esversion: 5\n};\n\n// These are JSHint boolean options which are shared with JSLint\n// where the definition in JSHint is opposite JSLint\nexports.inverted = {\n  bitwise : true,\n  forin   : true,\n  newcap  : true,\n  plusplus: true,\n  regexp  : true,\n  undef   : true,\n\n  // Inverted and renamed, use JSHint name here\n  eqeqeq  : true,\n  strict  : true\n};\n\nexports.validNames = Object.keys(exports.val)\n  .concat(Object.keys(exports.bool.relaxing))\n  .concat(Object.keys(exports.bool.enforcing))\n  .concat(Object.keys(exports.bool.obsolete))\n  .concat(Object.keys(exports.bool.environments));\n\n// These are JSHint boolean options which are shared with JSLint\n// where the name has been changed but the effect is unchanged\nexports.renamed = {\n  eqeq   : \"eqeqeq\",\n  windows: \"wsh\",\n  sloppy : \"strict\"\n};\n\nexports.removed = {\n  nomen: true,\n  onevar: true,\n  passfail: true,\n  white: true,\n  gcl: true,\n  smarttabs: true,\n  trailing: true\n};\n\n// Add options here which should not be automatically enforced by\n// `enforceall`.\nexports.noenforceall = {\n  varstmt: true,\n  strict: true\n};\n\n},{}],18:[function(require,module,exports){\n/*\n * Regular expressions. Some of these are stupidly long.\n */\n\n/*jshint maxlen:1000 */\n\n\"use strict\";\n\n// Unsafe comment or string (ax)\nexports.unsafeString =\n  /@cc|<\\/?|script|\\]\\s*\\]|<\\s*!|&lt/i;\n\n// Characters in strings that need escaping (nx and nxg)\nexports.needEsc =\n  /[\\u0000-\\u001f&<\"\\/\\\\\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/;\n\nexports.needEscGlobal =\n  /[\\u0000-\\u001f&<\"\\/\\\\\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g;\n\n// Star slash (lx)\nexports.starSlash = /\\*\\//;\n\n// Identifier (ix)\nexports.identifier = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/;\n\n// JavaScript URL (jx)\nexports.javascriptURL = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;\n\n// Catches /* falls through */ comments (ft)\nexports.fallsThrough = /^\\s*falls?\\sthrough\\s*$/;\n\n// very conservative rule (eg: only one space between the start of the comment and the first character)\n// to relax the maxlen option\nexports.maxlenException = /^(?:(?:\\/\\/|\\/\\*|\\*) ?)?[^ ]+$/;\n\n// Node.js releases prior to version 8 include a version of the V8 engine which\n// incorrectly interprets the character class escape `\\s`. The following\n// regular expression may be replaced with `/\\s/` when JSHint removes support\n// for Node.js versions prior to 8.\n// Source:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\nexports.whitespace = /[ \\f\\n\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]/;\n\n},{}],19:[function(require,module,exports){\n\"use strict\";\n\nvar _      = require(\"lodash\");\nvar events = require(\"events\");\n\n// Used to denote membership in lookup tables (a primitive value such as `true`\n// would be silently rejected for the property name \"__proto__\" in some\n// environments)\nvar marker = {};\n\n/**\n * Creates a scope manager that handles variables and labels, storing usages\n * and resolving when variables are used and undefined\n */\nvar scopeManager = function(state, predefined, exported, declared) {\n\n  var _current;\n  var _scopeStack = [];\n\n  function _newScope(type) {\n    _current = {\n      \"(labels)\": Object.create(null),\n      \"(usages)\": Object.create(null),\n      \"(breakLabels)\": Object.create(null),\n      \"(parent)\": _current,\n      \"(type)\": type,\n      \"(params)\": (type === \"functionparams\" || type === \"catchparams\") ? [] : null\n    };\n    _scopeStack.push(_current);\n  }\n\n  _newScope(\"global\");\n  _current[\"(predefined)\"] = predefined;\n\n  var _currentFunctBody = _current; // this is the block after the params = function\n\n  var usedPredefinedAndGlobals = Object.create(null);\n  var impliedGlobals = Object.create(null);\n  var unuseds = [];\n  var emitter = new events.EventEmitter();\n\n  function warning(code, token) {\n    emitter.emit(\"warning\", {\n      code: code,\n      token: token,\n      data: _.slice(arguments, 2)\n    });\n  }\n\n  function error(code, token) {\n    emitter.emit(\"warning\", {\n      code: code,\n      token: token,\n      data: _.slice(arguments, 2)\n    });\n  }\n\n  function _setupUsages(labelName) {\n    if (!_current[\"(usages)\"][labelName]) {\n      _current[\"(usages)\"][labelName] = {\n        \"(modified)\": [],\n        \"(reassigned)\": [],\n        \"(tokens)\": []\n      };\n    }\n  }\n\n  var _getUnusedOption = function(unused_opt) {\n    if (unused_opt === undefined) {\n      unused_opt = state.option.unused;\n    }\n\n    if (unused_opt === true) {\n      unused_opt = \"last-param\";\n    }\n\n    return unused_opt;\n  };\n\n  var _warnUnused = function(name, tkn, type, unused_opt) {\n    var line = tkn.line;\n    var chr  = tkn.from;\n    var raw_name = tkn.raw_text || name;\n\n    unused_opt = _getUnusedOption(unused_opt);\n\n    var warnable_types = {\n      \"vars\": [\"var\"],\n      \"last-param\": [\"var\", \"param\"],\n      \"strict\": [\"var\", \"param\", \"last-param\"]\n    };\n\n    if (unused_opt) {\n      if (warnable_types[unused_opt] && warnable_types[unused_opt].indexOf(type) !== -1) {\n        warning(\"W098\", { line: line, from: chr }, raw_name);\n      }\n    }\n\n    // inconsistent - see gh-1894\n    if (unused_opt || type === \"var\") {\n      unuseds.push({\n        name: name,\n        line: line,\n        character: chr\n      });\n    }\n  };\n\n  /**\n   * Checks the current scope for unused identifiers\n   */\n  function _checkForUnused() {\n    // function params are handled specially\n    // assume that parameters are the only thing declared in the param scope\n    if (_current[\"(type)\"] === \"functionparams\") {\n      _checkParams();\n      return;\n    }\n    var curentLabels = _current[\"(labels)\"];\n    for (var labelName in curentLabels) {\n      if (curentLabels[labelName][\"(type)\"] !== \"exception\" &&\n        curentLabels[labelName][\"(unused)\"]) {\n        _warnUnused(labelName, curentLabels[labelName][\"(token)\"], \"var\");\n      }\n    }\n  }\n\n  /**\n   * Checks the current scope for unused parameters\n   * Must be called in a function parameter scope\n   */\n  function _checkParams() {\n    var params = _current[\"(params)\"];\n\n    if (!params) {\n      return;\n    }\n\n    var param = params.pop();\n    var unused_opt;\n\n    while (param) {\n      var label = _current[\"(labels)\"][param];\n\n      unused_opt = _getUnusedOption(state.funct[\"(unusedOption)\"]);\n\n      // 'undefined' is a special case for (function(window, undefined) { ... })();\n      // patterns.\n      if (param === \"undefined\")\n        return;\n\n      if (label[\"(unused)\"]) {\n        _warnUnused(param, label[\"(token)\"], \"param\", state.funct[\"(unusedOption)\"]);\n      } else if (unused_opt === \"last-param\") {\n        return;\n      }\n\n      param = params.pop();\n    }\n  }\n\n  /**\n   * Finds the relevant label's scope, searching from nearest outwards\n   * @returns {Object} the scope the label was found in\n   */\n  function _getLabel(labelName) {\n    for (var i = _scopeStack.length - 1 ; i >= 0; --i) {\n      var scopeLabels = _scopeStack[i][\"(labels)\"];\n      if (scopeLabels[labelName]) {\n        return scopeLabels;\n      }\n    }\n  }\n\n  function usedSoFarInCurrentFunction(labelName) {\n    // used so far in this whole function and any sub functions\n    for (var i = _scopeStack.length - 1; i >= 0; i--) {\n      var current = _scopeStack[i];\n      if (current[\"(usages)\"][labelName]) {\n        return current[\"(usages)\"][labelName];\n      }\n      if (current === _currentFunctBody) {\n        break;\n      }\n    }\n    return false;\n  }\n\n  function _checkOuterShadow(labelName, token) {\n\n    // only check if shadow is outer\n    if (state.option.shadow !== \"outer\") {\n      return;\n    }\n\n    var isGlobal = _currentFunctBody[\"(type)\"] === \"global\",\n      isNewFunction = _current[\"(type)\"] === \"functionparams\";\n\n    var outsideCurrentFunction = !isGlobal;\n    for (var i = 0; i < _scopeStack.length; i++) {\n      var stackItem = _scopeStack[i];\n\n      if (!isNewFunction && _scopeStack[i + 1] === _currentFunctBody) {\n        outsideCurrentFunction = false;\n      }\n      if (outsideCurrentFunction && stackItem[\"(labels)\"][labelName]) {\n        warning(\"W123\", token, labelName);\n      }\n      if (stackItem[\"(breakLabels)\"][labelName]) {\n        warning(\"W123\", token, labelName);\n      }\n    }\n  }\n\n  function _latedefWarning(type, labelName, token) {\n    var isFunction;\n\n    if (state.option.latedef) {\n      isFunction = type === \"function\" || type === \"generator function\";\n\n      // if either latedef is strict and this is a function\n      //    or this is not a function\n      if ((state.option.latedef === true && isFunction) || !isFunction) {\n        warning(\"W003\", token, labelName);\n      }\n    }\n  }\n\n  var scopeManagerInst = {\n\n    on: function(names, listener) {\n      names.split(\" \").forEach(function(name) {\n        emitter.on(name, listener);\n      });\n    },\n\n    isPredefined: function(labelName) {\n      return !this.has(labelName) && _.has(_scopeStack[0][\"(predefined)\"], labelName);\n    },\n\n    /**\n     * Tell the manager we are entering a new block of code\n     * @param {string} [type] - The type of the block. Valid values are\n     *                          \"functionparams\", \"catchparams\" and\n     *                          \"functionouter\"\n     */\n    stack: function(type) {\n      var previousScope = _current;\n      _newScope(type);\n\n      if (!type && previousScope[\"(type)\"] === \"functionparams\") {\n\n        _current[\"(isFuncBody)\"] = true;\n        _currentFunctBody = _current;\n      }\n    },\n\n    unstack: function() {\n      // jshint proto: true\n      var subScope = _scopeStack.length > 1 ? _scopeStack[_scopeStack.length - 2] : null;\n      var isUnstackingFunctionBody = _current === _currentFunctBody,\n        isUnstackingFunctionParams = _current[\"(type)\"] === \"functionparams\",\n        isUnstackingFunctionOuter = _current[\"(type)\"] === \"functionouter\";\n\n      var i, j, isImmutable;\n      var currentUsages = _current[\"(usages)\"];\n      var currentLabels = _current[\"(labels)\"];\n      var usedLabelNameList = Object.keys(currentUsages);\n\n      /* istanbul ignore if */\n      if (currentUsages.__proto__ && usedLabelNameList.indexOf(\"__proto__\") === -1) {\n        usedLabelNameList.push(\"__proto__\");\n      }\n\n      for (i = 0; i < usedLabelNameList.length; i++) {\n        var usedLabelName = usedLabelNameList[i];\n\n        var usage = currentUsages[usedLabelName];\n        var usedLabel = currentLabels[usedLabelName];\n        if (usedLabel) {\n          var usedLabelType = usedLabel[\"(type)\"];\n          isImmutable = usedLabelType === \"const\" || usedLabelType === \"import\";\n\n          if (usedLabel[\"(useOutsideOfScope)\"] && !state.option.funcscope) {\n            var usedTokens = usage[\"(tokens)\"];\n            for (j = 0; j < usedTokens.length; j++) {\n              // Keep the consistency of https://github.com/jshint/jshint/issues/2409\n              if (usedLabel[\"(function)\"] === usedTokens[j][\"(function)\"]) {\n                error(\"W038\", usedTokens[j], usedLabelName);\n              }\n            }\n          }\n\n          // mark the label used\n          _current[\"(labels)\"][usedLabelName][\"(unused)\"] = false;\n\n          // check for modifying a const\n          if (isImmutable && usage[\"(modified)\"]) {\n            for (j = 0; j < usage[\"(modified)\"].length; j++) {\n              error(\"E013\", usage[\"(modified)\"][j], usedLabelName);\n            }\n          }\n\n          // check for re-assigning a function declaration\n          if ((usedLabelType === \"function\" || usedLabelType === \"generator function\" ||\n            usedLabelType === \"class\") && usage[\"(reassigned)\"]) {\n            for (j = 0; j < usage[\"(reassigned)\"].length; j++) {\n              if (!usage[\"(reassigned)\"][j].ignoreW021) {\n                warning(\"W021\", usage[\"(reassigned)\"][j], usedLabelName, usedLabelType);\n              }\n            }\n          }\n          continue;\n        }\n\n        if (subScope) {\n          var labelType = this.labeltype(usedLabelName);\n          isImmutable = labelType === \"const\" ||\n            (labelType === null && _scopeStack[0][\"(predefined)\"][usedLabelName] === false);\n          if (isUnstackingFunctionOuter && !isImmutable) {\n            if (!state.funct[\"(outerMutables)\"]) {\n              state.funct[\"(outerMutables)\"] = [];\n            }\n            state.funct[\"(outerMutables)\"].push(usedLabelName);\n          }\n\n          // not exiting the global scope, so copy the usage down in case its an out of scope usage\n          if (!subScope[\"(usages)\"][usedLabelName]) {\n            subScope[\"(usages)\"][usedLabelName] = usage;\n            if (isUnstackingFunctionBody) {\n              subScope[\"(usages)\"][usedLabelName][\"(onlyUsedSubFunction)\"] = true;\n            }\n          } else {\n            var subScopeUsage = subScope[\"(usages)\"][usedLabelName];\n            subScopeUsage[\"(modified)\"] = subScopeUsage[\"(modified)\"].concat(usage[\"(modified)\"]);\n            subScopeUsage[\"(tokens)\"] = subScopeUsage[\"(tokens)\"].concat(usage[\"(tokens)\"]);\n            subScopeUsage[\"(reassigned)\"] =\n              subScopeUsage[\"(reassigned)\"].concat(usage[\"(reassigned)\"]);\n          }\n        } else {\n          // this is exiting global scope, so we finalise everything here - we are at the end of the file\n          if (typeof _current[\"(predefined)\"][usedLabelName] === \"boolean\") {\n\n            // remove the declared token, so we know it is used\n            delete declared[usedLabelName];\n\n            // note it as used so it can be reported\n            usedPredefinedAndGlobals[usedLabelName] = marker;\n\n            // check for re-assigning a read-only (set to false) predefined\n            if (_current[\"(predefined)\"][usedLabelName] === false && usage[\"(reassigned)\"]) {\n              for (j = 0; j < usage[\"(reassigned)\"].length; j++) {\n                if (!usage[\"(reassigned)\"][j].ignoreW020) {\n                  warning(\"W020\", usage[\"(reassigned)\"][j]);\n                }\n              }\n            }\n          }\n          else {\n            // label usage is not predefined and we have not found a declaration\n            // so report as undeclared\n            for (j = 0; j < usage[\"(tokens)\"].length; j++) {\n              var undefinedToken = usage[\"(tokens)\"][j];\n              // if its not a forgiven undefined (e.g. typof x)\n              if (!undefinedToken.forgiveUndef) {\n                // if undef is on and undef was on when the token was defined\n                if (state.option.undef && !undefinedToken.ignoreUndef) {\n                  warning(\"W117\", undefinedToken, usedLabelName);\n                }\n                if (impliedGlobals[usedLabelName]) {\n                  impliedGlobals[usedLabelName].line.push(undefinedToken.line);\n                } else {\n                  impliedGlobals[usedLabelName] = {\n                    name: usedLabelName,\n                    line: [undefinedToken.line]\n                  };\n                }\n              }\n            }\n          }\n        }\n      }\n\n      // if exiting the global scope, we can warn about declared globals that haven't been used yet\n      if (!subScope) {\n        Object.keys(declared)\n          .forEach(function(labelNotUsed) {\n            _warnUnused(labelNotUsed, declared[labelNotUsed], \"var\");\n          });\n      }\n\n      // If this is not a function boundary, transfer function-scoped labels to\n      // the parent block (a rough simulation of variable hoisting). Previously\n      // existing labels in the parent block should take precedence so that things and stuff.\n      if (subScope && !isUnstackingFunctionBody &&\n        !isUnstackingFunctionParams && !isUnstackingFunctionOuter) {\n        var labelNames = Object.keys(currentLabels);\n        for (i = 0; i < labelNames.length; i++) {\n\n          var defLabelName = labelNames[i];\n          var defLabel = currentLabels[defLabelName];\n\n          if (!defLabel[\"(blockscoped)\"] && defLabel[\"(type)\"] !== \"exception\") {\n            var shadowed = subScope[\"(labels)\"][defLabelName];\n\n            // Do not overwrite a label if it exists in the parent scope\n            // because it is shared by adjacent blocks. Copy the `unused`\n            // property so that any references found within the current block\n            // are counted toward that higher-level declaration.\n            if (shadowed) {\n              shadowed[\"(unused)\"] &= defLabel[\"(unused)\"];\n\n            // \"Hoist\" the variable to the parent block, decorating the label\n            // so that future references, though technically valid, can be\n            // reported as \"out-of-scope\" in the absence of the `funcscope`\n            // option.\n            } else {\n              defLabel[\"(useOutsideOfScope)\"] =\n                // Do not warn about out-of-scope usages in the global scope\n                _currentFunctBody[\"(type)\"] !== \"global\" &&\n                // When a higher scope contains a binding for the label, the\n                // label is a re-declaration and should not prompt \"used\n                // out-of-scope\" warnings.\n                !this.funct.has(defLabelName, { excludeCurrent: true });\n\n              subScope[\"(labels)\"][defLabelName] = defLabel;\n            }\n\n            delete currentLabels[defLabelName];\n          }\n        }\n      }\n\n      _checkForUnused();\n\n      _scopeStack.pop();\n      if (isUnstackingFunctionBody) {\n        _currentFunctBody = _scopeStack[_.findLastIndex(_scopeStack, function(scope) {\n          // if function or if global (which is at the bottom so it will only return true if we call back)\n          return scope[\"(isFuncBody)\"] || scope[\"(type)\"] === \"global\";\n        })];\n      }\n\n      _current = subScope;\n    },\n\n    /**\n     * Add a param to the current scope\n     * @param {string} labelName\n     * @param {Token} token\n     * @param {string} [type=\"param\"] param type\n     */\n    addParam: function(labelName, token, type) {\n      type = type || \"param\";\n\n      if (type === \"exception\") {\n        // if defined in the current function\n        var previouslyDefinedLabelType = this.funct.labeltype(labelName);\n        if (previouslyDefinedLabelType && previouslyDefinedLabelType !== \"exception\") {\n          // and has not been used yet in the current function scope\n          if (!state.option.node) {\n            warning(\"W002\", state.tokens.next, labelName);\n          }\n        }\n\n        if (state.isStrict() && (labelName === \"arguments\" || labelName === \"eval\")) {\n          warning(\"E008\", token);\n        }\n      }\n\n      // The variable was declared in the current scope\n      if (_.has(_current[\"(labels)\"], labelName)) {\n        _current[\"(labels)\"][labelName].duplicated = true;\n\n      // The variable was declared in an outer scope\n      } else {\n        // if this scope has the variable defined, it's a re-definition error\n        _checkOuterShadow(labelName, token);\n\n        _current[\"(labels)\"][labelName] = {\n          \"(type)\" : type,\n          \"(token)\": token,\n          \"(unused)\": true };\n\n        _current[\"(params)\"].push(labelName);\n      }\n\n      if (_.has(_current[\"(usages)\"], labelName)) {\n        var usage = _current[\"(usages)\"][labelName];\n        // if its in a sub function it is not necessarily an error, just latedef\n        if (usage[\"(onlyUsedSubFunction)\"]) {\n          _latedefWarning(type, labelName, token);\n        } else {\n          // this is a clear illegal usage for block scoped variables\n          warning(\"E056\", token, labelName, type);\n        }\n      }\n    },\n\n    validateParams: function(isArrow) {\n      var isStrict = state.isStrict();\n      var currentFunctParamScope = _currentFunctBody[\"(parent)\"];\n\n      if (!currentFunctParamScope[\"(params)\"]) {\n        return;\n      }\n\n      currentFunctParamScope[\"(params)\"].forEach(function(labelName) {\n        var label = currentFunctParamScope[\"(labels)\"][labelName];\n\n        if (label.duplicated) {\n          if (isStrict || isArrow) {\n            warning(\"E011\", label[\"(token)\"], labelName);\n          } else if (state.option.shadow !== true) {\n            warning(\"W004\", label[\"(token)\"], labelName);\n          }\n        }\n\n        if (isStrict && (labelName === \"arguments\" || labelName === \"eval\")) {\n          warning(\"E008\", label[\"(token)\"]);\n        }\n      });\n    },\n\n    getUsedOrDefinedGlobals: function() {\n      // jshint proto: true\n      var list = Object.keys(usedPredefinedAndGlobals);\n\n      // If `__proto__` is used as a global variable name, its entry in the\n      // lookup table may not be enumerated by `Object.keys` (depending on the\n      // environment).\n      /* istanbul ignore if */\n      if (usedPredefinedAndGlobals.__proto__ === marker &&\n        list.indexOf(\"__proto__\") === -1) {\n        list.push(\"__proto__\");\n      }\n\n      return list;\n    },\n\n    /**\n     * Gets an array of implied globals\n     * @returns {Array.<{ name: string, line: Array.<number>}>}\n     */\n    getImpliedGlobals: function() {\n      // jshint proto: true\n      var values = _.values(impliedGlobals);\n      var hasProto = false;\n\n      // If `__proto__` is an implied global variable, its entry in the lookup\n      // table may not be enumerated by `_.values` (depending on the\n      // environment).\n      if (impliedGlobals.__proto__) {\n        hasProto = values.some(function(value) {\n          return value.name === \"__proto__\";\n        });\n\n        /* istanbul ignore if */\n        if (!hasProto) {\n          values.push(impliedGlobals.__proto__);\n        }\n      }\n\n      return values;\n    },\n\n    /**\n     * Returns a list of unused variables\n     * @returns {Array}\n     */\n    getUnuseds: function() {\n      return unuseds;\n    },\n\n    has: function(labelName) {\n      return Boolean(_getLabel(labelName));\n    },\n\n    labeltype: function(labelName) {\n      // returns a labels type or null if not present\n      var scopeLabels = _getLabel(labelName);\n      if (scopeLabels) {\n        return scopeLabels[labelName][\"(type)\"];\n      }\n      return null;\n    },\n\n    /**\n     * for the exported options, indicating a variable is used outside the file\n     */\n    addExported: function(labelName) {\n      var globalLabels = _scopeStack[0][\"(labels)\"];\n      if (_.has(declared, labelName)) {\n        // remove the declared token, so we know it is used\n        delete declared[labelName];\n      } else if (_.has(globalLabels, labelName)) {\n        globalLabels[labelName][\"(unused)\"] = false;\n      } else {\n        for (var i = 1; i < _scopeStack.length; i++) {\n          var scope = _scopeStack[i];\n          // if `scope.(type)` is not defined, it is a block scope\n          if (!scope[\"(type)\"]) {\n            if (_.has(scope[\"(labels)\"], labelName) &&\n                !scope[\"(labels)\"][labelName][\"(blockscoped)\"]) {\n              scope[\"(labels)\"][labelName][\"(unused)\"] = false;\n              return;\n            }\n          } else {\n            break;\n          }\n        }\n        exported[labelName] = true;\n      }\n    },\n\n    /**\n     * Mark an indentifier as es6 module exported\n     */\n    setExported: function(labelName, token) {\n      this.block.use(labelName, token);\n    },\n\n    initialize: function(labelName) {\n      if (_current[\"(labels)\"][labelName]) {\n        _current[\"(labels)\"][labelName][\"(initialized)\"] = true;\n      }\n    },\n\n    /**\n     * adds an indentifier to the relevant current scope and creates warnings/errors as necessary\n     * @param {string} labelName\n     * @param {Object} opts\n     * @param {String} opts.type - the type of the label e.g. \"param\", \"var\", \"let, \"const\", \"import\", \"function\", \"generator function\"\n     * @param {Token} opts.token - the token pointing at the declaration\n     * @param {boolean} opts.initialized - whether the binding should be created in an \"initialized\" state.\n     */\n    addlabel: function(labelName, opts) {\n\n      var type  = opts.type;\n      var token = opts.token;\n      var isblockscoped = type === \"let\" || type === \"const\" ||\n        type === \"class\" || type === \"import\" || type === \"generator function\";\n      var ishoisted = type === \"function\" || type === \"generator function\" ||\n        type === \"import\";\n      var isexported    = (isblockscoped ? _current : _currentFunctBody)[\"(type)\"] === \"global\" &&\n                          _.has(exported, labelName);\n\n      // outer shadow check (inner is only on non-block scoped)\n      _checkOuterShadow(labelName, token);\n\n      if (state.isStrict() && (labelName === \"arguments\" || labelName === \"eval\")) {\n        warning(\"E008\", token);\n      }\n\n      if (isblockscoped) {\n\n        var declaredInCurrentScope = _current[\"(labels)\"][labelName];\n        // for block scoped variables, params are seen in the current scope as the root function\n        // scope, so check these too.\n        if (!declaredInCurrentScope && _current === _currentFunctBody &&\n          _current[\"(type)\"] !== \"global\") {\n          declaredInCurrentScope = !!_currentFunctBody[\"(parent)\"][\"(labels)\"][labelName];\n        }\n\n        // if its not already defined (which is an error, so ignore) and is used in TDZ\n        if (!declaredInCurrentScope && _current[\"(usages)\"][labelName]) {\n          var usage = _current[\"(usages)\"][labelName];\n          // if its in a sub function it is not necessarily an error, just latedef\n          if (usage[\"(onlyUsedSubFunction)\"] || ishoisted) {\n            _latedefWarning(type, labelName, token);\n          } else if (!ishoisted) {\n            // this is a clear illegal usage for block scoped variables\n            warning(\"E056\", token, labelName, type);\n          }\n        }\n\n        // If this scope has already declared a binding with the same name,\n        // then this represents a redeclaration error if:\n        //\n        // 1. it is a \"hoisted\" block-scoped binding within a block. For\n        //    instance: generator functions may be redeclared in the global\n        //    scope but not within block statements\n        // 2. this is not a \"hoisted\" block-scoped binding\n        if (declaredInCurrentScope &&\n          (!ishoisted || (_current[\"(type)\"] !== \"global\" || type === \"import\"))) {\n          warning(\"E011\", token, labelName);\n        }\n        else if (state.option.shadow === \"outer\") {\n\n          // if shadow is outer, for block scope we want to detect any shadowing within this function\n          if (scopeManagerInst.funct.has(labelName)) {\n            warning(\"W004\", token, labelName);\n          }\n        }\n\n        scopeManagerInst.block.add(\n          labelName, type, token, !isexported, opts.initialized\n        );\n\n      } else {\n\n        var declaredInCurrentFunctionScope = scopeManagerInst.funct.has(labelName);\n\n        // check for late definition, ignore if already declared\n        if (!declaredInCurrentFunctionScope && usedSoFarInCurrentFunction(labelName)) {\n          _latedefWarning(type, labelName, token);\n        }\n\n        // defining with a var or a function when a block scope variable of the same name\n        // is in scope is an error\n        if (scopeManagerInst.funct.has(labelName, { onlyBlockscoped: true })) {\n          warning(\"E011\", token, labelName);\n        } else if (state.option.shadow !== true) {\n          // now since we didn't get any block scope variables, test for var/function\n          // shadowing\n          if (declaredInCurrentFunctionScope && labelName !== \"__proto__\") {\n\n            // see https://github.com/jshint/jshint/issues/2400\n            if (_currentFunctBody[\"(type)\"] !== \"global\") {\n              warning(\"W004\", token, labelName);\n            }\n          }\n        }\n\n        scopeManagerInst.funct.add(labelName, type, token, !isexported);\n\n        if (_currentFunctBody[\"(type)\"] === \"global\" && !state.impliedClosure()) {\n          usedPredefinedAndGlobals[labelName] = marker;\n        }\n      }\n    },\n\n    funct: {\n      /**\n       * Returns the label type given certain options\n       * @param labelName\n       * @param {Object=} options\n       * @param {Boolean=} options.onlyBlockscoped - only include block scoped labels\n       * @param {Boolean=} options.excludeParams - exclude the param scope\n       * @param {Boolean=} options.excludeCurrent - exclude the current scope\n       * @returns {String}\n       */\n      labeltype: function(labelName, options) {\n        var onlyBlockscoped = options && options.onlyBlockscoped;\n        var excludeParams = options && options.excludeParams;\n        var currentScopeIndex = _scopeStack.length - (options && options.excludeCurrent ? 2 : 1);\n        for (var i = currentScopeIndex; i >= 0; i--) {\n          var current = _scopeStack[i];\n          if (current[\"(labels)\"][labelName] &&\n            (!onlyBlockscoped || current[\"(labels)\"][labelName][\"(blockscoped)\"])) {\n            return current[\"(labels)\"][labelName][\"(type)\"];\n          }\n          var scopeCheck = excludeParams ? _scopeStack[ i - 1 ] : current;\n          if (scopeCheck && scopeCheck[\"(type)\"] === \"functionparams\") {\n            return null;\n          }\n        }\n        return null;\n      },\n      /**\n       * Returns if a break label exists in the function scope\n       * @param {string} labelName\n       * @returns {boolean}\n       */\n      hasBreakLabel: function(labelName) {\n        for (var i = _scopeStack.length - 1; i >= 0; i--) {\n          var current = _scopeStack[i];\n\n          if (current[\"(breakLabels)\"][labelName]) {\n            return true;\n          }\n          if (current[\"(type)\"] === \"functionparams\") {\n            return false;\n          }\n        }\n        return false;\n      },\n      /**\n       * Returns if the label is in the current function scope\n       * See scopeManager.funct.labelType for options\n       */\n      has: function(labelName, options) {\n        return Boolean(this.labeltype(labelName, options));\n      },\n\n      /**\n       * Adds a new function scoped variable\n       * see block.add for block scoped\n       */\n      add: function(labelName, type, tok, unused) {\n        _current[\"(labels)\"][labelName] = {\n          \"(type)\" : type,\n          \"(token)\": tok,\n          \"(blockscoped)\": false,\n          \"(function)\": _currentFunctBody,\n          \"(unused)\": unused };\n      }\n    },\n\n    block: {\n\n      /**\n       * is the current block global?\n       * @returns Boolean\n       */\n      isGlobal: function() {\n        return _current[\"(type)\"] === \"global\";\n      },\n\n      use: function(labelName, token) {\n\n        // if resolves to current function params, then do not store usage just resolve\n        // this is because function(a) { var a; a = a; } will resolve to the param, not\n        // to the unset var\n        // first check the param is used\n        var paramScope = _currentFunctBody[\"(parent)\"];\n        if (paramScope && paramScope[\"(labels)\"][labelName] &&\n          paramScope[\"(labels)\"][labelName][\"(type)\"] === \"param\") {\n\n          // then check its not declared by a block scope variable\n          if (!scopeManagerInst.funct.has(labelName,\n                { excludeParams: true, onlyBlockscoped: true })) {\n            paramScope[\"(labels)\"][labelName][\"(unused)\"] = false;\n          }\n        }\n\n        if (token && (state.ignored.W117 || state.option.undef === false)) {\n          token.ignoreUndef = true;\n        }\n\n        _setupUsages(labelName);\n\n        _current[\"(usages)\"][labelName][\"(onlyUsedSubFunction)\"] = false;\n\n        if (token) {\n          token[\"(function)\"] = _currentFunctBody;\n          _current[\"(usages)\"][labelName][\"(tokens)\"].push(token);\n        }\n\n        // blockscoped vars can't be used within their initializer (TDZ)\n        var label = _current[\"(labels)\"][labelName];\n        if (label && label[\"(blockscoped)\"] && !label[\"(initialized)\"]) {\n          error(\"E056\", token, labelName, label[\"(type)\"]);\n        }\n      },\n\n      reassign: function(labelName, token) {\n        token.ignoreW020 = state.ignored.W020;\n        token.ignoreW021 = state.ignored.W021;\n\n        this.modify(labelName, token);\n\n        _current[\"(usages)\"][labelName][\"(reassigned)\"].push(token);\n      },\n\n      modify: function(labelName, token) {\n\n        _setupUsages(labelName);\n\n        _current[\"(usages)\"][labelName][\"(onlyUsedSubFunction)\"] = false;\n        _current[\"(usages)\"][labelName][\"(modified)\"].push(token);\n      },\n\n      /**\n       * Adds a new variable\n       */\n      add: function(labelName, type, tok, unused, initialized) {\n        _current[\"(labels)\"][labelName] = {\n          \"(type)\" : type,\n          \"(token)\": tok,\n          \"(initialized)\": !!initialized,\n          \"(blockscoped)\": true,\n          \"(unused)\": unused };\n      },\n\n      addBreakLabel: function(labelName, opts) {\n        var token = opts.token;\n        if (scopeManagerInst.funct.hasBreakLabel(labelName)) {\n          warning(\"E011\", token, labelName);\n        }\n        else if (state.option.shadow === \"outer\") {\n          if (scopeManagerInst.funct.has(labelName)) {\n            warning(\"W004\", token, labelName);\n          } else {\n            _checkOuterShadow(labelName, token);\n          }\n        }\n        _current[\"(breakLabels)\"][labelName] = token;\n      }\n    }\n  };\n  return scopeManagerInst;\n};\n\nmodule.exports = scopeManager;\n\n},{\"events\":6,\"lodash\":13}],20:[function(require,module,exports){\n\"use strict\";\nvar NameStack = require(\"./name-stack.js\");\n\nvar state = {\n  syntax: {},\n\n  /**\n   * Determine if the code currently being linted is strict mode code.\n   *\n   * @returns {boolean}\n   */\n  isStrict: function() {\n    return this.directive[\"use strict\"] || this.inClassBody ||\n      this.option.module || this.option.strict === \"implied\";\n  },\n\n  /**\n   * Determine if the current state warrants a warning for statements outside\n   * of strict mode code.\n   *\n   * While emitting warnings based on function scope would be more intuitive\n   * (and less noisy), JSHint observes statement-based semantics in order to\n   * preserve legacy behavior.\n   *\n   * This method does not take the state of the parser into account, making no\n   * distinction between global code and function code. Because the \"missing\n   * 'use strict'\" warning is *also* reported at function boundaries, this\n   * function interprets `strict` option values `true` and `undefined` as\n   * equivalent.\n   */\n  stmtMissingStrict: function() {\n    if (this.option.strict === \"global\") {\n      return true;\n    }\n\n    if (this.option.strict === false) {\n      return false;\n    }\n\n    if (this.option.globalstrict) {\n      return true;\n    }\n\n    return false;\n  },\n\n  allowsGlobalUsd: function() {\n    return this.option.strict === \"global\" || this.option.globalstrict ||\n      this.option.module || this.impliedClosure();\n  },\n\n  /**\n   * Determine if the current configuration describes an environment that is\n   * wrapped in an immediately-invoked function expression prior to evaluation.\n   *\n   * @returns {boolean}\n   */\n  impliedClosure: function() {\n    return this.option.node || this.option.phantom || this.option.browserify;\n  },\n\n  // Assumption: chronologically ES3 < ES5 < ES6 < Moz\n\n  inMoz: function() {\n    return this.option.moz;\n  },\n\n  /**\n   * @param {boolean} strict - When `true`, only consider ES6 when in\n   *                           \"esversion: 6\" code.\n   */\n  inES6: function(strict) {\n    if (strict) {\n      return this.esVersion === 6;\n    }\n    return this.option.moz || this.esVersion >= 6;\n  },\n\n  /**\n   * @param {boolean} strict - When `true`, return `true` only when\n   *                           esVersion is exactly 5\n   */\n  inES5: function(strict) {\n    if (strict) {\n      return (!this.esVersion || this.esVersion === 5) && !this.option.moz;\n    }\n    return !this.esVersion || this.esVersion >= 5 || this.option.moz;\n  },\n\n  /**\n   * Determine the current version of the input language by inspecting the\n   * value of all ECMAScript-version-related options. This logic is necessary\n   * to ensure compatibility with deprecated options `es3`, `es5`, and\n   * `esnext`, and it may be drastically simplified when those options are\n   * removed.\n   *\n   * @returns {string|null} - the name of any incompatible option detected,\n   *                          `null` otherwise\n   */\n  inferEsVersion: function() {\n    var badOpt = null;\n\n    if (this.option.esversion) {\n      if (this.option.es3) {\n        badOpt = \"es3\";\n      } else if (this.option.es5) {\n        badOpt = \"es5\";\n      } else if (this.option.esnext) {\n        badOpt = \"esnext\";\n      }\n\n      if (badOpt) {\n        return badOpt;\n      }\n\n      if (this.option.esversion === 2015) {\n        this.esVersion = 6;\n      } else {\n        this.esVersion = this.option.esversion;\n      }\n    } else if (this.option.es3) {\n      this.esVersion = 3;\n    } else if (this.option.esnext) {\n      this.esVersion = 6;\n    }\n\n    return null;\n  },\n\n  reset: function() {\n    this.tokens = {\n      prev: null,\n      next: null,\n      curr: null\n    };\n\n    this.option = {};\n    this.esVersion = 5;\n    this.funct = null;\n    this.ignored = {};\n    this.directive = Object.create(null);\n    this.jsonMode = false;\n    this.lines = [];\n    this.tab = \"\";\n    this.cache = {}; // Node.JS doesn't have Map. Sniff.\n    this.ignoredLines = {};\n    this.forinifcheckneeded = false;\n    this.nameStack = new NameStack();\n    this.inClassBody = false;\n  }\n};\n\nexports.state = state;\n\n},{\"./name-stack.js\":16}],21:[function(require,module,exports){\n\"use strict\";\n\nexports.register = function(linter) {\n  // Check for properties named __proto__. This special property was\n  // deprecated and then re-introduced for ES6.\n\n  linter.on(\"Identifier\", function style_scanProto(data) {\n    if (linter.getOption(\"proto\")) {\n      return;\n    }\n\n    if (data.name === \"__proto__\") {\n      linter.warn(\"W103\", {\n        line: data.line,\n        char: data.char,\n        data: [ data.name, \"6\" ]\n      });\n    }\n  });\n\n  // Check for properties named __iterator__. This is a special property\n  // available only in browsers with JavaScript 1.7 implementation, but\n  // it is deprecated for ES6\n\n  linter.on(\"Identifier\", function style_scanIterator(data) {\n    if (linter.getOption(\"iterator\")) {\n      return;\n    }\n\n    if (data.name === \"__iterator__\") {\n      linter.warn(\"W103\", {\n        line: data.line,\n        char: data.char,\n        data: [ data.name ]\n      });\n    }\n  });\n\n  // Check that all identifiers are using camelCase notation.\n  // Exceptions: names like MY_VAR and _myVar.\n\n  linter.on(\"Identifier\", function style_scanCamelCase(data) {\n    if (!linter.getOption(\"camelcase\")) {\n      return;\n    }\n\n    if (data.name.replace(/^_+|_+$/g, \"\").indexOf(\"_\") > -1 && !data.name.match(/^[A-Z0-9_]*$/)) {\n      linter.warn(\"W106\", {\n        line: data.line,\n        char: data.char,\n        data: [ data.name ]\n      });\n    }\n  });\n\n  // Enforce consistency in style of quoting.\n\n  linter.on(\"String\", function style_scanQuotes(data) {\n    var quotmark = linter.getOption(\"quotmark\");\n    var code;\n\n    if (!quotmark) {\n      return;\n    }\n\n    // If quotmark is set to 'single' warn about all double-quotes.\n\n    if (quotmark === \"single\" && data.quote !== \"'\") {\n      code = \"W109\";\n    }\n\n    // If quotmark is set to 'double' warn about all single-quotes.\n\n    if (quotmark === \"double\" && data.quote !== \"\\\"\") {\n      code = \"W108\";\n    }\n\n    // If quotmark is set to true, remember the first quotation style\n    // and then warn about all others.\n\n    if (quotmark === true) {\n      if (!linter.getCache(\"quotmark\")) {\n        linter.setCache(\"quotmark\", data.quote);\n      }\n\n      if (linter.getCache(\"quotmark\") !== data.quote) {\n        code = \"W110\";\n      }\n    }\n\n    if (code) {\n      linter.warn(code, {\n        line: data.line,\n        char: data.char,\n      });\n    }\n  });\n\n  linter.on(\"Number\", function style_scanNumbers(data) {\n    if (data.value.charAt(0) === \".\") {\n      // Warn about a leading decimal point.\n      linter.warn(\"W008\", {\n        line: data.line,\n        char: data.char,\n        data: [ data.value ]\n      });\n    }\n\n    if (data.value.substr(data.value.length - 1) === \".\") {\n      // Warn about a trailing decimal point.\n      linter.warn(\"W047\", {\n        line: data.line,\n        char: data.char,\n        data: [ data.value ]\n      });\n    }\n\n    if (/^00+/.test(data.value)) {\n      // Multiple leading zeroes.\n      linter.warn(\"W046\", {\n        line: data.line,\n        char: data.char,\n        data: [ data.value ]\n      });\n    }\n  });\n\n  // Warn about script URLs.\n\n  linter.on(\"String\", function style_scanJavaScriptURLs(data) {\n    var re = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;\n\n    if (linter.getOption(\"scripturl\")) {\n      return;\n    }\n\n    if (re.test(data.value)) {\n      linter.warn(\"W107\", {\n        line: data.line,\n        char: data.char\n      });\n    }\n  });\n};\n\n},{}],22:[function(require,module,exports){\n// jshint -W001\n\n\"use strict\";\n\n// Identifiers provided by the ECMAScript standard.\n\nexports.reservedVars = {\n  NaN       : false,\n  undefined : false\n};\n\nexports.ecmaIdentifiers = {\n  3: {\n    Array              : false,\n    Boolean            : false,\n    Date               : false,\n    decodeURI          : false,\n    decodeURIComponent : false,\n    encodeURI          : false,\n    encodeURIComponent : false,\n    Error              : false,\n    \"eval\"             : false,\n    EvalError          : false,\n    Function           : false,\n    hasOwnProperty     : false,\n    Infinity           : false,\n    isFinite           : false,\n    isNaN              : false,\n    Math               : false,\n    Number             : false,\n    Object             : false,\n    parseInt           : false,\n    parseFloat         : false,\n    RangeError         : false,\n    ReferenceError     : false,\n    RegExp             : false,\n    String             : false,\n    SyntaxError        : false,\n    TypeError          : false,\n    URIError           : false\n  },\n  5: {\n    JSON               : false\n  },\n  6: {\n    ArrayBuffer        : false,\n    DataView           : false,\n    Float32Array       : false,\n    Float64Array       : false,\n    Int8Array          : false,\n    Int16Array         : false,\n    Int32Array         : false,\n    Map                : false,\n    Promise            : false,\n    Proxy              : false,\n    Reflect            : false,\n    Set                : false,\n    Symbol             : false,\n    Uint8Array         : false,\n    Uint16Array        : false,\n    Uint32Array        : false,\n    Uint8ClampedArray  : false,\n    WeakMap            : false,\n    WeakSet            : false\n  }\n};\n\n// Global variables commonly provided by a web browser environment.\n\nexports.browser = {\n  Audio                : false,\n  Blob                 : false,\n  addEventListener     : false,\n  applicationCache     : false,\n  atob                 : false,\n  blur                 : false,\n  btoa                 : false,\n  cancelAnimationFrame : false,\n  CanvasGradient       : false,\n  CanvasPattern        : false,\n  CanvasRenderingContext2D: false,\n  CSS                  : false,\n  CSSImportRule        : false,\n  CSSGroupingRule      : false,\n  CSSMarginRule        : false,\n  CSSMediaRule         : false,\n  CSSNamespaceRule     : false,\n  CSSPageRule          : false,\n  CSSRule              : false,\n  CSSRuleList          : false,\n  CSSStyleDeclaration  : false,\n  CSSStyleRule         : false,\n  CSSStyleSheet        : false,\n  clearInterval        : false,\n  clearTimeout         : false,\n  close                : false,\n  closed               : false,\n  Comment              : false,\n  CompositionEvent     : false,\n  CustomEvent          : false,\n  DOMParser            : false,\n  defaultStatus        : false,\n  Document             : false,\n  document             : false,\n  DocumentFragment     : false,\n  Element              : false,\n  ElementTimeControl   : false,\n  Event                : false,\n  event                : false,\n  fetch                : false,\n  File                 : false,\n  FileList             : false,\n  FileReader           : false,\n  FormData             : false,\n  focus                : false,\n  frames               : false,\n  getComputedStyle     : false,\n  Headers              : false,\n  HTMLAnchorElement    : false,\n  HTMLAreaElement      : false,\n  HTMLAudioElement     : false,\n  HTMLBaseElement      : false,\n  HTMLBlockquoteElement: false,\n  HTMLBodyElement      : false,\n  HTMLBRElement        : false,\n  HTMLButtonElement    : false,\n  HTMLCanvasElement    : false,\n  HTMLCollection       : false,\n  HTMLDataElement      : false,\n  HTMLDataListElement  : false,\n  HTMLDetailsElement   : false,\n  HTMLDialogElement    : false,\n  HTMLDirectoryElement : false,\n  HTMLDivElement       : false,\n  HTMLDListElement     : false,\n  HTMLElement          : false,\n  HTMLEmbedElement     : false,\n  HTMLFieldSetElement  : false,\n  HTMLFontElement      : false,\n  HTMLFormElement      : false,\n  HTMLFrameElement     : false,\n  HTMLFrameSetElement  : false,\n  HTMLHeadElement      : false,\n  HTMLHeadingElement   : false,\n  HTMLHRElement        : false,\n  HTMLHtmlElement      : false,\n  HTMLIFrameElement    : false,\n  HTMLImageElement     : false,\n  HTMLInputElement     : false,\n/* HTMLIsIndexElement was removed from the WHATWG HTML spec;\n   see https://github.com/whatwg/html/pull/1095.\n   HTMLIsIndexElement has been removed from browsers; see:\n   • Chromium Removal: https://codereview.chromium.org/96653004/\n   • Gecko Removal: https://bugzilla.mozilla.org/show_bug.cgi?id=1266495\n   • WebKit Removal: https://bugs.webkit.org/show_bug.cgi?id=7139.\n   See also the discussion at https://github.com/jshint/jshint/pull/3222. */\n  HTMLIsIndexElement   : false,\n  HTMLLabelElement     : false,\n  HTMLLayerElement     : false,\n  HTMLLegendElement    : false,\n  HTMLLIElement        : false,\n  HTMLLinkElement      : false,\n  HTMLMapElement       : false,\n  HTMLMarqueeElement   : false,\n  HTMLMediaElement     : false,\n  HTMLMenuElement      : false,\n  HTMLMetaElement      : false,\n  HTMLMeterElement     : false,\n  HTMLModElement       : false,\n  HTMLObjectElement    : false,\n  HTMLOListElement     : false,\n  HTMLOptGroupElement  : false,\n  HTMLOptionElement    : false,\n  HTMLParagraphElement : false,\n  HTMLParamElement     : false,\n  HTMLPictureElement   : false,\n  HTMLPreElement       : false,\n  HTMLProgressElement  : false,\n  HTMLQuoteElement     : false,\n  HTMLScriptElement    : false,\n  HTMLSelectElement    : false,\n  HTMLSlotElement      : false,\n  HTMLSourceElement    : false,\n  HTMLStyleElement     : false,\n  HTMLTableCaptionElement: false,\n  HTMLTableCellElement : false,\n  HTMLTableColElement  : false,\n  HTMLTableElement     : false,\n  HTMLTableRowElement  : false,\n  HTMLTableSectionElement: false,\n  HTMLTemplateElement  : false,\n  HTMLTextAreaElement  : false,\n  HTMLTimeElement      : false,\n  HTMLTitleElement     : false,\n  HTMLTrackElement     : false,\n  HTMLUListElement     : false,\n  HTMLVideoElement     : false,\n  history              : false,\n  Image                : false,\n  IntersectionObserver : false,\n  Intl                 : false,\n  length               : false,\n  localStorage         : false,\n  location             : false,\n  matchMedia           : false,\n  MediaList            : false,\n  MediaRecorder        : false,\n  MessageChannel       : false,\n  MessageEvent         : false,\n  MessagePort          : false,\n  MouseEvent           : false,\n  moveBy               : false,\n  moveTo               : false,\n  MutationObserver     : false,\n  name                 : false,\n  Node                 : false,\n  NodeFilter           : false,\n  NodeList             : false,\n  Notification         : false,\n  navigator            : false,\n  onbeforeunload       : true,\n  onblur               : true,\n  onerror              : true,\n  onfocus              : true,\n  onload               : true,\n  onresize             : true,\n  onunload             : true,\n  open                 : false,\n  openDatabase         : false,\n  opener               : false,\n  Option               : false,\n  parent               : false,\n  performance          : false,\n  print                : false,\n  Range                : false,\n  requestAnimationFrame : false,\n  removeEventListener  : false,\n  Request              : false,\n  resizeBy             : false,\n  resizeTo             : false,\n  Response             : false,\n  screen               : false,\n  scroll               : false,\n  scrollBy             : false,\n  scrollTo             : false,\n  sessionStorage       : false,\n  setInterval          : false,\n  setTimeout           : false,\n  SharedWorker         : false,\n  status               : false,\n  Storage              : false,\n  StyleSheet           : false,\n  SVGAElement          : false,\n  SVGAltGlyphDefElement: false,\n  SVGAltGlyphElement   : false,\n  SVGAltGlyphItemElement: false,\n  SVGAngle             : false,\n  SVGAnimateColorElement: false,\n  SVGAnimateElement    : false,\n  SVGAnimateMotionElement: false,\n  SVGAnimateTransformElement: false,\n  SVGAnimatedAngle     : false,\n  SVGAnimatedBoolean   : false,\n  SVGAnimatedEnumeration: false,\n  SVGAnimatedInteger   : false,\n  SVGAnimatedLength    : false,\n  SVGAnimatedLengthList: false,\n  SVGAnimatedNumber    : false,\n  SVGAnimatedNumberList: false,\n  SVGAnimatedPathData  : false,\n  SVGAnimatedPoints    : false,\n  SVGAnimatedPreserveAspectRatio: false,\n  SVGAnimatedRect      : false,\n  SVGAnimatedString    : false,\n  SVGAnimatedTransformList: false,\n  SVGAnimationElement  : false,\n  SVGCSSRule           : false,\n  SVGCircleElement     : false,\n  SVGClipPathElement   : false,\n  SVGColor             : false,\n  SVGColorProfileElement: false,\n  SVGColorProfileRule  : false,\n  SVGComponentTransferFunctionElement: false,\n  SVGCursorElement     : false,\n  SVGDefsElement       : false,\n  SVGDescElement       : false,\n  SVGDocument          : false,\n  SVGElement           : false,\n  SVGElementInstance   : false,\n  SVGElementInstanceList: false,\n  SVGEllipseElement    : false,\n  SVGExternalResourcesRequired: false,\n  SVGFEBlendElement    : false,\n  SVGFEColorMatrixElement: false,\n  SVGFEComponentTransferElement: false,\n  SVGFECompositeElement: false,\n  SVGFEConvolveMatrixElement: false,\n  SVGFEDiffuseLightingElement: false,\n  SVGFEDisplacementMapElement: false,\n  SVGFEDistantLightElement: false,\n  SVGFEFloodElement    : false,\n  SVGFEFuncAElement    : false,\n  SVGFEFuncBElement    : false,\n  SVGFEFuncGElement    : false,\n  SVGFEFuncRElement    : false,\n  SVGFEGaussianBlurElement: false,\n  SVGFEImageElement    : false,\n  SVGFEMergeElement    : false,\n  SVGFEMergeNodeElement: false,\n  SVGFEMorphologyElement: false,\n  SVGFEOffsetElement   : false,\n  SVGFEPointLightElement: false,\n  SVGFESpecularLightingElement: false,\n  SVGFESpotLightElement: false,\n  SVGFETileElement     : false,\n  SVGFETurbulenceElement: false,\n  SVGFilterElement     : false,\n  SVGFilterPrimitiveStandardAttributes: false,\n  SVGFitToViewBox      : false,\n  SVGFontElement       : false,\n  SVGFontFaceElement   : false,\n  SVGFontFaceFormatElement: false,\n  SVGFontFaceNameElement: false,\n  SVGFontFaceSrcElement: false,\n  SVGFontFaceUriElement: false,\n  SVGForeignObjectElement: false,\n  SVGGElement          : false,\n  SVGGlyphElement      : false,\n  SVGGlyphRefElement   : false,\n  SVGGradientElement   : false,\n  SVGHKernElement      : false,\n  SVGICCColor          : false,\n  SVGImageElement      : false,\n  SVGLangSpace         : false,\n  SVGLength            : false,\n  SVGLengthList        : false,\n  SVGLineElement       : false,\n  SVGLinearGradientElement: false,\n  SVGLocatable         : false,\n  SVGMPathElement      : false,\n  SVGMarkerElement     : false,\n  SVGMaskElement       : false,\n  SVGMatrix            : false,\n  SVGMetadataElement   : false,\n  SVGMissingGlyphElement: false,\n  SVGNumber            : false,\n  SVGNumberList        : false,\n  SVGPaint             : false,\n  SVGPathElement       : false,\n  SVGPathSeg           : false,\n  SVGPathSegArcAbs     : false,\n  SVGPathSegArcRel     : false,\n  SVGPathSegClosePath  : false,\n  SVGPathSegCurvetoCubicAbs: false,\n  SVGPathSegCurvetoCubicRel: false,\n  SVGPathSegCurvetoCubicSmoothAbs: false,\n  SVGPathSegCurvetoCubicSmoothRel: false,\n  SVGPathSegCurvetoQuadraticAbs: false,\n  SVGPathSegCurvetoQuadraticRel: false,\n  SVGPathSegCurvetoQuadraticSmoothAbs: false,\n  SVGPathSegCurvetoQuadraticSmoothRel: false,\n  SVGPathSegLinetoAbs  : false,\n  SVGPathSegLinetoHorizontalAbs: false,\n  SVGPathSegLinetoHorizontalRel: false,\n  SVGPathSegLinetoRel  : false,\n  SVGPathSegLinetoVerticalAbs: false,\n  SVGPathSegLinetoVerticalRel: false,\n  SVGPathSegList       : false,\n  SVGPathSegMovetoAbs  : false,\n  SVGPathSegMovetoRel  : false,\n  SVGPatternElement    : false,\n  SVGPoint             : false,\n  SVGPointList         : false,\n  SVGPolygonElement    : false,\n  SVGPolylineElement   : false,\n  SVGPreserveAspectRatio: false,\n  SVGRadialGradientElement: false,\n  SVGRect              : false,\n  SVGRectElement       : false,\n  SVGRenderingIntent   : false,\n  SVGSVGElement        : false,\n  SVGScriptElement     : false,\n  SVGSetElement        : false,\n  SVGStopElement       : false,\n  SVGStringList        : false,\n  SVGStylable          : false,\n  SVGStyleElement      : false,\n  SVGSwitchElement     : false,\n  SVGSymbolElement     : false,\n  SVGTRefElement       : false,\n  SVGTSpanElement      : false,\n  SVGTests             : false,\n  SVGTextContentElement: false,\n  SVGTextElement       : false,\n  SVGTextPathElement   : false,\n  SVGTextPositioningElement: false,\n  SVGTitleElement      : false,\n  SVGTransform         : false,\n  SVGTransformList     : false,\n  SVGTransformable     : false,\n  SVGURIReference      : false,\n  SVGUnitTypes         : false,\n  SVGUseElement        : false,\n  SVGVKernElement      : false,\n  SVGViewElement       : false,\n  SVGViewSpec          : false,\n  SVGZoomAndPan        : false,\n  Text                 : false,\n  TextDecoder          : false,\n  TextEncoder          : false,\n  TimeEvent            : false,\n  top                  : false,\n  URL                  : false,\n  WebGLActiveInfo      : false,\n  WebGLBuffer          : false,\n  WebGLContextEvent    : false,\n  WebGLFramebuffer     : false,\n  WebGLProgram         : false,\n  WebGLRenderbuffer    : false,\n  WebGLRenderingContext: false,\n  WebGLShader          : false,\n  WebGLShaderPrecisionFormat: false,\n  WebGLTexture         : false,\n  WebGLUniformLocation : false,\n  WebSocket            : false,\n  window               : false,\n  Window               : false,\n  Worker               : false,\n  XDomainRequest       : false,\n  XMLDocument          : false,\n  XMLHttpRequest       : false,\n  XMLSerializer        : false,\n  XPathEvaluator       : false,\n  XPathException       : false,\n  XPathExpression      : false,\n  XPathNamespace       : false,\n  XPathNSResolver      : false,\n  XPathResult          : false\n};\n\nexports.devel = {\n  alert  : false,\n  confirm: false,\n  console: false,\n  Debug  : false,\n  opera  : false,\n  prompt : false\n};\n\nexports.worker = {\n  importScripts  : true,\n  onmessage      : true,\n  postMessage    : true,\n  self           : true,\n  FileReaderSync : true\n};\n\n// Widely adopted global names that are not part of ECMAScript standard\nexports.nonstandard = {\n  escape  : false,\n  unescape: false\n};\n\n// Globals provided by popular JavaScript environments.\n\nexports.couch = {\n  \"require\" : false,\n  respond   : false,\n  getRow    : false,\n  emit      : false,\n  send      : false,\n  start     : false,\n  sum       : false,\n  log       : false,\n  exports   : false,\n  module    : false,\n  provides  : false\n};\n\nexports.node = {\n  __filename    : false,\n  __dirname     : false,\n  arguments     : false,\n  GLOBAL        : false,\n  global        : false,\n  module        : false,\n  require       : false,\n\n  // These globals are writeable because Node allows the following\n  // usage pattern: var Buffer = require(\"buffer\").Buffer;\n\n  Buffer        : true,\n  console       : true,\n  exports       : true,\n  process       : true,\n  setTimeout    : true,\n  clearTimeout  : true,\n  setInterval   : true,\n  clearInterval : true,\n  setImmediate  : true, // v0.9.1+\n  clearImmediate: true  // v0.9.1+\n};\n\nexports.browserify = {\n  __filename    : false,\n  __dirname     : false,\n  global        : false,\n  module        : false,\n  require       : false,\n  Buffer        : true,\n  exports       : true,\n  process       : true\n};\n\nexports.phantom = {\n  phantom      : true,\n  require      : true,\n  WebPage      : true,\n  console      : true, // in examples, but undocumented\n  exports      : true  // v1.7+\n};\n\nexports.qunit = {\n  asyncTest      : false,\n  deepEqual      : false,\n  equal          : false,\n  expect         : false,\n  module         : false,\n  notDeepEqual   : false,\n  notEqual       : false,\n  notOk          : false,\n  notPropEqual   : false,\n  notStrictEqual : false,\n  ok             : false,\n  propEqual      : false,\n  QUnit          : false,\n  raises         : false,\n  start          : false,\n  stop           : false,\n  strictEqual    : false,\n  test           : false,\n  \"throws\"       : false\n};\n\nexports.rhino = {\n  arguments    : false,\n  defineClass  : false,\n  deserialize  : false,\n  gc           : false,\n  help         : false,\n  importClass  : false,\n  importPackage: false,\n  \"java\"       : false,\n  load         : false,\n  loadClass    : false,\n  Packages     : false,\n  print        : false,\n  quit         : false,\n  readFile     : false,\n  readUrl      : false,\n  runCommand   : false,\n  seal         : false,\n  serialize    : false,\n  spawn        : false,\n  sync         : false,\n  toint32      : false,\n  version      : false\n};\n\nexports.shelljs = {\n  target       : false,\n  echo         : false,\n  exit         : false,\n  cd           : false,\n  pwd          : false,\n  ls           : false,\n  find         : false,\n  cp           : false,\n  rm           : false,\n  mv           : false,\n  mkdir        : false,\n  test         : false,\n  cat          : false,\n  sed          : false,\n  grep         : false,\n  which        : false,\n  dirs         : false,\n  pushd        : false,\n  popd         : false,\n  env          : false,\n  exec         : false,\n  chmod        : false,\n  config       : false,\n  error        : false,\n  tempdir      : false\n};\n\nexports.typed = {\n  ArrayBuffer         : false,\n  ArrayBufferView     : false,\n  DataView            : false,\n  Float32Array        : false,\n  Float64Array        : false,\n  Int16Array          : false,\n  Int32Array          : false,\n  Int8Array           : false,\n  Uint16Array         : false,\n  Uint32Array         : false,\n  Uint8Array          : false,\n  Uint8ClampedArray   : false\n};\n\nexports.wsh = {\n  ActiveXObject            : true,\n  Enumerator               : true,\n  GetObject                : true,\n  ScriptEngine             : true,\n  ScriptEngineBuildVersion : true,\n  ScriptEngineMajorVersion : true,\n  ScriptEngineMinorVersion : true,\n  VBArray                  : true,\n  WSH                      : true,\n  WScript                  : true,\n  XDomainRequest           : true\n};\n\n// Globals provided by popular JavaScript libraries.\n\nexports.dojo = {\n  dojo     : false,\n  dijit    : false,\n  dojox    : false,\n  define   : false,\n  \"require\": false\n};\n\nexports.jquery = {\n  \"$\"    : false,\n  jQuery : false\n};\n\nexports.mootools = {\n  \"$\"           : false,\n  \"$$\"          : false,\n  Asset         : false,\n  Browser       : false,\n  Chain         : false,\n  Class         : false,\n  Color         : false,\n  Cookie        : false,\n  Core          : false,\n  Document      : false,\n  DomReady      : false,\n  DOMEvent      : false,\n  DOMReady      : false,\n  Drag          : false,\n  Element       : false,\n  Elements      : false,\n  Event         : false,\n  Events        : false,\n  Fx            : false,\n  Group         : false,\n  Hash          : false,\n  HtmlTable     : false,\n  IFrame        : false,\n  IframeShim    : false,\n  InputValidator: false,\n  instanceOf    : false,\n  Keyboard      : false,\n  Locale        : false,\n  Mask          : false,\n  MooTools      : false,\n  Native        : false,\n  Options       : false,\n  OverText      : false,\n  Request       : false,\n  Scroller      : false,\n  Slick         : false,\n  Slider        : false,\n  Sortables     : false,\n  Spinner       : false,\n  Swiff         : false,\n  Tips          : false,\n  Type          : false,\n  typeOf        : false,\n  URI           : false,\n  Window        : false\n};\n\nexports.prototypejs = {\n  \"$\"               : false,\n  \"$$\"              : false,\n  \"$A\"              : false,\n  \"$F\"              : false,\n  \"$H\"              : false,\n  \"$R\"              : false,\n  \"$break\"          : false,\n  \"$continue\"       : false,\n  \"$w\"              : false,\n  Abstract          : false,\n  Ajax              : false,\n  Class             : false,\n  Enumerable        : false,\n  Element           : false,\n  Event             : false,\n  Field             : false,\n  Form              : false,\n  Hash              : false,\n  Insertion         : false,\n  ObjectRange       : false,\n  PeriodicalExecuter: false,\n  Position          : false,\n  Prototype         : false,\n  Selector          : false,\n  Template          : false,\n  Toggle            : false,\n  Try               : false,\n  Autocompleter     : false,\n  Builder           : false,\n  Control           : false,\n  Draggable         : false,\n  Draggables        : false,\n  Droppables        : false,\n  Effect            : false,\n  Sortable          : false,\n  SortableObserver  : false,\n  Sound             : false,\n  Scriptaculous     : false\n};\n\nexports.yui = {\n  YUI       : false,\n  Y         : false,\n  YUI_config: false\n};\n\nexports.mocha = {\n  // Global (for config etc.)\n  mocha       : false,\n  // BDD\n  describe    : false,\n  xdescribe   : false,\n  it          : false,\n  xit         : false,\n  context     : false,\n  xcontext    : false,\n  before      : false,\n  after       : false,\n  beforeEach  : false,\n  afterEach   : false,\n  // TDD\n  suite         : false,\n  test          : false,\n  setup         : false,\n  teardown      : false,\n  suiteSetup    : false,\n  suiteTeardown : false\n};\n\nexports.jasmine = {\n  jasmine     : false,\n  describe    : false,\n  xdescribe   : false,\n  it          : false,\n  xit         : false,\n  beforeEach  : false,\n  afterEach   : false,\n  setFixtures : false,\n  loadFixtures: false,\n  spyOn       : false,\n  expect      : false,\n  // Jasmine 1.3\n  runs        : false,\n  waitsFor    : false,\n  waits       : false,\n  // Jasmine 2.1\n  beforeAll   : false,\n  afterAll    : false,\n  fail        : false,\n  fdescribe   : false,\n  fit         : false,\n  pending     : false,\n  // Jasmine 2.6\n  spyOnProperty: false\n};\n\n},{}],\"jshint\":[function(require,module,exports){\n/*!\n * JSHint, by JSHint Community.\n *\n * This file (and this file only) is licensed under the same slightly modified\n * MIT license that JSLint is. It stops evil-doers everywhere:\n *\n *   Copyright (c) 2002 Douglas Crockford  (www.JSLint.com)\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the \"Software\"),\n *   to deal in the Software without restriction, including without limitation\n *   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n *   and/or sell copies of the Software, and to permit persons to whom\n *   the Software is furnished to do so, subject to the following conditions:\n *\n *   The above copyright notice and this permission notice shall be included\n *   in all copies or substantial portions of the Software.\n *\n *   The Software shall be used for Good, not Evil.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n *   DEALINGS IN THE SOFTWARE.\n *\n */\n\n/*jshint quotmark:double */\n/*exported console */\n\nvar _            = require(\"lodash\");\nvar events       = require(\"events\");\nvar vars         = require(\"./vars.js\");\nvar messages     = require(\"./messages.js\");\nvar Lexer        = require(\"./lex.js\").Lexer;\nvar reg          = require(\"./reg.js\");\nvar state        = require(\"./state.js\").state;\nvar style        = require(\"./style.js\");\nvar options      = require(\"./options.js\");\nvar scopeManager = require(\"./scope-manager.js\");\n\n// We need this module here because environments such as IE and Rhino\n// don't necessarilly expose the 'console' API and browserify uses\n// it to log things. It's a sad state of affair, really.\nvar console = require(\"console-browserify\");\n\n// We build the application inside a function so that we produce only a singleton\n// variable. That function will be invoked immediately, and its return value is\n// the JSHINT function itself.\n\nvar JSHINT = (function() {\n  \"use strict\";\n\n  var api, // Extension API\n\n    // These are operators that should not be used with the ! operator.\n    bang = {\n      \"<\"  : true,\n      \"<=\" : true,\n      \"==\" : true,\n      \"===\": true,\n      \"!==\": true,\n      \"!=\" : true,\n      \">\"  : true,\n      \">=\" : true,\n      \"+\"  : true,\n      \"-\"  : true,\n      \"*\"  : true,\n      \"/\"  : true,\n      \"%\"  : true\n    },\n\n    declared, // Globals that were declared using /*global ... */ syntax.\n\n    functions, // All of the functions\n\n    inblock,\n    indent,\n    lookahead,\n    lex,\n    member,\n    membersOnly,\n    predefined,    // Global variables defined by option\n\n    urls,\n\n    extraModules = [],\n    emitter = new events.EventEmitter();\n\n  function checkOption(name, t) {\n    name = name.trim();\n\n    if (/^[+-]W\\d{3}$/g.test(name)) {\n      return true;\n    }\n\n    if (options.validNames.indexOf(name) === -1) {\n      if (t.type !== \"jslint\" && !_.has(options.removed, name)) {\n        error(\"E001\", t, name);\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  function isString(obj) {\n    return Object.prototype.toString.call(obj) === \"[object String]\";\n  }\n\n  function isIdentifier(tkn, value) {\n    if (!tkn)\n      return false;\n\n    if (!tkn.identifier || tkn.value !== value)\n      return false;\n\n    return true;\n  }\n\n  function isReserved(token) {\n    if (!token.reserved) {\n      return false;\n    }\n    var meta = token.meta;\n\n    if (meta && meta.isFutureReservedWord) {\n      if (meta.moduleOnly && !state.option.module) {\n        return false;\n      }\n\n      if (state.inES5()) {\n        // ES3 FutureReservedWord in an ES5 environment.\n        if (!meta.es5) {\n          return false;\n        }\n\n        // Some ES5 FutureReservedWord identifiers are active only\n        // within a strict mode environment.\n        if (meta.strictOnly) {\n          if (!state.option.strict && !state.isStrict()) {\n            return false;\n          }\n        }\n\n        if (token.isProperty) {\n          return false;\n        }\n      }\n    }\n\n    return true;\n  }\n\n  function supplant(str, data) {\n    return str.replace(/\\{([^{}]*)\\}/g, function(a, b) {\n      var r = data[b];\n      return typeof r === \"string\" || typeof r === \"number\" ? r : a;\n    });\n  }\n\n  function combine(dest, src) {\n    Object.keys(src).forEach(function(name) {\n      if (_.has(JSHINT.blacklist, name)) return;\n      dest[name] = src[name];\n    });\n  }\n\n  function processenforceall() {\n    if (state.option.enforceall) {\n      for (var enforceopt in options.bool.enforcing) {\n        if (state.option[enforceopt] === undefined &&\n            !options.noenforceall[enforceopt]) {\n          state.option[enforceopt] = true;\n        }\n      }\n      for (var relaxopt in options.bool.relaxing) {\n        if (state.option[relaxopt] === undefined) {\n          state.option[relaxopt] = false;\n        }\n      }\n    }\n  }\n\n  /**\n   * Apply all linting options according to the status of the `state` object.\n   */\n  function applyOptions() {\n    var badESOpt = null;\n    processenforceall();\n\n    /**\n     * TODO: Remove in JSHint 3\n     */\n    badESOpt = state.inferEsVersion();\n    if (badESOpt) {\n      quit(\"E059\", state.tokens.next, \"esversion\", badESOpt);\n    }\n\n    if (state.inES5()) {\n      combine(predefined, vars.ecmaIdentifiers[5]);\n    }\n\n    if (state.inES6()) {\n      combine(predefined, vars.ecmaIdentifiers[6]);\n    }\n\n    /**\n     * Use `in` to check for the presence of any explicitly-specified value for\n     * `globalstrict` because both `true` and `false` should trigger an error.\n     */\n    if (state.option.strict === \"global\" && \"globalstrict\" in state.option) {\n      quit(\"E059\", state.tokens.next, \"strict\", \"globalstrict\");\n    }\n\n    if (state.option.module) {\n      /**\n       * TODO: Extend this restriction to *all* ES6-specific options.\n       */\n      if (!state.inES6()) {\n        warning(\"W134\", state.tokens.next, \"module\", 6);\n      }\n    }\n\n    if (state.option.couch) {\n      combine(predefined, vars.couch);\n    }\n\n    if (state.option.qunit) {\n      combine(predefined, vars.qunit);\n    }\n\n    if (state.option.rhino) {\n      combine(predefined, vars.rhino);\n    }\n\n    if (state.option.shelljs) {\n      combine(predefined, vars.shelljs);\n      combine(predefined, vars.node);\n    }\n    if (state.option.typed) {\n      combine(predefined, vars.typed);\n    }\n\n    if (state.option.phantom) {\n      combine(predefined, vars.phantom);\n    }\n\n    if (state.option.prototypejs) {\n      combine(predefined, vars.prototypejs);\n    }\n\n    if (state.option.node) {\n      combine(predefined, vars.node);\n      combine(predefined, vars.typed);\n    }\n\n    if (state.option.devel) {\n      combine(predefined, vars.devel);\n    }\n\n    if (state.option.dojo) {\n      combine(predefined, vars.dojo);\n    }\n\n    if (state.option.browser) {\n      combine(predefined, vars.browser);\n      combine(predefined, vars.typed);\n    }\n\n    if (state.option.browserify) {\n      combine(predefined, vars.browser);\n      combine(predefined, vars.typed);\n      combine(predefined, vars.browserify);\n    }\n\n    if (state.option.nonstandard) {\n      combine(predefined, vars.nonstandard);\n    }\n\n    if (state.option.jasmine) {\n      combine(predefined, vars.jasmine);\n    }\n\n    if (state.option.jquery) {\n      combine(predefined, vars.jquery);\n    }\n\n    if (state.option.mootools) {\n      combine(predefined, vars.mootools);\n    }\n\n    if (state.option.worker) {\n      combine(predefined, vars.worker);\n    }\n\n    if (state.option.wsh) {\n      combine(predefined, vars.wsh);\n    }\n\n    if (state.option.yui) {\n      combine(predefined, vars.yui);\n    }\n\n    if (state.option.mocha) {\n      combine(predefined, vars.mocha);\n    }\n  }\n\n  // Produce an error warning.\n  function quit(code, token, a, b) {\n    var percentage = Math.floor((token.line / state.lines.length) * 100);\n    var message = messages.errors[code].desc;\n\n    var exception = {\n      name: \"JSHintError\",\n      line: token.line,\n      character: token.from,\n      message: message + \" (\" + percentage + \"% scanned).\",\n      raw: message,\n      code: code,\n      a: a,\n      b: b\n    };\n\n    exception.reason = supplant(message, exception) + \" (\" + percentage +\n      \"% scanned).\";\n\n    throw exception;\n  }\n\n  function removeIgnoredMessages() {\n    var ignored = state.ignoredLines;\n\n    if (_.isEmpty(ignored)) return;\n    JSHINT.errors = _.reject(JSHINT.errors, function(err) { return ignored[err.line] });\n  }\n\n  function warning(code, t, a, b, c, d) {\n    var ch, l, w, msg;\n\n    if (/^W\\d{3}$/.test(code)) {\n      if (state.ignored[code])\n        return;\n\n      msg = messages.warnings[code];\n    } else if (/E\\d{3}/.test(code)) {\n      msg = messages.errors[code];\n    } else if (/I\\d{3}/.test(code)) {\n      msg = messages.info[code];\n    }\n\n    t = t || state.tokens.next || {};\n    if (t.id === \"(end)\") {  // `~\n      t = state.tokens.curr;\n    }\n\n    l = t.line;\n    ch = t.from;\n\n    w = {\n      id: \"(error)\",\n      raw: msg.desc,\n      code: msg.code,\n      evidence: state.lines[l - 1] || \"\",\n      line: l,\n      character: ch,\n      scope: JSHINT.scope,\n      a: a,\n      b: b,\n      c: c,\n      d: d\n    };\n\n    w.reason = supplant(msg.desc, w);\n    JSHINT.errors.push(w);\n\n    removeIgnoredMessages();\n\n    if (JSHINT.errors.length >= state.option.maxerr)\n      quit(\"E043\", t);\n\n    return w;\n  }\n\n  function warningAt(m, l, ch, a, b, c, d) {\n    return warning(m, {\n      line: l,\n      from: ch\n    }, a, b, c, d);\n  }\n\n  function error(m, t, a, b, c, d) {\n    warning(m, t, a, b, c, d);\n  }\n\n  function errorAt(m, l, ch, a, b, c, d) {\n    return error(m, {\n      line: l,\n      from: ch\n    }, a, b, c, d);\n  }\n\n  // Tracking of \"internal\" scripts, like eval containing a static string\n  function addEvalCode(elem, token) {\n    JSHINT.internals.push({\n      id: \"(internal)\",\n      elem: elem,\n      token: token,\n      code: token.value.replace(/([^\\\\])(\\\\*)\\2\\\\n/g, \"$1\\n\")\n    });\n  }\n\n  /**\n   * Process an inline linting directive\n   *\n   * @param {Token} directiveToken - the directive-bearing comment token\n   * @param {Token} previous - the token that preceeds the directive\n   */\n  function lintingDirective(directiveToken, previous) {\n    var body = directiveToken.body.split(\",\")\n      .map(function(s) { return s.trim(); });\n    var predef = {};\n\n    if (directiveToken.type === \"falls through\") {\n      previous.caseFallsThrough = true;\n      return;\n    }\n\n    if (directiveToken.type === \"globals\") {\n      body.forEach(function(g, idx) {\n        g = g.split(\":\");\n        var key = g[0].trim();\n        var val = (g[1] || \"\").trim();\n\n        if (key === \"-\" || !key.length) {\n          // Ignore trailing comma\n          if (idx > 0 && idx === body.length - 1) {\n            return;\n          }\n          error(\"E002\", directiveToken);\n          return;\n        }\n\n        if (key.charAt(0) === \"-\") {\n          key = key.slice(1);\n          val = false;\n\n          JSHINT.blacklist[key] = key;\n          delete predefined[key];\n        } else {\n          predef[key] = (val === \"true\");\n        }\n      });\n\n      combine(predefined, predef);\n\n      for (var key in predef) {\n        if (_.has(predef, key)) {\n          declared[key] = directiveToken;\n        }\n      }\n    }\n\n    if (directiveToken.type === \"exported\") {\n      body.forEach(function(e, idx) {\n        if (!e.length) {\n          // Ignore trailing comma\n          if (idx > 0 && idx === body.length - 1) {\n            return;\n          }\n          error(\"E002\", directiveToken);\n          return;\n        }\n\n        state.funct[\"(scope)\"].addExported(e);\n      });\n    }\n\n    if (directiveToken.type === \"members\") {\n      membersOnly = membersOnly || {};\n\n      body.forEach(function(m) {\n        var ch1 = m.charAt(0);\n        var ch2 = m.charAt(m.length - 1);\n\n        if (ch1 === ch2 && (ch1 === \"\\\"\" || ch1 === \"'\")) {\n          m = m\n            .substr(1, m.length - 2)\n            .replace(\"\\\\\\\"\", \"\\\"\");\n        }\n\n        membersOnly[m] = false;\n      });\n    }\n\n    var numvals = [\n      \"maxstatements\",\n      \"maxparams\",\n      \"maxdepth\",\n      \"maxcomplexity\",\n      \"maxerr\",\n      \"maxlen\",\n      \"indent\"\n    ];\n\n    if (directiveToken.type === \"jshint\" || directiveToken.type === \"jslint\") {\n      body.forEach(function(g) {\n        g = g.split(\":\");\n        var key = g[0].trim();\n        var val = (g[1] || \"\").trim();\n\n        if (!checkOption(key, directiveToken)) {\n          return;\n        }\n\n        if (numvals.indexOf(key) >= 0) {\n          // GH988 - numeric options can be disabled by setting them to `false`\n          if (val !== \"false\") {\n            val = +val;\n\n            if (typeof val !== \"number\" || !isFinite(val) || val <= 0 || Math.floor(val) !== val) {\n              error(\"E032\", directiveToken, g[1].trim());\n              return;\n            }\n\n            state.option[key] = val;\n          } else {\n            state.option[key] = key === \"indent\" ? 4 : false;\n          }\n\n          return;\n        }\n\n        if (key === \"validthis\") {\n          // `validthis` is valid only within a function scope.\n\n          if (state.funct[\"(global)\"])\n            return void error(\"E009\");\n\n          if (val !== \"true\" && val !== \"false\")\n            return void error(\"E002\", directiveToken);\n\n          state.option.validthis = (val === \"true\");\n          return;\n        }\n\n        if (key === \"quotmark\") {\n          switch (val) {\n          case \"true\":\n          case \"false\":\n            state.option.quotmark = (val === \"true\");\n            break;\n          case \"double\":\n          case \"single\":\n            state.option.quotmark = val;\n            break;\n          default:\n            error(\"E002\", directiveToken);\n          }\n          return;\n        }\n\n        if (key === \"shadow\") {\n          switch (val) {\n          case \"true\":\n            state.option.shadow = true;\n            break;\n          case \"outer\":\n            state.option.shadow = \"outer\";\n            break;\n          case \"false\":\n          case \"inner\":\n            state.option.shadow = \"inner\";\n            break;\n          default:\n            error(\"E002\", directiveToken);\n          }\n          return;\n        }\n\n        if (key === \"unused\") {\n          switch (val) {\n          case \"true\":\n            state.option.unused = true;\n            break;\n          case \"false\":\n            state.option.unused = false;\n            break;\n          case \"vars\":\n          case \"strict\":\n            state.option.unused = val;\n            break;\n          default:\n            error(\"E002\", directiveToken);\n          }\n          return;\n        }\n\n        if (key === \"latedef\") {\n          switch (val) {\n          case \"true\":\n            state.option.latedef = true;\n            break;\n          case \"false\":\n            state.option.latedef = false;\n            break;\n          case \"nofunc\":\n            state.option.latedef = \"nofunc\";\n            break;\n          default:\n            error(\"E002\", directiveToken);\n          }\n          return;\n        }\n\n        if (key === \"ignore\") {\n          switch (val) {\n          case \"line\":\n            state.ignoredLines[directiveToken.line] = true;\n            removeIgnoredMessages();\n            break;\n          default:\n            error(\"E002\", directiveToken);\n          }\n          return;\n        }\n\n        if (key === \"strict\") {\n          switch (val) {\n          case \"true\":\n            state.option.strict = true;\n            break;\n          case \"false\":\n            state.option.strict = false;\n            break;\n          case \"global\":\n          case \"implied\":\n            state.option.strict = val;\n            break;\n          default:\n            error(\"E002\", directiveToken);\n          }\n          return;\n        }\n\n        if (key === \"module\") {\n          /**\n           * TODO: Extend this restriction to *all* \"environmental\" options.\n           */\n          if (!hasParsedCode(state.funct)) {\n            error(\"E055\", directiveToken, \"module\");\n          }\n        }\n\n        if (key === \"esversion\") {\n          switch (val) {\n          case \"3\":\n          case \"5\":\n          case \"6\":\n          case \"2015\":\n            state.option.moz = false;\n            state.option.esversion = +val;\n            break;\n          default:\n            error(\"E002\", directiveToken);\n          }\n          if (!hasParsedCode(state.funct)) {\n            error(\"E055\", directiveToken, \"esversion\");\n          }\n          return;\n        }\n\n        var match = /^([+-])(W\\d{3})$/g.exec(key);\n        if (match) {\n          // ignore for -W..., unignore for +W...\n          state.ignored[match[2]] = (match[1] === \"-\");\n          return;\n        }\n\n        var tn;\n        if (val === \"true\" || val === \"false\") {\n          if (directiveToken.type === \"jslint\") {\n            tn = options.renamed[key] || key;\n            state.option[tn] = (val === \"true\");\n\n            if (options.inverted[tn] !== undefined) {\n              state.option[tn] = !state.option[tn];\n            }\n          } else {\n            state.option[key] = (val === \"true\");\n          }\n\n          return;\n        }\n\n        error(\"E002\", directiveToken);\n      });\n\n      applyOptions();\n    }\n  }\n\n  /**\n   * Return a token beyond the token available in `state.tokens.next`. If no\n   * such token exists, return the \"(end)\" token. This function is used to\n   * determine parsing strategies in cases where the value of the next token\n   * does not provide sufficient information, as is the case with `for` loops,\n   * e.g.:\n   *\n   *     for ( var i in ...\n   *\n   * versus:\n   *\n   *     for ( var i = ...\n   *\n   * @param {number} [p] - offset of desired token; defaults to 0\n   *\n   * @returns {token}\n   */\n  function peek(p) {\n    var i = p || 0, j = lookahead.length, t;\n\n    if (i < j) {\n      return lookahead[i];\n    }\n\n    while (j <= i) {\n      t = lex.token();\n\n      // When the lexer is exhausted, this function should produce the \"(end)\"\n      // token, even in cases where the requested token is beyond the end of\n      // the input stream.\n      if (!t) {\n        // If the lookahead buffer is empty, the expected \"(end)\" token was\n        // already emitted by the most recent invocation of `advance` and is\n        // available as the next token.\n        if (!lookahead.length) {\n          return state.tokens.next;\n        }\n\n        return lookahead[j - 1];\n      }\n\n      lookahead[j] = t;\n      j += 1;\n    }\n\n    return t;\n  }\n\n  function peekIgnoreEOL() {\n    var i = 0;\n    var t;\n    do {\n      t = peek(i++);\n    } while (t.id === \"(endline)\");\n    return t;\n  }\n\n  // Produce the next token. It looks for programming errors.\n\n  function advance(id, t) {\n\n    switch (state.tokens.curr.id) {\n    case \"(number)\":\n      if (state.tokens.next.id === \".\") {\n        warning(\"W005\", state.tokens.curr);\n      }\n      break;\n    case \"-\":\n      if (state.tokens.next.id === \"-\" || state.tokens.next.id === \"--\") {\n        warning(\"W006\");\n      }\n      break;\n    case \"+\":\n      if (state.tokens.next.id === \"+\" || state.tokens.next.id === \"++\") {\n        warning(\"W007\");\n      }\n      break;\n    }\n\n    if (id && state.tokens.next.id !== id) {\n      if (t) {\n        if (state.tokens.next.id === \"(end)\") {\n          error(\"E019\", t, t.id);\n        } else {\n          error(\"E020\", state.tokens.next, id, t.id, t.line, state.tokens.next.value);\n        }\n      } else if (state.tokens.next.type !== \"(identifier)\" || state.tokens.next.value !== id) {\n        warning(\"W116\", state.tokens.next, id, state.tokens.next.value);\n      }\n    }\n\n    state.tokens.prev = state.tokens.curr;\n    state.tokens.curr = state.tokens.next;\n    for (;;) {\n      state.tokens.next = lookahead.shift() || lex.token();\n\n      if (!state.tokens.next) { // No more tokens left, give up\n        quit(\"E041\", state.tokens.curr);\n      }\n\n      if (state.tokens.next.id === \"(end)\" || state.tokens.next.id === \"(error)\") {\n        return;\n      }\n\n      if (state.tokens.next.check) {\n        state.tokens.next.check();\n      }\n\n      if (state.tokens.next.isSpecial) {\n        lintingDirective(state.tokens.next, state.tokens.curr);\n      } else {\n        if (state.tokens.next.id !== \"(endline)\") {\n          break;\n        }\n      }\n    }\n  }\n\n  /**\n   * Determine whether a given token is an operator.\n   *\n   * @param {token} token\n   *\n   * @returns {boolean}\n   */\n  function isOperator(token) {\n    return token.first || token.right || token.left || token.id === \"yield\";\n  }\n\n  function isEndOfExpr(curr, next) {\n    if (arguments.length === 0) {\n      curr = state.tokens.curr;\n      next = state.tokens.next;\n    }\n\n    if (next.id === \";\" || next.id === \"}\" || next.id === \":\") {\n      return true;\n    }\n    if (next.infix === curr.infix || curr.ltBoundary === \"after\" ||\n      next.ltBoundary === \"before\") {\n      return curr.line !== startLine(next);\n    }\n    return false;\n  }\n\n  // This is the heart of JSHINT, the Pratt parser. In addition to parsing, it\n  // is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is\n  // like .nud except that it is only used on the first token of a statement.\n  // Having .fud makes it much easier to define statement-oriented languages like\n  // JavaScript. I retained Pratt's nomenclature.\n\n  // .nud  Null denotation\n  // .fud  First null denotation\n  // .led  Left denotation\n  //  lbp  Left binding power\n  //  rbp  Right binding power\n\n  // They are elements of the parsing method called Top Down Operator Precedence.\n\n  function expression(rbp, initial) {\n    var left, isArray = false, isObject = false, isLetExpr = false;\n\n    state.nameStack.push();\n\n    // if current expression is a let expression\n    if (!initial && state.tokens.next.value === \"let\" && peek(0).value === \"(\") {\n      if (!state.inMoz()) {\n        warning(\"W118\", state.tokens.next, \"let expressions\");\n      }\n      isLetExpr = true;\n      // create a new block scope we use only for the current expression\n      state.funct[\"(scope)\"].stack();\n      advance(\"let\");\n      advance(\"(\");\n      state.tokens.prev.fud();\n      advance(\")\");\n    }\n\n    if (state.tokens.next.id === \"(end)\")\n      error(\"E006\", state.tokens.curr);\n\n    advance();\n\n    if (initial) {\n      state.funct[\"(verb)\"] = state.tokens.curr.value;\n      state.tokens.curr.beginsStmt = true;\n    }\n\n    if (initial === true && state.tokens.curr.fud) {\n      left = state.tokens.curr.fud();\n    } else {\n      if (state.tokens.curr.nud) {\n        left = state.tokens.curr.nud(rbp);\n      } else {\n        error(\"E030\", state.tokens.curr, state.tokens.curr.id);\n      }\n\n      while (rbp < state.tokens.next.lbp && !isEndOfExpr()) {\n        isArray = state.tokens.curr.value === \"Array\";\n        isObject = state.tokens.curr.value === \"Object\";\n\n        // #527, new Foo.Array(), Foo.Array(), new Foo.Object(), Foo.Object()\n        // Line breaks in IfStatement heads exist to satisfy the checkJSHint\n        // \"Line too long.\" error.\n        if (left && (left.value || (left.first && left.first.value))) {\n          // If the left.value is not \"new\", or the left.first.value is a \".\"\n          // then safely assume that this is not \"new Array()\" and possibly\n          // not \"new Object()\"...\n          if (left.value !== \"new\" ||\n            (left.first && left.first.value && left.first.value === \".\")) {\n            isArray = false;\n            // ...In the case of Object, if the left.value and state.tokens.curr.value\n            // are not equal, then safely assume that this not \"new Object()\"\n            if (left.value !== state.tokens.curr.value) {\n              isObject = false;\n            }\n          }\n        }\n\n        advance();\n\n        if (isArray && state.tokens.curr.id === \"(\" && state.tokens.next.id === \")\") {\n          warning(\"W009\", state.tokens.curr);\n        }\n\n        if (isObject && state.tokens.curr.id === \"(\" && state.tokens.next.id === \")\") {\n          warning(\"W010\", state.tokens.curr);\n        }\n\n        if (left && state.tokens.curr.led) {\n          left = state.tokens.curr.led(left);\n        } else {\n          error(\"E033\", state.tokens.curr, state.tokens.curr.id);\n        }\n      }\n    }\n    if (isLetExpr) {\n      state.funct[\"(scope)\"].unstack();\n    }\n\n    state.nameStack.pop();\n\n    return left;\n  }\n\n\n  // Functions for conformance of style.\n\n  function startLine(token) {\n    return token.startLine || token.line;\n  }\n\n  function nobreaknonadjacent(left, right) {\n    if (!state.option.laxbreak && left.line !== startLine(right)) {\n      warning(\"W014\", right, right.value);\n    }\n  }\n\n  function nolinebreak(t) {\n    t = t;\n    if (t.line !== startLine(state.tokens.next)) {\n      warning(\"E022\", t, t.value);\n    }\n  }\n\n  function nobreakcomma(left, right) {\n    if (left.line !== startLine(right)) {\n      if (!state.option.laxcomma) {\n        if (parseComma.first) {\n          warning(\"I001\");\n          parseComma.first = false;\n        }\n        warning(\"W014\", left, right.value);\n      }\n    }\n  }\n\n  function parseComma(opts) {\n    opts = opts || {};\n\n    if (!opts.peek) {\n      nobreakcomma(state.tokens.curr, state.tokens.next);\n      advance(\",\");\n    } else {\n      nobreakcomma(state.tokens.prev, state.tokens.curr);\n    }\n\n    if (state.tokens.next.identifier && !(opts.property && state.inES5())) {\n      // Keywords that cannot follow a comma operator.\n      switch (state.tokens.next.value) {\n      case \"break\":\n      case \"case\":\n      case \"catch\":\n      case \"continue\":\n      case \"default\":\n      case \"do\":\n      case \"else\":\n      case \"finally\":\n      case \"for\":\n      case \"if\":\n      case \"in\":\n      case \"instanceof\":\n      case \"return\":\n      case \"switch\":\n      case \"throw\":\n      case \"try\":\n      case \"var\":\n      case \"let\":\n      case \"while\":\n      case \"with\":\n        error(\"E024\", state.tokens.next, state.tokens.next.value);\n        return false;\n      }\n    }\n\n    if (state.tokens.next.type === \"(punctuator)\") {\n      switch (state.tokens.next.value) {\n      case \"}\":\n      case \"]\":\n      case \",\":\n        if (opts.allowTrailing) {\n          return true;\n        }\n\n        /* falls through */\n      case \")\":\n        error(\"E024\", state.tokens.next, state.tokens.next.value);\n        return false;\n      }\n    }\n    return true;\n  }\n\n  // Functional constructors for making the symbols that will be inherited by\n  // tokens.\n\n  function symbol(s, p) {\n    var x = state.syntax[s];\n    if (!x || typeof x !== \"object\") {\n      state.syntax[s] = x = {\n        id: s,\n        lbp: p,\n        value: s\n      };\n    }\n    return x;\n  }\n\n  function delim(s) {\n    var x = symbol(s, 0);\n    x.delim = true;\n    return x;\n  }\n\n  function stmt(s, f) {\n    var x = delim(s);\n    x.identifier = x.reserved = true;\n    x.fud = f;\n    return x;\n  }\n\n  function blockstmt(s, f) {\n    var x = stmt(s, f);\n    x.block = true;\n    return x;\n  }\n\n  function reserveName(x) {\n    var c = x.id.charAt(0);\n    if ((c >= \"a\" && c <= \"z\") || (c >= \"A\" && c <= \"Z\")) {\n      x.identifier = x.reserved = true;\n    }\n    return x;\n  }\n\n  function prefix(s, f) {\n    var x = symbol(s, 150);\n    reserveName(x);\n\n    x.nud = (typeof f === \"function\") ? f : function() {\n      this.arity = \"unary\";\n      this.right = expression(150);\n\n      if (this.id === \"++\" || this.id === \"--\") {\n        if (state.option.plusplus) {\n          warning(\"W016\", this, this.id);\n        }\n\n        if (this.right) {\n          checkLeftSideAssign(this.right, this);\n        }\n      }\n\n      return this;\n    };\n\n    return x;\n  }\n\n  function type(s, f) {\n    var x = delim(s);\n    x.type = s;\n    x.nud = f;\n    return x;\n  }\n\n  function reserve(name, func) {\n    var x = type(name, func);\n    x.identifier = true;\n    x.reserved = true;\n    return x;\n  }\n\n  function FutureReservedWord(name, meta) {\n    var x = type(name, (meta && meta.nud) || function() {\n      return this;\n    });\n\n    meta = meta || {};\n    meta.isFutureReservedWord = true;\n\n    x.value = name;\n    x.identifier = true;\n    x.reserved = true;\n    x.meta = meta;\n\n    return x;\n  }\n\n  function reservevar(s, v) {\n    return reserve(s, function() {\n      if (typeof v === \"function\") {\n        v(this);\n      }\n      return this;\n    });\n  }\n\n  function infix(s, f, p, w) {\n    var x = symbol(s, p);\n    reserveName(x);\n    x.infix = true;\n    x.led = function(left) {\n      if (!w) {\n        nobreaknonadjacent(state.tokens.prev, state.tokens.curr);\n      }\n      if ((s === \"in\" || s === \"instanceof\") && left.id === \"!\") {\n        warning(\"W018\", left, \"!\");\n      }\n      if (typeof f === \"function\") {\n        return f(left, this);\n      } else {\n        this.left = left;\n        this.right = expression(p);\n        return this;\n      }\n    };\n    return x;\n  }\n\n  function application(s) {\n    var x = symbol(s, 42);\n\n    x.infix = true;\n    x.led = function(left) {\n      nobreaknonadjacent(state.tokens.prev, state.tokens.curr);\n\n      this.left = left;\n      this.right = doFunction({ type: \"arrow\", loneArg: left });\n      return this;\n    };\n    return x;\n  }\n\n  function relation(s, f) {\n    var x = symbol(s, 100);\n\n    x.infix = true;\n    x.led = function(left) {\n      nobreaknonadjacent(state.tokens.prev, state.tokens.curr);\n      this.left = left;\n      var right = this.right = expression(100);\n\n      if (isIdentifier(left, \"NaN\") || isIdentifier(right, \"NaN\")) {\n        warning(\"W019\", this);\n      } else if (f) {\n        f.apply(this, [left, right]);\n      }\n\n      if (!left || !right) {\n        quit(\"E041\", state.tokens.curr);\n      }\n\n      if (left.id === \"!\") {\n        warning(\"W018\", left, \"!\");\n      }\n\n      if (right.id === \"!\") {\n        warning(\"W018\", right, \"!\");\n      }\n\n      return this;\n    };\n    return x;\n  }\n\n  var typeofValues = {};\n  typeofValues.legacy = [\n    // E4X extended the `typeof` operator to return \"xml\" for the XML and\n    // XMLList types it introduced.\n    // Ref: 11.3.2 The typeof Operator\n    // http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf\n    \"xml\",\n    // IE<9 reports \"unknown\" when the `typeof` operator is applied to an\n    // object existing across a COM+ bridge. In lieu of official documentation\n    // (which does not exist), see:\n    // http://robertnyman.com/2005/12/21/what-is-typeof-unknown/\n    \"unknown\"\n  ];\n  typeofValues.es3 = [\n    \"undefined\", \"boolean\", \"number\", \"string\", \"function\", \"object\",\n  ];\n  typeofValues.es3 = typeofValues.es3.concat(typeofValues.legacy);\n  typeofValues.es6 = typeofValues.es3.concat(\"symbol\");\n\n  // Checks whether the 'typeof' operator is used with the correct\n  // value. For docs on 'typeof' see:\n  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof\n  function isTypoTypeof(left, right, state) {\n    var values;\n\n    if (state.option.notypeof)\n      return false;\n\n    if (!left || !right)\n      return false;\n\n    values = state.inES6() ? typeofValues.es6 : typeofValues.es3;\n\n    if (right.type === \"(identifier)\" && right.value === \"typeof\" && left.type === \"(string)\")\n      return !_.includes(values, left.value);\n\n    return false;\n  }\n\n  function isGlobalEval(left, state) {\n    var isGlobal = false;\n\n    // permit methods to refer to an \"eval\" key in their own context\n    if (left.type === \"this\" && state.funct[\"(context)\"] === null) {\n      isGlobal = true;\n    }\n    // permit use of \"eval\" members of objects\n    else if (left.type === \"(identifier)\") {\n      if (state.option.node && left.value === \"global\") {\n        isGlobal = true;\n      }\n\n      else if (state.option.browser && (left.value === \"window\" || left.value === \"document\")) {\n        isGlobal = true;\n      }\n    }\n\n    return isGlobal;\n  }\n\n  function findNativePrototype(left) {\n    var natives = [\n      \"Array\", \"ArrayBuffer\", \"Boolean\", \"Collator\", \"DataView\", \"Date\",\n      \"DateTimeFormat\", \"Error\", \"EvalError\", \"Float32Array\", \"Float64Array\",\n      \"Function\", \"Infinity\", \"Intl\", \"Int16Array\", \"Int32Array\", \"Int8Array\",\n      \"Iterator\", \"Number\", \"NumberFormat\", \"Object\", \"RangeError\",\n      \"ReferenceError\", \"RegExp\", \"StopIteration\", \"String\", \"SyntaxError\",\n      \"TypeError\", \"Uint16Array\", \"Uint32Array\", \"Uint8Array\", \"Uint8ClampedArray\",\n      \"URIError\"\n    ];\n\n    function walkPrototype(obj) {\n      if (typeof obj !== \"object\") return;\n      return obj.right === \"prototype\" ? obj : walkPrototype(obj.left);\n    }\n\n    function walkNative(obj) {\n      while (!obj.identifier && typeof obj.left === \"object\")\n        obj = obj.left;\n\n      if (obj.identifier && natives.indexOf(obj.value) >= 0 &&\n          state.funct[\"(scope)\"].isPredefined(obj.value)) {\n        return obj.value;\n      }\n    }\n\n    var prototype = walkPrototype(left);\n    if (prototype) return walkNative(prototype);\n  }\n\n  /**\n   * Checks the left hand side of an assignment for issues, returns if ok\n   * @param {token} left - the left hand side of the assignment\n   * @param {token=} assignToken - the token for the assignment, used for reporting\n   * @param {object=} options - optional object\n   * @param {boolean} options.allowDestructuring - whether to allow destructuting binding\n   * @returns {boolean} Whether the left hand side is OK\n   */\n  function checkLeftSideAssign(left, assignToken, options) {\n\n    var allowDestructuring = options && options.allowDestructuring;\n\n    assignToken = assignToken || left;\n\n    if (state.option.freeze) {\n      var nativeObject = findNativePrototype(left);\n      if (nativeObject)\n        warning(\"W121\", left, nativeObject);\n    }\n    if (checkPunctuator(left, \"...\")) {\n      left = left.right;\n    }\n\n    if (left.identifier && !left.isMetaProperty) {\n      // reassign also calls modify\n      // but we are specific in order to catch function re-assignment\n      // and globals re-assignment\n      state.funct[\"(scope)\"].block.reassign(left.value, left);\n    }\n\n    if (left.id === \".\") {\n      if (!left.left || left.left.value === \"arguments\" && !state.isStrict()) {\n        warning(\"W143\", assignToken);\n      }\n\n      state.nameStack.set(state.tokens.prev);\n      return true;\n    } else if (left.id === \"{\" || left.id === \"[\") {\n      if (!allowDestructuring || !left.destructAssign) {\n        if (left.id === \"{\" || !left.left) {\n          warning(\"E031\", assignToken);\n        } else if (left.left.value === \"arguments\" && !state.isStrict()) {\n          warning(\"W143\", assignToken);\n        }\n      }\n\n      if (left.id === \"[\") {\n        state.nameStack.set(left.right);\n      }\n\n      return true;\n    } else if (left.identifier && !isReserved(left) && !left.isMetaProperty &&\n      left.value !== \"eval\" && left.value !== \"arguments\") {\n      if (state.funct[\"(scope)\"].labeltype(left.value) === \"exception\") {\n        warning(\"W022\", left);\n      }\n      state.nameStack.set(left);\n      return true;\n    }\n\n    error(\"E031\", assignToken);\n\n    return false;\n  }\n\n  function assignop(s, f, p) {\n    var x = infix(s, typeof f === \"function\" ? f : function(left, that) {\n      that.left = left;\n\n      checkLeftSideAssign(left, that, { allowDestructuring: true });\n\n      that.right = expression(10);\n\n      return that;\n    }, p);\n\n    x.exps = true;\n    x.assign = true;\n    return x;\n  }\n\n\n  function bitwise(s, f, p) {\n    var x = symbol(s, p);\n    reserveName(x);\n    x.infix = true;\n    x.led = (typeof f === \"function\") ? f : function(left) {\n      if (state.option.bitwise) {\n        warning(\"W016\", this, this.id);\n      }\n      this.left = left;\n      this.right = expression(p);\n      return this;\n    };\n    return x;\n  }\n\n  function bitwiseassignop(s) {\n    return assignop(s, function(left, that) {\n      if (state.option.bitwise) {\n        warning(\"W016\", that, that.id);\n      }\n\n      checkLeftSideAssign(left, that);\n\n      that.right = expression(10);\n\n      return that;\n    }, 20);\n  }\n\n  function suffix(s) {\n    var x = symbol(s, 150);\n\n    x.led = function(left) {\n      // this = suffix e.g. \"++\" punctuator\n      // left = symbol operated e.g. \"a\" identifier or \"a.b\" punctuator\n      if (state.option.plusplus) {\n        warning(\"W016\", this, this.id);\n      }\n\n      checkLeftSideAssign(left, this);\n\n      this.left = left;\n      return this;\n    };\n    return x;\n  }\n\n  // prop means that this identifier is that of an object property\n  function optionalidentifier(prop, preserve) {\n    if (!state.tokens.next.identifier) {\n      return;\n    }\n\n    if (!preserve) {\n      advance();\n    }\n\n    var curr = state.tokens.curr;\n    var val  = state.tokens.curr.value;\n\n    if (!isReserved(curr)) {\n      return val;\n    }\n\n    if (prop) {\n      if (state.inES5()) {\n        return val;\n      }\n    }\n\n    warning(\"W024\", state.tokens.curr, state.tokens.curr.id);\n    return val;\n  }\n\n  // prop means that this identifier is that of an object property\n  function identifier(prop) {\n    var i = optionalidentifier(prop, false);\n    if (i) {\n      return i;\n    }\n\n    // parameter destructuring with rest operator\n    if (state.tokens.next.value === \"...\") {\n      if (!state.inES6(true)) {\n        warning(\"W119\", state.tokens.next, \"spread/rest operator\", \"6\");\n      }\n      advance();\n\n      if (checkPunctuator(state.tokens.next, \"...\")) {\n        warning(\"E024\", state.tokens.next, \"...\");\n        while (checkPunctuator(state.tokens.next, \"...\")) {\n          advance();\n        }\n      }\n\n      if (!state.tokens.next.identifier) {\n        warning(\"E024\", state.tokens.curr, state.tokens.next.id);\n        return;\n      }\n\n      return identifier(prop);\n    } else {\n      error(\"E030\", state.tokens.next, state.tokens.next.value);\n\n      // The token should be consumed after a warning is issued so the parser\n      // can continue as though an identifier were found. The semicolon token\n      // should not be consumed in this way so that the parser interprets it as\n      // a statement delimeter;\n      if (state.tokens.next.id !== \";\") {\n        advance();\n      }\n    }\n  }\n\n\n  function reachable(controlToken) {\n    var i = 0, t;\n    if (state.tokens.next.id !== \";\" || controlToken.inBracelessBlock) {\n      return;\n    }\n    for (;;) {\n      do {\n        t = peek(i);\n        i += 1;\n      } while (t.id !== \"(end)\" && t.id === \"(comment)\");\n\n      if (t.reach) {\n        return;\n      }\n      if (t.id !== \"(endline)\") {\n        if (t.id === \"function\") {\n          if (state.option.latedef === true) {\n            warning(\"W026\", t);\n          }\n          break;\n        }\n\n        warning(\"W027\", t, t.value, controlToken.value);\n        break;\n      }\n    }\n  }\n\n  /**\n   * Consume the semicolon that delimits the statement currently being parsed,\n   * emitting relevant warnings/errors as appropriate.\n   *\n   * @param {token} stmt - token describing the statement under consideration\n   */\n  function parseFinalSemicolon(stmt) {\n    if (state.tokens.next.id !== \";\") {\n      // don't complain about unclosed templates / strings\n      if (state.tokens.next.isUnclosed) return advance();\n\n      var sameLine = startLine(state.tokens.next) === state.tokens.curr.line &&\n                     state.tokens.next.id !== \"(end)\";\n      var blockEnd = checkPunctuator(state.tokens.next, \"}\");\n\n      if (sameLine && !blockEnd && !(stmt.id === \"do\" && state.inES6(true))) {\n        errorAt(\"E058\", state.tokens.curr.line, state.tokens.curr.character);\n      } else if (!state.option.asi) {\n        // If this is the last statement in a block that ends on\n        // the same line *and* option lastsemic is on, ignore the warning.\n        // Otherwise, complain about missing semicolon.\n        if (!(blockEnd && sameLine && state.option.lastsemic)) {\n          warningAt(\"W033\", state.tokens.curr.line, state.tokens.curr.character);\n        }\n      }\n    } else {\n      advance(\";\");\n    }\n  }\n\n  function statement() {\n    var i = indent, r, t = state.tokens.next, hasOwnScope = false;\n\n    if (t.id === \";\") {\n      advance(\";\");\n      return;\n    }\n\n    // Is this a labelled statement?\n    var res = isReserved(t);\n\n    // We're being more tolerant here: if someone uses\n    // a FutureReservedWord as a label, we warn but proceed\n    // anyway.\n\n    if (res && t.meta && t.meta.isFutureReservedWord && peek().id === \":\") {\n      warning(\"W024\", t, t.id);\n      res = false;\n    }\n\n    if (t.identifier && !res && peek().id === \":\") {\n      advance();\n      advance(\":\");\n\n      hasOwnScope = true;\n      state.funct[\"(scope)\"].stack();\n      state.funct[\"(scope)\"].block.addBreakLabel(t.value, { token: state.tokens.curr });\n\n      if (!state.tokens.next.labelled && state.tokens.next.value !== \"{\") {\n        warning(\"W028\", state.tokens.next, t.value, state.tokens.next.value);\n      }\n\n      t = state.tokens.next;\n    }\n\n    // Is it a lonely block?\n\n    if (t.id === \"{\") {\n      // Is it a switch case block?\n      //\n      //  switch (foo) {\n      //    case bar: { <= here.\n      //      ...\n      //    }\n      //  }\n      var iscase = (state.funct[\"(verb)\"] === \"case\" && state.tokens.curr.value === \":\");\n      block(true, true, false, false, iscase);\n\n      if (hasOwnScope) {\n        state.funct[\"(scope)\"].unstack();\n      }\n\n      return;\n    }\n\n    // Parse the statement.\n\n    r = expression(0, true);\n\n    if (r && !(r.identifier && r.value === \"function\") &&\n        !(r.type === \"(punctuator)\" && r.left &&\n          r.left.identifier && r.left.value === \"function\")) {\n      if (!state.isStrict() && state.stmtMissingStrict()) {\n        warning(\"E007\");\n      }\n    }\n\n    // Look for the final semicolon.\n\n    if (!t.block) {\n      if (!state.option.expr && (!r || !r.exps)) {\n        warning(\"W030\", state.tokens.curr);\n      } else if (state.option.nonew && r && r.left && r.id === \"(\" && r.left.id === \"new\") {\n        warning(\"W031\", t);\n      }\n      parseFinalSemicolon(t);\n    }\n\n\n    // Restore the indentation.\n\n    indent = i;\n    if (hasOwnScope) {\n      state.funct[\"(scope)\"].unstack();\n    }\n    return r;\n  }\n\n\n  function statements() {\n    var a = [], p;\n\n    while (!state.tokens.next.reach && state.tokens.next.id !== \"(end)\") {\n      if (state.tokens.next.id === \";\") {\n        p = peek();\n\n        if (!p || (p.id !== \"(\" && p.id !== \"[\")) {\n          warning(\"W032\");\n        }\n\n        advance(\";\");\n      } else {\n        a.push(statement());\n      }\n    }\n    return a;\n  }\n\n\n  /*\n   * read all directives\n   */\n  function directives() {\n    var current = state.tokens.next;\n    while (state.tokens.next.id === \"(string)\") {\n      var next = peekIgnoreEOL();\n      if (!isEndOfExpr(current, next)) {\n        break;\n      }\n      current = next;\n\n      advance();\n      var directive = state.tokens.curr.value;\n      if (state.directive[directive] ||\n          (directive === \"use strict\" && state.option.strict === \"implied\")) {\n        warning(\"W034\", state.tokens.curr, directive);\n      }\n\n      // there's no directive negation, so always set to true\n      state.directive[directive] = true;\n\n      parseFinalSemicolon(current);\n    }\n\n    if (state.isStrict()) {\n      state.option.undef = true;\n    }\n  }\n\n\n  /*\n   * Parses a single block. A block is a sequence of statements wrapped in\n   * braces.\n   *\n   * ordinary   - true for everything but function bodies and try blocks.\n   * stmt       - true if block can be a single statement (e.g. in if/for/while).\n   * isfunc     - true if block is a function body\n   * isfatarrow - true if its a body of a fat arrow function\n   * iscase      - true if block is a switch case block\n   */\n  function block(ordinary, stmt, isfunc, isfatarrow, iscase) {\n    var a,\n      b = inblock,\n      old_indent = indent,\n      m,\n      t,\n      d;\n\n    inblock = ordinary;\n\n    t = state.tokens.next;\n\n    var metrics = state.funct[\"(metrics)\"];\n    metrics.nestedBlockDepth += 1;\n    metrics.verifyMaxNestedBlockDepthPerFunction();\n\n    if (state.tokens.next.id === \"{\") {\n      advance(\"{\");\n\n      // create a new block scope\n      state.funct[\"(scope)\"].stack();\n      state.funct[\"(noblockscopedvar)\"] = false;\n\n      if (state.tokens.next.id !== \"}\") {\n        indent += state.option.indent;\n        while (!ordinary && state.tokens.next.from > indent) {\n          indent += state.option.indent;\n        }\n\n        if (isfunc) {\n          m = {};\n          for (d in state.directive) {\n            m[d] = state.directive[d];\n          }\n          directives();\n\n          state.funct[\"(isStrict)\"] = state.isStrict();\n\n          if (state.option.strict && state.funct[\"(context)\"][\"(global)\"]) {\n            if (!m[\"use strict\"] && !state.isStrict()) {\n              warning(\"E007\");\n            }\n          }\n        }\n\n        a = statements();\n\n        metrics.statementCount += a.length;\n\n        indent -= state.option.indent;\n      } else if (isfunc) {\n        // Ensure property is set for functions with empty bodies.\n        state.funct[\"(isStrict)\"] = state.isStrict();\n      }\n\n      advance(\"}\", t);\n\n      if (isfunc) {\n        state.funct[\"(scope)\"].validateParams(isfatarrow);\n        if (m) {\n          state.directive = m;\n        }\n      }\n\n      state.funct[\"(scope)\"].unstack();\n\n      indent = old_indent;\n    } else if (!ordinary) {\n      if (isfunc) {\n        state.funct[\"(scope)\"].stack();\n\n        if (stmt && !isfatarrow && !state.inMoz()) {\n          error(\"W118\", state.tokens.curr, \"function closure expressions\");\n        }\n\n        if (isfatarrow) {\n          state.funct[\"(scope)\"].validateParams(true);\n        }\n\n        expression(10);\n\n        if (state.option.strict && state.funct[\"(context)\"][\"(global)\"]) {\n          if (!state.isStrict()) {\n            warning(\"E007\");\n          }\n        }\n\n        state.funct[\"(scope)\"].unstack();\n      } else {\n        error(\"E021\", state.tokens.next, \"{\", state.tokens.next.value);\n      }\n    } else {\n\n      // check to avoid let declaration not within a block\n      // though is fine inside for loop initializer section\n      state.funct[\"(noblockscopedvar)\"] = state.tokens.next.id !== \"for\";\n      state.funct[\"(scope)\"].stack();\n\n      if (!stmt || state.option.curly) {\n        warning(\"W116\", state.tokens.next, \"{\", state.tokens.next.value);\n      }\n\n      state.tokens.next.inBracelessBlock = true;\n      indent += state.option.indent;\n      // test indentation only if statement is in new line\n      a = [statement()];\n      indent -= state.option.indent;\n\n      state.funct[\"(scope)\"].unstack();\n      delete state.funct[\"(noblockscopedvar)\"];\n    }\n\n    // Don't clear and let it propagate out if it is \"break\", \"return\" or similar in switch case\n    switch (state.funct[\"(verb)\"]) {\n    case \"break\":\n    case \"continue\":\n    case \"return\":\n    case \"throw\":\n      if (iscase) {\n        break;\n      }\n\n      /* falls through */\n    default:\n      state.funct[\"(verb)\"] = null;\n    }\n\n    inblock = b;\n    if (ordinary && state.option.noempty && (!a || a.length === 0)) {\n      warning(\"W035\", state.tokens.prev);\n    }\n    metrics.nestedBlockDepth -= 1;\n    return a;\n  }\n\n\n  function countMember(m) {\n    if (membersOnly && typeof membersOnly[m] !== \"boolean\") {\n      warning(\"W036\", state.tokens.curr, m);\n    }\n    if (typeof member[m] === \"number\") {\n      member[m] += 1;\n    } else {\n      member[m] = 1;\n    }\n  }\n\n  // Build the syntax table by declaring the syntactic elements of the language.\n\n  type(\"(number)\", function() {\n    return this;\n  });\n\n  type(\"(string)\", function() {\n    return this;\n  });\n\n  state.syntax[\"(identifier)\"] = {\n    type: \"(identifier)\",\n    lbp: 0,\n    identifier: true,\n\n    nud: function() {\n      var v = this.value;\n\n      // If this identifier is the lone parameter to a shorthand \"fat arrow\"\n      // function definition, i.e.\n      //\n      //     x => x;\n      //\n      // ...it should not be considered as a variable in the current scope. It\n      // will be added to the scope of the new function when the next token is\n      // parsed, so it can be safely ignored for now.\n      if (state.tokens.next.id === \"=>\") {\n        return this;\n      }\n\n      if (!state.funct[\"(comparray)\"].check(v)) {\n        state.funct[\"(scope)\"].block.use(v, state.tokens.curr);\n      }\n      return this;\n    },\n\n    led: function() {\n      error(\"E033\", state.tokens.next, state.tokens.next.value);\n    }\n  };\n\n  var baseTemplateSyntax = {\n    identifier: false,\n    template: true,\n  };\n  state.syntax[\"(template)\"] = _.extend({\n    lbp: 155,\n    type: \"(template)\",\n    nud: doTemplateLiteral,\n    led: doTemplateLiteral,\n    noSubst: false\n  }, baseTemplateSyntax);\n\n  state.syntax[\"(template middle)\"] = _.extend({\n    lbp: 0,\n    type: \"(template middle)\",\n    noSubst: false\n  }, baseTemplateSyntax);\n\n  state.syntax[\"(template tail)\"] = _.extend({\n    lbp: 0,\n    type: \"(template tail)\",\n    tail: true,\n    noSubst: false\n  }, baseTemplateSyntax);\n\n  state.syntax[\"(no subst template)\"] = _.extend({\n    lbp: 155,\n    type: \"(template)\",\n    nud: doTemplateLiteral,\n    led: doTemplateLiteral,\n    noSubst: true,\n    tail: true // mark as tail, since it's always the last component\n  }, baseTemplateSyntax);\n\n  type(\"(regexp)\", function() {\n    return this;\n  });\n\n  // ECMAScript parser\n\n  delim(\"(endline)\");\n  (function(x) {\n    x.line = x.from = 0;\n  })(delim(\"(begin)\"));\n  delim(\"(end)\").reach = true;\n  delim(\"(error)\").reach = true;\n  delim(\"}\").reach = true;\n  delim(\")\");\n  delim(\"]\");\n  delim(\"\\\"\").reach = true;\n  delim(\"'\").reach = true;\n  delim(\";\");\n  delim(\":\").reach = true;\n  delim(\"#\");\n\n  reserve(\"else\");\n  reserve(\"case\").reach = true;\n  reserve(\"catch\");\n  reserve(\"default\").reach = true;\n  reserve(\"finally\");\n  reserve(\"true\", function() { return this; });\n  reserve(\"false\", function() { return this; });\n  reservevar(\"null\");\n  reservevar(\"this\", function(x) {\n    if (state.isStrict() && !isMethod() &&\n        !state.option.validthis && ((state.funct[\"(statement)\"] &&\n        state.funct[\"(name)\"].charAt(0) > \"Z\") || state.funct[\"(global)\"])) {\n      warning(\"W040\", x);\n    }\n  });\n\n  assignop(\"=\", \"assign\", 20);\n  assignop(\"+=\", \"assignadd\", 20);\n  assignop(\"-=\", \"assignsub\", 20);\n  assignop(\"*=\", \"assignmult\", 20);\n  assignop(\"/=\", \"assigndiv\", 20).nud = function() {\n    error(\"E014\");\n  };\n  assignop(\"%=\", \"assignmod\", 20);\n\n  bitwiseassignop(\"&=\");\n  bitwiseassignop(\"|=\");\n  bitwiseassignop(\"^=\");\n  bitwiseassignop(\"<<=\");\n  bitwiseassignop(\">>=\");\n  bitwiseassignop(\">>>=\");\n  infix(\",\", function(left, that) {\n    var expr;\n    that.exprs = [left];\n\n    if (state.option.nocomma) {\n      warning(\"W127\");\n    }\n\n    if (!parseComma({ peek: true })) {\n      return that;\n    }\n    while (true) {\n      if (!(expr = expression(10))) {\n        break;\n      }\n      that.exprs.push(expr);\n      if (state.tokens.next.value !== \",\" || !parseComma()) {\n        break;\n      }\n    }\n    return that;\n  }, 10, true);\n\n  infix(\"?\", function(left, that) {\n    increaseComplexityCount();\n    that.left = left;\n    that.right = expression(10);\n    advance(\":\");\n    expression(10);\n    return that;\n  }, 30);\n\n  var orPrecendence = 40;\n  infix(\"||\", function(left, that) {\n    increaseComplexityCount();\n    that.left = left;\n    that.right = expression(orPrecendence);\n    return that;\n  }, orPrecendence);\n  infix(\"&&\", \"and\", 50);\n  bitwise(\"|\", \"bitor\", 70);\n  bitwise(\"^\", \"bitxor\", 80);\n  bitwise(\"&\", \"bitand\", 90);\n  relation(\"==\", function(left, right) {\n    var eqnull = state.option.eqnull &&\n      ((left && left.value) === \"null\" || (right && right.value) === \"null\");\n\n    switch (true) {\n      case !eqnull && state.option.eqeqeq:\n        this.from = this.character;\n        warning(\"W116\", this, \"===\", \"==\");\n        break;\n      case isTypoTypeof(right, left, state):\n        warning(\"W122\", this, right.value);\n        break;\n      case isTypoTypeof(left, right, state):\n        warning(\"W122\", this, left.value);\n        break;\n    }\n\n    return this;\n  });\n  relation(\"===\", function(left, right) {\n    if (isTypoTypeof(right, left, state)) {\n      warning(\"W122\", this, right.value);\n    } else if (isTypoTypeof(left, right, state)) {\n      warning(\"W122\", this, left.value);\n    }\n    return this;\n  });\n  relation(\"!=\", function(left, right) {\n    var eqnull = state.option.eqnull &&\n        ((left && left.value) === \"null\" || (right && right.value) === \"null\");\n\n    if (!eqnull && state.option.eqeqeq) {\n      this.from = this.character;\n      warning(\"W116\", this, \"!==\", \"!=\");\n    } else if (isTypoTypeof(right, left, state)) {\n      warning(\"W122\", this, right.value);\n    } else if (isTypoTypeof(left, right, state)) {\n      warning(\"W122\", this, left.value);\n    }\n    return this;\n  });\n  relation(\"!==\", function(left, right) {\n    if (isTypoTypeof(right, left, state)) {\n      warning(\"W122\", this, right.value);\n    } else if (isTypoTypeof(left, right, state)) {\n      warning(\"W122\", this, left.value);\n    }\n    return this;\n  });\n  relation(\"<\");\n  relation(\">\");\n  relation(\"<=\");\n  relation(\">=\");\n  bitwise(\"<<\", \"shiftleft\", 120);\n  bitwise(\">>\", \"shiftright\", 120);\n  bitwise(\">>>\", \"shiftrightunsigned\", 120);\n  infix(\"in\", \"in\", 120);\n  infix(\"instanceof\", function(left, token) {\n    var right;\n    var scope = state.funct[\"(scope)\"];\n    token.left = left;\n    token.right = right = expression(120);\n\n    // This condition reflects a syntax error which will be reported by the\n    // `expression` function.\n    if (!right) {\n      return token;\n    }\n\n    if (right.id === \"(number)\" ||\n        right.id === \"(string)\" ||\n        right.value === \"null\" ||\n        (right.value === \"undefined\" && !scope.has(\"undefined\")) ||\n        right.arity === \"unary\" ||\n        right.id === \"{\" ||\n        (right.id === \"[\" && !right.right) ||\n        right.id === \"(regexp)\" ||\n        (right.id === \"(template)\" && !right.tag)) {\n      error(\"E060\");\n    }\n\n    if (right.id === \"function\") {\n      warning(\"W139\");\n    }\n\n    return token;\n  }, 120);\n  infix(\"+\", function(left, that) {\n    var right;\n    that.left = left;\n    that.right = right = expression(130);\n\n    if (left && right && left.id === \"(string)\" && right.id === \"(string)\") {\n      left.value += right.value;\n      left.character = right.character;\n      if (!state.option.scripturl && reg.javascriptURL.test(left.value)) {\n        warning(\"W050\", left);\n      }\n      return left;\n    }\n\n    return that;\n  }, 130);\n  prefix(\"+\", \"num\");\n  infix(\"-\", \"sub\", 130);\n  prefix(\"-\", \"neg\");\n  infix(\"*\", \"mult\", 140);\n  infix(\"/\", \"div\", 140);\n  infix(\"%\", \"mod\", 140);\n\n  suffix(\"++\");\n  prefix(\"++\", \"preinc\");\n  state.syntax[\"++\"].exps = true;\n  state.syntax[\"++\"].ltBoundary = \"before\";\n\n  suffix(\"--\");\n  prefix(\"--\", \"predec\");\n  state.syntax[\"--\"].exps = true;\n  state.syntax[\"--\"].ltBoundary = \"before\";\n\n  prefix(\"delete\", function() {\n    var p = expression(10);\n    if (!p) {\n      return this;\n    }\n\n    if (p.id !== \".\" && p.id !== \"[\") {\n      warning(\"W051\");\n    }\n    this.first = p;\n\n    // The `delete` operator accepts unresolvable references when not in strict\n    // mode, so the operand may be undefined.\n    if (p.identifier && !state.isStrict()) {\n      p.forgiveUndef = true;\n    }\n    return this;\n  }).exps = true;\n\n  prefix(\"~\", function() {\n    if (state.option.bitwise) {\n      warning(\"W016\", this, \"~\");\n    }\n    this.arity = \"unary\";\n    this.right = expression(150);\n    return this;\n  });\n\n  prefix(\"...\", function() {\n    if (!state.inES6(true)) {\n      warning(\"W119\", this, \"spread/rest operator\", \"6\");\n    }\n\n    // TODO: Allow all AssignmentExpression\n    // once parsing permits.\n    //\n    // How to handle eg. number, boolean when the built-in\n    // prototype of may have an @@iterator definition?\n    //\n    // Number.prototype[Symbol.iterator] = function * () {\n    //   yield this.valueOf();\n    // };\n    //\n    // var a = [ ...1 ];\n    // console.log(a); // [1];\n    //\n    // for (let n of [...10]) {\n    //    console.log(n);\n    // }\n    // // 10\n    //\n    //\n    // Boolean.prototype[Symbol.iterator] = function * () {\n    //   yield this.valueOf();\n    // };\n    //\n    // var a = [ ...true ];\n    // console.log(a); // [true];\n    //\n    // for (let n of [...false]) {\n    //    console.log(n);\n    // }\n    // // false\n    //\n    if (!state.tokens.next.identifier &&\n        state.tokens.next.type !== \"(string)\" &&\n          !checkPunctuators(state.tokens.next, [\"[\", \"(\"])) {\n\n      error(\"E030\", state.tokens.next, state.tokens.next.value);\n    }\n    this.right = expression(150);\n    return this;\n  });\n\n  prefix(\"!\", function() {\n    this.arity = \"unary\";\n    this.right = expression(150);\n\n    if (!this.right) { // '!' followed by nothing? Give up.\n      quit(\"E041\", this);\n    }\n\n    if (bang[this.right.id] === true) {\n      warning(\"W018\", this, \"!\");\n    }\n    return this;\n  });\n\n  prefix(\"typeof\", (function() {\n    var p = expression(150);\n    this.first = this.right = p;\n\n    if (!p) { // 'typeof' followed by nothing? Give up.\n      quit(\"E041\", this);\n    }\n\n    // The `typeof` operator accepts unresolvable references, so the operand\n    // may be undefined.\n    if (p.identifier) {\n      p.forgiveUndef = true;\n    }\n    return this;\n  }));\n  prefix(\"new\", function() {\n    var mp = metaProperty(\"target\", function() {\n      if (!state.inES6(true)) {\n        warning(\"W119\", state.tokens.prev, \"new.target\", \"6\");\n      }\n      var inFunction, c = state.funct;\n      while (c) {\n        inFunction = !c[\"(global)\"];\n        if (!c[\"(arrow)\"]) { break; }\n        c = c[\"(context)\"];\n      }\n      if (!inFunction) {\n        warning(\"W136\", state.tokens.prev, \"new.target\");\n      }\n    });\n    if (mp) { return mp; }\n\n    var c = expression(155), i;\n    if (c && c.id !== \"function\") {\n      if (c.identifier) {\n        switch (c.value) {\n        case \"Number\":\n        case \"String\":\n        case \"Boolean\":\n        case \"Math\":\n        case \"JSON\":\n          warning(\"W053\", state.tokens.prev, c.value);\n          break;\n        case \"Symbol\":\n          if (state.inES6()) {\n            warning(\"W053\", state.tokens.prev, c.value);\n          }\n          break;\n        case \"Function\":\n          if (!state.option.evil) {\n            warning(\"W054\");\n          }\n          break;\n        case \"Date\":\n        case \"RegExp\":\n        case \"this\":\n          break;\n        default:\n          if (c.id !== \"function\") {\n            i = c.value.substr(0, 1);\n            if (state.option.newcap && (i < \"A\" || i > \"Z\") &&\n              !state.funct[\"(scope)\"].isPredefined(c.value)) {\n              warning(\"W055\", state.tokens.curr);\n            }\n          }\n        }\n      } else {\n        if (c.id !== \".\" && c.id !== \"[\" && c.id !== \"(\") {\n          warning(\"W056\", state.tokens.curr);\n        }\n      }\n    } else {\n      if (!state.option.supernew)\n        warning(\"W057\", this);\n    }\n    if (state.tokens.next.id !== \"(\" && !state.option.supernew) {\n      warning(\"W058\", state.tokens.curr, state.tokens.curr.value);\n    }\n    this.first = this.right = c;\n    return this;\n  });\n  state.syntax[\"new\"].exps = true;\n\n  prefix(\"void\").exps = true;\n\n  infix(\".\", function(left, that) {\n    var m = identifier(true);\n\n    if (typeof m === \"string\") {\n      countMember(m);\n    }\n\n    that.left = left;\n    that.right = m;\n\n    if (m && m === \"hasOwnProperty\" && state.tokens.next.value === \"=\") {\n      warning(\"W001\");\n    }\n\n    if (left && left.value === \"arguments\" && (m === \"callee\" || m === \"caller\")) {\n      if (state.option.noarg)\n        warning(\"W059\", left, m);\n      else if (state.isStrict())\n        error(\"E008\");\n    } else if (!state.option.evil && left && left.value === \"document\" &&\n        (m === \"write\" || m === \"writeln\")) {\n      warning(\"W060\", left);\n    }\n\n    if (!state.option.evil && (m === \"eval\" || m === \"execScript\")) {\n      if (isGlobalEval(left, state)) {\n        warning(\"W061\");\n      }\n    }\n\n    return that;\n  }, 160, true);\n\n  infix(\"(\", function(left, that) {\n    if (state.option.immed && left && !left.immed && left.id === \"function\") {\n      warning(\"W062\");\n    }\n\n    if (state.option.asi && checkPunctuators(state.tokens.prev, [\")\", \"]\"]) &&\n      state.tokens.prev.line !== startLine(state.tokens.curr)) {\n      warning(\"W014\", state.tokens.curr, state.tokens.curr.id);\n    }\n\n    var n = 0;\n    var p = [];\n\n    if (left) {\n      if (left.type === \"(identifier)\") {\n        if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) {\n          if (\"Array Number String Boolean Date Object Error Symbol\".indexOf(left.value) === -1) {\n            if (left.value === \"Math\") {\n              warning(\"W063\", left);\n            } else if (state.option.newcap) {\n              warning(\"W064\", left);\n            }\n          }\n        }\n      }\n    }\n\n    if (state.tokens.next.id !== \")\") {\n      for (;;) {\n        p[p.length] = expression(10);\n        n += 1;\n        if (state.tokens.next.id !== \",\") {\n          break;\n        }\n        parseComma();\n      }\n    }\n\n    advance(\")\");\n\n    if (typeof left === \"object\") {\n      if (!state.inES5() && left.value === \"parseInt\" && n === 1) {\n        warning(\"W065\", state.tokens.curr);\n      }\n      if (!state.option.evil) {\n        if (left.value === \"eval\" || left.value === \"Function\" ||\n            left.value === \"execScript\") {\n          warning(\"W061\", left);\n\n          // This conditional expression was initially implemented with a typo\n          // which prevented the branch's execution in all cases. While\n          // enabling the code will produce behavior that is consistent with\n          // the other forms of code evaluation that follow, such a change is\n          // also technically incompatable with prior versions of JSHint (due\n          // to the fact that the behavior was never formally documented). This\n          // branch should be enabled as part of a major release.\n          //if (p[0] && p[0].id === \"(string)\") {\n          //  addEvalCode(left, p[0]);\n          //}\n        } else if (p[0] && p[0].id === \"(string)\" &&\n             (left.value === \"setTimeout\" ||\n            left.value === \"setInterval\")) {\n          warning(\"W066\", left);\n          addEvalCode(left, p[0]);\n\n        // window.setTimeout/setInterval\n        } else if (p[0] && p[0].id === \"(string)\" &&\n             left.value === \".\" &&\n             left.left.value === \"window\" &&\n             (left.right === \"setTimeout\" ||\n            left.right === \"setInterval\")) {\n          warning(\"W066\", left);\n          addEvalCode(left, p[0]);\n        }\n      }\n      if (!left.identifier && left.id !== \".\" && left.id !== \"[\" && left.id !== \"=>\" &&\n          left.id !== \"(\" && left.id !== \"&&\" && left.id !== \"||\" && left.id !== \"?\" &&\n          !(state.inES6() && left[\"(name)\"])) {\n        warning(\"W067\", that);\n      }\n    }\n\n    that.left = left;\n    return that;\n  }, 155, true).exps = true;\n\n  prefix(\"(\", function(rbp) {\n    var pn = state.tokens.next, pn1, i = -1;\n    var ret, triggerFnExpr, first, last;\n    var parens = 1;\n    var opening = state.tokens.curr;\n    var preceeding = state.tokens.prev;\n    var isNecessary = !state.option.singleGroups;\n\n    do {\n      if (pn.value === \"(\") {\n        parens += 1;\n      } else if (pn.value === \")\") {\n        parens -= 1;\n      }\n\n      i += 1;\n      pn1 = pn;\n      pn = peek(i);\n    } while (!(parens === 0 && pn1.value === \")\") && pn.type !== \"(end)\");\n\n    if (state.tokens.next.id === \"function\") {\n      triggerFnExpr = state.tokens.next.immed = true;\n    }\n\n    // If the balanced grouping operator is followed by a \"fat arrow\", the\n    // current token marks the beginning of a \"fat arrow\" function and parsing\n    // should proceed accordingly.\n    if (pn.value === \"=>\") {\n      return doFunction({ type: \"arrow\", parsedOpening: true });\n    }\n\n    var exprs = [];\n\n    if (state.tokens.next.id !== \")\") {\n      for (;;) {\n        exprs.push(expression(10));\n\n        if (state.tokens.next.id !== \",\") {\n          break;\n        }\n\n        if (state.option.nocomma) {\n          warning(\"W127\");\n        }\n\n        parseComma();\n      }\n    }\n\n    advance(\")\", this);\n    if (state.option.immed && exprs[0] && exprs[0].id === \"function\") {\n      if (state.tokens.next.id !== \"(\" &&\n        state.tokens.next.id !== \".\" && state.tokens.next.id !== \"[\") {\n        warning(\"W068\", this);\n      }\n    }\n\n    if (!exprs.length) {\n      return;\n    }\n    if (exprs.length > 1) {\n      ret = Object.create(state.syntax[\",\"]);\n      ret.exprs = exprs;\n\n      first = exprs[0];\n      last = exprs[exprs.length - 1];\n    } else {\n      ret = first = last = exprs[0];\n\n      if (!isNecessary) {\n        isNecessary =\n          // Used to distinguish from an ExpressionStatement which may not\n          // begin with the `{` and `function` tokens\n          (opening.beginsStmt && (ret.id === \"{\" || triggerFnExpr || isFunctor(ret))) ||\n          // Used to signal that a function expression is being supplied to\n          // some other operator.\n          (triggerFnExpr &&\n            // For parenthesis wrapping a function expression to be considered\n            // necessary, the grouping operator should be the left-hand-side of\n            // some other operator--either within the parenthesis or directly\n            // following them.\n            (!isEndOfExpr() || state.tokens.prev.id !== \"}\")) ||\n          // Used to demarcate an arrow function as the left-hand side of some\n          // operator.\n          (isFunctor(ret) && !isEndOfExpr()) ||\n          // Used as the return value of a single-statement arrow function\n          (ret.id === \"{\" && preceeding.id === \"=>\") ||\n          // Used to delineate an integer number literal from a dereferencing\n          // punctuator (otherwise interpreted as a decimal point)\n          (ret.type === \"(number)\" &&\n            checkPunctuator(pn, \".\") && /^\\d+$/.test(ret.value)) ||\n          // Used to wrap object destructuring assignment\n          (opening.beginsStmt && ret.id === \"=\" && ret.left.id === \"{\");\n      }\n    }\n\n    if (ret) {\n      // The operator may be necessary to override the default binding power of\n      // neighboring operators (whenever there is an operator in use within the\n      // first expression *or* the current group contains multiple expressions)\n      if (!isNecessary && (isOperator(first) || ret.exprs)) {\n        isNecessary =\n          (rbp > first.lbp) ||\n          (rbp > 0 && rbp === first.lbp) ||\n          (!isEndOfExpr() && last.lbp < state.tokens.next.lbp);\n      }\n\n      if (!isNecessary) {\n        warning(\"W126\", opening);\n      }\n\n      ret.paren = true;\n    }\n\n    return ret;\n  });\n\n  application(\"=>\");\n\n  infix(\"[\", function(left, that) {\n    var e, s, canUseDot;\n\n    if (state.option.asi && checkPunctuators(state.tokens.prev, [\")\", \"]\"]) &&\n      state.tokens.prev.line !== startLine(state.tokens.curr)) {\n      warning(\"W014\", state.tokens.curr, state.tokens.curr.id);\n    }\n\n    e = expression(10);\n\n    if (e && e.type === \"(string)\") {\n      if (!state.option.evil && (e.value === \"eval\" || e.value === \"execScript\")) {\n        if (isGlobalEval(left, state)) {\n          warning(\"W061\");\n        }\n      }\n\n      countMember(e.value);\n      if (!state.option.sub && reg.identifier.test(e.value)) {\n        s = state.syntax[e.value];\n\n        if (s) {\n          canUseDot = !isReserved(s);\n        } else {\n          // This branch exists to preserve legacy behavior with version 2.9.5\n          // and earlier. In those releases, `eval` and `arguments` were\n          // incorrectly interpreted as reserved keywords, so Member\n          // Expressions such as `object[\"eval\"]` did not trigger warning W069.\n          //\n          // TODO: Remove in JSHint 3\n          canUseDot = e.value !== \"eval\" && e.value !== \"arguments\";\n        }\n\n        if (canUseDot) {\n          warning(\"W069\", state.tokens.prev, e.value);\n        }\n      }\n    }\n    advance(\"]\", that);\n\n    if (e && e.value === \"hasOwnProperty\" && state.tokens.next.value === \"=\") {\n      warning(\"W001\");\n    }\n\n    that.left = left;\n    that.right = e;\n    return that;\n  }, 160, true);\n\n  function comprehensiveArrayExpression() {\n    var res = {};\n    res.exps = true;\n    state.funct[\"(comparray)\"].stack();\n\n    // Handle reversed for expressions, used in spidermonkey\n    var reversed = false;\n    if (state.tokens.next.value !== \"for\") {\n      reversed = true;\n      if (!state.inMoz()) {\n        warning(\"W116\", state.tokens.next, \"for\", state.tokens.next.value);\n      }\n      state.funct[\"(comparray)\"].setState(\"use\");\n      res.right = expression(10);\n    }\n\n    advance(\"for\");\n    if (state.tokens.next.value === \"each\") {\n      advance(\"each\");\n      if (!state.inMoz()) {\n        warning(\"W118\", state.tokens.curr, \"for each\");\n      }\n    }\n    advance(\"(\");\n    state.funct[\"(comparray)\"].setState(\"define\");\n    res.left = expression(130);\n    if (_.includes([\"in\", \"of\"], state.tokens.next.value)) {\n      advance();\n    } else {\n      error(\"E045\", state.tokens.curr);\n    }\n    state.funct[\"(comparray)\"].setState(\"generate\");\n    expression(10);\n\n    advance(\")\");\n    if (state.tokens.next.value === \"if\") {\n      advance(\"if\");\n      advance(\"(\");\n      state.funct[\"(comparray)\"].setState(\"filter\");\n      expression(10);\n      advance(\")\");\n    }\n\n    if (!reversed) {\n      state.funct[\"(comparray)\"].setState(\"use\");\n      res.right = expression(10);\n    }\n\n    advance(\"]\");\n    state.funct[\"(comparray)\"].unstack();\n    return res;\n  }\n\n  prefix(\"[\", function() {\n    var blocktype = lookupBlockType();\n    if (blocktype.isCompArray) {\n      if (!state.option.esnext && !state.inMoz()) {\n        warning(\"W118\", state.tokens.curr, \"array comprehension\");\n      }\n      return comprehensiveArrayExpression();\n    } else if (blocktype.isDestAssign) {\n      this.destructAssign = destructuringPattern({ openingParsed: true, assignment: true });\n      return this;\n    }\n    var b = state.tokens.curr.line !== startLine(state.tokens.next);\n    this.first = [];\n    if (b) {\n      indent += state.option.indent;\n      if (state.tokens.next.from === indent + state.option.indent) {\n        indent += state.option.indent;\n      }\n    }\n    while (state.tokens.next.id !== \"(end)\") {\n      while (state.tokens.next.id === \",\") {\n        if (!state.option.elision) {\n          if (!state.inES5()) {\n            // Maintain compat with old options --- ES5 mode without\n            // elision=true will warn once per comma\n            warning(\"W070\");\n          } else {\n            warning(\"W128\");\n            do {\n              advance(\",\");\n            } while (state.tokens.next.id === \",\");\n            continue;\n          }\n        }\n        advance(\",\");\n      }\n\n      if (state.tokens.next.id === \"]\") {\n        break;\n      }\n\n      this.first.push(expression(10));\n      if (state.tokens.next.id === \",\") {\n        parseComma({ allowTrailing: true });\n        if (state.tokens.next.id === \"]\" && !state.inES5()) {\n          warning(\"W070\", state.tokens.curr);\n          break;\n        }\n      } else {\n        if (state.option.trailingcomma && state.inES5()) {\n          warningAt(\"W140\", state.tokens.curr.line, state.tokens.curr.character);\n        }\n        break;\n      }\n    }\n    if (b) {\n      indent -= state.option.indent;\n    }\n    advance(\"]\", this);\n    return this;\n  });\n\n\n  function isMethod() {\n    return state.funct[\"(statement)\"] && state.funct[\"(statement)\"].type === \"class\" ||\n           state.funct[\"(context)\"] && state.funct[\"(context)\"][\"(verb)\"] === \"class\";\n  }\n\n\n  function isPropertyName(token) {\n    return token.identifier || token.id === \"(string)\" || token.id === \"(number)\";\n  }\n\n\n  function propertyName(preserveOrToken) {\n    var id;\n    var preserve = true;\n    if (typeof preserveOrToken === \"object\") {\n      id = preserveOrToken;\n    } else {\n      preserve = preserveOrToken;\n      id = optionalidentifier(true, preserve);\n    }\n\n    if (!id) {\n      if (state.tokens.next.id === \"(string)\") {\n        id = state.tokens.next.value;\n        if (!preserve) {\n          advance();\n        }\n      } else if (state.tokens.next.id === \"(number)\") {\n        id = state.tokens.next.value.toString();\n        if (!preserve) {\n          advance();\n        }\n      }\n    } else if (typeof id === \"object\") {\n      if (id.id === \"(string)\" || id.id === \"(identifier)\") id = id.value;\n      else if (id.id === \"(number)\") id = id.value.toString();\n    }\n\n    if (id === \"hasOwnProperty\") {\n      warning(\"W001\");\n    }\n\n    return id;\n  }\n\n  /**\n   * @param {Object} [options]\n   * @param {token} [options.loneArg] The argument to the function in cases\n   *                                  where it was defined using the\n   *                                  single-argument shorthand.\n   * @param {bool} [options.parsedOpening] Whether the opening parenthesis has\n   *                                       already been parsed.\n   * @returns {{ arity: number, params: Array.<string>}}\n   */\n  function functionparams(options) {\n    var next;\n    var paramsIds = [];\n    var ident;\n    var tokens = [];\n    var t;\n    var pastDefault = false;\n    var pastRest = false;\n    var arity = 0;\n    var loneArg = options && options.loneArg;\n\n    if (loneArg && loneArg.identifier === true) {\n      state.funct[\"(scope)\"].addParam(loneArg.value, loneArg);\n      return { arity: 1, params: [ loneArg.value ] };\n    }\n\n    next = state.tokens.next;\n\n    if (!options || !options.parsedOpening) {\n      advance(\"(\");\n    }\n\n    if (state.tokens.next.id === \")\") {\n      advance(\")\");\n      return;\n    }\n\n    function addParam(addParamArgs) {\n      state.funct[\"(scope)\"].addParam.apply(state.funct[\"(scope)\"], addParamArgs);\n    }\n\n    for (;;) {\n      arity++;\n      // are added to the param scope\n      var currentParams = [];\n\n      if (_.includes([\"{\", \"[\"], state.tokens.next.id)) {\n        tokens = destructuringPattern();\n        for (t in tokens) {\n          t = tokens[t];\n          if (t.id) {\n            paramsIds.push(t.id);\n            currentParams.push([t.id, t.token]);\n          }\n        }\n      } else {\n        if (checkPunctuator(state.tokens.next, \"...\")) pastRest = true;\n        ident = identifier();\n        if (ident) {\n          paramsIds.push(ident);\n          currentParams.push([ident, state.tokens.curr]);\n        } else {\n          // Skip invalid parameter.\n          while (!checkPunctuators(state.tokens.next, [\",\", \")\"])) advance();\n        }\n      }\n\n      // It is valid to have a regular argument after a default argument\n      // since undefined can be used for missing parameters. Still warn as it is\n      // a possible code smell.\n      if (pastDefault) {\n        if (state.tokens.next.id !== \"=\") {\n          error(\"W138\", state.tokens.curr);\n        }\n      }\n      if (state.tokens.next.id === \"=\") {\n        if (!state.inES6()) {\n          warning(\"W119\", state.tokens.next, \"default parameters\", \"6\");\n        }\n\n        if (pastRest) {\n          error(\"E062\", state.tokens.next);\n        }\n\n        advance(\"=\");\n        pastDefault = true;\n        expression(10);\n      }\n\n      // now we have evaluated the default expression, add the variable to the param scope\n      currentParams.forEach(addParam);\n\n      if (state.tokens.next.id === \",\") {\n        if (pastRest) {\n          warning(\"W131\", state.tokens.next);\n        }\n        parseComma();\n      } else {\n        advance(\")\", next);\n        return { arity: arity, params: paramsIds };\n      }\n    }\n  }\n\n  function functor(name, token, overwrites) {\n    var funct = {\n      \"(name)\"      : name,\n      \"(breakage)\"  : 0,\n      \"(loopage)\"   : 0,\n      // The strictness of the function body is tracked via a dedicated\n      // property (as opposed to via the global `state` object) so that the\n      // value can be referenced after the body has been fully parsed (i.e.\n      // when validating the identifier used in function declarations and\n      // function expressions).\n      \"(isStrict)\"  : \"unknown\",\n\n      \"(global)\"    : false,\n\n      \"(line)\"      : null,\n      \"(character)\" : null,\n      \"(metrics)\"   : null,\n      \"(statement)\" : null,\n      \"(context)\"   : null,\n      \"(scope)\"     : null,\n      \"(comparray)\" : null,\n      \"(generator)\" : null,\n      \"(arrow)\"     : null,\n      \"(params)\"    : null\n    };\n\n    if (token) {\n      _.extend(funct, {\n        \"(line)\"     : token.line,\n        \"(character)\": token.character,\n        \"(metrics)\"  : createMetrics(token)\n      });\n    }\n\n    _.extend(funct, overwrites);\n\n    if (funct[\"(context)\"]) {\n      funct[\"(scope)\"] = funct[\"(context)\"][\"(scope)\"];\n      funct[\"(comparray)\"]  = funct[\"(context)\"][\"(comparray)\"];\n    }\n\n    return funct;\n  }\n\n  function isFunctor(token) {\n    return \"(scope)\" in token;\n  }\n\n  /**\n   * Determine if the parser has begun parsing executable code.\n   *\n   * @param {Token} funct - The current \"functor\" token\n   *\n   * @returns {boolean}\n   */\n  function hasParsedCode(funct) {\n    return funct[\"(global)\"] && !funct[\"(verb)\"];\n  }\n\n  /**\n   * This function is used as both a null-denotation method *and* a\n   * left-denotation method, meaning the first parameter is overloaded.\n   */\n  function doTemplateLiteral(leftOrRbp) {\n    // ASSERT: this.type === \"(template)\"\n    // jshint validthis: true\n    var ctx = this.context;\n    var noSubst = this.noSubst;\n    var depth = this.depth;\n    var left = typeof leftOrRbp === \"number\" ? null : leftOrRbp;\n\n    if (!noSubst) {\n      while (!end()) {\n        if (!state.tokens.next.template || state.tokens.next.depth > depth) {\n          expression(0); // should probably have different rbp?\n        } else {\n          // skip template start / middle\n          advance();\n        }\n      }\n    }\n\n    return {\n      id: \"(template)\",\n      type: \"(template)\",\n      tag: left\n    };\n\n    function end() {\n      if (state.tokens.curr.template && state.tokens.curr.tail &&\n          state.tokens.curr.context === ctx) return true;\n      var complete = (state.tokens.next.template && state.tokens.next.tail &&\n                      state.tokens.next.context === ctx);\n      if (complete) advance();\n      return complete || state.tokens.next.isUnclosed;\n    }\n  }\n\n  /**\n   * @param {Object} [options]\n   * @param {string} [options.name] The identifier belonging to the function (if\n   *                                any)\n   * @param {token} [options.statement] The statement that triggered creation\n   *                                    of the current function.\n   * @param {string} [options.type] If specified, either \"generator\" or \"arrow\"\n   * @param {token} [options.loneArg] The argument to the function in cases\n   *                                  where it was defined using the\n   *                                  single-argument shorthand\n   * @param {bool} [options.parsedOpening] Whether the opening parenthesis has\n   *                                       already been parsed\n   * @param {string} [options.classExprBinding] Define a function with this\n   *                                            identifier in the new function's\n   *                                            scope, mimicking the bahavior of\n   *                                            class expression names within\n   *                                            the body of member functions.\n   */\n  function doFunction(options) {\n    var f, token, name, statement, classExprBinding, isGenerator, isArrow,\n      isMethod, ignoreLoopFunc;\n    var oldOption = state.option;\n    var oldIgnored = state.ignored;\n\n    if (options) {\n      name = options.name;\n      statement = options.statement;\n      classExprBinding = options.classExprBinding;\n      isGenerator = options.type === \"generator\";\n      isArrow = options.type === \"arrow\";\n      isMethod = options.isMethod;\n      ignoreLoopFunc = options.ignoreLoopFunc;\n    }\n\n    state.option = Object.create(state.option);\n    state.ignored = Object.create(state.ignored);\n\n    state.funct = functor(name || state.nameStack.infer(), state.tokens.next, {\n      \"(statement)\": statement,\n      \"(context)\":   state.funct,\n      \"(arrow)\":     isArrow,\n      \"(method)\":    isMethod,\n      \"(generator)\": isGenerator\n    });\n\n    f = state.funct;\n    token = state.tokens.curr;\n\n    functions.push(state.funct);\n\n    // So that the function is available to itself and referencing itself is not\n    // seen as a closure, add the function name to a new scope, but do not\n    // test for unused (unused: false)\n    // it is a new block scope so that params can override it, it can be block scoped\n    // but declarations inside the function don't cause already declared error\n    state.funct[\"(scope)\"].stack(\"functionouter\");\n    var internallyAccessibleName = name || classExprBinding;\n    if (internallyAccessibleName) {\n      state.funct[\"(scope)\"].block.add(internallyAccessibleName,\n        classExprBinding ? \"class\" : \"function\", state.tokens.curr, false);\n    }\n\n    if (!isArrow) {\n      state.funct[\"(scope)\"].funct.add(\"arguments\", \"var\", token, false);\n    }\n\n    // create the param scope (params added in functionparams)\n    state.funct[\"(scope)\"].stack(\"functionparams\");\n\n    var paramsInfo = functionparams(options);\n\n    if (paramsInfo) {\n      state.funct[\"(params)\"] = paramsInfo.params;\n      state.funct[\"(metrics)\"].arity = paramsInfo.arity;\n      state.funct[\"(metrics)\"].verifyMaxParametersPerFunction();\n    } else {\n      state.funct[\"(metrics)\"].arity = 0;\n    }\n\n    if (isArrow) {\n      if (!state.inES6(true)) {\n        warning(\"W119\", state.tokens.curr, \"arrow function syntax (=>)\", \"6\");\n      }\n\n      if (!options.loneArg) {\n        advance(\"=>\");\n      }\n    }\n\n    block(false, true, true, isArrow);\n\n    if (!state.option.noyield && isGenerator &&\n        state.funct[\"(generator)\"] !== \"yielded\") {\n      warning(\"W124\", state.tokens.curr);\n    }\n\n    state.funct[\"(metrics)\"].verifyMaxStatementsPerFunction();\n    state.funct[\"(metrics)\"].verifyMaxComplexityPerFunction();\n    state.funct[\"(unusedOption)\"] = state.option.unused;\n    state.option = oldOption;\n    state.ignored = oldIgnored;\n    state.funct[\"(last)\"] = state.tokens.curr.line;\n    state.funct[\"(lastcharacter)\"] = state.tokens.curr.character;\n\n    // unstack the params scope\n    state.funct[\"(scope)\"].unstack(); // also does usage and label checks\n\n    // unstack the function outer stack\n    state.funct[\"(scope)\"].unstack();\n\n    state.funct = state.funct[\"(context)\"];\n\n    if (!ignoreLoopFunc && !state.option.loopfunc && state.funct[\"(loopage)\"]) {\n      // If the function we just parsed accesses any non-local variables\n      // trigger a warning. Otherwise, the function is safe even within\n      // a loop.\n      if (f[\"(outerMutables)\"]) {\n        warning(\"W083\", token, f[\"(outerMutables)\"].join(\", \"));\n      }\n    }\n\n    return f;\n  }\n\n  function createMetrics(functionStartToken) {\n    return {\n      statementCount: 0,\n      nestedBlockDepth: -1,\n      ComplexityCount: 1,\n      arity: 0,\n\n      verifyMaxStatementsPerFunction: function() {\n        if (state.option.maxstatements &&\n          this.statementCount > state.option.maxstatements) {\n          warning(\"W071\", functionStartToken, this.statementCount);\n        }\n      },\n\n      verifyMaxParametersPerFunction: function() {\n        if (_.isNumber(state.option.maxparams) &&\n          this.arity > state.option.maxparams) {\n          warning(\"W072\", functionStartToken, this.arity);\n        }\n      },\n\n      verifyMaxNestedBlockDepthPerFunction: function() {\n        if (state.option.maxdepth &&\n          this.nestedBlockDepth > 0 &&\n          this.nestedBlockDepth === state.option.maxdepth + 1) {\n          warning(\"W073\", null, this.nestedBlockDepth);\n        }\n      },\n\n      verifyMaxComplexityPerFunction: function() {\n        var max = state.option.maxcomplexity;\n        var cc = this.ComplexityCount;\n        if (max && cc > max) {\n          warning(\"W074\", functionStartToken, cc);\n        }\n      }\n    };\n  }\n\n  function increaseComplexityCount() {\n    state.funct[\"(metrics)\"].ComplexityCount += 1;\n  }\n\n  // Parse assignments that were found instead of conditionals.\n  // For example: if (a = 1) { ... }\n\n  function checkCondAssignment(expr) {\n    var id, paren;\n    if (expr) {\n      id = expr.id;\n      paren = expr.paren;\n      if (id === \",\" && (expr = expr.exprs[expr.exprs.length - 1])) {\n        id = expr.id;\n        paren = paren || expr.paren;\n      }\n    }\n    switch (id) {\n    case \"=\":\n    case \"+=\":\n    case \"-=\":\n    case \"*=\":\n    case \"%=\":\n    case \"&=\":\n    case \"|=\":\n    case \"^=\":\n    case \"/=\":\n      if (!paren && !state.option.boss) {\n        warning(\"W084\");\n      }\n    }\n  }\n\n  /**\n   * @param {object} props Collection of property descriptors for a given\n   *                       object.\n   */\n  function checkProperties(props) {\n    // Check for lonely setters if in the ES5 mode.\n    if (state.inES5()) {\n      for (var name in props) {\n        if (props[name] && props[name].setterToken && !props[name].getterToken) {\n          warning(\"W078\", props[name].setterToken);\n        }\n      }\n    }\n  }\n\n  function metaProperty(name, c) {\n    if (checkPunctuator(state.tokens.next, \".\")) {\n      var left = state.tokens.curr.id;\n      advance(\".\");\n      var id = identifier();\n      state.tokens.curr.isMetaProperty = true;\n      if (name !== id) {\n        error(\"E057\", state.tokens.prev, left, id);\n      } else {\n        c();\n      }\n      return state.tokens.curr;\n    }\n  }\n\n  (function(x) {\n    x.nud = function() {\n      var b, f, i, p, t, isGeneratorMethod = false, nextVal;\n      var props = Object.create(null); // All properties, including accessors\n\n      b = state.tokens.curr.line !== startLine(state.tokens.next);\n      if (b) {\n        indent += state.option.indent;\n        if (state.tokens.next.from === indent + state.option.indent) {\n          indent += state.option.indent;\n        }\n      }\n\n      var blocktype = lookupBlockType();\n      if (blocktype.isDestAssign) {\n        this.destructAssign = destructuringPattern({ openingParsed: true, assignment: true });\n        return this;\n      }\n\n      for (;;) {\n        if (state.tokens.next.id === \"}\") {\n          break;\n        }\n\n        nextVal = state.tokens.next.value;\n        if (state.tokens.next.identifier &&\n            (peekIgnoreEOL().id === \",\" || peekIgnoreEOL().id === \"}\")) {\n          if (!state.inES6()) {\n            warning(\"W104\", state.tokens.next, \"object short notation\", \"6\");\n          }\n          i = propertyName(true);\n          saveProperty(props, i, state.tokens.next);\n\n          expression(10);\n\n        } else if (peek().id !== \":\" && (nextVal === \"get\" || nextVal === \"set\")) {\n          advance(nextVal);\n\n          if (!state.inES5()) {\n            error(\"E034\");\n          }\n\n          if (state.tokens.next.id === \"[\") {\n            i = computedPropertyName();\n          } else {\n            i = propertyName();\n\n            // ES6 allows for get() {...} and set() {...} method\n            // definition shorthand syntax, so we don't produce an error\n            // if linting ECMAScript 6 code.\n            if (!i && !state.inES6()) {\n              error(\"E035\");\n            }\n          }\n\n          // We don't want to save this getter unless it's an actual getter\n          // and not an ES6 concise method\n          if (i) {\n            saveAccessor(nextVal, props, i, state.tokens.curr);\n          }\n\n          t = state.tokens.next;\n          f = doFunction({ isMethod: true });\n          p = f[\"(params)\"];\n\n          // Don't warn about getter/setter pairs if this is an ES6 concise method\n          if (nextVal === \"get\" && i && p) {\n            warning(\"W076\", t, p[0], i);\n          } else if (nextVal === \"set\" && i && f[\"(metrics)\"].arity !== 1) {\n            warning(\"W077\", t, i);\n          }\n        } else {\n          if (state.tokens.next.value === \"*\" && state.tokens.next.type === \"(punctuator)\") {\n            if (!state.inES6()) {\n              warning(\"W104\", state.tokens.next, \"generator functions\", \"6\");\n            }\n            advance(\"*\");\n            isGeneratorMethod = true;\n          } else {\n            isGeneratorMethod = false;\n          }\n\n          if (state.tokens.next.id === \"[\") {\n            i = computedPropertyName();\n            state.nameStack.set(i);\n          } else {\n            state.nameStack.set(state.tokens.next);\n            i = propertyName();\n            saveProperty(props, i, state.tokens.next);\n\n            if (typeof i !== \"string\") {\n              break;\n            }\n          }\n\n          if (state.tokens.next.value === \"(\") {\n            if (!state.inES6()) {\n              warning(\"W104\", state.tokens.curr, \"concise methods\", \"6\");\n            }\n            doFunction({\n              isMethod: true,\n              type: isGeneratorMethod ? \"generator\" : null\n            });\n          } else {\n            advance(\":\");\n            expression(10);\n          }\n        }\n\n        countMember(i);\n\n        if (state.tokens.next.id === \",\") {\n          parseComma({ allowTrailing: true, property: true });\n          if (state.tokens.next.id === \",\") {\n            warning(\"W070\", state.tokens.curr);\n          } else if (state.tokens.next.id === \"}\" && !state.inES5()) {\n            warning(\"W070\", state.tokens.curr);\n          }\n        } else {\n          if (state.option.trailingcomma && state.inES5()) {\n            warningAt(\"W140\", state.tokens.curr.line, state.tokens.curr.character);\n          }\n          break;\n        }\n      }\n      if (b) {\n        indent -= state.option.indent;\n      }\n      advance(\"}\", this);\n\n      checkProperties(props);\n\n      return this;\n    };\n    x.fud = function() {\n      error(\"E036\", state.tokens.curr);\n    };\n  }(delim(\"{\")));\n\n  function destructuringPattern(options) {\n    var isAssignment = options && options.assignment;\n\n    if (!state.inES6()) {\n      warning(\"W104\", state.tokens.curr,\n        isAssignment ? \"destructuring assignment\" : \"destructuring binding\", \"6\");\n    }\n\n    return destructuringPatternRecursive(options);\n  }\n\n  function destructuringPatternRecursive(options) {\n    var ids, idx;\n    var identifiers = [];\n    var openingParsed = options && options.openingParsed;\n    var isAssignment = options && options.assignment;\n    var recursiveOptions = isAssignment ? { assignment: isAssignment } : null;\n    var firstToken = openingParsed ? state.tokens.curr : state.tokens.next;\n\n    var nextInnerDE = function() {\n      var ident;\n      if (checkPunctuators(state.tokens.next, [\"[\", \"{\"])) {\n        ids = destructuringPatternRecursive(recursiveOptions);\n        for (idx = 0; idx < ids.length; idx++) {\n          identifiers.push({ id: ids[idx].id, token: ids[idx].token });\n        }\n      } else if (checkPunctuator(state.tokens.next, \",\")) {\n        identifiers.push({ id: null, token: state.tokens.curr });\n      } else if (checkPunctuator(state.tokens.next, \"(\")) {\n        advance(\"(\");\n        nextInnerDE();\n        advance(\")\");\n      } else {\n        var is_rest = checkPunctuator(state.tokens.next, \"...\");\n\n        if (isAssignment) {\n          var assignTarget = expression(20);\n          if (assignTarget) {\n            checkLeftSideAssign(assignTarget);\n\n            // if the target was a simple identifier, add it to the list to return\n            if (assignTarget.identifier) {\n              ident = assignTarget.value;\n            }\n          }\n        } else {\n          ident = identifier();\n        }\n        if (ident) {\n          identifiers.push({ id: ident, token: state.tokens.curr });\n        }\n        return is_rest;\n      }\n      return false;\n    };\n    var assignmentProperty = function() {\n      var id;\n      if (checkPunctuator(state.tokens.next, \"[\")) {\n        advance(\"[\");\n        expression(10);\n        advance(\"]\");\n        advance(\":\");\n        nextInnerDE();\n      } else if (state.tokens.next.id === \"(string)\" ||\n                 state.tokens.next.id === \"(number)\") {\n        advance();\n        advance(\":\");\n        nextInnerDE();\n      } else {\n        // this id will either be the property name or the property name and the assigning identifier\n        id = identifier();\n        if (checkPunctuator(state.tokens.next, \":\")) {\n          advance(\":\");\n          nextInnerDE();\n        } else if (id) {\n          // in this case we are assigning (not declaring), so check assignment\n          if (isAssignment) {\n            checkLeftSideAssign(state.tokens.curr);\n          }\n          identifiers.push({ id: id, token: state.tokens.curr });\n        }\n      }\n    };\n\n    var id, value;\n    if (checkPunctuator(firstToken, \"[\")) {\n      if (!openingParsed) {\n        advance(\"[\");\n      }\n      if (checkPunctuator(state.tokens.next, \"]\")) {\n        warning(\"W137\", state.tokens.curr);\n      }\n      var element_after_rest = false;\n      while (!checkPunctuator(state.tokens.next, \"]\")) {\n        if (nextInnerDE() && !element_after_rest &&\n            checkPunctuator(state.tokens.next, \",\")) {\n          warning(\"W130\", state.tokens.next);\n          element_after_rest = true;\n        }\n        if (checkPunctuator(state.tokens.next, \"=\")) {\n          if (checkPunctuator(state.tokens.prev, \"...\")) {\n            advance(\"]\");\n          } else {\n            advance(\"=\");\n          }\n          id = state.tokens.prev;\n          value = expression(10);\n          if (value && value.identifier && value.value === \"undefined\") {\n            warning(\"W080\", id, id.value);\n          }\n        }\n        if (!checkPunctuator(state.tokens.next, \"]\")) {\n          advance(\",\");\n        }\n      }\n      advance(\"]\");\n    } else if (checkPunctuator(firstToken, \"{\")) {\n\n      if (!openingParsed) {\n        advance(\"{\");\n      }\n      if (checkPunctuator(state.tokens.next, \"}\")) {\n        warning(\"W137\", state.tokens.curr);\n      }\n      while (!checkPunctuator(state.tokens.next, \"}\")) {\n        assignmentProperty();\n        if (checkPunctuator(state.tokens.next, \"=\")) {\n          advance(\"=\");\n          id = state.tokens.prev;\n          value = expression(10);\n          if (value && value.identifier && value.value === \"undefined\") {\n            warning(\"W080\", id, id.value);\n          }\n        }\n        if (!checkPunctuator(state.tokens.next, \"}\")) {\n          advance(\",\");\n          if (checkPunctuator(state.tokens.next, \"}\")) {\n            // Trailing comma\n            // ObjectBindingPattern: { BindingPropertyList , }\n            break;\n          }\n        }\n      }\n      advance(\"}\");\n    }\n    return identifiers;\n  }\n\n  function destructuringPatternMatch(tokens, value) {\n    var first = value.first;\n\n    if (!first)\n      return;\n\n    _.zip(tokens, Array.isArray(first) ? first : [ first ]).forEach(function(val) {\n      var token = val[0];\n      var value = val[1];\n\n      if (token && value)\n        token.first = value;\n      else if (token && token.first && !value)\n        warning(\"W080\", token.first, token.first.value);\n    });\n  }\n\n  function blockVariableStatement(type, statement, context) {\n    // used for both let and const statements\n\n    var prefix = context && context.prefix;\n    var inexport = context && context.inexport;\n    var isLet = type === \"let\";\n    var isConst = type === \"const\";\n    var tokens, lone, value, letblock;\n\n    if (!state.inES6()) {\n      warning(\"W104\", state.tokens.curr, type, \"6\");\n    }\n\n    if (isLet && state.tokens.next.value === \"(\") {\n      if (!state.inMoz()) {\n        warning(\"W118\", state.tokens.next, \"let block\");\n      }\n      advance(\"(\");\n      state.funct[\"(scope)\"].stack();\n      letblock = true;\n    } else if (state.funct[\"(noblockscopedvar)\"]) {\n      error(\"E048\", state.tokens.curr, isConst ? \"Const\" : \"Let\");\n    }\n\n    statement.first = [];\n    for (;;) {\n      var names = [];\n      if (_.includes([\"{\", \"[\"], state.tokens.next.value)) {\n        tokens = destructuringPattern();\n        lone = false;\n      } else {\n        tokens = [ { id: identifier(), token: state.tokens.curr } ];\n        lone = true;\n      }\n\n      if (!prefix && isConst && state.tokens.next.id !== \"=\") {\n        warning(\"E012\", state.tokens.curr, state.tokens.curr.value);\n      }\n\n      for (var t in tokens) {\n        if (tokens.hasOwnProperty(t)) {\n          t = tokens[t];\n          if (state.funct[\"(scope)\"].block.isGlobal()) {\n            if (predefined[t.id] === false) {\n              warning(\"W079\", t.token, t.id);\n            }\n          }\n          if (t.id && !state.funct[\"(noblockscopedvar)\"]) {\n            state.funct[\"(scope)\"].addlabel(t.id, {\n              type: type,\n              token: t.token });\n            names.push(t.token);\n          }\n        }\n      }\n\n      if (state.tokens.next.id === \"=\") {\n        advance(\"=\");\n        if (!prefix && peek(0).id === \"=\" && state.tokens.next.identifier) {\n          warning(\"W120\", state.tokens.next, state.tokens.next.value);\n        }\n        var id = state.tokens.prev;\n        // don't accept `in` in expression if prefix is used for ForIn/Of loop.\n        value = expression(prefix ? 120 : 10);\n        if (!prefix && value && value.identifier && value.value === \"undefined\") {\n          warning(\"W080\", id, id.value);\n        }\n        if (!lone) {\n          destructuringPatternMatch(names, value);\n        }\n      }\n\n      if (!prefix) {\n        for (t in tokens) {\n          if (tokens.hasOwnProperty(t)) {\n            t = tokens[t];\n            state.funct[\"(scope)\"].initialize(t.id);\n\n            if (lone && inexport) {\n              state.funct[\"(scope)\"].setExported(t.token.value, t.token);\n            }\n          }\n        }\n      }\n\n      statement.first = statement.first.concat(names);\n\n      if (state.tokens.next.id !== \",\") {\n        break;\n      }\n      parseComma();\n    }\n    if (letblock) {\n      advance(\")\");\n      block(true, true);\n      statement.block = true;\n      state.funct[\"(scope)\"].unstack();\n    }\n\n    return statement;\n  }\n\n  var conststatement = stmt(\"const\", function(context) {\n    return blockVariableStatement(\"const\", this, context);\n  });\n  conststatement.exps = true;\n\n  var letstatement = stmt(\"let\", function(context) {\n    return blockVariableStatement(\"let\", this, context);\n  });\n  letstatement.exps = true;\n\n  var varstatement = stmt(\"var\", function(context) {\n    var prefix = context && context.prefix;\n    var inexport = context && context.inexport;\n    var tokens, lone, value, id;\n\n    this.first = [];\n    for (;;) {\n      var names = [];\n      if (_.includes([\"{\", \"[\"], state.tokens.next.value)) {\n        tokens = destructuringPattern();\n        lone = false;\n      } else {\n        tokens = [];\n        id = identifier();\n\n        if (id) {\n          tokens.push({ id: id, token: state.tokens.curr });\n        }\n\n        lone = true;\n      }\n\n      if (state.option.varstmt) {\n        warning(\"W132\", this);\n      }\n\n      this.first = this.first.concat(names);\n\n      for (var t in tokens) {\n        if (tokens.hasOwnProperty(t)) {\n          t = tokens[t];\n          if (state.funct[\"(global)\"] && !state.impliedClosure()) {\n            if (predefined[t.id] === false) {\n              warning(\"W079\", t.token, t.id);\n            } else if (state.option.futurehostile === false) {\n              if ((!state.inES5() && vars.ecmaIdentifiers[5][t.id] === false) ||\n                (!state.inES6() && vars.ecmaIdentifiers[6][t.id] === false)) {\n                warning(\"W129\", t.token, t.id);\n              }\n            }\n          }\n          if (t.id) {\n            state.funct[\"(scope)\"].addlabel(t.id, {\n              type: \"var\",\n              token: t.token });\n\n            if (lone && inexport) {\n              state.funct[\"(scope)\"].setExported(t.id, t.token);\n            }\n            names.push(t.token);\n          }\n        }\n      }\n\n      if (state.tokens.next.id === \"=\") {\n        state.nameStack.set(state.tokens.curr);\n\n        advance(\"=\");\n        if (peek(0).id === \"=\" && state.tokens.next.identifier) {\n          if (!prefix &&\n              !state.funct[\"(params)\"] ||\n              state.funct[\"(params)\"].indexOf(state.tokens.next.value) === -1) {\n            warning(\"W120\", state.tokens.next, state.tokens.next.value);\n          }\n        }\n        id = state.tokens.prev;\n        // don't accept `in` in expression if prefix is used for ForIn/Of loop.\n        value = expression(prefix ? 120 : 10);\n        if (value && !prefix && !state.funct[\"(loopage)\"] &&\n          value.identifier && value.value === \"undefined\") {\n          warning(\"W080\", id, id.value);\n        }\n        if (!lone) {\n          destructuringPatternMatch(names, value);\n        }\n      }\n\n      if (state.tokens.next.id !== \",\") {\n        break;\n      }\n      parseComma();\n    }\n\n    return this;\n  });\n  varstatement.exps = true;\n\n  blockstmt(\"class\", function(rbp) {\n    return classdef.call(this, rbp, true);\n  });\n\n  function classdef(rbp, isStatement) {\n\n    /*jshint validthis:true */\n    var wasInClassBody = state.inClassBody;\n    state.inClassBody = true;\n\n    if (!state.inES6()) {\n      warning(\"W104\", state.tokens.curr, \"class\", \"6\");\n    }\n    if (isStatement) {\n      // BindingIdentifier\n      this.name = identifier();\n\n      state.funct[\"(scope)\"].addlabel(this.name, {\n        type: \"class\",\n        token: state.tokens.curr });\n\n    } else if (state.tokens.next.identifier && state.tokens.next.value !== \"extends\") {\n      // BindingIdentifier(opt)\n      this.name = identifier();\n      this.namedExpr = true;\n    } else {\n      this.name = state.nameStack.infer();\n    }\n\n    classtail(this);\n\n    state.inClassBody = wasInClassBody;\n\n    if (isStatement) {\n      state.funct[\"(scope)\"].initialize(this.name);\n    }\n\n    return this;\n  }\n\n  function classtail(c) {\n    // ClassHeritage(opt)\n    if (state.tokens.next.value === \"extends\") {\n      advance(\"extends\");\n      expression(10);\n    }\n\n    advance(\"{\");\n    // ClassBody(opt)\n    classbody(c);\n    advance(\"}\");\n  }\n\n  function classbody(c) {\n    var name;\n    var isStatic;\n    var isGenerator;\n    var getset;\n    var props = Object.create(null);\n    var staticProps = Object.create(null);\n    var computed;\n    while (state.tokens.next.id !== \"}\") {\n      name = state.tokens.next;\n      isStatic = false;\n      isGenerator = false;\n      getset = null;\n\n      // The ES6 grammar for ClassElement includes the `;` token, but it is\n      // defined only as a placeholder to facilitate future language\n      // extensions. In ES6 code, it serves no purpose.\n      if (name.id === \";\") {\n        warning(\"W032\");\n        advance(\";\");\n        continue;\n      }\n\n      if (name.id === \"*\") {\n        isGenerator = true;\n        advance(\"*\");\n        name = state.tokens.next;\n      }\n      if (name.id === \"[\") {\n        name = computedPropertyName();\n        computed = true;\n      } else if (isPropertyName(name)) {\n        // Non-Computed PropertyName\n        advance();\n        computed = false;\n        if (name.identifier && name.value === \"static\") {\n          if (checkPunctuator(state.tokens.next, \"*\")) {\n            isGenerator = true;\n            advance(\"*\");\n          }\n          if (isPropertyName(state.tokens.next) || state.tokens.next.id === \"[\") {\n            computed = state.tokens.next.id === \"[\";\n            isStatic = true;\n            name = state.tokens.next;\n            if (state.tokens.next.id === \"[\") {\n              name = computedPropertyName();\n            } else advance();\n          }\n        }\n\n        if (name.identifier && (name.value === \"get\" || name.value === \"set\")) {\n          if (isPropertyName(state.tokens.next) || state.tokens.next.id === \"[\") {\n            computed = state.tokens.next.id === \"[\";\n            getset = name;\n            name = state.tokens.next;\n            if (state.tokens.next.id === \"[\") {\n              name = computedPropertyName();\n            } else advance();\n          }\n        }\n      } else {\n        warning(\"W052\", state.tokens.next, state.tokens.next.value || state.tokens.next.type);\n        advance();\n        continue;\n      }\n\n      if (!checkPunctuator(state.tokens.next, \"(\")) {\n        // error --- class properties must be methods\n        error(\"E054\", state.tokens.next, state.tokens.next.value);\n        while (state.tokens.next.id !== \"}\" &&\n               !checkPunctuator(state.tokens.next, \"(\")) {\n          advance();\n        }\n        if (state.tokens.next.value !== \"(\") {\n          doFunction({\n            isMethod: true,\n            statement: c\n          });\n        }\n      }\n\n      if (!computed) {\n        // We don't know how to determine if we have duplicate computed property names :(\n        if (getset) {\n          saveAccessor(\n            getset.value, isStatic ? staticProps : props, name.value, name, true, isStatic);\n        } else {\n          if (name.value === \"constructor\") {\n            state.nameStack.set(c);\n          } else {\n            state.nameStack.set(name);\n          }\n          saveProperty(isStatic ? staticProps : props, name.value, name, true, isStatic);\n        }\n      }\n\n      if (getset && name.value === \"constructor\") {\n        var propDesc = getset.value === \"get\" ? \"class getter method\" : \"class setter method\";\n        error(\"E049\", name, propDesc, \"constructor\");\n      } else if (name.value === \"prototype\") {\n        error(\"E049\", name, \"class method\", \"prototype\");\n      }\n\n      propertyName(name);\n\n      doFunction({\n        statement: c,\n        isMethod: true,\n        type: isGenerator ? \"generator\" : null,\n        classExprBinding: c.namedExpr ? c.name : null\n      });\n    }\n\n    checkProperties(props);\n  }\n\n  blockstmt(\"function\", function(context) {\n    var inexport = context && context.inexport;\n    var generator = false;\n    if (state.tokens.next.value === \"*\") {\n      advance(\"*\");\n      if (state.inES6(true)) {\n        generator = true;\n      } else {\n        warning(\"W119\", state.tokens.curr, \"function*\", \"6\");\n      }\n    }\n    if (inblock) {\n      warning(\"W082\", state.tokens.curr);\n    }\n    var nameToken = optionalidentifier() ? state.tokens.curr : null;\n\n    if (!nameToken) {\n      warning(\"W025\");\n    } else {\n      state.funct[\"(scope)\"].addlabel(nameToken.value, {\n        type: generator ? \"generator function\" : \"function\",\n        token: state.tokens.curr,\n        initialized: true });\n\n      if (inexport) {\n        state.funct[\"(scope)\"].setExported(nameToken.value, state.tokens.prev);\n      }\n    }\n\n    var f = doFunction({\n      name: nameToken && nameToken.value,\n      statement: this,\n      type: generator ? \"generator\" : null,\n      ignoreLoopFunc: inblock // a declaration may already have warned\n    });\n\n    // If the function declaration is strict because the surrounding code is\n    // strict, the invalid name will trigger E008 when the scope manager\n    // attempts to create a binding in the strict environment record. An error\n    // should only be signaled here when the function itself enables strict\n    // mode (the scope manager will not report an error because a declaration\n    // does not introduce a binding into the function's environment record).\n    var enablesStrictMode = f[\"(isStrict)\"] && !state.isStrict();\n    if (nameToken && (f[\"(name)\"] === \"arguments\" || f[\"(name)\"] === \"eval\") &&\n      enablesStrictMode) {\n      error(\"E008\", nameToken);\n    }\n\n    if (state.tokens.next.id === \"(\" && state.tokens.next.line === state.tokens.curr.line) {\n      error(\"E039\");\n    }\n    return this;\n  });\n\n  prefix(\"function\", function() {\n    var generator = false;\n\n    if (state.tokens.next.value === \"*\") {\n      if (!state.inES6()) {\n        warning(\"W119\", state.tokens.curr, \"function*\", \"6\");\n      }\n      advance(\"*\");\n      generator = true;\n    }\n\n    var nameToken = optionalidentifier() ? state.tokens.curr : null;\n\n    var f = doFunction({\n      name: nameToken && nameToken.value,\n      type: generator ? \"generator\" : null\n    });\n\n    if (nameToken && (f[\"(name)\"] === \"arguments\" || f[\"(name)\"] === \"eval\") &&\n      f[\"(isStrict)\"]) {\n      error(\"E008\", nameToken);\n    }\n    return this;\n  });\n\n  blockstmt(\"if\", function() {\n    var t = state.tokens.next;\n    increaseComplexityCount();\n    state.condition = true;\n    advance(\"(\");\n    var expr = expression(0);\n\n    if (!expr) {\n      quit(\"E041\", this);\n    }\n\n    checkCondAssignment(expr);\n\n    // When the if is within a for-in loop, check if the condition\n    // starts with a negation operator\n    var forinifcheck = null;\n    if (state.option.forin && state.forinifcheckneeded) {\n      state.forinifcheckneeded = false; // We only need to analyze the first if inside the loop\n      forinifcheck = state.forinifchecks[state.forinifchecks.length - 1];\n      if (expr.type === \"(punctuator)\" && expr.value === \"!\") {\n        forinifcheck.type = \"(negative)\";\n      } else {\n        forinifcheck.type = \"(positive)\";\n      }\n    }\n\n    advance(\")\", t);\n    state.condition = false;\n    var s = block(true, true);\n\n    // When the if is within a for-in loop and the condition has a negative form,\n    // check if the body contains nothing but a continue statement\n    if (forinifcheck && forinifcheck.type === \"(negative)\") {\n      if (s && s[0] && s[0].type === \"(identifier)\" && s[0].value === \"continue\") {\n        forinifcheck.type = \"(negative-with-continue)\";\n      }\n    }\n\n    if (state.tokens.next.id === \"else\") {\n      advance(\"else\");\n      if (state.tokens.next.id === \"if\" || state.tokens.next.id === \"switch\") {\n        statement();\n      } else {\n        block(true, true);\n      }\n    }\n    return this;\n  });\n\n  blockstmt(\"try\", function() {\n    var b;\n\n    function doCatch() {\n      advance(\"catch\");\n      advance(\"(\");\n\n      state.funct[\"(scope)\"].stack(\"catchparams\");\n\n      if (checkPunctuators(state.tokens.next, [\"[\", \"{\"])) {\n        var tokens = destructuringPattern();\n        _.each(tokens, function(token) {\n          if (token.id) {\n            state.funct[\"(scope)\"].addParam(token.id, token, \"exception\");\n          }\n        });\n      } else if (state.tokens.next.type !== \"(identifier)\") {\n        warning(\"E030\", state.tokens.next, state.tokens.next.value);\n      } else {\n        // only advance if we have an identifier so we can continue parsing in the most common error - that no param is given.\n        state.funct[\"(scope)\"].addParam(identifier(), state.tokens.curr, \"exception\");\n      }\n\n      if (state.tokens.next.value === \"if\") {\n        if (!state.inMoz()) {\n          warning(\"W118\", state.tokens.curr, \"catch filter\");\n        }\n        advance(\"if\");\n        expression(0);\n      }\n\n      advance(\")\");\n\n      block(false);\n\n      state.funct[\"(scope)\"].unstack();\n    }\n\n    block(true);\n\n    while (state.tokens.next.id === \"catch\") {\n      increaseComplexityCount();\n      if (b && (!state.inMoz())) {\n        warning(\"W118\", state.tokens.next, \"multiple catch blocks\");\n      }\n      doCatch();\n      b = true;\n    }\n\n    if (state.tokens.next.id === \"finally\") {\n      advance(\"finally\");\n      block(true);\n      return;\n    }\n\n    if (!b) {\n      error(\"E021\", state.tokens.next, \"catch\", state.tokens.next.value);\n    }\n\n    return this;\n  });\n\n  blockstmt(\"while\", function() {\n    var t = state.tokens.next;\n    state.funct[\"(breakage)\"] += 1;\n    state.funct[\"(loopage)\"] += 1;\n    increaseComplexityCount();\n    advance(\"(\");\n    checkCondAssignment(expression(0));\n    advance(\")\", t);\n    block(true, true);\n    state.funct[\"(breakage)\"] -= 1;\n    state.funct[\"(loopage)\"] -= 1;\n    return this;\n  }).labelled = true;\n\n  blockstmt(\"with\", function() {\n    var t = state.tokens.next;\n    if (state.isStrict()) {\n      error(\"E010\", state.tokens.curr);\n    } else if (!state.option.withstmt) {\n      warning(\"W085\", state.tokens.curr);\n    }\n\n    advance(\"(\");\n    expression(0);\n    advance(\")\", t);\n    block(true, true);\n\n    return this;\n  });\n\n  blockstmt(\"switch\", function() {\n    var t = state.tokens.next;\n    var g = false;\n    var noindent = false;\n\n    state.funct[\"(breakage)\"] += 1;\n    advance(\"(\");\n    checkCondAssignment(expression(0));\n    advance(\")\", t);\n    t = state.tokens.next;\n    advance(\"{\");\n    state.funct[\"(scope)\"].stack();\n\n    if (state.tokens.next.from === indent)\n      noindent = true;\n\n    if (!noindent)\n      indent += state.option.indent;\n\n    this.cases = [];\n\n    for (;;) {\n      switch (state.tokens.next.id) {\n      case \"case\":\n        switch (state.funct[\"(verb)\"]) {\n        case \"yield\":\n        case \"break\":\n        case \"case\":\n        case \"continue\":\n        case \"return\":\n        case \"switch\":\n        case \"throw\":\n          break;\n        default:\n          // You can tell JSHint that you don't use break intentionally by\n          // adding a comment /* falls through */ on a line just before\n          // the next `case`.\n          if (!state.tokens.curr.caseFallsThrough) {\n            warning(\"W086\", state.tokens.curr, \"case\");\n          }\n        }\n\n        advance(\"case\");\n        this.cases.push(expression(0));\n        increaseComplexityCount();\n        g = true;\n        advance(\":\");\n        state.funct[\"(verb)\"] = \"case\";\n        break;\n      case \"default\":\n        switch (state.funct[\"(verb)\"]) {\n        case \"yield\":\n        case \"break\":\n        case \"continue\":\n        case \"return\":\n        case \"throw\":\n          break;\n        default:\n          // Do not display a warning if 'default' is the first statement or if\n          // there is a special /* falls through */ comment.\n          if (this.cases.length) {\n            if (!state.tokens.curr.caseFallsThrough) {\n              warning(\"W086\", state.tokens.curr, \"default\");\n            }\n          }\n        }\n\n        advance(\"default\");\n        g = true;\n        advance(\":\");\n        break;\n      case \"}\":\n        if (!noindent)\n          indent -= state.option.indent;\n\n        advance(\"}\", t);\n        state.funct[\"(scope)\"].unstack();\n        state.funct[\"(breakage)\"] -= 1;\n        state.funct[\"(verb)\"] = undefined;\n        return;\n      case \"(end)\":\n        error(\"E023\", state.tokens.next, \"}\");\n        return;\n      default:\n        indent += state.option.indent;\n        if (g) {\n          switch (state.tokens.curr.id) {\n          case \",\":\n            error(\"E040\");\n            return;\n          case \":\":\n            g = false;\n            statements();\n            break;\n          default:\n            error(\"E025\", state.tokens.curr);\n            return;\n          }\n        } else {\n          if (state.tokens.curr.id === \":\") {\n            advance(\":\");\n            error(\"E024\", state.tokens.curr, \":\");\n            statements();\n          } else {\n            error(\"E021\", state.tokens.next, \"case\", state.tokens.next.value);\n            return;\n          }\n        }\n        indent -= state.option.indent;\n      }\n    }\n  }).labelled = true;\n\n  stmt(\"debugger\", function() {\n    if (!state.option.debug) {\n      warning(\"W087\", this);\n    }\n    return this;\n  }).exps = true;\n\n  (function() {\n    var x = stmt(\"do\", function() {\n      state.funct[\"(breakage)\"] += 1;\n      state.funct[\"(loopage)\"] += 1;\n      increaseComplexityCount();\n\n      this.first = block(true, true);\n      advance(\"while\");\n      var t = state.tokens.next;\n      advance(\"(\");\n      checkCondAssignment(expression(0));\n      advance(\")\", t);\n      state.funct[\"(breakage)\"] -= 1;\n      state.funct[\"(loopage)\"] -= 1;\n      return this;\n    });\n    x.labelled = true;\n    x.exps = true;\n  }());\n\n  blockstmt(\"for\", function() {\n    var s, t = state.tokens.next;\n    var letscope = false;\n    var foreachtok = null;\n\n    if (t.value === \"each\") {\n      foreachtok = t;\n      advance(\"each\");\n      if (!state.inMoz()) {\n        warning(\"W118\", state.tokens.curr, \"for each\");\n      }\n    }\n\n    increaseComplexityCount();\n    advance(\"(\");\n\n    // what kind of for(…) statement it is? for(…of…)? for(…in…)? for(…;…;…)?\n    var nextop; // contains the token of the \"in\" or \"of\" operator\n    var i = 0;\n    var inof = [\"in\", \"of\"];\n    var level = 0; // BindingPattern \"level\" --- level 0 === no BindingPattern\n    var comma; // First comma punctuator at level 0\n    var initializer; // First initializer at level 0\n    var bindingPower;\n    var targets;\n    var target;\n\n    // If initial token is a BindingPattern, count it as such.\n    if (checkPunctuators(state.tokens.next, [\"{\", \"[\"])) ++level;\n    do {\n      nextop = peek(i);\n      ++i;\n      if (checkPunctuators(nextop, [\"{\", \"[\"])) ++level;\n      else if (checkPunctuators(nextop, [\"}\", \"]\"])) --level;\n      if (level < 0) break;\n      if (level === 0) {\n        if (!comma && checkPunctuator(nextop, \",\")) comma = nextop;\n        else if (!initializer && checkPunctuator(nextop, \"=\")) initializer = nextop;\n      }\n    } while (\n      (level > 0 || !_.includes(inof, nextop.value) && nextop.value !== \";\") &&\n      nextop.type !== \"(end)\");\n\n    // if we're in a for (… in|of …) statement\n    if (_.includes(inof, nextop.value)) {\n      if (nextop.value === \"of\") {\n        bindingPower = 20;\n        if (!state.inES6()) {\n          warning(\"W104\", nextop, \"for of\", \"6\");\n        }\n      } else {\n        bindingPower = 0;\n      }\n\n      if (initializer) {\n        error(\"W133\", comma, nextop.value, \"initializer is forbidden\");\n      }\n\n      if (comma) {\n        error(\"W133\", comma, nextop.value, \"more than one ForBinding\");\n      }\n\n      if (state.tokens.next.id === \"var\") {\n        advance(\"var\");\n        state.tokens.curr.fud({ prefix: true });\n      } else if (state.tokens.next.id === \"let\" || state.tokens.next.id === \"const\") {\n        advance(state.tokens.next.id);\n        // create a new block scope\n        letscope = true;\n        state.funct[\"(scope)\"].stack();\n        state.tokens.curr.fud({ prefix: true });\n      } else {\n        targets = [];\n\n        // The following parsing logic recognizes initializers and the comma\n        // operator despite the fact that they are not supported by the\n        // grammar. Doing so allows JSHint to emit more a meaningful error\n        // message (i.e. W133) in response to a common programming mistake.\n        do {\n          if (checkPunctuators(state.tokens.next, [\"{\", \"[\"])) {\n            destructuringPattern({ assignment: true }).forEach(function(elem) {\n              this.push(elem.token);\n            }, targets);\n          } else {\n            target = expression(120);\n\n            if (target.type === \"(identifier)\") {\n              targets.push(target);\n            }\n\n            checkLeftSideAssign(target, nextop);\n          }\n\n          if (checkPunctuator(state.tokens.next, \"=\")) {\n            advance(\"=\");\n            expression(120);\n          }\n\n          if (checkPunctuator(state.tokens.next, \",\")) {\n            advance(\",\");\n          }\n        } while (state.tokens.next !== nextop);\n\n        // In the event of a syntax error, do no issue warnings regarding the\n        // implicit creation of bindings.\n        if (!initializer && !comma) {\n          targets.forEach(function(token) {\n            if (!state.funct[\"(scope)\"].has(token.value)) {\n              warning(\"W088\", token, token.value);\n            }\n          });\n        }\n      }\n\n      advance(nextop.value);\n      // The binding power is variable because for-in statements accept any\n      // Expression in this position, while for-of statements are limited to\n      // AssignmentExpressions. For example:\n      //\n      //     for ( LeftHandSideExpression in Expression ) Statement\n      //     for ( LeftHandSideExpression of AssignmentExpression ) Statement\n      expression(bindingPower);\n      advance(\")\", t);\n\n      if (nextop.value === \"in\" && state.option.forin) {\n        state.forinifcheckneeded = true;\n\n        if (state.forinifchecks === undefined) {\n          state.forinifchecks = [];\n        }\n\n        // Push a new for-in-if check onto the stack. The type will be modified\n        // when the loop's body is parsed and a suitable if statement exists.\n        state.forinifchecks.push({\n          type: \"(none)\"\n        });\n      }\n\n      state.funct[\"(breakage)\"] += 1;\n      state.funct[\"(loopage)\"] += 1;\n\n      s = block(true, true);\n\n      if (nextop.value === \"in\" && state.option.forin) {\n        if (state.forinifchecks && state.forinifchecks.length > 0) {\n          var check = state.forinifchecks.pop();\n\n          if (// No if statement or not the first statement in loop body\n              s && s.length > 0 && (typeof s[0] !== \"object\" || s[0].value !== \"if\") ||\n              // Positive if statement is not the only one in loop body\n              check.type === \"(positive)\" && s.length > 1 ||\n              // Negative if statement but no continue\n              check.type === \"(negative)\") {\n            warning(\"W089\", this);\n          }\n        }\n\n        // Reset the flag in case no if statement was contained in the loop body\n        state.forinifcheckneeded = false;\n      }\n\n      state.funct[\"(breakage)\"] -= 1;\n      state.funct[\"(loopage)\"] -= 1;\n    } else {\n      if (foreachtok) {\n        error(\"E045\", foreachtok);\n      }\n      if (state.tokens.next.id !== \";\") {\n        if (state.tokens.next.id === \"var\") {\n          advance(\"var\");\n          state.tokens.curr.fud();\n        } else if (state.tokens.next.id === \"let\") {\n          advance(\"let\");\n          // create a new block scope\n          letscope = true;\n          state.funct[\"(scope)\"].stack();\n          state.tokens.curr.fud();\n        } else {\n          for (;;) {\n            expression(0, \"for\");\n            if (state.tokens.next.id !== \",\") {\n              break;\n            }\n            parseComma();\n          }\n        }\n      }\n      nolinebreak(state.tokens.curr);\n      advance(\";\");\n\n      // start loopage after the first ; as the next two expressions are executed\n      // on every loop\n      state.funct[\"(loopage)\"] += 1;\n      if (state.tokens.next.id !== \";\") {\n        checkCondAssignment(expression(0));\n      }\n      nolinebreak(state.tokens.curr);\n      advance(\";\");\n      if (state.tokens.next.id === \";\") {\n        error(\"E021\", state.tokens.next, \")\", \";\");\n      }\n      if (state.tokens.next.id !== \")\") {\n        for (;;) {\n          expression(0, \"for\");\n          if (state.tokens.next.id !== \",\") {\n            break;\n          }\n          parseComma();\n        }\n      }\n      advance(\")\", t);\n      state.funct[\"(breakage)\"] += 1;\n      block(true, true);\n      state.funct[\"(breakage)\"] -= 1;\n      state.funct[\"(loopage)\"] -= 1;\n\n    }\n    // unstack loop blockscope\n    if (letscope) {\n      state.funct[\"(scope)\"].unstack();\n    }\n    return this;\n  }).labelled = true;\n\n\n  stmt(\"break\", function() {\n    var v = state.tokens.next.value;\n\n    if (!state.option.asi)\n      nolinebreak(this);\n\n    if (state.tokens.next.id !== \";\" && !state.tokens.next.reach &&\n        state.tokens.curr.line === startLine(state.tokens.next)) {\n      if (!state.funct[\"(scope)\"].funct.hasBreakLabel(v)) {\n        warning(\"W090\", state.tokens.next, v);\n      }\n      this.first = state.tokens.next;\n      advance();\n    } else {\n      if (state.funct[\"(breakage)\"] === 0)\n        warning(\"W052\", state.tokens.next, this.value);\n    }\n\n    reachable(this);\n\n    return this;\n  }).exps = true;\n\n\n  stmt(\"continue\", function() {\n    var v = state.tokens.next.value;\n\n    if (state.funct[\"(breakage)\"] === 0 || !state.funct[\"(loopage)\"]) {\n      warning(\"W052\", state.tokens.next, this.value);\n    }\n\n    if (!state.option.asi)\n      nolinebreak(this);\n\n    if (state.tokens.next.id !== \";\" && !state.tokens.next.reach) {\n      if (state.tokens.curr.line === startLine(state.tokens.next)) {\n        if (!state.funct[\"(scope)\"].funct.hasBreakLabel(v)) {\n          warning(\"W090\", state.tokens.next, v);\n        }\n        this.first = state.tokens.next;\n        advance();\n      }\n    }\n\n    reachable(this);\n\n    return this;\n  }).exps = true;\n\n\n  stmt(\"return\", function() {\n    if (this.line === startLine(state.tokens.next)) {\n      if (state.tokens.next.id !== \";\" && !state.tokens.next.reach) {\n        this.first = expression(0);\n\n        if (this.first &&\n            this.first.type === \"(punctuator)\" && this.first.value === \"=\" &&\n            !this.first.paren && !state.option.boss) {\n          warningAt(\"W093\", this.first.line, this.first.character);\n        }\n      }\n    } else {\n      if (state.tokens.next.type === \"(punctuator)\" &&\n        [\"[\", \"{\", \"+\", \"-\"].indexOf(state.tokens.next.value) > -1) {\n        nolinebreak(this); // always warn (Line breaking error)\n      }\n    }\n\n    reachable(this);\n\n    return this;\n  }).exps = true;\n\n  (function(x) {\n    x.exps = true;\n    x.lbp = 25;\n    x.ltBoundary = \"after\";\n  }(prefix(\"yield\", function() {\n    if (state.inMoz()) {\n      return mozYield.call(this);\n    }\n    var prev = state.tokens.prev;\n\n    if (!this.beginsStmt && prev.lbp > 30 && !checkPunctuators(prev, [\"(\"])) {\n      error(\"E061\", this);\n    }\n\n    if (state.inES6(true) && !state.funct[\"(generator)\"]) {\n      // If it's a yield within a catch clause inside a generator then that's ok\n      if (!(\"(catch)\" === state.funct[\"(name)\"] && state.funct[\"(context)\"][\"(generator)\"])) {\n        error(\"E046\", state.tokens.curr, \"yield\");\n      }\n    } else if (!state.inES6()) {\n      warning(\"W104\", state.tokens.curr, \"yield\", \"6\");\n    }\n    state.funct[\"(generator)\"] = \"yielded\";\n\n    if (state.tokens.next.value === \"*\") {\n      advance(\"*\");\n    }\n\n    // Parse operand\n    if (!isEndOfExpr() && state.tokens.next.id !== \",\") {\n      if (state.tokens.next.nud) {\n\n        nobreaknonadjacent(state.tokens.curr, state.tokens.next);\n        this.first = expression(10);\n\n        if (this.first.type === \"(punctuator)\" && this.first.value === \"=\" &&\n            !this.first.paren && !state.option.boss) {\n          warningAt(\"W093\", this.first.line, this.first.character);\n        }\n      } else if (state.tokens.next.led) {\n        if (state.tokens.next.id !== \",\") {\n          error(\"W017\", state.tokens.next);\n        }\n      }\n    }\n\n    return this;\n  })));\n\n  /**\n   * Parsing logic for non-standard Mozilla implementation of `yield`\n   * expressions.\n   */\n  var mozYield = function() {\n    var prev = state.tokens.prev;\n    if (state.inES6(true) && !state.funct[\"(generator)\"]) {\n      // If it's a yield within a catch clause inside a generator then that's ok\n      if (!(\"(catch)\" === state.funct[\"(name)\"] && state.funct[\"(context)\"][\"(generator)\"])) {\n        error(\"E046\", state.tokens.curr, \"yield\");\n      }\n    }\n    state.funct[\"(generator)\"] = \"yielded\";\n    var delegatingYield = false;\n\n    if (state.tokens.next.value === \"*\") {\n      delegatingYield = true;\n      advance(\"*\");\n    }\n\n    if (this.line === startLine(state.tokens.next)) {\n      if (delegatingYield ||\n          (state.tokens.next.id !== \";\" && !state.option.asi &&\n           !state.tokens.next.reach && state.tokens.next.nud)) {\n\n        nobreaknonadjacent(state.tokens.curr, state.tokens.next);\n        this.first = expression(10);\n\n        if (this.first.type === \"(punctuator)\" && this.first.value === \"=\" &&\n            !this.first.paren && !state.option.boss) {\n          warningAt(\"W093\", this.first.line, this.first.character);\n        }\n      }\n\n      if (state.tokens.next.id !== \")\" &&\n          (prev.lbp > 30 || (!prev.assign && !isEndOfExpr()) || prev.id === \"yield\")) {\n        error(\"E050\", this);\n      }\n    } else if (!state.option.asi) {\n      nolinebreak(this); // always warn (Line breaking error)\n    }\n    return this;\n  };\n\n  stmt(\"throw\", function() {\n    nolinebreak(this);\n    this.first = expression(20);\n\n    reachable(this);\n\n    return this;\n  }).exps = true;\n\n  stmt(\"import\", function() {\n    if (!state.funct[\"(scope)\"].block.isGlobal()) {\n      error(\"E053\", state.tokens.curr, \"Import\");\n    }\n\n    if (!state.inES6()) {\n      warning(\"W119\", state.tokens.curr, \"import\", \"6\");\n    }\n\n    if (state.tokens.next.type === \"(string)\") {\n      // ModuleSpecifier :: StringLiteral\n      advance(\"(string)\");\n      return this;\n    }\n\n    if (state.tokens.next.identifier) {\n      // ImportClause :: ImportedDefaultBinding\n      this.name = identifier();\n      // Import bindings are immutable (see ES6 8.1.1.5.5)\n      state.funct[\"(scope)\"].addlabel(this.name, {\n        type: \"import\",\n        initialized: true,\n        token: state.tokens.curr });\n\n      if (state.tokens.next.value === \",\") {\n        // ImportClause :: ImportedDefaultBinding , NameSpaceImport\n        // ImportClause :: ImportedDefaultBinding , NamedImports\n        advance(\",\");\n        // At this point, we intentionally fall through to continue matching\n        // either NameSpaceImport or NamedImports.\n        // Discussion:\n        // https://github.com/jshint/jshint/pull/2144#discussion_r23978406\n      } else {\n        advance(\"from\");\n        advance(\"(string)\");\n        return this;\n      }\n    }\n\n    if (state.tokens.next.id === \"*\") {\n      // ImportClause :: NameSpaceImport\n      advance(\"*\");\n      advance(\"as\");\n      if (state.tokens.next.identifier) {\n        this.name = identifier();\n        // Import bindings are immutable (see ES6 8.1.1.5.5)\n        state.funct[\"(scope)\"].addlabel(this.name, {\n          type: \"import\",\n          initialized: true,\n          token: state.tokens.curr });\n      }\n    } else {\n      // ImportClause :: NamedImports\n      advance(\"{\");\n      for (;;) {\n        if (state.tokens.next.value === \"}\") {\n          advance(\"}\");\n          break;\n        }\n        var importName;\n        if (state.tokens.next.type === \"default\") {\n          importName = \"default\";\n          advance(\"default\");\n        } else {\n          importName = identifier();\n        }\n        if (state.tokens.next.value === \"as\") {\n          advance(\"as\");\n          importName = identifier();\n        }\n\n        // Import bindings are immutable (see ES6 8.1.1.5.5)\n        state.funct[\"(scope)\"].addlabel(importName, {\n          type: \"import\",\n          initialized: true,\n          token: state.tokens.curr });\n\n        if (state.tokens.next.value === \",\") {\n          advance(\",\");\n        } else if (state.tokens.next.value === \"}\") {\n          advance(\"}\");\n          break;\n        } else {\n          error(\"E024\", state.tokens.next, state.tokens.next.value);\n          break;\n        }\n      }\n    }\n\n    // FromClause\n    advance(\"from\");\n    advance(\"(string)\");\n\n    // Support for ES2015 modules was released without warning for `import`\n    // declarations that lack bindings. Issuing a warning would therefor\n    // constitute a breaking change.\n    // TODO: enable this warning in JSHint 3\n    // if (hasBindings) {\n    //   warning(\"W142\", this, \"import\", moduleSpecifier);\n    // }\n\n    return this;\n  }).exps = true;\n\n  stmt(\"export\", function() {\n    var ok = true;\n    var token;\n    var identifier;\n    var moduleSpecifier;\n\n    if (!state.inES6()) {\n      warning(\"W119\", state.tokens.curr, \"export\", \"6\");\n      ok = false;\n    }\n\n    if (!state.funct[\"(scope)\"].block.isGlobal()) {\n      error(\"E053\", state.tokens.curr, \"Export\");\n      ok = false;\n    }\n\n    if (state.tokens.next.value === \"*\") {\n      // ExportDeclaration :: export * FromClause\n      advance(\"*\");\n      advance(\"from\");\n      advance(\"(string)\");\n      return this;\n    }\n\n    if (state.tokens.next.type === \"default\") {\n      // ExportDeclaration ::\n      //      export default [lookahead ∉ { function, class }] AssignmentExpression[In] ;\n      //      export default HoistableDeclaration\n      //      export default ClassDeclaration\n      state.nameStack.set(state.tokens.next);\n      advance(\"default\");\n      var exportType = state.tokens.next.id;\n      if (exportType === \"function\" || exportType === \"class\") {\n        this.block = true;\n      }\n\n      token = peek();\n\n      expression(10);\n\n      identifier = token.value;\n\n      if (this.block) {\n        state.funct[\"(scope)\"].addlabel(identifier, {\n          type: exportType,\n          initialized: true,\n          token: token });\n\n        state.funct[\"(scope)\"].setExported(identifier, token);\n      }\n\n      return this;\n    }\n\n    if (state.tokens.next.value === \"{\") {\n      // ExportDeclaration :: export ExportClause\n      advance(\"{\");\n      var exportedTokens = [];\n      while (!checkPunctuator(state.tokens.next, \"}\")) {\n        if (!state.tokens.next.identifier) {\n          error(\"E030\", state.tokens.next, state.tokens.next.value);\n        }\n        advance();\n\n        exportedTokens.push(state.tokens.curr);\n\n        if (state.tokens.next.value === \"as\") {\n          advance(\"as\");\n          if (!state.tokens.next.identifier) {\n            error(\"E030\", state.tokens.next, state.tokens.next.value);\n          }\n          advance();\n        }\n\n        if (!checkPunctuator(state.tokens.next, \"}\")) {\n          advance(\",\");\n        }\n      }\n      advance(\"}\");\n      if (state.tokens.next.value === \"from\") {\n        // ExportDeclaration :: export ExportClause FromClause\n        advance(\"from\");\n        moduleSpecifier = state.tokens.next;\n        advance(\"(string)\");\n      } else if (ok) {\n        exportedTokens.forEach(function(token) {\n          state.funct[\"(scope)\"].setExported(token.value, token);\n        });\n      }\n\n      if (exportedTokens.length === 0) {\n        if (moduleSpecifier) {\n          warning(\"W142\", this, \"export\", moduleSpecifier.value);\n        } else {\n          warning(\"W141\", this, \"export\");\n        }\n      }\n\n      return this;\n    }\n\n    if (state.tokens.next.id === \"var\") {\n      // ExportDeclaration :: export VariableStatement\n      advance(\"var\");\n      state.tokens.curr.fud({ inexport:true });\n    } else if (state.tokens.next.id === \"let\") {\n      // ExportDeclaration :: export VariableStatement\n      advance(\"let\");\n      state.tokens.curr.fud({ inexport:true });\n    } else if (state.tokens.next.id === \"const\") {\n      // ExportDeclaration :: export VariableStatement\n      advance(\"const\");\n      state.tokens.curr.fud({ inexport:true });\n    } else if (state.tokens.next.id === \"function\") {\n      // ExportDeclaration :: export Declaration\n      this.block = true;\n      advance(\"function\");\n      state.syntax[\"function\"].fud({ inexport:true });\n    } else if (state.tokens.next.id === \"class\") {\n      // ExportDeclaration :: export Declaration\n      this.block = true;\n      advance(\"class\");\n      var classNameToken = state.tokens.next;\n      state.syntax[\"class\"].fud();\n      state.funct[\"(scope)\"].setExported(classNameToken.value, classNameToken);\n    } else {\n      error(\"E024\", state.tokens.next, state.tokens.next.value);\n    }\n\n    return this;\n  }).exps = true;\n\n  /**\n   * Determine if SuperCall or SuperProperty may be used in the current context\n   * (as described by the provided \"functor\" object).\n   *\n   * @param {string} type - one of \"property\" or \"call\"\n   * @param {object} funct - a \"functor\" object describing the current function\n   *                         context\n   *\n   * @returns {boolean}\n   */\n  function supportsSuper(type, funct) {\n    if (type === \"property\" && funct[\"(method)\"]) {\n      return true;\n    }\n\n    if (type === \"call\" && funct[\"(statement)\"] &&\n      funct[\"(statement)\"].id === \"class\") {\n      return true;\n    }\n\n    if (funct[\"(arrow)\"]) {\n      return supportsSuper(type, funct[\"(context)\"]);\n    }\n\n    return false;\n  }\n\n  var superNud = function() {\n    var next = state.tokens.next;\n\n    if (checkPunctuators(next, [\"[\", \".\"])) {\n      if (!supportsSuper(\"property\", state.funct)) {\n        error(\"E063\", this);\n      }\n    } else if (checkPunctuator(next, \"(\")) {\n      if (!supportsSuper(\"call\", state.funct)) {\n        error(\"E064\", this);\n      }\n    } else {\n      error(\"E024\", next, next.value || next.id);\n    }\n\n    return this;\n  };\n\n  // Future Reserved Words\n\n  FutureReservedWord(\"abstract\");\n  FutureReservedWord(\"await\", { es5: true, moduleOnly: true });\n  FutureReservedWord(\"boolean\");\n  FutureReservedWord(\"byte\");\n  FutureReservedWord(\"char\");\n  FutureReservedWord(\"class\", { es5: true, nud: classdef });\n  FutureReservedWord(\"double\");\n  FutureReservedWord(\"enum\", { es5: true });\n  FutureReservedWord(\"export\", { es5: true });\n  FutureReservedWord(\"extends\", { es5: true });\n  FutureReservedWord(\"final\");\n  FutureReservedWord(\"float\");\n  FutureReservedWord(\"goto\");\n  FutureReservedWord(\"implements\", { es5: true, strictOnly: true });\n  FutureReservedWord(\"import\", { es5: true });\n  FutureReservedWord(\"int\");\n  FutureReservedWord(\"interface\", { es5: true, strictOnly: true });\n  FutureReservedWord(\"long\");\n  FutureReservedWord(\"native\");\n  FutureReservedWord(\"package\", { es5: true, strictOnly: true });\n  FutureReservedWord(\"private\", { es5: true, strictOnly: true });\n  FutureReservedWord(\"protected\", { es5: true, strictOnly: true });\n  FutureReservedWord(\"public\", { es5: true, strictOnly: true });\n  FutureReservedWord(\"short\");\n  FutureReservedWord(\"static\", { es5: true, strictOnly: true });\n  FutureReservedWord(\"super\", { es5: true, nud: superNud });\n  FutureReservedWord(\"synchronized\");\n  FutureReservedWord(\"transient\");\n  FutureReservedWord(\"volatile\");\n\n  // this function is used to determine whether a squarebracket or a curlybracket\n  // expression is a comprehension array, destructuring assignment or a json value.\n\n  var lookupBlockType = function() {\n    var pn, pn1, prev;\n    var i = -1;\n    var bracketStack = 0;\n    var ret = {};\n    if (checkPunctuators(state.tokens.curr, [\"[\", \"{\"])) {\n      bracketStack += 1;\n    }\n    do {\n      prev = i === -1 ? state.tokens.curr : pn;\n      pn = i === -1 ? state.tokens.next : peek(i);\n      pn1 = peek(i + 1);\n      i = i + 1;\n      if (checkPunctuators(pn, [\"[\", \"{\"])) {\n        bracketStack += 1;\n      } else if (checkPunctuators(pn, [\"]\", \"}\"])) {\n        bracketStack -= 1;\n      }\n      if (bracketStack === 1 && pn.identifier && pn.value === \"for\" &&\n          !checkPunctuator(prev, \".\")) {\n        ret.isCompArray = true;\n        ret.notJson = true;\n        break;\n      }\n      if (bracketStack === 0 && checkPunctuators(pn, [\"}\", \"]\"])) {\n        if (pn1.value === \"=\") {\n          ret.isDestAssign = true;\n          ret.notJson = true;\n          break;\n        } else if (pn1.value === \".\") {\n          ret.notJson = true;\n          break;\n        }\n      }\n      if (checkPunctuator(pn, \";\")) {\n        ret.notJson = true;\n      }\n    } while (bracketStack > 0 && pn.id !== \"(end)\");\n    return ret;\n  };\n\n  function saveProperty(props, name, tkn, isClass, isStatic) {\n    var msg = [\"key\", \"class method\", \"static class method\"];\n    msg = msg[(isClass || false) + (isStatic || false)];\n    if (tkn.identifier) {\n      name = tkn.value;\n    }\n\n    if (props[name] && name !== \"__proto__\") {\n      warning(\"W075\", state.tokens.next, msg, name);\n    } else {\n      props[name] = Object.create(null);\n    }\n\n    props[name].basic = true;\n    props[name].basictkn = tkn;\n  }\n\n  /**\n   * @param {string} accessorType - Either \"get\" or \"set\"\n   * @param {object} props - a collection of all properties of the object to\n   *                         which the current accessor is being assigned\n   * @param {object} tkn - the identifier token representing the accessor name\n   * @param {boolean} isClass - whether the accessor is part of an ES6 Class\n   *                            definition\n   * @param {boolean} isStatic - whether the accessor is a static method\n   */\n  function saveAccessor(accessorType, props, name, tkn, isClass, isStatic) {\n    var flagName = accessorType === \"get\" ? \"getterToken\" : \"setterToken\";\n    var msg = \"\";\n\n    if (isClass) {\n      if (isStatic) {\n        msg += \"static \";\n      }\n      msg += accessorType + \"ter method\";\n    } else {\n      msg = \"key\";\n    }\n\n    state.tokens.curr.accessorType = accessorType;\n    state.nameStack.set(tkn);\n\n    if (props[name]) {\n      if ((props[name].basic || props[name][flagName]) && name !== \"__proto__\") {\n        warning(\"W075\", state.tokens.next, msg, name);\n      }\n    } else {\n      props[name] = Object.create(null);\n    }\n\n    props[name][flagName] = tkn;\n  }\n\n  function computedPropertyName() {\n    advance(\"[\");\n    if (!state.inES6()) {\n      warning(\"W119\", state.tokens.curr, \"computed property names\", \"6\");\n    }\n    var value = expression(10);\n    advance(\"]\");\n    return value;\n  }\n\n  /**\n   * Test whether a given token is a punctuator matching one of the specified values\n   * @param {Token} token\n   * @param {Array.<string>} values\n   * @returns {boolean}\n   */\n  function checkPunctuators(token, values) {\n    if (token.type === \"(punctuator)\") {\n      return _.includes(values, token.value);\n    }\n    return false;\n  }\n\n  /**\n   * Test whether a given token is a punctuator matching the specified value\n   * @param {Token} token\n   * @param {string} value\n   * @returns {boolean}\n   */\n  function checkPunctuator(token, value) {\n    return token.type === \"(punctuator)\" && token.value === value;\n  }\n\n  // Check whether this function has been reached for a destructuring assign with undeclared values\n  function destructuringAssignOrJsonValue() {\n    // lookup for the assignment (ECMAScript 6 only)\n    // if it has semicolons, it is a block, so go parse it as a block\n    // or it's not a block, but there are assignments, check for undeclared variables\n\n    var block = lookupBlockType();\n    if (block.notJson) {\n      if (!state.inES6() && block.isDestAssign) {\n        warning(\"W104\", state.tokens.curr, \"destructuring assignment\", \"6\");\n      }\n      statements();\n    // otherwise parse json value\n    } else {\n      state.option.laxbreak = true;\n      state.jsonMode = true;\n      jsonValue();\n    }\n  }\n\n  // array comprehension parsing function\n  // parses and defines the three states of the list comprehension in order\n  // to avoid defining global variables, but keeping them to the list comprehension scope\n  // only. The order of the states are as follows:\n  //  * \"use\" which will be the returned iterative part of the list comprehension\n  //  * \"define\" which will define the variables local to the list comprehension\n  //  * \"filter\" which will help filter out values\n\n  var arrayComprehension = function() {\n    var CompArray = function() {\n      this.mode = \"use\";\n      this.variables = [];\n    };\n    var _carrays = [];\n    var _current;\n    function declare(v) {\n      var l = _current.variables.filter(function(elt) {\n        // if it has, change its undef state\n        if (elt.value === v) {\n          elt.undef = false;\n          return v;\n        }\n      }).length;\n      return l !== 0;\n    }\n    function use(v) {\n      var l = _current.variables.filter(function(elt) {\n        // and if it has been defined\n        if (elt.value === v && !elt.undef) {\n          if (elt.unused === true) {\n            elt.unused = false;\n          }\n          return v;\n        }\n      }).length;\n      // otherwise we warn about it\n      return (l === 0);\n    }\n    return { stack: function() {\n          _current = new CompArray();\n          _carrays.push(_current);\n        },\n        unstack: function() {\n          _current.variables.filter(function(v) {\n            if (v.unused)\n              warning(\"W098\", v.token, v.token.raw_text || v.value);\n            if (v.undef)\n              state.funct[\"(scope)\"].block.use(v.value, v.token);\n          });\n          _carrays.splice(-1, 1);\n          _current = _carrays[_carrays.length - 1];\n        },\n        setState: function(s) {\n          if (_.includes([\"use\", \"define\", \"generate\", \"filter\"], s))\n            _current.mode = s;\n        },\n        check: function(v) {\n          if (!_current) {\n            return;\n          }\n          // When we are in \"use\" state of the list comp, we enqueue that var\n          if (_current && _current.mode === \"use\") {\n            if (use(v)) {\n              _current.variables.push({\n                token: state.tokens.curr,\n                value: v,\n                undef: true,\n                unused: false\n              });\n            }\n            return true;\n          // When we are in \"define\" state of the list comp,\n          } else if (_current && _current.mode === \"define\") {\n            // check if the variable has been used previously\n            if (!declare(v)) {\n              _current.variables.push({\n                token: state.tokens.curr,\n                value: v,\n                undef: false,\n                unused: true\n              });\n            }\n            return true;\n          // When we are in the \"generate\" state of the list comp,\n          } else if (_current && _current.mode === \"generate\") {\n            state.funct[\"(scope)\"].block.use(v, state.tokens.curr);\n            return true;\n          // When we are in \"filter\" state,\n          } else if (_current && _current.mode === \"filter\") {\n            // we check whether current variable has been declared\n            if (use(v)) {\n              // if not we warn about it\n              state.funct[\"(scope)\"].block.use(v, state.tokens.curr);\n            }\n            return true;\n          }\n          return false;\n        }\n        };\n  };\n\n\n  // Parse JSON\n\n  function jsonValue() {\n    function jsonObject() {\n      var o = {}, t = state.tokens.next;\n      advance(\"{\");\n      if (state.tokens.next.id !== \"}\") {\n        for (;;) {\n          if (state.tokens.next.id === \"(end)\") {\n            error(\"E026\", state.tokens.next, t.line);\n          } else if (state.tokens.next.id === \"}\") {\n            warning(\"W094\", state.tokens.curr);\n            break;\n          } else if (state.tokens.next.id === \",\") {\n            error(\"E028\", state.tokens.next);\n          } else if (state.tokens.next.id !== \"(string)\") {\n            warning(\"W095\", state.tokens.next, state.tokens.next.value);\n          }\n          if (o[state.tokens.next.value] === true) {\n            warning(\"W075\", state.tokens.next, \"key\", state.tokens.next.value);\n          } else if ((state.tokens.next.value === \"__proto__\" &&\n            !state.option.proto) || (state.tokens.next.value === \"__iterator__\" &&\n            !state.option.iterator)) {\n            warning(\"W096\", state.tokens.next, state.tokens.next.value);\n          } else {\n            o[state.tokens.next.value] = true;\n          }\n          advance();\n          advance(\":\");\n          jsonValue();\n          if (state.tokens.next.id !== \",\") {\n            break;\n          }\n          advance(\",\");\n        }\n      }\n      advance(\"}\");\n    }\n\n    function jsonArray() {\n      var t = state.tokens.next;\n      advance(\"[\");\n      if (state.tokens.next.id !== \"]\") {\n        for (;;) {\n          if (state.tokens.next.id === \"(end)\") {\n            error(\"E027\", state.tokens.next, t.line);\n          } else if (state.tokens.next.id === \"]\") {\n            warning(\"W094\", state.tokens.curr);\n            break;\n          } else if (state.tokens.next.id === \",\") {\n            error(\"E028\", state.tokens.next);\n          }\n          jsonValue();\n          if (state.tokens.next.id !== \",\") {\n            break;\n          }\n          advance(\",\");\n        }\n      }\n      advance(\"]\");\n    }\n\n    switch (state.tokens.next.id) {\n    case \"{\":\n      jsonObject();\n      break;\n    case \"[\":\n      jsonArray();\n      break;\n    case \"true\":\n    case \"false\":\n    case \"null\":\n    case \"(number)\":\n    case \"(string)\":\n      advance();\n      break;\n    case \"-\":\n      advance(\"-\");\n      advance(\"(number)\");\n      break;\n    default:\n      error(\"E003\", state.tokens.next);\n    }\n  }\n\n  /**\n   * Lint dynamically-evaluated code, appending any resulting errors/warnings\n   * into the global `errors` array.\n   *\n   * @param {array} internals - collection of \"internals\" objects describing\n   *                            string tokens that contain evaluated code\n   * @param {object} options - linting options to apply\n   * @param {object} globals - globally-defined bindings for the evaluated code\n   */\n  function lintEvalCode(internals, options, globals) {\n    var priorErrorCount, idx, jdx, internal;\n\n    for (idx = 0; idx < internals.length; idx += 1) {\n      internal = internals[idx];\n      options.scope = internal.elem;\n      priorErrorCount = JSHINT.errors.length;\n\n      itself(internal.code, options, globals);\n\n      for (jdx = priorErrorCount; jdx < JSHINT.errors.length; jdx += 1) {\n        JSHINT.errors[jdx].line += internal.token.line - 1;\n      }\n    }\n  }\n\n  var escapeRegex = function(str) {\n    return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n  };\n\n  // The actual JSHINT function itself.\n  var itself = function(s, o, g) {\n    var x, reIgnoreStr, reIgnore;\n    var optionKeys;\n    var newOptionObj = {};\n    var newIgnoredObj = {};\n\n    o = _.clone(o);\n    state.reset();\n\n    if (o && o.scope) {\n      JSHINT.scope = o.scope;\n    } else {\n      JSHINT.errors = [];\n      JSHINT.internals = [];\n      JSHINT.blacklist = {};\n      JSHINT.scope = \"(main)\";\n    }\n\n    predefined = Object.create(null);\n    combine(predefined, vars.ecmaIdentifiers[3]);\n    combine(predefined, vars.reservedVars);\n\n    combine(predefined, g || {});\n\n    declared = Object.create(null);\n    var exported = Object.create(null); // Variables that live outside the current file\n\n    function each(obj, cb) {\n      if (!obj)\n        return;\n\n      if (!Array.isArray(obj) && typeof obj === \"object\")\n        obj = Object.keys(obj);\n\n      obj.forEach(cb);\n    }\n\n    if (o) {\n      each(o.predef || null, function(item) {\n        var slice, prop;\n\n        if (item[0] === \"-\") {\n          slice = item.slice(1);\n          JSHINT.blacklist[slice] = slice;\n          // remove from predefined if there\n          delete predefined[slice];\n        } else {\n          prop = Object.getOwnPropertyDescriptor(o.predef, item);\n          predefined[item] = prop ? prop.value : false;\n        }\n      });\n\n      each(o.exported || null, function(item) {\n        exported[item] = true;\n      });\n\n      delete o.predef;\n      delete o.exported;\n\n      optionKeys = Object.keys(o);\n      for (x = 0; x < optionKeys.length; x++) {\n        if (/^-W\\d{3}$/g.test(optionKeys[x])) {\n          newIgnoredObj[optionKeys[x].slice(1)] = true;\n        } else {\n          var optionKey = optionKeys[x];\n          newOptionObj[optionKey] = o[optionKey];\n        }\n      }\n    }\n\n    state.option = newOptionObj;\n    state.ignored = newIgnoredObj;\n\n    state.option.indent = state.option.indent || 4;\n    state.option.maxerr = state.option.maxerr || 50;\n\n    indent = 1;\n\n    var scopeManagerInst = scopeManager(state, predefined, exported, declared);\n    scopeManagerInst.on(\"warning\", function(ev) {\n      warning.apply(null, [ ev.code, ev.token].concat(ev.data));\n    });\n\n    scopeManagerInst.on(\"error\", function(ev) {\n      error.apply(null, [ ev.code, ev.token ].concat(ev.data));\n    });\n\n    state.funct = functor(\"(global)\", null, {\n      \"(global)\"    : true,\n      \"(scope)\"     : scopeManagerInst,\n      \"(comparray)\" : arrayComprehension(),\n      \"(metrics)\"   : createMetrics(state.tokens.next)\n    });\n\n    functions = [state.funct];\n    urls = [];\n    member = {};\n    membersOnly = null;\n    inblock = false;\n    lookahead = [];\n\n    if (!isString(s) && !Array.isArray(s)) {\n      errorAt(\"E004\", 0);\n      return false;\n    }\n\n    api = {\n      get isJSON() {\n        return state.jsonMode;\n      },\n\n      getOption: function(name) {\n        return state.option[name] || null;\n      },\n\n      getCache: function(name) {\n        return state.cache[name];\n      },\n\n      setCache: function(name, value) {\n        state.cache[name] = value;\n      },\n\n      warn: function(code, data) {\n        warningAt.apply(null, [ code, data.line, data.char ].concat(data.data));\n      },\n\n      on: function(names, listener) {\n        names.split(\" \").forEach(function(name) {\n          emitter.on(name, listener);\n        }.bind(this));\n      }\n    };\n\n    emitter.removeAllListeners();\n    (extraModules || []).forEach(function(func) {\n      func(api);\n    });\n\n    state.tokens.prev = state.tokens.curr = state.tokens.next = state.syntax[\"(begin)\"];\n\n    if (o && o.ignoreDelimiters) {\n\n      if (!Array.isArray(o.ignoreDelimiters)) {\n        o.ignoreDelimiters = [o.ignoreDelimiters];\n      }\n\n      o.ignoreDelimiters.forEach(function(delimiterPair) {\n        if (!delimiterPair.start || !delimiterPair.end)\n            return;\n\n        reIgnoreStr = escapeRegex(delimiterPair.start) +\n                      \"[\\\\s\\\\S]*?\" +\n                      escapeRegex(delimiterPair.end);\n\n        reIgnore = new RegExp(reIgnoreStr, \"ig\");\n\n        s = s.replace(reIgnore, function(match) {\n          return match.replace(/./g, \" \");\n        });\n      });\n    }\n\n    lex = new Lexer(s);\n\n    lex.on(\"warning\", function(ev) {\n      warningAt.apply(null, [ ev.code, ev.line, ev.character].concat(ev.data));\n    });\n\n    lex.on(\"error\", function(ev) {\n      errorAt.apply(null, [ ev.code, ev.line, ev.character ].concat(ev.data));\n    });\n\n    lex.on(\"fatal\", function(ev) {\n      quit(\"E041\", ev);\n    });\n\n    lex.on(\"Identifier\", function(ev) {\n      emitter.emit(\"Identifier\", ev);\n    });\n\n    lex.on(\"String\", function(ev) {\n      emitter.emit(\"String\", ev);\n    });\n\n    lex.on(\"Number\", function(ev) {\n      emitter.emit(\"Number\", ev);\n    });\n\n    // Check options\n    for (var name in o) {\n      if (_.has(o, name)) {\n        checkOption(name, state.tokens.curr);\n      }\n    }\n\n    try {\n      applyOptions();\n\n      // combine the passed globals after we've assumed all our options\n      combine(predefined, g || {});\n\n      //reset values\n      parseComma.first = true;\n\n      advance();\n      switch (state.tokens.next.id) {\n      case \"{\":\n      case \"[\":\n        destructuringAssignOrJsonValue();\n        break;\n      default:\n        directives();\n\n        if (state.directive[\"use strict\"]) {\n          if (!state.allowsGlobalUsd()) {\n            warning(\"W097\", state.tokens.prev);\n          }\n        }\n\n        statements();\n      }\n\n      if (state.tokens.next.id !== \"(end)\") {\n        quit(\"E041\", state.tokens.curr);\n      }\n\n      state.funct[\"(scope)\"].unstack();\n\n    } catch (err) {\n      if (err && err.name === \"JSHintError\") {\n        var nt = state.tokens.next || {};\n        JSHINT.errors.push({\n          scope     : \"(main)\",\n          raw       : err.raw,\n          code      : err.code,\n          reason    : err.reason,\n          line      : err.line || nt.line,\n          character : err.character || nt.from\n        });\n      } else {\n        throw err;\n      }\n    }\n\n    // Loop over the listed \"internals\", and check them as well.\n    if (JSHINT.scope === \"(main)\") {\n      lintEvalCode(JSHINT.internals, o || {}, g);\n    }\n\n    return JSHINT.errors.length === 0;\n  };\n\n  // Modules.\n  itself.addModule = function(func) {\n    extraModules.push(func);\n  };\n\n  itself.addModule(style.register);\n\n  // Data summary.\n  itself.data = function() {\n    var data = {\n      functions: [],\n      options: state.option\n    };\n\n    var fu, f, i, n, globals;\n\n    if (itself.errors.length) {\n      data.errors = itself.errors;\n    }\n\n    if (state.jsonMode) {\n      data.json = true;\n    }\n\n    var impliedGlobals = state.funct[\"(scope)\"].getImpliedGlobals();\n    if (impliedGlobals.length > 0) {\n      data.implieds = impliedGlobals;\n    }\n\n    if (urls.length > 0) {\n      data.urls = urls;\n    }\n\n    globals = state.funct[\"(scope)\"].getUsedOrDefinedGlobals();\n    if (globals.length > 0) {\n      data.globals = globals;\n    }\n\n    for (i = 1; i < functions.length; i += 1) {\n      f = functions[i];\n      fu = {};\n\n      fu.name = f[\"(name)\"];\n      fu.param = f[\"(params)\"];\n      fu.line = f[\"(line)\"];\n      fu.character = f[\"(character)\"];\n      fu.last = f[\"(last)\"];\n      fu.lastcharacter = f[\"(lastcharacter)\"];\n\n      fu.metrics = {\n        complexity: f[\"(metrics)\"].ComplexityCount,\n        parameters: f[\"(metrics)\"].arity,\n        statements: f[\"(metrics)\"].statementCount\n      };\n\n      data.functions.push(fu);\n    }\n\n    var unuseds = state.funct[\"(scope)\"].getUnuseds();\n    if (unuseds.length > 0) {\n      data.unused = unuseds;\n    }\n\n    for (n in member) {\n      if (typeof member[n] === \"number\") {\n        data.member = member;\n        break;\n      }\n    }\n\n    return data;\n  };\n\n  itself.jshint = itself;\n\n  return itself;\n}());\n\n// Make JSHINT a Node module, if possible.\nif (typeof exports === \"object\" && exports) {\n  exports.JSHINT = JSHINT;\n}\n\n},{\"./lex.js\":14,\"./messages.js\":15,\"./options.js\":17,\"./reg.js\":18,\"./scope-manager.js\":19,\"./state.js\":20,\"./style.js\":21,\"./vars.js\":22,\"console-browserify\":11,\"events\":6,\"lodash\":13}]},{},[]);\n\nJSHINT = require('jshint').JSHINT;\nif (typeof exports === 'object' && exports) exports.JSHINT = JSHINT;\n}());"
  },
  {
    "path": "third_party/SVG-Edit/AUTHORS",
    "content": "Narendra Sisodiya <narendra@narendrasisodiya.com>\nPavol Rusnak <stick@gk2.sk>\nJeff Schiller <codedread@gmail.com>\nVidar Hokstad <vidar.hokstad@gmail.com>\nAlexis Deveria <adeveria@gmail.com>\nBrett Zamir <brettz9@yahoo.com>\n\nTranslation credits:\n\nar: Tarik Belaam <dubraise@gmail.com> (العربية)\ncs: Jan Ptacek <jan.ptacek@gmail.com> (Čeština)\nde: Reimar Bauer <rb.proj@googlemail.com> (Deutsch)\nes: Alicia Puerto <alicia.puerto.g@gmail.com> (Español)\nfa: Payman Delshad <payman@opera.com> (فارسی)\nfr: wormsxulla <wormsxulla@yahoo.com> (Français)\nfy: Wander Nauta <info@wandernauta.nl> (Frysk)\nhi: Tavish Naruka <tavishnaruka@gmail.com> (हिन्दी)\nja: Dong <iwadon@yarhalla.jpn.org> (日本語)\nnl: Jaap Blom <jaap.blom@gmail.com> (Nederlands)\nro: Christian Tzurcanu <christian.tzurcanu@gmail.com> (Româneşte)\nru: Laurent Dufloux <laurent.dufloux@etu.upmc.fr> (Русский)\nsk: Pavol Rusnak <stick@gk2.sk> (Slovenčina)\nzh-TW: 黃瀚生 (Han Sheng Huang) <zenixls2@gmail.com> (台灣正體)\n"
  },
  {
    "path": "third_party/SVG-Edit/LICENSE",
    "content": "Copyright (c) 2009-2018 by SVG-edit authors (see AUTHORS file)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "third_party/SVG-Edit/METADATA",
    "content": "name: \"SVG-Edit\"\ndescription:\n    \"SVG-Edit is an SVG editor embeddable in a webpage.\"\n\nthird_party {\n  url {\n    type: GIT\n    value: \"https://github.com/SVG-Edit/svgedit\"\n  }\n  version: \"a2df54881f6b3a4aabb646e60838ea6a7725c913\"\n  last_upgrade_date { year: 2018 month: 6 day: 11 }\n  license_type: NOTICE\n}\n"
  },
  {
    "path": "third_party/SVG-Edit/README.md",
    "content": "# ![alt text](https://svg-edit.github.io/svgedit/images/logo48x48.svg \"svg-edit logo of a pencil\") SVG-edit\n\nSVG-edit is a fast, web-based, javascript-driven SVG drawing editor that works in any modern browser.\n\n## Demo\n\n### [Try SVG-edit here](https://svg-edit.github.io/svgedit/releases/svg-edit-2.8.1/svg-editor.html)\n\n(Also available as a [download](https://github.com/SVG-Edit/svgedit/releases/download/svg-edit-2.8.1/svg-edit-2.8.1.zip) in [releases](https://github.com/SVG-Edit/svgedit/releases)).\n\nYou may also try the [pre-release](https://svg-edit.github.io/svgedit/releases/svg-edit-3.0.0-alpha.4/editor/svg-editor.html) (or the [ES6-Module](https://svg-edit.github.io/svgedit/releases/svg-edit-3.0.0-alpha.4/editor/svg-editor.html) version, assuming a modern browser).\n\n## Installation\n\nNote that steps 1-2 below are only necessary if you wish to integrate\nSVG-edit into your own npm package; otherwise, you can skip those steps\nand instead of looking within `node_modules/svgedit`, look within your\ncopy of the svgedit Git repo.\n\n1. Set up an npm package of your own: `npm init` (complete the fields).\n1. Install SVG-edit into your package: `npm i svgedit`\n1. Copy `svgedit-config-sample-es.js` (in the SVG-edit project root;\n    see `node_modules/svgedit`) to `svgedit-config-es.js`.\n  1. This will enable `svg-editor-es.html` to work, an HTML file directly\n    using ES6 modules. Note that this file only works on modern browsers.\n    The config file now imports the SVG edit code, minimizing the scripts\n    that need to be referenced in the HTML file.\n1. To also build a rolled-up, Babelified, non-ES Modules (IIFE)\n  JavaScript file which will allow `svg-editor.html` to work, a file\n  which does not rely on ES6 Modules support, follow these steps:\n  1. Run `npm install` within the `node_modules/svgedit` directory to\n    install the build tools for SVG-edit.\n  1. Run `npm run build-config` within the `node_modules/svgedit` directory.\n1. If you wish to make changes to the HTML, modify `svg-editor-es.html` and\n  then run `npm run build-html` to have the changes properly copied to\n  `svg-editor.html`.\n\n## Recent news\n  * 2018-05-26 Published 3.0.0-alpha.2 with ES6 Modules support\n  * 2017-07 Added to Packagist: https://packagist.org/packages/svg-edit/svgedit\n  * 2015-12-02 SVG-edit 2.8.1 was released.\n  * 2015-11-24 SVG-edit 2.8 was released.\n  * 2015-11-24 Code, issue tracking, and docs are being moved to github (previously [code.google.com](https://code.google.com/p/svg-edit)).\n  * 2014-04-17 2.7 and stable branches updated to reflect 2.7.1 important bug fixes for the embedded editor.\n  * 2014-04-07 SVG-edit 2.7 was released.\n  * 2013-01-15 SVG-edit 2.6 was released.\n\n## Videos\n\n  * [SVG-edit 2.4 Part 1](https://www.youtube.com/watch?v=zpC7b1ZJvvM)\n  * [SVG-edit 2.4 Part 2](https://www.youtube.com/watch?v=mDzZEoGUDe8)\n  * [SVG-edit 2.3 Features](https://www.youtube.com/watch?v=RVIcIy5fXOc)\n  * [Introduction to SVG-edit](https://www.youtube.com/watch?v=ZJKmEI06YiY) (Version 2.2)\n\n## Supported browsers\n\nThe following browsers had been tested for 2.6 or earlier and will probably continue to work with 2.8.\n  * Firefox 1.5+\n  * Opera 9.50+\n  * Safari 4+\n  * Chrome 1+\n  * IE 9+ and Edge\n\n## Further reading and more information\n\n * See [docs](docs/) for more documentation. See the [JSDocs for our latest release](https://svg-edit.github.io/svgedit/releases/svg-edit-3.0.0-alpha.4/docs/jsdoc/index.html).\n * [Acknowledgements](docs/Acknowledgements.md) lists open source projects used in svg-edit.\n * See [AUTHORS](AUTHORS) file for authors.\n * [Stackoverflow](https://stackoverflow.com/tags/svg-edit) group.\n * Join the [svg-edit mailing list](https://groups.google.com/forum/#!forum/svg-edit).\n * Join us on `#svg-edit` on `freenode.net` (or use the [web client](https://webchat.freenode.net/?channels=svg-edit)).\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/browser.js",
    "content": "/* globals jQuery */\n/**\n * Package: svgedit.browser\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2010 Jeff Schiller\n * Copyright(c) 2010 Alexis Deveria\n */\n\n// Dependencies:\n// 1) jQuery (for $.alert())\n\nimport './pathseg.js';\nimport {NS} from './svgedit.js';\n\nconst $ = jQuery;\n\nconst supportsSvg_ = (function () {\nreturn !!document.createElementNS && !!document.createElementNS(NS.SVG, 'svg').createSVGRect;\n}());\n\nexport const supportsSvg = () => supportsSvg_;\n\nconst {userAgent} = navigator;\nconst svg = document.createElementNS(NS.SVG, 'svg');\n\n// Note: Browser sniffing should only be used if no other detection method is possible\nconst isOpera_ = !!window.opera;\nconst isWebkit_ = userAgent.includes('AppleWebKit');\nconst isGecko_ = userAgent.includes('Gecko/');\nconst isIE_ = userAgent.includes('MSIE');\nconst isChrome_ = userAgent.includes('Chrome/');\nconst isWindows_ = userAgent.includes('Windows');\nconst isMac_ = userAgent.includes('Macintosh');\nconst isTouch_ = 'ontouchstart' in window;\n\nconst supportsSelectors_ = (function () {\nreturn !!svg.querySelector;\n}());\n\nconst supportsXpath_ = (function () {\nreturn !!document.evaluate;\n}());\n\n// segList functions (for FF1.5 and 2.0)\nconst supportsPathReplaceItem_ = (function () {\nconst path = document.createElementNS(NS.SVG, 'path');\npath.setAttribute('d', 'M0,0 10,10');\nconst seglist = path.pathSegList;\nconst seg = path.createSVGPathSegLinetoAbs(5, 5);\ntry {\n  seglist.replaceItem(seg, 1);\n  return true;\n} catch (err) {}\nreturn false;\n}());\n\nconst supportsPathInsertItemBefore_ = (function () {\nconst path = document.createElementNS(NS.SVG, 'path');\npath.setAttribute('d', 'M0,0 10,10');\nconst seglist = path.pathSegList;\nconst seg = path.createSVGPathSegLinetoAbs(5, 5);\ntry {\n  seglist.insertItemBefore(seg, 1);\n  return true;\n} catch (err) {}\nreturn false;\n}());\n\n// text character positioning (for IE9)\nconst supportsGoodTextCharPos_ = (function () {\nconst svgroot = document.createElementNS(NS.SVG, 'svg');\nconst svgcontent = document.createElementNS(NS.SVG, 'svg');\ndocument.documentElement.appendChild(svgroot);\nsvgcontent.setAttribute('x', 5);\nsvgroot.appendChild(svgcontent);\nconst text = document.createElementNS(NS.SVG, 'text');\ntext.textContent = 'a';\nsvgcontent.appendChild(text);\nconst pos = text.getStartPositionOfChar(0).x;\ndocument.documentElement.removeChild(svgroot);\nreturn (pos === 0);\n}());\n\nconst supportsPathBBox_ = (function () {\nconst svgcontent = document.createElementNS(NS.SVG, 'svg');\ndocument.documentElement.appendChild(svgcontent);\nconst path = document.createElementNS(NS.SVG, 'path');\npath.setAttribute('d', 'M0,0 C0,0 10,10 10,0');\nsvgcontent.appendChild(path);\nconst bbox = path.getBBox();\ndocument.documentElement.removeChild(svgcontent);\nreturn (bbox.height > 4 && bbox.height < 5);\n}());\n\n// Support for correct bbox sizing on groups with horizontal/vertical lines\nconst supportsHVLineContainerBBox_ = (function () {\nconst svgcontent = document.createElementNS(NS.SVG, 'svg');\ndocument.documentElement.appendChild(svgcontent);\nconst path = document.createElementNS(NS.SVG, 'path');\npath.setAttribute('d', 'M0,0 10,0');\nconst path2 = document.createElementNS(NS.SVG, 'path');\npath2.setAttribute('d', 'M5,0 15,0');\nconst g = document.createElementNS(NS.SVG, 'g');\ng.appendChild(path);\ng.appendChild(path2);\nsvgcontent.appendChild(g);\nconst bbox = g.getBBox();\ndocument.documentElement.removeChild(svgcontent);\n// Webkit gives 0, FF gives 10, Opera (correctly) gives 15\nreturn (bbox.width === 15);\n}());\n\nconst supportsEditableText_ = (function () {\n// TODO: Find better way to check support for this\nreturn isOpera_;\n}());\n\nconst supportsGoodDecimals_ = (function () {\n// Correct decimals on clone attributes (Opera < 10.5/win/non-en)\nconst rect = document.createElementNS(NS.SVG, 'rect');\nrect.setAttribute('x', 0.1);\nconst crect = rect.cloneNode(false);\nconst retValue = (!crect.getAttribute('x').includes(','));\nif (!retValue) {\n  // Todo: i18nize or remove\n  $.alert('NOTE: This version of Opera is known to contain bugs in SVG-edit.\\n' +\n\t'Please upgrade to the <a href=\"http://opera.com\">latest version</a> in which the problems have been fixed.');\n}\nreturn retValue;\n}());\n\nconst supportsNonScalingStroke_ = (function () {\nconst rect = document.createElementNS(NS.SVG, 'rect');\nrect.setAttribute('style', 'vector-effect:non-scaling-stroke');\nreturn rect.style.vectorEffect === 'non-scaling-stroke';\n}());\n\nlet supportsNativeSVGTransformLists_ = (function () {\nconst rect = document.createElementNS(NS.SVG, 'rect');\nconst rxform = rect.transform.baseVal;\nconst t1 = svg.createSVGTransform();\nrxform.appendItem(t1);\nconst r1 = rxform.getItem(0);\n// Todo: Do frame-independent instance checking\nreturn r1 instanceof SVGTransform && t1 instanceof SVGTransform &&\n\tr1.type === t1.type && r1.angle === t1.angle &&\n\tr1.matrix.a === t1.matrix.a &&\n\tr1.matrix.b === t1.matrix.b &&\n\tr1.matrix.c === t1.matrix.c &&\n\tr1.matrix.d === t1.matrix.d &&\n\tr1.matrix.e === t1.matrix.e &&\n\tr1.matrix.f === t1.matrix.f;\n}());\n\n// Public API\n\nexport const isOpera = () => isOpera_;\nexport const isWebkit = () => isWebkit_;\nexport const isGecko = () => isGecko_;\nexport const isIE = () => isIE_;\nexport const isChrome = () => isChrome_;\nexport const isWindows = () => isWindows_;\nexport const isMac = () => isMac_;\nexport const isTouch = () => isTouch_;\n\nexport const supportsSelectors = () => supportsSelectors_;\nexport const supportsXpath = () => supportsXpath_;\n\nexport const supportsPathReplaceItem = () => supportsPathReplaceItem_;\nexport const supportsPathInsertItemBefore = () => supportsPathInsertItemBefore_;\nexport const supportsPathBBox = () => supportsPathBBox_;\nexport const supportsHVLineContainerBBox = () => supportsHVLineContainerBBox_;\nexport const supportsGoodTextCharPos = () => supportsGoodTextCharPos_;\nexport const supportsEditableText = () => supportsEditableText_;\nexport const supportsGoodDecimals = () => supportsGoodDecimals_;\nexport const supportsNonScalingStroke = () => supportsNonScalingStroke_;\nexport const supportsNativeTransformLists = () => supportsNativeSVGTransformLists_;\n\n// Using for unit testing\nexport const disableSupportsNativeTransformLists = () => {\n  supportsNativeSVGTransformLists_ = false;\n};\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/canvg/canvg.js",
    "content": "/* eslint-disable new-cap */\n/* globals stackBlurCanvasRGBA, ActiveXObject */\n/*\n * canvg.js - Javascript SVG parser and renderer on Canvas\n * MIT Licensed\n * Gabe Lerner (gabelerner@gmail.com)\n * http://code.google.com/p/canvg/\n */\n\nimport RGBColor from './rgbcolor.js';\n\n// canvg(target, s)\n// empty parameters: replace all 'svg' elements on page with 'canvas' elements\n// target: canvas element or the id of a canvas element\n// s: svg string, url to svg file, or xml document\n// opts: optional hash of options\n//     ignoreMouse: true => ignore mouse events\n//     ignoreAnimation: true => ignore animations\n//     ignoreDimensions: true => does not try to resize canvas\n//     ignoreClear: true => does not clear canvas\n//     offsetX: int => draws at a x offset\n//     offsetY: int => draws at a y offset\n//     scaleWidth: int => scales horizontally to width\n//     scaleHeight: int => scales vertically to height\n//     renderCallback: function => will call the function after the first render is completed\n//     forceRedraw: function => will call the function on every frame, if it returns true, will redraw\nexport default function canvg (target, s, opts) {\n  // no parameters\n  if (target == null && s == null && opts == null) {\n    const svgTags = document.querySelectorAll('svg');\n    for (let i = 0; i < svgTags.length; i++) {\n      const svgTag = svgTags[i];\n      const c = document.createElement('canvas');\n      c.width = svgTag.clientWidth;\n      c.height = svgTag.clientHeight;\n      svgTag.parentNode.insertBefore(c, svgTag);\n      svgTag.parentNode.removeChild(svgTag);\n      const div = document.createElement('div');\n      div.appendChild(svgTag);\n      canvg(c, div.innerHTML);\n    }\n    return;\n  }\n\n  if (typeof target === 'string') {\n    target = document.getElementById(target);\n  }\n\n  // store class on canvas\n  if (target.svg != null) target.svg.stop();\n  const svg = build(opts || {});\n  // on i.e. 8 for flash canvas, we can't assign the property so check for it\n  if (!(target.childNodes.length === 1 && target.childNodes[0].nodeName === 'OBJECT')) {\n    target.svg = svg;\n  }\n\n  const ctx = target.getContext('2d');\n  if (typeof s.documentElement !== 'undefined') {\n    // load from xml doc\n    svg.loadXmlDoc(ctx, s);\n  } else if (s.substr(0, 1) === '<') {\n    // load from xml string\n    svg.loadXml(ctx, s);\n  } else {\n    // load from url\n    svg.load(ctx, s);\n  }\n}\n\nfunction build (opts) {\n  const svg = {opts};\n\n  svg.FRAMERATE = 30;\n  svg.MAX_VIRTUAL_PIXELS = 30000;\n\n  svg.log = function (msg) {};\n  if (svg.opts.log === true && typeof console !== 'undefined') {\n    svg.log = function (msg) { console.log(msg); };\n  }\n\n  // globals\n  svg.init = function (ctx) {\n    let uniqueId = 0;\n    svg.UniqueId = function () { uniqueId++; return 'canvg' + uniqueId; };\n    svg.Definitions = {};\n    svg.Styles = {};\n    svg.Animations = [];\n    svg.Images = [];\n    svg.ctx = ctx;\n    svg.ViewPort = new function () {\n      this.viewPorts = [];\n      this.Clear = function () { this.viewPorts = []; };\n      this.SetCurrent = function (width, height) { this.viewPorts.push({ width, height }); };\n      this.RemoveCurrent = function () { this.viewPorts.pop(); };\n      this.Current = function () { return this.viewPorts[this.viewPorts.length - 1]; };\n      this.width = function () { return this.Current().width; };\n      this.height = function () { return this.Current().height; };\n      this.ComputeSize = function (d) {\n        if (d != null && typeof d === 'number') return d;\n        if (d === 'x') return this.width();\n        if (d === 'y') return this.height();\n        return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2);\n      };\n    }();\n  };\n  svg.init();\n\n  // images loaded\n  svg.ImagesLoaded = function () {\n    for (let i = 0; i < svg.Images.length; i++) {\n      if (!svg.Images[i].loaded) return false;\n    }\n    return true;\n  };\n\n  // trim\n  svg.trim = function (s) { return s.replace(/^\\s+|\\s+$/g, ''); };\n\n  // compress spaces\n  svg.compressSpaces = function (s) { return s.replace(/[\\s\\r\\t\\n]+/gm, ' '); };\n\n  // ajax\n  svg.ajax = function (url) {\n    const AJAX = window.XMLHttpRequest\n      ? new XMLHttpRequest()\n      : new ActiveXObject('Microsoft.XMLHTTP');\n\n    if (AJAX) {\n      AJAX.open('GET', url, false);\n      AJAX.send(null);\n      return AJAX.responseText;\n    }\n    return null;\n  };\n\n  // parse xml\n  svg.parseXml = function (xml) {\n    if (window.DOMParser) {\n      const parser = new DOMParser();\n      return parser.parseFromString(xml, 'text/xml');\n    } else {\n      xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');\n      const xmlDoc = new ActiveXObject('Microsoft.XMLDOM');\n      xmlDoc.async = 'false';\n      xmlDoc.loadXML(xml);\n      return xmlDoc;\n    }\n  };\n\n  // text extensions\n  // get the text baseline\n  const textBaselineMapping = {\n    baseline: 'alphabetic',\n    'before-edge': 'top',\n    'text-before-edge': 'top',\n    middle: 'middle',\n    central: 'middle',\n    'after-edge': 'bottom',\n    'text-after-edge': 'bottom',\n    ideographic: 'ideographic',\n    alphabetic: 'alphabetic',\n    hanging: 'hanging',\n    mathematical: 'alphabetic'\n  };\n\n  svg.Property = class Property {\n    constructor (name, value) {\n      this.name = name;\n      this.value = value;\n    }\n\n    getValue () {\n      return this.value;\n    }\n\n    hasValue () {\n      return (this.value != null && this.value !== '');\n    }\n\n    // return the numerical value of the property\n    numValue () {\n      if (!this.hasValue()) return 0;\n\n      let n = parseFloat(this.value);\n      if ((this.value + '').match(/%$/)) {\n        n = n / 100.0;\n      }\n      return n;\n    }\n\n    valueOrDefault (def) {\n      if (this.hasValue()) return this.value;\n      return def;\n    }\n\n    numValueOrDefault (def) {\n      if (this.hasValue()) return this.numValue();\n      return def;\n    }\n\n    // color extensions\n    // augment the current color value with the opacity\n    addOpacity (opacityProp) {\n      let newValue = this.value;\n      if (opacityProp.value != null && opacityProp.value !== '' && typeof this.value === 'string') { // can only add opacity to colors, not patterns\n        const color = new RGBColor(this.value);\n        if (color.ok) {\n          newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacityProp.numValue() + ')';\n        }\n      }\n      return new svg.Property(this.name, newValue);\n    }\n\n    // definition extensions\n    // get the definition from the definitions table\n    getDefinition () {\n      let name = this.value.match(/#([^)'\"]+)/);\n      if (name) { name = name[1]; }\n      if (!name) { name = this.value; }\n      return svg.Definitions[name];\n    }\n\n    isUrlDefinition () {\n      return this.value.startsWith('url(');\n    }\n\n    getFillStyleDefinition (e, opacityProp) {\n      let def = this.getDefinition();\n\n      // gradient\n      if (def != null && def.createGradient) {\n        return def.createGradient(svg.ctx, e, opacityProp);\n      }\n\n      // pattern\n      if (def != null && def.createPattern) {\n        if (def.getHrefAttribute().hasValue()) {\n          const pt = def.attribute('patternTransform');\n          def = def.getHrefAttribute().getDefinition();\n          if (pt.hasValue()) { def.attribute('patternTransform', true).value = pt.value; }\n        }\n        return def.createPattern(svg.ctx, e);\n      }\n\n      return null;\n    }\n\n    // length extensions\n    getDPI (viewPort) {\n      return 96.0; // TODO: compute?\n    }\n\n    getEM (viewPort) {\n      let em = 12;\n\n      const fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);\n      if (fontSize.hasValue()) em = fontSize.toPixels(viewPort);\n\n      return em;\n    }\n\n    getUnits () {\n      const s = this.value + '';\n      return s.replace(/[0-9.-]/g, '');\n    }\n\n    // get the length as pixels\n    toPixels (viewPort, processPercent) {\n      if (!this.hasValue()) return 0;\n      const s = this.value + '';\n      if (s.match(/em$/)) return this.numValue() * this.getEM(viewPort);\n      if (s.match(/ex$/)) return this.numValue() * this.getEM(viewPort) / 2.0;\n      if (s.match(/px$/)) return this.numValue();\n      if (s.match(/pt$/)) return this.numValue() * this.getDPI(viewPort) * (1.0 / 72.0);\n      if (s.match(/pc$/)) return this.numValue() * 15;\n      if (s.match(/cm$/)) return this.numValue() * this.getDPI(viewPort) / 2.54;\n      if (s.match(/mm$/)) return this.numValue() * this.getDPI(viewPort) / 25.4;\n      if (s.match(/in$/)) return this.numValue() * this.getDPI(viewPort);\n      if (s.match(/%$/)) return this.numValue() * svg.ViewPort.ComputeSize(viewPort);\n      const n = this.numValue();\n      if (processPercent && n < 1.0) return n * svg.ViewPort.ComputeSize(viewPort);\n      return n;\n    }\n\n    // time extensions\n    // get the time as milliseconds\n    toMilliseconds () {\n      if (!this.hasValue()) return 0;\n      const s = this.value + '';\n      if (s.match(/s$/)) return this.numValue() * 1000;\n      if (s.match(/ms$/)) return this.numValue();\n      return this.numValue();\n    }\n\n    // angle extensions\n    // get the angle as radians\n    toRadians () {\n      if (!this.hasValue()) return 0;\n      const s = this.value + '';\n      if (s.match(/deg$/)) return this.numValue() * (Math.PI / 180.0);\n      if (s.match(/grad$/)) return this.numValue() * (Math.PI / 200.0);\n      if (s.match(/rad$/)) return this.numValue();\n      return this.numValue() * (Math.PI / 180.0);\n    }\n\n    toTextBaseline () {\n      if (!this.hasValue()) return null;\n      return textBaselineMapping[this.value];\n    }\n  };\n\n  // fonts\n  svg.Font = new function () {\n    this.Styles = 'normal|italic|oblique|inherit';\n    this.Variants = 'normal|small-caps|inherit';\n    this.Weights = 'normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit';\n\n    this.CreateFont = function (fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) {\n      const f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font);\n      return {\n        fontFamily: fontFamily || f.fontFamily,\n        fontSize: fontSize || f.fontSize,\n        fontStyle: fontStyle || f.fontStyle,\n        fontWeight: fontWeight || f.fontWeight,\n        fontVariant: fontVariant || f.fontVariant,\n        toString () {\n          return [\n            this.fontStyle, this.fontVariant, this.fontWeight,\n            this.fontSize, this.fontFamily\n          ].join(' ');\n        }\n      };\n    };\n\n    const that = this;\n    this.Parse = function (s) {\n      const f = {};\n      const d = svg.trim(svg.compressSpaces(s || '')).split(' ');\n      const set = {fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false};\n      let ff = '';\n      for (let i = 0; i < d.length; i++) {\n        if (!set.fontStyle && that.Styles.includes(d[i])) {\n          if (d[i] !== 'inherit') f.fontStyle = d[i]; set.fontStyle = true;\n        } else if (!set.fontVariant && that.Variants.includes(d[i])) {\n          if (d[i] !== 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true;\n        } else if (!set.fontWeight && that.Weights.includes(d[i])) {\n          if (d[i] !== 'inherit') f.fontWeight = d[i]; set.fontStyle = set.fontVariant = set.fontWeight = true;\n        } else if (!set.fontSize) {\n          if (d[i] !== 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true;\n        } else {\n          if (d[i] !== 'inherit') ff += d[i];\n        }\n      }\n      if (ff !== '') f.fontFamily = ff;\n      return f;\n    };\n  }();\n\n  // points and paths\n  svg.ToNumberArray = function (s) {\n    const a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' ');\n    for (let i = 0; i < a.length; i++) {\n      a[i] = parseFloat(a[i]);\n    }\n    return a;\n  };\n  svg.Point = class {\n    constructor (x, y) {\n      this.x = x;\n      this.y = y;\n    }\n\n    angleTo (p) {\n      return Math.atan2(p.y - this.y, p.x - this.x);\n    }\n\n    applyTransform (v) {\n      const xp = this.x * v[0] + this.y * v[2] + v[4];\n      const yp = this.x * v[1] + this.y * v[3] + v[5];\n      this.x = xp;\n      this.y = yp;\n    }\n  };\n\n  svg.CreatePoint = function (s) {\n    const a = svg.ToNumberArray(s);\n    return new svg.Point(a[0], a[1]);\n  };\n  svg.CreatePath = function (s) {\n    const a = svg.ToNumberArray(s);\n    const path = [];\n    for (let i = 0; i < a.length; i += 2) {\n      path.push(new svg.Point(a[i], a[i + 1]));\n    }\n    return path;\n  };\n\n  // bounding box\n  svg.BoundingBox = function (x1, y1, x2, y2) { // pass in initial points if you want\n    this.x1 = Number.NaN;\n    this.y1 = Number.NaN;\n    this.x2 = Number.NaN;\n    this.y2 = Number.NaN;\n\n    this.x = function () { return this.x1; };\n    this.y = function () { return this.y1; };\n    this.width = function () { return this.x2 - this.x1; };\n    this.height = function () { return this.y2 - this.y1; };\n\n    this.addPoint = function (x, y) {\n      if (x != null) {\n        if (isNaN(this.x1) || isNaN(this.x2)) {\n          this.x1 = x;\n          this.x2 = x;\n        }\n        if (x < this.x1) this.x1 = x;\n        if (x > this.x2) this.x2 = x;\n      }\n\n      if (y != null) {\n        if (isNaN(this.y1) || isNaN(this.y2)) {\n          this.y1 = y;\n          this.y2 = y;\n        }\n        if (y < this.y1) this.y1 = y;\n        if (y > this.y2) this.y2 = y;\n      }\n    };\n    this.addX = function (x) { this.addPoint(x, null); };\n    this.addY = function (y) { this.addPoint(null, y); };\n\n    this.addBoundingBox = function (bb) {\n      this.addPoint(bb.x1, bb.y1);\n      this.addPoint(bb.x2, bb.y2);\n    };\n\n    this.addQuadraticCurve = function (p0x, p0y, p1x, p1y, p2x, p2y) {\n      const cp1x = p0x + 2 / 3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0)\n      const cp1y = p0y + 2 / 3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0)\n      const cp2x = cp1x + 1 / 3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0)\n      const cp2y = cp1y + 1 / 3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0)\n      this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y);\n    };\n\n    this.addBezierCurve = function (p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {\n      // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html\n      const p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y];\n      this.addPoint(p0[0], p0[1]);\n      this.addPoint(p3[0], p3[1]);\n\n      for (let i = 0; i <= 1; i++) {\n        const f = function (t) {\n          return Math.pow(1 - t, 3) * p0[i] +\n          3 * Math.pow(1 - t, 2) * t * p1[i] +\n          3 * (1 - t) * Math.pow(t, 2) * p2[i] +\n          Math.pow(t, 3) * p3[i];\n        };\n\n        const b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];\n        const a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];\n        const c = 3 * p1[i] - 3 * p0[i];\n\n        if (a === 0) {\n          if (b === 0) continue;\n          const t = -c / b;\n          if (t > 0 && t < 1) {\n            if (i === 0) this.addX(f(t));\n            if (i === 1) this.addY(f(t));\n          }\n          continue;\n        }\n\n        const b2ac = Math.pow(b, 2) - 4 * c * a;\n        if (b2ac < 0) continue;\n        const t1 = (-b + Math.sqrt(b2ac)) / (2 * a);\n        if (t1 > 0 && t1 < 1) {\n          if (i === 0) this.addX(f(t1));\n          if (i === 1) this.addY(f(t1));\n        }\n        const t2 = (-b - Math.sqrt(b2ac)) / (2 * a);\n        if (t2 > 0 && t2 < 1) {\n          if (i === 0) this.addX(f(t2));\n          if (i === 1) this.addY(f(t2));\n        }\n      }\n    };\n\n    this.isPointInBox = function (x, y) {\n      return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2);\n    };\n\n    this.addPoint(x1, y1);\n    this.addPoint(x2, y2);\n  };\n\n  // transforms\n  svg.Transform = function (v) {\n    this.Type = {};\n\n    // translate\n    this.Type.translate = function (s) {\n      this.p = svg.CreatePoint(s);\n      this.apply = function (ctx) {\n        ctx.translate(this.p.x || 0.0, this.p.y || 0.0);\n      };\n      this.unapply = function (ctx) {\n        ctx.translate(-1.0 * this.p.x || 0.0, -1.0 * this.p.y || 0.0);\n      };\n      this.applyToPoint = function (p) {\n        p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);\n      };\n    };\n\n    // rotate\n    this.Type.rotate = function (s) {\n      const a = svg.ToNumberArray(s);\n      this.angle = new svg.Property('angle', a[0]);\n      this.cx = a[1] || 0;\n      this.cy = a[2] || 0;\n      this.apply = function (ctx) {\n        ctx.translate(this.cx, this.cy);\n        ctx.rotate(this.angle.toRadians());\n        ctx.translate(-this.cx, -this.cy);\n      };\n      this.unapply = function (ctx) {\n        ctx.translate(this.cx, this.cy);\n        ctx.rotate(-1.0 * this.angle.toRadians());\n        ctx.translate(-this.cx, -this.cy);\n      };\n      this.applyToPoint = function (p) {\n        const a = this.angle.toRadians();\n        p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);\n        p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]);\n        p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]);\n      };\n    };\n\n    this.Type.scale = function (s) {\n      this.p = svg.CreatePoint(s);\n      this.apply = function (ctx) {\n        ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0);\n      };\n      this.unapply = function (ctx) {\n        ctx.scale(1.0 / this.p.x || 1.0, 1.0 / this.p.y || this.p.x || 1.0);\n      };\n      this.applyToPoint = function (p) {\n        p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]);\n      };\n    };\n\n    this.Type.matrix = function (s) {\n      this.m = svg.ToNumberArray(s);\n      this.apply = function (ctx) {\n        ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);\n      };\n      this.applyToPoint = function (p) {\n        p.applyTransform(this.m);\n      };\n    };\n\n    this.Type.SkewBase = class extends this.Type.matrix {\n      constructor (s) {\n        super(s);\n        this.angle = new svg.Property('angle', s);\n      }\n    };\n\n    this.Type.skewX = class extends this.Type.SkewBase {\n      constructor (s) {\n        super(s);\n        this.m = [1, 0, Math.tan(this.angle.toRadians()), 1, 0, 0];\n      }\n    };\n\n    this.Type.skewY = class extends this.Type.SkewBase {\n      constructor (s) {\n        super(s);\n        this.m = [1, Math.tan(this.angle.toRadians()), 0, 1, 0, 0];\n      }\n    };\n\n    this.transforms = [];\n\n    this.apply = function (ctx) {\n      for (let i = 0; i < this.transforms.length; i++) {\n        this.transforms[i].apply(ctx);\n      }\n    };\n\n    this.unapply = function (ctx) {\n      for (let i = this.transforms.length - 1; i >= 0; i--) {\n        this.transforms[i].unapply(ctx);\n      }\n    };\n\n    this.applyToPoint = function (p) {\n      for (let i = 0; i < this.transforms.length; i++) {\n        this.transforms[i].applyToPoint(p);\n      }\n    };\n\n    const data = svg.trim(svg.compressSpaces(v)).replace(/\\)([a-zA-Z])/g, ') $1').replace(/\\)(\\s?,\\s?)/g, ') ').split(/\\s(?=[a-z])/);\n    for (let i = 0; i < data.length; i++) {\n      const type = svg.trim(data[i].split('(')[0]);\n      const s = data[i].split('(')[1].replace(')', '');\n      const transform = new this.Type[type](s);\n      transform.type = type;\n      this.transforms.push(transform);\n    }\n  };\n\n  // aspect ratio\n  svg.AspectRatio = function (ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {\n    // aspect ratio - https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute\n    aspectRatio = svg.compressSpaces(aspectRatio);\n    aspectRatio = aspectRatio.replace(/^defer\\s/, ''); // ignore defer\n    const align = aspectRatio.split(' ')[0] || 'xMidYMid';\n    const meetOrSlice = aspectRatio.split(' ')[1] || 'meet';\n\n    // calculate scale\n    const scaleX = width / desiredWidth;\n    const scaleY = height / desiredHeight;\n    const scaleMin = Math.min(scaleX, scaleY);\n    const scaleMax = Math.max(scaleX, scaleY);\n    if (meetOrSlice === 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; }\n    if (meetOrSlice === 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; }\n\n    refX = new svg.Property('refX', refX);\n    refY = new svg.Property('refY', refY);\n    if (refX.hasValue() && refY.hasValue()) {\n      ctx.translate(-scaleMin * refX.toPixels('x'), -scaleMin * refY.toPixels('y'));\n    } else {\n      // align\n      if (align.match(/^xMid/) && ((meetOrSlice === 'meet' && scaleMin === scaleY) || (meetOrSlice === 'slice' && scaleMax === scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);\n      if (align.match(/YMid$/) && ((meetOrSlice === 'meet' && scaleMin === scaleX) || (meetOrSlice === 'slice' && scaleMax === scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);\n      if (align.match(/^xMax/) && ((meetOrSlice === 'meet' && scaleMin === scaleY) || (meetOrSlice === 'slice' && scaleMax === scaleY))) ctx.translate(width - desiredWidth, 0);\n      if (align.match(/YMax$/) && ((meetOrSlice === 'meet' && scaleMin === scaleX) || (meetOrSlice === 'slice' && scaleMax === scaleX))) ctx.translate(0, height - desiredHeight);\n    }\n\n    // scale\n    if (align === 'none') ctx.scale(scaleX, scaleY);\n    else if (meetOrSlice === 'meet') ctx.scale(scaleMin, scaleMin);\n    else if (meetOrSlice === 'slice') ctx.scale(scaleMax, scaleMax);\n\n    // translate\n    ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);\n  };\n\n  // elements\n  svg.Element = {};\n\n  svg.EmptyProperty = new svg.Property('EMPTY', '');\n\n  svg.Element.ElementBase = function (node) {\n    this.attributes = {};\n    this.styles = {};\n    this.children = [];\n\n    // get or create attribute\n    this.attribute = function (name, createIfNotExists) {\n      let a = this.attributes[name];\n      if (a != null) return a;\n\n      if (createIfNotExists === true) { a = new svg.Property(name, ''); this.attributes[name] = a; }\n      return a || svg.EmptyProperty;\n    };\n\n    this.getHrefAttribute = function () {\n      for (const a in this.attributes) {\n        if (a.match(/:href$/)) {\n          return this.attributes[a];\n        }\n      }\n      return svg.EmptyProperty;\n    };\n\n    // get or create style, crawls up node tree\n    this.style = function (name, createIfNotExists, skipAncestors) {\n      let s = this.styles[name];\n      if (s != null) return s;\n\n      const a = this.attribute(name);\n      if (a != null && a.hasValue()) {\n        this.styles[name] = a; // move up to me to cache\n        return a;\n      }\n\n      if (skipAncestors !== true) {\n        const p = this.parent;\n        if (p != null) {\n          const ps = p.style(name);\n          if (ps != null && ps.hasValue()) {\n            return ps;\n          }\n        }\n      }\n\n      if (createIfNotExists === true) { s = new svg.Property(name, ''); this.styles[name] = s; }\n      return s || svg.EmptyProperty;\n    };\n\n    // base render\n    this.render = function (ctx) {\n      // don't render display=none\n      if (this.style('display').value === 'none') return;\n\n      // don't render visibility=hidden\n      if (this.style('visibility').value === 'hidden') return;\n\n      ctx.save();\n      if (this.attribute('mask').hasValue()) { // mask\n        const mask = this.attribute('mask').getDefinition();\n        if (mask != null) mask.apply(ctx, this);\n      } else if (this.style('filter').hasValue()) { // filter\n        const filter = this.style('filter').getDefinition();\n        if (filter != null) filter.apply(ctx, this);\n      } else {\n        this.setContext(ctx);\n        this.renderChildren(ctx);\n        this.clearContext(ctx);\n      }\n      ctx.restore();\n    };\n\n    // base set context\n    this.setContext = function (ctx) {\n      // OVERRIDE ME!\n    };\n\n    // base clear context\n    this.clearContext = function (ctx) {\n      // OVERRIDE ME!\n    };\n\n    // base render children\n    this.renderChildren = function (ctx) {\n      for (let i = 0; i < this.children.length; i++) {\n        this.children[i].render(ctx);\n      }\n    };\n\n    this.addChild = function (childNode, create) {\n      const child = create\n        ? svg.CreateElement(childNode)\n        : childNode;\n      child.parent = this;\n      if (child.type !== 'title') { this.children.push(child); }\n    };\n\n    if (node != null && node.nodeType === 1) { // ELEMENT_NODE\n      // add children\n      for (let i = 0, childNode; (childNode = node.childNodes[i]); i++) {\n        if (childNode.nodeType === 1) this.addChild(childNode, true); // ELEMENT_NODE\n        if (this.captureTextNodes && (childNode.nodeType === 3 || childNode.nodeType === 4)) {\n          const text = childNode.nodeValue || childNode.text || '';\n          if (svg.trim(svg.compressSpaces(text)) !== '') {\n            this.addChild(new svg.Element.tspan(childNode), false); // TEXT_NODE\n          }\n        }\n      }\n\n      // add attributes\n      for (let i = 0; i < node.attributes.length; i++) {\n        const attribute = node.attributes[i];\n        this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue);\n      }\n\n      // add tag styles\n      let styles = svg.Styles[node.nodeName];\n      if (styles != null) {\n        for (const name in styles) {\n          this.styles[name] = styles[name];\n        }\n      }\n\n      // add class styles\n      if (this.attribute('class').hasValue()) {\n        const classes = svg.compressSpaces(this.attribute('class').value).split(' ');\n        for (let j = 0; j < classes.length; j++) {\n          styles = svg.Styles['.' + classes[j]];\n          if (styles != null) {\n            for (const name in styles) {\n              this.styles[name] = styles[name];\n            }\n          }\n          styles = svg.Styles[node.nodeName + '.' + classes[j]];\n          if (styles != null) {\n            for (const name in styles) {\n              this.styles[name] = styles[name];\n            }\n          }\n        }\n      }\n\n      // add id styles\n      if (this.attribute('id').hasValue()) {\n        const styles = svg.Styles['#' + this.attribute('id').value];\n        if (styles != null) {\n          for (const name in styles) {\n            this.styles[name] = styles[name];\n          }\n        }\n      }\n\n      // add inline styles\n      if (this.attribute('style').hasValue()) {\n        const styles = this.attribute('style').value.split(';');\n        for (let i = 0; i < styles.length; i++) {\n          if (svg.trim(styles[i]) !== '') {\n            const style = styles[i].split(':');\n            const name = svg.trim(style[0]);\n            const value = svg.trim(style[1]);\n            this.styles[name] = new svg.Property(name, value);\n          }\n        }\n      }\n\n      // add id\n      if (this.attribute('id').hasValue()) {\n        if (svg.Definitions[this.attribute('id').value] == null) {\n          svg.Definitions[this.attribute('id').value] = this;\n        }\n      }\n    }\n  };\n\n  svg.Element.RenderedElementBase = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.setContext = function (ctx) {\n        // fill\n        if (this.style('fill').isUrlDefinition()) {\n          const fs = this.style('fill').getFillStyleDefinition(this, this.style('fill-opacity'));\n          if (fs != null) ctx.fillStyle = fs;\n        } else if (this.style('fill').hasValue()) {\n          const fillStyle = this.style('fill');\n          if (fillStyle.value === 'currentColor') fillStyle.value = this.style('color').value;\n          ctx.fillStyle = (fillStyle.value === 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);\n        }\n        if (this.style('fill-opacity').hasValue()) {\n          let fillStyle = new svg.Property('fill', ctx.fillStyle);\n          fillStyle = fillStyle.addOpacity(this.style('fill-opacity'));\n          ctx.fillStyle = fillStyle.value;\n        }\n\n        // stroke\n        if (this.style('stroke').isUrlDefinition()) {\n          const fs = this.style('stroke').getFillStyleDefinition(this, this.style('stroke-opacity'));\n          if (fs != null) ctx.strokeStyle = fs;\n        } else if (this.style('stroke').hasValue()) {\n          const strokeStyle = this.style('stroke');\n          if (strokeStyle.value === 'currentColor') strokeStyle.value = this.style('color').value;\n          ctx.strokeStyle = (strokeStyle.value === 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);\n        }\n        if (this.style('stroke-opacity').hasValue()) {\n          let strokeStyle = new svg.Property('stroke', ctx.strokeStyle);\n          strokeStyle = strokeStyle.addOpacity(this.style('stroke-opacity'));\n          ctx.strokeStyle = strokeStyle.value;\n        }\n        if (this.style('stroke-width').hasValue()) {\n          const newLineWidth = this.style('stroke-width').toPixels();\n          ctx.lineWidth = newLineWidth === 0 ? 0.001 : newLineWidth; // browsers don't respect 0\n        }\n        if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;\n        if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;\n        if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;\n        if (this.style('stroke-dasharray').hasValue() && this.style('stroke-dasharray').value !== 'none') {\n          const gaps = svg.ToNumberArray(this.style('stroke-dasharray').value);\n          if (typeof ctx.setLineDash !== 'undefined') {\n            ctx.setLineDash(gaps);\n          } else if (typeof ctx.webkitLineDash !== 'undefined') {\n            ctx.webkitLineDash = gaps;\n          } else if (typeof ctx.mozDash !== 'undefined' && !(gaps.length === 1 && gaps[0] === 0)) {\n            ctx.mozDash = gaps;\n          }\n\n          const offset = this.style('stroke-dashoffset').numValueOrDefault(1);\n          if (typeof ctx.lineDashOffset !== 'undefined') {\n            ctx.lineDashOffset = offset;\n          } else if (typeof ctx.webkitLineDashOffset !== 'undefined') {\n            ctx.webkitLineDashOffset = offset;\n          } else if (typeof ctx.mozDashOffset !== 'undefined') {\n            ctx.mozDashOffset = offset;\n          }\n        }\n\n        // font\n        if (typeof ctx.font !== 'undefined') {\n          ctx.font = svg.Font.CreateFont(\n            this.style('font-style').value,\n            this.style('font-variant').value,\n            this.style('font-weight').value,\n            this.style('font-size').hasValue() ? this.style('font-size').toPixels() + 'px' : '',\n            this.style('font-family').value).toString();\n        }\n\n        // transform\n        if (this.attribute('transform').hasValue()) {\n          const transform = new svg.Transform(this.attribute('transform').value);\n          transform.apply(ctx);\n        }\n\n        // clip\n        if (this.style('clip-path', false, true).hasValue()) {\n          const clip = this.style('clip-path', false, true).getDefinition();\n          if (clip != null) clip.apply(ctx);\n        }\n\n        // opacity\n        if (this.style('opacity').hasValue()) {\n          ctx.globalAlpha = this.style('opacity').numValue();\n        }\n      };\n    }\n  };\n\n  svg.Element.PathElementBase = class extends svg.Element.RenderedElementBase {\n    constructor (node) {\n      super(node);\n\n      this.path = function (ctx) {\n        if (ctx != null) ctx.beginPath();\n        return new svg.BoundingBox();\n      };\n\n      this.renderChildren = function (ctx) {\n        this.path(ctx);\n        svg.Mouse.checkPath(this, ctx);\n        if (ctx.fillStyle !== '') {\n          if (this.style('fill-rule').valueOrDefault('inherit') !== 'inherit') {\n            ctx.fill(this.style('fill-rule').value);\n          } else {\n            ctx.fill();\n          }\n        }\n        if (ctx.strokeStyle !== '') ctx.stroke();\n\n        const markers = this.getMarkers();\n        if (markers != null) {\n          if (this.style('marker-start').isUrlDefinition()) {\n            const marker = this.style('marker-start').getDefinition();\n            marker.render(ctx, markers[0][0], markers[0][1]);\n          }\n          if (this.style('marker-mid').isUrlDefinition()) {\n            const marker = this.style('marker-mid').getDefinition();\n            for (let i = 1; i < markers.length - 1; i++) {\n              marker.render(ctx, markers[i][0], markers[i][1]);\n            }\n          }\n          if (this.style('marker-end').isUrlDefinition()) {\n            const marker = this.style('marker-end').getDefinition();\n            marker.render(ctx, markers[markers.length - 1][0], markers[markers.length - 1][1]);\n          }\n        }\n      };\n\n      this.getBoundingBox = function () {\n        return this.path();\n      };\n\n      this.getMarkers = function () {\n        return null;\n      };\n    }\n  };\n\n  // svg element\n  svg.Element.svg = class extends svg.Element.RenderedElementBase {\n    constructor (node) {\n      super(node);\n\n      this.baseClearContext = this.clearContext;\n      this.clearContext = function (ctx) {\n        this.baseClearContext(ctx);\n        svg.ViewPort.RemoveCurrent();\n      };\n\n      this.baseSetContext = this.setContext;\n      this.setContext = function (ctx) {\n        // initial values and defaults\n        ctx.strokeStyle = 'rgba(0,0,0,0)';\n        ctx.lineCap = 'butt';\n        ctx.lineJoin = 'miter';\n        ctx.miterLimit = 4;\n        if (typeof ctx.font !== 'undefined' && typeof window.getComputedStyle !== 'undefined') {\n          ctx.font = window.getComputedStyle(ctx.canvas).getPropertyValue('font');\n        }\n\n        this.baseSetContext(ctx);\n\n        // create new view port\n        if (!this.attribute('x').hasValue()) this.attribute('x', true).value = 0;\n        if (!this.attribute('y').hasValue()) this.attribute('y', true).value = 0;\n        ctx.translate(this.attribute('x').toPixels('x'), this.attribute('y').toPixels('y'));\n\n        let width = svg.ViewPort.width();\n        let height = svg.ViewPort.height();\n\n        if (!this.attribute('width').hasValue()) this.attribute('width', true).value = '100%';\n        if (!this.attribute('height').hasValue()) this.attribute('height', true).value = '100%';\n        if (typeof this.root === 'undefined') {\n          width = this.attribute('width').toPixels('x');\n          height = this.attribute('height').toPixels('y');\n\n          let x = 0;\n          let y = 0;\n          if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {\n            x = -this.attribute('refX').toPixels('x');\n            y = -this.attribute('refY').toPixels('y');\n          }\n\n          if (this.attribute('overflow').valueOrDefault('hidden') !== 'visible') {\n            ctx.beginPath();\n            ctx.moveTo(x, y);\n            ctx.lineTo(width, y);\n            ctx.lineTo(width, height);\n            ctx.lineTo(x, height);\n            ctx.closePath();\n            ctx.clip();\n          }\n        }\n        svg.ViewPort.SetCurrent(width, height);\n\n        // viewbox\n        if (this.attribute('viewBox').hasValue()) {\n          const viewBox = svg.ToNumberArray(this.attribute('viewBox').value);\n          const minX = viewBox[0];\n          const minY = viewBox[1];\n          width = viewBox[2];\n          height = viewBox[3];\n\n          svg.AspectRatio(\n            ctx,\n            this.attribute('preserveAspectRatio').value,\n            svg.ViewPort.width(),\n            width,\n            svg.ViewPort.height(),\n            height,\n            minX,\n            minY,\n            this.attribute('refX').value,\n            this.attribute('refY').value\n          );\n\n          svg.ViewPort.RemoveCurrent();\n          svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);\n        }\n      };\n    }\n  };\n\n  // rect element\n  svg.Element.rect = class extends svg.Element.PathElementBase {\n    constructor (node) {\n      super(node);\n\n      this.path = function (ctx) {\n        const x = this.attribute('x').toPixels('x');\n        const y = this.attribute('y').toPixels('y');\n        const width = this.attribute('width').toPixels('x');\n        const height = this.attribute('height').toPixels('y');\n        let rx = this.attribute('rx').toPixels('x');\n        let ry = this.attribute('ry').toPixels('y');\n        if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;\n        if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;\n        rx = Math.min(rx, width / 2.0);\n        ry = Math.min(ry, height / 2.0);\n        if (ctx != null) {\n          ctx.beginPath();\n          ctx.moveTo(x + rx, y);\n          ctx.lineTo(x + width - rx, y);\n          ctx.quadraticCurveTo(x + width, y, x + width, y + ry);\n          ctx.lineTo(x + width, y + height - ry);\n          ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height);\n          ctx.lineTo(x + rx, y + height);\n          ctx.quadraticCurveTo(x, y + height, x, y + height - ry);\n          ctx.lineTo(x, y + ry);\n          ctx.quadraticCurveTo(x, y, x + rx, y);\n          ctx.closePath();\n        }\n\n        return new svg.BoundingBox(x, y, x + width, y + height);\n      };\n    }\n  };\n\n  // circle element\n  svg.Element.circle = class extends svg.Element.PathElementBase {\n    constructor (node) {\n      super(node);\n\n      this.path = function (ctx) {\n        const cx = this.attribute('cx').toPixels('x');\n        const cy = this.attribute('cy').toPixels('y');\n        const r = this.attribute('r').toPixels();\n\n        if (ctx != null) {\n          ctx.beginPath();\n          ctx.arc(cx, cy, r, 0, Math.PI * 2, true);\n          ctx.closePath();\n        }\n\n        return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);\n      };\n    }\n  };\n\n  // ellipse element\n  svg.Element.ellipse = class extends svg.Element.PathElementBase {\n    constructor (node) {\n      super(node);\n\n      this.path = function (ctx) {\n        const KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);\n        const rx = this.attribute('rx').toPixels('x');\n        const ry = this.attribute('ry').toPixels('y');\n        const cx = this.attribute('cx').toPixels('x');\n        const cy = this.attribute('cy').toPixels('y');\n\n        if (ctx != null) {\n          ctx.beginPath();\n          ctx.moveTo(cx, cy - ry);\n          ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);\n          ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);\n          ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);\n          ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);\n          ctx.closePath();\n        }\n\n        return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);\n      };\n    }\n  };\n\n  // line element\n  svg.Element.line = class extends svg.Element.PathElementBase {\n    constructor (node) {\n      super(node);\n\n      this.getPoints = function () {\n        return [\n          new svg.Point(this.attribute('x1').toPixels('x'), this.attribute('y1').toPixels('y')),\n          new svg.Point(this.attribute('x2').toPixels('x'), this.attribute('y2').toPixels('y'))];\n      };\n\n      this.path = function (ctx) {\n        const points = this.getPoints();\n\n        if (ctx != null) {\n          ctx.beginPath();\n          ctx.moveTo(points[0].x, points[0].y);\n          ctx.lineTo(points[1].x, points[1].y);\n        }\n\n        return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);\n      };\n\n      this.getMarkers = function () {\n        const points = this.getPoints();\n        const a = points[0].angleTo(points[1]);\n        return [[points[0], a], [points[1], a]];\n      };\n    }\n  };\n\n  // polyline element\n  svg.Element.polyline = class extends svg.Element.PathElementBase {\n    constructor (node) {\n      super(node);\n\n      this.points = svg.CreatePath(this.attribute('points').value);\n      this.path = function (ctx) {\n        const bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);\n        if (ctx != null) {\n          ctx.beginPath();\n          ctx.moveTo(this.points[0].x, this.points[0].y);\n        }\n        for (let i = 1; i < this.points.length; i++) {\n          bb.addPoint(this.points[i].x, this.points[i].y);\n          if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);\n        }\n        return bb;\n      };\n\n      this.getMarkers = function () {\n        const markers = [];\n        for (let i = 0; i < this.points.length - 1; i++) {\n          markers.push([this.points[i], this.points[i].angleTo(this.points[i + 1])]);\n        }\n        markers.push([this.points[this.points.length - 1], markers[markers.length - 1][1]]);\n        return markers;\n      };\n    }\n  };\n\n  // polygon element\n  svg.Element.polygon = class extends svg.Element.polyline {\n    constructor (node) {\n      super(node);\n\n      this.basePath = this.path;\n      this.path = function (ctx) {\n        const bb = this.basePath(ctx);\n        if (ctx != null) {\n          ctx.lineTo(this.points[0].x, this.points[0].y);\n          ctx.closePath();\n        }\n        return bb;\n      };\n    }\n  };\n\n  // path element\n  svg.Element.path = class extends svg.Element.PathElementBase {\n    constructor (node) {\n      super(node);\n\n      let d = this.attribute('d').value;\n      // TODO: convert to real lexer based on https://www.w3.org/TR/SVG11/paths.html#PathDataBNF\n      d = d.replace(/,/gm, ' '); // get rid of all commas\n      d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2'); // separate commands from commands\n      d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2'); // separate commands from commands\n      d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\\s])/gm, '$1 $2'); // separate commands from points\n      d = d.replace(/([^\\s])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2'); // separate commands from points\n      d = d.replace(/([0-9])([+-])/gm, '$1 $2'); // separate digits when no comma\n      d = d.replace(/(\\.[0-9]*)(\\.)/gm, '$1 $2'); // separate digits when no comma\n      d = d.replace(/([Aa](\\s+[0-9]+){3})\\s+([01])\\s*([01])/gm, '$1 $3 $4 '); // shorthand elliptical arc path syntax\n      d = svg.compressSpaces(d); // compress multiple spaces\n      d = svg.trim(d);\n      this.PathParser = new function (d) {\n        this.tokens = d.split(' ');\n\n        this.reset = function () {\n          this.i = -1;\n          this.command = '';\n          this.previousCommand = '';\n          this.start = new svg.Point(0, 0);\n          this.control = new svg.Point(0, 0);\n          this.current = new svg.Point(0, 0);\n          this.points = [];\n          this.angles = [];\n        };\n\n        this.isEnd = function () {\n          return this.i >= this.tokens.length - 1;\n        };\n\n        this.isCommandOrEnd = function () {\n          if (this.isEnd()) return true;\n          return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null;\n        };\n\n        this.isRelativeCommand = function () {\n          switch (this.command) {\n          case 'm':\n          case 'l':\n          case 'h':\n          case 'v':\n          case 'c':\n          case 's':\n          case 'q':\n          case 't':\n          case 'a':\n          case 'z':\n            return true;\n          }\n          return false;\n        };\n\n        this.getToken = function () {\n          this.i++;\n          return this.tokens[this.i];\n        };\n\n        this.getScalar = function () {\n          return parseFloat(this.getToken());\n        };\n\n        this.nextCommand = function () {\n          this.previousCommand = this.command;\n          this.command = this.getToken();\n        };\n\n        this.getPoint = function () {\n          const p = new svg.Point(this.getScalar(), this.getScalar());\n          return this.makeAbsolute(p);\n        };\n\n        this.getAsControlPoint = function () {\n          const p = this.getPoint();\n          this.control = p;\n          return p;\n        };\n\n        this.getAsCurrentPoint = function () {\n          const p = this.getPoint();\n          this.current = p;\n          return p;\n        };\n\n        this.getReflectedControlPoint = function () {\n          if (this.previousCommand.toLowerCase() !== 'c' &&\n            this.previousCommand.toLowerCase() !== 's' &&\n            this.previousCommand.toLowerCase() !== 'q' &&\n            this.previousCommand.toLowerCase() !== 't') {\n            return this.current;\n          }\n\n          // reflect point\n          const p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);\n          return p;\n        };\n\n        this.makeAbsolute = function (p) {\n          if (this.isRelativeCommand()) {\n            p.x += this.current.x;\n            p.y += this.current.y;\n          }\n          return p;\n        };\n\n        this.addMarker = function (p, from, priorTo) {\n          // if the last angle isn't filled in because we didn't have this point yet ...\n          if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length - 1] == null) {\n            this.angles[this.angles.length - 1] = this.points[this.points.length - 1].angleTo(priorTo);\n          }\n          this.addMarkerAngle(p, from == null ? null : from.angleTo(p));\n        };\n\n        this.addMarkerAngle = function (p, a) {\n          this.points.push(p);\n          this.angles.push(a);\n        };\n\n        this.getMarkerPoints = function () { return this.points; };\n        this.getMarkerAngles = function () {\n          for (let i = 0; i < this.angles.length; i++) {\n            if (this.angles[i] == null) {\n              for (let j = i + 1; j < this.angles.length; j++) {\n                if (this.angles[j] != null) {\n                  this.angles[i] = this.angles[j];\n                  break;\n                }\n              }\n            }\n          }\n          return this.angles;\n        };\n      }(d);\n\n      this.path = function (ctx) {\n        const pp = this.PathParser;\n        pp.reset();\n\n        const bb = new svg.BoundingBox();\n        if (ctx != null) ctx.beginPath();\n        while (!pp.isEnd()) {\n          pp.nextCommand();\n          switch (pp.command) {\n          case 'M':\n          case 'm':\n            const p = pp.getAsCurrentPoint();\n            pp.addMarker(p);\n            bb.addPoint(p.x, p.y);\n            if (ctx != null) ctx.moveTo(p.x, p.y);\n            pp.start = pp.current;\n            while (!pp.isCommandOrEnd()) {\n              const p = pp.getAsCurrentPoint();\n              pp.addMarker(p, pp.start);\n              bb.addPoint(p.x, p.y);\n              if (ctx != null) ctx.lineTo(p.x, p.y);\n            }\n            break;\n          case 'L':\n          case 'l':\n            while (!pp.isCommandOrEnd()) {\n              const c = pp.current;\n              const p = pp.getAsCurrentPoint();\n              pp.addMarker(p, c);\n              bb.addPoint(p.x, p.y);\n              if (ctx != null) ctx.lineTo(p.x, p.y);\n            }\n            break;\n          case 'H':\n          case 'h':\n            while (!pp.isCommandOrEnd()) {\n              const newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);\n              pp.addMarker(newP, pp.current);\n              pp.current = newP;\n              bb.addPoint(pp.current.x, pp.current.y);\n              if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);\n            }\n            break;\n          case 'V':\n          case 'v':\n            while (!pp.isCommandOrEnd()) {\n              const newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());\n              pp.addMarker(newP, pp.current);\n              pp.current = newP;\n              bb.addPoint(pp.current.x, pp.current.y);\n              if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);\n            }\n            break;\n          case 'C':\n          case 'c':\n            while (!pp.isCommandOrEnd()) {\n              const curr = pp.current;\n              const p1 = pp.getPoint();\n              const cntrl = pp.getAsControlPoint();\n              const cp = pp.getAsCurrentPoint();\n              pp.addMarker(cp, cntrl, p1);\n              bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);\n              if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);\n            }\n            break;\n          case 'S':\n          case 's':\n            while (!pp.isCommandOrEnd()) {\n              const curr = pp.current;\n              const p1 = pp.getReflectedControlPoint();\n              const cntrl = pp.getAsControlPoint();\n              const cp = pp.getAsCurrentPoint();\n              pp.addMarker(cp, cntrl, p1);\n              bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);\n              if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);\n            }\n            break;\n          case 'Q':\n          case 'q':\n            while (!pp.isCommandOrEnd()) {\n              const curr = pp.current;\n              const cntrl = pp.getAsControlPoint();\n              const cp = pp.getAsCurrentPoint();\n              pp.addMarker(cp, cntrl, cntrl);\n              bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);\n              if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);\n            }\n            break;\n          case 'T':\n          case 't':\n            while (!pp.isCommandOrEnd()) {\n              const curr = pp.current;\n              const cntrl = pp.getReflectedControlPoint();\n              pp.control = cntrl;\n              const cp = pp.getAsCurrentPoint();\n              pp.addMarker(cp, cntrl, cntrl);\n              bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);\n              if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);\n            }\n            break;\n          case 'A':\n          case 'a':\n            while (!pp.isCommandOrEnd()) {\n              const curr = pp.current;\n              let rx = pp.getScalar();\n              let ry = pp.getScalar();\n              const xAxisRotation = pp.getScalar() * (Math.PI / 180.0);\n              const largeArcFlag = pp.getScalar();\n              const sweepFlag = pp.getScalar();\n              const cp = pp.getAsCurrentPoint();\n\n              // Conversion from endpoint to center parameterization\n              // https://www.w3.org/TR/SVG11/implnote.html#ArcConversionEndpointToCenter\n\n              // x1', y1'\n              const currp = new svg.Point(\n                Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,\n                -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0\n              );\n              // adjust radii\n              const l = Math.pow(currp.x, 2) / Math.pow(rx, 2) + Math.pow(currp.y, 2) / Math.pow(ry, 2);\n              if (l > 1) {\n                rx *= Math.sqrt(l);\n                ry *= Math.sqrt(l);\n              }\n              // cx', cy'\n              let s = (largeArcFlag === sweepFlag ? -1 : 1) * Math.sqrt(\n                ((Math.pow(rx, 2) * Math.pow(ry, 2)) - (Math.pow(rx, 2) * Math.pow(currp.y, 2)) - (Math.pow(ry, 2) * Math.pow(currp.x, 2))) /\n                (Math.pow(rx, 2) * Math.pow(currp.y, 2) + Math.pow(ry, 2) * Math.pow(currp.x, 2))\n              );\n              if (isNaN(s)) s = 0;\n              const cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);\n              // cx, cy\n              const centp = new svg.Point(\n                (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,\n                (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y\n              );\n              // vector magnitude\n              const m = function (v) { return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2)); };\n              // ratio between two vectors\n              const r = function (u, v) { return (u[0] * v[0] + u[1] * v[1]) / (m(u) * m(v)); };\n              // angle between two vectors\n              const a = function (u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(r(u, v)); };\n              // initial angle\n              const a1 = a([1, 0], [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]);\n              // angle delta\n              const u = [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry];\n              const v = [(-currp.x - cpp.x) / rx, (-currp.y - cpp.y) / ry];\n              let ad = a(u, v);\n              if (r(u, v) <= -1) ad = Math.PI;\n              if (r(u, v) >= 1) ad = 0;\n\n              // for markers\n              const dir = 1 - sweepFlag ? 1.0 : -1.0;\n              const ah = a1 + dir * (ad / 2.0);\n              const halfWay = new svg.Point(\n                centp.x + rx * Math.cos(ah),\n                centp.y + ry * Math.sin(ah)\n              );\n              pp.addMarkerAngle(halfWay, ah - dir * Math.PI / 2);\n              pp.addMarkerAngle(cp, ah - dir * Math.PI);\n\n              bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better\n              if (ctx != null) {\n                const r = rx > ry ? rx : ry;\n                const sx = rx > ry ? 1 : rx / ry;\n                const sy = rx > ry ? ry / rx : 1;\n\n                ctx.translate(centp.x, centp.y);\n                ctx.rotate(xAxisRotation);\n                ctx.scale(sx, sy);\n                ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);\n                ctx.scale(1 / sx, 1 / sy);\n                ctx.rotate(-xAxisRotation);\n                ctx.translate(-centp.x, -centp.y);\n              }\n            }\n            break;\n          case 'Z':\n          case 'z':\n            if (ctx != null) ctx.closePath();\n            pp.current = pp.start;\n          }\n        }\n\n        return bb;\n      };\n\n      this.getMarkers = function () {\n        const points = this.PathParser.getMarkerPoints();\n        const angles = this.PathParser.getMarkerAngles();\n\n        const markers = [];\n        for (let i = 0; i < points.length; i++) {\n          markers.push([points[i], angles[i]]);\n        }\n        return markers;\n      };\n    }\n  };\n\n  // pattern element\n  svg.Element.pattern = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.createPattern = function (ctx, element) {\n        const width = this.attribute('width').toPixels('x', true);\n        const height = this.attribute('height').toPixels('y', true);\n\n        // render me using a temporary svg element\n        const tempSvg = new svg.Element.svg();\n        tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);\n        tempSvg.attributes['width'] = new svg.Property('width', width + 'px');\n        tempSvg.attributes['height'] = new svg.Property('height', height + 'px');\n        tempSvg.attributes['transform'] = new svg.Property('transform', this.attribute('patternTransform').value);\n        tempSvg.children = this.children;\n\n        const c = document.createElement('canvas');\n        c.width = width;\n        c.height = height;\n        const cctx = c.getContext('2d');\n        if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {\n          cctx.translate(this.attribute('x').toPixels('x', true), this.attribute('y').toPixels('y', true));\n        }\n        // render 3x3 grid so when we transform there's no white space on edges\n        for (let x = -1; x <= 1; x++) {\n          for (let y = -1; y <= 1; y++) {\n            cctx.save();\n            cctx.translate(x * c.width, y * c.height);\n            tempSvg.render(cctx);\n            cctx.restore();\n          }\n        }\n        const pattern = ctx.createPattern(c, 'repeat');\n        return pattern;\n      };\n    }\n  };\n\n  // marker element\n  svg.Element.marker = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.baseRender = this.render;\n      this.render = function (ctx, point, angle) {\n        ctx.translate(point.x, point.y);\n        if (this.attribute('orient').valueOrDefault('auto') === 'auto') ctx.rotate(angle);\n        if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);\n        ctx.save();\n\n        // render me using a temporary svg element\n        const tempSvg = new svg.Element.svg();\n        tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);\n        tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);\n        tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);\n        tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);\n        tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);\n        tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));\n        tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));\n        tempSvg.children = this.children;\n        tempSvg.render(ctx);\n\n        ctx.restore();\n        if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(1 / ctx.lineWidth, 1 / ctx.lineWidth);\n        if (this.attribute('orient').valueOrDefault('auto') === 'auto') ctx.rotate(-angle);\n        ctx.translate(-point.x, -point.y);\n      };\n    }\n  };\n\n  // definitions element\n  svg.Element.defs = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.render = function (ctx) {\n        // NOOP\n      };\n    }\n  };\n\n  // base for gradients\n  svg.Element.GradientBase = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');\n\n      this.stops = [];\n      for (let i = 0; i < this.children.length; i++) {\n        const child = this.children[i];\n        if (child.type === 'stop') this.stops.push(child);\n      }\n\n      this.getGradient = function () {\n        // OVERRIDE ME!\n      };\n\n      this.createGradient = function (ctx, element, parentOpacityProp) {\n        const stopsContainer = this.getHrefAttribute().hasValue()\n          ? this.getHrefAttribute().getDefinition()\n          : this;\n\n        const addParentOpacity = function (color) {\n          if (parentOpacityProp.hasValue()) {\n            const p = new svg.Property('color', color);\n            return p.addOpacity(parentOpacityProp).value;\n          }\n          return color;\n        };\n\n        const g = this.getGradient(ctx, element);\n        if (g == null) return addParentOpacity(stopsContainer.stops[stopsContainer.stops.length - 1].color);\n        for (let i = 0; i < stopsContainer.stops.length; i++) {\n          g.addColorStop(stopsContainer.stops[i].offset, addParentOpacity(stopsContainer.stops[i].color));\n        }\n\n        if (this.attribute('gradientTransform').hasValue()) {\n          // render as transformed pattern on temporary canvas\n          const rootView = svg.ViewPort.viewPorts[0];\n\n          const rect = new svg.Element.rect();\n          rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS / 3.0);\n          rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS / 3.0);\n          rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS);\n          rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS);\n\n          const group = new svg.Element.g();\n          group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value);\n          group.children = [ rect ];\n\n          const tempSvg = new svg.Element.svg();\n          tempSvg.attributes['x'] = new svg.Property('x', 0);\n          tempSvg.attributes['y'] = new svg.Property('y', 0);\n          tempSvg.attributes['width'] = new svg.Property('width', rootView.width);\n          tempSvg.attributes['height'] = new svg.Property('height', rootView.height);\n          tempSvg.children = [ group ];\n\n          const c = document.createElement('canvas');\n          c.width = rootView.width;\n          c.height = rootView.height;\n          const tempCtx = c.getContext('2d');\n          tempCtx.fillStyle = g;\n          tempSvg.render(tempCtx);\n          return tempCtx.createPattern(c, 'no-repeat');\n        }\n\n        return g;\n      };\n    }\n  };\n\n  // linear gradient element\n  svg.Element.linearGradient = class extends svg.Element.GradientBase {\n    constructor (node) {\n      super(node);\n\n      this.getGradient = function (ctx, element) {\n        const bb = this.gradientUnits === 'objectBoundingBox'\n          ? element.getBoundingBox()\n          : null;\n\n        if (!this.attribute('x1').hasValue() &&\n          !this.attribute('y1').hasValue() &&\n          !this.attribute('x2').hasValue() &&\n          !this.attribute('y2').hasValue()\n        ) {\n          this.attribute('x1', true).value = 0;\n          this.attribute('y1', true).value = 0;\n          this.attribute('x2', true).value = 1;\n          this.attribute('y2', true).value = 0;\n        }\n\n        const x1 = (this.gradientUnits === 'objectBoundingBox'\n          ? bb.x() + bb.width() * this.attribute('x1').numValue()\n          : this.attribute('x1').toPixels('x'));\n        const y1 = (this.gradientUnits === 'objectBoundingBox'\n          ? bb.y() + bb.height() * this.attribute('y1').numValue()\n          : this.attribute('y1').toPixels('y'));\n        const x2 = (this.gradientUnits === 'objectBoundingBox'\n          ? bb.x() + bb.width() * this.attribute('x2').numValue()\n          : this.attribute('x2').toPixels('x'));\n        const y2 = (this.gradientUnits === 'objectBoundingBox'\n          ? bb.y() + bb.height() * this.attribute('y2').numValue()\n          : this.attribute('y2').toPixels('y'));\n\n        if (x1 === x2 && y1 === y2) return null;\n        return ctx.createLinearGradient(x1, y1, x2, y2);\n      };\n    }\n  };\n\n  // radial gradient element\n  svg.Element.radialGradient = class extends svg.Element.GradientBase {\n    constructor (node) {\n      super(node);\n\n      this.getGradient = function (ctx, element) {\n        const bb = element.getBoundingBox();\n\n        if (!this.attribute('cx').hasValue()) this.attribute('cx', true).value = '50%';\n        if (!this.attribute('cy').hasValue()) this.attribute('cy', true).value = '50%';\n        if (!this.attribute('r').hasValue()) this.attribute('r', true).value = '50%';\n\n        const cx = (this.gradientUnits === 'objectBoundingBox'\n          ? bb.x() + bb.width() * this.attribute('cx').numValue()\n          : this.attribute('cx').toPixels('x'));\n        const cy = (this.gradientUnits === 'objectBoundingBox'\n          ? bb.y() + bb.height() * this.attribute('cy').numValue()\n          : this.attribute('cy').toPixels('y'));\n\n        let fx = cx;\n        let fy = cy;\n        if (this.attribute('fx').hasValue()) {\n          fx = (this.gradientUnits === 'objectBoundingBox'\n            ? bb.x() + bb.width() * this.attribute('fx').numValue()\n            : this.attribute('fx').toPixels('x'));\n        }\n        if (this.attribute('fy').hasValue()) {\n          fy = (this.gradientUnits === 'objectBoundingBox'\n            ? bb.y() + bb.height() * this.attribute('fy').numValue()\n            : this.attribute('fy').toPixels('y'));\n        }\n\n        const r = (this.gradientUnits === 'objectBoundingBox'\n          ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue()\n          : this.attribute('r').toPixels());\n\n        return ctx.createRadialGradient(fx, fy, 0, cx, cy, r);\n      };\n    }\n  };\n\n  // gradient stop element\n  svg.Element.stop = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.offset = this.attribute('offset').numValue();\n      if (this.offset < 0) this.offset = 0;\n      if (this.offset > 1) this.offset = 1;\n\n      let stopColor = this.style('stop-color');\n      if (this.style('stop-opacity').hasValue()) {\n        stopColor = stopColor.addOpacity(this.style('stop-opacity'));\n      }\n      this.color = stopColor.value;\n    }\n  };\n\n  // animation base element\n  svg.Element.AnimateBase = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      svg.Animations.push(this);\n\n      this.duration = 0.0;\n      this.begin = this.attribute('begin').toMilliseconds();\n      this.maxDuration = this.begin + this.attribute('dur').toMilliseconds();\n\n      this.getProperty = function () {\n        const attributeType = this.attribute('attributeType').value;\n        const attributeName = this.attribute('attributeName').value;\n\n        if (attributeType === 'CSS') {\n          return this.parent.style(attributeName, true);\n        }\n        return this.parent.attribute(attributeName, true);\n      };\n\n      this.initialValue = null;\n      this.initialUnits = '';\n      this.removed = false;\n\n      this.calcValue = function () {\n        // OVERRIDE ME!\n        return '';\n      };\n\n      this.update = function (delta) {\n        // set initial value\n        if (this.initialValue == null) {\n          this.initialValue = this.getProperty().value;\n          this.initialUnits = this.getProperty().getUnits();\n        }\n\n        // if we're past the end time\n        if (this.duration > this.maxDuration) {\n          // loop for indefinitely repeating animations\n          if (this.attribute('repeatCount').value === 'indefinite' ||\n            this.attribute('repeatDur').value === 'indefinite') {\n            this.duration = 0.0;\n          } else if (this.attribute('fill').valueOrDefault('remove') === 'freeze' && !this.frozen) {\n            this.frozen = true;\n            this.parent.animationFrozen = true;\n            this.parent.animationFrozenValue = this.getProperty().value;\n          } else if (this.attribute('fill').valueOrDefault('remove') === 'remove' && !this.removed) {\n            this.removed = true;\n            this.getProperty().value = this.parent.animationFrozen ? this.parent.animationFrozenValue : this.initialValue;\n            return true;\n          }\n          return false;\n        }\n        this.duration = this.duration + delta;\n\n        // if we're past the begin time\n        let updated = false;\n        if (this.begin < this.duration) {\n          let newValue = this.calcValue(); // tween\n\n          if (this.attribute('type').hasValue()) {\n            // for transform, etc.\n            const type = this.attribute('type').value;\n            newValue = type + '(' + newValue + ')';\n          }\n\n          this.getProperty().value = newValue;\n          updated = true;\n        }\n\n        return updated;\n      };\n\n      this.from = this.attribute('from');\n      this.to = this.attribute('to');\n      this.values = this.attribute('values');\n      if (this.values.hasValue()) this.values.value = this.values.value.split(';');\n\n      // fraction of duration we've covered\n      this.progress = function () {\n        const ret = { progress: (this.duration - this.begin) / (this.maxDuration - this.begin) };\n        if (this.values.hasValue()) {\n          const p = ret.progress * (this.values.value.length - 1);\n          const lb = Math.floor(p), ub = Math.ceil(p);\n          ret.from = new svg.Property('from', parseFloat(this.values.value[lb]));\n          ret.to = new svg.Property('to', parseFloat(this.values.value[ub]));\n          ret.progress = (p - lb) / (ub - lb);\n        } else {\n          ret.from = this.from;\n          ret.to = this.to;\n        }\n        return ret;\n      };\n    }\n  };\n\n  // animate element\n  svg.Element.animate = class extends svg.Element.AnimateBase {\n    constructor (node) {\n      super(node);\n\n      this.calcValue = function () {\n        const p = this.progress();\n\n        // tween value linearly\n        const newValue = p.from.numValue() + (p.to.numValue() - p.from.numValue()) * p.progress;\n        return newValue + this.initialUnits;\n      };\n    }\n  };\n\n  // animate color element\n  svg.Element.animateColor = class extends svg.Element.AnimateBase {\n    constructor (node) {\n      super(node);\n\n      this.calcValue = function () {\n        const p = this.progress();\n        const from = new RGBColor(p.from.value);\n        const to = new RGBColor(p.to.value);\n\n        if (from.ok && to.ok) {\n          // tween color linearly\n          const r = from.r + (to.r - from.r) * p.progress;\n          const g = from.g + (to.g - from.g) * p.progress;\n          const b = from.b + (to.b - from.b) * p.progress;\n          return 'rgb(' + parseInt(r, 10) + ',' + parseInt(g, 10) + ',' + parseInt(b, 10) + ')';\n        }\n        return this.attribute('from').value;\n      };\n    }\n  };\n\n  // animate transform element\n  svg.Element.animateTransform = class extends svg.Element.animate {\n    constructor (node) {\n      super(node);\n\n      this.calcValue = function () {\n        const p = this.progress();\n\n        // tween value linearly\n        const from = svg.ToNumberArray(p.from.value);\n        const to = svg.ToNumberArray(p.to.value);\n        let newValue = '';\n        for (let i = 0; i < from.length; i++) {\n          newValue += from[i] + (to[i] - from[i]) * p.progress + ' ';\n        }\n        return newValue;\n      };\n    }\n  };\n\n  // font element\n  svg.Element.font = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.horizAdvX = this.attribute('horiz-adv-x').numValue();\n\n      this.isRTL = false;\n      this.isArabic = false;\n      this.fontFace = null;\n      this.missingGlyph = null;\n      this.glyphs = [];\n      for (let i = 0; i < this.children.length; i++) {\n        const child = this.children[i];\n        if (child.type === 'font-face') {\n          this.fontFace = child;\n          if (child.style('font-family').hasValue()) {\n            svg.Definitions[child.style('font-family').value] = this;\n          }\n        } else if (child.type === 'missing-glyph') {\n          this.missingGlyph = child;\n        } else if (child.type === 'glyph') {\n          if (child.arabicForm !== '') {\n            this.isRTL = true;\n            this.isArabic = true;\n            if (typeof this.glyphs[child.unicode] === 'undefined') {\n              this.glyphs[child.unicode] = [];\n            }\n            this.glyphs[child.unicode][child.arabicForm] = child;\n          } else {\n            this.glyphs[child.unicode] = child;\n          }\n        }\n      }\n    }\n  };\n\n  // font-face element\n  svg.Element.fontface = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.ascent = this.attribute('ascent').value;\n      this.descent = this.attribute('descent').value;\n      this.unitsPerEm = this.attribute('units-per-em').numValue();\n    }\n  };\n\n  // missing-glyph element\n  svg.Element.missingglyph = class extends svg.Element.path {\n    constructor (node) {\n      super(node);\n\n      this.horizAdvX = 0;\n    }\n  };\n\n  // glyph element\n  svg.Element.glyph = class extends svg.Element.path {\n    constructor (node) {\n      super(node);\n\n      this.horizAdvX = this.attribute('horiz-adv-x').numValue();\n      this.unicode = this.attribute('unicode').value;\n      this.arabicForm = this.attribute('arabic-form').value;\n    }\n  };\n\n  // text element\n  svg.Element.text = class extends svg.Element.RenderedElementBase {\n    constructor (node) {\n      super(node);\n      this.captureTextNodes = true;\n\n      this.baseSetContext = this.setContext;\n      this.setContext = function (ctx) {\n        this.baseSetContext(ctx);\n\n        let textBaseline = this.style('dominant-baseline').toTextBaseline();\n        if (textBaseline == null) textBaseline = this.style('alignment-baseline').toTextBaseline();\n        if (textBaseline != null) ctx.textBaseline = textBaseline;\n      };\n\n      this.getBoundingBox = function () {\n        const x = this.attribute('x').toPixels('x');\n        const y = this.attribute('y').toPixels('y');\n        const fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);\n        return new svg.BoundingBox(x, y - fontSize, x + Math.floor(fontSize * 2.0 / 3.0) * this.children[0].getText().length, y);\n      };\n\n      this.renderChildren = function (ctx) {\n        this.x = this.attribute('x').toPixels('x');\n        this.y = this.attribute('y').toPixels('y');\n        this.x += this.getAnchorDelta(ctx, this, 0);\n        for (let i = 0; i < this.children.length; i++) {\n          this.renderChild(ctx, this, i);\n        }\n      };\n\n      this.getAnchorDelta = function (ctx, parent, startI) {\n        const textAnchor = this.style('text-anchor').valueOrDefault('start');\n        if (textAnchor !== 'start') {\n          let width = 0;\n          for (let i = startI; i < parent.children.length; i++) {\n            const child = parent.children[i];\n            if (i > startI && child.attribute('x').hasValue()) break; // new group\n            width += child.measureTextRecursive(ctx);\n          }\n          return -1 * (textAnchor === 'end' ? width : width / 2.0);\n        }\n        return 0;\n      };\n\n      this.renderChild = function (ctx, parent, i) {\n        const child = parent.children[i];\n        if (child.attribute('x').hasValue()) {\n          child.x = child.attribute('x').toPixels('x') + this.getAnchorDelta(ctx, parent, i);\n          if (child.attribute('dx').hasValue()) child.x += child.attribute('dx').toPixels('x');\n        } else {\n          if (this.attribute('dx').hasValue()) this.x += this.attribute('dx').toPixels('x');\n          if (child.attribute('dx').hasValue()) this.x += child.attribute('dx').toPixels('x');\n          child.x = this.x;\n        }\n        this.x = child.x + child.measureText(ctx);\n\n        if (child.attribute('y').hasValue()) {\n          child.y = child.attribute('y').toPixels('y');\n          if (child.attribute('dy').hasValue()) child.y += child.attribute('dy').toPixels('y');\n        } else {\n          if (this.attribute('dy').hasValue()) this.y += this.attribute('dy').toPixels('y');\n          if (child.attribute('dy').hasValue()) this.y += child.attribute('dy').toPixels('y');\n          child.y = this.y;\n        }\n        this.y = child.y;\n\n        child.render(ctx);\n\n        for (let i = 0; i < child.children.length; i++) {\n          this.renderChild(ctx, child, i);\n        }\n      };\n    }\n  };\n\n  // text base\n  svg.Element.TextElementBase = class extends svg.Element.RenderedElementBase {\n    constructor (node) {\n      super(node);\n\n      this.getGlyph = function (font, text, i) {\n        const c = text[i];\n        let glyph = null;\n        if (font.isArabic) {\n          let arabicForm = 'isolated';\n          if ((i === 0 || text[i - 1] === ' ') && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'terminal';\n          if (i > 0 && text[i - 1] !== ' ' && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'medial';\n          if (i > 0 && text[i - 1] !== ' ' && (i === text.length - 1 || text[i + 1] === ' ')) arabicForm = 'initial';\n          if (typeof font.glyphs[c] !== 'undefined') {\n            glyph = font.glyphs[c][arabicForm];\n            if (glyph == null && font.glyphs[c].type === 'glyph') glyph = font.glyphs[c];\n          }\n        } else {\n          glyph = font.glyphs[c];\n        }\n        if (glyph == null) glyph = font.missingGlyph;\n        return glyph;\n      };\n\n      this.renderChildren = function (ctx) {\n        const customFont = this.parent.style('font-family').getDefinition();\n        if (customFont != null) {\n          const fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);\n          const fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle);\n          let text = this.getText();\n          if (customFont.isRTL) text = text.split('').reverse().join('');\n\n          const dx = svg.ToNumberArray(this.parent.attribute('dx').value);\n          for (let i = 0; i < text.length; i++) {\n            const glyph = this.getGlyph(customFont, text, i);\n            const scale = fontSize / customFont.fontFace.unitsPerEm;\n            ctx.translate(this.x, this.y);\n            ctx.scale(scale, -scale);\n            const lw = ctx.lineWidth;\n            ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize;\n            if (fontStyle === 'italic') ctx.transform(1, 0, 0.4, 1, 0, 0);\n            glyph.render(ctx);\n            if (fontStyle === 'italic') ctx.transform(1, 0, -0.4, 1, 0, 0);\n            ctx.lineWidth = lw;\n            ctx.scale(1 / scale, -1 / scale);\n            ctx.translate(-this.x, -this.y);\n\n            this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm;\n            if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) {\n              this.x += dx[i];\n            }\n          }\n          return;\n        }\n\n        if (ctx.fillStyle !== '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);\n        if (ctx.strokeStyle !== '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y);\n      };\n\n      this.getText = function () {\n        // OVERRIDE ME\n      };\n\n      this.measureTextRecursive = function (ctx) {\n        let width = this.measureText(ctx);\n        for (let i = 0; i < this.children.length; i++) {\n          width += this.children[i].measureTextRecursive(ctx);\n        }\n        return width;\n      };\n\n      this.measureText = function (ctx) {\n        const customFont = this.parent.style('font-family').getDefinition();\n        if (customFont != null) {\n          const fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);\n          let measure = 0;\n          let text = this.getText();\n          if (customFont.isRTL) text = text.split('').reverse().join('');\n          const dx = svg.ToNumberArray(this.parent.attribute('dx').value);\n          for (let i = 0; i < text.length; i++) {\n            const glyph = this.getGlyph(customFont, text, i);\n            measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm;\n            if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) {\n              measure += dx[i];\n            }\n          }\n          return measure;\n        }\n\n        const textToMeasure = svg.compressSpaces(this.getText());\n        if (!ctx.measureText) return textToMeasure.length * 10;\n\n        ctx.save();\n        this.setContext(ctx);\n        const {width} = ctx.measureText(textToMeasure);\n        ctx.restore();\n        return width;\n      };\n    }\n  };\n\n  // tspan\n  svg.Element.tspan = class extends svg.Element.TextElementBase {\n    constructor (node) {\n      super(node);\n      this.captureTextNodes = true;\n\n      this.text = node.nodeValue || node.text || '';\n      this.getText = function () {\n        return this.text;\n      };\n    }\n  };\n\n  // tref\n  svg.Element.tref = class extends svg.Element.TextElementBase {\n    constructor (node) {\n      super(node);\n\n      this.getText = function () {\n        const element = this.getHrefAttribute().getDefinition();\n        if (element != null) return element.children[0].getText();\n      };\n    }\n  };\n\n  // a element\n  svg.Element.a = class extends svg.Element.TextElementBase {\n    constructor (node) {\n      super(node);\n\n      this.hasText = true;\n      for (let i = 0, childNode; (childNode = node.childNodes[i]); i++) {\n        if (childNode.nodeType !== 3) this.hasText = false;\n      }\n\n      // this might contain text\n      this.text = this.hasText ? node.childNodes[0].nodeValue : '';\n      this.getText = function () {\n        return this.text;\n      };\n\n      this.baseRenderChildren = this.renderChildren;\n      this.renderChildren = function (ctx) {\n        if (this.hasText) {\n          // render as text element\n          this.baseRenderChildren(ctx);\n          const fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);\n          svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.toPixels('y'), this.x + this.measureText(ctx), this.y));\n        } else {\n          // render as temporary group\n          const g = new svg.Element.g();\n          g.children = this.children;\n          g.parent = this;\n          g.render(ctx);\n        }\n      };\n\n      this.onclick = function () {\n        window.open(this.getHrefAttribute().value);\n      };\n\n      this.onmousemove = function () {\n        svg.ctx.canvas.style.cursor = 'pointer';\n      };\n    }\n  };\n\n  // image element\n  svg.Element.image = class extends svg.Element.RenderedElementBase {\n    constructor (node) {\n      super(node);\n\n      const href = this.getHrefAttribute().value;\n      if (href === '') {\n        return;\n      }\n      const isSvg = href.match(/\\.svg$/);\n\n      svg.Images.push(this);\n      this.loaded = false;\n      if (!isSvg) {\n        this.img = document.createElement('img');\n        if (svg.opts['useCORS'] === true) { this.img.crossOrigin = 'Anonymous'; }\n        const self = this;\n        this.img.onload = function () { self.loaded = true; };\n        this.img.onerror = function () { svg.log('ERROR: image \"' + href + '\" not found'); self.loaded = true; };\n        this.img.src = href;\n      } else {\n        this.img = svg.ajax(href);\n        this.loaded = true;\n      }\n\n      this.renderChildren = function (ctx) {\n        const x = this.attribute('x').toPixels('x');\n        const y = this.attribute('y').toPixels('y');\n\n        const width = this.attribute('width').toPixels('x');\n        const height = this.attribute('height').toPixels('y');\n        if (width === 0 || height === 0) return;\n\n        ctx.save();\n        if (isSvg) {\n          ctx.drawSvg(this.img, x, y, width, height);\n        } else {\n          ctx.translate(x, y);\n          svg.AspectRatio(\n            ctx,\n            this.attribute('preserveAspectRatio').value,\n            width,\n            this.img.width,\n            height,\n            this.img.height,\n            0,\n            0\n          );\n          ctx.drawImage(this.img, 0, 0);\n        }\n        ctx.restore();\n      };\n\n      this.getBoundingBox = function () {\n        const x = this.attribute('x').toPixels('x');\n        const y = this.attribute('y').toPixels('y');\n        const width = this.attribute('width').toPixels('x');\n        const height = this.attribute('height').toPixels('y');\n        return new svg.BoundingBox(x, y, x + width, y + height);\n      };\n    }\n  };\n\n  // group element\n  svg.Element.g = class extends svg.Element.RenderedElementBase {\n    constructor (node) {\n      super(node);\n\n      this.getBoundingBox = function () {\n        const bb = new svg.BoundingBox();\n        for (let i = 0; i < this.children.length; i++) {\n          bb.addBoundingBox(this.children[i].getBoundingBox());\n        }\n        return bb;\n      };\n    }\n  };\n\n  // symbol element\n  svg.Element.symbol = class extends svg.Element.RenderedElementBase {\n    constructor (node) {\n      super(node);\n\n      this.render = function (ctx) {\n        // NO RENDER\n      };\n    }\n  };\n\n  // style element\n  svg.Element.style = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      // text, or spaces then CDATA\n      let css = '';\n      for (let i = 0, childNode; (childNode = node.childNodes[i]); i++) {\n        css += childNode.nodeValue;\n      }\n      css = css.replace(/(\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+\\/)|(^[\\s]*\\/\\/.*)/gm, ''); // remove comments\n      css = svg.compressSpaces(css); // replace whitespace\n      const cssDefs = css.split('}');\n      for (let i = 0; i < cssDefs.length; i++) {\n        if (svg.trim(cssDefs[i]) !== '') {\n          const cssDef = cssDefs[i].split('{');\n          const cssClasses = cssDef[0].split(',');\n          const cssProps = cssDef[1].split(';');\n          for (let j = 0; j < cssClasses.length; j++) {\n            const cssClass = svg.trim(cssClasses[j]);\n            if (cssClass !== '') {\n              const props = {};\n              for (let k = 0; k < cssProps.length; k++) {\n                const prop = cssProps[k].indexOf(':');\n                const name = cssProps[k].substr(0, prop);\n                const value = cssProps[k].substr(prop + 1, cssProps[k].length - prop);\n                if (name != null && value != null) {\n                  props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value));\n                }\n              }\n              svg.Styles[cssClass] = props;\n              if (cssClass === '@font-face') {\n                const fontFamily = props['font-family'].value.replace(/\"/g, '');\n                const srcs = props['src'].value.split(',');\n                for (let s = 0; s < srcs.length; s++) {\n                  if (srcs[s].includes('format(\"svg\")')) {\n                    const urlStart = srcs[s].indexOf('url');\n                    const urlEnd = srcs[s].indexOf(')', urlStart);\n                    const url = srcs[s].substr(urlStart + 5, urlEnd - urlStart - 6);\n                    const doc = svg.parseXml(svg.ajax(url));\n                    const fonts = doc.getElementsByTagName('font');\n                    for (let f = 0; f < fonts.length; f++) {\n                      const font = svg.CreateElement(fonts[f]);\n                      svg.Definitions[fontFamily] = font;\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  };\n\n  // use element\n  svg.Element.use = class extends svg.Element.RenderedElementBase {\n    constructor (node) {\n      super(node);\n\n      this.baseSetContext = this.setContext;\n      this.setContext = function (ctx) {\n        this.baseSetContext(ctx);\n        if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').toPixels('x'), 0);\n        if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').toPixels('y'));\n      };\n\n      const element = this.getHrefAttribute().getDefinition();\n\n      this.path = function (ctx) {\n        if (element != null) element.path(ctx);\n      };\n\n      this.getBoundingBox = function () {\n        if (element != null) return element.getBoundingBox();\n      };\n\n      this.renderChildren = function (ctx) {\n        if (element != null) {\n          let tempSvg = element;\n          if (element.type === 'symbol') {\n            // render me using a temporary svg element in symbol cases (https://www.w3.org/TR/SVG/struct.html#UseElement)\n            tempSvg = new svg.Element.svg();\n            tempSvg.type = 'svg';\n            tempSvg.attributes['viewBox'] = new svg.Property('viewBox', element.attribute('viewBox').value);\n            tempSvg.attributes['preserveAspectRatio'] = new svg.Property('preserveAspectRatio', element.attribute('preserveAspectRatio').value);\n            tempSvg.attributes['overflow'] = new svg.Property('overflow', element.attribute('overflow').value);\n            tempSvg.children = element.children;\n          }\n          if (tempSvg.type === 'svg') {\n            // if symbol or svg, inherit width/height from me\n            if (this.attribute('width').hasValue()) tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);\n            if (this.attribute('height').hasValue()) tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);\n          }\n          const oldParent = tempSvg.parent;\n          tempSvg.parent = null;\n          tempSvg.render(ctx);\n          tempSvg.parent = oldParent;\n        }\n      };\n    }\n  };\n\n  // mask element\n  svg.Element.mask = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.apply = function (ctx, element) {\n        // render as temp svg\n        let x = this.attribute('x').toPixels('x');\n        let y = this.attribute('y').toPixels('y');\n        let width = this.attribute('width').toPixels('x');\n        let height = this.attribute('height').toPixels('y');\n\n        if (width === 0 && height === 0) {\n          const bb = new svg.BoundingBox();\n          for (let i = 0; i < this.children.length; i++) {\n            bb.addBoundingBox(this.children[i].getBoundingBox());\n          }\n          x = Math.floor(bb.x1);\n          y = Math.floor(bb.y1);\n          width = Math.floor(bb.width());\n          height = Math.floor(bb.height());\n        }\n\n        // temporarily remove mask to avoid recursion\n        const mask = element.attribute('mask').value;\n        element.attribute('mask').value = '';\n\n        const cMask = document.createElement('canvas');\n        cMask.width = x + width;\n        cMask.height = y + height;\n        const maskCtx = cMask.getContext('2d');\n        this.renderChildren(maskCtx);\n\n        const c = document.createElement('canvas');\n        c.width = x + width;\n        c.height = y + height;\n        const tempCtx = c.getContext('2d');\n        element.render(tempCtx);\n        tempCtx.globalCompositeOperation = 'destination-in';\n        tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat');\n        tempCtx.fillRect(0, 0, x + width, y + height);\n\n        ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat');\n        ctx.fillRect(0, 0, x + width, y + height);\n\n        // reassign mask\n        element.attribute('mask').value = mask;\n      };\n\n      this.render = function (ctx) {\n        // NO RENDER\n      };\n    }\n  };\n\n  // clip element\n  svg.Element.clipPath = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.apply = function (ctx) {\n        for (let i = 0; i < this.children.length; i++) {\n          const child = this.children[i];\n          if (typeof child.path !== 'undefined') {\n            let transform = null;\n            if (child.attribute('transform').hasValue()) {\n              transform = new svg.Transform(child.attribute('transform').value);\n              transform.apply(ctx);\n            }\n            child.path(ctx);\n            ctx.clip();\n            if (transform) { transform.unapply(ctx); }\n          }\n        }\n      };\n\n      this.render = function (ctx) {\n        // NO RENDER\n      };\n    }\n  };\n\n  // filters\n  svg.Element.filter = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.apply = function (ctx, element) {\n        // render as temp svg\n        const bb = element.getBoundingBox();\n        const x = Math.floor(bb.x1);\n        const y = Math.floor(bb.y1);\n        const width = Math.floor(bb.width());\n        const height = Math.floor(bb.height());\n\n        // temporarily remove filter to avoid recursion\n        const filter = element.style('filter').value;\n        element.style('filter').value = '';\n\n        let px = 0, py = 0;\n        for (let i = 0; i < this.children.length; i++) {\n          const efd = this.children[i].extraFilterDistance || 0;\n          px = Math.max(px, efd);\n          py = Math.max(py, efd);\n        }\n\n        const c = document.createElement('canvas');\n        c.width = width + 2 * px;\n        c.height = height + 2 * py;\n        const tempCtx = c.getContext('2d');\n        tempCtx.translate(-x + px, -y + py);\n        element.render(tempCtx);\n\n        // apply filters\n        for (let i = 0; i < this.children.length; i++) {\n          this.children[i].apply(tempCtx, 0, 0, width + 2 * px, height + 2 * py);\n        }\n\n        // render on me\n        ctx.drawImage(c, 0, 0, width + 2 * px, height + 2 * py, x - px, y - py, width + 2 * px, height + 2 * py);\n\n        // reassign filter\n        element.style('filter', true).value = filter;\n      };\n\n      this.render = function (ctx) {\n        // NO RENDER\n      };\n    }\n  };\n\n  svg.Element.feMorphology = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.apply = function (ctx, x, y, width, height) {\n        // TODO: implement\n      };\n    }\n  };\n\n  svg.Element.feComposite = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.apply = function (ctx, x, y, width, height) {\n        // TODO: implement\n      };\n    }\n  };\n\n  svg.Element.feColorMatrix = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      let matrix = svg.ToNumberArray(this.attribute('values').value);\n      switch (this.attribute('type').valueOrDefault('matrix')) { // https://www.w3.org/TR/SVG/filters.html#feColorMatrixElement\n      case 'saturate':\n        const s = matrix[0];\n        matrix = [\n          0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0, 0,\n          0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0, 0,\n          0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0, 0,\n          0, 0, 0, 1, 0,\n          0, 0, 0, 0, 1\n        ];\n        break;\n      case 'hueRotate':\n        const a = matrix[0] * Math.PI / 180.0;\n        const c = function (m1, m2, m3) { return m1 + Math.cos(a) * m2 + Math.sin(a) * m3; };\n        matrix = [\n          c(0.213, 0.787, -0.213), c(0.715, -0.715, -0.715), c(0.072, -0.072, 0.928), 0, 0,\n          c(0.213, -0.213, 0.143), c(0.715, 0.285, 0.140), c(0.072, -0.072, -0.283), 0, 0,\n          c(0.213, -0.213, -0.787), c(0.715, -0.715, 0.715), c(0.072, 0.928, 0.072), 0, 0,\n          0, 0, 0, 1, 0,\n          0, 0, 0, 0, 1\n        ];\n        break;\n      case 'luminanceToAlpha':\n        matrix = [\n          0, 0, 0, 0, 0,\n          0, 0, 0, 0, 0,\n          0, 0, 0, 0, 0,\n          0.2125, 0.7154, 0.0721, 0, 0,\n          0, 0, 0, 0, 1\n        ];\n        break;\n      }\n\n      function imGet (img, x, y, width, height, rgba) {\n        return img[y * width * 4 + x * 4 + rgba];\n      }\n\n      function imSet (img, x, y, width, height, rgba, val) {\n        img[y * width * 4 + x * 4 + rgba] = val;\n      }\n\n      function m (i, v) {\n        const mi = matrix[i];\n        return mi * (mi < 0 ? v - 255 : v);\n      }\n\n      this.apply = function (ctx, x, y, width, height) {\n        // assuming x==0 && y==0 for now\n        const srcData = ctx.getImageData(0, 0, width, height);\n        for (let y = 0; y < height; y++) {\n          for (let x = 0; x < width; x++) {\n            const r = imGet(srcData.data, x, y, width, height, 0);\n            const g = imGet(srcData.data, x, y, width, height, 1);\n            const b = imGet(srcData.data, x, y, width, height, 2);\n            const a = imGet(srcData.data, x, y, width, height, 3);\n            imSet(srcData.data, x, y, width, height, 0, m(0, r) + m(1, g) + m(2, b) + m(3, a) + m(4, 1));\n            imSet(srcData.data, x, y, width, height, 1, m(5, r) + m(6, g) + m(7, b) + m(8, a) + m(9, 1));\n            imSet(srcData.data, x, y, width, height, 2, m(10, r) + m(11, g) + m(12, b) + m(13, a) + m(14, 1));\n            imSet(srcData.data, x, y, width, height, 3, m(15, r) + m(16, g) + m(17, b) + m(18, a) + m(19, 1));\n          }\n        }\n        ctx.clearRect(0, 0, width, height);\n        ctx.putImageData(srcData, 0, 0);\n      };\n    }\n  };\n\n  svg.Element.feGaussianBlur = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super(node);\n\n      this.blurRadius = Math.floor(this.attribute('stdDeviation').numValue());\n      this.extraFilterDistance = this.blurRadius;\n\n      this.apply = function (ctx, x, y, width, height) {\n        if (typeof stackBlurCanvasRGBA === 'undefined') {\n          svg.log('ERROR: StackBlur.js must be included for blur to work');\n          return;\n        }\n\n        // StackBlur requires canvas be on document\n        ctx.canvas.id = svg.UniqueId();\n        ctx.canvas.style.display = 'none';\n        document.body.appendChild(ctx.canvas);\n        stackBlurCanvasRGBA(ctx.canvas.id, x, y, width, height, this.blurRadius);\n        document.body.removeChild(ctx.canvas);\n      };\n    }\n  };\n\n  // title element, do nothing\n  svg.Element.title = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super();\n    }\n  };\n\n  // desc element, do nothing\n  svg.Element.desc = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super();\n    }\n  };\n\n  svg.Element.MISSING = class extends svg.Element.ElementBase {\n    constructor (node) {\n      super();\n      svg.log('ERROR: Element \\'' + node.nodeName + '\\' not yet implemented.');\n    }\n  };\n\n  // element factory\n  svg.CreateElement = function (node) {\n    const className = node.nodeName\n      .replace(/^[^:]+:/, '') // remove namespace\n      .replace(/-/g, ''); // remove dashes\n    let e;\n    if (typeof svg.Element[className] !== 'undefined') {\n      e = new svg.Element[className](node);\n    } else {\n      e = new svg.Element.MISSING(node);\n    }\n\n    e.type = node.nodeName;\n    return e;\n  };\n\n  // load from url\n  svg.load = function (ctx, url) {\n    svg.loadXml(ctx, svg.ajax(url));\n  };\n\n  // load from xml\n  svg.loadXml = function (ctx, xml) {\n    svg.loadXmlDoc(ctx, svg.parseXml(xml));\n  };\n\n  svg.loadXmlDoc = function (ctx, dom) {\n    svg.init(ctx);\n\n    const mapXY = function (p) {\n      let e = ctx.canvas;\n      while (e) {\n        p.x -= e.offsetLeft;\n        p.y -= e.offsetTop;\n        e = e.offsetParent;\n      }\n      if (window.scrollX) p.x += window.scrollX;\n      if (window.scrollY) p.y += window.scrollY;\n      return p;\n    };\n\n    // bind mouse\n    if (svg.opts['ignoreMouse'] !== true) {\n      ctx.canvas.onclick = function (e) {\n        const p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));\n        svg.Mouse.onclick(p.x, p.y);\n      };\n      ctx.canvas.onmousemove = function (e) {\n        const p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));\n        svg.Mouse.onmousemove(p.x, p.y);\n      };\n    }\n\n    const e = svg.CreateElement(dom.documentElement);\n    e.root = true;\n\n    // render loop\n    let isFirstRender = true;\n    const draw = function () {\n      svg.ViewPort.Clear();\n      if (ctx.canvas.parentNode) svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight);\n\n      if (svg.opts['ignoreDimensions'] !== true) {\n        // set canvas size\n        if (e.style('width').hasValue()) {\n          ctx.canvas.width = e.style('width').toPixels('x');\n          ctx.canvas.style.width = ctx.canvas.width + 'px';\n        }\n        if (e.style('height').hasValue()) {\n          ctx.canvas.height = e.style('height').toPixels('y');\n          ctx.canvas.style.height = ctx.canvas.height + 'px';\n        }\n      }\n      let cWidth = ctx.canvas.clientWidth || ctx.canvas.width;\n      let cHeight = ctx.canvas.clientHeight || ctx.canvas.height;\n      if (svg.opts['ignoreDimensions'] === true && e.style('width').hasValue() && e.style('height').hasValue()) {\n        cWidth = e.style('width').toPixels('x');\n        cHeight = e.style('height').toPixels('y');\n      }\n      svg.ViewPort.SetCurrent(cWidth, cHeight);\n\n      if (svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX'];\n      if (svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY'];\n      if (svg.opts['scaleWidth'] != null || svg.opts['scaleHeight'] != null) {\n        const viewBox = svg.ToNumberArray(e.attribute('viewBox').value);\n        let xRatio = null, yRatio = null;\n\n        if (svg.opts['scaleWidth'] != null) {\n          if (e.attribute('width').hasValue()) xRatio = e.attribute('width').toPixels('x') / svg.opts['scaleWidth'];\n          else if (!isNaN(viewBox[2])) xRatio = viewBox[2] / svg.opts['scaleWidth'];\n        }\n\n        if (svg.opts['scaleHeight'] != null) {\n          if (e.attribute('height').hasValue()) yRatio = e.attribute('height').toPixels('y') / svg.opts['scaleHeight'];\n          else if (!isNaN(viewBox[3])) yRatio = viewBox[3] / svg.opts['scaleHeight'];\n        }\n\n        if (xRatio == null) { xRatio = yRatio; }\n        if (yRatio == null) { yRatio = xRatio; }\n\n        e.attribute('width', true).value = svg.opts['scaleWidth'];\n        e.attribute('height', true).value = svg.opts['scaleHeight'];\n        e.attribute('viewBox', true).value = '0 0 ' + (cWidth * xRatio) + ' ' + (cHeight * yRatio);\n        e.attribute('preserveAspectRatio', true).value = 'none';\n      }\n\n      // clear and render\n      if (svg.opts['ignoreClear'] !== true) {\n        ctx.clearRect(0, 0, cWidth, cHeight);\n      }\n      e.render(ctx);\n      if (isFirstRender) {\n        isFirstRender = false;\n        if (typeof svg.opts['renderCallback'] === 'function') {\n          svg.opts['renderCallback'](dom);\n        }\n      }\n    };\n\n    let waitingForImages = true;\n    if (svg.ImagesLoaded()) {\n      waitingForImages = false;\n      draw();\n    }\n    svg.intervalID = setInterval(function () {\n      let needUpdate = false;\n\n      if (waitingForImages && svg.ImagesLoaded()) {\n        waitingForImages = false;\n        needUpdate = true;\n      }\n\n      // need update from mouse events?\n      if (svg.opts['ignoreMouse'] !== true) {\n        needUpdate = needUpdate | svg.Mouse.hasEvents();\n      }\n\n      // need update from animations?\n      if (svg.opts['ignoreAnimation'] !== true) {\n        for (let i = 0; i < svg.Animations.length; i++) {\n          needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE);\n        }\n      }\n\n      // need update from redraw?\n      if (typeof svg.opts['forceRedraw'] === 'function') {\n        if (svg.opts['forceRedraw']() === true) needUpdate = true;\n      }\n\n      // render if needed\n      if (needUpdate) {\n        draw();\n        svg.Mouse.runEvents(); // run and clear our events\n      }\n    }, 1000 / svg.FRAMERATE);\n  };\n\n  svg.stop = function () {\n    if (svg.intervalID) {\n      clearInterval(svg.intervalID);\n    }\n  };\n\n  svg.Mouse = new function () {\n    this.events = [];\n    this.hasEvents = function () { return this.events.length !== 0; };\n\n    this.onclick = function (x, y) {\n      this.events.push({ type: 'onclick', x, y,\n        run (e) { if (e.onclick) e.onclick(); }\n      });\n    };\n\n    this.onmousemove = function (x, y) {\n      this.events.push({ type: 'onmousemove', x, y,\n        run (e) { if (e.onmousemove) e.onmousemove(); }\n      });\n    };\n\n    this.eventElements = [];\n\n    this.checkPath = function (element, ctx) {\n      for (let i = 0; i < this.events.length; i++) {\n        const e = this.events[i];\n        if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;\n      }\n    };\n\n    this.checkBoundingBox = function (element, bb) {\n      for (let i = 0; i < this.events.length; i++) {\n        const e = this.events[i];\n        if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;\n      }\n    };\n\n    this.runEvents = function () {\n      svg.ctx.canvas.style.cursor = '';\n\n      for (let i = 0; i < this.events.length; i++) {\n        const e = this.events[i];\n        let element = this.eventElements[i];\n        while (element) {\n          e.run(element);\n          element = element.parent;\n        }\n      }\n\n      // done running, clear\n      this.events = [];\n      this.eventElements = [];\n    };\n  }();\n\n  return svg;\n}\n\nif (typeof CanvasRenderingContext2D !== 'undefined') {\n  CanvasRenderingContext2D.prototype.drawSvg = function (s, dx, dy, dw, dh) {\n    canvg(this.canvas, s, {\n      ignoreMouse: true,\n      ignoreAnimation: true,\n      ignoreDimensions: true,\n      ignoreClear: true,\n      offsetX: dx,\n      offsetY: dy,\n      scaleWidth: dw,\n      scaleHeight: dh\n    });\n  };\n}\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/canvg/rgbcolor.js",
    "content": "/**\n * A class to parse color values\n * @author Stoyan Stefanov <sstoo@gmail.com>\n * @link   https://www.phpied.com/rgb-color-parser-in-javascript/\n * @license MIT\n */\nexport default function RGBColor (colorString) {\n  this.ok = false;\n\n  // strip any leading #\n  if (colorString.charAt(0) === '#') { // remove # if any\n    colorString = colorString.substr(1, 6);\n  }\n\n  colorString = colorString.replace(/ /g, '');\n  colorString = colorString.toLowerCase();\n\n  // before getting into regexps, try simple matches\n  // and overwrite the input\n  const simpleColors = {\n    aliceblue: 'f0f8ff',\n    antiquewhite: 'faebd7',\n    aqua: '00ffff',\n    aquamarine: '7fffd4',\n    azure: 'f0ffff',\n    beige: 'f5f5dc',\n    bisque: 'ffe4c4',\n    black: '000000',\n    blanchedalmond: 'ffebcd',\n    blue: '0000ff',\n    blueviolet: '8a2be2',\n    brown: 'a52a2a',\n    burlywood: 'deb887',\n    cadetblue: '5f9ea0',\n    chartreuse: '7fff00',\n    chocolate: 'd2691e',\n    coral: 'ff7f50',\n    cornflowerblue: '6495ed',\n    cornsilk: 'fff8dc',\n    crimson: 'dc143c',\n    cyan: '00ffff',\n    darkblue: '00008b',\n    darkcyan: '008b8b',\n    darkgoldenrod: 'b8860b',\n    darkgray: 'a9a9a9',\n    darkgreen: '006400',\n    darkkhaki: 'bdb76b',\n    darkmagenta: '8b008b',\n    darkolivegreen: '556b2f',\n    darkorange: 'ff8c00',\n    darkorchid: '9932cc',\n    darkred: '8b0000',\n    darksalmon: 'e9967a',\n    darkseagreen: '8fbc8f',\n    darkslateblue: '483d8b',\n    darkslategray: '2f4f4f',\n    darkturquoise: '00ced1',\n    darkviolet: '9400d3',\n    deeppink: 'ff1493',\n    deepskyblue: '00bfff',\n    dimgray: '696969',\n    dodgerblue: '1e90ff',\n    feldspar: 'd19275',\n    firebrick: 'b22222',\n    floralwhite: 'fffaf0',\n    forestgreen: '228b22',\n    fuchsia: 'ff00ff',\n    gainsboro: 'dcdcdc',\n    ghostwhite: 'f8f8ff',\n    gold: 'ffd700',\n    goldenrod: 'daa520',\n    gray: '808080',\n    green: '008000',\n    greenyellow: 'adff2f',\n    honeydew: 'f0fff0',\n    hotpink: 'ff69b4',\n    indianred: 'cd5c5c',\n    indigo: '4b0082',\n    ivory: 'fffff0',\n    khaki: 'f0e68c',\n    lavender: 'e6e6fa',\n    lavenderblush: 'fff0f5',\n    lawngreen: '7cfc00',\n    lemonchiffon: 'fffacd',\n    lightblue: 'add8e6',\n    lightcoral: 'f08080',\n    lightcyan: 'e0ffff',\n    lightgoldenrodyellow: 'fafad2',\n    lightgrey: 'd3d3d3',\n    lightgreen: '90ee90',\n    lightpink: 'ffb6c1',\n    lightsalmon: 'ffa07a',\n    lightseagreen: '20b2aa',\n    lightskyblue: '87cefa',\n    lightslateblue: '8470ff',\n    lightslategray: '778899',\n    lightsteelblue: 'b0c4de',\n    lightyellow: 'ffffe0',\n    lime: '00ff00',\n    limegreen: '32cd32',\n    linen: 'faf0e6',\n    magenta: 'ff00ff',\n    maroon: '800000',\n    mediumaquamarine: '66cdaa',\n    mediumblue: '0000cd',\n    mediumorchid: 'ba55d3',\n    mediumpurple: '9370d8',\n    mediumseagreen: '3cb371',\n    mediumslateblue: '7b68ee',\n    mediumspringgreen: '00fa9a',\n    mediumturquoise: '48d1cc',\n    mediumvioletred: 'c71585',\n    midnightblue: '191970',\n    mintcream: 'f5fffa',\n    mistyrose: 'ffe4e1',\n    moccasin: 'ffe4b5',\n    navajowhite: 'ffdead',\n    navy: '000080',\n    oldlace: 'fdf5e6',\n    olive: '808000',\n    olivedrab: '6b8e23',\n    orange: 'ffa500',\n    orangered: 'ff4500',\n    orchid: 'da70d6',\n    palegoldenrod: 'eee8aa',\n    palegreen: '98fb98',\n    paleturquoise: 'afeeee',\n    palevioletred: 'd87093',\n    papayawhip: 'ffefd5',\n    peachpuff: 'ffdab9',\n    peru: 'cd853f',\n    pink: 'ffc0cb',\n    plum: 'dda0dd',\n    powderblue: 'b0e0e6',\n    purple: '800080',\n    red: 'ff0000',\n    rosybrown: 'bc8f8f',\n    royalblue: '4169e1',\n    saddlebrown: '8b4513',\n    salmon: 'fa8072',\n    sandybrown: 'f4a460',\n    seagreen: '2e8b57',\n    seashell: 'fff5ee',\n    sienna: 'a0522d',\n    silver: 'c0c0c0',\n    skyblue: '87ceeb',\n    slateblue: '6a5acd',\n    slategray: '708090',\n    snow: 'fffafa',\n    springgreen: '00ff7f',\n    steelblue: '4682b4',\n    tan: 'd2b48c',\n    teal: '008080',\n    thistle: 'd8bfd8',\n    tomato: 'ff6347',\n    turquoise: '40e0d0',\n    violet: 'ee82ee',\n    violetred: 'd02090',\n    wheat: 'f5deb3',\n    white: 'ffffff',\n    whitesmoke: 'f5f5f5',\n    yellow: 'ffff00',\n    yellowgreen: '9acd32'\n  };\n  for (const key in simpleColors) {\n    if (simpleColors.hasOwnProperty(key)) {\n      if (colorString === key) {\n        colorString = simpleColors[key];\n      }\n    }\n  }\n  // emd of simple type-in colors\n\n  // array of color definition objects\n  const colorDefs = [\n    {\n      re: /^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$/,\n      example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],\n      process (bits) {\n        return [\n          parseInt(bits[1], 10),\n          parseInt(bits[2], 10),\n          parseInt(bits[3], 10)\n        ];\n      }\n    },\n    {\n      re: /^(\\w{2})(\\w{2})(\\w{2})$/,\n      example: ['#00ff00', '336699'],\n      process (bits) {\n        return [\n          parseInt(bits[1], 16),\n          parseInt(bits[2], 16),\n          parseInt(bits[3], 16)\n        ];\n      }\n    },\n    {\n      re: /^(\\w{1})(\\w{1})(\\w{1})$/,\n      example: ['#fb0', 'f0f'],\n      process (bits) {\n        return [\n          parseInt(bits[1] + bits[1], 16),\n          parseInt(bits[2] + bits[2], 16),\n          parseInt(bits[3] + bits[3], 16)\n        ];\n      }\n    }\n  ];\n\n  // search through the definitions to find a match\n  for (let i = 0; i < colorDefs.length; i++) {\n    const {re} = colorDefs[i];\n    const processor = colorDefs[i].process;\n    const bits = re.exec(colorString);\n    if (bits) {\n      const channels = processor(bits);\n      this.r = channels[0];\n      this.g = channels[1];\n      this.b = channels[2];\n      this.ok = true;\n    }\n  }\n\n  // validate/cleanup values\n  this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);\n  this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);\n  this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);\n\n  // some getters\n  this.toRGB = function () {\n    return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';\n  };\n  this.toHex = function () {\n    let r = this.r.toString(16);\n    let g = this.g.toString(16);\n    let b = this.b.toString(16);\n    if (r.length === 1) { r = '0' + r; }\n    if (g.length === 1) { g = '0' + g; }\n    if (b.length === 1) { b = '0' + b; }\n    return '#' + r + g + b;\n  };\n\n  // help\n  this.getHelpXML = function () {\n    const examples = [];\n    // add regexps\n    for (let i = 0; i < colorDefs.length; i++) {\n      const {example} = colorDefs[i];\n      for (let j = 0; j < example.length; j++) {\n        examples[examples.length] = example[j];\n      }\n    }\n    // add type-in colors\n    for (const sc in simpleColors) {\n      if (simpleColors.hasOwnProperty(sc)) {\n        examples[examples.length] = sc;\n      }\n    }\n\n    const xml = document.createElement('ul');\n    xml.setAttribute('id', 'rgbcolor-examples');\n    for (let i = 0; i < examples.length; i++) {\n      try {\n        const listItem = document.createElement('li');\n        const listColor = new RGBColor(examples[i]);\n        const exampleDiv = document.createElement('div');\n        exampleDiv.style.cssText =\n            'margin: 3px; ' +\n            'border: 1px solid black; ' +\n            'background:' + listColor.toHex() + '; ' +\n            'color:' + listColor.toHex()\n        ;\n        exampleDiv.appendChild(document.createTextNode('test'));\n        const listItemValue = document.createTextNode(\n          ' ' + examples[i] + ' -> ' + listColor.toRGB() + ' -> ' + listColor.toHex()\n        );\n        listItem.appendChild(exampleDiv);\n        listItem.appendChild(listItemValue);\n        xml.appendChild(listItem);\n      } catch (e) {}\n    }\n    return xml;\n  };\n}\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/coords.js",
    "content": "/* globals jQuery */\n/**\n * Coords.\n *\n * Licensed under the MIT License\n *\n */\n\nimport './pathseg.js';\nimport {\n  snapToGrid, assignAttributes, getBBox, getRefElem, findDefs\n} from './svgutils.js';\nimport {\n  transformPoint, transformListToTransform, matrixMultiply, transformBox\n} from './math.js';\nimport {getTransformList} from './svgtransformlist.js';\n\nconst $ = jQuery;\n\n// this is how we map paths to our preferred relative segment types\nconst pathMap = [0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a',\n  'H', 'h', 'V', 'v', 'S', 's', 'T', 't'];\n\n/**\n * @typedef editorContext\n * @type {?object}\n * @property {function} getGridSnapping\n * @property {function} getDrawing\n*/\nlet editorContext_ = null;\n\n/**\n* @param {editorContext} editorContext\n*/\nexport const init = function (editorContext) {\n  editorContext_ = editorContext;\n};\n\n/**\n * Applies coordinate changes to an element based on the given matrix\n * @param {Element} selected - DOM element to be changed\n * @param {Object} changes - Object with changes to be remapped\n * @param {SVGMatrix} m - Matrix object to use for remapping coordinates\n*/\nexport const remapElement = function (selected, changes, m) {\n  const remap = function (x, y) { return transformPoint(x, y, m); },\n    scalew = function (w) { return m.a * w; },\n    scaleh = function (h) { return m.d * h; },\n    doSnapping = editorContext_.getGridSnapping() && selected.parentNode.parentNode.localName === 'svg',\n    finishUp = function () {\n      if (doSnapping) {\n        for (const o in changes) {\n          changes[o] = snapToGrid(changes[o]);\n        }\n      }\n      assignAttributes(selected, changes, 1000, true);\n    },\n    box = getBBox(selected);\n\n  for (let i = 0; i < 2; i++) {\n    const type = i === 0 ? 'fill' : 'stroke';\n    const attrVal = selected.getAttribute(type);\n    if (attrVal && attrVal.startsWith('url(')) {\n      if (m.a < 0 || m.d < 0) {\n        const grad = getRefElem(attrVal);\n        const newgrad = grad.cloneNode(true);\n        if (m.a < 0) {\n          // flip x\n          const x1 = newgrad.getAttribute('x1');\n          const x2 = newgrad.getAttribute('x2');\n          newgrad.setAttribute('x1', -(x1 - 1));\n          newgrad.setAttribute('x2', -(x2 - 1));\n        }\n\n        if (m.d < 0) {\n          // flip y\n          const y1 = newgrad.getAttribute('y1');\n          const y2 = newgrad.getAttribute('y2');\n          newgrad.setAttribute('y1', -(y1 - 1));\n          newgrad.setAttribute('y2', -(y2 - 1));\n        }\n        newgrad.id = editorContext_.getDrawing().getNextId();\n        findDefs().appendChild(newgrad);\n        selected.setAttribute(type, 'url(#' + newgrad.id + ')');\n      }\n\n      // Not really working :(\n      // if (selected.tagName === 'path') {\n      //   reorientGrads(selected, m);\n      // }\n    }\n  }\n\n  const elName = selected.tagName;\n  if (elName === 'g' || elName === 'text' || elName === 'tspan' || elName === 'use') {\n    // if it was a translate, then just update x,y\n    if (m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1 && (m.e !== 0 || m.f !== 0)) {\n      // [T][M] = [M][T']\n      // therefore [T'] = [M_inv][T][M]\n      const existing = transformListToTransform(selected).matrix,\n        tNew = matrixMultiply(existing.inverse(), m, existing);\n      changes.x = parseFloat(changes.x) + tNew.e;\n      changes.y = parseFloat(changes.y) + tNew.f;\n    } else {\n      // we just absorb all matrices into the element and don't do any remapping\n      const chlist = getTransformList(selected);\n      const mt = editorContext_.getSVGRoot().createSVGTransform();\n      mt.setMatrix(matrixMultiply(transformListToTransform(chlist).matrix, m));\n      chlist.clear();\n      chlist.appendItem(mt);\n    }\n  }\n\n  // now we have a set of changes and an applied reduced transform list\n  // we apply the changes directly to the DOM\n  switch (elName) {\n  case 'foreignObject':\n  case 'rect':\n  case 'image': {\n    // Allow images to be inverted (give them matrix when flipped)\n    if (elName === 'image' && (m.a < 0 || m.d < 0)) {\n      // Convert to matrix\n      const chlist = getTransformList(selected);\n      const mt = editorContext_.getSVGRoot().createSVGTransform();\n      mt.setMatrix(matrixMultiply(transformListToTransform(chlist).matrix, m));\n      chlist.clear();\n      chlist.appendItem(mt);\n    } else {\n      const pt1 = remap(changes.x, changes.y);\n      changes.width = scalew(changes.width);\n      changes.height = scaleh(changes.height);\n      changes.x = pt1.x + Math.min(0, changes.width);\n      changes.y = pt1.y + Math.min(0, changes.height);\n      changes.width = Math.abs(changes.width);\n      changes.height = Math.abs(changes.height);\n    }\n    finishUp();\n    break;\n  } case 'ellipse': {\n    const c = remap(changes.cx, changes.cy);\n    changes.cx = c.x;\n    changes.cy = c.y;\n    changes.rx = scalew(changes.rx);\n    changes.ry = scaleh(changes.ry);\n    changes.rx = Math.abs(changes.rx);\n    changes.ry = Math.abs(changes.ry);\n    finishUp();\n    break;\n  } case 'circle': {\n    const c = remap(changes.cx, changes.cy);\n    changes.cx = c.x;\n    changes.cy = c.y;\n    // take the minimum of the new selected box's dimensions for the new circle radius\n    const tbox = transformBox(box.x, box.y, box.width, box.height, m);\n    const w = tbox.tr.x - tbox.tl.x, h = tbox.bl.y - tbox.tl.y;\n    changes.r = Math.min(w / 2, h / 2);\n\n    if (changes.r) { changes.r = Math.abs(changes.r); }\n    finishUp();\n    break;\n  } case 'line': {\n    const pt1 = remap(changes.x1, changes.y1);\n    const pt2 = remap(changes.x2, changes.y2);\n    changes.x1 = pt1.x;\n    changes.y1 = pt1.y;\n    changes.x2 = pt2.x;\n    changes.y2 = pt2.y;\n  } // Fallthrough\n  case 'text':\n  case 'tspan':\n  case 'use': {\n    finishUp();\n    break;\n  } case 'g': {\n    const gsvg = $(selected).data('gsvg');\n    if (gsvg) {\n      assignAttributes(gsvg, changes, 1000, true);\n    }\n    break;\n  } case 'polyline':\n  case 'polygon': {\n    const len = changes.points.length;\n    for (let i = 0; i < len; ++i) {\n      const pt = changes.points[i];\n      const {x, y} = remap(pt.x, pt.y);\n      changes.points[i].x = x;\n      changes.points[i].y = y;\n    }\n\n    // const len = changes.points.length;\n    let pstr = '';\n    for (let i = 0; i < len; ++i) {\n      const pt = changes.points[i];\n      pstr += pt.x + ',' + pt.y + ' ';\n    }\n    selected.setAttribute('points', pstr);\n    break;\n  } case 'path': {\n    const segList = selected.pathSegList;\n    let len = segList.numberOfItems;\n    changes.d = [];\n    for (let i = 0; i < len; ++i) {\n      const seg = segList.getItem(i);\n      changes.d[i] = {\n        type: seg.pathSegType,\n        x: seg.x,\n        y: seg.y,\n        x1: seg.x1,\n        y1: seg.y1,\n        x2: seg.x2,\n        y2: seg.y2,\n        r1: seg.r1,\n        r2: seg.r2,\n        angle: seg.angle,\n        largeArcFlag: seg.largeArcFlag,\n        sweepFlag: seg.sweepFlag\n      };\n    }\n\n    len = changes.d.length;\n    const firstseg = changes.d[0],\n      currentpt = remap(firstseg.x, firstseg.y);\n    changes.d[0].x = currentpt.x;\n    changes.d[0].y = currentpt.y;\n    for (let i = 1; i < len; ++i) {\n      const seg = changes.d[i];\n      const {type} = seg;\n      // if absolute or first segment, we want to remap x, y, x1, y1, x2, y2\n      // if relative, we want to scalew, scaleh\n      if (type % 2 === 0) { // absolute\n        const thisx = (seg.x !== undefined) ? seg.x : currentpt.x, // for V commands\n          thisy = (seg.y !== undefined) ? seg.y : currentpt.y; // for H commands\n        const pt = remap(thisx, thisy);\n        const pt1 = remap(seg.x1, seg.y1);\n        const pt2 = remap(seg.x2, seg.y2);\n        seg.x = pt.x;\n        seg.y = pt.y;\n        seg.x1 = pt1.x;\n        seg.y1 = pt1.y;\n        seg.x2 = pt2.x;\n        seg.y2 = pt2.y;\n        seg.r1 = scalew(seg.r1);\n        seg.r2 = scaleh(seg.r2);\n      } else { // relative\n        seg.x = scalew(seg.x);\n        seg.y = scaleh(seg.y);\n        seg.x1 = scalew(seg.x1);\n        seg.y1 = scaleh(seg.y1);\n        seg.x2 = scalew(seg.x2);\n        seg.y2 = scaleh(seg.y2);\n        seg.r1 = scalew(seg.r1);\n        seg.r2 = scaleh(seg.r2);\n      }\n    } // for each segment\n\n    let dstr = '';\n    len = changes.d.length;\n    for (let i = 0; i < len; ++i) {\n      const seg = changes.d[i];\n      const {type} = seg;\n      dstr += pathMap[type];\n      switch (type) {\n      case 13: // relative horizontal line (h)\n      case 12: // absolute horizontal line (H)\n        dstr += seg.x + ' ';\n        break;\n      case 15: // relative vertical line (v)\n      case 14: // absolute vertical line (V)\n        dstr += seg.y + ' ';\n        break;\n      case 3: // relative move (m)\n      case 5: // relative line (l)\n      case 19: // relative smooth quad (t)\n      case 2: // absolute move (M)\n      case 4: // absolute line (L)\n      case 18: // absolute smooth quad (T)\n        dstr += seg.x + ',' + seg.y + ' ';\n        break;\n      case 7: // relative cubic (c)\n      case 6: // absolute cubic (C)\n        dstr += seg.x1 + ',' + seg.y1 + ' ' + seg.x2 + ',' + seg.y2 + ' ' +\n          seg.x + ',' + seg.y + ' ';\n        break;\n      case 9: // relative quad (q)\n      case 8: // absolute quad (Q)\n        dstr += seg.x1 + ',' + seg.y1 + ' ' + seg.x + ',' + seg.y + ' ';\n        break;\n      case 11: // relative elliptical arc (a)\n      case 10: // absolute elliptical arc (A)\n        dstr += seg.r1 + ',' + seg.r2 + ' ' + seg.angle + ' ' + (+seg.largeArcFlag) +\n          ' ' + (+seg.sweepFlag) + ' ' + seg.x + ',' + seg.y + ' ';\n        break;\n      case 17: // relative smooth cubic (s)\n      case 16: // absolute smooth cubic (S)\n        dstr += seg.x2 + ',' + seg.y2 + ' ' + seg.x + ',' + seg.y + ' ';\n        break;\n      }\n    }\n\n    selected.setAttribute('d', dstr);\n    break;\n  }\n  }\n};\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/draw.js",
    "content": "/* globals jQuery */\n/**\n * Package: svgedit.draw\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2011 Jeff Schiller\n */\n\nimport Layer from './layer.js';\nimport HistoryRecordingService from './historyrecording.js';\n\nimport {NS} from './svgedit.js';\nimport {isOpera} from './browser.js';\nimport {\n  toXml, getElem,\n  copyElem as utilCopyElem\n} from './svgutils.js';\nimport {\n  BatchCommand, RemoveElementCommand, MoveElementCommand, ChangeElementCommand\n} from './history.js';\n\nconst $ = jQuery;\n\nconst visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use'.split(',');\n\nconst RandomizeModes = {\n  LET_DOCUMENT_DECIDE: 0,\n  ALWAYS_RANDOMIZE: 1,\n  NEVER_RANDOMIZE: 2\n};\nlet randIds = RandomizeModes.LET_DOCUMENT_DECIDE;\n// Array with current disabled elements (for in-group editing)\nlet disabledElems = [];\n\n/**\n * Get a HistoryRecordingService.\n * @param {svgedit.history.HistoryRecordingService=} hrService - if exists, return it instead of creating a new service.\n * @returns {svgedit.history.HistoryRecordingService}\n */\nfunction historyRecordingService (hrService) {\n  return hrService || new HistoryRecordingService(canvas_.undoMgr);\n}\n\n/**\n * Find the layer name in a group element.\n * @param group The group element to search in.\n * @returns {string} The layer name or empty string.\n */\nfunction findLayerNameInGroup (group) {\n  return $('title', group).text() ||\n    (isOpera() && group.querySelectorAll\n      // Hack for Opera 10.60\n      ? $(group.querySelectorAll('title')).text()\n      : '');\n}\n\n/**\n * Given a set of names, return a new unique name.\n * @param {Array.<string>} existingLayerNames - Existing layer names.\n * @returns {string} - The new name.\n */\nfunction getNewLayerName (existingLayerNames) {\n  let i = 1;\n  // TODO(codedread): What about internationalization of \"Layer\"?\n  while (existingLayerNames.includes(('Layer ' + i))) { i++; }\n  return 'Layer ' + i;\n}\n\n/**\n * This class encapsulates the concept of a SVG-edit drawing\n * @param {SVGSVGElement} svgElem - The SVG DOM Element that this JS object\n *     encapsulates.  If the svgElem has a se:nonce attribute on it, then\n *     IDs will use the nonce as they are generated.\n * @param {String} [optIdPrefix=svg_] - The ID prefix to use.\n */\nexport class Drawing {\n  constructor (svgElem, optIdPrefix) {\n    if (!svgElem || !svgElem.tagName || !svgElem.namespaceURI ||\n      svgElem.tagName !== 'svg' || svgElem.namespaceURI !== NS.SVG) {\n      throw new Error('Error: svgedit.draw.Drawing instance initialized without a <svg> element');\n    }\n\n    /**\n    * The SVG DOM Element that represents this drawing.\n    * @type {SVGSVGElement}\n    */\n    this.svgElem_ = svgElem;\n\n    /**\n    * The latest object number used in this drawing.\n    * @type {number}\n    */\n    this.obj_num = 0;\n\n    /**\n    * The prefix to prepend to each element id in the drawing.\n    * @type {String}\n    */\n    this.idPrefix = optIdPrefix || 'svg_';\n\n    /**\n    * An array of released element ids to immediately reuse.\n    * @type {Array.<number>}\n    */\n    this.releasedNums = [];\n\n    /**\n    * The z-ordered array of Layer objects. Each layer has a name\n    * and group element.\n    * The first layer is the one at the bottom of the rendering.\n    * @type {Array.<Layer>}\n    */\n    this.all_layers = [];\n\n    /**\n    * Map of all_layers by name.\n    *\n    * Note: Layers are ordered, but referenced externally by name; so, we need both container\n    * types depending on which function is called (i.e. all_layers and layer_map).\n    *\n    * @type {Object.<string, Layer>}\n    */\n    this.layer_map = {};\n\n    /**\n    * The current layer being used.\n    * @type {Layer}\n    */\n    this.current_layer = null;\n\n    /**\n    * The nonce to use to uniquely identify elements across drawings.\n    * @type {!String}\n    */\n    this.nonce_ = '';\n    const n = this.svgElem_.getAttributeNS(NS.SE, 'nonce');\n    // If already set in the DOM, use the nonce throughout the document\n    // else, if randomizeIds(true) has been called, create and set the nonce.\n    if (!!n && randIds !== RandomizeModes.NEVER_RANDOMIZE) {\n      this.nonce_ = n;\n    } else if (randIds === RandomizeModes.ALWAYS_RANDOMIZE) {\n      this.setNonce(Math.floor(Math.random() * 100001));\n    }\n  }\n\n  /**\n   * @param {string} id Element ID to retrieve\n   * @returns {Element} SVG element within the root SVGSVGElement\n  */\n  getElem_ (id) {\n    if (this.svgElem_.querySelector) {\n      // querySelector lookup\n      return this.svgElem_.querySelector('#' + id);\n    }\n    // jQuery lookup: twice as slow as xpath in FF\n    return $(this.svgElem_).find('[id=' + id + ']')[0];\n  }\n\n  /**\n   * @returns {SVGSVGElement}\n   */\n  getSvgElem () {\n    return this.svgElem_;\n  }\n\n  /**\n   * @returns {!string|number} The previously set nonce\n   */\n  getNonce () {\n    return this.nonce_;\n  }\n\n  /**\n   * @param {!string|number} n The nonce to set\n   */\n  setNonce (n) {\n    this.svgElem_.setAttributeNS(NS.XMLNS, 'xmlns:se', NS.SE);\n    this.svgElem_.setAttributeNS(NS.SE, 'se:nonce', n);\n    this.nonce_ = n;\n  }\n\n  /**\n   * Clears any previously set nonce\n   */\n  clearNonce () {\n    // We deliberately leave any se:nonce attributes alone,\n    // we just don't use it to randomize ids.\n    this.nonce_ = '';\n  }\n\n  /**\n   * Returns the latest object id as a string.\n   * @return {String} The latest object Id.\n   */\n  getId () {\n    return this.nonce_\n      ? this.idPrefix + this.nonce_ + '_' + this.obj_num\n      : this.idPrefix + this.obj_num;\n  }\n\n  /**\n   * Returns the next object Id as a string.\n   * @return {String} The next object Id to use.\n   */\n  getNextId () {\n    const oldObjNum = this.obj_num;\n    let restoreOldObjNum = false;\n\n    // If there are any released numbers in the release stack,\n    // use the last one instead of the next obj_num.\n    // We need to temporarily use obj_num as that is what getId() depends on.\n    if (this.releasedNums.length > 0) {\n      this.obj_num = this.releasedNums.pop();\n      restoreOldObjNum = true;\n    } else {\n      // If we are not using a released id, then increment the obj_num.\n      this.obj_num++;\n    }\n\n    // Ensure the ID does not exist.\n    let id = this.getId();\n    while (this.getElem_(id)) {\n      if (restoreOldObjNum) {\n        this.obj_num = oldObjNum;\n        restoreOldObjNum = false;\n      }\n      this.obj_num++;\n      id = this.getId();\n    }\n    // Restore the old object number if required.\n    if (restoreOldObjNum) {\n      this.obj_num = oldObjNum;\n    }\n    return id;\n  }\n\n  /**\n   * Releases the object Id, letting it be used as the next id in getNextId().\n   * This method DOES NOT remove any elements from the DOM, it is expected\n   * that client code will do this.\n   * @param {string} id - The id to release.\n   * @returns {boolean} True if the id was valid to be released, false otherwise.\n  */\n  releaseId (id) {\n    // confirm if this is a valid id for this Document, else return false\n    const front = this.idPrefix + (this.nonce_ ? this.nonce_ + '_' : '');\n    if (typeof id !== 'string' || !id.startsWith(front)) {\n      return false;\n    }\n    // extract the obj_num of this id\n    const num = parseInt(id.substr(front.length), 10);\n\n    // if we didn't get a positive number or we already released this number\n    // then return false.\n    if (typeof num !== 'number' || num <= 0 || this.releasedNums.includes(num)) {\n      return false;\n    }\n\n    // push the released number into the released queue\n    this.releasedNums.push(num);\n\n    return true;\n  }\n\n  /**\n   * Returns the number of layers in the current drawing.\n   * @returns {integer} The number of layers in the current drawing.\n  */\n  getNumLayers () {\n    return this.all_layers.length;\n  }\n\n  /**\n   * Check if layer with given name already exists\n   * @param {string} name - The layer name to check\n  */\n  hasLayer (name) {\n    return this.layer_map[name] !== undefined;\n  }\n\n  /**\n   * Returns the name of the ith layer. If the index is out of range, an empty string is returned.\n   * @param {integer} i - The zero-based index of the layer you are querying.\n   * @returns {string} The name of the ith layer (or the empty string if none found)\n  */\n  getLayerName (i) {\n    return i >= 0 && i < this.getNumLayers() ? this.all_layers[i].getName() : '';\n  }\n\n  /**\n   * @returns {SVGGElement} The SVGGElement representing the current layer.\n   */\n  getCurrentLayer () {\n    return this.current_layer ? this.current_layer.getGroup() : null;\n  }\n\n  /**\n   * Get a layer by name.\n   * @returns {SVGGElement} The SVGGElement representing the named layer or null.\n   */\n  getLayerByName (name) {\n    const layer = this.layer_map[name];\n    return layer ? layer.getGroup() : null;\n  }\n\n  /**\n   * Returns the name of the currently selected layer. If an error occurs, an empty string\n   * is returned.\n   * @returns {string} The name of the currently active layer (or the empty string if none found).\n  */\n  getCurrentLayerName () {\n    return this.current_layer ? this.current_layer.getName() : '';\n  }\n\n  /**\n   * Set the current layer's name.\n   * @param {string} name - The new name.\n   * @param {svgedit.history.HistoryRecordingService} hrService - History recording service\n   * @returns {string|null} The new name if changed; otherwise, null.\n   */\n  setCurrentLayerName (name, hrService) {\n    let finalName = null;\n    if (this.current_layer) {\n      const oldName = this.current_layer.getName();\n      finalName = this.current_layer.setName(name, hrService);\n      if (finalName) {\n        delete this.layer_map[oldName];\n        this.layer_map[finalName] = this.current_layer;\n      }\n    }\n    return finalName;\n  }\n\n  /**\n   * Set the current layer's position.\n   * @param {number} newpos - The zero-based index of the new position of the layer. Range should be 0 to layers-1\n   * @returns {Object} If the name was changed, returns {title:SVGGElement, previousName:string}; otherwise null.\n   */\n  setCurrentLayerPosition (newpos) {\n    const layerCount = this.getNumLayers();\n    if (!this.current_layer || newpos < 0 || newpos >= layerCount) {\n      return null;\n    }\n\n    let oldpos;\n    for (oldpos = 0; oldpos < layerCount; ++oldpos) {\n      if (this.all_layers[oldpos] === this.current_layer) { break; }\n    }\n    // some unknown error condition (current_layer not in all_layers)\n    if (oldpos === layerCount) { return null; }\n\n    if (oldpos !== newpos) {\n      // if our new position is below us, we need to insert before the node after newpos\n      const currentGroup = this.current_layer.getGroup();\n      const oldNextSibling = currentGroup.nextSibling;\n\n      let refGroup = null;\n      if (newpos > oldpos) {\n        if (newpos < layerCount - 1) {\n          refGroup = this.all_layers[newpos + 1].getGroup();\n        }\n      // if our new position is above us, we need to insert before the node at newpos\n      } else {\n        refGroup = this.all_layers[newpos].getGroup();\n      }\n      this.svgElem_.insertBefore(currentGroup, refGroup);\n\n      this.identifyLayers();\n      this.setCurrentLayer(this.getLayerName(newpos));\n\n      return {\n        currentGroup,\n        oldNextSibling\n      };\n    }\n    return null;\n  }\n\n  mergeLayer (hrService) {\n    const currentGroup = this.current_layer.getGroup();\n    const prevGroup = $(currentGroup).prev()[0];\n    if (!prevGroup) { return; }\n\n    hrService.startBatchCommand('Merge Layer');\n\n    const layerNextSibling = currentGroup.nextSibling;\n    hrService.removeElement(currentGroup, layerNextSibling, this.svgElem_);\n\n    while (currentGroup.firstChild) {\n      const child = currentGroup.firstChild;\n      if (child.localName === 'title') {\n        hrService.removeElement(child, child.nextSibling, currentGroup);\n        currentGroup.removeChild(child);\n        continue;\n      }\n      const oldNextSibling = child.nextSibling;\n      prevGroup.appendChild(child);\n      hrService.moveElement(child, oldNextSibling, currentGroup);\n    }\n\n    // Remove current layer's group\n    this.current_layer.removeGroup();\n    // Remove the current layer and set the previous layer as the new current layer\n    const index = this.all_layers.indexOf(this.current_layer);\n    if (index > 0) {\n      const name = this.current_layer.getName();\n      this.current_layer = this.all_layers[index - 1];\n      this.all_layers.splice(index, 1);\n      delete this.layer_map[name];\n    }\n\n    hrService.endBatchCommand();\n  }\n\n  mergeAllLayers (hrService) {\n    // Set the current layer to the last layer.\n    this.current_layer = this.all_layers[this.all_layers.length - 1];\n\n    hrService.startBatchCommand('Merge all Layers');\n    while (this.all_layers.length > 1) {\n      this.mergeLayer(hrService);\n    }\n    hrService.endBatchCommand();\n  }\n\n  /**\n   * Sets the current layer. If the name is not a valid layer name, then this\n   * function returns false. Otherwise it returns true. This is not an\n   * undo-able action.\n   * @param {string} name - The name of the layer you want to switch to.\n   * @returns {boolean} true if the current layer was switched, otherwise false\n   */\n  setCurrentLayer (name) {\n    const layer = this.layer_map[name];\n    if (layer) {\n      if (this.current_layer) {\n        this.current_layer.deactivate();\n      }\n      this.current_layer = layer;\n      this.current_layer.activate();\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * Deletes the current layer from the drawing and then clears the selection.\n   * This function then calls the 'changed' handler.  This is an undoable action.\n   * @returns {SVGGElement} The SVGGElement of the layer removed or null.\n   */\n  deleteCurrentLayer () {\n    if (this.current_layer && this.getNumLayers() > 1) {\n      const oldLayerGroup = this.current_layer.removeGroup();\n      this.identifyLayers();\n      return oldLayerGroup;\n    }\n    return null;\n  }\n\n  /**\n   * Updates layer system and sets the current layer to the\n   * top-most layer (last <g> child of this drawing).\n  */\n  identifyLayers () {\n    this.all_layers = [];\n    this.layer_map = {};\n    const numchildren = this.svgElem_.childNodes.length;\n    // loop through all children of SVG element\n    const orphans = [], layernames = [];\n    let layer = null;\n    let childgroups = false;\n    for (let i = 0; i < numchildren; ++i) {\n      const child = this.svgElem_.childNodes.item(i);\n      // for each g, find its layer name\n      if (child && child.nodeType === 1) {\n        if (child.tagName === 'g') {\n          childgroups = true;\n          const name = findLayerNameInGroup(child);\n          if (name) {\n            layernames.push(name);\n            layer = new Layer(name, child);\n            this.all_layers.push(layer);\n            this.layer_map[name] = layer;\n          } else {\n            // if group did not have a name, it is an orphan\n            orphans.push(child);\n          }\n        } else if (visElems.includes(child.nodeName)) {\n          // Child is \"visible\" (i.e. not a <title> or <defs> element), so it is an orphan\n          orphans.push(child);\n        }\n      }\n    }\n\n    // If orphans or no layers found, create a new layer and add all the orphans to it\n    if (orphans.length > 0 || !childgroups) {\n      layer = new Layer(getNewLayerName(layernames), null, this.svgElem_);\n      layer.appendChildren(orphans);\n      this.all_layers.push(layer);\n      this.layer_map[name] = layer;\n    } else {\n      layer.activate();\n    }\n    this.current_layer = layer;\n  }\n\n  /**\n   * Creates a new top-level layer in the drawing with the given name and\n   * makes it the current layer.\n   * @param {string} name - The given name. If the layer name exists, a new name will be generated.\n   * @param {svgedit.history.HistoryRecordingService} hrService - History recording service\n   * @returns {SVGGElement} The SVGGElement of the new layer, which is\n   *     also the current layer of this drawing.\n  */\n  createLayer (name, hrService) {\n    if (this.current_layer) {\n      this.current_layer.deactivate();\n    }\n    // Check for duplicate name.\n    if (name === undefined || name === null || name === '' || this.layer_map[name]) {\n      name = getNewLayerName(Object.keys(this.layer_map));\n    }\n\n    // Crate new layer and add to DOM as last layer\n    const layer = new Layer(name, null, this.svgElem_);\n    // Like to assume hrService exists, but this is backwards compatible with old version of createLayer.\n    if (hrService) {\n      hrService.startBatchCommand('Create Layer');\n      hrService.insertElement(layer.getGroup());\n      hrService.endBatchCommand();\n    }\n\n    this.all_layers.push(layer);\n    this.layer_map[name] = layer;\n    this.current_layer = layer;\n    return layer.getGroup();\n  }\n\n  /**\n   * Creates a copy of the current layer with the given name and makes it the current layer.\n   * @param {string} name - The given name. If the layer name exists, a new name will be generated.\n   * @param {svgedit.history.HistoryRecordingService} hrService - History recording service\n   * @returns {SVGGElement} The SVGGElement of the new layer, which is\n   *     also the current layer of this drawing.\n  */\n  cloneLayer (name, hrService) {\n    if (!this.current_layer) { return null; }\n    this.current_layer.deactivate();\n    // Check for duplicate name.\n    if (name === undefined || name === null || name === '' || this.layer_map[name]) {\n      name = getNewLayerName(Object.keys(this.layer_map));\n    }\n\n    // Create new group and add to DOM just after current_layer\n    const currentGroup = this.current_layer.getGroup();\n    const layer = new Layer(name, currentGroup, this.svgElem_);\n    const group = layer.getGroup();\n\n    // Clone children\n    const children = currentGroup.childNodes;\n    for (let index = 0; index < children.length; index++) {\n      const ch = children[index];\n      if (ch.localName === 'title') { continue; }\n      group.appendChild(this.copyElem(ch));\n    }\n\n    if (hrService) {\n      hrService.startBatchCommand('Duplicate Layer');\n      hrService.insertElement(group);\n      hrService.endBatchCommand();\n    }\n\n    // Update layer containers and current_layer.\n    const index = this.all_layers.indexOf(this.current_layer);\n    if (index >= 0) {\n      this.all_layers.splice(index + 1, 0, layer);\n    } else {\n      this.all_layers.push(layer);\n    }\n    this.layer_map[name] = layer;\n    this.current_layer = layer;\n    return group;\n  }\n\n  /**\n   * Returns whether the layer is visible.  If the layer name is not valid,\n   * then this function returns false.\n   * @param {string} layername - The name of the layer which you want to query.\n   * @returns {boolean} The visibility state of the layer, or false if the layer name was invalid.\n  */\n  getLayerVisibility (layername) {\n    const layer = this.layer_map[layername];\n    return layer ? layer.isVisible() : false;\n  }\n\n  /**\n   * Sets the visibility of the layer. If the layer name is not valid, this\n   * function returns false, otherwise it returns true. This is an\n   * undo-able action.\n   * @param {string} layername - The name of the layer to change the visibility\n   * @param {boolean} bVisible - Whether the layer should be visible\n   * @returns {?SVGGElement} The SVGGElement representing the layer if the\n   *   layername was valid, otherwise null.\n  */\n  setLayerVisibility (layername, bVisible) {\n    if (typeof bVisible !== 'boolean') {\n      return null;\n    }\n    const layer = this.layer_map[layername];\n    if (!layer) { return null; }\n    layer.setVisible(bVisible);\n    return layer.getGroup();\n  }\n\n  /**\n   * Returns the opacity of the given layer.  If the input name is not a layer, null is returned.\n   * @param {string} layername - name of the layer on which to get the opacity\n   * @returns {?number} The opacity value of the given layer.  This will be a value between 0.0 and 1.0, or null\n   * if layername is not a valid layer\n  */\n  getLayerOpacity (layername) {\n    const layer = this.layer_map[layername];\n    if (!layer) { return null; }\n    return layer.getOpacity();\n  }\n\n  /**\n   * Sets the opacity of the given layer.  If the input name is not a layer,\n   * nothing happens. If opacity is not a value between 0.0 and 1.0, then\n   * nothing happens.\n   * @param {string} layername - Name of the layer on which to set the opacity\n   * @param {number} opacity - A float value in the range 0.0-1.0\n  */\n  setLayerOpacity (layername, opacity) {\n    if (typeof opacity !== 'number' || opacity < 0.0 || opacity > 1.0) {\n      return;\n    }\n    const layer = this.layer_map[layername];\n    if (layer) {\n      layer.setOpacity(opacity);\n    }\n  }\n\n  /**\n   * Create a clone of an element, updating its ID and its children's IDs when needed\n   * @param {Element} el - DOM element to clone\n   * @returns {Element}\n   */\n  copyElem (el) {\n    const self = this;\n    const getNextIdClosure = function () { return self.getNextId(); };\n    return utilCopyElem(el, getNextIdClosure);\n  }\n}\n\n/**\n * Called to ensure that drawings will or will not have randomized ids.\n * The currentDrawing will have its nonce set if it doesn't already.\n * @param {boolean} enableRandomization - flag indicating if documents should have randomized ids\n * @param {svgedit.draw.Drawing} currentDrawing\n */\nexport const randomizeIds = function (enableRandomization, currentDrawing) {\n  randIds = enableRandomization === false\n    ? RandomizeModes.NEVER_RANDOMIZE\n    : RandomizeModes.ALWAYS_RANDOMIZE;\n\n  if (randIds === RandomizeModes.ALWAYS_RANDOMIZE && !currentDrawing.getNonce()) {\n    currentDrawing.setNonce(Math.floor(Math.random() * 100001));\n  } else if (randIds === RandomizeModes.NEVER_RANDOMIZE && currentDrawing.getNonce()) {\n    currentDrawing.clearNonce();\n  }\n};\n\n// Layer API Functions\n\n/**\n* Group: Layers\n*/\n\nlet canvas_;\nexport const init = function (canvas) {\n  canvas_ = canvas;\n};\n\n// Updates layer system\nexport const identifyLayers = function () {\n  leaveContext();\n  canvas_.getCurrentDrawing().identifyLayers();\n};\n\n/**\n* Creates a new top-level layer in the drawing with the given name, sets the current layer\n* to it, and then clears the selection. This function then calls the 'changed' handler.\n* This is an undoable action.\n* @param name - The given name\n* @param hrService\n*/\nexport const createLayer = function (name, hrService) {\n  const newLayer = canvas_.getCurrentDrawing().createLayer(\n    name,\n    historyRecordingService(hrService)\n  );\n  canvas_.clearSelection();\n  canvas_.call('changed', [newLayer]);\n};\n\n/**\n * Creates a new top-level layer in the drawing with the given name, copies all the current layer's contents\n * to it, and then clears the selection. This function then calls the 'changed' handler.\n * This is an undoable action.\n * @param {string} name - The given name. If the layer name exists, a new name will be generated.\n * @param {svgedit.history.HistoryRecordingService} hrService - History recording service\n */\nexport const cloneLayer = function (name, hrService) {\n  // Clone the current layer and make the cloned layer the new current layer\n  const newLayer = canvas_.getCurrentDrawing().cloneLayer(name, historyRecordingService(hrService));\n\n  canvas_.clearSelection();\n  leaveContext();\n  canvas_.call('changed', [newLayer]);\n};\n\n/**\n* Deletes the current layer from the drawing and then clears the selection. This function\n* then calls the 'changed' handler. This is an undoable action.\n*/\nexport const deleteCurrentLayer = function () {\n  let currentLayer = canvas_.getCurrentDrawing().getCurrentLayer();\n  const {nextSibling} = currentLayer;\n  const parent = currentLayer.parentNode;\n  currentLayer = canvas_.getCurrentDrawing().deleteCurrentLayer();\n  if (currentLayer) {\n    const batchCmd = new BatchCommand('Delete Layer');\n    // store in our Undo History\n    batchCmd.addSubCommand(new RemoveElementCommand(currentLayer, nextSibling, parent));\n    canvas_.addCommandToHistory(batchCmd);\n    canvas_.clearSelection();\n    canvas_.call('changed', [parent]);\n    return true;\n  }\n  return false;\n};\n\n/**\n* Sets the current layer. If the name is not a valid layer name, then this function returns\n* false. Otherwise it returns true. This is not an undo-able action.\n* @param name - The name of the layer you want to switch to.\n*\n* @returns true if the current layer was switched, otherwise false\n*/\nexport const setCurrentLayer = function (name) {\n  const result = canvas_.getCurrentDrawing().setCurrentLayer(toXml(name));\n  if (result) {\n    canvas_.clearSelection();\n  }\n  return result;\n};\n\n/**\n* Renames the current layer. If the layer name is not valid (i.e. unique), then this function\n* does nothing and returns false, otherwise it returns true. This is an undo-able action.\n*\n* @param newname - the new name you want to give the current layer. This name must be unique\n* among all layer names.\n* @returns {Boolean} Whether the rename succeeded\n*/\nexport const renameCurrentLayer = function (newname) {\n  const drawing = canvas_.getCurrentDrawing();\n  const layer = drawing.getCurrentLayer();\n  if (layer) {\n    const result = drawing.setCurrentLayerName(newname, historyRecordingService());\n    if (result) {\n      canvas_.call('changed', [layer]);\n      return true;\n    }\n  }\n  return false;\n};\n\n/**\n* Changes the position of the current layer to the new value. If the new index is not valid,\n* this function does nothing and returns false, otherwise it returns true. This is an\n* undo-able action.\n* @param newpos - The zero-based index of the new position of the layer. This should be between\n* 0 and (number of layers - 1)\n*\n* @returns {Boolean} true if the current layer position was changed, false otherwise.\n*/\nexport const setCurrentLayerPosition = function (newpos) {\n  const drawing = canvas_.getCurrentDrawing();\n  const result = drawing.setCurrentLayerPosition(newpos);\n  if (result) {\n    canvas_.addCommandToHistory(new MoveElementCommand(result.currentGroup, result.oldNextSibling, canvas_.getSVGContent()));\n    return true;\n  }\n  return false;\n};\n\n/**\n* Sets the visibility of the layer. If the layer name is not valid, this function return\n* false, otherwise it returns true. This is an undo-able action.\n* @param layername - The name of the layer to change the visibility\n* @param {Boolean} bVisible - Whether the layer should be visible\n* @returns {Boolean} true if the layer's visibility was set, false otherwise\n*/\nexport const setLayerVisibility = function (layername, bVisible) {\n  const drawing = canvas_.getCurrentDrawing();\n  const prevVisibility = drawing.getLayerVisibility(layername);\n  const layer = drawing.setLayerVisibility(layername, bVisible);\n  if (layer) {\n    const oldDisplay = prevVisibility ? 'inline' : 'none';\n    canvas_.addCommandToHistory(new ChangeElementCommand(layer, {display: oldDisplay}, 'Layer Visibility'));\n  } else {\n    return false;\n  }\n\n  if (layer === drawing.getCurrentLayer()) {\n    canvas_.clearSelection();\n    canvas_.pathActions.clear();\n  }\n  // call('changed', [selected]);\n  return true;\n};\n\n/**\n* Moves the selected elements to layername. If the name is not a valid layer name, then false\n* is returned. Otherwise it returns true. This is an undo-able action.\n*\n* @param layername - The name of the layer you want to which you want to move the selected elements\n* @returns {Boolean} Whether the selected elements were moved to the layer.\n*/\nexport const moveSelectedToLayer = function (layername) {\n  // find the layer\n  const drawing = canvas_.getCurrentDrawing();\n  const layer = drawing.getLayerByName(layername);\n  if (!layer) { return false; }\n\n  const batchCmd = new BatchCommand('Move Elements to Layer');\n\n  // loop for each selected element and move it\n  const selElems = canvas_.getSelectedElements();\n  let i = selElems.length;\n  while (i--) {\n    const elem = selElems[i];\n    if (!elem) { continue; }\n    const oldNextSibling = elem.nextSibling;\n    // TODO: this is pretty brittle!\n    const oldLayer = elem.parentNode;\n    layer.appendChild(elem);\n    batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldLayer));\n  }\n\n  canvas_.addCommandToHistory(batchCmd);\n\n  return true;\n};\n\nexport const mergeLayer = function (hrService) {\n  canvas_.getCurrentDrawing().mergeLayer(historyRecordingService(hrService));\n  canvas_.clearSelection();\n  leaveContext();\n  canvas_.changeSvgcontent();\n};\n\nexport const mergeAllLayers = function (hrService) {\n  canvas_.getCurrentDrawing().mergeAllLayers(historyRecordingService(hrService));\n  canvas_.clearSelection();\n  leaveContext();\n  canvas_.changeSvgcontent();\n};\n\n// Return from a group context to the regular kind, make any previously\n// disabled elements enabled again\nexport const leaveContext = function () {\n  const len = disabledElems.length;\n  if (len) {\n    for (let i = 0; i < len; i++) {\n      const elem = disabledElems[i];\n      const orig = canvas_.elData(elem, 'orig_opac');\n      if (orig !== 1) {\n        elem.setAttribute('opacity', orig);\n      } else {\n        elem.removeAttribute('opacity');\n      }\n      elem.setAttribute('style', 'pointer-events: inherit');\n    }\n    disabledElems = [];\n    canvas_.clearSelection(true);\n    canvas_.call('contextset', null);\n  }\n  canvas_.setCurrentGroup(null);\n};\n\n// Set the current context (for in-group editing)\nexport const setContext = function (elem) {\n  leaveContext();\n  if (typeof elem === 'string') {\n    elem = getElem(elem);\n  }\n\n  // Edit inside this group\n  canvas_.setCurrentGroup(elem);\n\n  // Disable other elements\n  $(elem).parentsUntil('#svgcontent').andSelf().siblings().each(function () {\n    const opac = this.getAttribute('opacity') || 1;\n    // Store the original's opacity\n    canvas_.elData(this, 'orig_opac', opac);\n    this.setAttribute('opacity', opac * 0.33);\n    this.setAttribute('style', 'pointer-events: none');\n    disabledElems.push(this);\n  });\n\n  canvas_.clearSelection();\n  canvas_.call('contextset', canvas_.getCurrentGroup());\n};\n\nexport {Layer};\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/external/dynamic-import-polyfill/importModule.js",
    "content": "// MIT License\n// From: https://github.com/uupaa/dynamic-import-polyfill/blob/master/importModule.js\n\nfunction toAbsoluteURL(url) {\n  const a = document.createElement(\"a\");\n  a.setAttribute(\"href\", url);    // <a href=\"hoge.html\">\n  return a.cloneNode(false).href; // -> \"http://example.com/hoge.html\"\n}\n\n// My own addition\nexport function importScript(url) {\n  return new Promise((resolve, reject) => {\n    const script = document.createElement(\"script\");\n    const destructor = () => {\n      script.onerror = null;\n      script.onload = null;\n      script.remove();\n      script.src = \"\";\n    };\n    script.defer = \"defer\";\n    script.onerror = () => {\n      reject(new Error(`Failed to import: ${url}`));\n      destructor();\n    };\n    script.onload = () => {\n      resolve();\n      destructor();\n    };\n    script.src = url;\n\n    document.head.appendChild(script);\n  });\n}\n\nexport function importModule(url) {\n  return new Promise((resolve, reject) => {\n    const vector = \"$importModule$\" + Math.random().toString(32).slice(2);\n    const script = document.createElement(\"script\");\n    const destructor = () => {\n      delete window[vector];\n      script.onerror = null;\n      script.onload = null;\n      script.remove();\n      URL.revokeObjectURL(script.src);\n      script.src = \"\";\n    };\n    script.defer = \"defer\";\n    script.type = \"module\";\n    script.onerror = () => {\n      reject(new Error(`Failed to import: ${url}`));\n      destructor();\n    };\n    script.onload = () => {\n      resolve(window[vector]);\n      destructor();\n    };\n    const absURL = toAbsoluteURL(url);\n    const loader = `import * as m from \"${absURL}\"; window.${vector} = m;`; // export Module\n    const blob = new Blob([loader], { type: \"text/javascript\" });\n    script.src = URL.createObjectURL(blob);\n\n    document.head.appendChild(script);\n  });\n}\n\nexport default importModule;\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/history.js",
    "content": "/**\n * Package: svedit.history\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2010 Jeff Schiller\n */\n\nimport {getHref, setHref, getRotationAngle} from './svgutils.js';\nimport {removeElementFromListMap} from './svgtransformlist.js';\n\n/**\n* Group: Undo/Redo history management\n*/\nexport const HistoryEventTypes = {\n  BEFORE_APPLY: 'before_apply',\n  AFTER_APPLY: 'after_apply',\n  BEFORE_UNAPPLY: 'before_unapply',\n  AFTER_UNAPPLY: 'after_unapply'\n};\n\n// const removedElements = {};\n\n/**\n * An interface that all command objects must implement.\n * @typedef {Object} svgedit.history.HistoryCommand\n *   void apply(svgedit.history.HistoryEventHandler);\n *   void unapply(svgedit.history.HistoryEventHandler);\n *   Element[] elements();\n *   String getText();\n *\n *   static String type();\n * }\n *\n * Interface: svgedit.history.HistoryEventHandler\n * An interface for objects that will handle history events.\n *\n * interface svgedit.history.HistoryEventHandler {\n *   void handleHistoryEvent(eventType, command);\n * }\n *\n * eventType is a string conforming to one of the HistoryEvent types.\n * command is an object fulfilling the HistoryCommand interface.\n */\n\n/**\n * @class svgedit.history.MoveElementCommand\n * @implements svgedit.history.HistoryCommand\n * History command for an element that had its DOM position changed\n * @param {Element} elem - The DOM element that was moved\n * @param {Element} oldNextSibling - The element's next sibling before it was moved\n * @param {Element} oldParent - The element's parent before it was moved\n * @param {string} [text] - An optional string visible to user related to this change\n*/\nexport class MoveElementCommand {\n  constructor (elem, oldNextSibling, oldParent, text) {\n    this.elem = elem;\n    this.text = text ? ('Move ' + elem.tagName + ' to ' + text) : ('Move ' + elem.tagName);\n    this.oldNextSibling = oldNextSibling;\n    this.oldParent = oldParent;\n    this.newNextSibling = elem.nextSibling;\n    this.newParent = elem.parentNode;\n  }\n  getText () {\n    return this.text;\n  }\n  type () {\n    return 'svgedit.history.MoveElementCommand';\n  }\n\n  /**\n   * Re-positions the element\n   * @param {{handleHistoryEvent: function}} handler\n  */\n  apply (handler) {\n    // TODO(codedread): Refactor this common event code into a base HistoryCommand class.\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_APPLY, this);\n    }\n\n    this.elem = this.newParent.insertBefore(this.elem, this.newNextSibling);\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_APPLY, this);\n    }\n  }\n\n  /**\n   * Positions the element back to its original location\n   * @param {{handleHistoryEvent: function}} handler\n  */\n  unapply (handler) {\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_UNAPPLY, this);\n    }\n\n    this.elem = this.oldParent.insertBefore(this.elem, this.oldNextSibling);\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_UNAPPLY, this);\n    }\n  }\n\n  /**\n  * @returns {Array} Array with element associated with this command\n  */\n  elements () {\n    return [this.elem];\n  }\n}\nMoveElementCommand.type = MoveElementCommand.prototype.type;\n\n/**\n* @implements svgedit.history.HistoryCommand\n* History command for an element that was added to the DOM\n*\n* @param elem - The newly added DOM element\n* @param text - An optional string visible to user related to this change\n*/\nexport class InsertElementCommand {\n  constructor (elem, text) {\n    this.elem = elem;\n    this.text = text || ('Create ' + elem.tagName);\n    this.parent = elem.parentNode;\n    this.nextSibling = this.elem.nextSibling;\n  }\n\n  type () {\n    return 'svgedit.history.InsertElementCommand';\n  }\n\n  getText () {\n    return this.text;\n  }\n\n  // Re-Inserts the new element\n  apply (handler) {\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_APPLY, this);\n    }\n\n    this.elem = this.parent.insertBefore(this.elem, this.nextSibling);\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_APPLY, this);\n    }\n  }\n\n  // Removes the element\n  unapply (handler) {\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_UNAPPLY, this);\n    }\n\n    this.parent = this.elem.parentNode;\n    this.elem = this.elem.parentNode.removeChild(this.elem);\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_UNAPPLY, this);\n    }\n  }\n\n  /**\n  * @returns {Array} Array with element associated with this command\n  */\n  elements () {\n    return [this.elem];\n  }\n}\nInsertElementCommand.type = InsertElementCommand.prototype.type;\n\n/**\n* @implements svgedit.history.HistoryCommand\n* History command for an element removed from the DOM\n* @param elem - The removed DOM element\n* @param oldNextSibling - The DOM element's nextSibling when it was in the DOM\n* @param oldParent - The DOM element's parent\n* @param {String} [text] - An optional string visible to user related to this change\n*/\nexport class RemoveElementCommand {\n  constructor (elem, oldNextSibling, oldParent, text) {\n    this.elem = elem;\n    this.text = text || ('Delete ' + elem.tagName);\n    this.nextSibling = oldNextSibling;\n    this.parent = oldParent;\n\n    // special hack for webkit: remove this element's entry in the svgTransformLists map\n    removeElementFromListMap(elem);\n  }\n  type () {\n    return 'svgedit.history.RemoveElementCommand';\n  }\n\n  getText () {\n    return this.text;\n  }\n\n  // Re-removes the new element\n  apply (handler) {\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_APPLY, this);\n    }\n\n    removeElementFromListMap(this.elem);\n    this.parent = this.elem.parentNode;\n    this.elem = this.parent.removeChild(this.elem);\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_APPLY, this);\n    }\n  }\n\n  // Re-adds the new element\n  unapply (handler) {\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_UNAPPLY, this);\n    }\n\n    removeElementFromListMap(this.elem);\n    if (this.nextSibling == null) {\n      if (window.console) {\n        console.log('Error: reference element was lost');\n      }\n    }\n    this.parent.insertBefore(this.elem, this.nextSibling);\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_UNAPPLY, this);\n    }\n  }\n\n  /**\n  * @returns {Array} Array with element associated with this command\n  */\n  elements () {\n    return [this.elem];\n  }\n}\nRemoveElementCommand.type = RemoveElementCommand.prototype.type;\n\n/**\n* @implements svgedit.history.HistoryCommand\n* History command to make a change to an element.\n* Usually an attribute change, but can also be textcontent.\n* @param elem - The DOM element that was changed\n* @param attrs - An object with the attributes to be changed and the values they had *before* the change\n* @param {String} text - An optional string visible to user related to this change\n*/\nexport class ChangeElementCommand {\n  constructor (elem, attrs, text) {\n    this.elem = elem;\n    this.text = text ? ('Change ' + elem.tagName + ' ' + text) : ('Change ' + elem.tagName);\n    this.newValues = {};\n    this.oldValues = attrs;\n    for (const attr in attrs) {\n      if (attr === '#text') {\n        this.newValues[attr] = elem.textContent;\n      } else if (attr === '#href') {\n        this.newValues[attr] = getHref(elem);\n      } else {\n        this.newValues[attr] = elem.getAttribute(attr);\n      }\n    }\n  }\n  type () {\n    return 'svgedit.history.ChangeElementCommand';\n  }\n\n  getText () {\n    return this.text;\n  }\n\n  // Performs the stored change action\n  apply (handler) {\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_APPLY, this);\n    }\n\n    let bChangedTransform = false;\n    for (const attr in this.newValues) {\n      if (this.newValues[attr]) {\n        if (attr === '#text') {\n          this.elem.textContent = this.newValues[attr];\n        } else if (attr === '#href') {\n          setHref(this.elem, this.newValues[attr]);\n        } else {\n          this.elem.setAttribute(attr, this.newValues[attr]);\n        }\n      } else {\n        if (attr === '#text') {\n          this.elem.textContent = '';\n        } else {\n          this.elem.setAttribute(attr, '');\n          this.elem.removeAttribute(attr);\n        }\n      }\n\n      if (attr === 'transform') { bChangedTransform = true; }\n    }\n\n    // relocate rotational transform, if necessary\n    if (!bChangedTransform) {\n      const angle = getRotationAngle(this.elem);\n      if (angle) {\n        const bbox = this.elem.getBBox();\n        const cx = bbox.x + bbox.width / 2,\n          cy = bbox.y + bbox.height / 2;\n        const rotate = ['rotate(', angle, ' ', cx, ',', cy, ')'].join('');\n        if (rotate !== this.elem.getAttribute('transform')) {\n          this.elem.setAttribute('transform', rotate);\n        }\n      }\n    }\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_APPLY, this);\n    }\n\n    return true;\n  }\n\n  // Reverses the stored change action\n  unapply (handler) {\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_UNAPPLY, this);\n    }\n\n    let bChangedTransform = false;\n    for (const attr in this.oldValues) {\n      if (this.oldValues[attr]) {\n        if (attr === '#text') {\n          this.elem.textContent = this.oldValues[attr];\n        } else if (attr === '#href') {\n          setHref(this.elem, this.oldValues[attr]);\n        } else {\n          this.elem.setAttribute(attr, this.oldValues[attr]);\n        }\n      } else {\n        if (attr === '#text') {\n          this.elem.textContent = '';\n        } else {\n          this.elem.removeAttribute(attr);\n        }\n      }\n      if (attr === 'transform') { bChangedTransform = true; }\n    }\n    // relocate rotational transform, if necessary\n    if (!bChangedTransform) {\n      const angle = getRotationAngle(this.elem);\n      if (angle) {\n        const bbox = this.elem.getBBox();\n        const cx = bbox.x + bbox.width / 2,\n          cy = bbox.y + bbox.height / 2;\n        const rotate = ['rotate(', angle, ' ', cx, ',', cy, ')'].join('');\n        if (rotate !== this.elem.getAttribute('transform')) {\n          this.elem.setAttribute('transform', rotate);\n        }\n      }\n    }\n\n    // Remove transformlist to prevent confusion that causes bugs like 575.\n    removeElementFromListMap(this.elem);\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_UNAPPLY, this);\n    }\n\n    return true;\n  }\n\n  /**\n  * @returns {Array} Array with element associated with this command\n  */\n  elements () {\n    return [this.elem];\n  }\n}\nChangeElementCommand.type = ChangeElementCommand.prototype.type;\n\n// TODO: create a 'typing' command object that tracks changes in text\n// if a new Typing command is created and the top command on the stack is also a Typing\n// and they both affect the same element, then collapse the two commands into one\n\n/**\n* @implements svgedit.history.HistoryCommand\n* History command that can contain/execute multiple other commands\n* @param {String} [text] - An optional string visible to user related to this change\n*/\nexport class BatchCommand {\n  constructor (text) {\n    this.text = text || 'Batch Command';\n    this.stack = [];\n  }\n\n  type () {\n    return 'svgedit.history.BatchCommand';\n  }\n\n  getText () {\n    return this.text;\n  }\n\n  // Runs \"apply\" on all subcommands\n  apply (handler) {\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_APPLY, this);\n    }\n\n    const len = this.stack.length;\n    for (let i = 0; i < len; ++i) {\n      this.stack[i].apply(handler);\n    }\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_APPLY, this);\n    }\n  }\n\n  // Runs \"unapply\" on all subcommands\n  unapply (handler) {\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.BEFORE_UNAPPLY, this);\n    }\n\n    for (let i = this.stack.length - 1; i >= 0; i--) {\n      this.stack[i].unapply(handler);\n    }\n\n    if (handler) {\n      handler.handleHistoryEvent(HistoryEventTypes.AFTER_UNAPPLY, this);\n    }\n  }\n\n  // Iterate through all our subcommands and returns all the elements we are changing\n  elements () {\n    const elems = [];\n    let cmd = this.stack.length;\n    while (cmd--) {\n      const thisElems = this.stack[cmd].elements();\n      let elem = thisElems.length;\n      while (elem--) {\n        if (!elems.includes(thisElems[elem])) { elems.push(thisElems[elem]); }\n      }\n    }\n    return elems;\n  }\n\n  /**\n  * Adds a given command to the history stack\n  * @param cmd - The undo command object to add\n  */\n  addSubCommand (cmd) {\n    this.stack.push(cmd);\n  }\n\n  /**\n  * @returns {Boolean} Indicates whether or not the batch command is empty\n  */\n  isEmpty () {\n    return !this.stack.length;\n  }\n}\nBatchCommand.type = BatchCommand.prototype.type;\n\n/**\n* @param historyEventHandler - an object that conforms to the HistoryEventHandler interface\n* (see above)\n*/\nexport class UndoManager {\n  constructor (historyEventHandler) {\n    this.handler_ = historyEventHandler || null;\n    this.undoStackPointer = 0;\n    this.undoStack = [];\n\n    // this is the stack that stores the original values, the elements and\n    // the attribute name for begin/finish\n    this.undoChangeStackPointer = -1;\n    this.undoableChangeStack = [];\n  }\n\n  // Resets the undo stack, effectively clearing the undo/redo history\n  resetUndoStack () {\n    this.undoStack = [];\n    this.undoStackPointer = 0;\n  }\n\n  /**\n  * @returns {Number} Integer with the current size of the undo history stack\n  */\n  getUndoStackSize () {\n    return this.undoStackPointer;\n  }\n\n  /**\n  * @returns {Number} Integer with the current size of the redo history stack\n  */\n  getRedoStackSize () {\n    return this.undoStack.length - this.undoStackPointer;\n  }\n\n  /**\n  * @returns {String} String associated with the next undo command\n  */\n  getNextUndoCommandText () {\n    return this.undoStackPointer > 0 ? this.undoStack[this.undoStackPointer - 1].getText() : '';\n  }\n\n  /**\n  * @returns {String} String associated with the next redo command\n  */\n  getNextRedoCommandText () {\n    return this.undoStackPointer < this.undoStack.length ? this.undoStack[this.undoStackPointer].getText() : '';\n  }\n\n  // Performs an undo step\n  undo () {\n    if (this.undoStackPointer > 0) {\n      const cmd = this.undoStack[--this.undoStackPointer];\n      cmd.unapply(this.handler_);\n    }\n  }\n\n  // Performs a redo step\n  redo () {\n    if (this.undoStackPointer < this.undoStack.length && this.undoStack.length > 0) {\n      const cmd = this.undoStack[this.undoStackPointer++];\n      cmd.apply(this.handler_);\n    }\n  }\n\n  /**\n  * Adds a command object to the undo history stack\n  * @param cmd - The command object to add\n  */\n  addCommandToHistory (cmd) {\n    // FIXME: we MUST compress consecutive text changes to the same element\n    // (right now each keystroke is saved as a separate command that includes the\n    // entire text contents of the text element)\n    // TODO: consider limiting the history that we store here (need to do some slicing)\n\n    // if our stack pointer is not at the end, then we have to remove\n    // all commands after the pointer and insert the new command\n    if (this.undoStackPointer < this.undoStack.length && this.undoStack.length > 0) {\n      this.undoStack = this.undoStack.splice(0, this.undoStackPointer);\n    }\n    this.undoStack.push(cmd);\n    this.undoStackPointer = this.undoStack.length;\n  }\n\n  /**\n  * This function tells the canvas to remember the old values of the\n  * attrName attribute for each element sent in.  The elements and values\n  * are stored on a stack, so the next call to finishUndoableChange() will\n  * pop the elements and old values off the stack, gets the current values\n  * from the DOM and uses all of these to construct the undo-able command.\n  * @param attrName - The name of the attribute being changed\n  * @param elems - Array of DOM elements being changed\n  */\n  beginUndoableChange (attrName, elems) {\n    const p = ++this.undoChangeStackPointer;\n    let i = elems.length;\n    const oldValues = new Array(i), elements = new Array(i);\n    while (i--) {\n      const elem = elems[i];\n      if (elem == null) { continue; }\n      elements[i] = elem;\n      oldValues[i] = elem.getAttribute(attrName);\n    }\n    this.undoableChangeStack[p] = {\n      attrName,\n      oldValues,\n      elements\n    };\n  }\n\n  /**\n  * This function returns a BatchCommand object which summarizes the\n  * change since beginUndoableChange was called.  The command can then\n  * be added to the command history\n  * @returns Batch command object with resulting changes\n  */\n  finishUndoableChange () {\n    const p = this.undoChangeStackPointer--;\n    const changeset = this.undoableChangeStack[p];\n    const {attrName} = changeset;\n    const batchCmd = new BatchCommand('Change ' + attrName);\n    let i = changeset.elements.length;\n    while (i--) {\n      const elem = changeset.elements[i];\n      if (elem == null) { continue; }\n      const changes = {};\n      changes[attrName] = changeset.oldValues[i];\n      if (changes[attrName] !== elem.getAttribute(attrName)) {\n        batchCmd.addSubCommand(new ChangeElementCommand(elem, changes, attrName));\n      }\n    }\n    this.undoableChangeStack[p] = null;\n    return batchCmd;\n  }\n}\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/historyrecording.js",
    "content": "/**\n * Package: svgedit.history\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2016 Flint O'Brien\n */\n\nimport {\n  BatchCommand, MoveElementCommand, InsertElementCommand, RemoveElementCommand,\n  ChangeElementCommand\n} from './history.js';\n\n/**\n * History recording service.\n *\n * A self-contained service interface for recording history. Once injected, no other dependencies\n * or globals are required (example: UndoManager, command types, etc.). Easy to mock for unit tests.\n * Built on top of history classes in history.js.\n *\n * There is a simple start/end interface for batch commands.\n *\n * HistoryRecordingService.NO_HISTORY is a singleton that can be passed in to functions\n * that record history. This helps when the caller requires that no history be recorded.\n *\n * Usage:\n * The following will record history: insert, batch, insert.\n * ```\n * hrService = new svgedit.history.HistoryRecordingService(this.undoMgr);\n * hrService.insertElement(elem, text);         // add simple command to history.\n * hrService.startBatchCommand('create two elements');\n * hrService.changeElement(elem, attrs, text);  // add to batchCommand\n * hrService.changeElement(elem, attrs2, text); // add to batchCommand\n * hrService.endBatchCommand();                  // add batch command with two change commands to history.\n * hrService.insertElement(elem, text);         // add simple command to history.\n * ```\n *\n * Note that all functions return this, so commands can be chained, like so:\n *\n * ```\n * hrService\n *   .startBatchCommand('create two elements')\n *   .insertElement(elem, text)\n *   .changeElement(elem, attrs, text)\n *   .endBatchCommand();\n * ```\n *\n * @param {svgedit.history.UndoManager} undoManager - The undo manager.\n *     A value of null is valid for cases where no history recording is required.\n *     See singleton: HistoryRecordingService.NO_HISTORY\n */\nclass HistoryRecordingService {\n  constructor (undoManager) {\n    this.undoManager_ = undoManager;\n    this.currentBatchCommand_ = null;\n    this.batchCommandStack_ = [];\n  }\n\n  /**\n   * Start a batch command so multiple commands can recorded as a single history command.\n   * Requires a corresponding call to endBatchCommand. Start and end commands can be nested.\n   *\n   * @param {string} text - Optional string describing the batch command.\n   * @returns {svgedit.history.HistoryRecordingService}\n   */\n  startBatchCommand (text) {\n    if (!this.undoManager_) { return this; }\n    this.currentBatchCommand_ = new BatchCommand(text);\n    this.batchCommandStack_.push(this.currentBatchCommand_);\n    return this;\n  }\n\n  /**\n   * End a batch command and add it to the history or a parent batch command.\n   * @returns {svgedit.history.HistoryRecordingService}\n   */\n  endBatchCommand () {\n    if (!this.undoManager_) { return this; }\n    if (this.currentBatchCommand_) {\n      const batchCommand = this.currentBatchCommand_;\n      this.batchCommandStack_.pop();\n      const {length} = this.batchCommandStack_;\n      this.currentBatchCommand_ = length ? this.batchCommandStack_[length - 1] : null;\n      this.addCommand_(batchCommand);\n    }\n    return this;\n  }\n\n  /**\n   * Add a MoveElementCommand to the history or current batch command\n   * @param {Element} elem - The DOM element that was moved\n   * @param {Element} oldNextSibling - The element's next sibling before it was moved\n   * @param {Element} oldParent - The element's parent before it was moved\n   * @param {string} [text] - An optional string visible to user related to this change\n   * @returns {svgedit.history.HistoryRecordingService}\n   */\n  moveElement (elem, oldNextSibling, oldParent, text) {\n    if (!this.undoManager_) { return this; }\n    this.addCommand_(new MoveElementCommand(elem, oldNextSibling, oldParent, text));\n    return this;\n  }\n\n  /**\n   * Add an InsertElementCommand to the history or current batch command\n   * @param {Element} elem - The DOM element that was added\n   * @param {string} [text] - An optional string visible to user related to this change\n   * @returns {svgedit.history.HistoryRecordingService}\n   */\n  insertElement (elem, text) {\n    if (!this.undoManager_) { return this; }\n    this.addCommand_(new InsertElementCommand(elem, text));\n    return this;\n  }\n\n  /**\n   * Add a RemoveElementCommand to the history or current batch command\n   * @param {Element} elem - The DOM element that was removed\n   * @param {Element} oldNextSibling - The element's next sibling before it was removed\n   * @param {Element} oldParent - The element's parent before it was removed\n   * @param {string} [text] - An optional string visible to user related to this change\n   * @returns {svgedit.history.HistoryRecordingService}\n   */\n  removeElement (elem, oldNextSibling, oldParent, text) {\n    if (!this.undoManager_) { return this; }\n    this.addCommand_(new RemoveElementCommand(elem, oldNextSibling, oldParent, text));\n    return this;\n  }\n\n  /**\n   * Add a ChangeElementCommand to the history or current batch command\n   * @param {Element} elem - The DOM element that was changed\n   * @param {Object} attrs - An object with the attributes to be changed and the values they had *before* the change\n   * @param {string} [text] - An optional string visible to user related to this change\n   * @returns {svgedit.history.HistoryRecordingService}\n   */\n  changeElement (elem, attrs, text) {\n    if (!this.undoManager_) { return this; }\n    this.addCommand_(new ChangeElementCommand(elem, attrs, text));\n    return this;\n  }\n\n  /**\n   * Private function to add a command to the history or current batch command.\n   * @param cmd\n   * @returns {svgedit.history.HistoryRecordingService}\n   * @private\n   */\n  addCommand_ (cmd) {\n    if (!this.undoManager_) { return this; }\n    if (this.currentBatchCommand_) {\n      this.currentBatchCommand_.addSubCommand(cmd);\n    } else {\n      this.undoManager_.addCommandToHistory(cmd);\n    }\n  }\n}\n/**\n * @property {HistoryRecordingService} NO_HISTORY - Singleton that can be passed to functions that record history, but the caller requires that no history be recorded.\n */\nHistoryRecordingService.NO_HISTORY = new HistoryRecordingService();\nexport default HistoryRecordingService;\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/jquery-svg.js",
    "content": "/**\n * jQuery module to work with SVG.\n *\n * Licensed under the MIT License\n *\n */\n\n// This fixes $(...).attr() to work as expected with SVG elements.\n// Does not currently use *AttributeNS() since we rarely need that.\n\n// See https://api.jquery.com/attr/ for basic documentation of .attr()\n\n// Additional functionality:\n// - When getting attributes, a string that's a number is returned as type number.\n// - If an array is supplied as the first parameter, multiple values are returned\n//    as an object with values for each given attribute\n\nexport default function ($) {\n  const proxied = $.fn.attr,\n    svgns = 'http://www.w3.org/2000/svg';\n  $.fn.attr = function (key, value) {\n    const len = this.length;\n    if (!len) { return proxied.apply(this, arguments); }\n    for (let i = 0; i < len; ++i) {\n      const elem = this[i];\n      // set/get SVG attribute\n      if (elem.namespaceURI === svgns) {\n        // Setting attribute\n        if (value !== undefined) {\n          elem.setAttribute(key, value);\n        } else if (Array.isArray(key)) {\n          // Getting attributes from array\n          const obj = {};\n          let j = key.length;\n\n          while (j--) {\n            const aname = key[j];\n            let attr = elem.getAttribute(aname);\n            // This returns a number when appropriate\n            if (attr || attr === '0') {\n              attr = isNaN(attr) ? attr : (attr - 0);\n            }\n            obj[aname] = attr;\n          }\n          return obj;\n        }\n        if (typeof key === 'object') {\n          // Setting attributes from object\n          for (const v in key) {\n            elem.setAttribute(v, key[v]);\n          }\n        // Getting attribute\n        } else {\n          let attr = elem.getAttribute(key);\n          if (attr || attr === '0') {\n            attr = isNaN(attr) ? attr : (attr - 0);\n          }\n          return attr;\n        }\n      } else {\n        return proxied.apply(this, arguments);\n      }\n    }\n    return this;\n  };\n  return $;\n}\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/layer.js",
    "content": "/* globals jQuery */\n/**\n * Licensed under the MIT License\n *\n * Copyright(c) 2011 Jeff Schiller\n * Copyright(c) 2016 Flint O'Brien\n */\n\nimport {NS} from './svgedit.js';\nimport {toXml, walkTree} from './svgutils.js';\n\nconst $ = jQuery;\n\n/**\n * This class encapsulates the concept of a layer in the drawing. It can be constructed with\n * an existing group element or, with three parameters, will create a new layer group element.\n *\n * Usage:\n * new Layer'name', group)          // Use the existing group for this layer.\n * new Layer('name', group, svgElem) // Create a new group and add it to the DOM after group.\n * new Layer('name', null, svgElem)  // Create a new group and add it to the DOM as the last layer.\n *\n * @param {string} name - Layer name\n * @param {SVGGElement|null} group - An existing SVG group element or null.\n *     If group and no svgElem, use group for this layer.\n *     If group and svgElem, create a new group element and insert it in the DOM after group.\n *     If no group and svgElem, create a new group element and insert it in the DOM as the last layer.\n * @param {SVGGElement=} svgElem - The SVG DOM element. If defined, use this to add\n *     a new layer to the document.\n */\nclass Layer {\n  constructor (name, group, svgElem) {\n    this.name_ = name;\n    this.group_ = svgElem ? null : group;\n\n    if (svgElem) {\n      // Create a group element with title and add it to the DOM.\n      const svgdoc = svgElem.ownerDocument;\n      this.group_ = svgdoc.createElementNS(NS.SVG, 'g');\n      const layerTitle = svgdoc.createElementNS(NS.SVG, 'title');\n      layerTitle.textContent = name;\n      this.group_.appendChild(layerTitle);\n      if (group) {\n        $(group).after(this.group_);\n      } else {\n        svgElem.appendChild(this.group_);\n      }\n    }\n\n    addLayerClass(this.group_);\n    walkTree(this.group_, function (e) {\n      e.setAttribute('style', 'pointer-events:inherit');\n    });\n\n    this.group_.setAttribute('style', svgElem ? 'pointer-events:all' : 'pointer-events:none');\n  }\n\n  /**\n   * Get the layer's name.\n   * @returns {string} The layer name\n   */\n  getName () {\n    return this.name_;\n  }\n\n  /**\n   * Get the group element for this layer.\n   * @returns {SVGGElement} The layer SVG group\n   */\n  getGroup () {\n    return this.group_;\n  }\n\n  /**\n   * Active this layer so it takes pointer events.\n   */\n  activate () {\n    this.group_.setAttribute('style', 'pointer-events:all');\n  }\n\n  /**\n   * Deactive this layer so it does NOT take pointer events.\n   */\n  deactivate () {\n    this.group_.setAttribute('style', 'pointer-events:none');\n  }\n\n  /**\n   * Set this layer visible or hidden based on 'visible' parameter.\n   * @param {boolean} visible - If true, make visible; otherwise, hide it.\n   */\n  setVisible (visible) {\n    const expected = visible === undefined || visible ? 'inline' : 'none';\n    const oldDisplay = this.group_.getAttribute('display');\n    if (oldDisplay !== expected) {\n      this.group_.setAttribute('display', expected);\n    }\n  }\n\n  /**\n   * Is this layer visible?\n   * @returns {boolean} True if visible.\n   */\n  isVisible () {\n    return this.group_.getAttribute('display') !== 'none';\n  }\n\n  /**\n   * Get layer opacity.\n   * @returns {number} Opacity value.\n   */\n  getOpacity () {\n    const opacity = this.group_.getAttribute('opacity');\n    if (opacity === null || opacity === undefined) {\n      return 1;\n    }\n    return parseFloat(opacity);\n  }\n\n  /**\n   * Sets the opacity of this layer. If opacity is not a value between 0.0 and 1.0,\n   * nothing happens.\n   * @param {number} opacity - A float value in the range 0.0-1.0\n   */\n  setOpacity (opacity) {\n    if (typeof opacity === 'number' && opacity >= 0.0 && opacity <= 1.0) {\n      this.group_.setAttribute('opacity', opacity);\n    }\n  }\n\n  /**\n   * Append children to this layer.\n   * @param {SVGGElement} children - The children to append to this layer.\n   */\n  appendChildren (children) {\n    for (let i = 0; i < children.length; ++i) {\n      this.group_.appendChild(children[i]);\n    }\n  }\n\n  getTitleElement () {\n    const len = this.group_.childNodes.length;\n    for (let i = 0; i < len; ++i) {\n      const child = this.group_.childNodes.item(i);\n      if (child && child.tagName === 'title') {\n        return child;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Set the name of this layer.\n   * @param {string} name - The new name.\n   * @param {svgedit.history.HistoryRecordingService} hrService - History recording service\n   * @returns {string|null} The new name if changed; otherwise, null.\n   */\n  setName (name, hrService) {\n    const previousName = this.name_;\n    name = toXml(name);\n    // now change the underlying title element contents\n    const title = this.getTitleElement();\n    if (title) {\n      $(title).empty();\n      title.textContent = name;\n      this.name_ = name;\n      if (hrService) {\n        hrService.changeElement(title, {'#text': previousName});\n      }\n      return this.name_;\n    }\n    return null;\n  }\n\n  /**\n   * Remove this layer's group from the DOM. No more functions on group can be called after this.\n   * @param {SVGGElement} children - The children to append to this layer.\n   * @returns {SVGGElement} The layer SVG group that was just removed.\n   */\n  removeGroup () {\n    const parent = this.group_.parentNode;\n    const group = parent.removeChild(this.group_);\n    this.group_ = undefined;\n    return group;\n  }\n}\n/**\n * @property {string} CLASS_NAME - class attribute assigned to all layer groups.\n */\nLayer.CLASS_NAME = 'layer';\n\n/**\n * @property {RegExp} CLASS_REGEX - Used to test presence of class Layer.CLASS_NAME\n */\nLayer.CLASS_REGEX = new RegExp('(\\\\s|^)' + Layer.CLASS_NAME + '(\\\\s|$)');\n\n/**\n * Add class Layer.CLASS_NAME to the element (usually class='layer').\n *\n * Parameters:\n * @param {SVGGElement} elem - The SVG element to update\n */\nfunction addLayerClass (elem) {\n  const classes = elem.getAttribute('class');\n  if (classes === null || classes === undefined || !classes.length) {\n    elem.setAttribute('class', Layer.CLASS_NAME);\n  } else if (!Layer.CLASS_REGEX.test(classes)) {\n    elem.setAttribute('class', classes + ' ' + Layer.CLASS_NAME);\n  }\n}\n\nexport default Layer;\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/math.js",
    "content": "/**\n * Package: svedit.math\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2010 Alexis Deveria\n * Copyright(c) 2010 Jeff Schiller\n */\n\n/**\n* @typedef AngleCoord45\n* @type {Object}\n* @property {number} x - The angle-snapped x value\n* @property {number} y - The angle-snapped y value\n* @property {number} a - The angle at which to snap\n*/\n\nimport {NS} from './svgedit.js';\nimport {getTransformList} from './svgtransformlist.js';\n\n// Constants\nconst NEAR_ZERO = 1e-14;\n\n// Throw away SVGSVGElement used for creating matrices/transforms.\nconst svg = document.createElementNS(NS.SVG, 'svg');\n\n/**\n * A (hopefully) quicker function to transform a point by a matrix\n * (this function avoids any DOM calls and just does the math)\n * @param {number} x - Float representing the x coordinate\n * @param {number} y - Float representing the y coordinate\n * @param {SVGMatrix} m - Matrix object to transform the point with\n * @returns {Object} An x, y object representing the transformed point\n*/\nexport const transformPoint = function (x, y, m) {\n  return {x: m.a * x + m.c * y + m.e, y: m.b * x + m.d * y + m.f};\n};\n\n/**\n * Helper function to check if the matrix performs no actual transform\n * (i.e. exists for identity purposes)\n * @param {SVGMatrix} m - The matrix object to check\n * @returns {boolean} Indicates whether or not the matrix is 1,0,0,1,0,0\n*/\nexport const isIdentity = function (m) {\n  return (m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1 && m.e === 0 && m.f === 0);\n};\n\n/**\n * This function tries to return a SVGMatrix that is the multiplication m1*m2.\n * We also round to zero when it's near zero\n * @param {...SVGMatrix} args - Matrix objects to multiply\n * @returns {SVGMatrix} The matrix object resulting from the calculation\n*/\nexport const matrixMultiply = function (...args) {\n  const m = args.reduceRight((prev, m1) => {\n    return m1.multiply(prev);\n  });\n\n  if (Math.abs(m.a) < NEAR_ZERO) { m.a = 0; }\n  if (Math.abs(m.b) < NEAR_ZERO) { m.b = 0; }\n  if (Math.abs(m.c) < NEAR_ZERO) { m.c = 0; }\n  if (Math.abs(m.d) < NEAR_ZERO) { m.d = 0; }\n  if (Math.abs(m.e) < NEAR_ZERO) { m.e = 0; }\n  if (Math.abs(m.f) < NEAR_ZERO) { m.f = 0; }\n\n  return m;\n};\n\n/**\n * See if the given transformlist includes a non-indentity matrix transform\n * @param {Object} [tlist] - The transformlist to check\n * @returns {boolean} Whether or not a matrix transform was found\n*/\nexport const hasMatrixTransform = function (tlist) {\n  if (!tlist) { return false; }\n  let num = tlist.numberOfItems;\n  while (num--) {\n    const xform = tlist.getItem(num);\n    if (xform.type === 1 && !isIdentity(xform.matrix)) { return true; }\n  }\n  return false;\n};\n\n/**\n * Transforms a rectangle based on the given matrix\n * @param {number} l - Float with the box's left coordinate\n * @param {number} t - Float with the box's top coordinate\n * @param {number} w - Float with the box width\n * @param {number} h - Float with the box height\n * @param {SVGMatrix} m - Matrix object to transform the box by\n * @returns {Object} An object with the following values:\n * tl - The top left coordinate (x,y object)\n * tr - The top right coordinate (x,y object)\n * bl - The bottom left coordinate (x,y object)\n * br - The bottom right coordinate (x,y object)\n * aabox - Object with the following values:\n * x - Float with the axis-aligned x coordinate\n * y - Float with the axis-aligned y coordinate\n * width - Float with the axis-aligned width coordinate\n * height - Float with the axis-aligned height coordinate\n*/\nexport const transformBox = function (l, t, w, h, m) {\n  const tl = transformPoint(l, t, m),\n    tr = transformPoint((l + w), t, m),\n    bl = transformPoint(l, (t + h), m),\n    br = transformPoint((l + w), (t + h), m),\n\n    minx = Math.min(tl.x, tr.x, bl.x, br.x),\n    maxx = Math.max(tl.x, tr.x, bl.x, br.x),\n    miny = Math.min(tl.y, tr.y, bl.y, br.y),\n    maxy = Math.max(tl.y, tr.y, bl.y, br.y);\n\n  return {\n    tl,\n    tr,\n    bl,\n    br,\n    aabox: {\n      x: minx,\n      y: miny,\n      width: (maxx - minx),\n      height: (maxy - miny)\n    }\n  };\n};\n\n/**\n * This returns a single matrix Transform for a given Transform List\n * (this is the equivalent of SVGTransformList.consolidate() but unlike\n * that method, this one does not modify the actual SVGTransformList)\n * This function is very liberal with its min, max arguments\n * @param {Object} tlist - The transformlist object\n * @param {integer} [min=0] - Optional integer indicating start transform position\n * @param {integer} [max] - Optional integer indicating end transform position;\n *   defaults to one less than the tlist's numberOfItems\n * @returns {Object} A single matrix transform object\n*/\nexport const transformListToTransform = function (tlist, min, max) {\n  if (tlist == null) {\n    // Or should tlist = null have been prevented before this?\n    return svg.createSVGTransformFromMatrix(svg.createSVGMatrix());\n  }\n  min = min || 0;\n  max = max || (tlist.numberOfItems - 1);\n  min = parseInt(min, 10);\n  max = parseInt(max, 10);\n  if (min > max) { const temp = max; max = min; min = temp; }\n  let m = svg.createSVGMatrix();\n  for (let i = min; i <= max; ++i) {\n    // if our indices are out of range, just use a harmless identity matrix\n    const mtom = (i >= 0 && i < tlist.numberOfItems\n      ? tlist.getItem(i).matrix\n      : svg.createSVGMatrix());\n    m = matrixMultiply(m, mtom);\n  }\n  return svg.createSVGTransformFromMatrix(m);\n};\n\n/**\n * Get the matrix object for a given element\n * @param {Element} elem - The DOM element to check\n * @returns {SVGMatrix} The matrix object associated with the element's transformlist\n*/\nexport const getMatrix = function (elem) {\n  const tlist = getTransformList(elem);\n  return transformListToTransform(tlist).matrix;\n};\n\n/**\n * Returns a 45 degree angle coordinate associated with the two given\n * coordinates\n * @param {number} x1 - First coordinate's x value\n * @param {number} x2 - Second coordinate's x value\n * @param {number} y1 - First coordinate's y value\n * @param {number} y2 - Second coordinate's y value\n * @returns {AngleCoord45}\n*/\nexport const snapToAngle = function (x1, y1, x2, y2) {\n  const snap = Math.PI / 4; // 45 degrees\n  const dx = x2 - x1;\n  const dy = y2 - y1;\n  const angle = Math.atan2(dy, dx);\n  const dist = Math.sqrt(dx * dx + dy * dy);\n  const snapangle = Math.round(angle / snap) * snap;\n\n  return {\n    x: x1 + dist * Math.cos(snapangle),\n    y: y1 + dist * Math.sin(snapangle),\n    a: snapangle\n  };\n};\n\n/**\n * Check if two rectangles (BBoxes objects) intersect each other\n * @param {SVGRect} r1 - The first BBox-like object\n * @param {SVGRect} r2 - The second BBox-like object\n * @returns {boolean} True if rectangles intersect\n */\nexport const rectsIntersect = function (r1, r2) {\n  return r2.x < (r1.x + r1.width) &&\n    (r2.x + r2.width) > r1.x &&\n    r2.y < (r1.y + r1.height) &&\n    (r2.y + r2.height) > r1.y;\n};\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/path.js",
    "content": "/* globals jQuery */\n/**\n * Package: svgedit.path\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2011 Alexis Deveria\n * Copyright(c) 2011 Jeff Schiller\n */\n\nimport './pathseg.js';\nimport {NS} from './svgedit.js';\nimport {getTransformList} from './svgtransformlist.js';\nimport {shortFloat} from './units.js';\nimport {ChangeElementCommand, BatchCommand} from './history.js';\nimport {\n  transformPoint, getMatrix, snapToAngle, rectsIntersect,\n  transformListToTransform\n} from './math.js';\nimport {\n  assignAttributes, getElem, getRotationAngle, getBBox,\n  getRefElem, findDefs, snapToGrid,\n  getBBox as utilsGetBBox\n} from './svgutils.js';\nimport {\n  supportsPathInsertItemBefore, supportsPathReplaceItem, isWebkit\n} from './browser.js';\n\nconst $ = jQuery;\n\nconst segData = {\n  2: ['x', 'y'],\n  4: ['x', 'y'],\n  6: ['x', 'y', 'x1', 'y1', 'x2', 'y2'],\n  8: ['x', 'y', 'x1', 'y1'],\n  10: ['x', 'y', 'r1', 'r2', 'angle', 'largeArcFlag', 'sweepFlag'],\n  12: ['x'],\n  14: ['y'],\n  16: ['x', 'y', 'x2', 'y2'],\n  18: ['x', 'y']\n};\n\nconst uiStrings = {};\nexport const setUiStrings = function (strs) {\n  Object.assign(uiStrings, strs.ui);\n};\n\nlet pathFuncs = [];\n\nlet linkControlPts = true;\n\n// Stores references to paths via IDs.\n// TODO: Make this cross-document happy.\nlet pathData = {};\n\nexport const setLinkControlPoints = function (lcp) {\n  linkControlPts = lcp;\n};\n\nexport let path = null;\n\nlet editorContext_ = null;\n\nexport const init = function (editorContext) {\n  editorContext_ = editorContext;\n\n  pathFuncs = [0, 'ClosePath'];\n  const pathFuncsStrs = ['Moveto', 'Lineto', 'CurvetoCubic', 'CurvetoQuadratic', 'Arc',\n    'LinetoHorizontal', 'LinetoVertical', 'CurvetoCubicSmooth', 'CurvetoQuadraticSmooth'];\n  $.each(pathFuncsStrs, function (i, s) {\n    pathFuncs.push(s + 'Abs');\n    pathFuncs.push(s + 'Rel');\n  });\n};\n\nexport const insertItemBefore = function (elem, newseg, index) {\n  // Support insertItemBefore on paths for FF2\n  const list = elem.pathSegList;\n\n  if (supportsPathInsertItemBefore()) {\n    list.insertItemBefore(newseg, index);\n    return;\n  }\n  const len = list.numberOfItems;\n  const arr = [];\n  for (let i = 0; i < len; i++) {\n    const curSeg = list.getItem(i);\n    arr.push(curSeg);\n  }\n  list.clear();\n  for (let i = 0; i < len; i++) {\n    if (i === index) { // index + 1\n      list.appendItem(newseg);\n    }\n    list.appendItem(arr[i]);\n  }\n};\n\n// TODO: See if this should just live in replacePathSeg\nexport const ptObjToArr = function (type, segItem) {\n  const arr = segData[type], len = arr.length;\n  const out = [];\n  for (let i = 0; i < len; i++) {\n    out[i] = segItem[arr[i]];\n  }\n  return out;\n};\n\nexport const getGripPt = function (seg, altPt) {\n  const {path} = seg;\n  let out = {\n    x: altPt ? altPt.x : seg.item.x,\n    y: altPt ? altPt.y : seg.item.y\n  };\n\n  if (path.matrix) {\n    const pt = transformPoint(out.x, out.y, path.matrix);\n    out = pt;\n  }\n\n  const currentZoom = editorContext_.getCurrentZoom();\n  out.x *= currentZoom;\n  out.y *= currentZoom;\n\n  return out;\n};\n\nexport const getPointFromGrip = function (pt, path) {\n  const out = {\n    x: pt.x,\n    y: pt.y\n  };\n\n  if (path.matrix) {\n    pt = transformPoint(out.x, out.y, path.imatrix);\n    out.x = pt.x;\n    out.y = pt.y;\n  }\n\n  const currentZoom = editorContext_.getCurrentZoom();\n  out.x /= currentZoom;\n  out.y /= currentZoom;\n\n  return out;\n};\n\n/**\n* Requires prior call to `setUiStrings` if `xlink:title`\n*    to be set on the grip\n*/\nexport const addPointGrip = function (index, x, y) {\n  // create the container of all the point grips\n  const pointGripContainer = getGripContainer();\n\n  let pointGrip = getElem('pathpointgrip_' + index);\n  // create it\n  if (!pointGrip) {\n    pointGrip = document.createElementNS(NS.SVG, 'circle');\n    const atts = {\n      id: 'pathpointgrip_' + index,\n      display: 'none',\n      r: 4,\n      fill: '#0FF',\n      stroke: '#00F',\n      'stroke-width': 2,\n      cursor: 'move',\n      style: 'pointer-events:all'\n    };\n    if ('pathNodeTooltip' in uiStrings) { // May be empty if running path.js without svg-editor\n      atts['xlink:title'] = uiStrings.pathNodeTooltip;\n    }\n    assignAttributes(pointGrip, atts);\n    pointGrip = pointGripContainer.appendChild(pointGrip);\n\n    const grip = $('#pathpointgrip_' + index);\n    grip.dblclick(function () {\n      if (path) {\n        path.setSegType();\n      }\n    });\n  }\n  if (x && y) {\n    // set up the point grip element and display it\n    assignAttributes(pointGrip, {\n      cx: x,\n      cy: y,\n      display: 'inline'\n    });\n  }\n  return pointGrip;\n};\n\nexport const getGripContainer = function () {\n  let c = getElem('pathpointgrip_container');\n  if (!c) {\n    const parent = getElem('selectorParentGroup');\n    c = parent.appendChild(document.createElementNS(NS.SVG, 'g'));\n    c.id = 'pathpointgrip_container';\n  }\n  return c;\n};\n\n/**\n* Requires prior call to `setUiStrings` if `xlink:title`\n*    to be set on the grip\n*/\nexport const addCtrlGrip = function (id) {\n  let pointGrip = getElem('ctrlpointgrip_' + id);\n  if (pointGrip) { return pointGrip; }\n\n  pointGrip = document.createElementNS(NS.SVG, 'circle');\n  const atts = {\n    id: 'ctrlpointgrip_' + id,\n    display: 'none',\n    r: 4,\n    fill: '#0FF',\n    stroke: '#55F',\n    'stroke-width': 1,\n    cursor: 'move',\n    style: 'pointer-events:all'\n  };\n  if ('pathCtrlPtTooltip' in uiStrings) { // May be empty if running path.js without svg-editor\n    atts['xlink:title'] = uiStrings.pathCtrlPtTooltip;\n  }\n  assignAttributes(pointGrip, atts);\n  getGripContainer().appendChild(pointGrip);\n  return pointGrip;\n};\n\nexport const getCtrlLine = function (id) {\n  let ctrlLine = getElem('ctrlLine_' + id);\n  if (ctrlLine) { return ctrlLine; }\n\n  ctrlLine = document.createElementNS(NS.SVG, 'line');\n  assignAttributes(ctrlLine, {\n    id: 'ctrlLine_' + id,\n    stroke: '#555',\n    'stroke-width': 1,\n    style: 'pointer-events:none'\n  });\n  getGripContainer().appendChild(ctrlLine);\n  return ctrlLine;\n};\n\nexport const getPointGrip = function (seg, update) {\n  const {index} = seg;\n  const pointGrip = addPointGrip(index);\n\n  if (update) {\n    const pt = getGripPt(seg);\n    assignAttributes(pointGrip, {\n      cx: pt.x,\n      cy: pt.y,\n      display: 'inline'\n    });\n  }\n\n  return pointGrip;\n};\n\nexport const getControlPoints = function (seg) {\n  const {item, index} = seg;\n  if (!('x1' in item) || !('x2' in item)) { return null; }\n  const cpt = {};\n  /* const pointGripContainer = */ getGripContainer();\n\n  // Note that this is intentionally not seg.prev.item\n  const prev = path.segs[index - 1].item;\n\n  const segItems = [prev, item];\n\n  for (let i = 1; i < 3; i++) {\n    const id = index + 'c' + i;\n\n    const ctrlLine = cpt['c' + i + '_line'] = getCtrlLine(id);\n\n    const pt = getGripPt(seg, {x: item['x' + i], y: item['y' + i]});\n    const gpt = getGripPt(seg, {x: segItems[i - 1].x, y: segItems[i - 1].y});\n\n    assignAttributes(ctrlLine, {\n      x1: pt.x,\n      y1: pt.y,\n      x2: gpt.x,\n      y2: gpt.y,\n      display: 'inline'\n    });\n\n    cpt['c' + i + '_line'] = ctrlLine;\n\n    // create it\n    const pointGrip = cpt['c' + i] = addCtrlGrip(id);\n\n    assignAttributes(pointGrip, {\n      cx: pt.x,\n      cy: pt.y,\n      display: 'inline'\n    });\n    cpt['c' + i] = pointGrip;\n  }\n  return cpt;\n};\n\n// This replaces the segment at the given index. Type is given as number.\nexport const replacePathSeg = function (type, index, pts, elem) {\n  const pth = elem || path.elem;\n\n  const func = 'createSVGPathSeg' + pathFuncs[type];\n  const seg = pth[func].apply(pth, pts);\n\n  if (supportsPathReplaceItem()) {\n    pth.pathSegList.replaceItem(seg, index);\n  } else {\n    const segList = pth.pathSegList;\n    const len = segList.numberOfItems;\n    const arr = [];\n    for (let i = 0; i < len; i++) {\n      const curSeg = segList.getItem(i);\n      arr.push(curSeg);\n    }\n    segList.clear();\n    for (let i = 0; i < len; i++) {\n      if (i === index) {\n        segList.appendItem(seg);\n      } else {\n        segList.appendItem(arr[i]);\n      }\n    }\n  }\n};\n\nexport const getSegSelector = function (seg, update) {\n  const {index} = seg;\n  let segLine = getElem('segline_' + index);\n  if (!segLine) {\n    const pointGripContainer = getGripContainer();\n    // create segline\n    segLine = document.createElementNS(NS.SVG, 'path');\n    assignAttributes(segLine, {\n      id: 'segline_' + index,\n      display: 'none',\n      fill: 'none',\n      stroke: '#0FF',\n      'stroke-width': 2,\n      style: 'pointer-events:none',\n      d: 'M0,0 0,0'\n    });\n    pointGripContainer.appendChild(segLine);\n  }\n\n  if (update) {\n    const {prev} = seg;\n    if (!prev) {\n      segLine.setAttribute('display', 'none');\n      return segLine;\n    }\n\n    const pt = getGripPt(prev);\n    // Set start point\n    replacePathSeg(2, 0, [pt.x, pt.y], segLine);\n\n    const pts = ptObjToArr(seg.type, seg.item, true);\n    for (let i = 0; i < pts.length; i += 2) {\n      const pt = getGripPt(seg, {x: pts[i], y: pts[i + 1]});\n      pts[i] = pt.x;\n      pts[i + 1] = pt.y;\n    }\n\n    replacePathSeg(seg.type, 1, pts, segLine);\n  }\n  return segLine;\n};\n\n/**\n* Takes three points and creates a smoother line based on them\n* @param ct1 - Object with x and y values (first control point)\n* @param ct2 - Object with x and y values (second control point)\n* @param pt - Object with x and y values (third point)\n* @returns Array of two \"smoothed\" point objects\n*/\nexport const smoothControlPoints = function (ct1, ct2, pt) {\n  // each point must not be the origin\n  const x1 = ct1.x - pt.x,\n    y1 = ct1.y - pt.y,\n    x2 = ct2.x - pt.x,\n    y2 = ct2.y - pt.y;\n\n  if ((x1 !== 0 || y1 !== 0) && (x2 !== 0 || y2 !== 0)) {\n    const\n      r1 = Math.sqrt(x1 * x1 + y1 * y1),\n      r2 = Math.sqrt(x2 * x2 + y2 * y2),\n      nct1 = editorContext_.getSVGRoot().createSVGPoint(),\n      nct2 = editorContext_.getSVGRoot().createSVGPoint();\n    let anglea = Math.atan2(y1, x1),\n      angleb = Math.atan2(y2, x2);\n    if (anglea < 0) { anglea += 2 * Math.PI; }\n    if (angleb < 0) { angleb += 2 * Math.PI; }\n\n    const angleBetween = Math.abs(anglea - angleb),\n      angleDiff = Math.abs(Math.PI - angleBetween) / 2;\n\n    let newAnglea, newAngleb;\n    if (anglea - angleb > 0) {\n      newAnglea = angleBetween < Math.PI ? (anglea + angleDiff) : (anglea - angleDiff);\n      newAngleb = angleBetween < Math.PI ? (angleb - angleDiff) : (angleb + angleDiff);\n    } else {\n      newAnglea = angleBetween < Math.PI ? (anglea - angleDiff) : (anglea + angleDiff);\n      newAngleb = angleBetween < Math.PI ? (angleb + angleDiff) : (angleb - angleDiff);\n    }\n\n    // rotate the points\n    nct1.x = r1 * Math.cos(newAnglea) + pt.x;\n    nct1.y = r1 * Math.sin(newAnglea) + pt.y;\n    nct2.x = r2 * Math.cos(newAngleb) + pt.x;\n    nct2.y = r2 * Math.sin(newAngleb) + pt.y;\n\n    return [nct1, nct2];\n  }\n  return undefined;\n};\n\nexport class Segment {\n  constructor (index, item) {\n    this.selected = false;\n    this.index = index;\n    this.item = item;\n    this.type = item.pathSegType;\n\n    this.ctrlpts = [];\n    this.ptgrip = null;\n    this.segsel = null;\n  }\n\n  showCtrlPts (y) {\n    for (const i in this.ctrlpts) {\n      if (this.ctrlpts.hasOwnProperty(i)) {\n        this.ctrlpts[i].setAttribute('display', y ? 'inline' : 'none');\n      }\n    }\n  }\n\n  selectCtrls (y) {\n    $('#ctrlpointgrip_' + this.index + 'c1, #ctrlpointgrip_' + this.index + 'c2')\n      .attr('fill', y ? '#0FF' : '#EEE');\n  }\n\n  show (y) {\n    if (this.ptgrip) {\n      this.ptgrip.setAttribute('display', y ? 'inline' : 'none');\n      this.segsel.setAttribute('display', y ? 'inline' : 'none');\n      // Show/hide all control points if available\n      this.showCtrlPts(y);\n    }\n  }\n\n  select (y) {\n    if (this.ptgrip) {\n      this.ptgrip.setAttribute('stroke', y ? '#0FF' : '#00F');\n      this.segsel.setAttribute('display', y ? 'inline' : 'none');\n      if (this.ctrlpts) {\n        this.selectCtrls(y);\n      }\n      this.selected = y;\n    }\n  }\n\n  addGrip () {\n    this.ptgrip = getPointGrip(this, true);\n    this.ctrlpts = getControlPoints(this, true);\n    this.segsel = getSegSelector(this, true);\n  }\n\n  update (full) {\n    if (this.ptgrip) {\n      const pt = getGripPt(this);\n      assignAttributes(this.ptgrip, {\n        cx: pt.x,\n        cy: pt.y\n      });\n\n      getSegSelector(this, true);\n\n      if (this.ctrlpts) {\n        if (full) {\n          this.item = path.elem.pathSegList.getItem(this.index);\n          this.type = this.item.pathSegType;\n        }\n        getControlPoints(this);\n      }\n      // this.segsel.setAttribute('display', y ? 'inline' : 'none');\n    }\n  }\n\n  move (dx, dy) {\n    const {item} = this;\n\n    const curPts = this.ctrlpts\n      ? [item.x += dx, item.y += dy,\n        item.x1, item.y1, item.x2 += dx, item.y2 += dy\n      ]\n      : [item.x += dx, item.y += dy];\n\n    replacePathSeg(this.type, this.index, curPts);\n\n    if (this.next && this.next.ctrlpts) {\n      const next = this.next.item;\n      const nextPts = [next.x, next.y,\n        next.x1 += dx, next.y1 += dy, next.x2, next.y2];\n      replacePathSeg(this.next.type, this.next.index, nextPts);\n    }\n\n    if (this.mate) {\n      // The last point of a closed subpath has a 'mate',\n      // which is the 'M' segment of the subpath\n      const {item} = this.mate;\n      const pts = [item.x += dx, item.y += dy];\n      replacePathSeg(this.mate.type, this.mate.index, pts);\n      // Has no grip, so does not need 'updating'?\n    }\n\n    this.update(true);\n    if (this.next) { this.next.update(true); }\n  }\n\n  setLinked (num) {\n    let seg, anum, pt;\n    if (num === 2) {\n      anum = 1;\n      seg = this.next;\n      if (!seg) { return; }\n      pt = this.item;\n    } else {\n      anum = 2;\n      seg = this.prev;\n      if (!seg) { return; }\n      pt = seg.item;\n    }\n\n    const {item} = seg;\n    item['x' + anum] = pt.x + (pt.x - this.item['x' + num]);\n    item['y' + anum] = pt.y + (pt.y - this.item['y' + num]);\n\n    const pts = [item.x, item.y,\n      item.x1, item.y1,\n      item.x2, item.y2];\n\n    replacePathSeg(seg.type, seg.index, pts);\n    seg.update(true);\n  }\n\n  moveCtrl (num, dx, dy) {\n    const {item} = this;\n    item['x' + num] += dx;\n    item['y' + num] += dy;\n\n    const pts = [item.x, item.y,\n      item.x1, item.y1, item.x2, item.y2];\n\n    replacePathSeg(this.type, this.index, pts);\n    this.update(true);\n  }\n\n  setType (newType, pts) {\n    replacePathSeg(newType, this.index, pts);\n    this.type = newType;\n    this.item = path.elem.pathSegList.getItem(this.index);\n    this.showCtrlPts(newType === 6);\n    this.ctrlpts = getControlPoints(this);\n    this.update(true);\n  }\n}\n\nexport class Path {\n  constructor (elem) {\n    if (!elem || elem.tagName !== 'path') {\n      throw new Error('svgedit.path.Path constructed without a <path> element');\n    }\n\n    this.elem = elem;\n    this.segs = [];\n    this.selected_pts = [];\n    path = this;\n\n    this.init();\n  }\n\n  // Reset path data\n  init () {\n    // Hide all grips, etc\n\n    // fixed, needed to work on all found elements, not just first\n    $(getGripContainer()).find('*').each(function () {\n      $(this).attr('display', 'none');\n    });\n\n    const segList = this.elem.pathSegList;\n    const len = segList.numberOfItems;\n    this.segs = [];\n    this.selected_pts = [];\n    this.first_seg = null;\n\n    // Set up segs array\n    for (let i = 0; i < len; i++) {\n      const item = segList.getItem(i);\n      const segment = new Segment(i, item);\n      segment.path = this;\n      this.segs.push(segment);\n    }\n\n    const {segs} = this;\n\n    let startI = null;\n    for (let i = 0; i < len; i++) {\n      const seg = segs[i];\n      const nextSeg = (i + 1) >= len ? null : segs[i + 1];\n      const prevSeg = (i - 1) < 0 ? null : segs[i - 1];\n      if (seg.type === 2) {\n        if (prevSeg && prevSeg.type !== 1) {\n          // New sub-path, last one is open,\n          // so add a grip to last sub-path's first point\n          const startSeg = segs[startI];\n          startSeg.next = segs[startI + 1];\n          startSeg.next.prev = startSeg;\n          startSeg.addGrip();\n        }\n        // Remember that this is a starter seg\n        startI = i;\n      } else if (nextSeg && nextSeg.type === 1) {\n        // This is the last real segment of a closed sub-path\n        // Next is first seg after \"M\"\n        seg.next = segs[startI + 1];\n\n        // First seg after \"M\"'s prev is this\n        seg.next.prev = seg;\n        seg.mate = segs[startI];\n        seg.addGrip();\n        if (this.first_seg == null) {\n          this.first_seg = seg;\n        }\n      } else if (!nextSeg) {\n        if (seg.type !== 1) {\n          // Last seg, doesn't close so add a grip\n          // to last sub-path's first point\n          const startSeg = segs[startI];\n          startSeg.next = segs[startI + 1];\n          startSeg.next.prev = startSeg;\n          startSeg.addGrip();\n          seg.addGrip();\n\n          if (!this.first_seg) {\n            // Open path, so set first as real first and add grip\n            this.first_seg = segs[startI];\n          }\n        }\n      } else if (seg.type !== 1) {\n        // Regular segment, so add grip and its \"next\"\n        seg.addGrip();\n\n        // Don't set its \"next\" if it's an \"M\"\n        if (nextSeg && nextSeg.type !== 2) {\n          seg.next = nextSeg;\n          seg.next.prev = seg;\n        }\n      }\n    }\n    return this;\n  }\n\n  eachSeg (fn) {\n    const len = this.segs.length;\n    for (let i = 0; i < len; i++) {\n      const ret = fn.call(this.segs[i], i);\n      if (ret === false) { break; }\n    }\n  }\n\n  addSeg (index) {\n    // Adds a new segment\n    const seg = this.segs[index];\n    if (!seg.prev) { return; }\n\n    const {prev} = seg;\n    let newseg, newX, newY;\n    switch (seg.item.pathSegType) {\n    case 4: {\n      newX = (seg.item.x + prev.item.x) / 2;\n      newY = (seg.item.y + prev.item.y) / 2;\n      newseg = this.elem.createSVGPathSegLinetoAbs(newX, newY);\n      break;\n    } case 6: { // make it a curved segment to preserve the shape (WRS)\n      // https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm#Geometric_interpretation\n      const p0x = (prev.item.x + seg.item.x1) / 2;\n      const p1x = (seg.item.x1 + seg.item.x2) / 2;\n      const p2x = (seg.item.x2 + seg.item.x) / 2;\n      const p01x = (p0x + p1x) / 2;\n      const p12x = (p1x + p2x) / 2;\n      newX = (p01x + p12x) / 2;\n      const p0y = (prev.item.y + seg.item.y1) / 2;\n      const p1y = (seg.item.y1 + seg.item.y2) / 2;\n      const p2y = (seg.item.y2 + seg.item.y) / 2;\n      const p01y = (p0y + p1y) / 2;\n      const p12y = (p1y + p2y) / 2;\n      newY = (p01y + p12y) / 2;\n      newseg = this.elem.createSVGPathSegCurvetoCubicAbs(newX, newY, p0x, p0y, p01x, p01y);\n      const pts = [seg.item.x, seg.item.y, p12x, p12y, p2x, p2y];\n      replacePathSeg(seg.type, index, pts);\n      break;\n    }\n    }\n\n    insertItemBefore(this.elem, newseg, index);\n  }\n\n  deleteSeg (index) {\n    const seg = this.segs[index];\n    const list = this.elem.pathSegList;\n\n    seg.show(false);\n    const {next} = seg;\n    if (seg.mate) {\n      // Make the next point be the \"M\" point\n      const pt = [next.item.x, next.item.y];\n      replacePathSeg(2, next.index, pt);\n\n      // Reposition last node\n      replacePathSeg(4, seg.index, pt);\n\n      list.removeItem(seg.mate.index);\n    } else if (!seg.prev) {\n      // First node of open path, make next point the M\n      // const {item} = seg;\n      const pt = [next.item.x, next.item.y];\n      replacePathSeg(2, seg.next.index, pt);\n      list.removeItem(index);\n    } else {\n      list.removeItem(index);\n    }\n  }\n\n  subpathIsClosed (index) {\n    let closed = false;\n    // Check if subpath is already open\n    path.eachSeg(function (i) {\n      if (i <= index) { return true; }\n      if (this.type === 2) {\n        // Found M first, so open\n        return false;\n      }\n      if (this.type === 1) {\n        // Found Z first, so closed\n        closed = true;\n        return false;\n      }\n    });\n\n    return closed;\n  }\n\n  removePtFromSelection (index) {\n    const pos = this.selected_pts.indexOf(index);\n    if (pos === -1) {\n      return;\n    }\n    this.segs[index].select(false);\n    this.selected_pts.splice(pos, 1);\n  }\n\n  clearSelection () {\n    this.eachSeg(function () {\n      // 'this' is the segment here\n      this.select(false);\n    });\n    this.selected_pts = [];\n  }\n\n  storeD () {\n    this.last_d = this.elem.getAttribute('d');\n  }\n\n  show (y) {\n    // Shows this path's segment grips\n    this.eachSeg(function () {\n      // 'this' is the segment here\n      this.show(y);\n    });\n    if (y) {\n      this.selectPt(this.first_seg.index);\n    }\n    return this;\n  }\n\n  // Move selected points\n  movePts (dx, dy) {\n    let i = this.selected_pts.length;\n    while (i--) {\n      const seg = this.segs[this.selected_pts[i]];\n      seg.move(dx, dy);\n    }\n  }\n\n  moveCtrl (dx, dy) {\n    const seg = this.segs[this.selected_pts[0]];\n    seg.moveCtrl(this.dragctrl, dx, dy);\n    if (linkControlPts) {\n      seg.setLinked(this.dragctrl);\n    }\n  }\n\n  setSegType (newType) {\n    this.storeD();\n    let i = this.selected_pts.length;\n    let text;\n    while (i--) {\n      const selPt = this.selected_pts[i];\n\n      // Selected seg\n      const cur = this.segs[selPt];\n      const {prev} = cur;\n      if (!prev) { continue; }\n\n      if (!newType) { // double-click, so just toggle\n        text = 'Toggle Path Segment Type';\n\n        // Toggle segment to curve/straight line\n        const oldType = cur.type;\n\n        newType = (oldType === 6) ? 4 : 6;\n      }\n\n      newType = Number(newType);\n\n      const curX = cur.item.x;\n      const curY = cur.item.y;\n      const prevX = prev.item.x;\n      const prevY = prev.item.y;\n      let points;\n      switch (newType) {\n      case 6: {\n        if (cur.olditem) {\n          const old = cur.olditem;\n          points = [curX, curY, old.x1, old.y1, old.x2, old.y2];\n        } else {\n          const diffX = curX - prevX;\n          const diffY = curY - prevY;\n          // get control points from straight line segment\n          /*\n          const ct1x = (prevX + (diffY/2));\n          const ct1y = (prevY - (diffX/2));\n          const ct2x = (curX + (diffY/2));\n          const ct2y = (curY - (diffX/2));\n          */\n          // create control points on the line to preserve the shape (WRS)\n          const ct1x = (prevX + (diffX / 3));\n          const ct1y = (prevY + (diffY / 3));\n          const ct2x = (curX - (diffX / 3));\n          const ct2y = (curY - (diffY / 3));\n          points = [curX, curY, ct1x, ct1y, ct2x, ct2y];\n        }\n        break;\n      } case 4: {\n        points = [curX, curY];\n\n        // Store original prevve segment nums\n        cur.olditem = cur.item;\n        break;\n      }\n      }\n\n      cur.setType(newType, points);\n    }\n    path.endChanges(text);\n  }\n\n  selectPt (pt, ctrlNum) {\n    this.clearSelection();\n    if (pt == null) {\n      this.eachSeg(function (i) {\n        // 'this' is the segment here.\n        if (this.prev) {\n          pt = i;\n        }\n      });\n    }\n    this.addPtsToSelection(pt);\n    if (ctrlNum) {\n      this.dragctrl = ctrlNum;\n\n      if (linkControlPts) {\n        this.segs[pt].setLinked(ctrlNum);\n      }\n    }\n  }\n\n  // Update position of all points\n  update () {\n    const {elem} = this;\n    if (getRotationAngle(elem)) {\n      this.matrix = getMatrix(elem);\n      this.imatrix = this.matrix.inverse();\n    } else {\n      this.matrix = null;\n      this.imatrix = null;\n    }\n\n    this.eachSeg(function (i) {\n      this.item = elem.pathSegList.getItem(i);\n      this.update();\n    });\n\n    return this;\n  }\n\n  endChanges (text) {\n    if (isWebkit()) { editorContext_.resetD(this.elem); }\n    const cmd = new ChangeElementCommand(this.elem, {d: this.last_d}, text);\n    editorContext_.endChanges({cmd, elem: this.elem});\n  }\n\n  addPtsToSelection (indexes) {\n    if (!Array.isArray(indexes)) { indexes = [indexes]; }\n    for (let i = 0; i < indexes.length; i++) {\n      const index = indexes[i];\n      const seg = this.segs[index];\n      if (seg.ptgrip) {\n        if (!this.selected_pts.includes(index) && index >= 0) {\n          this.selected_pts.push(index);\n        }\n      }\n    }\n    this.selected_pts.sort();\n    let i = this.selected_pts.length;\n    const grips = [];\n    grips.length = i;\n    // Loop through points to be selected and highlight each\n    while (i--) {\n      const pt = this.selected_pts[i];\n      const seg = this.segs[pt];\n      seg.select(true);\n      grips[i] = seg.ptgrip;\n    }\n\n    const closedSubpath = this.subpathIsClosed(this.selected_pts[0]);\n    editorContext_.addPtsToSelection({grips, closedSubpath});\n  }\n}\n\nexport const getPath_ = function (elem) {\n  let p = pathData[elem.id];\n  if (!p) {\n    p = pathData[elem.id] = new Path(elem);\n  }\n  return p;\n};\n\nexport const removePath_ = function (id) {\n  if (id in pathData) { delete pathData[id]; }\n};\n\nlet newcx, newcy, oldcx, oldcy, angle;\n\nconst getRotVals = function (x, y) {\n  let dx = x - oldcx;\n  let dy = y - oldcy;\n\n  // rotate the point around the old center\n  let r = Math.sqrt(dx * dx + dy * dy);\n  let theta = Math.atan2(dy, dx) + angle;\n  dx = r * Math.cos(theta) + oldcx;\n  dy = r * Math.sin(theta) + oldcy;\n\n  // dx,dy should now hold the actual coordinates of each\n  // point after being rotated\n\n  // now we want to rotate them around the new center in the reverse direction\n  dx -= newcx;\n  dy -= newcy;\n\n  r = Math.sqrt(dx * dx + dy * dy);\n  theta = Math.atan2(dy, dx) - angle;\n\n  return {x: r * Math.cos(theta) + newcx,\n    y: r * Math.sin(theta) + newcy};\n};\n\n// If the path was rotated, we must now pay the piper:\n// Every path point must be rotated into the rotated coordinate system of\n// its old center, then determine the new center, then rotate it back\n// This is because we want the path to remember its rotation\n\n// TODO: This is still using ye olde transform methods, can probably\n// be optimized or even taken care of by `recalculateDimensions`\nexport const recalcRotatedPath = function () {\n  const currentPath = path.elem;\n  angle = getRotationAngle(currentPath, true);\n  if (!angle) { return; }\n  // selectedBBoxes[0] = path.oldbbox;\n  const oldbox = path.oldbbox; // selectedBBoxes[0],\n  oldcx = oldbox.x + oldbox.width / 2;\n  oldcy = oldbox.y + oldbox.height / 2;\n  let box = getBBox(currentPath);\n  newcx = box.x + box.width / 2;\n  newcy = box.y + box.height / 2;\n\n  // un-rotate the new center to the proper position\n  const dx = newcx - oldcx,\n    dy = newcy - oldcy,\n    r = Math.sqrt(dx * dx + dy * dy),\n    theta = Math.atan2(dy, dx) + angle;\n\n  newcx = r * Math.cos(theta) + oldcx;\n  newcy = r * Math.sin(theta) + oldcy;\n\n  const list = currentPath.pathSegList;\n\n  let i = list.numberOfItems;\n  while (i) {\n    i -= 1;\n    const seg = list.getItem(i),\n      type = seg.pathSegType;\n    if (type === 1) { continue; }\n\n    const rvals = getRotVals(seg.x, seg.y),\n      points = [rvals.x, rvals.y];\n    if (seg.x1 != null && seg.x2 != null) {\n      const cVals1 = getRotVals(seg.x1, seg.y1);\n      const cVals2 = getRotVals(seg.x2, seg.y2);\n      points.splice(points.length, 0, cVals1.x, cVals1.y, cVals2.x, cVals2.y);\n    }\n    replacePathSeg(type, i, points);\n  } // loop for each point\n\n  box = getBBox(currentPath);\n  // selectedBBoxes[0].x = box.x; selectedBBoxes[0].y = box.y;\n  // selectedBBoxes[0].width = box.width; selectedBBoxes[0].height = box.height;\n\n  // now we must set the new transform to be rotated around the new center\n  const Rnc = editorContext_.getSVGRoot().createSVGTransform(),\n    tlist = getTransformList(currentPath);\n  Rnc.setRotate((angle * 180.0 / Math.PI), newcx, newcy);\n  tlist.replaceItem(Rnc, 0);\n};\n\n// ====================================\n// Public API starts here\n\nexport const clearData = function () {\n  pathData = {};\n};\n\n// Making public for mocking\nexport const reorientGrads = function (elem, m) {\n  const bb = utilsGetBBox(elem);\n  for (let i = 0; i < 2; i++) {\n    const type = i === 0 ? 'fill' : 'stroke';\n    const attrVal = elem.getAttribute(type);\n    if (attrVal && attrVal.startsWith('url(')) {\n      const grad = getRefElem(attrVal);\n      if (grad.tagName === 'linearGradient') {\n        let x1 = grad.getAttribute('x1') || 0;\n        let y1 = grad.getAttribute('y1') || 0;\n        let x2 = grad.getAttribute('x2') || 1;\n        let y2 = grad.getAttribute('y2') || 0;\n\n        // Convert to USOU points\n        x1 = (bb.width * x1) + bb.x;\n        y1 = (bb.height * y1) + bb.y;\n        x2 = (bb.width * x2) + bb.x;\n        y2 = (bb.height * y2) + bb.y;\n\n        // Transform those points\n        const pt1 = transformPoint(x1, y1, m);\n        const pt2 = transformPoint(x2, y2, m);\n\n        // Convert back to BB points\n        const gCoords = {};\n\n        gCoords.x1 = (pt1.x - bb.x) / bb.width;\n        gCoords.y1 = (pt1.y - bb.y) / bb.height;\n        gCoords.x2 = (pt2.x - bb.x) / bb.width;\n        gCoords.y2 = (pt2.y - bb.y) / bb.height;\n\n        const newgrad = grad.cloneNode(true);\n        $(newgrad).attr(gCoords);\n\n        newgrad.id = editorContext_.getNextId();\n        findDefs().appendChild(newgrad);\n        elem.setAttribute(type, 'url(#' + newgrad.id + ')');\n      }\n    }\n  }\n};\n\n// this is how we map paths to our preferred relative segment types\nconst pathMap = [0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a',\n  'H', 'h', 'V', 'v', 'S', 's', 'T', 't'];\n\n/**\n * TODO: move to pathActions.js\n * Convert a path to one with only absolute or relative values\n * @param {Object} path - the path to convert\n * @param {boolean} toRel - true of convert to relative\n * @returns {string}\n */\nexport const convertPath = function (path, toRel) {\n  const segList = path.pathSegList;\n  const len = segList.numberOfItems;\n  let curx = 0, cury = 0;\n  let d = '';\n  let lastM = null;\n\n  for (let i = 0; i < len; ++i) {\n    const seg = segList.getItem(i);\n    // if these properties are not in the segment, set them to zero\n    let x = seg.x || 0,\n      y = seg.y || 0,\n      x1 = seg.x1 || 0,\n      y1 = seg.y1 || 0,\n      x2 = seg.x2 || 0,\n      y2 = seg.y2 || 0;\n\n    const type = seg.pathSegType;\n    let letter = pathMap[type]['to' + (toRel ? 'Lower' : 'Upper') + 'Case']();\n\n    switch (type) {\n    case 1: // z,Z closepath (Z/z)\n      d += 'z';\n      if (lastM && !toRel) {\n        curx = lastM[0];\n        cury = lastM[1];\n      }\n      break;\n    case 12: // absolute horizontal line (H)\n      x -= curx;\n      // Fallthrough\n    case 13: // relative horizontal line (h)\n      if (toRel) {\n        curx += x;\n        letter = 'l';\n      } else {\n        x += curx;\n        curx = x;\n        letter = 'L';\n      }\n      // Convert to \"line\" for easier editing\n      d += pathDSegment(letter, [[x, cury]]);\n      break;\n    case 14: // absolute vertical line (V)\n      y -= cury;\n      // Fallthrough\n    case 15: // relative vertical line (v)\n      if (toRel) {\n        cury += y;\n        letter = 'l';\n      } else {\n        y += cury;\n        cury = y;\n        letter = 'L';\n      }\n      // Convert to \"line\" for easier editing\n      d += pathDSegment(letter, [[curx, y]]);\n      break;\n    case 2: // absolute move (M)\n    case 4: // absolute line (L)\n    case 18: // absolute smooth quad (T)\n      x -= curx;\n      y -= cury;\n      // Fallthrough\n    case 5: // relative line (l)\n    case 3: // relative move (m)\n    case 19: // relative smooth quad (t)\n      if (toRel) {\n        curx += x;\n        cury += y;\n      } else {\n        x += curx;\n        y += cury;\n        curx = x;\n        cury = y;\n      }\n      if (type === 2 || type === 3) { lastM = [curx, cury]; }\n\n      d += pathDSegment(letter, [[x, y]]);\n      break;\n    case 6: // absolute cubic (C)\n      x -= curx; x1 -= curx; x2 -= curx;\n      y -= cury; y1 -= cury; y2 -= cury;\n      // Fallthrough\n    case 7: // relative cubic (c)\n      if (toRel) {\n        curx += x;\n        cury += y;\n      } else {\n        x += curx; x1 += curx; x2 += curx;\n        y += cury; y1 += cury; y2 += cury;\n        curx = x;\n        cury = y;\n      }\n      d += pathDSegment(letter, [[x1, y1], [x2, y2], [x, y]]);\n      break;\n    case 8: // absolute quad (Q)\n      x -= curx; x1 -= curx;\n      y -= cury; y1 -= cury;\n      // Fallthrough\n    case 9: // relative quad (q)\n      if (toRel) {\n        curx += x;\n        cury += y;\n      } else {\n        x += curx; x1 += curx;\n        y += cury; y1 += cury;\n        curx = x;\n        cury = y;\n      }\n      d += pathDSegment(letter, [[x1, y1], [x, y]]);\n      break;\n    case 10: // absolute elliptical arc (A)\n      x -= curx;\n      y -= cury;\n      // Fallthrough\n    case 11: // relative elliptical arc (a)\n      if (toRel) {\n        curx += x;\n        cury += y;\n      } else {\n        x += curx;\n        y += cury;\n        curx = x;\n        cury = y;\n      }\n      d += pathDSegment(letter, [[seg.r1, seg.r2]], [\n        seg.angle,\n        (seg.largeArcFlag ? 1 : 0),\n        (seg.sweepFlag ? 1 : 0)\n      ], [x, y]);\n      break;\n    case 16: // absolute smooth cubic (S)\n      x -= curx; x2 -= curx;\n      y -= cury; y2 -= cury;\n      // Fallthrough\n    case 17: // relative smooth cubic (s)\n      if (toRel) {\n        curx += x;\n        cury += y;\n      } else {\n        x += curx; x2 += curx;\n        y += cury; y2 += cury;\n        curx = x;\n        cury = y;\n      }\n      d += pathDSegment(letter, [[x2, y2], [x, y]]);\n      break;\n    } // switch on path segment type\n  } // for each segment\n  return d;\n};\n\n/**\n * TODO: refactor callers in convertPath to use getPathDFromSegments instead of this function.\n * Legacy code refactored from svgcanvas.pathActions.convertPath\n * @param letter - path segment command\n * @param {Array.<Array.<number>>} points - x,y points.\n * @param {Array.<Array.<number>>=} morePoints - x,y points\n * @param {Array.<number>=}lastPoint - x,y point\n * @returns {string}\n */\nfunction pathDSegment (letter, points, morePoints, lastPoint) {\n  $.each(points, function (i, pnt) {\n    points[i] = shortFloat(pnt);\n  });\n  let segment = letter + points.join(' ');\n  if (morePoints) {\n    segment += ' ' + morePoints.join(' ');\n  }\n  if (lastPoint) {\n    segment += ' ' + shortFloat(lastPoint);\n  }\n  return segment;\n}\n\n/**\n* Group: Path edit functions\n* Functions relating to editing path elements\n*/\nexport const pathActions = (function () {\n  let subpath = false;\n  let newPoint, firstCtrl;\n\n  let currentPath = null;\n  let hasMoved = false;\n  // No `editorContext_` yet but should be ok as is `null` by default\n  // editorContext_.setDrawnPath(null);\n\n  // This function converts a polyline (created by the fh_path tool) into\n  // a path element and coverts every three line segments into a single bezier\n  // curve in an attempt to smooth out the free-hand\n  const smoothPolylineIntoPath = function (element) {\n    let i;\n    const {points} = element;\n    const N = points.numberOfItems;\n    if (N >= 4) {\n      // loop through every 3 points and convert to a cubic bezier curve segment\n      //\n      // NOTE: this is cheating, it means that every 3 points has the potential to\n      // be a corner instead of treating each point in an equal manner. In general,\n      // this technique does not look that good.\n      //\n      // I am open to better ideas!\n      //\n      // Reading:\n      // - http://www.efg2.com/Lab/Graphics/Jean-YvesQueinecBezierCurves.htm\n      // - https://www.codeproject.com/KB/graphics/BezierSpline.aspx?msg=2956963\n      // - https://www.ian-ko.com/ET_GeoWizards/UserGuide/smooth.htm\n      // - https://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-der.html\n      let curpos = points.getItem(0), prevCtlPt = null;\n      let d = [];\n      d.push(['M', curpos.x, ',', curpos.y, ' C'].join(''));\n      for (i = 1; i <= (N - 4); i += 3) {\n        let ct1 = points.getItem(i);\n        const ct2 = points.getItem(i + 1);\n        const end = points.getItem(i + 2);\n\n        // if the previous segment had a control point, we want to smooth out\n        // the control points on both sides\n        if (prevCtlPt) {\n          const newpts = smoothControlPoints(prevCtlPt, ct1, curpos);\n          if (newpts && newpts.length === 2) {\n            const prevArr = d[d.length - 1].split(',');\n            prevArr[2] = newpts[0].x;\n            prevArr[3] = newpts[0].y;\n            d[d.length - 1] = prevArr.join(',');\n            ct1 = newpts[1];\n          }\n        }\n\n        d.push([ct1.x, ct1.y, ct2.x, ct2.y, end.x, end.y].join(','));\n\n        curpos = end;\n        prevCtlPt = ct2;\n      }\n      // handle remaining line segments\n      d.push('L');\n      while (i < N) {\n        const pt = points.getItem(i);\n        d.push([pt.x, pt.y].join(','));\n        i++;\n      }\n      d = d.join(' ');\n\n      // create new path element\n      element = editorContext_.addSvgElementFromJson({\n        element: 'path',\n        curStyles: true,\n        attr: {\n          id: editorContext_.getId(),\n          d,\n          fill: 'none'\n        }\n      });\n      // No need to call \"changed\", as this is already done under mouseUp\n    }\n    return element;\n  };\n\n  return {\n    mouseDown (evt, mouseTarget, startX, startY) {\n      let id;\n      if (editorContext_.getCurrentMode() === 'path') {\n        let mouseX = startX; // Was this meant to work with the other `mouseX`? (was defined globally so adding `let` to at least avoid a global)\n        let mouseY = startY; // Was this meant to work with the other `mouseY`? (was defined globally so adding `let` to at least avoid a global)\n\n        const currentZoom = editorContext_.getCurrentZoom();\n        let x = mouseX / currentZoom,\n          y = mouseY / currentZoom,\n          stretchy = getElem('path_stretch_line');\n        newPoint = [x, y];\n\n        if (editorContext_.getGridSnapping()) {\n          x = snapToGrid(x);\n          y = snapToGrid(y);\n          mouseX = snapToGrid(mouseX);\n          mouseY = snapToGrid(mouseY);\n        }\n\n        if (!stretchy) {\n          stretchy = document.createElementNS(NS.SVG, 'path');\n          assignAttributes(stretchy, {\n            id: 'path_stretch_line',\n            stroke: '#22C',\n            'stroke-width': '0.5',\n            fill: 'none'\n          });\n          stretchy = getElem('selectorParentGroup').appendChild(stretchy);\n        }\n        stretchy.setAttribute('display', 'inline');\n\n        let keep = null;\n        let index;\n        // if pts array is empty, create path element with M at current point\n        let drawnPath = editorContext_.getDrawnPath();\n        if (!drawnPath) {\n          const dAttr = 'M' + x + ',' + y + ' '; // Was this meant to work with the other `dAttr`? (was defined globally so adding `var` to at least avoid a global)\n          drawnPath = editorContext_.setDrawnPath(editorContext_.addSvgElementFromJson({\n            element: 'path',\n            curStyles: true,\n            attr: {\n              d: dAttr,\n              id: editorContext_.getNextId(),\n              opacity: editorContext_.getOpacity() / 2\n            }\n          }));\n          // set stretchy line to first point\n          stretchy.setAttribute('d', ['M', mouseX, mouseY, mouseX, mouseY].join(' '));\n          index = subpath ? path.segs.length : 0;\n          addPointGrip(index, mouseX, mouseY);\n        } else {\n          // determine if we clicked on an existing point\n          const seglist = drawnPath.pathSegList;\n          let i = seglist.numberOfItems;\n          const FUZZ = 6 / currentZoom;\n          let clickOnPoint = false;\n          while (i) {\n            i--;\n            const item = seglist.getItem(i);\n            const px = item.x, py = item.y;\n            // found a matching point\n            if (x >= (px - FUZZ) && x <= (px + FUZZ) &&\n              y >= (py - FUZZ) && y <= (py + FUZZ)\n            ) {\n              clickOnPoint = true;\n              break;\n            }\n          }\n\n          // get path element that we are in the process of creating\n          id = editorContext_.getId();\n\n          // Remove previous path object if previously created\n          removePath_(id);\n\n          const newpath = getElem(id);\n          let newseg;\n          let sSeg;\n          const len = seglist.numberOfItems;\n          // if we clicked on an existing point, then we are done this path, commit it\n          // (i, i+1) are the x,y that were clicked on\n          if (clickOnPoint) {\n            // if clicked on any other point but the first OR\n            // the first point was clicked on and there are less than 3 points\n            // then leave the path open\n            // otherwise, close the path\n            if (i <= 1 && len >= 2) {\n              // Create end segment\n              const absX = seglist.getItem(0).x;\n              const absY = seglist.getItem(0).y;\n\n              sSeg = stretchy.pathSegList.getItem(1);\n              if (sSeg.pathSegType === 4) {\n                newseg = drawnPath.createSVGPathSegLinetoAbs(absX, absY);\n              } else {\n                newseg = drawnPath.createSVGPathSegCurvetoCubicAbs(\n                  absX,\n                  absY,\n                  sSeg.x1 / currentZoom,\n                  sSeg.y1 / currentZoom,\n                  absX,\n                  absY\n                );\n              }\n\n              const endseg = drawnPath.createSVGPathSegClosePath();\n              seglist.appendItem(newseg);\n              seglist.appendItem(endseg);\n            } else if (len < 3) {\n              keep = false;\n              return keep;\n            }\n            $(stretchy).remove();\n\n            // This will signal to commit the path\n            // const element = newpath; // Other event handlers define own `element`, so this was probably not meant to interact with them or one which shares state (as there were none); I therefore adding a missing `var` to avoid a global\n            drawnPath = editorContext_.setDrawnPath(null);\n            editorContext_.setStarted(false);\n\n            if (subpath) {\n              if (path.matrix) {\n                editorContext_.remapElement(newpath, {}, path.matrix.inverse());\n              }\n\n              const newD = newpath.getAttribute('d');\n              const origD = $(path.elem).attr('d');\n              $(path.elem).attr('d', origD + newD);\n              $(newpath).remove();\n              if (path.matrix) {\n                recalcRotatedPath();\n              }\n              init();\n              pathActions.toEditMode(path.elem);\n              path.selectPt();\n              return false;\n            }\n          // else, create a new point, update path element\n          } else {\n            // Checks if current target or parents are #svgcontent\n            if (!$.contains(\n              editorContext_.getContainer(),\n              editorContext_.getMouseTarget(evt)\n            )) {\n              // Clicked outside canvas, so don't make point\n              console.log('Clicked outside canvas');\n              return false;\n            }\n\n            const num = drawnPath.pathSegList.numberOfItems;\n            const last = drawnPath.pathSegList.getItem(num - 1);\n            const lastx = last.x, lasty = last.y;\n\n            if (evt.shiftKey) {\n              const xya = snapToAngle(lastx, lasty, x, y);\n              ({x, y} = xya);\n            }\n\n            // Use the segment defined by stretchy\n            sSeg = stretchy.pathSegList.getItem(1);\n            if (sSeg.pathSegType === 4) {\n              newseg = drawnPath.createSVGPathSegLinetoAbs(\n                editorContext_.round(x),\n                editorContext_.round(y)\n              );\n            } else {\n              newseg = drawnPath.createSVGPathSegCurvetoCubicAbs(\n                editorContext_.round(x),\n                editorContext_.round(y),\n                sSeg.x1 / currentZoom,\n                sSeg.y1 / currentZoom,\n                sSeg.x2 / currentZoom,\n                sSeg.y2 / currentZoom\n              );\n            }\n\n            drawnPath.pathSegList.appendItem(newseg);\n\n            x *= currentZoom;\n            y *= currentZoom;\n\n            // set stretchy line to latest point\n            stretchy.setAttribute('d', ['M', x, y, x, y].join(' '));\n            index = num;\n            if (subpath) { index += path.segs.length; }\n            addPointGrip(index, x, y);\n          }\n          // keep = true;\n        }\n\n        return;\n      }\n\n      // TODO: Make sure currentPath isn't null at this point\n      if (!path) { return; }\n\n      path.storeD();\n\n      ({id} = evt.target);\n      let curPt;\n      if (id.substr(0, 14) === 'pathpointgrip_') {\n        // Select this point\n        curPt = path.cur_pt = parseInt(id.substr(14), 10);\n        path.dragging = [startX, startY];\n        const seg = path.segs[curPt];\n\n        // only clear selection if shift is not pressed (otherwise, add\n        // node to selection)\n        if (!evt.shiftKey) {\n          if (path.selected_pts.length <= 1 || !seg.selected) {\n            path.clearSelection();\n          }\n          path.addPtsToSelection(curPt);\n        } else if (seg.selected) {\n          path.removePtFromSelection(curPt);\n        } else {\n          path.addPtsToSelection(curPt);\n        }\n      } else if (id.startsWith('ctrlpointgrip_')) {\n        path.dragging = [startX, startY];\n\n        const parts = id.split('_')[1].split('c');\n        curPt = Number(parts[0]);\n        const ctrlNum = Number(parts[1]);\n        path.selectPt(curPt, ctrlNum);\n      }\n\n      // Start selection box\n      if (!path.dragging) {\n        let rubberBox = editorContext_.getRubberBox();\n        if (rubberBox == null) {\n          rubberBox = editorContext_.setRubberBox(\n            editorContext_.selectorManager.getRubberBandBox()\n          );\n        }\n        const currentZoom = editorContext_.getCurrentZoom();\n        assignAttributes(rubberBox, {\n          x: startX * currentZoom,\n          y: startY * currentZoom,\n          width: 0,\n          height: 0,\n          display: 'inline'\n        }, 100);\n      }\n    },\n    mouseMove (mouseX, mouseY) {\n      const currentZoom = editorContext_.getCurrentZoom();\n      hasMoved = true;\n      const drawnPath = editorContext_.getDrawnPath();\n      if (editorContext_.getCurrentMode() === 'path') {\n        if (!drawnPath) { return; }\n        const seglist = drawnPath.pathSegList;\n        const index = seglist.numberOfItems - 1;\n\n        if (newPoint) {\n          // First point\n          // if (!index) { return; }\n\n          // Set control points\n          const pointGrip1 = addCtrlGrip('1c1');\n          const pointGrip2 = addCtrlGrip('0c2');\n\n          // dragging pointGrip1\n          pointGrip1.setAttribute('cx', mouseX);\n          pointGrip1.setAttribute('cy', mouseY);\n          pointGrip1.setAttribute('display', 'inline');\n\n          const ptX = newPoint[0];\n          const ptY = newPoint[1];\n\n          // set curve\n          // const seg = seglist.getItem(index);\n          const curX = mouseX / currentZoom;\n          const curY = mouseY / currentZoom;\n          const altX = (ptX + (ptX - curX));\n          const altY = (ptY + (ptY - curY));\n\n          pointGrip2.setAttribute('cx', altX * currentZoom);\n          pointGrip2.setAttribute('cy', altY * currentZoom);\n          pointGrip2.setAttribute('display', 'inline');\n\n          const ctrlLine = getCtrlLine(1);\n          assignAttributes(ctrlLine, {\n            x1: mouseX,\n            y1: mouseY,\n            x2: altX * currentZoom,\n            y2: altY * currentZoom,\n            display: 'inline'\n          });\n\n          if (index === 0) {\n            firstCtrl = [mouseX, mouseY];\n          } else {\n            const last = seglist.getItem(index - 1);\n            let lastX = last.x;\n            let lastY = last.y;\n\n            if (last.pathSegType === 6) {\n              lastX += (lastX - last.x2);\n              lastY += (lastY - last.y2);\n            } else if (firstCtrl) {\n              lastX = firstCtrl[0] / currentZoom;\n              lastY = firstCtrl[1] / currentZoom;\n            }\n            replacePathSeg(6, index, [ptX, ptY, lastX, lastY, altX, altY], drawnPath);\n          }\n        } else {\n          const stretchy = getElem('path_stretch_line');\n          if (stretchy) {\n            const prev = seglist.getItem(index);\n            if (prev.pathSegType === 6) {\n              const prevX = prev.x + (prev.x - prev.x2);\n              const prevY = prev.y + (prev.y - prev.y2);\n              replacePathSeg(6, 1, [mouseX, mouseY, prevX * currentZoom, prevY * currentZoom, mouseX, mouseY], stretchy);\n            } else if (firstCtrl) {\n              replacePathSeg(6, 1, [mouseX, mouseY, firstCtrl[0], firstCtrl[1], mouseX, mouseY], stretchy);\n            } else {\n              replacePathSeg(4, 1, [mouseX, mouseY], stretchy);\n            }\n          }\n        }\n        return;\n      }\n      // if we are dragging a point, let's move it\n      if (path.dragging) {\n        const pt = getPointFromGrip({\n          x: path.dragging[0],\n          y: path.dragging[1]\n        }, path);\n        const mpt = getPointFromGrip({\n          x: mouseX,\n          y: mouseY\n        }, path);\n        const diffX = mpt.x - pt.x;\n        const diffY = mpt.y - pt.y;\n        path.dragging = [mouseX, mouseY];\n\n        if (path.dragctrl) {\n          path.moveCtrl(diffX, diffY);\n        } else {\n          path.movePts(diffX, diffY);\n        }\n      } else {\n        path.selected_pts = [];\n        path.eachSeg(function (i) {\n          const seg = this;\n          if (!seg.next && !seg.prev) { return; }\n\n          // const {item} = seg;\n          const rubberBox = editorContext_.getRubberBox();\n          const rbb = rubberBox.getBBox();\n\n          const pt = getGripPt(seg);\n          const ptBb = {\n            x: pt.x,\n            y: pt.y,\n            width: 0,\n            height: 0\n          };\n\n          const sel = rectsIntersect(rbb, ptBb);\n\n          this.select(sel);\n          // Note that addPtsToSelection is not being run\n          if (sel) { path.selected_pts.push(seg.index); }\n        });\n      }\n    },\n    mouseUp (evt, element, mouseX, mouseY) {\n      const drawnPath = editorContext_.getDrawnPath();\n      // Create mode\n      if (editorContext_.getCurrentMode() === 'path') {\n        newPoint = null;\n        if (!drawnPath) {\n          element = getElem(editorContext_.getId());\n          editorContext_.setStarted(false);\n          firstCtrl = null;\n        }\n\n        return {\n          keep: true,\n          element\n        };\n      }\n\n      // Edit mode\n      const rubberBox = editorContext_.getRubberBox();\n      if (path.dragging) {\n        const lastPt = path.cur_pt;\n\n        path.dragging = false;\n        path.dragctrl = false;\n        path.update();\n\n        if (hasMoved) {\n          path.endChanges('Move path point(s)');\n        }\n\n        if (!evt.shiftKey && !hasMoved) {\n          path.selectPt(lastPt);\n        }\n      } else if (rubberBox && rubberBox.getAttribute('display') !== 'none') {\n        // Done with multi-node-select\n        rubberBox.setAttribute('display', 'none');\n\n        if (rubberBox.getAttribute('width') <= 2 && rubberBox.getAttribute('height') <= 2) {\n          pathActions.toSelectMode(evt.target);\n        }\n\n      // else, move back to select mode\n      } else {\n        pathActions.toSelectMode(evt.target);\n      }\n      hasMoved = false;\n    },\n    toEditMode (element) {\n      path = getPath_(element);\n      editorContext_.setCurrentMode('pathedit');\n      editorContext_.clearSelection();\n      path.show(true).update();\n      path.oldbbox = utilsGetBBox(path.elem);\n      subpath = false;\n    },\n    toSelectMode (elem) {\n      const selPath = (elem === path.elem);\n      editorContext_.setCurrentMode('select');\n      path.show(false);\n      currentPath = false;\n      editorContext_.clearSelection();\n\n      if (path.matrix) {\n        // Rotated, so may need to re-calculate the center\n        recalcRotatedPath();\n      }\n\n      if (selPath) {\n        editorContext_.call('selected', [elem]);\n        editorContext_.addToSelection([elem], true);\n      }\n    },\n    addSubPath (on) {\n      if (on) {\n        // Internally we go into \"path\" mode, but in the UI it will\n        // still appear as if in \"pathedit\" mode.\n        editorContext_.setCurrentMode('path');\n        subpath = true;\n      } else {\n        pathActions.clear(true);\n        pathActions.toEditMode(path.elem);\n      }\n    },\n    select (target) {\n      if (currentPath === target) {\n        pathActions.toEditMode(target);\n        editorContext_.setCurrentMode('pathedit');\n      // going into pathedit mode\n      } else {\n        currentPath = target;\n      }\n    },\n    reorient () {\n      const elem = editorContext_.getSelectedElements()[0];\n      if (!elem) { return; }\n      const angle = getRotationAngle(elem);\n      if (angle === 0) { return; }\n\n      const batchCmd = new BatchCommand('Reorient path');\n      const changes = {\n        d: elem.getAttribute('d'),\n        transform: elem.getAttribute('transform')\n      };\n      batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));\n      editorContext_.clearSelection();\n      this.resetOrientation(elem);\n\n      editorContext_.addCommandToHistory(batchCmd);\n\n      // Set matrix to null\n      getPath_(elem).show(false).matrix = null;\n\n      this.clear();\n\n      editorContext_.addToSelection([elem], true);\n      editorContext_.call('changed', editorContext_.getSelectedElements());\n    },\n\n    clear (remove) {\n      const drawnPath = editorContext_.getDrawnPath();\n      currentPath = null;\n      if (drawnPath) {\n        const elem = getElem(editorContext_.getId());\n        $(getElem('path_stretch_line')).remove();\n        $(elem).remove();\n        $(getElem('pathpointgrip_container')).find('*').attr('display', 'none');\n        firstCtrl = null;\n        editorContext_.setDrawnPath(null);\n        editorContext_.setStarted(false);\n      } else if (editorContext_.getCurrentMode() === 'pathedit') {\n        this.toSelectMode();\n      }\n      if (path) { path.init().show(false); }\n    },\n    resetOrientation (pth) {\n      if (pth == null || pth.nodeName !== 'path') { return false; }\n      const tlist = getTransformList(pth);\n      const m = transformListToTransform(tlist).matrix;\n      tlist.clear();\n      pth.removeAttribute('transform');\n      const segList = pth.pathSegList;\n\n      // Opera/win/non-EN throws an error here.\n      // TODO: Find out why!\n      // Presumed fixed in Opera 10.5, so commented out for now\n\n      // try {\n      const len = segList.numberOfItems;\n      // } catch(err) {\n      //   const fixed_d = pathActions.convertPath(pth);\n      //   pth.setAttribute('d', fixed_d);\n      //   segList = pth.pathSegList;\n      //   const len = segList.numberOfItems;\n      // }\n      // let lastX, lastY;\n      for (let i = 0; i < len; ++i) {\n        const seg = segList.getItem(i);\n        const type = seg.pathSegType;\n        if (type === 1) { continue; }\n        const pts = [];\n        $.each(['', 1, 2], function (j, n) {\n          const x = seg['x' + n], y = seg['y' + n];\n          if (x !== undefined && y !== undefined) {\n            const pt = transformPoint(x, y, m);\n            pts.splice(pts.length, 0, pt.x, pt.y);\n          }\n        });\n        replacePathSeg(type, i, pts, pth);\n      }\n\n      reorientGrads(pth, m);\n    },\n    zoomChange () {\n      if (editorContext_.getCurrentMode() === 'pathedit') {\n        path.update();\n      }\n    },\n    getNodePoint () {\n      const selPt = path.selected_pts.length ? path.selected_pts[0] : 1;\n\n      const seg = path.segs[selPt];\n      return {\n        x: seg.item.x,\n        y: seg.item.y,\n        type: seg.type\n      };\n    },\n    linkControlPoints (linkPoints) {\n      setLinkControlPoints(linkPoints);\n    },\n    clonePathNode () {\n      path.storeD();\n\n      const selPts = path.selected_pts;\n      // const {segs} = path;\n\n      let i = selPts.length;\n      const nums = [];\n\n      while (i--) {\n        const pt = selPts[i];\n        path.addSeg(pt);\n\n        nums.push(pt + i);\n        nums.push(pt + i + 1);\n      }\n      path.init().addPtsToSelection(nums);\n\n      path.endChanges('Clone path node(s)');\n    },\n    opencloseSubPath () {\n      const selPts = path.selected_pts;\n      // Only allow one selected node for now\n      if (selPts.length !== 1) { return; }\n\n      const {elem} = path;\n      const list = elem.pathSegList;\n\n      // const len = list.numberOfItems;\n\n      const index = selPts[0];\n\n      let openPt = null;\n      let startItem = null;\n\n      // Check if subpath is already open\n      path.eachSeg(function (i) {\n        if (this.type === 2 && i <= index) {\n          startItem = this.item;\n        }\n        if (i <= index) { return true; }\n        if (this.type === 2) {\n          // Found M first, so open\n          openPt = i;\n          return false;\n        }\n        if (this.type === 1) {\n          // Found Z first, so closed\n          openPt = false;\n          return false;\n        }\n      });\n\n      if (openPt == null) {\n        // Single path, so close last seg\n        openPt = path.segs.length - 1;\n      }\n\n      if (openPt !== false) {\n        // Close this path\n\n        // Create a line going to the previous \"M\"\n        const newseg = elem.createSVGPathSegLinetoAbs(startItem.x, startItem.y);\n\n        const closer = elem.createSVGPathSegClosePath();\n        if (openPt === path.segs.length - 1) {\n          list.appendItem(newseg);\n          list.appendItem(closer);\n        } else {\n          insertItemBefore(elem, closer, openPt);\n          insertItemBefore(elem, newseg, openPt);\n        }\n\n        path.init().selectPt(openPt + 1);\n        return;\n      }\n\n      // M 1,1 L 2,2 L 3,3 L 1,1 z // open at 2,2\n      // M 2,2 L 3,3 L 1,1\n\n      // M 1,1 L 2,2 L 1,1 z M 4,4 L 5,5 L6,6 L 5,5 z\n      // M 1,1 L 2,2 L 1,1 z [M 4,4] L 5,5 L(M)6,6 L 5,5 z\n\n      const seg = path.segs[index];\n\n      if (seg.mate) {\n        list.removeItem(index); // Removes last \"L\"\n        list.removeItem(index); // Removes the \"Z\"\n        path.init().selectPt(index - 1);\n        return;\n      }\n\n      let lastM, zSeg;\n\n      // Find this sub-path's closing point and remove\n      for (let i = 0; i < list.numberOfItems; i++) {\n        const item = list.getItem(i);\n\n        if (item.pathSegType === 2) {\n          // Find the preceding M\n          lastM = i;\n        } else if (i === index) {\n          // Remove it\n          list.removeItem(lastM);\n          // index--;\n        } else if (item.pathSegType === 1 && index < i) {\n          // Remove the closing seg of this subpath\n          zSeg = i - 1;\n          list.removeItem(i);\n          break;\n        }\n      }\n\n      let num = (index - lastM) - 1;\n\n      while (num--) {\n        insertItemBefore(elem, list.getItem(lastM), zSeg);\n      }\n\n      const pt = list.getItem(lastM);\n\n      // Make this point the new \"M\"\n      replacePathSeg(2, lastM, [pt.x, pt.y]);\n\n      // i = index; // i is local here, so has no effect; what was the intent for this?\n\n      path.init().selectPt(0);\n    },\n    deletePathNode () {\n      if (!pathActions.canDeleteNodes) { return; }\n      path.storeD();\n\n      const selPts = path.selected_pts;\n\n      let i = selPts.length;\n      while (i--) {\n        const pt = selPts[i];\n        path.deleteSeg(pt);\n      }\n\n      // Cleanup\n      const cleanup = function () {\n        const segList = path.elem.pathSegList;\n        let len = segList.numberOfItems;\n\n        const remItems = function (pos, count) {\n          while (count--) {\n            segList.removeItem(pos);\n          }\n        };\n\n        if (len <= 1) { return true; }\n\n        while (len--) {\n          const item = segList.getItem(len);\n          if (item.pathSegType === 1) {\n            const prev = segList.getItem(len - 1);\n            const nprev = segList.getItem(len - 2);\n            if (prev.pathSegType === 2) {\n              remItems(len - 1, 2);\n              cleanup();\n              break;\n            } else if (nprev.pathSegType === 2) {\n              remItems(len - 2, 3);\n              cleanup();\n              break;\n            }\n          } else if (item.pathSegType === 2) {\n            if (len > 0) {\n              const prevType = segList.getItem(len - 1).pathSegType;\n              // Path has M M\n              if (prevType === 2) {\n                remItems(len - 1, 1);\n                cleanup();\n                break;\n              // Entire path ends with Z M\n              } else if (prevType === 1 && segList.numberOfItems - 1 === len) {\n                remItems(len, 1);\n                cleanup();\n                break;\n              }\n            }\n          }\n        }\n        return false;\n      };\n\n      cleanup();\n\n      // Completely delete a path with 1 or 0 segments\n      if (path.elem.pathSegList.numberOfItems <= 1) {\n        pathActions.toSelectMode(path.elem);\n        editorContext_.canvas.deleteSelectedElements();\n        return;\n      }\n\n      path.init();\n      path.clearSelection();\n\n      // TODO: Find right way to select point now\n      // path.selectPt(selPt);\n      if (window.opera) { // Opera repaints incorrectly\n        const cp = $(path.elem);\n        cp.attr('d', cp.attr('d'));\n      }\n      path.endChanges('Delete path node(s)');\n    },\n    smoothPolylineIntoPath,\n    setSegType (v) {\n      path.setSegType(v);\n    },\n    moveNode (attr, newValue) {\n      const selPts = path.selected_pts;\n      if (!selPts.length) { return; }\n\n      path.storeD();\n\n      // Get first selected point\n      const seg = path.segs[selPts[0]];\n      const diff = {x: 0, y: 0};\n      diff[attr] = newValue - seg.item[attr];\n\n      seg.move(diff.x, diff.y);\n      path.endChanges('Move path point');\n    },\n    fixEnd (elem) {\n      // Adds an extra segment if the last seg before a Z doesn't end\n      // at its M point\n      // M0,0 L0,100 L100,100 z\n      const segList = elem.pathSegList;\n      const len = segList.numberOfItems;\n      let lastM;\n      for (let i = 0; i < len; ++i) {\n        const item = segList.getItem(i);\n        if (item.pathSegType === 2) {\n          lastM = item;\n        }\n\n        if (item.pathSegType === 1) {\n          const prev = segList.getItem(i - 1);\n          if (prev.x !== lastM.x || prev.y !== lastM.y) {\n            // Add an L segment here\n            const newseg = elem.createSVGPathSegLinetoAbs(lastM.x, lastM.y);\n            insertItemBefore(elem, newseg, i);\n            // Can this be done better?\n            pathActions.fixEnd(elem);\n            break;\n          }\n        }\n      }\n      if (isWebkit()) { editorContext_.resetD(elem); }\n    },\n    // Convert a path to one with only absolute or relative values\n    convertPath\n  };\n})();\n// end pathActions\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/pathseg.js",
    "content": "// SVGPathSeg API polyfill\n// https://github.com/progers/pathseg\n//\n// This is a drop-in replacement for the SVGPathSeg and SVGPathSegList APIs that were removed from\n// SVG2 (https://lists.w3.org/Archives/Public/www-svg/2015Jun/0044.html), including the latest spec\n// changes which were implemented in Firefox 43 and Chrome 46.\n\n(() => {\nif (!('SVGPathSeg' in window)) {\n  // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg\n  class SVGPathSeg {\n    constructor (type, typeAsLetter, owningPathSegList) {\n      this.pathSegType = type;\n      this.pathSegTypeAsLetter = typeAsLetter;\n      this._owningPathSegList = owningPathSegList;\n    }\n    // Notify owning PathSegList on any changes so they can be synchronized back to the path element.\n    _segmentChanged () {\n      if (this._owningPathSegList) {\n        this._owningPathSegList.segmentChanged(this);\n      }\n    }\n  }\n  SVGPathSeg.prototype.classname = 'SVGPathSeg';\n\n  SVGPathSeg.PATHSEG_UNKNOWN = 0;\n  SVGPathSeg.PATHSEG_CLOSEPATH = 1;\n  SVGPathSeg.PATHSEG_MOVETO_ABS = 2;\n  SVGPathSeg.PATHSEG_MOVETO_REL = 3;\n  SVGPathSeg.PATHSEG_LINETO_ABS = 4;\n  SVGPathSeg.PATHSEG_LINETO_REL = 5;\n  SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6;\n  SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7;\n  SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8;\n  SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9;\n  SVGPathSeg.PATHSEG_ARC_ABS = 10;\n  SVGPathSeg.PATHSEG_ARC_REL = 11;\n  SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12;\n  SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13;\n  SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14;\n  SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15;\n  SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16;\n  SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17;\n  SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18;\n  SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19;\n\n  class SVGPathSegClosePath extends SVGPathSeg {\n    constructor (owningPathSegList) {\n      super(SVGPathSeg.PATHSEG_CLOSEPATH, 'z', owningPathSegList);\n    }\n    toString () { return '[object SVGPathSegClosePath]'; }\n    _asPathString () { return this.pathSegTypeAsLetter; }\n    clone () { return new SVGPathSegClosePath(undefined); }\n  }\n\n  class SVGPathSegMovetoAbs extends SVGPathSeg {\n    constructor (owningPathSegList, x, y) {\n      super(SVGPathSeg.PATHSEG_MOVETO_ABS, 'M', owningPathSegList);\n      this._x = x;\n      this._y = y;\n    }\n    toString () { return '[object SVGPathSegMovetoAbs]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegMovetoAbs(undefined, this._x, this._y); }\n  }\n  Object.defineProperties(SVGPathSegMovetoAbs.prototype, {\n    x: {\n      get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true\n    },\n    y: {\n      get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true\n    }\n  });\n\n  class SVGPathSegMovetoRel extends SVGPathSeg {\n    constructor (owningPathSegList, x, y) {\n      super(SVGPathSeg.PATHSEG_MOVETO_REL, 'm', owningPathSegList);\n      this._x = x;\n      this._y = y;\n    }\n    toString () { return '[object SVGPathSegMovetoRel]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegMovetoRel(undefined, this._x, this._y); }\n  }\n  Object.defineProperties(SVGPathSegMovetoRel.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegLinetoAbs extends SVGPathSeg {\n    constructor (owningPathSegList, x, y) {\n      super(SVGPathSeg.PATHSEG_LINETO_ABS, 'L', owningPathSegList);\n      this._x = x;\n      this._y = y;\n    }\n    toString () { return '[object SVGPathSegLinetoAbs]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegLinetoAbs(undefined, this._x, this._y); }\n  }\n  Object.defineProperties(SVGPathSegLinetoAbs.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegLinetoRel extends SVGPathSeg {\n    constructor (owningPathSegList, x, y) {\n      super(SVGPathSeg.PATHSEG_LINETO_REL, 'l', owningPathSegList);\n      this._x = x;\n      this._y = y;\n    }\n    toString () { return '[object SVGPathSegLinetoRel]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegLinetoRel(undefined, this._x, this._y); }\n  }\n  Object.defineProperties(SVGPathSegLinetoRel.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegCurvetoCubicAbs extends SVGPathSeg {\n    constructor (owningPathSegList, x, y, x1, y1, x2, y2) {\n      super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, 'C', owningPathSegList);\n      this._x = x;\n      this._y = y;\n      this._x1 = x1;\n      this._y1 = y1;\n      this._x2 = x2;\n      this._y2 = y2;\n    }\n    toString () { return '[object SVGPathSegCurvetoCubicAbs]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegCurvetoCubicAbs(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); }\n  }\n  Object.defineProperties(SVGPathSegCurvetoCubicAbs.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true },\n    x1: { get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true },\n    y1: { get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true },\n    x2: { get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true },\n    y2: { get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegCurvetoCubicRel extends SVGPathSeg {\n    constructor (owningPathSegList, x, y, x1, y1, x2, y2) {\n      super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, 'c', owningPathSegList);\n      this._x = x;\n      this._y = y;\n      this._x1 = x1;\n      this._y1 = y1;\n      this._x2 = x2;\n      this._y2 = y2;\n    }\n    toString () { return '[object SVGPathSegCurvetoCubicRel]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegCurvetoCubicRel(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); }\n  }\n  Object.defineProperties(SVGPathSegCurvetoCubicRel.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true },\n    x1: { get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true },\n    y1: { get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true },\n    x2: { get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true },\n    y2: { get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg {\n    constructor (owningPathSegList, x, y, x1, y1) {\n      super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, 'Q', owningPathSegList);\n      this._x = x;\n      this._y = y;\n      this._x1 = x1;\n      this._y1 = y1;\n    }\n    toString () { return '[object SVGPathSegCurvetoQuadraticAbs]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegCurvetoQuadraticAbs(undefined, this._x, this._y, this._x1, this._y1); }\n  }\n  Object.defineProperties(SVGPathSegCurvetoQuadraticAbs.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true },\n    x1: { get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true },\n    y1: { get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegCurvetoQuadraticRel extends SVGPathSeg {\n    constructor (owningPathSegList, x, y, x1, y1) {\n      super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, 'q', owningPathSegList);\n      this._x = x;\n      this._y = y;\n      this._x1 = x1;\n      this._y1 = y1;\n    }\n    toString () { return '[object SVGPathSegCurvetoQuadraticRel]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegCurvetoQuadraticRel(undefined, this._x, this._y, this._x1, this._y1); }\n  }\n  Object.defineProperties(SVGPathSegCurvetoQuadraticRel.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true },\n    x1: { get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true },\n    y1: { get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegArcAbs extends SVGPathSeg {\n    constructor (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {\n      super(SVGPathSeg.PATHSEG_ARC_ABS, 'A', owningPathSegList);\n      this._x = x;\n      this._y = y;\n      this._r1 = r1;\n      this._r2 = r2;\n      this._angle = angle;\n      this._largeArcFlag = largeArcFlag;\n      this._sweepFlag = sweepFlag;\n    }\n    toString () { return '[object SVGPathSegArcAbs]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegArcAbs(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); }\n  }\n  Object.defineProperties(SVGPathSegArcAbs.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true },\n    r1: { get () { return this._r1; }, set (r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true },\n    r2: { get () { return this._r2; }, set (r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true },\n    angle: { get () { return this._angle; }, set (angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true },\n    largeArcFlag: { get () { return this._largeArcFlag; }, set (largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true },\n    sweepFlag: { get () { return this._sweepFlag; }, set (sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegArcRel extends SVGPathSeg {\n    constructor (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {\n      super(SVGPathSeg.PATHSEG_ARC_REL, 'a', owningPathSegList);\n      this._x = x;\n      this._y = y;\n      this._r1 = r1;\n      this._r2 = r2;\n      this._angle = angle;\n      this._largeArcFlag = largeArcFlag;\n      this._sweepFlag = sweepFlag;\n    }\n    toString () { return '[object SVGPathSegArcRel]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegArcRel(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); }\n  }\n  Object.defineProperties(SVGPathSegArcRel.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true },\n    r1: { get () { return this._r1; }, set (r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true },\n    r2: { get () { return this._r2; }, set (r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true },\n    angle: { get () { return this._angle; }, set (angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true },\n    largeArcFlag: { get () { return this._largeArcFlag; }, set (largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true },\n    sweepFlag: { get () { return this._sweepFlag; }, set (sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegLinetoHorizontalAbs extends SVGPathSeg {\n    constructor (owningPathSegList, x) {\n      super(SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, 'H', owningPathSegList);\n      this._x = x;\n    }\n    toString () { return '[object SVGPathSegLinetoHorizontalAbs]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x; }\n    clone () { return new SVGPathSegLinetoHorizontalAbs(undefined, this._x); }\n  }\n  Object.defineProperty(SVGPathSegLinetoHorizontalAbs.prototype, 'x', { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true });\n\n  class SVGPathSegLinetoHorizontalRel extends SVGPathSeg {\n    constructor (owningPathSegList, x) {\n      super(SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, 'h', owningPathSegList);\n      this._x = x;\n    }\n    toString () { return '[object SVGPathSegLinetoHorizontalRel]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x; }\n    clone () { return new SVGPathSegLinetoHorizontalRel(undefined, this._x); }\n  }\n  Object.defineProperty(SVGPathSegLinetoHorizontalRel.prototype, 'x', { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true });\n\n  class SVGPathSegLinetoVerticalAbs extends SVGPathSeg {\n    constructor (owningPathSegList, y) {\n      super(SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, 'V', owningPathSegList);\n      this._y = y;\n    }\n    toString () { return '[object SVGPathSegLinetoVerticalAbs]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._y; }\n    clone () { return new SVGPathSegLinetoVerticalAbs(undefined, this._y); }\n  }\n  Object.defineProperty(SVGPathSegLinetoVerticalAbs.prototype, 'y', { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true });\n\n  class SVGPathSegLinetoVerticalRel extends SVGPathSeg {\n    constructor (owningPathSegList, y) {\n      super(SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, 'v', owningPathSegList);\n      this._y = y;\n    }\n    toString () { return '[object SVGPathSegLinetoVerticalRel]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._y; }\n    clone () { return new SVGPathSegLinetoVerticalRel(undefined, this._y); }\n  }\n  Object.defineProperty(SVGPathSegLinetoVerticalRel.prototype, 'y', { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true });\n\n  class SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg {\n    constructor (owningPathSegList, x, y, x2, y2) {\n      super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, 'S', owningPathSegList);\n      this._x = x;\n      this._y = y;\n      this._x2 = x2;\n      this._y2 = y2;\n    }\n    toString () { return '[object SVGPathSegCurvetoCubicSmoothAbs]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegCurvetoCubicSmoothAbs(undefined, this._x, this._y, this._x2, this._y2); }\n  }\n  Object.defineProperties(SVGPathSegCurvetoCubicSmoothAbs.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true },\n    x2: { get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true },\n    y2: { get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg {\n    constructor (owningPathSegList, x, y, x2, y2) {\n      super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, 's', owningPathSegList);\n      this._x = x;\n      this._y = y;\n      this._x2 = x2;\n      this._y2 = y2;\n    }\n    toString () { return '[object SVGPathSegCurvetoCubicSmoothRel]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegCurvetoCubicSmoothRel(undefined, this._x, this._y, this._x2, this._y2); }\n  }\n  Object.defineProperties(SVGPathSegCurvetoCubicSmoothRel.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true },\n    x2: { get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true },\n    y2: { get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg {\n    constructor (owningPathSegList, x, y) {\n      super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, 'T', owningPathSegList);\n      this._x = x;\n      this._y = y;\n    }\n    toString () { return '[object SVGPathSegCurvetoQuadraticSmoothAbs]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegCurvetoQuadraticSmoothAbs(undefined, this._x, this._y); }\n  }\n  Object.defineProperties(SVGPathSegCurvetoQuadraticSmoothAbs.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true }\n  });\n\n  class SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg {\n    constructor (owningPathSegList, x, y) {\n      super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, 't', owningPathSegList);\n      this._x = x;\n      this._y = y;\n    }\n    toString () { return '[object SVGPathSegCurvetoQuadraticSmoothRel]'; }\n    _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n    clone () { return new SVGPathSegCurvetoQuadraticSmoothRel(undefined, this._x, this._y); }\n  }\n  Object.defineProperties(SVGPathSegCurvetoQuadraticSmoothRel.prototype, {\n    x: { get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true },\n    y: { get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true }\n  });\n\n  // Add createSVGPathSeg* functions to SVGPathElement.\n  // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathElement.\n  SVGPathElement.prototype.createSVGPathSegClosePath = function () { return new SVGPathSegClosePath(undefined); };\n  SVGPathElement.prototype.createSVGPathSegMovetoAbs = function (x, y) { return new SVGPathSegMovetoAbs(undefined, x, y); };\n  SVGPathElement.prototype.createSVGPathSegMovetoRel = function (x, y) { return new SVGPathSegMovetoRel(undefined, x, y); };\n  SVGPathElement.prototype.createSVGPathSegLinetoAbs = function (x, y) { return new SVGPathSegLinetoAbs(undefined, x, y); };\n  SVGPathElement.prototype.createSVGPathSegLinetoRel = function (x, y) { return new SVGPathSegLinetoRel(undefined, x, y); };\n  SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs = function (x, y, x1, y1, x2, y2) { return new SVGPathSegCurvetoCubicAbs(undefined, x, y, x1, y1, x2, y2); };\n  SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel = function (x, y, x1, y1, x2, y2) { return new SVGPathSegCurvetoCubicRel(undefined, x, y, x1, y1, x2, y2); };\n  SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs = function (x, y, x1, y1) { return new SVGPathSegCurvetoQuadraticAbs(undefined, x, y, x1, y1); };\n  SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel = function (x, y, x1, y1) { return new SVGPathSegCurvetoQuadraticRel(undefined, x, y, x1, y1); };\n  SVGPathElement.prototype.createSVGPathSegArcAbs = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new SVGPathSegArcAbs(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); };\n  SVGPathElement.prototype.createSVGPathSegArcRel = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new SVGPathSegArcRel(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); };\n  SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs = function (x) { return new SVGPathSegLinetoHorizontalAbs(undefined, x); };\n  SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel = function (x) { return new SVGPathSegLinetoHorizontalRel(undefined, x); };\n  SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs = function (y) { return new SVGPathSegLinetoVerticalAbs(undefined, y); };\n  SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel = function (y) { return new SVGPathSegLinetoVerticalRel(undefined, y); };\n  SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs = function (x, y, x2, y2) { return new SVGPathSegCurvetoCubicSmoothAbs(undefined, x, y, x2, y2); };\n  SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel = function (x, y, x2, y2) { return new SVGPathSegCurvetoCubicSmoothRel(undefined, x, y, x2, y2); };\n  SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs = function (x, y) { return new SVGPathSegCurvetoQuadraticSmoothAbs(undefined, x, y); };\n  SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel = function (x, y) { return new SVGPathSegCurvetoQuadraticSmoothRel(undefined, x, y); };\n\n  if (!('getPathSegAtLength' in SVGPathElement.prototype)) {\n    // Add getPathSegAtLength to SVGPathElement.\n    // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-__svg__SVGPathElement__getPathSegAtLength\n    // This polyfill requires SVGPathElement.getTotalLength to implement the distance-along-a-path algorithm.\n    SVGPathElement.prototype.getPathSegAtLength = function (distance) {\n      if (distance === undefined || !isFinite(distance)) {\n        throw new Error('Invalid arguments.');\n      }\n\n      const measurementElement = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n      measurementElement.setAttribute('d', this.getAttribute('d'));\n      let lastPathSegment = measurementElement.pathSegList.numberOfItems - 1;\n\n      // If the path is empty, return 0.\n      if (lastPathSegment <= 0) {\n        return 0;\n      }\n\n      do {\n        measurementElement.pathSegList.removeItem(lastPathSegment);\n        if (distance > measurementElement.getTotalLength()) {\n          break;\n        }\n        lastPathSegment--;\n      } while (lastPathSegment > 0);\n      return lastPathSegment;\n    };\n  }\n\n  window.SVGPathSeg = SVGPathSeg;\n  window.SVGPathSegClosePath = SVGPathSegClosePath;\n  window.SVGPathSegMovetoAbs = SVGPathSegMovetoAbs;\n  window.SVGPathSegMovetoRel = SVGPathSegMovetoRel;\n  window.SVGPathSegLinetoAbs = SVGPathSegLinetoAbs;\n  window.SVGPathSegLinetoRel = SVGPathSegLinetoRel;\n  window.SVGPathSegCurvetoCubicAbs = SVGPathSegCurvetoCubicAbs;\n  window.SVGPathSegCurvetoCubicRel = SVGPathSegCurvetoCubicRel;\n  window.SVGPathSegCurvetoQuadraticAbs = SVGPathSegCurvetoQuadraticAbs;\n  window.SVGPathSegCurvetoQuadraticRel = SVGPathSegCurvetoQuadraticRel;\n  window.SVGPathSegArcAbs = SVGPathSegArcAbs;\n  window.SVGPathSegArcRel = SVGPathSegArcRel;\n  window.SVGPathSegLinetoHorizontalAbs = SVGPathSegLinetoHorizontalAbs;\n  window.SVGPathSegLinetoHorizontalRel = SVGPathSegLinetoHorizontalRel;\n  window.SVGPathSegLinetoVerticalAbs = SVGPathSegLinetoVerticalAbs;\n  window.SVGPathSegLinetoVerticalRel = SVGPathSegLinetoVerticalRel;\n  window.SVGPathSegCurvetoCubicSmoothAbs = SVGPathSegCurvetoCubicSmoothAbs;\n  window.SVGPathSegCurvetoCubicSmoothRel = SVGPathSegCurvetoCubicSmoothRel;\n  window.SVGPathSegCurvetoQuadraticSmoothAbs = SVGPathSegCurvetoQuadraticSmoothAbs;\n  window.SVGPathSegCurvetoQuadraticSmoothRel = SVGPathSegCurvetoQuadraticSmoothRel;\n}\n\n// Checking for SVGPathSegList in window checks for the case of an implementation without the\n// SVGPathSegList API.\n// The second check for appendItem is specific to Firefox 59+ which removed only parts of the\n// SVGPathSegList API (e.g., appendItem). In this case we need to re-implement the entire API\n// so the polyfill data (i.e., _list) is used throughout.\nif (!('SVGPathSegList' in window) || !('appendItem' in SVGPathSegList.prototype)) {\n  // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSegList\n  class SVGPathSegList {\n    constructor (pathElement) {\n      this._pathElement = pathElement;\n      this._list = this._parsePath(this._pathElement.getAttribute('d'));\n\n      // Use a MutationObserver to catch changes to the path's \"d\" attribute.\n      this._mutationObserverConfig = {attributes: true, attributeFilter: ['d']};\n      this._pathElementMutationObserver = new MutationObserver(this._updateListFromPathMutations.bind(this));\n      this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);\n    }\n    // Process any pending mutations to the path element and update the list as needed.\n    // This should be the first call of all public functions and is needed because\n    // MutationObservers are not synchronous so we can have pending asynchronous mutations.\n    _checkPathSynchronizedToList () {\n      this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords());\n    }\n\n    _updateListFromPathMutations (mutationRecords) {\n      if (!this._pathElement) {\n        return;\n      }\n      let hasPathMutations = false;\n      mutationRecords.forEach(function (record) {\n        if (record.attributeName === 'd') {\n          hasPathMutations = true;\n        }\n      });\n      if (hasPathMutations) {\n        this._list = this._parsePath(this._pathElement.getAttribute('d'));\n      }\n    }\n\n    // Serialize the list and update the path's 'd' attribute.\n    _writeListToPath () {\n      this._pathElementMutationObserver.disconnect();\n      this._pathElement.setAttribute('d', SVGPathSegList._pathSegArrayAsString(this._list));\n      this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);\n    }\n\n    // When a path segment changes the list needs to be synchronized back to the path element.\n    segmentChanged (pathSeg) {\n      this._writeListToPath();\n    }\n\n    clear () {\n      this._checkPathSynchronizedToList();\n\n      this._list.forEach(function (pathSeg) {\n        pathSeg._owningPathSegList = null;\n      });\n      this._list = [];\n      this._writeListToPath();\n    }\n\n    initialize (newItem) {\n      this._checkPathSynchronizedToList();\n\n      this._list = [newItem];\n      newItem._owningPathSegList = this;\n      this._writeListToPath();\n      return newItem;\n    }\n\n    _checkValidIndex (index) {\n      if (isNaN(index) || index < 0 || index >= this.numberOfItems) {\n        throw new Error('INDEX_SIZE_ERR');\n      }\n    }\n\n    getItem (index) {\n      this._checkPathSynchronizedToList();\n\n      this._checkValidIndex(index);\n      return this._list[index];\n    }\n\n    insertItemBefore (newItem, index) {\n      this._checkPathSynchronizedToList();\n\n      // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list.\n      if (index > this.numberOfItems) {\n        index = this.numberOfItems;\n      }\n      if (newItem._owningPathSegList) {\n        // SVG2 spec says to make a copy.\n        newItem = newItem.clone();\n      }\n      this._list.splice(index, 0, newItem);\n      newItem._owningPathSegList = this;\n      this._writeListToPath();\n      return newItem;\n    }\n\n    replaceItem (newItem, index) {\n      this._checkPathSynchronizedToList();\n\n      if (newItem._owningPathSegList) {\n        // SVG2 spec says to make a copy.\n        newItem = newItem.clone();\n      }\n      this._checkValidIndex(index);\n      this._list[index] = newItem;\n      newItem._owningPathSegList = this;\n      this._writeListToPath();\n      return newItem;\n    }\n\n    removeItem (index) {\n      this._checkPathSynchronizedToList();\n\n      this._checkValidIndex(index);\n      const item = this._list[index];\n      this._list.splice(index, 1);\n      this._writeListToPath();\n      return item;\n    }\n\n    appendItem (newItem) {\n      this._checkPathSynchronizedToList();\n\n      if (newItem._owningPathSegList) {\n        // SVG2 spec says to make a copy.\n        newItem = newItem.clone();\n      }\n      this._list.push(newItem);\n      newItem._owningPathSegList = this;\n      // TODO: Optimize this to just append to the existing attribute.\n      this._writeListToPath();\n      return newItem;\n    }\n\n    // This closely follows SVGPathParser::parsePath from Source/core/svg/SVGPathParser.cpp.\n    _parsePath (string) {\n      if (!string || !string.length) {\n        return [];\n      }\n\n      const owningPathSegList = this;\n\n      class Builder {\n        constructor () {\n          this.pathSegList = [];\n        }\n        appendSegment (pathSeg) {\n          this.pathSegList.push(pathSeg);\n        }\n      }\n\n      class Source {\n        constructor (string) {\n          this._string = string;\n          this._currentIndex = 0;\n          this._endIndex = this._string.length;\n          this._previousCommand = SVGPathSeg.PATHSEG_UNKNOWN;\n\n          this._skipOptionalSpaces();\n        }\n        _isCurrentSpace () {\n          const character = this._string[this._currentIndex];\n          return character <= ' ' && (character === ' ' || character === '\\n' || character === '\\t' || character === '\\r' || character === '\\f');\n        }\n\n        _skipOptionalSpaces () {\n          while (this._currentIndex < this._endIndex && this._isCurrentSpace()) {\n            this._currentIndex++;\n          }\n          return this._currentIndex < this._endIndex;\n        }\n\n        _skipOptionalSpacesOrDelimiter () {\n          if (this._currentIndex < this._endIndex && !this._isCurrentSpace() && this._string.charAt(this._currentIndex) !== ',') {\n            return false;\n          }\n          if (this._skipOptionalSpaces()) {\n            if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === ',') {\n              this._currentIndex++;\n              this._skipOptionalSpaces();\n            }\n          }\n          return this._currentIndex < this._endIndex;\n        }\n\n        hasMoreData () {\n          return this._currentIndex < this._endIndex;\n        }\n\n        peekSegmentType () {\n          const lookahead = this._string[this._currentIndex];\n          return this._pathSegTypeFromChar(lookahead);\n        }\n\n        _pathSegTypeFromChar (lookahead) {\n          switch (lookahead) {\n          case 'Z':\n          case 'z':\n            return SVGPathSeg.PATHSEG_CLOSEPATH;\n          case 'M':\n            return SVGPathSeg.PATHSEG_MOVETO_ABS;\n          case 'm':\n            return SVGPathSeg.PATHSEG_MOVETO_REL;\n          case 'L':\n            return SVGPathSeg.PATHSEG_LINETO_ABS;\n          case 'l':\n            return SVGPathSeg.PATHSEG_LINETO_REL;\n          case 'C':\n            return SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS;\n          case 'c':\n            return SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL;\n          case 'Q':\n            return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS;\n          case 'q':\n            return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL;\n          case 'A':\n            return SVGPathSeg.PATHSEG_ARC_ABS;\n          case 'a':\n            return SVGPathSeg.PATHSEG_ARC_REL;\n          case 'H':\n            return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS;\n          case 'h':\n            return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL;\n          case 'V':\n            return SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS;\n          case 'v':\n            return SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL;\n          case 'S':\n            return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS;\n          case 's':\n            return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL;\n          case 'T':\n            return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS;\n          case 't':\n            return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL;\n          default:\n            return SVGPathSeg.PATHSEG_UNKNOWN;\n          }\n        }\n\n        _nextCommandHelper (lookahead, previousCommand) {\n          // Check for remaining coordinates in the current command.\n          if ((lookahead === '+' || lookahead === '-' || lookahead === '.' || (lookahead >= '0' && lookahead <= '9')) && previousCommand !== SVGPathSeg.PATHSEG_CLOSEPATH) {\n            if (previousCommand === SVGPathSeg.PATHSEG_MOVETO_ABS) {\n              return SVGPathSeg.PATHSEG_LINETO_ABS;\n            }\n            if (previousCommand === SVGPathSeg.PATHSEG_MOVETO_REL) {\n              return SVGPathSeg.PATHSEG_LINETO_REL;\n            }\n            return previousCommand;\n          }\n          return SVGPathSeg.PATHSEG_UNKNOWN;\n        }\n\n        initialCommandIsMoveTo () {\n          // If the path is empty it is still valid, so return true.\n          if (!this.hasMoreData()) {\n            return true;\n          }\n          const command = this.peekSegmentType();\n          // Path must start with moveTo.\n          return command === SVGPathSeg.PATHSEG_MOVETO_ABS || command === SVGPathSeg.PATHSEG_MOVETO_REL;\n        }\n\n        // Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp.\n        // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF\n        _parseNumber () {\n          let exponent = 0;\n          let integer = 0;\n          let frac = 1;\n          let decimal = 0;\n          let sign = 1;\n          let expsign = 1;\n\n          const startIndex = this._currentIndex;\n\n          this._skipOptionalSpaces();\n\n          // Read the sign.\n          if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '+') {\n            this._currentIndex++;\n          } else if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '-') {\n            this._currentIndex++;\n            sign = -1;\n          }\n\n          if (this._currentIndex === this._endIndex || ((this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') && this._string.charAt(this._currentIndex) !== '.')) {\n            // The first character of a number must be one of [0-9+-.].\n            return undefined;\n          }\n\n          // Read the integer part, build right-to-left.\n          const startIntPartIndex = this._currentIndex;\n          while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') {\n            this._currentIndex++; // Advance to first non-digit.\n          }\n\n          if (this._currentIndex !== startIntPartIndex) {\n            let scanIntPartIndex = this._currentIndex - 1;\n            let multiplier = 1;\n            while (scanIntPartIndex >= startIntPartIndex) {\n              integer += multiplier * (this._string.charAt(scanIntPartIndex--) - '0');\n              multiplier *= 10;\n            }\n          }\n\n          // Read the decimals.\n          if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '.') {\n            this._currentIndex++;\n\n            // There must be a least one digit following the .\n            if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') {\n              return undefined;\n            }\n            while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') {\n              frac *= 10;\n              decimal += (this._string.charAt(this._currentIndex) - '0') / frac;\n              this._currentIndex += 1;\n            }\n          }\n\n          // Read the exponent part.\n          if (this._currentIndex !== startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) === 'e' || this._string.charAt(this._currentIndex) === 'E') && (this._string.charAt(this._currentIndex + 1) !== 'x' && this._string.charAt(this._currentIndex + 1) !== 'm')) {\n            this._currentIndex++;\n\n            // Read the sign of the exponent.\n            if (this._string.charAt(this._currentIndex) === '+') {\n              this._currentIndex++;\n            } else if (this._string.charAt(this._currentIndex) === '-') {\n              this._currentIndex++;\n              expsign = -1;\n            }\n\n            // There must be an exponent.\n            if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') {\n              return undefined;\n            }\n\n            while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') {\n              exponent *= 10;\n              exponent += (this._string.charAt(this._currentIndex) - '0');\n              this._currentIndex++;\n            }\n          }\n\n          let number = integer + decimal;\n          number *= sign;\n\n          if (exponent) {\n            number *= Math.pow(10, expsign * exponent);\n          }\n\n          if (startIndex === this._currentIndex) {\n            return undefined;\n          }\n\n          this._skipOptionalSpacesOrDelimiter();\n\n          return number;\n        }\n\n        _parseArcFlag () {\n          if (this._currentIndex >= this._endIndex) {\n            return undefined;\n          }\n          let flag = false;\n          const flagChar = this._string.charAt(this._currentIndex++);\n          if (flagChar === '0') {\n            flag = false;\n          } else if (flagChar === '1') {\n            flag = true;\n          } else {\n            return undefined;\n          }\n\n          this._skipOptionalSpacesOrDelimiter();\n          return flag;\n        }\n\n        parseSegment () {\n          const lookahead = this._string[this._currentIndex];\n          let command = this._pathSegTypeFromChar(lookahead);\n          if (command === SVGPathSeg.PATHSEG_UNKNOWN) {\n            // Possibly an implicit command. Not allowed if this is the first command.\n            if (this._previousCommand === SVGPathSeg.PATHSEG_UNKNOWN) {\n              return null;\n            }\n            command = this._nextCommandHelper(lookahead, this._previousCommand);\n            if (command === SVGPathSeg.PATHSEG_UNKNOWN) {\n              return null;\n            }\n          } else {\n            this._currentIndex++;\n          }\n\n          this._previousCommand = command;\n\n          switch (command) {\n          case SVGPathSeg.PATHSEG_MOVETO_REL:\n            return new SVGPathSegMovetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());\n          case SVGPathSeg.PATHSEG_MOVETO_ABS:\n            return new SVGPathSegMovetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());\n          case SVGPathSeg.PATHSEG_LINETO_REL:\n            return new SVGPathSegLinetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());\n          case SVGPathSeg.PATHSEG_LINETO_ABS:\n            return new SVGPathSegLinetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());\n          case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:\n            return new SVGPathSegLinetoHorizontalRel(owningPathSegList, this._parseNumber());\n          case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:\n            return new SVGPathSegLinetoHorizontalAbs(owningPathSegList, this._parseNumber());\n          case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL:\n            return new SVGPathSegLinetoVerticalRel(owningPathSegList, this._parseNumber());\n          case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS:\n            return new SVGPathSegLinetoVerticalAbs(owningPathSegList, this._parseNumber());\n          case SVGPathSeg.PATHSEG_CLOSEPATH:\n            this._skipOptionalSpaces();\n            return new SVGPathSegClosePath(owningPathSegList);\n          case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL: {\n            const points = {x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n            return new SVGPathSegCurvetoCubicRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);\n          } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS: {\n            const points = {x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n            return new SVGPathSegCurvetoCubicAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);\n          } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL: {\n            const points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n            return new SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, points.x, points.y, points.x2, points.y2);\n          } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: {\n            const points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n            return new SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, points.x, points.y, points.x2, points.y2);\n          } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL: {\n            const points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n            return new SVGPathSegCurvetoQuadraticRel(owningPathSegList, points.x, points.y, points.x1, points.y1);\n          } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS:\n            const points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n            return new SVGPathSegCurvetoQuadraticAbs(owningPathSegList, points.x, points.y, points.x1, points.y1);\n          case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:\n            return new SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, this._parseNumber(), this._parseNumber());\n          case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:\n            return new SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, this._parseNumber(), this._parseNumber());\n          case SVGPathSeg.PATHSEG_ARC_REL: {\n            const points = {x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber()};\n            return new SVGPathSegArcRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);\n          } case SVGPathSeg.PATHSEG_ARC_ABS: {\n            const points = {x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber()};\n            return new SVGPathSegArcAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);\n          } default:\n            throw new Error('Unknown path seg type.');\n          }\n        }\n      }\n\n      const builder = new Builder();\n      const source = new Source(string);\n\n      if (!source.initialCommandIsMoveTo()) {\n        return [];\n      }\n      while (source.hasMoreData()) {\n        const pathSeg = source.parseSegment();\n        if (!pathSeg) {\n          return [];\n        }\n        builder.appendSegment(pathSeg);\n      }\n\n      return builder.pathSegList;\n    }\n  }\n\n  SVGPathSegList.prototype.classname = 'SVGPathSegList';\n\n  Object.defineProperty(SVGPathSegList.prototype, 'numberOfItems', {\n    get () {\n      this._checkPathSynchronizedToList();\n      return this._list.length;\n    },\n    enumerable: true\n  });\n\n  SVGPathSegList._pathSegArrayAsString = function (pathSegArray) {\n    let string = '';\n    let first = true;\n    pathSegArray.forEach(function (pathSeg) {\n      if (first) {\n        first = false;\n        string += pathSeg._asPathString();\n      } else {\n        string += ' ' + pathSeg._asPathString();\n      }\n    });\n    return string;\n  };\n\n  // Add the pathSegList accessors to SVGPathElement.\n  // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGAnimatedPathData\n  Object.defineProperties(SVGPathElement.prototype, {\n    pathSegList: {\n      get () {\n        if (!this._pathSegList) {\n          this._pathSegList = new SVGPathSegList(this);\n        }\n        return this._pathSegList;\n      },\n      enumerable: true\n    },\n    // FIXME: The following are not implemented and simply return SVGPathElement.pathSegList.\n    normalizedPathSegList: { get () { return this.pathSegList; }, enumerable: true },\n    animatedPathSegList: { get () { return this.pathSegList; }, enumerable: true },\n    animatedNormalizedPathSegList: { get () { return this.pathSegList; }, enumerable: true }\n  });\n  window.SVGPathSegList = SVGPathSegList;\n}\n})();\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/recalculate.js",
    "content": "/* globals jQuery */\n/**\n * Recalculate.\n *\n * Licensed under the MIT License\n *\n */\n\n// Dependencies:\n// 1) jquery-svg.js\n\nimport jqPluginSVG from './jquery-svg.js'; // Needed for SVG attribute setting and array form with `attr`\nimport {NS} from './svgedit.js';\nimport {convertToNum} from './units.js';\nimport {isWebkit} from './browser.js';\nimport {getTransformList} from './svgtransformlist.js';\nimport {getRotationAngle, getHref, getBBox, getRefElem} from './svgutils.js';\nimport {BatchCommand, ChangeElementCommand} from './history.js';\nimport {remapElement} from './coords.js';\nimport {\n  isIdentity, matrixMultiply, transformPoint, transformListToTransform,\n  hasMatrixTransform\n} from './math.js';\n\nconst $ = jqPluginSVG(jQuery);\n\nlet context_;\n\n/**\n* @param editorContext\n*/\nexport const init = function (editorContext) {\n  context_ = editorContext;\n};\n\n/**\n* Updates a <clipPath>s values based on the given translation of an element\n* @param attr - The clip-path attribute value with the clipPath's ID\n* @param tx - The translation's x value\n* @param ty - The translation's y value\n*/\nexport const updateClipPath = function (attr, tx, ty) {\n  const path = getRefElem(attr).firstChild;\n  const cpXform = getTransformList(path);\n  const newxlate = context_.getSVGRoot().createSVGTransform();\n  newxlate.setTranslate(tx, ty);\n\n  cpXform.appendItem(newxlate);\n\n  // Update clipPath's dimensions\n  recalculateDimensions(path);\n};\n\n/**\n* Decides the course of action based on the element's transform list\n* @param selected - The DOM element to recalculate\n* @returns Undo command object with the resulting change\n*/\nexport const recalculateDimensions = function (selected) {\n  if (selected == null) { return null; }\n\n  // Firefox Issue - 1081\n  if (selected.nodeName === 'svg' && navigator.userAgent.includes('Firefox/20')) {\n    return null;\n  }\n\n  const svgroot = context_.getSVGRoot();\n  const tlist = getTransformList(selected);\n\n  // remove any unnecessary transforms\n  if (tlist && tlist.numberOfItems > 0) {\n    let k = tlist.numberOfItems;\n    const noi = k;\n    while (k--) {\n      const xform = tlist.getItem(k);\n      if (xform.type === 0) {\n        tlist.removeItem(k);\n      // remove identity matrices\n      } else if (xform.type === 1) {\n        if (isIdentity(xform.matrix)) {\n          if (noi === 1) {\n            // Overcome Chrome bug (though only when noi is 1) with\n            //    `removeItem` preventing `removeAttribute` from\n            //    subsequently working\n            // See https://bugs.chromium.org/p/chromium/issues/detail?id=843901\n            selected.removeAttribute('transform');\n            return null;\n          }\n          tlist.removeItem(k);\n        }\n      // remove zero-degree rotations\n      } else if (xform.type === 4) {\n        if (xform.angle === 0) {\n          tlist.removeItem(k);\n        }\n      }\n    }\n    // End here if all it has is a rotation\n    if (tlist.numberOfItems === 1 &&\n        getRotationAngle(selected)) { return null; }\n  }\n\n  // if this element had no transforms, we are done\n  if (!tlist || tlist.numberOfItems === 0) {\n    // Chrome apparently had a bug that requires clearing the attribute first.\n    selected.setAttribute('transform', '');\n    // However, this still next line currently doesn't work at all in Chrome\n    selected.removeAttribute('transform');\n    // selected.transform.baseVal.clear(); // Didn't help for Chrome bug\n    return null;\n  }\n\n  // TODO: Make this work for more than 2\n  if (tlist) {\n    let mxs = [];\n    let k = tlist.numberOfItems;\n    while (k--) {\n      const xform = tlist.getItem(k);\n      if (xform.type === 1) {\n        mxs.push([xform.matrix, k]);\n      } else if (mxs.length) {\n        mxs = [];\n      }\n    }\n    if (mxs.length === 2) {\n      const mNew = svgroot.createSVGTransformFromMatrix(matrixMultiply(mxs[1][0], mxs[0][0]));\n      tlist.removeItem(mxs[0][1]);\n      tlist.removeItem(mxs[1][1]);\n      tlist.insertItemBefore(mNew, mxs[1][1]);\n    }\n\n    // combine matrix + translate\n    k = tlist.numberOfItems;\n    if (k >= 2 && tlist.getItem(k - 2).type === 1 && tlist.getItem(k - 1).type === 2) {\n      const mt = svgroot.createSVGTransform();\n\n      const m = matrixMultiply(\n        tlist.getItem(k - 2).matrix,\n        tlist.getItem(k - 1).matrix);\n      mt.setMatrix(m);\n      tlist.removeItem(k - 2);\n      tlist.removeItem(k - 2);\n      tlist.appendItem(mt);\n    }\n  }\n\n  // If it still has a single [M] or [R][M], return null too (prevents BatchCommand from being returned).\n  switch (selected.tagName) {\n  // Ignore these elements, as they can absorb the [M]\n  case 'line':\n  case 'polyline':\n  case 'polygon':\n  case 'path':\n    break;\n  default:\n    if ((tlist.numberOfItems === 1 && tlist.getItem(0).type === 1) ||\n        (tlist.numberOfItems === 2 && tlist.getItem(0).type === 1 && tlist.getItem(0).type === 4)) {\n      return null;\n    }\n  }\n\n  // Grouped SVG element\n  const gsvg = $(selected).data('gsvg');\n\n  // we know we have some transforms, so set up return variable\n  const batchCmd = new BatchCommand('Transform');\n\n  // store initial values that will be affected by reducing the transform list\n  let changes = {};\n  let initial = null;\n  let attrs = [];\n  switch (selected.tagName) {\n  case 'line':\n    attrs = ['x1', 'y1', 'x2', 'y2'];\n    break;\n  case 'circle':\n    attrs = ['cx', 'cy', 'r'];\n    break;\n  case 'ellipse':\n    attrs = ['cx', 'cy', 'rx', 'ry'];\n    break;\n  case 'foreignObject':\n  case 'rect':\n  case 'image':\n    attrs = ['width', 'height', 'x', 'y'];\n    break;\n  case 'use':\n  case 'text':\n  case 'tspan':\n    attrs = ['x', 'y'];\n    break;\n  case 'polygon':\n  case 'polyline': {\n    initial = {};\n    initial.points = selected.getAttribute('points');\n    const list = selected.points;\n    const len = list.numberOfItems;\n    changes.points = new Array(len);\n    for (let i = 0; i < len; ++i) {\n      const pt = list.getItem(i);\n      changes.points[i] = {x: pt.x, y: pt.y};\n    }\n    break;\n  } case 'path':\n    initial = {};\n    initial.d = selected.getAttribute('d');\n    changes.d = selected.getAttribute('d');\n    break;\n  } // switch on element type to get initial values\n\n  if (attrs.length) {\n    changes = $(selected).attr(attrs);\n    $.each(changes, function (attr, val) {\n      changes[attr] = convertToNum(attr, val);\n    });\n  } else if (gsvg) {\n    // GSVG exception\n    changes = {\n      x: $(gsvg).attr('x') || 0,\n      y: $(gsvg).attr('y') || 0\n    };\n  }\n\n  // if we haven't created an initial array in polygon/polyline/path, then\n  // make a copy of initial values and include the transform\n  if (initial == null) {\n    initial = $.extend(true, {}, changes);\n    $.each(initial, function (attr, val) {\n      initial[attr] = convertToNum(attr, val);\n    });\n  }\n  // save the start transform value too\n  initial.transform = context_.getStartTransform() || '';\n\n  let oldcenter, newcenter;\n\n  // if it's a regular group, we have special processing to flatten transforms\n  if ((selected.tagName === 'g' && !gsvg) || selected.tagName === 'a') {\n    const box = getBBox(selected);\n\n    oldcenter = {x: box.x + box.width / 2, y: box.y + box.height / 2};\n    newcenter = transformPoint(\n      box.x + box.width / 2,\n      box.y + box.height / 2,\n      transformListToTransform(tlist).matrix\n    );\n    let m = svgroot.createSVGMatrix();\n\n    // temporarily strip off the rotate and save the old center\n    const gangle = getRotationAngle(selected);\n    if (gangle) {\n      const a = gangle * Math.PI / 180;\n      let s;\n      if (Math.abs(a) > (1.0e-10)) {\n        s = Math.sin(a) / (1 - Math.cos(a));\n      } else {\n        // FIXME: This blows up if the angle is exactly 0!\n        s = 2 / a;\n      }\n      for (let i = 0; i < tlist.numberOfItems; ++i) {\n        const xform = tlist.getItem(i);\n        if (xform.type === 4) {\n          // extract old center through mystical arts\n          const rm = xform.matrix;\n          oldcenter.y = (s * rm.e + rm.f) / 2;\n          oldcenter.x = (rm.e - s * rm.f) / 2;\n          tlist.removeItem(i);\n          break;\n        }\n      }\n    }\n    const N = tlist.numberOfItems;\n    let tx = 0, ty = 0, operation = 0;\n\n    let firstM;\n    if (N) {\n      firstM = tlist.getItem(0).matrix;\n    }\n\n    let oldStartTransform;\n    // first, if it was a scale then the second-last transform will be it\n    if (N >= 3 && tlist.getItem(N - 2).type === 3 &&\n      tlist.getItem(N - 3).type === 2 && tlist.getItem(N - 1).type === 2) {\n      operation = 3; // scale\n\n      // if the children are unrotated, pass the scale down directly\n      // otherwise pass the equivalent matrix() down directly\n      const tm = tlist.getItem(N - 3).matrix,\n        sm = tlist.getItem(N - 2).matrix,\n        tmn = tlist.getItem(N - 1).matrix;\n\n      const children = selected.childNodes;\n      let c = children.length;\n      while (c--) {\n        const child = children.item(c);\n        tx = 0;\n        ty = 0;\n        if (child.nodeType === 1) {\n          const childTlist = getTransformList(child);\n\n          // some children might not have a transform (<metadata>, <defs>, etc)\n          if (!childTlist) { continue; }\n\n          const m = transformListToTransform(childTlist).matrix;\n\n          // Convert a matrix to a scale if applicable\n          // if (hasMatrixTransform(childTlist) && childTlist.numberOfItems == 1) {\n          //   if (m.b==0 && m.c==0 && m.e==0 && m.f==0) {\n          //     childTlist.removeItem(0);\n          //     const translateOrigin = svgroot.createSVGTransform(),\n          //       scale = svgroot.createSVGTransform(),\n          //       translateBack = svgroot.createSVGTransform();\n          //     translateOrigin.setTranslate(0, 0);\n          //     scale.setScale(m.a, m.d);\n          //     translateBack.setTranslate(0, 0);\n          //     childTlist.appendItem(translateBack);\n          //     childTlist.appendItem(scale);\n          //     childTlist.appendItem(translateOrigin);\n          //   }\n          // }\n\n          const angle = getRotationAngle(child);\n          oldStartTransform = context_.getStartTransform();\n          const childxforms = [];\n          context_.setStartTransform(child.getAttribute('transform'));\n          if (angle || hasMatrixTransform(childTlist)) {\n            const e2t = svgroot.createSVGTransform();\n            e2t.setMatrix(matrixMultiply(tm, sm, tmn, m));\n            childTlist.clear();\n            childTlist.appendItem(e2t);\n            childxforms.push(e2t);\n          // if not rotated or skewed, push the [T][S][-T] down to the child\n          } else {\n            // update the transform list with translate,scale,translate\n\n            // slide the [T][S][-T] from the front to the back\n            // [T][S][-T][M] = [M][T2][S2][-T2]\n\n            // (only bringing [-T] to the right of [M])\n            // [T][S][-T][M] = [T][S][M][-T2]\n            // [-T2] = [M_inv][-T][M]\n            const t2n = matrixMultiply(m.inverse(), tmn, m);\n            // [T2] is always negative translation of [-T2]\n            const t2 = svgroot.createSVGMatrix();\n            t2.e = -t2n.e;\n            t2.f = -t2n.f;\n\n            // [T][S][-T][M] = [M][T2][S2][-T2]\n            // [S2] = [T2_inv][M_inv][T][S][-T][M][-T2_inv]\n            const s2 = matrixMultiply(t2.inverse(), m.inverse(), tm, sm, tmn, m, t2n.inverse());\n\n            const translateOrigin = svgroot.createSVGTransform(),\n              scale = svgroot.createSVGTransform(),\n              translateBack = svgroot.createSVGTransform();\n            translateOrigin.setTranslate(t2n.e, t2n.f);\n            scale.setScale(s2.a, s2.d);\n            translateBack.setTranslate(t2.e, t2.f);\n            childTlist.appendItem(translateBack);\n            childTlist.appendItem(scale);\n            childTlist.appendItem(translateOrigin);\n            childxforms.push(translateBack);\n            childxforms.push(scale);\n            childxforms.push(translateOrigin);\n            // logMatrix(translateBack.matrix);\n            // logMatrix(scale.matrix);\n          } // not rotated\n          batchCmd.addSubCommand(recalculateDimensions(child));\n          // TODO: If any <use> have this group as a parent and are\n          // referencing this child, then we need to impose a reverse\n          // scale on it so that when it won't get double-translated\n          // const uses = selected.getElementsByTagNameNS(NS.SVG, 'use');\n          // const href = '#' + child.id;\n          // let u = uses.length;\n          // while (u--) {\n          //   const useElem = uses.item(u);\n          //   if (href == getHref(useElem)) {\n          //     const usexlate = svgroot.createSVGTransform();\n          //     usexlate.setTranslate(-tx,-ty);\n          //     getTransformList(useElem).insertItemBefore(usexlate,0);\n          //     batchCmd.addSubCommand( recalculateDimensions(useElem) );\n          //   }\n          // }\n          context_.setStartTransform(oldStartTransform);\n        } // element\n      } // for each child\n      // Remove these transforms from group\n      tlist.removeItem(N - 1);\n      tlist.removeItem(N - 2);\n      tlist.removeItem(N - 3);\n    } else if (N >= 3 && tlist.getItem(N - 1).type === 1) {\n      operation = 3; // scale\n      m = transformListToTransform(tlist).matrix;\n      const e2t = svgroot.createSVGTransform();\n      e2t.setMatrix(m);\n      tlist.clear();\n      tlist.appendItem(e2t);\n    // next, check if the first transform was a translate\n    // if we had [ T1 ] [ M ] we want to transform this into [ M ] [ T2 ]\n    // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ]\n    } else if ((N === 1 || (N > 1 && tlist.getItem(1).type !== 3)) &&\n      tlist.getItem(0).type === 2) {\n      operation = 2; // translate\n      const T_M = transformListToTransform(tlist).matrix;\n      tlist.removeItem(0);\n      const mInv = transformListToTransform(tlist).matrix.inverse();\n      const M2 = matrixMultiply(mInv, T_M);\n\n      tx = M2.e;\n      ty = M2.f;\n\n      if (tx !== 0 || ty !== 0) {\n        // we pass the translates down to the individual children\n        const children = selected.childNodes;\n        let c = children.length;\n\n        let clipPathsDone = [];\n\n        while (c--) {\n          const child = children.item(c);\n          if (child.nodeType === 1) {\n            // Check if child has clip-path\n            if (child.getAttribute('clip-path')) {\n              // tx, ty\n              const attr = child.getAttribute('clip-path');\n              if (!clipPathsDone.includes(attr)) {\n                updateClipPath(attr, tx, ty);\n                clipPathsDone.push(attr);\n              }\n            }\n\n            oldStartTransform = context_.getStartTransform();\n            context_.setStartTransform(child.getAttribute('transform'));\n\n            const childTlist = getTransformList(child);\n            // some children might not have a transform (<metadata>, <defs>, etc)\n            if (childTlist) {\n              const newxlate = svgroot.createSVGTransform();\n              newxlate.setTranslate(tx, ty);\n              if (childTlist.numberOfItems) {\n                childTlist.insertItemBefore(newxlate, 0);\n              } else {\n                childTlist.appendItem(newxlate);\n              }\n              batchCmd.addSubCommand(recalculateDimensions(child));\n              // If any <use> have this group as a parent and are\n              // referencing this child, then impose a reverse translate on it\n              // so that when it won't get double-translated\n              const uses = selected.getElementsByTagNameNS(NS.SVG, 'use');\n              const href = '#' + child.id;\n              let u = uses.length;\n              while (u--) {\n                const useElem = uses.item(u);\n                if (href === getHref(useElem)) {\n                  const usexlate = svgroot.createSVGTransform();\n                  usexlate.setTranslate(-tx, -ty);\n                  getTransformList(useElem).insertItemBefore(usexlate, 0);\n                  batchCmd.addSubCommand(recalculateDimensions(useElem));\n                }\n              }\n              context_.setStartTransform(oldStartTransform);\n            }\n          }\n        }\n\n        clipPathsDone = [];\n        context_.setStartTransform(oldStartTransform);\n      }\n    // else, a matrix imposition from a parent group\n    // keep pushing it down to the children\n    } else if (N === 1 && tlist.getItem(0).type === 1 && !gangle) {\n      operation = 1;\n      const m = tlist.getItem(0).matrix,\n        children = selected.childNodes;\n      let c = children.length;\n      while (c--) {\n        const child = children.item(c);\n        if (child.nodeType === 1) {\n          oldStartTransform = context_.getStartTransform();\n          context_.setStartTransform(child.getAttribute('transform'));\n          const childTlist = getTransformList(child);\n\n          if (!childTlist) { continue; }\n\n          const em = matrixMultiply(m, transformListToTransform(childTlist).matrix);\n          const e2m = svgroot.createSVGTransform();\n          e2m.setMatrix(em);\n          childTlist.clear();\n          childTlist.appendItem(e2m, 0);\n\n          batchCmd.addSubCommand(recalculateDimensions(child));\n          context_.setStartTransform(oldStartTransform);\n\n          // Convert stroke\n          // TODO: Find out if this should actually happen somewhere else\n          const sw = child.getAttribute('stroke-width');\n          if (child.getAttribute('stroke') !== 'none' && !isNaN(sw)) {\n            const avg = (Math.abs(em.a) + Math.abs(em.d)) / 2;\n            child.setAttribute('stroke-width', sw * avg);\n          }\n        }\n      }\n      tlist.clear();\n    // else it was just a rotate\n    } else {\n      if (gangle) {\n        const newRot = svgroot.createSVGTransform();\n        newRot.setRotate(gangle, newcenter.x, newcenter.y);\n        if (tlist.numberOfItems) {\n          tlist.insertItemBefore(newRot, 0);\n        } else {\n          tlist.appendItem(newRot);\n        }\n      }\n      if (tlist.numberOfItems === 0) {\n        selected.removeAttribute('transform');\n      }\n      return null;\n    }\n\n    // if it was a translate, put back the rotate at the new center\n    if (operation === 2) {\n      if (gangle) {\n        newcenter = {\n          x: oldcenter.x + firstM.e,\n          y: oldcenter.y + firstM.f\n        };\n\n        const newRot = svgroot.createSVGTransform();\n        newRot.setRotate(gangle, newcenter.x, newcenter.y);\n        if (tlist.numberOfItems) {\n          tlist.insertItemBefore(newRot, 0);\n        } else {\n          tlist.appendItem(newRot);\n        }\n      }\n    // if it was a resize\n    } else if (operation === 3) {\n      const m = transformListToTransform(tlist).matrix;\n      const roldt = svgroot.createSVGTransform();\n      roldt.setRotate(gangle, oldcenter.x, oldcenter.y);\n      const rold = roldt.matrix;\n      const rnew = svgroot.createSVGTransform();\n      rnew.setRotate(gangle, newcenter.x, newcenter.y);\n      const rnewInv = rnew.matrix.inverse(),\n        mInv = m.inverse(),\n        extrat = matrixMultiply(mInv, rnewInv, rold, m);\n\n      tx = extrat.e;\n      ty = extrat.f;\n\n      if (tx !== 0 || ty !== 0) {\n        // now push this transform down to the children\n        // we pass the translates down to the individual children\n        const children = selected.childNodes;\n        let c = children.length;\n        while (c--) {\n          const child = children.item(c);\n          if (child.nodeType === 1) {\n            oldStartTransform = context_.getStartTransform();\n            context_.setStartTransform(child.getAttribute('transform'));\n            const childTlist = getTransformList(child);\n            const newxlate = svgroot.createSVGTransform();\n            newxlate.setTranslate(tx, ty);\n            if (childTlist.numberOfItems) {\n              childTlist.insertItemBefore(newxlate, 0);\n            } else {\n              childTlist.appendItem(newxlate);\n            }\n\n            batchCmd.addSubCommand(recalculateDimensions(child));\n            context_.setStartTransform(oldStartTransform);\n          }\n        }\n      }\n\n      if (gangle) {\n        if (tlist.numberOfItems) {\n          tlist.insertItemBefore(rnew, 0);\n        } else {\n          tlist.appendItem(rnew);\n        }\n      }\n    }\n  // else, it's a non-group\n  } else {\n    // FIXME: box might be null for some elements (<metadata> etc), need to handle this\n    const box = getBBox(selected);\n\n    // Paths (and possbly other shapes) will have no BBox while still in <defs>,\n    // but we still may need to recalculate them (see issue 595).\n    // TODO: Figure out how to get BBox from these elements in case they\n    // have a rotation transform\n\n    if (!box && selected.tagName !== 'path') return null;\n\n    let m = svgroot.createSVGMatrix();\n    // temporarily strip off the rotate and save the old center\n    const angle = getRotationAngle(selected);\n    if (angle) {\n      oldcenter = {x: box.x + box.width / 2, y: box.y + box.height / 2};\n      newcenter = transformPoint(\n        box.x + box.width / 2,\n        box.y + box.height / 2,\n        transformListToTransform(tlist).matrix\n      );\n\n      const a = angle * Math.PI / 180;\n      const s = (Math.abs(a) > (1.0e-10))\n        ? Math.sin(a) / (1 - Math.cos(a))\n        // FIXME: This blows up if the angle is exactly 0!\n        : 2 / a;\n\n      for (let i = 0; i < tlist.numberOfItems; ++i) {\n        const xform = tlist.getItem(i);\n        if (xform.type === 4) {\n          // extract old center through mystical arts\n          const rm = xform.matrix;\n          oldcenter.y = (s * rm.e + rm.f) / 2;\n          oldcenter.x = (rm.e - s * rm.f) / 2;\n          tlist.removeItem(i);\n          break;\n        }\n      }\n    }\n\n    // 2 = translate, 3 = scale, 4 = rotate, 1 = matrix imposition\n    let operation = 0;\n    const N = tlist.numberOfItems;\n\n    // Check if it has a gradient with userSpaceOnUse, in which case\n    // adjust it by recalculating the matrix transform.\n    // TODO: Make this work in Webkit using svgedit.transformlist.SVGTransformList\n    if (!isWebkit()) {\n      const fill = selected.getAttribute('fill');\n      if (fill && fill.startsWith('url(')) {\n        const paint = getRefElem(fill);\n        let type = 'pattern';\n        if (paint.tagName !== type) type = 'gradient';\n        const attrVal = paint.getAttribute(type + 'Units');\n        if (attrVal === 'userSpaceOnUse') {\n          // Update the userSpaceOnUse element\n          m = transformListToTransform(tlist).matrix;\n          const gtlist = getTransformList(paint);\n          const gmatrix = transformListToTransform(gtlist).matrix;\n          m = matrixMultiply(m, gmatrix);\n          const mStr = 'matrix(' + [m.a, m.b, m.c, m.d, m.e, m.f].join(',') + ')';\n          paint.setAttribute(type + 'Transform', mStr);\n        }\n      }\n    }\n\n    // first, if it was a scale of a non-skewed element, then the second-last\n    // transform will be the [S]\n    // if we had [M][T][S][T] we want to extract the matrix equivalent of\n    // [T][S][T] and push it down to the element\n    if (N >= 3 && tlist.getItem(N - 2).type === 3 &&\n      tlist.getItem(N - 3).type === 2 && tlist.getItem(N - 1).type === 2) {\n      // Removed this so a <use> with a given [T][S][T] would convert to a matrix.\n      // Is that bad?\n      //  && selected.nodeName != 'use'\n      operation = 3; // scale\n      m = transformListToTransform(tlist, N - 3, N - 1).matrix;\n      tlist.removeItem(N - 1);\n      tlist.removeItem(N - 2);\n      tlist.removeItem(N - 3);\n    // if we had [T][S][-T][M], then this was a skewed element being resized\n    // Thus, we simply combine it all into one matrix\n    } else if (N === 4 && tlist.getItem(N - 1).type === 1) {\n      operation = 3; // scale\n      m = transformListToTransform(tlist).matrix;\n      const e2t = svgroot.createSVGTransform();\n      e2t.setMatrix(m);\n      tlist.clear();\n      tlist.appendItem(e2t);\n      // reset the matrix so that the element is not re-mapped\n      m = svgroot.createSVGMatrix();\n    // if we had [R][T][S][-T][M], then this was a rotated matrix-element\n    // if we had [T1][M] we want to transform this into [M][T2]\n    // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] and we can push [T2]\n    // down to the element\n    } else if ((N === 1 || (N > 1 && tlist.getItem(1).type !== 3)) &&\n      tlist.getItem(0).type === 2) {\n      operation = 2; // translate\n      const oldxlate = tlist.getItem(0).matrix,\n        meq = transformListToTransform(tlist, 1).matrix,\n        meqInv = meq.inverse();\n      m = matrixMultiply(meqInv, oldxlate, meq);\n      tlist.removeItem(0);\n    // else if this child now has a matrix imposition (from a parent group)\n    // we might be able to simplify\n    } else if (N === 1 && tlist.getItem(0).type === 1 && !angle) {\n      // Remap all point-based elements\n      m = transformListToTransform(tlist).matrix;\n      switch (selected.tagName) {\n      case 'line':\n        changes = $(selected).attr(['x1', 'y1', 'x2', 'y2']);\n        // Fallthrough\n      case 'polyline':\n      case 'polygon':\n        changes.points = selected.getAttribute('points');\n        if (changes.points) {\n          const list = selected.points;\n          const len = list.numberOfItems;\n          changes.points = new Array(len);\n          for (let i = 0; i < len; ++i) {\n            const pt = list.getItem(i);\n            changes.points[i] = {x: pt.x, y: pt.y};\n          }\n        }\n        // Fallthrough\n      case 'path':\n        changes.d = selected.getAttribute('d');\n        operation = 1;\n        tlist.clear();\n        break;\n      default:\n        break;\n      }\n    // if it was a rotation, put the rotate back and return without a command\n    // (this function has zero work to do for a rotate())\n    } else {\n      operation = 4; // rotation\n      if (angle) {\n        const newRot = svgroot.createSVGTransform();\n        newRot.setRotate(angle, newcenter.x, newcenter.y);\n\n        if (tlist.numberOfItems) {\n          tlist.insertItemBefore(newRot, 0);\n        } else {\n          tlist.appendItem(newRot);\n        }\n      }\n      if (tlist.numberOfItems === 0) {\n        selected.removeAttribute('transform');\n      }\n      return null;\n    }\n\n    // if it was a translate or resize, we need to remap the element and absorb the xform\n    if (operation === 1 || operation === 2 || operation === 3) {\n      remapElement(selected, changes, m);\n    } // if we are remapping\n\n    // if it was a translate, put back the rotate at the new center\n    if (operation === 2) {\n      if (angle) {\n        if (!hasMatrixTransform(tlist)) {\n          newcenter = {\n            x: oldcenter.x + m.e,\n            y: oldcenter.y + m.f\n          };\n        }\n        const newRot = svgroot.createSVGTransform();\n        newRot.setRotate(angle, newcenter.x, newcenter.y);\n        if (tlist.numberOfItems) {\n          tlist.insertItemBefore(newRot, 0);\n        } else {\n          tlist.appendItem(newRot);\n        }\n      }\n      // We have special processing for tspans:  Tspans are not transformable\n      // but they can have x,y coordinates (sigh).  Thus, if this was a translate,\n      // on a text element, also translate any tspan children.\n      if (selected.tagName === 'text') {\n        const children = selected.childNodes;\n        let c = children.length;\n        while (c--) {\n          const child = children.item(c);\n          if (child.tagName === 'tspan') {\n            const tspanChanges = {\n              x: $(child).attr('x') || 0,\n              y: $(child).attr('y') || 0\n            };\n            remapElement(child, tspanChanges, m);\n          }\n        }\n      }\n    // [Rold][M][T][S][-T] became [Rold][M]\n    // we want it to be [Rnew][M][Tr] where Tr is the\n    // translation required to re-center it\n    // Therefore, [Tr] = [M_inv][Rnew_inv][Rold][M]\n    } else if (operation === 3 && angle) {\n      const m = transformListToTransform(tlist).matrix;\n      const roldt = svgroot.createSVGTransform();\n      roldt.setRotate(angle, oldcenter.x, oldcenter.y);\n      const rold = roldt.matrix;\n      const rnew = svgroot.createSVGTransform();\n      rnew.setRotate(angle, newcenter.x, newcenter.y);\n      const rnewInv = rnew.matrix.inverse();\n      const mInv = m.inverse();\n      const extrat = matrixMultiply(mInv, rnewInv, rold, m);\n\n      remapElement(selected, changes, extrat);\n      if (angle) {\n        if (tlist.numberOfItems) {\n          tlist.insertItemBefore(rnew, 0);\n        } else {\n          tlist.appendItem(rnew);\n        }\n      }\n    }\n  } // a non-group\n\n  // if the transform list has been emptied, remove it\n  if (tlist.numberOfItems === 0) {\n    selected.removeAttribute('transform');\n  }\n\n  batchCmd.addSubCommand(new ChangeElementCommand(selected, initial));\n\n  return batchCmd;\n};\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/sanitize.js",
    "content": "/**\n * Package: svgedit.sanitize\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2010 Alexis Deveria\n * Copyright(c) 2010 Jeff Schiller\n */\n\nimport {getReverseNS, NS} from './svgedit.js';\nimport {isGecko} from './browser.js';\nimport {getHref, setHref, getUrlFromAttr} from './svgutils.js';\n\nconst REVERSE_NS = getReverseNS();\n\n// this defines which elements and attributes that we support\nconst svgWhiteList_ = {\n  // SVG Elements\n  a: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'xlink:href', 'xlink:title'],\n  circle: ['class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'r', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],\n  clipPath: ['class', 'clipPathUnits', 'id'],\n  defs: [],\n  style: ['type'],\n  desc: [],\n  ellipse: ['class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],\n  feGaussianBlur: ['class', 'color-interpolation-filters', 'id', 'requiredFeatures', 'stdDeviation'],\n  filter: ['class', 'color-interpolation-filters', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'requiredFeatures', 'width', 'x', 'xlink:href', 'y'],\n  foreignObject: ['class', 'font-size', 'height', 'id', 'opacity', 'requiredFeatures', 'style', 'transform', 'width', 'x', 'y'],\n  g: ['class', 'clip-path', 'clip-rule', 'id', 'display', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-anchor'],\n  image: ['class', 'clip-path', 'clip-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:href', 'xlink:title', 'y'],\n  line: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'y1', 'y2'],\n  linearGradient: ['class', 'id', 'gradientTransform', 'gradientUnits', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'x1', 'x2', 'xlink:href', 'y1', 'y2'],\n  marker: ['id', 'class', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'systemLanguage', 'viewBox'],\n  mask: ['class', 'height', 'id', 'maskContentUnits', 'maskUnits', 'width', 'x', 'y'],\n  metadata: ['class', 'id'],\n  path: ['class', 'clip-path', 'clip-rule', 'd', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],\n  pattern: ['class', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:href', 'y'],\n  polygon: ['class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'class', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],\n  polyline: ['class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],\n  radialGradient: ['class', 'cx', 'cy', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'xlink:href'],\n  rect: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'width', 'x', 'y'],\n  stop: ['class', 'id', 'offset', 'requiredFeatures', 'stop-color', 'stop-opacity', 'style', 'systemLanguage'],\n  svg: ['class', 'clip-path', 'clip-rule', 'filter', 'id', 'height', 'mask', 'preserveAspectRatio', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xmlns', 'xmlns:se', 'xmlns:xlink', 'y'],\n  switch: ['class', 'id', 'requiredFeatures', 'systemLanguage'],\n  symbol: ['class', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'opacity', 'preserveAspectRatio', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'viewBox'],\n  text: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'transform', 'x', 'xml:space', 'y'],\n  textPath: ['class', 'id', 'method', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'transform', 'xlink:href'],\n  title: [],\n  tspan: ['class', 'clip-path', 'clip-rule', 'dx', 'dy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'rotate', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'textLength', 'transform', 'x', 'xml:space', 'y'],\n  use: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'transform', 'width', 'x', 'xlink:href', 'y'],\n\n  // MathML Elements\n  annotation: ['encoding'],\n  'annotation-xml': ['encoding'],\n  maction: ['actiontype', 'other', 'selection'],\n  math: ['class', 'id', 'display', 'xmlns'],\n  menclose: ['notation'],\n  merror: [],\n  mfrac: ['linethickness'],\n  mi: ['mathvariant'],\n  mmultiscripts: [],\n  mn: [],\n  mo: ['fence', 'lspace', 'maxsize', 'minsize', 'rspace', 'stretchy'],\n  mover: [],\n  mpadded: ['lspace', 'width', 'height', 'depth', 'voffset'],\n  mphantom: [],\n  mprescripts: [],\n  mroot: [],\n  mrow: ['xlink:href', 'xlink:type', 'xmlns:xlink'],\n  mspace: ['depth', 'height', 'width'],\n  msqrt: [],\n  mstyle: ['displaystyle', 'mathbackground', 'mathcolor', 'mathvariant', 'scriptlevel'],\n  msub: [],\n  msubsup: [],\n  msup: [],\n  mtable: ['align', 'columnalign', 'columnlines', 'columnspacing', 'displaystyle', 'equalcolumns', 'equalrows', 'frame', 'rowalign', 'rowlines', 'rowspacing', 'width'],\n  mtd: ['columnalign', 'columnspan', 'rowalign', 'rowspan'],\n  mtext: [],\n  mtr: ['columnalign', 'rowalign'],\n  munder: [],\n  munderover: [],\n  none: [],\n  semantics: []\n};\n\n// Produce a Namespace-aware version of svgWhitelist\nconst svgWhiteListNS_ = {};\nObject.entries(svgWhiteList_).forEach(function ([elt, atts]) {\n  const attNS = {};\n  Object.entries(atts).forEach(function ([i, att]) {\n    if (att.includes(':')) {\n      const v = att.split(':');\n      attNS[v[1]] = NS[(v[0]).toUpperCase()];\n    } else {\n      attNS[att] = att === 'xmlns' ? NS.XMLNS : null;\n    }\n  });\n  svgWhiteListNS_[elt] = attNS;\n});\n\n/**\n* Sanitizes the input node and its children\n* It only keeps what is allowed from our whitelist defined above\n* @param node - The DOM element to be checked (we'll also check its children)\n*/\nexport const sanitizeSvg = function (node) {\n  // Cleanup text nodes\n  if (node.nodeType === 3) { // 3 === TEXT_NODE\n    // Trim whitespace\n    node.nodeValue = node.nodeValue.replace(/^\\s+|\\s+$/g, '');\n    // Remove if empty\n    if (!node.nodeValue.length) {\n      node.parentNode.removeChild(node);\n    }\n  }\n\n  // We only care about element nodes.\n  // Automatically return for all non-element nodes, such as comments, etc.\n  if (node.nodeType !== 1) { // 1 == ELEMENT_NODE\n    return;\n  }\n\n  const doc = node.ownerDocument;\n  const parent = node.parentNode;\n  // can parent ever be null here?  I think the root node's parent is the document...\n  if (!doc || !parent) {\n    return;\n  }\n\n  const allowedAttrs = svgWhiteList_[node.nodeName];\n  const allowedAttrsNS = svgWhiteListNS_[node.nodeName];\n  // if this element is supported, sanitize it\n  if (typeof allowedAttrs !== 'undefined') {\n    const seAttrs = [];\n    let i = node.attributes.length;\n    while (i--) {\n      // if the attribute is not in our whitelist, then remove it\n      // could use jQuery's inArray(), but I don't know if that's any better\n      const attr = node.attributes.item(i);\n      const attrName = attr.nodeName;\n      const attrLocalName = attr.localName;\n      const attrNsURI = attr.namespaceURI;\n      // Check that an attribute with the correct localName in the correct namespace is on\n      // our whitelist or is a namespace declaration for one of our allowed namespaces\n      if (!(allowedAttrsNS.hasOwnProperty(attrLocalName) && attrNsURI === allowedAttrsNS[attrLocalName] && attrNsURI !== NS.XMLNS) &&\n        !(attrNsURI === NS.XMLNS && REVERSE_NS[attr.value])) {\n        // TODO(codedread): Programmatically add the se: attributes to the NS-aware whitelist.\n        // Bypassing the whitelist to allow se: prefixes.\n        // Is there a more appropriate way to do this?\n        if (attrName.startsWith('se:') || attrName.startsWith('data-')) {\n          seAttrs.push([attrName, attr.value]);\n        }\n        node.removeAttributeNS(attrNsURI, attrLocalName);\n      }\n\n      // Add spaces before negative signs where necessary\n      if (isGecko()) {\n        switch (attrName) {\n        case 'transform':\n        case 'gradientTransform':\n        case 'patternTransform':\n          const val = attr.value.replace(/(\\d)-/g, '$1 -');\n          node.setAttribute(attrName, val);\n          break;\n        }\n      }\n\n      // For the style attribute, rewrite it in terms of XML presentational attributes\n      if (attrName === 'style') {\n        const props = attr.value.split(';');\n        let p = props.length;\n        while (p--) {\n          const [name, val] = props[p].split(':');\n          const styleAttrName = (name || '').trim();\n          const styleAttrVal = (val || '').trim();\n          // Now check that this attribute is supported\n          if (allowedAttrs.includes(styleAttrName)) {\n            node.setAttribute(styleAttrName, styleAttrVal);\n          }\n        }\n        node.removeAttribute('style');\n      }\n    }\n\n    Object.values(seAttrs).forEach(function (attr) {\n      node.setAttributeNS(NS.SE, attr[0], attr[1]);\n    });\n\n    // for some elements that have a xlink:href, ensure the URI refers to a local element\n    // (but not for links)\n    const href = getHref(node);\n    if (href &&\n      ['filter', 'linearGradient', 'pattern',\n        'radialGradient', 'textPath', 'use'].includes(node.nodeName)) {\n      // TODO: we simply check if the first character is a #, is this bullet-proof?\n      if (href[0] !== '#') {\n        // remove the attribute (but keep the element)\n        setHref(node, '');\n        node.removeAttributeNS(NS.XLINK, 'href');\n      }\n    }\n\n    // Safari crashes on a <use> without a xlink:href, so we just remove the node here\n    if (node.nodeName === 'use' && !getHref(node)) {\n      parent.removeChild(node);\n      return;\n    }\n    // if the element has attributes pointing to a non-local reference,\n    // need to remove the attribute\n    Object.values(['clip-path', 'fill', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke'], function (attr) {\n      let val = node.getAttribute(attr);\n      if (val) {\n        val = getUrlFromAttr(val);\n        // simply check for first character being a '#'\n        if (val && val[0] !== '#') {\n          node.setAttribute(attr, '');\n          node.removeAttribute(attr);\n        }\n      }\n    });\n\n    // recurse to children\n    i = node.childNodes.length;\n    while (i--) { sanitizeSvg(node.childNodes.item(i)); }\n  // else (element not supported), remove it\n  } else {\n    // remove all children from this node and insert them before this node\n    // FIXME: in the case of animation elements this will hardly ever be correct\n    const children = [];\n    while (node.hasChildNodes()) {\n      children.push(parent.insertBefore(node.firstChild, node));\n    }\n\n    // remove this node from the document altogether\n    parent.removeChild(node);\n\n    // call sanitizeSvg on each of those children\n    let i = children.length;\n    while (i--) { sanitizeSvg(children[i]); }\n  }\n};\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/select.js",
    "content": "/* globals jQuery */\n/**\n * Package: svedit.select\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2010 Alexis Deveria\n * Copyright(c) 2010 Jeff Schiller\n */\n\nimport {isTouch, isWebkit} from './browser.js'; // , isOpera\nimport {getRotationAngle, getBBox, getStrokedBBox} from './svgutils.js';\nimport {transformListToTransform, transformBox, transformPoint} from './math.js';\nimport {getTransformList} from './svgtransformlist.js';\n\nconst $ = jQuery;\n\nlet svgFactory_;\nlet config_;\nlet selectorManager_; // A Singleton\nconst gripRadius = isTouch() ? 10 : 4;\n\n/**\n* Private class for DOM element selection boxes\n* @param id - integer to internally indentify the selector\n* @param elem - DOM element associated with this selector\n* @param bbox - Optional bbox to use for initialization (prevents duplicate getBBox call).\n*/\nexport class Selector {\n  constructor (id, elem, bbox) {\n    // this is the selector's unique number\n    this.id = id;\n\n    // this holds a reference to the element for which this selector is being used\n    this.selectedElement = elem;\n\n    // this is a flag used internally to track whether the selector is being used or not\n    this.locked = true;\n\n    // this holds a reference to the <g> element that holds all visual elements of the selector\n    this.selectorGroup = svgFactory_.createSVGElement({\n      element: 'g',\n      attr: {id: ('selectorGroup' + this.id)}\n    });\n\n    // this holds a reference to the path rect\n    this.selectorRect = this.selectorGroup.appendChild(\n      svgFactory_.createSVGElement({\n        element: 'path',\n        attr: {\n          id: ('selectedBox' + this.id),\n          fill: 'none',\n          stroke: '#22C',\n          'stroke-width': '1',\n          'stroke-dasharray': '5,5',\n          // need to specify this so that the rect is not selectable\n          style: 'pointer-events:none'\n        }\n      })\n    );\n\n    // this holds a reference to the grip coordinates for this selector\n    this.gripCoords = {\n      nw: null,\n      n: null,\n      ne: null,\n      e: null,\n      se: null,\n      s: null,\n      sw: null,\n      w: null\n    };\n\n    this.reset(this.selectedElement, bbox);\n  }\n\n  /**\n  * Used to reset the id and element that the selector is attached to\n  * @param e - DOM element associated with this selector\n  * @param bbox - Optional bbox to use for reset (prevents duplicate getBBox call).\n  */\n  reset (e, bbox) {\n    this.locked = true;\n    this.selectedElement = e;\n    this.resize(bbox);\n    this.selectorGroup.setAttribute('display', 'inline');\n  }\n\n  /**\n  * Updates cursors for corner grips on rotation so arrows point the right way\n  * @param {Number} angle - Float indicating current rotation angle in degrees\n  */\n  updateGripCursors (angle) {\n    let dir;\n    const dirArr = [];\n    let steps = Math.round(angle / 45);\n    if (steps < 0) { steps += 8; }\n    for (dir in selectorManager_.selectorGrips) {\n      dirArr.push(dir);\n    }\n    while (steps > 0) {\n      dirArr.push(dirArr.shift());\n      steps--;\n    }\n    let i = 0;\n    for (dir in selectorManager_.selectorGrips) {\n      selectorManager_.selectorGrips[dir].setAttribute('style', ('cursor:' + dirArr[i] + '-resize'));\n      i++;\n    }\n  }\n\n  /**\n  * Show the resize grips of this selector\n  *\n  * @param {Boolean} show - Indicates whether grips should be shown or not\n  */\n  showGrips (show) {\n    const bShow = show ? 'inline' : 'none';\n    selectorManager_.selectorGripsGroup.setAttribute('display', bShow);\n    const elem = this.selectedElement;\n    this.hasGrips = show;\n    if (elem && show) {\n      this.selectorGroup.appendChild(selectorManager_.selectorGripsGroup);\n      this.updateGripCursors(getRotationAngle(elem));\n    }\n  }\n\n  /**\n  * Updates the selector to match the element's size\n  * @param bbox - Optional bbox to use for resize (prevents duplicate getBBox call).\n  */\n  resize (bbox) {\n    const selectedBox = this.selectorRect,\n      mgr = selectorManager_,\n      selectedGrips = mgr.selectorGrips,\n      selected = this.selectedElement,\n      sw = selected.getAttribute('stroke-width'),\n      currentZoom = svgFactory_.getCurrentZoom();\n    let offset = 1 / currentZoom;\n    if (selected.getAttribute('stroke') !== 'none' && !isNaN(sw)) {\n      offset += (sw / 2);\n    }\n\n    const {tagName} = selected;\n    if (tagName === 'text') {\n      offset += 2 / currentZoom;\n    }\n\n    // loop and transform our bounding box until we reach our first rotation\n    const tlist = getTransformList(selected);\n    const m = transformListToTransform(tlist).matrix;\n\n    // This should probably be handled somewhere else, but for now\n    // it keeps the selection box correctly positioned when zoomed\n    m.e *= currentZoom;\n    m.f *= currentZoom;\n\n    if (!bbox) {\n      bbox = getBBox(selected);\n    }\n    // TODO: getBBox (previous line) already knows to call getStrokedBBox when tagName === 'g'. Remove this?\n    // TODO: getBBox doesn't exclude 'gsvg' and calls getStrokedBBox for any 'g'. Should getBBox be updated?\n    if (tagName === 'g' && !$.data(selected, 'gsvg')) {\n      // The bbox for a group does not include stroke vals, so we\n      // get the bbox based on its children.\n      const strokedBbox = getStrokedBBox([selected.childNodes]);\n      if (strokedBbox) {\n        bbox = strokedBbox;\n      }\n    }\n\n    // apply the transforms\n    const l = bbox.x, t = bbox.y, w = bbox.width, h = bbox.height;\n    bbox = {x: l, y: t, width: w, height: h};\n\n    // we need to handle temporary transforms too\n    // if skewed, get its transformed box, then find its axis-aligned bbox\n\n    // *\n    offset *= currentZoom;\n\n    const nbox = transformBox(l * currentZoom, t * currentZoom, w * currentZoom, h * currentZoom, m),\n      {aabox} = nbox;\n    let nbax = aabox.x - offset,\n      nbay = aabox.y - offset,\n      nbaw = aabox.width + (offset * 2),\n      nbah = aabox.height + (offset * 2);\n\n    // now if the shape is rotated, un-rotate it\n    const cx = nbax + nbaw / 2,\n      cy = nbay + nbah / 2;\n\n    const angle = getRotationAngle(selected);\n    if (angle) {\n      const rot = svgFactory_.svgRoot().createSVGTransform();\n      rot.setRotate(-angle, cx, cy);\n      const rotm = rot.matrix;\n      nbox.tl = transformPoint(nbox.tl.x, nbox.tl.y, rotm);\n      nbox.tr = transformPoint(nbox.tr.x, nbox.tr.y, rotm);\n      nbox.bl = transformPoint(nbox.bl.x, nbox.bl.y, rotm);\n      nbox.br = transformPoint(nbox.br.x, nbox.br.y, rotm);\n\n      // calculate the axis-aligned bbox\n      const {tl} = nbox;\n      let minx = tl.x,\n        miny = tl.y,\n        maxx = tl.x,\n        maxy = tl.y;\n\n      const {min, max} = Math;\n\n      minx = min(minx, min(nbox.tr.x, min(nbox.bl.x, nbox.br.x))) - offset;\n      miny = min(miny, min(nbox.tr.y, min(nbox.bl.y, nbox.br.y))) - offset;\n      maxx = max(maxx, max(nbox.tr.x, max(nbox.bl.x, nbox.br.x))) + offset;\n      maxy = max(maxy, max(nbox.tr.y, max(nbox.bl.y, nbox.br.y))) + offset;\n\n      nbax = minx;\n      nbay = miny;\n      nbaw = (maxx - minx);\n      nbah = (maxy - miny);\n    }\n\n    const dstr = 'M' + nbax + ',' + nbay +\n      ' L' + (nbax + nbaw) + ',' + nbay +\n      ' ' + (nbax + nbaw) + ',' + (nbay + nbah) +\n      ' ' + nbax + ',' + (nbay + nbah) + 'z';\n    selectedBox.setAttribute('d', dstr);\n\n    const xform = angle ? 'rotate(' + [angle, cx, cy].join(',') + ')' : '';\n    this.selectorGroup.setAttribute('transform', xform);\n\n    // TODO(codedread): Is this needed?\n    //  if (selected === selectedElements[0]) {\n    this.gripCoords = {\n      nw: [nbax, nbay],\n      ne: [nbax + nbaw, nbay],\n      sw: [nbax, nbay + nbah],\n      se: [nbax + nbaw, nbay + nbah],\n      n: [nbax + (nbaw) / 2, nbay],\n      w: [nbax, nbay + (nbah) / 2],\n      e: [nbax + nbaw, nbay + (nbah) / 2],\n      s: [nbax + (nbaw) / 2, nbay + nbah]\n    };\n    for (const dir in this.gripCoords) {\n      const coords = this.gripCoords[dir];\n      selectedGrips[dir].setAttribute('cx', coords[0]);\n      selectedGrips[dir].setAttribute('cy', coords[1]);\n    }\n\n    // we want to go 20 pixels in the negative transformed y direction, ignoring scale\n    mgr.rotateGripConnector.setAttribute('x1', nbax + (nbaw) / 2);\n    mgr.rotateGripConnector.setAttribute('y1', nbay);\n    mgr.rotateGripConnector.setAttribute('x2', nbax + (nbaw) / 2);\n    mgr.rotateGripConnector.setAttribute('y2', nbay - (gripRadius * 5));\n\n    mgr.rotateGrip.setAttribute('cx', nbax + (nbaw) / 2);\n    mgr.rotateGrip.setAttribute('cy', nbay - (gripRadius * 5));\n    // }\n  }\n}\n\n/**\n*\n*/\nexport class SelectorManager {\n  constructor () {\n    // this will hold the <g> element that contains all selector rects/grips\n    this.selectorParentGroup = null;\n\n    // this is a special rect that is used for multi-select\n    this.rubberBandBox = null;\n\n    // this will hold objects of type Selector (see above)\n    this.selectors = [];\n\n    // this holds a map of SVG elements to their Selector object\n    this.selectorMap = {};\n\n    // this holds a reference to the grip elements\n    this.selectorGrips = {\n      nw: null,\n      n: null,\n      ne: null,\n      e: null,\n      se: null,\n      s: null,\n      sw: null,\n      w: null\n    };\n\n    this.selectorGripsGroup = null;\n    this.rotateGripConnector = null;\n    this.rotateGrip = null;\n\n    this.initGroup();\n  }\n\n  /**\n  * Resets the parent selector group element\n  */\n  initGroup () {\n    // remove old selector parent group if it existed\n    if (this.selectorParentGroup && this.selectorParentGroup.parentNode) {\n      this.selectorParentGroup.parentNode.removeChild(this.selectorParentGroup);\n    }\n\n    // create parent selector group and add it to svgroot\n    this.selectorParentGroup = svgFactory_.createSVGElement({\n      element: 'g',\n      attr: {id: 'selectorParentGroup'}\n    });\n    this.selectorGripsGroup = svgFactory_.createSVGElement({\n      element: 'g',\n      attr: {display: 'none'}\n    });\n    this.selectorParentGroup.appendChild(this.selectorGripsGroup);\n    svgFactory_.svgRoot().appendChild(this.selectorParentGroup);\n\n    this.selectorMap = {};\n    this.selectors = [];\n    this.rubberBandBox = null;\n\n    // add the corner grips\n    for (const dir in this.selectorGrips) {\n      const grip = svgFactory_.createSVGElement({\n        element: 'circle',\n        attr: {\n          id: ('selectorGrip_resize_' + dir),\n          fill: '#22C',\n          r: gripRadius,\n          style: ('cursor:' + dir + '-resize'),\n          // This expands the mouse-able area of the grips making them\n          // easier to grab with the mouse.\n          // This works in Opera and WebKit, but does not work in Firefox\n          // see https://bugzilla.mozilla.org/show_bug.cgi?id=500174\n          'stroke-width': 2,\n          'pointer-events': 'all'\n        }\n      });\n\n      $.data(grip, 'dir', dir);\n      $.data(grip, 'type', 'resize');\n      this.selectorGrips[dir] = this.selectorGripsGroup.appendChild(grip);\n    }\n\n    // add rotator elems\n    this.rotateGripConnector = this.selectorGripsGroup.appendChild(\n      svgFactory_.createSVGElement({\n        element: 'line',\n        attr: {\n          id: ('selectorGrip_rotateconnector'),\n          stroke: '#22C',\n          'stroke-width': '1'\n        }\n      })\n    );\n\n    this.rotateGrip = this.selectorGripsGroup.appendChild(\n      svgFactory_.createSVGElement({\n        element: 'circle',\n        attr: {\n          id: 'selectorGrip_rotate',\n          fill: 'lime',\n          r: gripRadius,\n          stroke: '#22C',\n          'stroke-width': 2,\n          style: 'cursor:url(' + config_.imgPath + 'rotate.png) 12 12, auto;'\n        }\n      })\n    );\n    $.data(this.rotateGrip, 'type', 'rotate');\n\n    if ($('#canvasBackground').length) { return; }\n\n    const dims = config_.dimensions;\n    const canvasbg = svgFactory_.createSVGElement({\n      element: 'svg',\n      attr: {\n        id: 'canvasBackground',\n        width: dims[0],\n        height: dims[1],\n        x: 0,\n        y: 0,\n        overflow: (isWebkit() ? 'none' : 'visible'), // Chrome 7 has a problem with this when zooming out\n        style: 'pointer-events:none'\n      }\n    });\n\n    const rect = svgFactory_.createSVGElement({\n      element: 'rect',\n      attr: {\n        width: '100%',\n        height: '100%',\n        x: 0,\n        y: 0,\n        'stroke-width': 1,\n        stroke: '#000',\n        fill: '#FFF',\n        style: 'pointer-events:none'\n      }\n    });\n\n    // Both Firefox and WebKit are too slow with this filter region (especially at higher\n    // zoom levels) and Opera has at least one bug\n    // if (!isOpera()) rect.setAttribute('filter', 'url(#canvashadow)');\n    canvasbg.appendChild(rect);\n    svgFactory_.svgRoot().insertBefore(canvasbg, svgFactory_.svgContent());\n  }\n\n  /**\n  *\n  * @param elem - DOM element to get the selector for\n  * @param [bbox] - Optional bbox to use for reset (prevents duplicate getBBox call).\n  * @returns The selector based on the given element\n  */\n  requestSelector (elem, bbox) {\n    if (elem == null) { return null; }\n\n    const N = this.selectors.length;\n    // If we've already acquired one for this element, return it.\n    if (typeof this.selectorMap[elem.id] === 'object') {\n      this.selectorMap[elem.id].locked = true;\n      return this.selectorMap[elem.id];\n    }\n    for (let i = 0; i < N; ++i) {\n      if (this.selectors[i] && !this.selectors[i].locked) {\n        this.selectors[i].locked = true;\n        this.selectors[i].reset(elem, bbox);\n        this.selectorMap[elem.id] = this.selectors[i];\n        return this.selectors[i];\n      }\n    }\n    // if we reached here, no available selectors were found, we create one\n    this.selectors[N] = new Selector(N, elem, bbox);\n    this.selectorParentGroup.appendChild(this.selectors[N].selectorGroup);\n    this.selectorMap[elem.id] = this.selectors[N];\n    return this.selectors[N];\n  }\n\n  /**\n  * Removes the selector of the given element (hides selection box)\n  *\n  * @param elem - DOM element to remove the selector for\n  */\n  releaseSelector (elem) {\n    if (elem == null) { return; }\n    const N = this.selectors.length,\n      sel = this.selectorMap[elem.id];\n    if (!sel.locked) {\n      // TODO(codedread): Ensure this exists in this module.\n      console.log('WARNING! selector was released but was already unlocked');\n    }\n    for (let i = 0; i < N; ++i) {\n      if (this.selectors[i] && this.selectors[i] === sel) {\n        delete this.selectorMap[elem.id];\n        sel.locked = false;\n        sel.selectedElement = null;\n        sel.showGrips(false);\n\n        // remove from DOM and store reference in JS but only if it exists in the DOM\n        try {\n          sel.selectorGroup.setAttribute('display', 'none');\n        } catch (e) {}\n\n        break;\n      }\n    }\n  }\n\n  /**\n  * @returns The rubberBandBox DOM element. This is the rectangle drawn by\n  * the user for selecting/zooming\n  */\n  getRubberBandBox () {\n    if (!this.rubberBandBox) {\n      this.rubberBandBox = this.selectorParentGroup.appendChild(\n        svgFactory_.createSVGElement({\n          element: 'rect',\n          attr: {\n            id: 'selectorRubberBand',\n            fill: '#22C',\n            'fill-opacity': 0.15,\n            stroke: '#22C',\n            'stroke-width': 0.5,\n            display: 'none',\n            style: 'pointer-events:none'\n          }\n        })\n      );\n    }\n    return this.rubberBandBox;\n  }\n}\n\n/**\n * An object that creates SVG elements for the canvas.\n *\n * interface svgedit.select.SVGFactory {\n *   SVGElement createSVGElement(jsonMap);\n *   SVGSVGElement svgRoot();\n *   SVGSVGElement svgContent();\n *\n *   Number currentZoom();\n * }\n */\n\n/**\n * Initializes this module.\n *\n * @param config - An object containing configurable parameters (imgPath)\n * @param svgFactory - An object implementing the SVGFactory interface (see above).\n */\nexport const init = function (config, svgFactory) {\n  config_ = config;\n  svgFactory_ = svgFactory;\n  selectorManager_ = new SelectorManager();\n};\n\n/**\n *\n * @returns The SelectorManager instance.\n */\nexport const getSelectorManager = () => selectorManager_;\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/svgcanvas.js",
    "content": "/* eslint-disable indent */\n/* globals jQuery, jsPDF */\n/*\n * svgcanvas.js\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2010 Alexis Deveria\n * Copyright(c) 2010 Pavol Rusnak\n * Copyright(c) 2010 Jeff Schiller\n *\n */\n\n/* Dependencies:\n1. Also expects jQuery UI for `svgCanvasToString` and\n`convertToGroup` use of `:data()` selector\n*/\n\nimport './pathseg.js';\nimport canvg from './canvg/canvg.js';\nimport jqPluginSVG from './jquery-svg.js'; // Needed for SVG attribute setting and array form with `attr`\n\nimport * as draw from './draw.js';\nimport * as pathModule from './path.js';\nimport {sanitizeSvg} from './sanitize.js';\nimport {getReverseNS, NS} from './svgedit.js';\nimport {\n  text2xml, assignAttributes, cleanupElement, getElem, getUrlFromAttr,\n  findDefs, getHref, setHref, getRefElem, getRotationAngle, getPathBBox,\n  preventClickDefault, snapToGrid, walkTree, walkTreePost,\n  getBBoxOfElementAsPath, convertToPath, toXml, encode64, decode64,\n  buildJSPDFCallback, dataURLToObjectURL, createObjectURL,\n  buildCanvgCallback, getVisibleElements, executeAfterLoads,\n  init as utilsInit, getBBox as utilsGetBBox, getStrokedBBoxDefaultVisible\n} from './svgutils.js';\nimport * as history from './history.js';\nimport {\n  transformPoint, matrixMultiply, hasMatrixTransform, transformListToTransform,\n  getMatrix, snapToAngle, isIdentity, rectsIntersect, transformBox\n} from './math.js';\nimport {\n  convertToNum, convertAttrs, convertUnit, shortFloat, getTypeMap,\n  init as unitsInit\n} from './units.js';\nimport {\n  isGecko, isChrome, isIE, isWebkit, supportsNonScalingStroke, supportsGoodTextCharPos\n} from './browser.js'; // , supportsEditableText\nimport {\n  getTransformList, resetListMap,\n  SVGTransformList as SVGEditTransformList\n} from './svgtransformlist.js';\nimport {\n  remapElement,\n  init as coordsInit\n} from './coords.js';\nimport {\n  recalculateDimensions,\n  init as recalculateInit\n} from './recalculate.js';\nimport {\n  getSelectorManager,\n  init as selectInit\n} from './select.js';\n\nconst $ = jqPluginSVG(jQuery);\nconst {\n  MoveElementCommand, InsertElementCommand, RemoveElementCommand,\n  ChangeElementCommand, BatchCommand, UndoManager, HistoryEventTypes\n} = history;\n\nif (!window.console) {\n  window.console = {};\n  window.console.log = function (str) {};\n  window.console.dir = function (str) {};\n}\n\nif (window.opera) {\n  window.console.log = function (str) { opera.postError(str); };\n  window.console.dir = function (str) {};\n}\n\n/**\n* The main SvgCanvas class that manages all SVG-related functions\n* @param container - The container HTML element that should hold the SVG root element\n* @param {Object} config - An object that contains configuration data\n*/\nclass SvgCanvas {\n  constructor (container, config) {\n// Alias Namespace constants\n\n// Default configuration options\nconst curConfig = {\n  show_outside_canvas: true,\n  selectNew: true,\n  dimensions: [640, 480]\n};\n\n// Update config with new one if given\nif (config) {\n  $.extend(curConfig, config);\n}\n\n// Array with width/height of canvas\nconst {dimensions} = curConfig;\n\nconst canvas = this;\n\n// \"document\" element associated with the container (same as window.document using default svg-editor.js)\n// NOTE: This is not actually a SVG document, but an HTML document.\nconst svgdoc = container.ownerDocument;\n\n// This is a container for the document being edited, not the document itself.\nconst svgroot = svgdoc.importNode(\n  text2xml(\n    '<svg id=\"svgroot\" xmlns=\"' + NS.SVG + '\" xlinkns=\"' + NS.XLINK + '\" ' +\n      'width=\"' + dimensions[0] + '\" height=\"' + dimensions[1] + '\" x=\"' + dimensions[0] + '\" y=\"' + dimensions[1] + '\" overflow=\"visible\">' +\n      '<defs>' +\n        '<filter id=\"canvashadow\" filterUnits=\"objectBoundingBox\">' +\n          '<feGaussianBlur in=\"SourceAlpha\" stdDeviation=\"4\" result=\"blur\"/>' +\n          '<feOffset in=\"blur\" dx=\"5\" dy=\"5\" result=\"offsetBlur\"/>' +\n          '<feMerge>' +\n            '<feMergeNode in=\"offsetBlur\"/>' +\n            '<feMergeNode in=\"SourceGraphic\"/>' +\n          '</feMerge>' +\n        '</filter>' +\n      '</defs>' +\n    '</svg>'\n  ).documentElement,\n  true\n);\ncontainer.appendChild(svgroot);\n\n// The actual element that represents the final output SVG element\nlet svgcontent = svgdoc.createElementNS(NS.SVG, 'svg');\n\n// This function resets the svgcontent element while keeping it in the DOM.\nconst clearSvgContentElement = canvas.clearSvgContentElement = function () {\n  $(svgcontent).empty();\n\n  // TODO: Clear out all other attributes first?\n  $(svgcontent).attr({\n    id: 'svgcontent',\n    width: dimensions[0],\n    height: dimensions[1],\n    x: dimensions[0],\n    y: dimensions[1],\n    overflow: curConfig.show_outside_canvas ? 'visible' : 'hidden',\n    xmlns: NS.SVG,\n    'xmlns:se': NS.SE,\n    'xmlns:xlink': NS.XLINK\n  }).appendTo(svgroot);\n\n  // TODO: make this string optional and set by the client\n  const comment = svgdoc.createComment(' Created with SVG-edit - https://github.com/SVG-Edit/svgedit');\n  svgcontent.appendChild(comment);\n};\nclearSvgContentElement();\n\n// Prefix string for element IDs\nlet idprefix = 'svg_';\n\n/**\n* Changes the ID prefix to the given value\n* @param {String} p - String with the new prefix\n*/\ncanvas.setIdPrefix = function (p) {\n  idprefix = p;\n};\n\n// Current svgedit.draw.Drawing object\n// @type {svgedit.draw.Drawing}\ncanvas.current_drawing_ = new draw.Drawing(svgcontent, idprefix);\n\n/**\n* Returns the current Drawing.\n* @returns {svgedit.draw.Drawing}\n*/\nconst getCurrentDrawing = canvas.getCurrentDrawing = function () {\n  return canvas.current_drawing_;\n};\n\n// Float displaying the current zoom level (1 = 100%, .5 = 50%, etc)\nlet currentZoom = 1;\n\n// pointer to current group (for in-group editing)\nlet currentGroup = null;\n\n// Object containing data for the currently selected styles\nconst allProperties = {\n  shape: {\n    fill: (curConfig.initFill.color === 'none' ? '' : '#') + curConfig.initFill.color,\n    fill_paint: null,\n    fill_opacity: curConfig.initFill.opacity,\n    stroke: '#' + curConfig.initStroke.color,\n    stroke_paint: null,\n    stroke_opacity: curConfig.initStroke.opacity,\n    stroke_width: curConfig.initStroke.width,\n    stroke_dasharray: 'none',\n    stroke_linejoin: 'miter',\n    stroke_linecap: 'butt',\n    opacity: curConfig.initOpacity\n  }\n};\n\nallProperties.text = $.extend(true, {}, allProperties.shape);\n$.extend(allProperties.text, {\n  fill: '#000000',\n  stroke_width: curConfig.text && curConfig.text.stroke_width,\n  font_size: curConfig.text && curConfig.text.font_size,\n  font_family: curConfig.text && curConfig.text.font_family\n});\n\n// Current shape style properties\nconst curShape = allProperties.shape;\n\n// Array with all the currently selected elements\n// default size of 1 until it needs to grow bigger\nlet selectedElements = [];\n\nconst getJsonFromSvgElement = this.getJsonFromSvgElement = function (data) {\n  // Text node\n  if (data.nodeType === 3) return data.nodeValue;\n\n  const retval = {\n    element: data.tagName,\n    // namespace: nsMap[data.namespaceURI],\n    attr: {},\n    children: []\n  };\n\n  // Iterate attributes\n  for (let i = 0, attr; (attr = data.attributes[i]); i++) {\n    retval.attr[attr.name] = attr.value;\n  }\n\n  // Iterate children\n  for (let i = 0, node; (node = data.childNodes[i]); i++) {\n    retval.children[i] = getJsonFromSvgElement(node);\n  }\n\n  return retval;\n};\n\n/**\n* Create a new SVG element based on the given object keys/values and add it to the current layer\n* The element will be ran through cleanupElement before being returned\n*\n* @param data - Object with the following keys/values:\n* @param {String} data.element - tag name of the SVG element to create\n* @param {Object} data.attr - Has key-value attributes to assign to the new element\n* @param {Boolean} [data.curStyles] - Indicates whether current style attributes should be applied first\n* @param {Array} [data.children] - Data objects to be added recursively as children\n* @param {String} [data.namespace=\"http://www.w3.org/2000/svg\"] - Indicate a (non-SVG) namespace\n*\n* @returns The new element\n*/\nconst addSvgElementFromJson = this.addSvgElementFromJson = function (data) {\n  if (typeof data === 'string') return svgdoc.createTextNode(data);\n\n  let shape = getElem(data.attr.id);\n  // if shape is a path but we need to create a rect/ellipse, then remove the path\n  const currentLayer = getCurrentDrawing().getCurrentLayer();\n  if (shape && data.element !== shape.tagName) {\n    currentLayer.removeChild(shape);\n    shape = null;\n  }\n  if (!shape) {\n    const ns = data.namespace || NS.SVG;\n    shape = svgdoc.createElementNS(ns, data.element);\n    if (currentLayer) {\n      (currentGroup || currentLayer).appendChild(shape);\n    }\n  }\n  if (data.curStyles) {\n    assignAttributes(shape, {\n      fill: curShape.fill,\n      stroke: curShape.stroke,\n      'stroke-width': curShape.stroke_width,\n      'stroke-dasharray': curShape.stroke_dasharray,\n      'stroke-linejoin': curShape.stroke_linejoin,\n      'stroke-linecap': curShape.stroke_linecap,\n      'stroke-opacity': curShape.stroke_opacity,\n      'fill-opacity': curShape.fill_opacity,\n      opacity: curShape.opacity / 2,\n      style: 'pointer-events:inherit'\n    }, 100);\n  }\n  assignAttributes(shape, data.attr, 100);\n  cleanupElement(shape);\n\n  // Children\n  if (data.children) {\n    data.children.forEach(function (child) {\n      shape.appendChild(addSvgElementFromJson(child));\n    });\n  }\n\n  return shape;\n};\n\ncanvas.getTransformList = getTransformList;\n\ncanvas.matrixMultiply = matrixMultiply;\ncanvas.hasMatrixTransform = hasMatrixTransform;\ncanvas.transformListToTransform = transformListToTransform;\n\n// initialize from units.js\n// send in an object implementing the ElementContainer interface (see units.js)\nunitsInit({\n  getBaseUnit () { return curConfig.baseUnit; },\n  getElement: getElem,\n  getHeight () { return svgcontent.getAttribute('height') / currentZoom; },\n  getWidth () { return svgcontent.getAttribute('width') / currentZoom; },\n  getRoundDigits () { return saveOptions.round_digits; }\n});\n\ncanvas.convertToNum = convertToNum;\n\nconst getSVGContent = () => { return svgcontent; };\n\n/**\n* @returns {Array} the array with selected DOM elements\n*/\nconst getSelectedElements = this.getSelectedElems = function () {\n  return selectedElements;\n};\n\nconst pathActions = pathModule.pathActions;\n\nutilsInit({\n  pathActions, // Ok since not modifying\n  getSVGContent,\n  addSvgElementFromJson,\n  getSelectedElements,\n  getDOMDocument () { return svgdoc; },\n  getDOMContainer () { return container; },\n  getSVGRoot () { return svgroot; },\n  // TODO: replace this mostly with a way to get the current drawing.\n  getBaseUnit () { return curConfig.baseUnit; },\n  getSnappingStep () { return curConfig.snappingStep; }\n});\n\ncanvas.findDefs = findDefs;\ncanvas.getUrlFromAttr = getUrlFromAttr;\ncanvas.getHref = getHref;\ncanvas.setHref = setHref;\n/* const getBBox = */ canvas.getBBox = utilsGetBBox;\ncanvas.getRotationAngle = getRotationAngle;\ncanvas.getElem = getElem;\ncanvas.getRefElem = getRefElem;\ncanvas.assignAttributes = assignAttributes;\nthis.cleanupElement = cleanupElement;\n\nconst getGridSnapping = () => { return curConfig.gridSnapping; };\ncoordsInit({\n  getDrawing () { return getCurrentDrawing(); },\n  getSVGRoot () { return svgroot; },\n  getGridSnapping\n});\nthis.remapElement = remapElement;\n\nrecalculateInit({\n  getSVGRoot () { return svgroot; },\n  getStartTransform () { return startTransform; },\n  setStartTransform (transform) { startTransform = transform; }\n});\nthis.recalculateDimensions = recalculateDimensions;\n\n// import from sanitize.js\nconst nsMap = getReverseNS();\ncanvas.sanitizeSvg = sanitizeSvg;\n\n// Implement the svgedit.history.HistoryEventHandler interface.\nconst undoMgr = canvas.undoMgr = new UndoManager({\n  handleHistoryEvent (eventType, cmd) {\n    const EventTypes = HistoryEventTypes;\n    // TODO: handle setBlurOffsets.\n    if (eventType === EventTypes.BEFORE_UNAPPLY || eventType === EventTypes.BEFORE_APPLY) {\n      canvas.clearSelection();\n    } else if (eventType === EventTypes.AFTER_APPLY || eventType === EventTypes.AFTER_UNAPPLY) {\n      const elems = cmd.elements();\n      canvas.pathActions.clear();\n      call('changed', elems);\n      const cmdType = cmd.type();\n      const isApply = (eventType === EventTypes.AFTER_APPLY);\n      if (cmdType === MoveElementCommand.type()) {\n        const parent = isApply ? cmd.newParent : cmd.oldParent;\n        if (parent === svgcontent) {\n          draw.identifyLayers();\n        }\n      } else if (cmdType === InsertElementCommand.type() ||\n          cmdType === RemoveElementCommand.type()) {\n        if (cmd.parent === svgcontent) {\n          draw.identifyLayers();\n        }\n        if (cmdType === InsertElementCommand.type()) {\n          if (isApply) { restoreRefElems(cmd.elem); }\n        } else {\n          if (!isApply) { restoreRefElems(cmd.elem); }\n        }\n        if (cmd.elem.tagName === 'use') {\n          setUseData(cmd.elem);\n        }\n      } else if (cmdType === ChangeElementCommand.type()) {\n        // if we are changing layer names, re-identify all layers\n        if (cmd.elem.tagName === 'title' &&\n          cmd.elem.parentNode.parentNode === svgcontent\n        ) {\n          draw.identifyLayers();\n        }\n        const values = isApply ? cmd.newValues : cmd.oldValues;\n        // If stdDeviation was changed, update the blur.\n        if (values.stdDeviation) {\n          canvas.setBlurOffsets(cmd.elem.parentNode, values.stdDeviation);\n        }\n        // This is resolved in later versions of webkit, perhaps we should\n        // have a featured detection for correct 'use' behavior?\n        // ——————————\n        // Remove & Re-add hack for Webkit (issue 775)\n        // if (cmd.elem.tagName === 'use' && isWebkit()) {\n        //  const {elem} = cmd;\n        //  if (!elem.getAttribute('x') && !elem.getAttribute('y')) {\n        //    const parent = elem.parentNode;\n        //    const sib = elem.nextSibling;\n        //    parent.removeChild(elem);\n        //    parent.insertBefore(elem, sib);\n        //  }\n        // }\n      }\n    }\n  }\n});\nconst addCommandToHistory = function (cmd) {\n  canvas.undoMgr.addCommandToHistory(cmd);\n};\n\n/**\n* @returns The current zoom level\n*/\nconst getCurrentZoom = this.getZoom = function () { return currentZoom; };\n\n/**\n* This method rounds the incoming value to the nearest value based on the `currentZoom`\n* @param {Number} val\n* @returns Rounded value to nearest value based on `currentZoom`\n*/\nconst round = this.round = function (val) {\n  return parseInt(val * currentZoom, 10) / currentZoom;\n};\n\n// import from select.js\nselectInit(curConfig, {\n  createSVGElement (jsonMap) { return canvas.addSvgElementFromJson(jsonMap); },\n  svgRoot () { return svgroot; },\n  svgContent () { return svgcontent; },\n  getCurrentZoom\n});\n// this object manages selectors for us\nconst selectorManager = this.selectorManager = getSelectorManager();\n\nconst getNextId = canvas.getNextId = function () { return getCurrentDrawing().getNextId(); };\nconst getId = canvas.getId = function () { return getCurrentDrawing().getId(); };\n\n/**\n* Run the callback function associated with the given event\n* @param ev - String with the event name\n* @param arg - Argument to pass through to the callback function\n*/\nconst call = function (ev, arg) {\n  if (events[ev]) {\n    return events[ev](window, arg);\n  }\n};\n\n/**\n* Clears the selection. The 'selected' handler is then called.\n* @param {Boolean} [noCall] - When true does not call the \"selected\" handler\n*/\nconst clearSelection = function (noCall) {\n  selectedElements.map(function (elem) {\n    if (elem == null) return;\n\n    selectorManager.releaseSelector(elem);\n  });\n  selectedElements = [];\n\n  if (!noCall) { call('selected', selectedElements); }\n};\n\n/**\n* Adds a list of elements to the selection. The 'selected' handler is then called.\n* @param {Array} elemsToAdd - An array of DOM elements to add to the selection\n* @param {Boolean} showGrips - Indicates whether the resize grips should be shown\n*/\nconst addToSelection = function (elemsToAdd, showGrips) {\n  if (!elemsToAdd.length) { return; }\n  // find the first null in our selectedElements array\n\n  let j = 0;\n  while (j < selectedElements.length) {\n    if (selectedElements[j] == null) {\n      break;\n    }\n    ++j;\n  }\n\n  // now add each element consecutively\n  let i = elemsToAdd.length;\n  while (i--) {\n    let elem = elemsToAdd[i];\n    if (!elem) { continue; }\n    const bbox = utilsGetBBox(elem);\n    if (!bbox) { continue; }\n\n    if (elem.tagName === 'a' && elem.childNodes.length === 1) {\n      // Make \"a\" element's child be the selected element\n      elem = elem.firstChild;\n    }\n\n    // if it's not already there, add it\n    if (!selectedElements.includes(elem)) {\n      selectedElements[j] = elem;\n\n      // only the first selectedBBoxes element is ever used in the codebase these days\n      // if (j === 0) selectedBBoxes[0] = utilsGetBBox(elem);\n      j++;\n      const sel = selectorManager.requestSelector(elem, bbox);\n\n      if (selectedElements.length > 1) {\n        sel.showGrips(false);\n      }\n    }\n  }\n  call('selected', selectedElements);\n\n  if (showGrips || selectedElements.length === 1) {\n    selectorManager.requestSelector(selectedElements[0]).showGrips(true);\n  } else {\n    selectorManager.requestSelector(selectedElements[0]).showGrips(false);\n  }\n\n  // make sure the elements are in the correct order\n  // See: https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition\n\n  selectedElements.sort(function (a, b) {\n    if (a && b && a.compareDocumentPosition) {\n      return 3 - (b.compareDocumentPosition(a) & 6);\n    }\n    if (a == null) {\n      return 1;\n    }\n  });\n\n  // Make sure first elements are not null\n  while (selectedElements[0] == null) {\n    selectedElements.shift(0);\n  }\n};\n\nconst getOpacity = function () {\n  return curShape.opacity;\n};\n\n/**\n* Gets the desired element from a mouse event\n* @param evt - Event object from the mouse event\n* @returns DOM element we want\n*/\nconst getMouseTarget = this.getMouseTarget = function (evt) {\n  if (evt == null) {\n    return null;\n  }\n  let mouseTarget = evt.target;\n\n  // if it was a <use>, Opera and WebKit return the SVGElementInstance\n  if (mouseTarget.correspondingUseElement) { mouseTarget = mouseTarget.correspondingUseElement; }\n\n  // for foreign content, go up until we find the foreignObject\n  // WebKit browsers set the mouse target to the svgcanvas div\n  if ([NS.MATH, NS.HTML].includes(mouseTarget.namespaceURI) &&\n    mouseTarget.id !== 'svgcanvas'\n  ) {\n    while (mouseTarget.nodeName !== 'foreignObject') {\n      mouseTarget = mouseTarget.parentNode;\n      if (!mouseTarget) { return svgroot; }\n    }\n  }\n\n  // Get the desired mouseTarget with jQuery selector-fu\n  // If it's root-like, select the root\n  const currentLayer = getCurrentDrawing().getCurrentLayer();\n  if ([svgroot, container, svgcontent, currentLayer].includes(mouseTarget)) {\n    return svgroot;\n  }\n\n  const $target = $(mouseTarget);\n\n  // If it's a selection grip, return the grip parent\n  if ($target.closest('#selectorParentGroup').length) {\n    // While we could instead have just returned mouseTarget,\n    // this makes it easier to indentify as being a selector grip\n    return selectorManager.selectorParentGroup;\n  }\n\n  while (mouseTarget.parentNode !== (currentGroup || currentLayer)) {\n    mouseTarget = mouseTarget.parentNode;\n  }\n\n  //\n  // // go up until we hit a child of a layer\n  // while (mouseTarget.parentNode.parentNode.tagName == 'g') {\n  //   mouseTarget = mouseTarget.parentNode;\n  // }\n  // Webkit bubbles the mouse event all the way up to the div, so we\n  // set the mouseTarget to the svgroot like the other browsers\n  // if (mouseTarget.nodeName.toLowerCase() == 'div') {\n  //   mouseTarget = svgroot;\n  // }\n\n  return mouseTarget;\n};\n\ncanvas.pathActions = pathActions;\nfunction resetD (p) {\n  p.setAttribute('d', pathActions.convertPath(p));\n}\npathModule.init({\n  selectorManager, // Ok since not changing\n  canvas, // Ok since not changing\n  call,\n  resetD,\n  round,\n  clearSelection,\n  addToSelection,\n  addCommandToHistory,\n  remapElement,\n  addSvgElementFromJson,\n  getGridSnapping,\n  getOpacity,\n  getSelectedElements,\n  getContainer () {\n    return container;\n  },\n  setStarted (s) {\n    started = s;\n  },\n  getRubberBox () {\n    return rubberBox;\n  },\n  setRubberBox (rb) {\n    rubberBox = rb;\n    return rubberBox;\n  },\n  addPtsToSelection ({closedSubpath, grips}) {\n    // TODO: Correct this:\n    pathActions.canDeleteNodes = true;\n    pathActions.closed_subpath = closedSubpath;\n    call('pointsAdded', {closedSubpath, grips});\n    call('selected', grips);\n  },\n  endChanges ({cmd, elem}) {\n    addCommandToHistory(cmd);\n    call('changed', [elem]);\n  },\n  getCurrentZoom,\n  getId,\n  getNextId,\n  getMouseTarget,\n  getCurrentMode () {\n    return currentMode;\n  },\n  setCurrentMode (cm) {\n    currentMode = cm;\n    return currentMode;\n  },\n  getDrawnPath () {\n    return drawnPath;\n  },\n  setDrawnPath (dp) {\n    drawnPath = dp;\n    return drawnPath;\n  },\n  getSVGRoot () { return svgroot; }\n});\n\n// Interface strings, usually for title elements\nconst uiStrings = {};\n\nconst visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use';\nconst refAttrs = ['clip-path', 'fill', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke'];\n\nconst elData = $.data;\n\n// Animation element to change the opacity of any newly created element\nconst opacAni = document.createElementNS(NS.SVG, 'animate');\n$(opacAni).attr({\n  attributeName: 'opacity',\n  begin: 'indefinite',\n  dur: 1,\n  fill: 'freeze'\n}).appendTo(svgroot);\n\nconst restoreRefElems = function (elem) {\n  // Look for missing reference elements, restore any found\n  const attrs = $(elem).attr(refAttrs);\n  for (const o in attrs) {\n    const val = attrs[o];\n    if (val && val.startsWith('url(')) {\n      const id = getUrlFromAttr(val).substr(1);\n      const ref = getElem(id);\n      if (!ref) {\n        findDefs().appendChild(removedElements[id]);\n        delete removedElements[id];\n      }\n    }\n  }\n\n  const childs = elem.getElementsByTagName('*');\n\n  if (childs.length) {\n    for (let i = 0, l = childs.length; i < l; i++) {\n      restoreRefElems(childs[i]);\n    }\n  }\n};\n\n// (function () {\n// TODO For Issue 208: this is a start on a thumbnail\n//  const svgthumb = svgdoc.createElementNS(NS.SVG, 'use');\n//  svgthumb.setAttribute('width', '100');\n//  svgthumb.setAttribute('height', '100');\n//  setHref(svgthumb, '#svgcontent');\n//  svgroot.appendChild(svgthumb);\n// }());\n\n// Object to contain image data for raster images that were found encodable\nconst encodableImages = {},\n\n  // Object with save options\n  saveOptions = {round_digits: 5},\n\n  // Object with IDs for imported files, to see if one was already added\n  importIds = {},\n\n  // Current text style properties\n  curText = allProperties.text,\n\n  // Object to contain all included extensions\n  extensions = {},\n\n  // Map of deleted reference elements\n  removedElements = {};\n\nlet\n  // String with image URL of last loadable image\n  lastGoodImgUrl = curConfig.imgPath + 'logo.png',\n\n  // Boolean indicating whether or not a draw action has been started\n  started = false,\n\n  // String with an element's initial transform attribute value\n  startTransform = null,\n\n  // String indicating the current editor mode\n  currentMode = 'select',\n\n  // String with the current direction in which an element is being resized\n  currentResizeMode = 'none',\n\n  // Current general properties\n  curProperties = curShape,\n\n  // Array with selected elements' Bounding box object\n  // selectedBBoxes = new Array(1),\n\n  // The DOM element that was just selected\n  justSelected = null,\n\n  // DOM element for selection rectangle drawn by the user\n  rubberBox = null,\n\n  // Array of current BBoxes, used in getIntersectionList().\n  curBBoxes = [],\n\n  // Canvas point for the most recent right click\n  lastClickPoint = null;\n\n// Should this return an array by default, so extension results aren't overwritten?\nconst runExtensions = this.runExtensions = function (action, vars, returnArray) {\n  let result = returnArray ? [] : false;\n  $.each(extensions, function (name, opts) {\n    if (opts && action in opts) {\n      if (returnArray) {\n        result.push(opts[action](vars));\n      } else {\n        result = opts[action](vars);\n      }\n    }\n  });\n  return result;\n};\n\n/**\n* Add an extension to the editor\n* @param {String} name - String with the ID of the extension\n* @param {Function} extFunc - Function supplied by the extension with its data\n*/\nthis.addExtension = function (name, extFunc) {\n  let ext;\n  if (!(name in extensions)) {\n    // Provide private vars/funcs here. Is there a better way to do this?\n    const argObj = $.extend(canvas.getPrivateMethods(), {\n      svgroot,\n      svgcontent,\n      nonce: getCurrentDrawing().getNonce(),\n      selectorManager\n    });\n    if (typeof extFunc === 'function') {\n      ext = extFunc(argObj);\n    } else {\n      ext = extFunc;\n      if (ext.callback) {\n        ext.callback = ext.callback.bind(ext, argObj);\n      }\n    }\n    extensions[name] = ext;\n    call('extension_added', ext);\n  } else {\n    console.log('Cannot add extension \"' + name + '\", an extension by that name already exists.');\n  }\n};\n\n/**\n* This method sends back an array or a NodeList full of elements that\n* intersect the multi-select rubber-band-box on the currentLayer only.\n*\n* We brute-force getIntersectionList for browsers that do not support it (Firefox).\n*\n* Reference:\n* Firefox does not implement getIntersectionList(), see https://bugzilla.mozilla.org/show_bug.cgi?id=501421\n* @param rect\n* @returns {Array|NodeList} Bbox elements\n*/\nconst getIntersectionList = this.getIntersectionList = function (rect) {\n  if (rubberBox == null) { return null; }\n\n  const parent = currentGroup || getCurrentDrawing().getCurrentLayer();\n\n  let rubberBBox;\n  if (!rect) {\n    rubberBBox = rubberBox.getBBox();\n    const bb = svgcontent.createSVGRect();\n\n    for (const o in rubberBBox) {\n      bb[o] = rubberBBox[o] / currentZoom;\n    }\n    rubberBBox = bb;\n  } else {\n    rubberBBox = svgcontent.createSVGRect();\n    rubberBBox.x = rect.x;\n    rubberBBox.y = rect.y;\n    rubberBBox.width = rect.width;\n    rubberBBox.height = rect.height;\n  }\n\n  let resultList = null;\n  if (!isIE) {\n    if (typeof svgroot.getIntersectionList === 'function') {\n      // Offset the bbox of the rubber box by the offset of the svgcontent element.\n      rubberBBox.x += parseInt(svgcontent.getAttribute('x'), 10);\n      rubberBBox.y += parseInt(svgcontent.getAttribute('y'), 10);\n\n      resultList = svgroot.getIntersectionList(rubberBBox, parent);\n    }\n  }\n\n  if (resultList == null || typeof resultList.item !== 'function') {\n    resultList = [];\n\n    if (!curBBoxes.length) {\n      // Cache all bboxes\n      curBBoxes = getVisibleElementsAndBBoxes(parent);\n    }\n    let i = curBBoxes.length;\n    while (i--) {\n      if (!rubberBBox.width) { continue; }\n      if (rectsIntersect(rubberBBox, curBBoxes[i].bbox)) {\n        resultList.push(curBBoxes[i].elem);\n      }\n    }\n  }\n\n  // addToSelection expects an array, but it's ok to pass a NodeList\n  // because using square-bracket notation is allowed:\n  // https://www.w3.org/TR/DOM-Level-2-Core/ecma-script-binding.html\n  return resultList;\n};\n\nthis.getStrokedBBox = getStrokedBBoxDefaultVisible;\n\nthis.getVisibleElements = getVisibleElements;\n\n/**\n* Get all elements that have a BBox (excludes &lt;defs>, &lt;title>, etc).\n* Note that 0-opacity, off-screen etc elements are still considered \"visible\"\n* for this function\n* @param parent - The parent DOM element to search within\n* @returns {Array} An array with objects that include:\n* - elem - The element\n* - bbox - The element's BBox as retrieved from `getStrokedBBoxDefaultVisible`\n*/\nconst getVisibleElementsAndBBoxes = this.getVisibleElementsAndBBoxes = function (parent) {\n  if (!parent) {\n    parent = $(svgcontent).children(); // Prevent layers from being included\n  }\n  const contentElems = [];\n  $(parent).children().each(function (i, elem) {\n    if (elem.getBBox) {\n      contentElems.push({elem, bbox: getStrokedBBoxDefaultVisible([elem])});\n    }\n  });\n  return contentElems.reverse();\n};\n\n/**\n* Wrap an SVG element into a group element, mark the group as 'gsvg'\n* @param elem - SVG element to wrap\n*/\nconst groupSvgElem = this.groupSvgElem = function (elem) {\n  const g = document.createElementNS(NS.SVG, 'g');\n  elem.parentNode.replaceChild(g, elem);\n  $(g).append(elem).data('gsvg', elem)[0].id = getNextId();\n};\n\n// Set scope for these functions\n\n// Object to contain editor event names and callback functions\nconst events = {};\n\ncanvas.call = call;\n\n/**\n* Attaches a callback function to an event\n* @param {String} ev - String indicating the name of the event\n* @param {Function} f - The callback function to bind to the event\n* @returns The previous event\n*/\ncanvas.bind = function (ev, f) {\n  const old = events[ev];\n  events[ev] = f;\n  return old;\n};\n\n/**\n* Runs the SVG Document through the sanitizer and then updates its paths.\n* @param newDoc - The SVG DOM document\n*/\nthis.prepareSvg = function (newDoc) {\n  this.sanitizeSvg(newDoc.documentElement);\n\n  // convert paths into absolute commands\n  const paths = newDoc.getElementsByTagNameNS(NS.SVG, 'path');\n  for (let i = 0, len = paths.length; i < len; ++i) {\n    const path = paths[i];\n    path.setAttribute('d', pathActions.convertPath(path));\n    pathActions.fixEnd(path);\n  }\n};\n\n/**\n* Hack for Firefox bugs where text element features aren't updated or get\n* messed up. See issue 136 and issue 137.\n* This function clones the element and re-selects it\n* @todo Test for this bug on load and add it to \"support\" object instead of\n* browser sniffing\n* @param elem - The (text) DOM element to clone\n* @returns Cloned element\n*/\nconst ffClone = function (elem) {\n  if (!isGecko()) { return elem; }\n  const clone = elem.cloneNode(true);\n  elem.parentNode.insertBefore(clone, elem);\n  elem.parentNode.removeChild(elem);\n  selectorManager.releaseSelector(elem);\n  selectedElements[0] = clone;\n  selectorManager.requestSelector(clone).showGrips(true);\n  return clone;\n};\n\n// this.each is deprecated, if any extension used this it can be recreated by doing this:\n// $(canvas.getRootElem()).children().each(...)\n\n// this.each = function (cb) {\n//  $(svgroot).children().each(cb);\n// };\n\n/**\n* Removes any old rotations if present, prepends a new rotation at the\n* transformed center\n* @param val - The new rotation angle in degrees\n* @param {Boolean} preventUndo - Indicates whether the action should be undoable or not\n*/\nthis.setRotationAngle = function (val, preventUndo) {\n  // ensure val is the proper type\n  val = parseFloat(val);\n  const elem = selectedElements[0];\n  const oldTransform = elem.getAttribute('transform');\n  const bbox = utilsGetBBox(elem);\n  const cx = bbox.x + bbox.width / 2, cy = bbox.y + bbox.height / 2;\n  const tlist = getTransformList(elem);\n\n  // only remove the real rotational transform if present (i.e. at index=0)\n  if (tlist.numberOfItems > 0) {\n    const xform = tlist.getItem(0);\n    if (xform.type === 4) {\n      tlist.removeItem(0);\n    }\n  }\n  // find Rnc and insert it\n  if (val !== 0) {\n    const center = transformPoint(cx, cy, transformListToTransform(tlist).matrix);\n    const Rnc = svgroot.createSVGTransform();\n    Rnc.setRotate(val, center.x, center.y);\n    if (tlist.numberOfItems) {\n      tlist.insertItemBefore(Rnc, 0);\n    } else {\n      tlist.appendItem(Rnc);\n    }\n  } else if (tlist.numberOfItems === 0) {\n    elem.removeAttribute('transform');\n  }\n\n  if (!preventUndo) {\n    // we need to undo it, then redo it so it can be undo-able! :)\n    // TODO: figure out how to make changes to transform list undo-able cross-browser?\n    const newTransform = elem.getAttribute('transform');\n    elem.setAttribute('transform', oldTransform);\n    changeSelectedAttribute('transform', newTransform, selectedElements);\n    call('changed', selectedElements);\n  }\n  // const pointGripContainer = getElem('pathpointgrip_container');\n  // if (elem.nodeName === 'path' && pointGripContainer) {\n  //   pathActions.setPointContainerTransform(elem.getAttribute('transform'));\n  // }\n  const selector = selectorManager.requestSelector(selectedElements[0]);\n  selector.resize();\n  selector.updateGripCursors(val);\n};\n\n// Runs recalculateDimensions on the selected elements,\n// adding the changes to a single batch command\nconst recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = function () {\n  const text = (currentResizeMode === 'none' ? 'position' : 'size');\n  const batchCmd = new BatchCommand(text);\n\n  let i = selectedElements.length;\n  while (i--) {\n    const elem = selectedElements[i];\n    // if (getRotationAngle(elem) && !hasMatrixTransform(getTransformList(elem))) { continue; }\n    const cmd = recalculateDimensions(elem);\n    if (cmd) {\n      batchCmd.addSubCommand(cmd);\n    }\n  }\n\n  if (!batchCmd.isEmpty()) {\n    addCommandToHistory(batchCmd);\n    call('changed', selectedElements);\n  }\n};\n\n// Debug tool to easily see the current matrix in the browser's console\nconst logMatrix = function (m) {\n  console.log([m.a, m.b, m.c, m.d, m.e, m.f]);\n};\n\n// Root Current Transformation Matrix in user units\nlet rootSctm = null;\n\n/**\n* Group: Selection\n*/\n\nthis.clearSelection = clearSelection;\n\n// TODO: do we need to worry about selectedBBoxes here?\n\nthis.addToSelection = addToSelection;\n\n/**\n* Selects only the given elements, shortcut for clearSelection(); addToSelection()\n* @param {Array} elems - an array of DOM elements to be selected\n*/\nconst selectOnly = this.selectOnly = function (elems, showGrips) {\n  clearSelection(true);\n  addToSelection(elems, showGrips);\n};\n\n// TODO: could use slice here to make this faster?\n// TODO: should the 'selected' handler\n\n/**\n* Removes elements from the selection.\n* @param {Array} elemsToRemove - an array of elements to remove from selection\n*/\n/* const removeFromSelection = */ this.removeFromSelection = function (elemsToRemove) {\n  if (selectedElements[0] == null) { return; }\n  if (!elemsToRemove.length) { return; }\n\n  // find every element and remove it from our array copy\n  const newSelectedItems = [],\n    len = selectedElements.length;\n  for (let i = 0; i < len; ++i) {\n    const elem = selectedElements[i];\n    if (elem) {\n      // keep the item\n      if (!elemsToRemove.includes(elem)) {\n        newSelectedItems.push(elem);\n      } else { // remove the item and its selector\n        selectorManager.releaseSelector(elem);\n      }\n    }\n  }\n  // the copy becomes the master now\n  selectedElements = newSelectedItems;\n};\n\n// Clears the selection, then adds all elements in the current layer to the selection.\nthis.selectAllInCurrentLayer = function () {\n  const currentLayer = getCurrentDrawing().getCurrentLayer();\n  if (currentLayer) {\n    currentMode = 'select';\n    selectOnly($(currentGroup || currentLayer).children());\n  }\n};\n\nlet drawnPath = null;\n\n// Mouse events\n(function () {\nconst freehand = {\n  minx: null,\n  miny: null,\n  maxx: null,\n  maxy: null\n};\nconst THRESHOLD_DIST = 0.8,\n  STEP_COUNT = 10;\nlet dAttr = null,\n  startX = null,\n  startY = null,\n  rStartX = null,\n  rStartY = null,\n  initBbox = {},\n  sumDistance = 0,\n  controllPoint2 = {x: 0, y: 0},\n  controllPoint1 = {x: 0, y: 0},\n  start = {x: 0, y: 0},\n  end = {x: 0, y: 0},\n  bSpline = {x: 0, y: 0},\n  nextPos = {x: 0, y: 0},\n  parameter,\n  nextParameter;\n\nconst getBsplinePoint = function (t) {\n  const spline = {x: 0, y: 0},\n    p0 = controllPoint2,\n    p1 = controllPoint1,\n    p2 = start,\n    p3 = end,\n    S = 1.0 / 6.0,\n    t2 = t * t,\n    t3 = t2 * t;\n\n  const m = [\n    [-1, 3, -3, 1],\n    [3, -6, 3, 0],\n    [-3, 0, 3, 0],\n    [1, 4, 1, 0]\n  ];\n\n  spline.x = S * (\n    (p0.x * m[0][0] + p1.x * m[0][1] + p2.x * m[0][2] + p3.x * m[0][3]) * t3 +\n      (p0.x * m[1][0] + p1.x * m[1][1] + p2.x * m[1][2] + p3.x * m[1][3]) * t2 +\n      (p0.x * m[2][0] + p1.x * m[2][1] + p2.x * m[2][2] + p3.x * m[2][3]) * t +\n      (p0.x * m[3][0] + p1.x * m[3][1] + p2.x * m[3][2] + p3.x * m[3][3])\n  );\n  spline.y = S * (\n    (p0.y * m[0][0] + p1.y * m[0][1] + p2.y * m[0][2] + p3.y * m[0][3]) * t3 +\n      (p0.y * m[1][0] + p1.y * m[1][1] + p2.y * m[1][2] + p3.y * m[1][3]) * t2 +\n      (p0.y * m[2][0] + p1.y * m[2][1] + p2.y * m[2][2] + p3.y * m[2][3]) * t +\n      (p0.y * m[3][0] + p1.y * m[3][1] + p2.y * m[3][2] + p3.y * m[3][3])\n  );\n\n  return {\n    x: spline.x,\n    y: spline.y\n  };\n};\n// - when we are in a create mode, the element is added to the canvas\n// but the action is not recorded until mousing up\n// - when we are in select mode, select the element, remember the position\n// and do nothing else\nconst mouseDown = function (evt) {\n  if (canvas.spaceKey || evt.button === 1) { return; }\n\n  const rightClick = evt.button === 2;\n\n  if (evt.altKey) { // duplicate when dragging\n    canvas.cloneSelectedElements(0, 0);\n  }\n\n  rootSctm = $('#svgcontent g')[0].getScreenCTM().inverse();\n\n  const pt = transformPoint(evt.pageX, evt.pageY, rootSctm),\n    mouseX = pt.x * currentZoom,\n    mouseY = pt.y * currentZoom;\n\n  evt.preventDefault();\n\n  if (rightClick) {\n    currentMode = 'select';\n    lastClickPoint = pt;\n  }\n\n  // This would seem to be unnecessary...\n  // if (!['select', 'resize'].includes(currentMode)) {\n  //   setGradient();\n  // }\n\n  let x = mouseX / currentZoom,\n    y = mouseY / currentZoom;\n  let mouseTarget = getMouseTarget(evt);\n\n  if (mouseTarget.tagName === 'a' && mouseTarget.childNodes.length === 1) {\n    mouseTarget = mouseTarget.firstChild;\n  }\n\n  // realX/y ignores grid-snap value\n  const realX = x;\n  rStartX = startX = x;\n  const realY = y;\n  rStartY = startY = y;\n\n  if (curConfig.gridSnapping) {\n    x = snapToGrid(x);\n    y = snapToGrid(y);\n    startX = snapToGrid(startX);\n    startY = snapToGrid(startY);\n  }\n\n  // if it is a selector grip, then it must be a single element selected,\n  // set the mouseTarget to that and update the mode to rotate/resize\n\n  if (mouseTarget === selectorManager.selectorParentGroup && selectedElements[0] != null) {\n    const grip = evt.target;\n    const griptype = elData(grip, 'type');\n    // rotating\n    if (griptype === 'rotate') {\n      currentMode = 'rotate';\n    // resizing\n    } else if (griptype === 'resize') {\n      currentMode = 'resize';\n      currentResizeMode = elData(grip, 'dir');\n    }\n    mouseTarget = selectedElements[0];\n  }\n\n  startTransform = mouseTarget.getAttribute('transform');\n  let i, strokeW;\n  const tlist = getTransformList(mouseTarget);\n  switch (currentMode) {\n  case 'select':\n    started = true;\n    currentResizeMode = 'none';\n    if (rightClick) { started = false; }\n\n    if (mouseTarget !== svgroot) {\n      // if this element is not yet selected, clear selection and select it\n      if (!selectedElements.includes(mouseTarget)) {\n        // only clear selection if shift is not pressed (otherwise, add\n        // element to selection)\n        if (!evt.shiftKey) {\n          // No need to do the call here as it will be done on addToSelection\n          clearSelection(true);\n        }\n        addToSelection([mouseTarget]);\n        justSelected = mouseTarget;\n        pathActions.clear();\n      }\n      // else if it's a path, go into pathedit mode in mouseup\n\n      if (!rightClick) {\n        // insert a dummy transform so if the element(s) are moved it will have\n        // a transform to use for its translate\n        for (i = 0; i < selectedElements.length; ++i) {\n          if (selectedElements[i] == null) { continue; }\n          const slist = getTransformList(selectedElements[i]);\n          if (slist.numberOfItems) {\n            slist.insertItemBefore(svgroot.createSVGTransform(), 0);\n          } else {\n            slist.appendItem(svgroot.createSVGTransform());\n          }\n        }\n      }\n    } else if (!rightClick) {\n      clearSelection();\n      currentMode = 'multiselect';\n      if (rubberBox == null) {\n        rubberBox = selectorManager.getRubberBandBox();\n      }\n      rStartX *= currentZoom;\n      rStartY *= currentZoom;\n      // console.log('p',[evt.pageX, evt.pageY]);\n      // console.log('c',[evt.clientX, evt.clientY]);\n      // console.log('o',[evt.offsetX, evt.offsetY]);\n      // console.log('s',[startX, startY]);\n\n      assignAttributes(rubberBox, {\n        x: rStartX,\n        y: rStartY,\n        width: 0,\n        height: 0,\n        display: 'inline'\n      }, 100);\n    }\n    break;\n  case 'zoom':\n    started = true;\n    if (rubberBox == null) {\n      rubberBox = selectorManager.getRubberBandBox();\n    }\n    assignAttributes(rubberBox, {\n      x: realX * currentZoom,\n      y: realX * currentZoom,\n      width: 0,\n      height: 0,\n      display: 'inline'\n    }, 100);\n    break;\n  case 'resize':\n    started = true;\n    startX = x;\n    startY = y;\n\n    // Getting the BBox from the selection box, since we know we\n    // want to orient around it\n    initBbox = utilsGetBBox($('#selectedBox0')[0]);\n    const bb = {};\n    $.each(initBbox, function (key, val) {\n      bb[key] = val / currentZoom;\n    });\n    initBbox = bb;\n\n    // append three dummy transforms to the tlist so that\n    // we can translate,scale,translate in mousemove\n    const pos = getRotationAngle(mouseTarget) ? 1 : 0;\n\n    if (hasMatrixTransform(tlist)) {\n      tlist.insertItemBefore(svgroot.createSVGTransform(), pos);\n      tlist.insertItemBefore(svgroot.createSVGTransform(), pos);\n      tlist.insertItemBefore(svgroot.createSVGTransform(), pos);\n    } else {\n      tlist.appendItem(svgroot.createSVGTransform());\n      tlist.appendItem(svgroot.createSVGTransform());\n      tlist.appendItem(svgroot.createSVGTransform());\n\n      if (supportsNonScalingStroke()) {\n        // Handle crash for newer Chrome and Safari 6 (Mobile and Desktop):\n        // https://code.google.com/p/svg-edit/issues/detail?id=904\n        // Chromium issue: https://code.google.com/p/chromium/issues/detail?id=114625\n        // TODO: Remove this workaround once vendor fixes the issue\n        const iswebkit = isWebkit();\n\n        let delayedStroke;\n        if (iswebkit) {\n          delayedStroke = function (ele) {\n            const _stroke = ele.getAttributeNS(null, 'stroke');\n            ele.removeAttributeNS(null, 'stroke');\n            // Re-apply stroke after delay. Anything higher than 1 seems to cause flicker\n            if (_stroke !== null) setTimeout(function () { ele.setAttributeNS(null, 'stroke', _stroke); }, 0);\n          };\n        }\n        mouseTarget.style.vectorEffect = 'non-scaling-stroke';\n        if (iswebkit) { delayedStroke(mouseTarget); }\n\n        const all = mouseTarget.getElementsByTagName('*'),\n          len = all.length;\n        for (i = 0; i < len; i++) {\n          all[i].style.vectorEffect = 'non-scaling-stroke';\n          if (iswebkit) { delayedStroke(all[i]); }\n        }\n      }\n    }\n    break;\n  case 'fhellipse':\n  case 'fhrect':\n  case 'fhpath':\n    start.x = realX;\n    start.y = realY;\n    started = true;\n    dAttr = realX + ',' + realY + ' ';\n    strokeW = parseFloat(curShape.stroke_width) === 0 ? 1 : curShape.stroke_width;\n    addSvgElementFromJson({\n      element: 'polyline',\n      curStyles: true,\n      attr: {\n        points: dAttr,\n        id: getNextId(),\n        fill: 'none',\n        opacity: curShape.opacity / 2,\n        'stroke-linecap': 'round',\n        style: 'pointer-events:none'\n      }\n    });\n    freehand.minx = realX;\n    freehand.maxx = realX;\n    freehand.miny = realY;\n    freehand.maxy = realY;\n    break;\n  case 'image':\n    started = true;\n    const newImage = addSvgElementFromJson({\n      element: 'image',\n      attr: {\n        x,\n        y,\n        width: 0,\n        height: 0,\n        id: getNextId(),\n        opacity: curShape.opacity / 2,\n        style: 'pointer-events:inherit'\n      }\n    });\n    setHref(newImage, lastGoodImgUrl);\n    preventClickDefault(newImage);\n    break;\n  case 'square':\n    // FIXME: once we create the rect, we lose information that this was a square\n    // (for resizing purposes this could be important)\n    // Fallthrough\n  case 'rect':\n    started = true;\n    startX = x;\n    startY = y;\n    addSvgElementFromJson({\n      element: 'rect',\n      curStyles: true,\n      attr: {\n        x,\n        y,\n        width: 0,\n        height: 0,\n        id: getNextId(),\n        opacity: curShape.opacity / 2\n      }\n    });\n    break;\n  case 'line':\n    started = true;\n    strokeW = Number(curShape.stroke_width) === 0 ? 1 : curShape.stroke_width;\n    addSvgElementFromJson({\n      element: 'line',\n      curStyles: true,\n      attr: {\n        x1: x,\n        y1: y,\n        x2: x,\n        y2: y,\n        id: getNextId(),\n        stroke: curShape.stroke,\n        'stroke-width': strokeW,\n        'stroke-dasharray': curShape.stroke_dasharray,\n        'stroke-linejoin': curShape.stroke_linejoin,\n        'stroke-linecap': curShape.stroke_linecap,\n        'stroke-opacity': curShape.stroke_opacity,\n        fill: 'none',\n        opacity: curShape.opacity / 2,\n        style: 'pointer-events:none'\n      }\n    });\n    break;\n  case 'circle':\n    started = true;\n    addSvgElementFromJson({\n      element: 'circle',\n      curStyles: true,\n      attr: {\n        cx: x,\n        cy: y,\n        r: 0,\n        id: getNextId(),\n        opacity: curShape.opacity / 2\n      }\n    });\n    break;\n  case 'ellipse':\n    started = true;\n    addSvgElementFromJson({\n      element: 'ellipse',\n      curStyles: true,\n      attr: {\n        cx: x,\n        cy: y,\n        rx: 0,\n        ry: 0,\n        id: getNextId(),\n        opacity: curShape.opacity / 2\n      }\n    });\n    break;\n  case 'text':\n    started = true;\n    /* const newText = */ addSvgElementFromJson({\n      element: 'text',\n      curStyles: true,\n      attr: {\n        x,\n        y,\n        id: getNextId(),\n        fill: curText.fill,\n        'stroke-width': curText.stroke_width,\n        'font-size': curText.font_size,\n        'font-family': curText.font_family,\n        'text-anchor': 'middle',\n        'xml:space': 'preserve',\n        opacity: curShape.opacity\n      }\n    });\n    // newText.textContent = 'text';\n    break;\n  case 'path':\n    // Fall through\n  case 'pathedit':\n    startX *= currentZoom;\n    startY *= currentZoom;\n    pathActions.mouseDown(evt, mouseTarget, startX, startY);\n    started = true;\n    break;\n  case 'textedit':\n    startX *= currentZoom;\n    startY *= currentZoom;\n    textActions.mouseDown(evt, mouseTarget, startX, startY);\n    started = true;\n    break;\n  case 'rotate':\n    started = true;\n    // we are starting an undoable change (a drag-rotation)\n    canvas.undoMgr.beginUndoableChange('transform', selectedElements);\n    break;\n  default:\n    // This could occur in an extension\n    break;\n  }\n\n  const extResult = runExtensions('mouseDown', {\n    event: evt,\n    start_x: startX,\n    start_y: startY,\n    selectedElements\n  }, true);\n\n  $.each(extResult, function (i, r) {\n    if (r && r.started) {\n      started = true;\n    }\n  });\n};\n\n// in this function we do not record any state changes yet (but we do update\n// any elements that are still being created, moved or resized on the canvas)\nconst mouseMove = function (evt) {\n  if (!started) { return; }\n  if (evt.button === 1 || canvas.spaceKey) { return; }\n\n  let i, xya, c, cx, cy, dx, dy, len, angle, box,\n    selected = selectedElements[0];\n  const\n    pt = transformPoint(evt.pageX, evt.pageY, rootSctm),\n    mouseX = pt.x * currentZoom,\n    mouseY = pt.y * currentZoom,\n    shape = getElem(getId());\n\n  let realX = mouseX / currentZoom;\n  let x = realX;\n  let realY = mouseY / currentZoom;\n  let y = realY;\n\n  if (curConfig.gridSnapping) {\n    x = snapToGrid(x);\n    y = snapToGrid(y);\n  }\n\n  evt.preventDefault();\n  let tlist;\n  switch (currentMode) {\n  case 'select': {\n    // we temporarily use a translate on the element(s) being dragged\n    // this transform is removed upon mousing up and the element is\n    // relocated to the new location\n    if (selectedElements[0] !== null) {\n      dx = x - startX;\n      dy = y - startY;\n\n      if (curConfig.gridSnapping) {\n        dx = snapToGrid(dx);\n        dy = snapToGrid(dy);\n      }\n\n      if (evt.shiftKey) {\n        xya = snapToAngle(startX, startY, x, y);\n        ({x, y} = xya);\n      }\n\n      if (dx !== 0 || dy !== 0) {\n        len = selectedElements.length;\n        for (i = 0; i < len; ++i) {\n          selected = selectedElements[i];\n          if (selected == null) { break; }\n          // if (i === 0) {\n          //   const box = utilsGetBBox(selected);\n          //     selectedBBoxes[i].x = box.x + dx;\n          //     selectedBBoxes[i].y = box.y + dy;\n          // }\n\n          // update the dummy transform in our transform list\n          // to be a translate\n          const xform = svgroot.createSVGTransform();\n          tlist = getTransformList(selected);\n          // Note that if Webkit and there's no ID for this\n          // element, the dummy transform may have gotten lost.\n          // This results in unexpected behaviour\n\n          xform.setTranslate(dx, dy);\n          if (tlist.numberOfItems) {\n            tlist.replaceItem(xform, 0);\n          } else {\n            tlist.appendItem(xform);\n          }\n\n          // update our internal bbox that we're tracking while dragging\n          selectorManager.requestSelector(selected).resize();\n        }\n\n        call('transition', selectedElements);\n      }\n    }\n    break;\n  } case 'multiselect': {\n    realX *= currentZoom;\n    realY *= currentZoom;\n    assignAttributes(rubberBox, {\n      x: Math.min(rStartX, realX),\n      y: Math.min(rStartY, realY),\n      width: Math.abs(realX - rStartX),\n      height: Math.abs(realY - rStartY)\n    }, 100);\n\n    // for each selected:\n    // - if newList contains selected, do nothing\n    // - if newList doesn't contain selected, remove it from selected\n    // - for any newList that was not in selectedElements, add it to selected\n    const elemsToRemove = selectedElements.slice(), elemsToAdd = [],\n      newList = getIntersectionList();\n\n    // For every element in the intersection, add if not present in selectedElements.\n    len = newList.length;\n    for (i = 0; i < len; ++i) {\n      const intElem = newList[i];\n      // Found an element that was not selected before, so we should add it.\n      if (!selectedElements.includes(intElem)) {\n        elemsToAdd.push(intElem);\n      }\n      // Found an element that was already selected, so we shouldn't remove it.\n      const foundInd = elemsToRemove.indexOf(intElem);\n      if (foundInd !== -1) {\n        elemsToRemove.splice(foundInd, 1);\n      }\n    }\n\n    if (elemsToRemove.length > 0) {\n      canvas.removeFromSelection(elemsToRemove);\n    }\n\n    if (elemsToAdd.length > 0) {\n      canvas.addToSelection(elemsToAdd);\n    }\n\n    break;\n  } case 'resize': {\n    // we track the resize bounding box and translate/scale the selected element\n    // while the mouse is down, when mouse goes up, we use this to recalculate\n    // the shape's coordinates\n    tlist = getTransformList(selected);\n    const hasMatrix = hasMatrixTransform(tlist);\n    box = hasMatrix ? initBbox : utilsGetBBox(selected);\n    let left = box.x,\n      top = box.y,\n      {width, height} = box;\n    dx = (x - startX);\n    dy = (y - startY);\n\n    if (curConfig.gridSnapping) {\n      dx = snapToGrid(dx);\n      dy = snapToGrid(dy);\n      height = snapToGrid(height);\n      width = snapToGrid(width);\n    }\n\n    // if rotated, adjust the dx,dy values\n    angle = getRotationAngle(selected);\n    if (angle) {\n      const r = Math.sqrt(dx * dx + dy * dy),\n        theta = Math.atan2(dy, dx) - angle * Math.PI / 180.0;\n      dx = r * Math.cos(theta);\n      dy = r * Math.sin(theta);\n    }\n\n    // if not stretching in y direction, set dy to 0\n    // if not stretching in x direction, set dx to 0\n    if (!currentResizeMode.includes('n') && !currentResizeMode.includes('s')) {\n      dy = 0;\n    }\n    if (!currentResizeMode.includes('e') && !currentResizeMode.includes('w')) {\n      dx = 0;\n    }\n\n    let // ts = null,\n      tx = 0, ty = 0,\n      sy = height ? (height + dy) / height : 1,\n      sx = width ? (width + dx) / width : 1;\n    // if we are dragging on the north side, then adjust the scale factor and ty\n    if (currentResizeMode.includes('n')) {\n      sy = height ? (height - dy) / height : 1;\n      ty = height;\n    }\n\n    // if we dragging on the east side, then adjust the scale factor and tx\n    if (currentResizeMode.includes('w')) {\n      sx = width ? (width - dx) / width : 1;\n      tx = width;\n    }\n\n    // update the transform list with translate,scale,translate\n    const translateOrigin = svgroot.createSVGTransform(),\n      scale = svgroot.createSVGTransform(),\n      translateBack = svgroot.createSVGTransform();\n\n    if (curConfig.gridSnapping) {\n      left = snapToGrid(left);\n      tx = snapToGrid(tx);\n      top = snapToGrid(top);\n      ty = snapToGrid(ty);\n    }\n\n    translateOrigin.setTranslate(-(left + tx), -(top + ty));\n    if (evt.shiftKey) {\n      if (sx === 1) {\n        sx = sy;\n      } else { sy = sx; }\n    }\n    scale.setScale(sx, sy);\n\n    translateBack.setTranslate(left + tx, top + ty);\n    if (hasMatrix) {\n      const diff = angle ? 1 : 0;\n      tlist.replaceItem(translateOrigin, 2 + diff);\n      tlist.replaceItem(scale, 1 + diff);\n      tlist.replaceItem(translateBack, Number(diff));\n    } else {\n      const N = tlist.numberOfItems;\n      tlist.replaceItem(translateBack, N - 3);\n      tlist.replaceItem(scale, N - 2);\n      tlist.replaceItem(translateOrigin, N - 1);\n    }\n\n    selectorManager.requestSelector(selected).resize();\n\n    call('transition', selectedElements);\n\n    break;\n  } case 'zoom': {\n    realX *= currentZoom;\n    realY *= currentZoom;\n    assignAttributes(rubberBox, {\n      x: Math.min(rStartX * currentZoom, realX),\n      y: Math.min(rStartY * currentZoom, realY),\n      width: Math.abs(realX - rStartX * currentZoom),\n      height: Math.abs(realY - rStartY * currentZoom)\n    }, 100);\n    break;\n  } case 'text': {\n    assignAttributes(shape, {\n      x,\n      y\n    }, 1000);\n    break;\n  } case 'line': {\n    if (curConfig.gridSnapping) {\n      x = snapToGrid(x);\n      y = snapToGrid(y);\n    }\n\n    let x2 = x;\n    let y2 = y;\n\n    if (evt.shiftKey) {\n      xya = snapToAngle(startX, startY, x2, y2);\n      x2 = xya.x;\n      y2 = xya.y;\n    }\n\n    shape.setAttributeNS(null, 'x2', x2);\n    shape.setAttributeNS(null, 'y2', y2);\n    break;\n  } case 'foreignObject':\n    // fall through\n  case 'square':\n    // fall through\n  case 'rect':\n    // fall through\n  case 'image': {\n    const square = (currentMode === 'square') || evt.shiftKey;\n    let\n      w = Math.abs(x - startX),\n      h = Math.abs(y - startY);\n    let newX, newY;\n    if (square) {\n      w = h = Math.max(w, h);\n      newX = startX < x ? startX : startX - w;\n      newY = startY < y ? startY : startY - h;\n    } else {\n      newX = Math.min(startX, x);\n      newY = Math.min(startY, y);\n    }\n\n    if (curConfig.gridSnapping) {\n      w = snapToGrid(w);\n      h = snapToGrid(h);\n      newX = snapToGrid(newX);\n      newY = snapToGrid(newY);\n    }\n\n    assignAttributes(shape, {\n      width: w,\n      height: h,\n      x: newX,\n      y: newY\n    }, 1000);\n\n    break;\n  } case 'circle': {\n    c = $(shape).attr(['cx', 'cy']);\n    ({cx, cy} = c);\n    let rad = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));\n    if (curConfig.gridSnapping) {\n      rad = snapToGrid(rad);\n    }\n    shape.setAttributeNS(null, 'r', rad);\n    break;\n  } case 'ellipse': {\n    c = $(shape).attr(['cx', 'cy']);\n    ({cx, cy} = c);\n    if (curConfig.gridSnapping) {\n      x = snapToGrid(x);\n      cx = snapToGrid(cx);\n      y = snapToGrid(y);\n      cy = snapToGrid(cy);\n    }\n    shape.setAttributeNS(null, 'rx', Math.abs(x - cx));\n    const ry = Math.abs(evt.shiftKey ? (x - cx) : (y - cy));\n    shape.setAttributeNS(null, 'ry', ry);\n    break;\n  }\n  case 'fhellipse':\n  case 'fhrect': {\n    freehand.minx = Math.min(realX, freehand.minx);\n    freehand.maxx = Math.max(realX, freehand.maxx);\n    freehand.miny = Math.min(realY, freehand.miny);\n    freehand.maxy = Math.max(realY, freehand.maxy);\n  }\n  // Fallthrough\n  case 'fhpath': {\n    // dAttr += + realX + ',' + realY + ' ';\n    // shape.setAttributeNS(null, 'points', dAttr);\n    end.x = realX; end.y = realY;\n    if (controllPoint2.x && controllPoint2.y) {\n      for (i = 0; i < STEP_COUNT - 1; i++) {\n        parameter = i / STEP_COUNT;\n        nextParameter = (i + 1) / STEP_COUNT;\n        bSpline = getBsplinePoint(nextParameter);\n        nextPos = bSpline;\n        bSpline = getBsplinePoint(parameter);\n        sumDistance += Math.sqrt((nextPos.x - bSpline.x) * (nextPos.x - bSpline.x) + (nextPos.y - bSpline.y) * (nextPos.y - bSpline.y));\n        if (sumDistance > THRESHOLD_DIST) {\n          dAttr += +bSpline.x + ',' + bSpline.y + ' ';\n          shape.setAttributeNS(null, 'points', dAttr);\n          sumDistance -= THRESHOLD_DIST;\n        }\n      }\n    }\n    controllPoint2 = {x: controllPoint1.x, y: controllPoint1.y};\n    controllPoint1 = {x: start.x, y: start.y};\n    start = {x: end.x, y: end.y};\n    break;\n  // update path stretch line coordinates\n  } case 'path': {\n  }\n  // fall through\n  case 'pathedit': {\n    x *= currentZoom;\n    y *= currentZoom;\n\n    if (curConfig.gridSnapping) {\n      x = snapToGrid(x);\n      y = snapToGrid(y);\n      startX = snapToGrid(startX);\n      startY = snapToGrid(startY);\n    }\n    if (evt.shiftKey) {\n      const {path} = pathModule;\n      let x1, y1;\n      if (path) {\n        x1 = path.dragging ? path.dragging[0] : startX;\n        y1 = path.dragging ? path.dragging[1] : startY;\n      } else {\n        x1 = startX;\n        y1 = startY;\n      }\n      xya = snapToAngle(x1, y1, x, y);\n      ({x, y} = xya);\n    }\n\n    if (rubberBox && rubberBox.getAttribute('display') !== 'none') {\n      realX *= currentZoom;\n      realY *= currentZoom;\n      assignAttributes(rubberBox, {\n        x: Math.min(rStartX * currentZoom, realX),\n        y: Math.min(rStartY * currentZoom, realY),\n        width: Math.abs(realX - rStartX * currentZoom),\n        height: Math.abs(realY - rStartY * currentZoom)\n      }, 100);\n    }\n    pathActions.mouseMove(x, y);\n\n    break;\n  } case 'textedit': {\n    x *= currentZoom;\n    y *= currentZoom;\n    // if (rubberBox && rubberBox.getAttribute('display') !== 'none') {\n    //   assignAttributes(rubberBox, {\n    //     x: Math.min(startX, x),\n    //     y: Math.min(startY, y),\n    //     width: Math.abs(x - startX),\n    //     height: Math.abs(y - startY)\n    //   }, 100);\n    // }\n\n    textActions.mouseMove(mouseX, mouseY);\n\n    break;\n  } case 'rotate': {\n    box = utilsGetBBox(selected);\n    cx = box.x + box.width / 2;\n    cy = box.y + box.height / 2;\n    const m = getMatrix(selected),\n      center = transformPoint(cx, cy, m);\n    cx = center.x;\n    cy = center.y;\n    angle = ((Math.atan2(cy - y, cx - x) * (180 / Math.PI)) - 90) % 360;\n    if (curConfig.gridSnapping) {\n      angle = snapToGrid(angle);\n    }\n    if (evt.shiftKey) { // restrict rotations to nice angles (WRS)\n      const snap = 45;\n      angle = Math.round(angle / snap) * snap;\n    }\n\n    canvas.setRotationAngle(angle < -180 ? (360 + angle) : angle, true);\n    call('transition', selectedElements);\n    break;\n  } default:\n    break;\n  }\n\n  runExtensions('mouseMove', {\n    event: evt,\n    mouse_x: mouseX,\n    mouse_y: mouseY,\n    selected\n  });\n}; // mouseMove()\n\n// - in create mode, the element's opacity is set properly, we create an InsertElementCommand\n// and store it on the Undo stack\n// - in move/resize mode, the element's attributes which were affected by the move/resize are\n// identified, a ChangeElementCommand is created and stored on the stack for those attrs\n// this is done in when we recalculate the selected dimensions()\nconst mouseUp = function (evt) {\n  if (evt.button === 2) { return; }\n  const tempJustSelected = justSelected;\n  justSelected = null;\n  if (!started) { return; }\n  const pt = transformPoint(evt.pageX, evt.pageY, rootSctm),\n    mouseX = pt.x * currentZoom,\n    mouseY = pt.y * currentZoom,\n    x = mouseX / currentZoom,\n    y = mouseY / currentZoom;\n\n  let element = getElem(getId());\n  let keep = false;\n\n  const realX = x;\n  const realY = y;\n\n  // TODO: Make true when in multi-unit mode\n  const useUnit = false; // (curConfig.baseUnit !== 'px');\n  started = false;\n  let attrs, t;\n  switch (currentMode) {\n  // intentionally fall-through to select here\n  case 'resize':\n  case 'multiselect':\n    if (rubberBox != null) {\n      rubberBox.setAttribute('display', 'none');\n      curBBoxes = [];\n    }\n    currentMode = 'select';\n    // Fallthrough\n  case 'select':\n    if (selectedElements[0] != null) {\n      // if we only have one selected element\n      if (selectedElements[1] == null) {\n        // set our current stroke/fill properties to the element's\n        const selected = selectedElements[0];\n        switch (selected.tagName) {\n        case 'g':\n        case 'use':\n        case 'image':\n        case 'foreignObject':\n          break;\n        default:\n          curProperties.fill = selected.getAttribute('fill');\n          curProperties.fill_opacity = selected.getAttribute('fill-opacity');\n          curProperties.stroke = selected.getAttribute('stroke');\n          curProperties.stroke_opacity = selected.getAttribute('stroke-opacity');\n          curProperties.stroke_width = selected.getAttribute('stroke-width');\n          curProperties.stroke_dasharray = selected.getAttribute('stroke-dasharray');\n          curProperties.stroke_linejoin = selected.getAttribute('stroke-linejoin');\n          curProperties.stroke_linecap = selected.getAttribute('stroke-linecap');\n        }\n\n        if (selected.tagName === 'text') {\n          curText.font_size = selected.getAttribute('font-size');\n          curText.font_family = selected.getAttribute('font-family');\n        }\n        selectorManager.requestSelector(selected).showGrips(true);\n\n        // This shouldn't be necessary as it was done on mouseDown...\n        // call('selected', [selected]);\n      }\n      // always recalculate dimensions to strip off stray identity transforms\n      recalculateAllSelectedDimensions();\n      // if it was being dragged/resized\n      if (realX !== rStartX || realY !== rStartY) {\n        const len = selectedElements.length;\n        for (let i = 0; i < len; ++i) {\n          if (selectedElements[i] == null) { break; }\n          if (!selectedElements[i].firstChild) {\n            // Not needed for groups (incorrectly resizes elems), possibly not needed at all?\n            selectorManager.requestSelector(selectedElements[i]).resize();\n          }\n        }\n      // no change in position/size, so maybe we should move to pathedit\n      } else {\n        t = evt.target;\n        if (selectedElements[0].nodeName === 'path' && selectedElements[1] == null) {\n          pathActions.select(selectedElements[0]);\n        // if it was a path\n        // else, if it was selected and this is a shift-click, remove it from selection\n        } else if (evt.shiftKey) {\n          if (tempJustSelected !== t) {\n            canvas.removeFromSelection([t]);\n          }\n        }\n      } // no change in mouse position\n\n      // Remove non-scaling stroke\n      if (supportsNonScalingStroke()) {\n        const elem = selectedElements[0];\n        if (elem) {\n          elem.removeAttribute('style');\n          walkTree(elem, function (elem) {\n            elem.removeAttribute('style');\n          });\n        }\n      }\n    }\n    return;\n  case 'zoom':\n    if (rubberBox != null) {\n      rubberBox.setAttribute('display', 'none');\n    }\n    const factor = evt.shiftKey ? 0.5 : 2;\n    call('zoomed', {\n      x: Math.min(rStartX, realX),\n      y: Math.min(rStartY, realY),\n      width: Math.abs(realX - rStartX),\n      height: Math.abs(realY - rStartY),\n      factor\n    });\n    return;\n  case 'fhpath':\n    // Check that the path contains at least 2 points; a degenerate one-point path\n    // causes problems.\n    // Webkit ignores how we set the points attribute with commas and uses space\n    // to separate all coordinates, see https://bugs.webkit.org/show_bug.cgi?id=29870\n    sumDistance = 0;\n    controllPoint2 = {x: 0, y: 0};\n    controllPoint1 = {x: 0, y: 0};\n    start = {x: 0, y: 0};\n    end = {x: 0, y: 0};\n    const coords = element.getAttribute('points');\n    const commaIndex = coords.indexOf(',');\n    if (commaIndex >= 0) {\n      keep = coords.indexOf(',', commaIndex + 1) >= 0;\n    } else {\n      keep = coords.indexOf(' ', coords.indexOf(' ') + 1) >= 0;\n    }\n    if (keep) {\n      element = pathActions.smoothPolylineIntoPath(element);\n    }\n    break;\n  case 'line':\n    attrs = $(element).attr(['x1', 'x2', 'y1', 'y2']);\n    keep = (attrs.x1 !== attrs.x2 || attrs.y1 !== attrs.y2);\n    break;\n  case 'foreignObject':\n  case 'square':\n  case 'rect':\n  case 'image':\n    attrs = $(element).attr(['width', 'height']);\n    // Image should be kept regardless of size (use inherit dimensions later)\n    keep = (attrs.width !== '0' || attrs.height !== '0') || currentMode === 'image';\n    break;\n  case 'circle':\n    keep = (element.getAttribute('r') !== '0');\n    break;\n  case 'ellipse':\n    attrs = $(element).attr(['rx', 'ry']);\n    keep = (attrs.rx != null || attrs.ry != null);\n    break;\n  case 'fhellipse':\n    if ((freehand.maxx - freehand.minx) > 0 &&\n      (freehand.maxy - freehand.miny) > 0) {\n      element = addSvgElementFromJson({\n        element: 'ellipse',\n        curStyles: true,\n        attr: {\n          cx: (freehand.minx + freehand.maxx) / 2,\n          cy: (freehand.miny + freehand.maxy) / 2,\n          rx: (freehand.maxx - freehand.minx) / 2,\n          ry: (freehand.maxy - freehand.miny) / 2,\n          id: getId()\n        }\n      });\n      call('changed', [element]);\n      keep = true;\n    }\n    break;\n  case 'fhrect':\n    if ((freehand.maxx - freehand.minx) > 0 &&\n      (freehand.maxy - freehand.miny) > 0) {\n      element = addSvgElementFromJson({\n        element: 'rect',\n        curStyles: true,\n        attr: {\n          x: freehand.minx,\n          y: freehand.miny,\n          width: (freehand.maxx - freehand.minx),\n          height: (freehand.maxy - freehand.miny),\n          id: getId()\n        }\n      });\n      call('changed', [element]);\n      keep = true;\n    }\n    break;\n  case 'text':\n    keep = true;\n    selectOnly([element]);\n    textActions.start(element);\n    break;\n  case 'path':\n    // set element to null here so that it is not removed nor finalized\n    element = null;\n    // continue to be set to true so that mouseMove happens\n    started = true;\n\n    const res = pathActions.mouseUp(evt, element, mouseX, mouseY);\n    ({element} = res);\n    ({keep} = res);\n    break;\n  case 'pathedit':\n    keep = true;\n    element = null;\n    pathActions.mouseUp(evt);\n    break;\n  case 'textedit':\n    keep = false;\n    element = null;\n    textActions.mouseUp(evt, mouseX, mouseY);\n    break;\n  case 'rotate':\n    keep = true;\n    element = null;\n    currentMode = 'select';\n    const batchCmd = canvas.undoMgr.finishUndoableChange();\n    if (!batchCmd.isEmpty()) {\n      addCommandToHistory(batchCmd);\n    }\n    // perform recalculation to weed out any stray identity transforms that might get stuck\n    recalculateAllSelectedDimensions();\n    call('changed', selectedElements);\n    break;\n  default:\n    // This could occur in an extension\n    break;\n  }\n\n  const extResult = runExtensions('mouseUp', {\n    event: evt,\n    mouse_x: mouseX,\n    mouse_y: mouseY\n  }, true);\n\n  $.each(extResult, function (i, r) {\n    if (r) {\n      keep = r.keep || keep;\n      ({element} = r);\n      started = r.started || started;\n    }\n  });\n\n  if (!keep && element != null) {\n    getCurrentDrawing().releaseId(getId());\n    element.parentNode.removeChild(element);\n    element = null;\n\n    t = evt.target;\n\n    // if this element is in a group, go up until we reach the top-level group\n    // just below the layer groups\n    // TODO: once we implement links, we also would have to check for <a> elements\n    while (t && t.parentNode && t.parentNode.parentNode && t.parentNode.parentNode.tagName === 'g') {\n      t = t.parentNode;\n    }\n    // if we are not in the middle of creating a path, and we've clicked on some shape,\n    // then go to Select mode.\n    // WebKit returns <div> when the canvas is clicked, Firefox/Opera return <svg>\n    if ((currentMode !== 'path' || !drawnPath) &&\n      t && t.parentNode &&\n      t.parentNode.id !== 'selectorParentGroup' &&\n      t.id !== 'svgcanvas' && t.id !== 'svgroot'\n    ) {\n      // switch into \"select\" mode if we've clicked on an element\n      canvas.setMode('select');\n      selectOnly([t], true);\n    }\n  } else if (element != null) {\n    canvas.addedNew = true;\n\n    if (useUnit) { convertAttrs(element); }\n\n    let aniDur = 0.2;\n    let cAni;\n    if (opacAni.beginElement && parseFloat(element.getAttribute('opacity')) !== curShape.opacity) {\n      cAni = $(opacAni).clone().attr({\n        to: curShape.opacity,\n        dur: aniDur\n      }).appendTo(element);\n      try {\n        // Fails in FF4 on foreignObject\n        cAni[0].beginElement();\n      } catch (e) {}\n    } else {\n      aniDur = 0;\n    }\n\n    // Ideally this would be done on the endEvent of the animation,\n    // but that doesn't seem to be supported in Webkit\n    setTimeout(function () {\n      if (cAni) { cAni.remove(); }\n      element.setAttribute('opacity', curShape.opacity);\n      element.setAttribute('style', 'pointer-events:inherit');\n      cleanupElement(element);\n      if (currentMode === 'path') {\n        pathActions.toEditMode(element);\n      } else if (curConfig.selectNew) {\n        selectOnly([element], true);\n      }\n      // we create the insert command that is stored on the stack\n      // undo means to call cmd.unapply(), redo means to call cmd.apply()\n      addCommandToHistory(new InsertElementCommand(element));\n\n      call('changed', [element]);\n    }, aniDur * 1000);\n  }\n\n  startTransform = null;\n};\n\nconst dblClick = function (evt) {\n  const evtTarget = evt.target;\n  const parent = evtTarget.parentNode;\n\n  // Do nothing if already in current group\n  if (parent === currentGroup) { return; }\n\n  let mouseTarget = getMouseTarget(evt);\n  const {tagName} = mouseTarget;\n\n  if (tagName === 'text' && currentMode !== 'textedit') {\n    const pt = transformPoint(evt.pageX, evt.pageY, rootSctm);\n    textActions.select(mouseTarget, pt.x, pt.y);\n  }\n\n  if ((tagName === 'g' || tagName === 'a') &&\n    getRotationAngle(mouseTarget)\n  ) {\n    // TODO: Allow method of in-group editing without having to do\n    // this (similar to editing rotated paths)\n\n    // Ungroup and regroup\n    pushGroupProperties(mouseTarget);\n    mouseTarget = selectedElements[0];\n    clearSelection(true);\n  }\n  // Reset context\n  if (currentGroup) {\n    draw.leaveContext();\n  }\n\n  if ((parent.tagName !== 'g' && parent.tagName !== 'a') ||\n    parent === getCurrentDrawing().getCurrentLayer() ||\n    mouseTarget === selectorManager.selectorParentGroup\n  ) {\n    // Escape from in-group edit\n    return;\n  }\n  draw.setContext(mouseTarget);\n};\n\n// prevent links from being followed in the canvas\nconst handleLinkInCanvas = function (e) {\n  e.preventDefault();\n  return false;\n};\n\n// Added mouseup to the container here.\n// TODO(codedread): Figure out why after the Closure compiler, the window mouseup is ignored.\n$(container).mousedown(mouseDown).mousemove(mouseMove).click(handleLinkInCanvas).dblclick(dblClick).mouseup(mouseUp);\n// $(window).mouseup(mouseUp);\n\n// TODO(rafaelcastrocouto): User preference for shift key and zoom factor\n$(container).bind('mousewheel DOMMouseScroll', function (e) {\n  if (!e.shiftKey) { return; }\n\n  e.preventDefault();\n  const evt = e.originalEvent;\n\n  rootSctm = $('#svgcontent g')[0].getScreenCTM().inverse();\n\n  const workarea = $('#workarea');\n\tconst scrbar = 15;\n\tconst rulerwidth = curConfig.showRulers ? 16 : 0;\n\n\t// mouse relative to content area in content pixels\n\tconst pt = transformPoint(evt.pageX, evt.pageY, rootSctm);\n\n\t// full work area width in screen pixels\n\tconst editorFullW = workarea.width();\n\tconst editorFullH = workarea.height();\n\n\t// work area width minus scroll and ruler in screen pixels\n\tconst editorW = editorFullW - scrbar - rulerwidth;\n\tconst editorH = editorFullH - scrbar - rulerwidth;\n\n\t// work area width in content pixels\n\tconst workareaViewW = editorW * rootSctm.a;\n\tconst workareaViewH = editorH * rootSctm.d;\n\n\t// content offset from canvas in screen pixels\n\tconst wOffset = workarea.offset();\n\tconst wOffsetLeft = wOffset['left'] + rulerwidth;\n\tconst wOffsetTop = wOffset['top'] + rulerwidth;\n\n  const delta = (evt.wheelDelta) ? evt.wheelDelta : (evt.detail) ? -evt.detail : 0;\n  if (!delta) { return; }\n\n  let factor = Math.max(3 / 4, Math.min(4 / 3, (delta)));\n\n  let wZoom, hZoom;\n\tif (factor > 1) {\n\t\twZoom = Math.ceil(editorW / workareaViewW * factor * 100) / 100;\n\t\thZoom = Math.ceil(editorH / workareaViewH * factor * 100) / 100;\n\t} else {\n\t\twZoom = Math.floor(editorW / workareaViewW * factor * 100) / 100;\n\t\thZoom = Math.floor(editorH / workareaViewH * factor * 100) / 100;\n\t}\n\tlet zoomlevel = Math.min(wZoom, hZoom);\n\tzoomlevel = Math.min(10, Math.max(0.01, zoomlevel));\n\tif (zoomlevel === currentZoom) {\n\t\treturn;\n\t}\n\tfactor = zoomlevel / currentZoom;\n\n\t// top left of workarea in content pixels before zoom\n\tconst topLeftOld = transformPoint(wOffsetLeft, wOffsetTop, rootSctm);\n\n\t// top left of workarea in content pixels after zoom\n\tconst topLeftNew = {\n\t\tx: pt.x - (pt.x - topLeftOld.x) / factor,\n\t\ty: pt.y - (pt.y - topLeftOld.y) / factor\n\t};\n\n\t// top left of workarea in canvas pixels relative to content after zoom\n\tconst topLeftNewCanvas = {\n\t\tx: topLeftNew.x * zoomlevel,\n\t\ty: topLeftNew.y * zoomlevel\n\t};\n\n\t// new center in canvas pixels\n\tconst newCtr = {\n\t\tx: topLeftNewCanvas.x - rulerwidth + editorFullW / 2,\n\t\ty: topLeftNewCanvas.y - rulerwidth + editorFullH / 2\n\t};\n\n\tcanvas.setZoom(zoomlevel);\n\t$('#zoom').val((zoomlevel * 100).toFixed(1));\n\n\tcall('updateCanvas', {center: false, newCtr});\n\tcall('zoomDone');\n});\n}());\n\n/**\n* Group: Text edit functions\n* Functions relating to editing text elements\n*/\nconst textActions = canvas.textActions = (function () {\nlet curtext;\nlet textinput;\nlet cursor;\nlet selblock;\nlet blinker;\nlet chardata = [];\nlet textbb; // , transbb;\nlet matrix;\nlet lastX, lastY;\nlet allowDbl;\n\nfunction setCursor (index) {\n  const empty = (textinput.value === '');\n  $(textinput).focus();\n\n  if (!arguments.length) {\n    if (empty) {\n      index = 0;\n    } else {\n      if (textinput.selectionEnd !== textinput.selectionStart) { return; }\n      index = textinput.selectionEnd;\n    }\n  }\n\n  const charbb = chardata[index];\n  if (!empty) {\n    textinput.setSelectionRange(index, index);\n  }\n  cursor = getElem('text_cursor');\n  if (!cursor) {\n    cursor = document.createElementNS(NS.SVG, 'line');\n    assignAttributes(cursor, {\n      id: 'text_cursor',\n      stroke: '#333',\n      'stroke-width': 1\n    });\n    cursor = getElem('selectorParentGroup').appendChild(cursor);\n  }\n\n  if (!blinker) {\n    blinker = setInterval(function () {\n      const show = (cursor.getAttribute('display') === 'none');\n      cursor.setAttribute('display', show ? 'inline' : 'none');\n    }, 600);\n  }\n\n  const startPt = ptToScreen(charbb.x, textbb.y);\n  const endPt = ptToScreen(charbb.x, (textbb.y + textbb.height));\n\n  assignAttributes(cursor, {\n    x1: startPt.x,\n    y1: startPt.y,\n    x2: endPt.x,\n    y2: endPt.y,\n    visibility: 'visible',\n    display: 'inline'\n  });\n\n  if (selblock) { selblock.setAttribute('d', ''); }\n}\n\nfunction setSelection (start, end, skipInput) {\n  if (start === end) {\n    setCursor(end);\n    return;\n  }\n\n  if (!skipInput) {\n    textinput.setSelectionRange(start, end);\n  }\n\n  selblock = getElem('text_selectblock');\n  if (!selblock) {\n    selblock = document.createElementNS(NS.SVG, 'path');\n    assignAttributes(selblock, {\n      id: 'text_selectblock',\n      fill: 'green',\n      opacity: 0.5,\n      style: 'pointer-events:none'\n    });\n    getElem('selectorParentGroup').appendChild(selblock);\n  }\n\n  const startbb = chardata[start];\n  const endbb = chardata[end];\n\n  cursor.setAttribute('visibility', 'hidden');\n\n  const tl = ptToScreen(startbb.x, textbb.y),\n    tr = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y),\n    bl = ptToScreen(startbb.x, textbb.y + textbb.height),\n    br = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y + textbb.height);\n\n  const dstr = 'M' + tl.x + ',' + tl.y +\n    ' L' + tr.x + ',' + tr.y +\n    ' ' + br.x + ',' + br.y +\n    ' ' + bl.x + ',' + bl.y + 'z';\n\n  assignAttributes(selblock, {\n    d: dstr,\n    display: 'inline'\n  });\n}\n\nfunction getIndexFromPoint (mouseX, mouseY) {\n  // Position cursor here\n  const pt = svgroot.createSVGPoint();\n  pt.x = mouseX;\n  pt.y = mouseY;\n\n  // No content, so return 0\n  if (chardata.length === 1) { return 0; }\n  // Determine if cursor should be on left or right of character\n  let charpos = curtext.getCharNumAtPosition(pt);\n  if (charpos < 0) {\n    // Out of text range, look at mouse coords\n    charpos = chardata.length - 2;\n    if (mouseX <= chardata[0].x) {\n      charpos = 0;\n    }\n  } else if (charpos >= chardata.length - 2) {\n    charpos = chardata.length - 2;\n  }\n  const charbb = chardata[charpos];\n  const mid = charbb.x + (charbb.width / 2);\n  if (mouseX > mid) {\n    charpos++;\n  }\n  return charpos;\n}\n\nfunction setCursorFromPoint (mouseX, mouseY) {\n  setCursor(getIndexFromPoint(mouseX, mouseY));\n}\n\nfunction setEndSelectionFromPoint (x, y, apply) {\n  const i1 = textinput.selectionStart;\n  const i2 = getIndexFromPoint(x, y);\n\n  const start = Math.min(i1, i2);\n  const end = Math.max(i1, i2);\n  setSelection(start, end, !apply);\n}\n\nfunction screenToPt (xIn, yIn) {\n  const out = {\n    x: xIn,\n    y: yIn\n  };\n\n  out.x /= currentZoom;\n  out.y /= currentZoom;\n\n  if (matrix) {\n    const pt = transformPoint(out.x, out.y, matrix.inverse());\n    out.x = pt.x;\n    out.y = pt.y;\n  }\n\n  return out;\n}\n\nfunction ptToScreen (xIn, yIn) {\n  const out = {\n    x: xIn,\n    y: yIn\n  };\n\n  if (matrix) {\n    const pt = transformPoint(out.x, out.y, matrix);\n    out.x = pt.x;\n    out.y = pt.y;\n  }\n\n  out.x *= currentZoom;\n  out.y *= currentZoom;\n\n  return out;\n}\n\n/*\n// Not currently in use\nfunction hideCursor () {\n  if (cursor) {\n    cursor.setAttribute('visibility', 'hidden');\n  }\n}\n*/\n\nfunction selectAll (evt) {\n  setSelection(0, curtext.textContent.length);\n  $(this).unbind(evt);\n}\n\nfunction selectWord (evt) {\n  if (!allowDbl || !curtext) { return; }\n\n  const ept = transformPoint(evt.pageX, evt.pageY, rootSctm),\n    mouseX = ept.x * currentZoom,\n    mouseY = ept.y * currentZoom;\n  const pt = screenToPt(mouseX, mouseY);\n\n  const index = getIndexFromPoint(pt.x, pt.y);\n  const str = curtext.textContent;\n  const first = str.substr(0, index).replace(/[a-z0-9]+$/i, '').length;\n  const m = str.substr(index).match(/^[a-z0-9]+/i);\n  const last = (m ? m[0].length : 0) + index;\n  setSelection(first, last);\n\n  // Set tripleclick\n  $(evt.target).click(selectAll);\n  setTimeout(function () {\n    $(evt.target).unbind('click', selectAll);\n  }, 300);\n}\n\nreturn {\n  select (target, x, y) {\n    curtext = target;\n    textActions.toEditMode(x, y);\n  },\n  start (elem) {\n    curtext = elem;\n    textActions.toEditMode();\n  },\n  mouseDown (evt, mouseTarget, startX, startY) {\n    const pt = screenToPt(startX, startY);\n\n    textinput.focus();\n    setCursorFromPoint(pt.x, pt.y);\n    lastX = startX;\n    lastY = startY;\n\n    // TODO: Find way to block native selection\n  },\n  mouseMove (mouseX, mouseY) {\n    const pt = screenToPt(mouseX, mouseY);\n    setEndSelectionFromPoint(pt.x, pt.y);\n  },\n  mouseUp (evt, mouseX, mouseY) {\n    const pt = screenToPt(mouseX, mouseY);\n\n    setEndSelectionFromPoint(pt.x, pt.y, true);\n\n    // TODO: Find a way to make this work: Use transformed BBox instead of evt.target\n    // if (lastX === mouseX && lastY === mouseY\n    //   && !rectsIntersect(transbb, {x: pt.x, y: pt.y, width: 0, height: 0})) {\n    //   textActions.toSelectMode(true);\n    // }\n\n    if (\n      evt.target !== curtext &&\n      mouseX < lastX + 2 &&\n      mouseX > lastX - 2 &&\n      mouseY < lastY + 2 &&\n      mouseY > lastY - 2\n    ) {\n      textActions.toSelectMode(true);\n    }\n  },\n  setCursor,\n  toEditMode (x, y) {\n    allowDbl = false;\n    currentMode = 'textedit';\n    selectorManager.requestSelector(curtext).showGrips(false);\n    // Make selector group accept clicks\n    /* const selector = */ selectorManager.requestSelector(curtext); // Do we need this? Has side effect of setting lock, so keeping for now, but next line wasn't being used\n    // const sel = selector.selectorRect;\n\n    textActions.init();\n\n    $(curtext).css('cursor', 'text');\n\n    // if (supportsEditableText()) {\n    //   curtext.setAttribute('editable', 'simple');\n    //   return;\n    // }\n\n    if (!arguments.length) {\n      setCursor();\n    } else {\n      const pt = screenToPt(x, y);\n      setCursorFromPoint(pt.x, pt.y);\n    }\n\n    setTimeout(function () {\n      allowDbl = true;\n    }, 300);\n  },\n  toSelectMode (selectElem) {\n    currentMode = 'select';\n    clearInterval(blinker);\n    blinker = null;\n    if (selblock) { $(selblock).attr('display', 'none'); }\n    if (cursor) { $(cursor).attr('visibility', 'hidden'); }\n    $(curtext).css('cursor', 'move');\n\n    if (selectElem) {\n      clearSelection();\n      $(curtext).css('cursor', 'move');\n\n      call('selected', [curtext]);\n      addToSelection([curtext], true);\n    }\n    if (curtext && !curtext.textContent.length) {\n      // No content, so delete\n      canvas.deleteSelectedElements();\n    }\n\n    $(textinput).blur();\n\n    curtext = false;\n\n    // if (supportsEditableText()) {\n    //   curtext.removeAttribute('editable');\n    // }\n  },\n  setInputElem (elem) {\n    textinput = elem;\n    // $(textinput).blur(hideCursor);\n  },\n  clear () {\n    if (currentMode === 'textedit') {\n      textActions.toSelectMode();\n    }\n  },\n  init (inputElem) {\n    if (!curtext) { return; }\n    let i, end;\n    // if (supportsEditableText()) {\n    //   curtext.select();\n    //   return;\n    // }\n\n    if (!curtext.parentNode) {\n      // Result of the ffClone, need to get correct element\n      curtext = selectedElements[0];\n      selectorManager.requestSelector(curtext).showGrips(false);\n    }\n\n    const str = curtext.textContent;\n    const len = str.length;\n\n    const xform = curtext.getAttribute('transform');\n\n    textbb = utilsGetBBox(curtext);\n\n    matrix = xform ? getMatrix(curtext) : null;\n\n    chardata = [];\n    chardata.length = len;\n    textinput.focus();\n\n    $(curtext).unbind('dblclick', selectWord).dblclick(selectWord);\n\n    if (!len) {\n      end = {x: textbb.x + (textbb.width / 2), width: 0};\n    }\n\n    for (i = 0; i < len; i++) {\n      const start = curtext.getStartPositionOfChar(i);\n      end = curtext.getEndPositionOfChar(i);\n\n      if (!supportsGoodTextCharPos()) {\n        const offset = canvas.contentW * currentZoom;\n        start.x -= offset;\n        end.x -= offset;\n\n        start.x /= currentZoom;\n        end.x /= currentZoom;\n      }\n\n      // Get a \"bbox\" equivalent for each character. Uses the\n      // bbox data of the actual text for y, height purposes\n\n      // TODO: Decide if y, width and height are actually necessary\n      chardata[i] = {\n        x: start.x,\n        y: textbb.y, // start.y?\n        width: end.x - start.x,\n        height: textbb.height\n      };\n    }\n\n    // Add a last bbox for cursor at end of text\n    chardata.push({\n      x: end.x,\n      width: 0\n    });\n    setSelection(textinput.selectionStart, textinput.selectionEnd, true);\n  }\n};\n}());\n\n/**\n* Group: Serialization\n*/\n\n/**\n* Looks at DOM elements inside the <defs> to see if they are referred to,\n* removes them from the DOM if they are not.\n* @returns The amount of elements that were removed\n*/\nconst removeUnusedDefElems = this.removeUnusedDefElems = function () {\n  const defs = svgcontent.getElementsByTagNameNS(NS.SVG, 'defs');\n  if (!defs || !defs.length) { return 0; }\n\n  // if (!defs.firstChild) { return; }\n\n  const defelemUses = [];\n  let numRemoved = 0;\n  const attrs = ['fill', 'stroke', 'filter', 'marker-start', 'marker-mid', 'marker-end'];\n  const alen = attrs.length;\n\n  const allEls = svgcontent.getElementsByTagNameNS(NS.SVG, '*');\n  const allLen = allEls.length;\n\n  let i, j;\n  for (i = 0; i < allLen; i++) {\n    const el = allEls[i];\n    for (j = 0; j < alen; j++) {\n      const ref = getUrlFromAttr(el.getAttribute(attrs[j]));\n      if (ref) {\n        defelemUses.push(ref.substr(1));\n      }\n    }\n\n    // gradients can refer to other gradients\n    const href = getHref(el);\n    if (href && href.startsWith('#')) {\n      defelemUses.push(href.substr(1));\n    }\n  }\n\n  const defelems = $(defs).find('linearGradient, radialGradient, filter, marker, svg, symbol');\n  i = defelems.length;\n  while (i--) {\n    const defelem = defelems[i];\n    const {id} = defelem;\n    if (!defelemUses.includes(id)) {\n      // Not found, so remove (but remember)\n      removedElements[id] = defelem;\n      defelem.parentNode.removeChild(defelem);\n      numRemoved++;\n    }\n  }\n\n  return numRemoved;\n};\n\n/**\n* Main function to set up the SVG content for output\n* @returns {String} The SVG image for output\n*/\nthis.svgCanvasToString = function () {\n  // keep calling it until there are none to remove\n  while (removeUnusedDefElems() > 0) {}\n\n  pathActions.clear(true);\n\n  // Keep SVG-Edit comment on top\n  $.each(svgcontent.childNodes, function (i, node) {\n    if (i && node.nodeType === 8 && node.data.includes('Created with')) {\n      svgcontent.insertBefore(node, svgcontent.firstChild);\n    }\n  });\n\n  // Move out of in-group editing mode\n  if (currentGroup) {\n    draw.leaveContext();\n    selectOnly([currentGroup]);\n  }\n\n  const nakedSvgs = [];\n\n  // Unwrap gsvg if it has no special attributes (only id and style)\n  $(svgcontent).find('g:data(gsvg)').each(function () {\n    const attrs = this.attributes;\n    let len = attrs.length;\n    for (let i = 0; i < len; i++) {\n      if (attrs[i].nodeName === 'id' || attrs[i].nodeName === 'style') {\n        len--;\n      }\n    }\n    // No significant attributes, so ungroup\n    if (len <= 0) {\n      const svg = this.firstChild;\n      nakedSvgs.push(svg);\n      $(this).replaceWith(svg);\n    }\n  });\n  const output = this.svgToString(svgcontent, 0);\n\n  // Rewrap gsvg\n  if (nakedSvgs.length) {\n    $(nakedSvgs).each(function () {\n      groupSvgElem(this);\n    });\n  }\n\n  return output;\n};\n\n/**\n* Sub function ran on each SVG element to convert it to a string as desired\n* @param elem - The SVG element to convert\n* @param {Number} indent - Integer with the amount of spaces to indent this tag\n* @returns {String} The given element as an SVG tag\n*/\nthis.svgToString = function (elem, indent) {\n  const out = [];\n  const unit = curConfig.baseUnit;\n  const unitRe = new RegExp('^-?[\\\\d\\\\.]+' + unit + '$');\n\n  if (elem) {\n    cleanupElement(elem);\n    const attrs = Array.from(elem.attributes);\n    let i;\n    const childs = elem.childNodes;\n    attrs.sort((a, b) => a.name > b.name ? -1 : 1);\n\n    for (i = 0; i < indent; i++) { out.push(' '); }\n    out.push('<'); out.push(elem.nodeName);\n    if (elem.id === 'svgcontent') {\n      // Process root element separately\n      const res = getResolution();\n\n      const vb = '';\n      // TODO: Allow this by dividing all values by current baseVal\n      // Note that this also means we should properly deal with this on import\n      // if (curConfig.baseUnit !== 'px') {\n      //   const unit = curConfig.baseUnit;\n      //   const unitM = getTypeMap()[unit];\n      //   res.w = shortFloat(res.w / unitM);\n      //   res.h = shortFloat(res.h / unitM);\n      //   vb = ' viewBox=\"' + [0, 0, res.w, res.h].join(' ') + '\"';\n      //   res.w += unit;\n      //   res.h += unit;\n      // }\n\n      if (unit !== 'px') {\n        res.w = convertUnit(res.w, unit) + unit;\n        res.h = convertUnit(res.h, unit) + unit;\n      }\n\n      out.push(' width=\"' + res.w + '\" height=\"' + res.h + '\"' + vb + ' xmlns=\"' + NS.SVG + '\"');\n\n      const nsuris = {};\n\n      // Check elements for namespaces, add if found\n      $(elem).find('*').andSelf().each(function () {\n        // const el = this;\n        // for some elements have no attribute\n        const uri = this.namespaceURI;\n        if (uri && !nsuris[uri] && nsMap[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml') {\n          nsuris[uri] = true;\n          out.push(' xmlns:' + nsMap[uri] + '=\"' + uri + '\"');\n        }\n\n        $.each(this.attributes, function (i, attr) {\n          const uri = attr.namespaceURI;\n          if (uri && !nsuris[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml') {\n            nsuris[uri] = true;\n            out.push(' xmlns:' + nsMap[uri] + '=\"' + uri + '\"');\n          }\n        });\n      });\n\n      i = attrs.length;\n      const attrNames = ['width', 'height', 'xmlns', 'x', 'y', 'viewBox', 'id', 'overflow'];\n      while (i--) {\n        const attr = attrs[i];\n        const attrVal = toXml(attr.value);\n\n        // Namespaces have already been dealt with, so skip\n        if (attr.nodeName.startsWith('xmlns:')) { continue; }\n\n        // only serialize attributes we don't use internally\n        if (attrVal !== '' && !attrNames.includes(attr.localName)) {\n          if (!attr.namespaceURI || nsMap[attr.namespaceURI]) {\n            out.push(' ');\n            out.push(attr.nodeName); out.push('=\"');\n            out.push(attrVal); out.push('\"');\n          }\n        }\n      }\n    } else {\n      // Skip empty defs\n      if (elem.nodeName === 'defs' && !elem.firstChild) { return; }\n\n      const mozAttrs = ['-moz-math-font-style', '_moz-math-font-style'];\n      for (i = attrs.length - 1; i >= 0; i--) {\n        const attr = attrs[i];\n        let attrVal = toXml(attr.value);\n        // remove bogus attributes added by Gecko\n        if (mozAttrs.includes(attr.localName)) { continue; }\n        if (attrVal !== '') {\n          if (attrVal.startsWith('pointer-events')) { continue; }\n          if (attr.localName === 'class' && attrVal.startsWith('se_')) { continue; }\n          out.push(' ');\n          if (attr.localName === 'd') { attrVal = pathActions.convertPath(elem, true); }\n          if (!isNaN(attrVal)) {\n            attrVal = shortFloat(attrVal);\n          } else if (unitRe.test(attrVal)) {\n            attrVal = shortFloat(attrVal) + unit;\n          }\n\n          // Embed images when saving\n          if (saveOptions.apply &&\n            elem.nodeName === 'image' &&\n            attr.localName === 'href' &&\n            saveOptions.images &&\n            saveOptions.images === 'embed'\n          ) {\n            const img = encodableImages[attrVal];\n            if (img) { attrVal = img; }\n          }\n\n          // map various namespaces to our fixed namespace prefixes\n          // (the default xmlns attribute itself does not get a prefix)\n          if (!attr.namespaceURI || attr.namespaceURI === NS.SVG || nsMap[attr.namespaceURI]) {\n            out.push(attr.nodeName); out.push('=\"');\n            out.push(attrVal); out.push('\"');\n          }\n        }\n      }\n    }\n\n    if (elem.hasChildNodes()) {\n      out.push('>');\n      indent++;\n      let bOneLine = false;\n\n      for (i = 0; i < childs.length; i++) {\n        const child = childs.item(i);\n        switch (child.nodeType) {\n        case 1: // element node\n          out.push('\\n');\n          out.push(this.svgToString(childs.item(i), indent));\n          break;\n        case 3: // text node\n          const str = child.nodeValue.replace(/^\\s+|\\s+$/g, '');\n          if (str !== '') {\n            bOneLine = true;\n            out.push(String(toXml(str)));\n          }\n          break;\n        case 4: // cdata node\n          out.push('\\n');\n          out.push(new Array(indent + 1).join(' '));\n          out.push('<![CDATA[');\n          out.push(child.nodeValue);\n          out.push(']]>');\n          break;\n        case 8: // comment\n          out.push('\\n');\n          out.push(new Array(indent + 1).join(' '));\n          out.push('<!--');\n          out.push(child.data);\n          out.push('-->');\n          break;\n        } // switch on node type\n      }\n      indent--;\n      if (!bOneLine) {\n        out.push('\\n');\n        for (i = 0; i < indent; i++) { out.push(' '); }\n      }\n      out.push('</'); out.push(elem.nodeName); out.push('>');\n    } else {\n      out.push('/>');\n    }\n  }\n  return out.join('');\n}; // end svgToString()\n\n/**\n* Converts a given image file to a data URL when possible, then runs a given callback\n* @param {String} val - String with the path/URL of the image\n* @param {Function} callback - Optional function to run when image data is found, supplies the\n* result (data URL or false) as first parameter.\n*/\nthis.embedImage = function (val, callback) {\n  // load in the image and once it's loaded, get the dimensions\n  $(new Image()).load(function () {\n    // create a canvas the same size as the raster image\n    const canvas = document.createElement('canvas');\n    canvas.width = this.width;\n    canvas.height = this.height;\n    // load the raster image into the canvas\n    canvas.getContext('2d').drawImage(this, 0, 0);\n    // retrieve the data: URL\n    try {\n      let urldata = ';svgedit_url=' + encodeURIComponent(val);\n      urldata = canvas.toDataURL().replace(';base64', urldata + ';base64');\n      encodableImages[val] = urldata;\n    } catch (e) {\n      encodableImages[val] = false;\n    }\n    lastGoodImgUrl = val;\n    if (callback) { callback(encodableImages[val]); }\n  }).attr('src', val);\n};\n\n/**\n* Sets a given URL to be a \"last good image\" URL\n*/\nthis.setGoodImage = function (val) {\n  lastGoodImgUrl = val;\n};\n\n/**\n*\n*/\nthis.open = function () {\n  // Nothing by default, handled by optional widget/extension\n};\n\n/**\n* Serializes the current drawing into SVG XML text and returns it to the 'saved' handler.\n* This function also includes the XML prolog. Clients of the SvgCanvas bind their save\n* function to the 'saved' event.\n*/\nthis.save = function (opts) {\n  // remove the selected outline before serializing\n  clearSelection();\n  // Update save options if provided\n  if (opts) { $.extend(saveOptions, opts); }\n  saveOptions.apply = true;\n\n  // no need for doctype, see https://jwatt.org/svg/authoring/#doctype-declaration\n  const str = this.svgCanvasToString();\n  call('saved', str);\n};\n\n/**\n* Codes only is useful for locale-independent detection\n*/\nfunction getIssues () {\n  // remove the selected outline before serializing\n  clearSelection();\n\n  // Check for known CanVG issues\n  const issues = [];\n  const issueCodes = [];\n\n  // Selector and notice\n  const issueList = {\n    feGaussianBlur: uiStrings.exportNoBlur,\n    foreignObject: uiStrings.exportNoforeignObject,\n    '[stroke-dasharray]': uiStrings.exportNoDashArray\n  };\n  const content = $(svgcontent);\n\n  // Add font/text check if Canvas Text API is not implemented\n  if (!('font' in $('<canvas>')[0].getContext('2d'))) {\n    issueList.text = uiStrings.exportNoText;\n  }\n\n  $.each(issueList, function (sel, descr) {\n    if (content.find(sel).length) {\n      issueCodes.push(sel);\n      issues.push(descr);\n    }\n  });\n  return {issues, issueCodes};\n}\n\n/**\n* Generates a Data URL based on the current image, then calls \"exported\"\n* with an object including the string, image information, and any issues found\n* @param {String} [imgType=\"PNG\"]\n* @param {Number} [quality] Between 0 and 1\n* @param {String} [exportWindowName]\n* @param {Function} [cb]\n* @returns {Promise}\n*/\nthis.rasterExport = function (imgType, quality, exportWindowName, cb) {\n  const mimeType = 'image/' + imgType.toLowerCase();\n  const {issues, issueCodes} = getIssues();\n  const svg = this.svgCanvasToString();\n\n  return new Promise((resolve, reject) => {\n    buildCanvgCallback(function () {\n      const type = imgType || 'PNG';\n      if (!$('#export_canvas').length) {\n        $('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');\n      }\n      const c = $('#export_canvas')[0];\n      c.width = canvas.contentW;\n      c.height = canvas.contentH;\n\n      canvg(c, svg, {renderCallback () {\n        const dataURLType = (type === 'ICO' ? 'BMP' : type).toLowerCase();\n        const datauri = quality\n          ? c.toDataURL('image/' + dataURLType, quality)\n          : c.toDataURL('image/' + dataURLType);\n        let bloburl;\n        function done () {\n          const obj = {\n            datauri, bloburl, svg, issues, issueCodes, type: imgType,\n            mimeType, quality, exportWindowName\n          };\n          call('exported', obj);\n          if (cb) {\n            cb(obj);\n          }\n          resolve(obj);\n        }\n        if (c.toBlob) {\n          c.toBlob(function (blob) {\n            bloburl = createObjectURL(blob);\n            done();\n          }, mimeType, quality);\n          return;\n        }\n        bloburl = dataURLToObjectURL(datauri);\n        done();\n      }});\n    })();\n  });\n};\n\n/**\n* @param {String} exportWindowName\n* @param outputType Needed?\n* @param {Function} cb\n* @returns {Promise}\n*/\nthis.exportPDF = function (exportWindowName, outputType, cb) {\n  const that = this;\n  return new Promise((resolve, reject) => {\n    buildJSPDFCallback(function () {\n      const res = getResolution();\n      const orientation = res.w > res.h ? 'landscape' : 'portrait';\n      const unit = 'pt'; // curConfig.baseUnit; // We could use baseUnit, but that is presumably not intended for export purposes\n      const doc = jsPDF({\n        orientation,\n        unit,\n        format: [res.w, res.h]\n        // , compressPdf: true\n      }); // Todo: Give options to use predefined jsPDF formats like \"a4\", etc. from pull-down (with option to keep customizable)\n      const docTitle = getDocumentTitle();\n      doc.setProperties({\n        title: docTitle /* ,\n        subject: '',\n        author: '',\n        keywords: '',\n        creator: '' */\n      });\n      const {issues, issueCodes} = getIssues();\n      const svg = that.svgCanvasToString();\n      doc.addSVG(svg, 0, 0);\n\n      // doc.output('save'); // Works to open in a new\n      //  window; todo: configure this and other export\n      //  options to optionally work in this manner as\n      //  opposed to opening a new tab\n      const obj = {svg, issues, issueCodes, exportWindowName};\n      const method = outputType || 'dataurlstring';\n      obj[method] = doc.output(method);\n      if (cb) {\n        cb(obj);\n      }\n      resolve(obj);\n      call('exportedPDF', obj);\n    })();\n  });\n};\n\n/**\n* Returns the current drawing as raw SVG XML text.\n* @returns The current drawing as raw SVG XML text.\n*/\nthis.getSvgString = function () {\n  saveOptions.apply = false;\n  return this.svgCanvasToString();\n};\n\n/**\n* This function determines whether to use a nonce in the prefix, when\n* generating IDs for future documents in SVG-Edit.\n* @param {Boolean} [enableRandomization] If true, adds a nonce to the prefix. Thus\n* svgCanvas.randomizeIds() <==> svgCanvas.randomizeIds(true)\n*\n* if you're controlling SVG-Edit externally, and want randomized IDs, call\n* this BEFORE calling svgCanvas.setSvgString\n*/\nthis.randomizeIds = function (enableRandomization) {\n  if (arguments.length > 0 && enableRandomization === false) {\n    draw.randomizeIds(false, getCurrentDrawing());\n  } else {\n    draw.randomizeIds(true, getCurrentDrawing());\n  }\n};\n\n/**\n* Ensure each element has a unique ID\n* @param g - The parent element of the tree to give unique IDs\n*/\nconst uniquifyElems = this.uniquifyElems = function (g) {\n  const ids = {};\n  // TODO: Handle markers and connectors. These are not yet re-identified properly\n  // as their referring elements do not get remapped.\n  //\n  // <marker id='se_marker_end_svg_7'/>\n  // <polyline id='svg_7' se:connector='svg_1 svg_6' marker-end='url(#se_marker_end_svg_7)'/>\n  //\n  // Problem #1: if svg_1 gets renamed, we do not update the polyline's se:connector attribute\n  // Problem #2: if the polyline svg_7 gets renamed, we do not update the marker id nor the polyline's marker-end attribute\n  const refElems = ['filter', 'linearGradient', 'pattern', 'radialGradient', 'symbol', 'textPath', 'use'];\n\n  walkTree(g, function (n) {\n    // if it's an element node\n    if (n.nodeType === 1) {\n      // and the element has an ID\n      if (n.id) {\n        // and we haven't tracked this ID yet\n        if (!(n.id in ids)) {\n          // add this id to our map\n          ids[n.id] = {elem: null, attrs: [], hrefs: []};\n        }\n        ids[n.id].elem = n;\n      }\n\n      // now search for all attributes on this element that might refer\n      // to other elements\n      $.each(refAttrs, function (i, attr) {\n        const attrnode = n.getAttributeNode(attr);\n        if (attrnode) {\n          // the incoming file has been sanitized, so we should be able to safely just strip off the leading #\n          const url = getUrlFromAttr(attrnode.value),\n            refid = url ? url.substr(1) : null;\n          if (refid) {\n            if (!(refid in ids)) {\n              // add this id to our map\n              ids[refid] = {elem: null, attrs: [], hrefs: []};\n            }\n            ids[refid].attrs.push(attrnode);\n          }\n        }\n      });\n\n      // check xlink:href now\n      const href = getHref(n);\n      // TODO: what if an <image> or <a> element refers to an element internally?\n      if (href && refElems.includes(n.nodeName)) {\n        const refid = href.substr(1);\n        if (refid) {\n          if (!(refid in ids)) {\n            // add this id to our map\n            ids[refid] = {elem: null, attrs: [], hrefs: []};\n          }\n          ids[refid].hrefs.push(n);\n        }\n      }\n    }\n  });\n\n  // in ids, we now have a map of ids, elements and attributes, let's re-identify\n  for (const oldid in ids) {\n    if (!oldid) { continue; }\n    const {elem} = ids[oldid];\n    if (elem) {\n      const newid = getNextId();\n\n      // assign element its new id\n      elem.id = newid;\n\n      // remap all url() attributes\n      const {attrs} = ids[oldid];\n      let j = attrs.length;\n      while (j--) {\n        const attr = attrs[j];\n        attr.ownerElement.setAttribute(attr.name, 'url(#' + newid + ')');\n      }\n\n      // remap all href attributes\n      const hreffers = ids[oldid].hrefs;\n      let k = hreffers.length;\n      while (k--) {\n        const hreffer = hreffers[k];\n        setHref(hreffer, '#' + newid);\n      }\n    }\n  }\n};\n\n/**\n* Assigns reference data for each use element\n*/\nconst setUseData = this.setUseData = function (parent) {\n  let elems = $(parent);\n\n  if (parent.tagName !== 'use') {\n    elems = elems.find('use');\n  }\n\n  elems.each(function () {\n    const id = getHref(this).substr(1);\n    const refElem = getElem(id);\n    if (!refElem) { return; }\n    $(this).data('ref', refElem);\n    if (refElem.tagName === 'symbol' || refElem.tagName === 'svg') {\n      $(this).data('symbol', refElem).data('ref', refElem);\n    }\n  });\n};\n\n/**\n* Converts gradients from userSpaceOnUse to objectBoundingBox\n* @param elem\n*/\nconst convertGradients = this.convertGradients = function (elem) {\n  let elems = $(elem).find('linearGradient, radialGradient');\n  if (!elems.length && isWebkit()) {\n    // Bug in webkit prevents regular *Gradient selector search\n    elems = $(elem).find('*').filter(function () {\n      return (this.tagName.includes('Gradient'));\n    });\n  }\n\n  elems.each(function () {\n    const grad = this;\n    if ($(grad).attr('gradientUnits') === 'userSpaceOnUse') {\n      // TODO: Support more than one element with this ref by duplicating parent grad\n      const elems = $(svgcontent).find('[fill=\"url(#' + grad.id + ')\"],[stroke=\"url(#' + grad.id + ')\"]');\n      if (!elems.length) { return; }\n\n      // get object's bounding box\n      const bb = utilsGetBBox(elems[0]);\n\n      // This will occur if the element is inside a <defs> or a <symbol>,\n      // in which we shouldn't need to convert anyway.\n      if (!bb) { return; }\n\n      if (grad.tagName === 'linearGradient') {\n        const gCoords = $(grad).attr(['x1', 'y1', 'x2', 'y2']);\n\n        // If has transform, convert\n        const tlist = grad.gradientTransform.baseVal;\n        if (tlist && tlist.numberOfItems > 0) {\n          const m = transformListToTransform(tlist).matrix;\n          const pt1 = transformPoint(gCoords.x1, gCoords.y1, m);\n          const pt2 = transformPoint(gCoords.x2, gCoords.y2, m);\n\n          gCoords.x1 = pt1.x;\n          gCoords.y1 = pt1.y;\n          gCoords.x2 = pt2.x;\n          gCoords.y2 = pt2.y;\n          grad.removeAttribute('gradientTransform');\n        }\n\n        $(grad).attr({\n          x1: (gCoords.x1 - bb.x) / bb.width,\n          y1: (gCoords.y1 - bb.y) / bb.height,\n          x2: (gCoords.x2 - bb.x) / bb.width,\n          y2: (gCoords.y2 - bb.y) / bb.height\n        });\n        grad.removeAttribute('gradientUnits');\n      }\n      // else {\n      //   Note: radialGradient elements cannot be easily converted\n      //   because userSpaceOnUse will keep circular gradients, while\n      //   objectBoundingBox will x/y scale the gradient according to\n      //   its bbox.\n      //\n      //   For now we'll do nothing, though we should probably have\n      //   the gradient be updated as the element is moved, as\n      //   inkscape/illustrator do.\n      //\n      //   const gCoords = $(grad).attr(['cx', 'cy', 'r']);\n      //\n      //   $(grad).attr({\n      //     cx: (gCoords.cx - bb.x) / bb.width,\n      //     cy: (gCoords.cy - bb.y) / bb.height,\n      //     r: gCoords.r\n      //   });\n      //\n      //   grad.removeAttribute('gradientUnits');\n      // }\n    }\n  });\n};\n\n/**\n* Converts selected/given <use> or child SVG element to a group\n* @param elem\n*/\nconst convertToGroup = this.convertToGroup = function (elem) {\n  if (!elem) {\n    elem = selectedElements[0];\n  }\n  const $elem = $(elem);\n  const batchCmd = new BatchCommand();\n  let ts;\n\n  if ($elem.data('gsvg')) {\n    // Use the gsvg as the new group\n    const svg = elem.firstChild;\n    const pt = $(svg).attr(['x', 'y']);\n\n    $(elem.firstChild.firstChild).unwrap();\n    $(elem).removeData('gsvg');\n\n    const tlist = getTransformList(elem);\n    const xform = svgroot.createSVGTransform();\n    xform.setTranslate(pt.x, pt.y);\n    tlist.appendItem(xform);\n    recalculateDimensions(elem);\n    call('selected', [elem]);\n  } else if ($elem.data('symbol')) {\n    elem = $elem.data('symbol');\n\n    ts = $elem.attr('transform');\n    const pos = $elem.attr(['x', 'y']);\n\n    const vb = elem.getAttribute('viewBox');\n\n    if (vb) {\n      const nums = vb.split(' ');\n      pos.x -= +nums[0];\n      pos.y -= +nums[1];\n    }\n\n    // Not ideal, but works\n    ts += ' translate(' + (pos.x || 0) + ',' + (pos.y || 0) + ')';\n\n    const prev = $elem.prev();\n\n    // Remove <use> element\n    batchCmd.addSubCommand(new RemoveElementCommand($elem[0], $elem[0].nextSibling, $elem[0].parentNode));\n    $elem.remove();\n\n    // See if other elements reference this symbol\n    const hasMore = $(svgcontent).find('use:data(symbol)').length;\n\n    const g = svgdoc.createElementNS(NS.SVG, 'g');\n    const childs = elem.childNodes;\n\n    let i;\n    for (i = 0; i < childs.length; i++) {\n      g.appendChild(childs[i].cloneNode(true));\n    }\n\n    // Duplicate the gradients for Gecko, since they weren't included in the <symbol>\n    if (isGecko()) {\n      const dupeGrads = $(findDefs()).children('linearGradient,radialGradient,pattern').clone();\n      $(g).append(dupeGrads);\n    }\n\n    if (ts) {\n      g.setAttribute('transform', ts);\n    }\n\n    const parent = elem.parentNode;\n\n    uniquifyElems(g);\n\n    // Put the dupe gradients back into <defs> (after uniquifying them)\n    if (isGecko()) {\n      $(findDefs()).append($(g).find('linearGradient,radialGradient,pattern'));\n    }\n\n    // now give the g itself a new id\n    g.id = getNextId();\n\n    prev.after(g);\n\n    if (parent) {\n      if (!hasMore) {\n        // remove symbol/svg element\n        const {nextSibling} = elem;\n        parent.removeChild(elem);\n        batchCmd.addSubCommand(new RemoveElementCommand(elem, nextSibling, parent));\n      }\n      batchCmd.addSubCommand(new InsertElementCommand(g));\n    }\n\n    setUseData(g);\n\n    if (isGecko()) {\n      convertGradients(findDefs());\n    } else {\n      convertGradients(g);\n    }\n\n    // recalculate dimensions on the top-level children so that unnecessary transforms\n    // are removed\n    walkTreePost(g, function (n) {\n      try {\n        recalculateDimensions(n);\n      } catch (e) {\n        console.log(e);\n      }\n    });\n\n    // Give ID for any visible element missing one\n    $(g).find(visElems).each(function () {\n      if (!this.id) { this.id = getNextId(); }\n    });\n\n    selectOnly([g]);\n\n    const cm = pushGroupProperties(g, true);\n    if (cm) {\n      batchCmd.addSubCommand(cm);\n    }\n\n    addCommandToHistory(batchCmd);\n  } else {\n    console.log('Unexpected element to ungroup:', elem);\n  }\n};\n\n/**\n* This function sets the current drawing as the input SVG XML.\n* @param {String} xmlString - The SVG as XML text.\n* @param {Boolean} [preventUndo=false] - Indicates if we want to do the\n* changes without adding them to the undo stack - e.g. for initializing a\n* drawing on page load.\n* @returns {Boolean} This function returns false if the set was\n*     unsuccessful, true otherwise.\n*/\nthis.setSvgString = function (xmlString, preventUndo) {\n  try {\n    // convert string into XML document\n    const newDoc = text2xml(xmlString);\n    if (newDoc.firstElementChild &&\n      newDoc.firstElementChild.namespaceURI !== NS.SVG) {\n      return false;\n    }\n\n    this.prepareSvg(newDoc);\n\n    const batchCmd = new BatchCommand('Change Source');\n\n    // remove old svg document\n    const {nextSibling} = svgcontent;\n    const oldzoom = svgroot.removeChild(svgcontent);\n    batchCmd.addSubCommand(new RemoveElementCommand(oldzoom, nextSibling, svgroot));\n\n    // set new svg document\n    // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode()\n    if (svgdoc.adoptNode) {\n      svgcontent = svgdoc.adoptNode(newDoc.documentElement);\n    } else {\n      svgcontent = svgdoc.importNode(newDoc.documentElement, true);\n    }\n\n    svgroot.appendChild(svgcontent);\n    const content = $(svgcontent);\n\n    canvas.current_drawing_ = new draw.Drawing(svgcontent, idprefix);\n\n    // retrieve or set the nonce\n    const nonce = getCurrentDrawing().getNonce();\n    if (nonce) {\n      call('setnonce', nonce);\n    } else {\n      call('unsetnonce');\n    }\n\n    // change image href vals if possible\n    content.find('image').each(function () {\n      const image = this;\n      preventClickDefault(image);\n      const val = getHref(this);\n      if (val) {\n        if (val.startsWith('data:')) {\n          // Check if an SVG-edit data URI\n          const m = val.match(/svgedit_url=(.*?);/);\n          if (m) {\n            const url = decodeURIComponent(m[1]);\n            $(new Image()).load(function () {\n              image.setAttributeNS(NS.XLINK, 'xlink:href', url);\n            }).attr('src', url);\n          }\n        }\n        // Add to encodableImages if it loads\n        canvas.embedImage(val);\n      }\n    });\n\n    // Wrap child SVGs in group elements\n    content.find('svg').each(function () {\n      // Skip if it's in a <defs>\n      if ($(this).closest('defs').length) { return; }\n\n      uniquifyElems(this);\n\n      // Check if it already has a gsvg group\n      const pa = this.parentNode;\n      if (pa.childNodes.length === 1 && pa.nodeName === 'g') {\n        $(pa).data('gsvg', this);\n        pa.id = pa.id || getNextId();\n      } else {\n        groupSvgElem(this);\n      }\n    });\n\n    // For Firefox: Put all paint elems in defs\n    if (isGecko()) {\n      content.find('linearGradient, radialGradient, pattern').appendTo(findDefs());\n    }\n\n    // Set ref element for <use> elements\n\n    // TODO: This should also be done if the object is re-added through \"redo\"\n    setUseData(content);\n\n    convertGradients(content[0]);\n\n    const attrs = {\n      id: 'svgcontent',\n      overflow: curConfig.show_outside_canvas ? 'visible' : 'hidden'\n    };\n\n    let percs = false;\n\n    // determine proper size\n    if (content.attr('viewBox')) {\n      const vb = content.attr('viewBox').split(' ');\n      attrs.width = vb[2];\n      attrs.height = vb[3];\n    // handle content that doesn't have a viewBox\n    } else {\n      $.each(['width', 'height'], function (i, dim) {\n        // Set to 100 if not given\n        const val = content.attr(dim) || '100%';\n\n        if (String(val).substr(-1) === '%') {\n          // Use user units if percentage given\n          percs = true;\n        } else {\n          attrs[dim] = convertToNum(dim, val);\n        }\n      });\n    }\n\n    // identify layers\n    draw.identifyLayers();\n\n    // Give ID for any visible layer children missing one\n    content.children().find(visElems).each(function () {\n      if (!this.id) { this.id = getNextId(); }\n    });\n\n    // Percentage width/height, so let's base it on visible elements\n    if (percs) {\n      const bb = getStrokedBBoxDefaultVisible();\n      attrs.width = bb.width + bb.x;\n      attrs.height = bb.height + bb.y;\n    }\n\n    // Just in case negative numbers are given or\n    // result from the percs calculation\n    if (attrs.width <= 0) { attrs.width = 100; }\n    if (attrs.height <= 0) { attrs.height = 100; }\n\n    content.attr(attrs);\n    this.contentW = attrs.width;\n    this.contentH = attrs.height;\n\n    batchCmd.addSubCommand(new InsertElementCommand(svgcontent));\n    // update root to the correct size\n    const changes = content.attr(['width', 'height']);\n    batchCmd.addSubCommand(new ChangeElementCommand(svgroot, changes));\n\n    // reset zoom\n    currentZoom = 1;\n\n    // reset transform lists\n    resetListMap();\n    clearSelection();\n    pathModule.clearData();\n    svgroot.appendChild(selectorManager.selectorParentGroup);\n\n    if (!preventUndo) addCommandToHistory(batchCmd);\n    call('changed', [svgcontent]);\n  } catch (e) {\n    console.log(e);\n    return false;\n  }\n\n  return true;\n};\n\n/**\n* This function imports the input SVG XML as a &lt;symbol> in the &lt;defs>, then adds a\n* &lt;use> to the current layer.\n* @param {String} xmlString - The SVG as XML text.\n* @returns This function returns null if the import was unsuccessful, or the element otherwise.\n* @todo\n* - properly handle if namespace is introduced by imported content (must add to svgcontent\n* and update all prefixes in the imported node)\n* - properly handle recalculating dimensions, recalculateDimensions() doesn't handle\n* arbitrary transform lists, but makes some assumptions about how the transform list\n* was obtained\n* - import should happen in top-left of current zoomed viewport\n*/\nthis.importSvgString = function (xmlString) {\n  let j, ts, useEl;\n  try {\n    // Get unique ID\n    const uid = encode64(xmlString.length + xmlString).substr(0, 32);\n\n    let useExisting = false;\n    // Look for symbol and make sure symbol exists in image\n    if (importIds[uid]) {\n      if ($(importIds[uid].symbol).parents('#svgroot').length) {\n        useExisting = true;\n      }\n    }\n\n    const batchCmd = new BatchCommand('Import Image');\n    let symbol;\n    if (useExisting) {\n      ({symbol} = importIds[uid]);\n      ts = importIds[uid].xform;\n    } else {\n      // convert string into XML document\n      const newDoc = text2xml(xmlString);\n\n      this.prepareSvg(newDoc);\n\n      // import new svg document into our document\n      let svg;\n      // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode()\n      if (svgdoc.adoptNode) {\n        svg = svgdoc.adoptNode(newDoc.documentElement);\n      } else {\n        svg = svgdoc.importNode(newDoc.documentElement, true);\n      }\n\n      uniquifyElems(svg);\n\n      const innerw = convertToNum('width', svg.getAttribute('width')),\n        innerh = convertToNum('height', svg.getAttribute('height')),\n        innervb = svg.getAttribute('viewBox'),\n        // if no explicit viewbox, create one out of the width and height\n        vb = innervb ? innervb.split(' ') : [0, 0, innerw, innerh];\n      for (j = 0; j < 4; ++j) {\n        vb[j] = +(vb[j]);\n      }\n\n      // TODO: properly handle preserveAspectRatio\n      const // canvasw = +svgcontent.getAttribute('width'),\n        canvash = +svgcontent.getAttribute('height');\n      // imported content should be 1/3 of the canvas on its largest dimension\n\n      if (innerh > innerw) {\n        ts = 'scale(' + (canvash / 3) / vb[3] + ')';\n      } else {\n        ts = 'scale(' + (canvash / 3) / vb[2] + ')';\n      }\n\n      // Hack to make recalculateDimensions understand how to scale\n      ts = 'translate(0) ' + ts + ' translate(0)';\n\n      symbol = svgdoc.createElementNS(NS.SVG, 'symbol');\n      const defs = findDefs();\n\n      if (isGecko()) {\n        // Move all gradients into root for Firefox, workaround for this bug:\n        // https://bugzilla.mozilla.org/show_bug.cgi?id=353575\n        // TODO: Make this properly undo-able.\n        $(svg).find('linearGradient, radialGradient, pattern').appendTo(defs);\n      }\n\n      while (svg.firstChild) {\n        const first = svg.firstChild;\n        symbol.appendChild(first);\n      }\n      const attrs = svg.attributes;\n      for (let i = 0; i < attrs.length; i++) {\n        const attr = attrs[i];\n        symbol.setAttribute(attr.nodeName, attr.value);\n      }\n      symbol.id = getNextId();\n\n      // Store data\n      importIds[uid] = {\n        symbol,\n        xform: ts\n      };\n\n      findDefs().appendChild(symbol);\n      batchCmd.addSubCommand(new InsertElementCommand(symbol));\n    }\n\n    useEl = svgdoc.createElementNS(NS.SVG, 'use');\n    useEl.id = getNextId();\n    setHref(useEl, '#' + symbol.id);\n\n    (currentGroup || getCurrentDrawing().getCurrentLayer()).appendChild(useEl);\n    batchCmd.addSubCommand(new InsertElementCommand(useEl));\n    clearSelection();\n\n    useEl.setAttribute('transform', ts);\n    recalculateDimensions(useEl);\n    $(useEl).data('symbol', symbol).data('ref', symbol);\n    addToSelection([useEl]);\n\n    // TODO: Find way to add this in a recalculateDimensions-parsable way\n    // if (vb[0] !== 0 || vb[1] !== 0) {\n    //   ts = 'translate(' + (-vb[0]) + ',' + (-vb[1]) + ') ' + ts;\n    // }\n    addCommandToHistory(batchCmd);\n    call('changed', [svgcontent]);\n  } catch (e) {\n    console.log(e);\n    return null;\n  }\n\n  // we want to return the element so we can automatically select it\n  return useEl;\n};\n\n// Could deprecate, but besides external uses, their usage makes clear that\n//  canvas is a dependency for all of these\n[\n  'identifyLayers', 'createLayer', 'cloneLayer', 'deleteCurrentLayer',\n  'setCurrentLayer', 'renameCurrentLayer', 'setCurrentLayerPosition',\n  'setLayerVisibility', 'moveSelectedToLayer', 'mergeLayer', 'mergeAllLayers',\n  'leaveContext', 'setContext'\n].forEach((prop) => {\n  canvas[prop] = draw[prop];\n});\ndraw.init({\n  pathActions,\n  getCurrentGroup () {\n    return currentGroup;\n  },\n  setCurrentGroup (cg) {\n    currentGroup = cg;\n  },\n  getSelectedElements,\n  getSVGContent,\n  undoMgr,\n  elData,\n  getCurrentDrawing,\n  clearSelection,\n  call,\n  addCommandToHistory,\n  changeSvgcontent () {\n    call('changed', [svgcontent]);\n  }\n});\n\n/**\n* Group: Document functions\n*/\n\n/**\n* Clears the current document. This is not an undoable action.\n*/\nthis.clear = function () {\n  pathActions.clear();\n\n  clearSelection();\n\n  // clear the svgcontent node\n  canvas.clearSvgContentElement();\n\n  // create new document\n  canvas.current_drawing_ = new draw.Drawing(svgcontent);\n\n  // create empty first layer\n  canvas.createLayer('Layer 1');\n\n  // clear the undo stack\n  canvas.undoMgr.resetUndoStack();\n\n  // reset the selector manager\n  selectorManager.initGroup();\n\n  // reset the rubber band box\n  rubberBox = selectorManager.getRubberBandBox();\n\n  call('cleared');\n};\n\n/**\n* Alias function\n*/\nthis.linkControlPoints = pathActions.linkControlPoints;\n\n/**\n* @returns The content DOM element\n*/\nthis.getContentElem = function () { return svgcontent; };\n\n/**\n* @returns The root DOM element\n*/\nthis.getRootElem = function () { return svgroot; };\n\n/**\n* @returns {Object} The current dimensions and zoom level in an object\n*/\nconst getResolution = this.getResolution = function () {\n//    const vb = svgcontent.getAttribute('viewBox').split(' ');\n//    return {w:vb[2], h:vb[3], zoom: currentZoom};\n\n  const w = svgcontent.getAttribute('width') / currentZoom;\n  const h = svgcontent.getAttribute('height') / currentZoom;\n\n  return {\n    w,\n    h,\n    zoom: currentZoom\n  };\n};\n\n/**\n* @returns The current snap to grid setting\n*/\nthis.getSnapToGrid = function () { return curConfig.gridSnapping; };\n\n/**\n* @returns {String} A string which describes the revision number of SvgCanvas.\n*/\nthis.getVersion = function () {\n  return 'svgcanvas.js ($Rev$)';\n};\n\n/**\n* Update interface strings with given values\n* @param strs - Object with strings (see locales file)\n*/\nthis.setUiStrings = function (strs) {\n  Object.assign(uiStrings, strs.notification);\n  pathModule.setUiStrings(strs);\n};\n\n/**\n* Update configuration options with given values\n* @param {Object} opts - Object with options (see curConfig for examples)\n*/\nthis.setConfig = function (opts) {\n  Object.assign(curConfig, opts);\n};\n\n/**\n* @param elem\n* @returns {String|undefined} the current group/SVG's title contents\n*/\nthis.getTitle = function (elem) {\n  elem = elem || selectedElements[0];\n  if (!elem) { return; }\n  elem = $(elem).data('gsvg') || $(elem).data('symbol') || elem;\n  const childs = elem.childNodes;\n  for (let i = 0; i < childs.length; i++) {\n    if (childs[i].nodeName === 'title') {\n      return childs[i].textContent;\n    }\n  }\n  return '';\n};\n\n/**\n* Sets the group/SVG's title content\n* @param val\n* @todo Combine this with `setDocumentTitle`\n*/\nthis.setGroupTitle = function (val) {\n  let elem = selectedElements[0];\n  elem = $(elem).data('gsvg') || elem;\n\n  const ts = $(elem).children('title');\n\n  const batchCmd = new BatchCommand('Set Label');\n\n  let title;\n  if (!val.length) {\n    // Remove title element\n    const tsNextSibling = ts.nextSibling;\n    batchCmd.addSubCommand(new RemoveElementCommand(ts[0], tsNextSibling, elem));\n    ts.remove();\n  } else if (ts.length) {\n    // Change title contents\n    title = ts[0];\n    batchCmd.addSubCommand(new ChangeElementCommand(title, {'#text': title.textContent}));\n    title.textContent = val;\n  } else {\n    // Add title element\n    title = svgdoc.createElementNS(NS.SVG, 'title');\n    title.textContent = val;\n    $(elem).prepend(title);\n    batchCmd.addSubCommand(new InsertElementCommand(title));\n  }\n\n  addCommandToHistory(batchCmd);\n};\n\n/**\n* @returns {String|undefined} The current document title or an empty string if not found\n*/\nconst getDocumentTitle = this.getDocumentTitle = function () {\n  return canvas.getTitle(svgcontent);\n};\n\n/**\n* Adds/updates a title element for the document with the given name.\n* This is an undoable action\n* @param {String} newtitle - String with the new title\n*/\nthis.setDocumentTitle = function (newtitle) {\n  const childs = svgcontent.childNodes;\n  let docTitle = false, oldTitle = '';\n\n  const batchCmd = new BatchCommand('Change Image Title');\n\n  for (let i = 0; i < childs.length; i++) {\n    if (childs[i].nodeName === 'title') {\n      docTitle = childs[i];\n      oldTitle = docTitle.textContent;\n      break;\n    }\n  }\n  if (!docTitle) {\n    docTitle = svgdoc.createElementNS(NS.SVG, 'title');\n    svgcontent.insertBefore(docTitle, svgcontent.firstChild);\n  }\n\n  if (newtitle.length) {\n    docTitle.textContent = newtitle;\n  } else {\n    // No title given, so element is not necessary\n    docTitle.parentNode.removeChild(docTitle);\n  }\n  batchCmd.addSubCommand(new ChangeElementCommand(docTitle, {'#text': oldTitle}));\n  addCommandToHistory(batchCmd);\n};\n\n/**\n* Returns the editor's namespace URL, optionally adds it to root element\n* @param {Boolean} add - Indicates whether or not to add the namespace value\n* @returns {String} The editor's namespace URL\n*/\nthis.getEditorNS = function (add) {\n  if (add) {\n    svgcontent.setAttribute('xmlns:se', NS.SE);\n  }\n  return NS.SE;\n};\n\n/**\n* Changes the document's dimensions to the given size\n* @param x - Number with the width of the new dimensions in user units.\n* Can also be the string \"fit\" to indicate \"fit to content\"\n* @param y - Number with the height of the new dimensions in user units.\n* @returns {Boolean} Indicates if resolution change was succesful.\n* It will fail on \"fit to content\" option with no content to fit to.\n*/\nthis.setResolution = function (x, y) {\n  const res = getResolution();\n  const {w, h} = res;\n  let batchCmd;\n\n  if (x === 'fit') {\n    // Get bounding box\n    const bbox = getStrokedBBoxDefaultVisible();\n\n    if (bbox) {\n      batchCmd = new BatchCommand('Fit Canvas to Content');\n      const visEls = getVisibleElements();\n      addToSelection(visEls);\n      const dx = [], dy = [];\n      $.each(visEls, function (i, item) {\n        dx.push(bbox.x * -1);\n        dy.push(bbox.y * -1);\n      });\n\n      const cmd = canvas.moveSelectedElements(dx, dy, true);\n      batchCmd.addSubCommand(cmd);\n      clearSelection();\n\n      x = Math.round(bbox.width);\n      y = Math.round(bbox.height);\n    } else {\n      return false;\n    }\n  }\n  if (x !== w || y !== h) {\n    if (!batchCmd) {\n      batchCmd = new BatchCommand('Change Image Dimensions');\n    }\n\n    x = convertToNum('width', x);\n    y = convertToNum('height', y);\n\n    svgcontent.setAttribute('width', x);\n    svgcontent.setAttribute('height', y);\n\n    this.contentW = x;\n    this.contentH = y;\n    batchCmd.addSubCommand(new ChangeElementCommand(svgcontent, {width: w, height: h}));\n\n    svgcontent.setAttribute('viewBox', [0, 0, x / currentZoom, y / currentZoom].join(' '));\n    batchCmd.addSubCommand(new ChangeElementCommand(svgcontent, {viewBox: ['0 0', w, h].join(' ')}));\n\n    addCommandToHistory(batchCmd);\n    call('changed', [svgcontent]);\n  }\n  return true;\n};\n\n/**\n* @returns An object with x, y values indicating the svgcontent element's\n* position in the editor's canvas.\n*/\nthis.getOffset = function () {\n  return $(svgcontent).attr(['x', 'y']);\n};\n\n/**\n* Sets the zoom level on the canvas-side based on the given value\n* @param val - Bounding box object to zoom to or string indicating zoom option\n* @param {Number} editorW - Integer with the editor's workarea box's width\n* @param {Number} editorH - Integer with the editor's workarea box's height\n* @returns {Object|undefined}\n*/\nthis.setBBoxZoom = function (val, editorW, editorH) {\n  let spacer = 0.85;\n  let bb;\n  const calcZoom = function (bb) {\n    if (!bb) { return false; }\n    const wZoom = Math.round((editorW / bb.width) * 100 * spacer) / 100;\n    const hZoom = Math.round((editorH / bb.height) * 100 * spacer) / 100;\n    const zoom = Math.min(wZoom, hZoom);\n    canvas.setZoom(zoom);\n    return {zoom, bbox: bb};\n  };\n\n  if (typeof val === 'object') {\n    bb = val;\n    if (bb.width === 0 || bb.height === 0) {\n      const newzoom = bb.zoom ? bb.zoom : currentZoom * bb.factor;\n      canvas.setZoom(newzoom);\n      return {zoom: currentZoom, bbox: bb};\n    }\n    return calcZoom(bb);\n  }\n\n  switch (val) {\n  case 'selection':\n    if (!selectedElements[0]) { return; }\n    const selectedElems = $.map(selectedElements, function (n) { if (n) { return n; } });\n    bb = getStrokedBBoxDefaultVisible(selectedElems);\n    break;\n  case 'canvas':\n    const res = getResolution();\n    spacer = 0.95;\n    bb = {width: res.w, height: res.h, x: 0, y: 0};\n    break;\n  case 'content':\n    bb = getStrokedBBoxDefaultVisible();\n    break;\n  case 'layer':\n    bb = getStrokedBBoxDefaultVisible(getVisibleElements(getCurrentDrawing().getCurrentLayer()));\n    break;\n  default:\n    return;\n  }\n  return calcZoom(bb);\n};\n\n/**\n* Sets the zoom to the given level\n* @param {Number} zoomlevel - Float indicating the zoom level to change to\n*/\nthis.setZoom = function (zoomlevel) {\n  const res = getResolution();\n  svgcontent.setAttribute('viewBox', '0 0 ' + res.w / zoomlevel + ' ' + res.h / zoomlevel);\n  currentZoom = zoomlevel;\n  $.each(selectedElements, function (i, elem) {\n    if (!elem) { return; }\n    selectorManager.requestSelector(elem).resize();\n  });\n  pathActions.zoomChange();\n  runExtensions('zoomChanged', zoomlevel);\n};\n\n/**\n* @returns {String} The current editor mode string\n*/\nthis.getMode = function () {\n  return currentMode;\n};\n\n/**\n* Sets the editor's mode to the given string\n* @param {String} name - String with the new mode to change to\n*/\nthis.setMode = function (name) {\n  pathActions.clear(true);\n  textActions.clear();\n  curProperties = (selectedElements[0] && selectedElements[0].nodeName === 'text') ? curText : curShape;\n  currentMode = name;\n};\n\n/**\n* Group: Element Styling\n*/\n\n/**\n* @returns The current fill/stroke option\n*/\nthis.getColor = function (type) {\n  return curProperties[type];\n};\n\n/**\n* Change the current stroke/fill color/gradient value\n* @param {String} type - String indicating fill or stroke\n* @param val - The value to set the stroke attribute to\n* @param {Boolean} preventUndo - Boolean indicating whether or not this should be and undoable option\n*/\nthis.setColor = function (type, val, preventUndo) {\n  curShape[type] = val;\n  curProperties[type + '_paint'] = {type: 'solidColor'};\n  const elems = [];\n  function addNonG (e) {\n    if (e.nodeName !== 'g') {\n      elems.push(e);\n    }\n  }\n  let i = selectedElements.length;\n  while (i--) {\n    const elem = selectedElements[i];\n    if (elem) {\n      if (elem.tagName === 'g') {\n        walkTree(elem, addNonG);\n      } else {\n        if (type === 'fill') {\n          if (elem.tagName !== 'polyline' && elem.tagName !== 'line') {\n            elems.push(elem);\n          }\n        } else {\n          elems.push(elem);\n        }\n      }\n    }\n  }\n  if (elems.length > 0) {\n    if (!preventUndo) {\n      changeSelectedAttribute(type, val, elems);\n      call('changed', elems);\n    } else {\n      changeSelectedAttributeNoUndo(type, val, elems);\n    }\n  }\n};\n\n// Apply the current gradient to selected element's fill or stroke\n//\n// Parameters\n// type - String indicating \"fill\" or \"stroke\" to apply to an element\nconst setGradient = this.setGradient = function (type) {\n  if (!curProperties[type + '_paint'] || curProperties[type + '_paint'].type === 'solidColor') { return; }\n  let grad = canvas[type + 'Grad'];\n  // find out if there is a duplicate gradient already in the defs\n  const duplicateGrad = findDuplicateGradient(grad);\n  const defs = findDefs();\n  // no duplicate found, so import gradient into defs\n  if (!duplicateGrad) {\n    // const origGrad = grad;\n    grad = defs.appendChild(svgdoc.importNode(grad, true));\n    // get next id and set it on the grad\n    grad.id = getNextId();\n  } else { // use existing gradient\n    grad = duplicateGrad;\n  }\n  canvas.setColor(type, 'url(#' + grad.id + ')');\n};\n\n/**\n* Check if exact gradient already exists\n* @param grad - The gradient DOM element to compare to others\n* @returns The existing gradient if found, null if not\n*/\nconst findDuplicateGradient = function (grad) {\n  const defs = findDefs();\n  const existingGrads = $(defs).find('linearGradient, radialGradient');\n  let i = existingGrads.length;\n  const radAttrs = ['r', 'cx', 'cy', 'fx', 'fy'];\n  while (i--) {\n    const og = existingGrads[i];\n    if (grad.tagName === 'linearGradient') {\n      if (grad.getAttribute('x1') !== og.getAttribute('x1') ||\n        grad.getAttribute('y1') !== og.getAttribute('y1') ||\n        grad.getAttribute('x2') !== og.getAttribute('x2') ||\n        grad.getAttribute('y2') !== og.getAttribute('y2')\n      ) {\n        continue;\n      }\n    } else {\n      const gradAttrs = $(grad).attr(radAttrs);\n      const ogAttrs = $(og).attr(radAttrs);\n\n      let diff = false;\n      $.each(radAttrs, function (i, attr) {\n        if (gradAttrs[attr] !== ogAttrs[attr]) { diff = true; }\n      });\n\n      if (diff) { continue; }\n    }\n\n    // else could be a duplicate, iterate through stops\n    const stops = grad.getElementsByTagNameNS(NS.SVG, 'stop');\n    const ostops = og.getElementsByTagNameNS(NS.SVG, 'stop');\n\n    if (stops.length !== ostops.length) {\n      continue;\n    }\n\n    let j = stops.length;\n    while (j--) {\n      const stop = stops[j];\n      const ostop = ostops[j];\n\n      if (stop.getAttribute('offset') !== ostop.getAttribute('offset') ||\n        stop.getAttribute('stop-opacity') !== ostop.getAttribute('stop-opacity') ||\n        stop.getAttribute('stop-color') !== ostop.getAttribute('stop-color')) {\n        break;\n      }\n    }\n\n    if (j === -1) {\n      return og;\n    }\n  } // for each gradient in defs\n\n  return null;\n};\n\n/**\n* Set a color/gradient to a fill/stroke\n* @param {\"fill\"|\"stroke\"} type - String with \"fill\" or \"stroke\"\n* @param paint - The jGraduate paint object to apply\n*/\nthis.setPaint = function (type, paint) {\n  // make a copy\n  const p = new $.jGraduate.Paint(paint);\n  this.setPaintOpacity(type, p.alpha / 100, true);\n\n  // now set the current paint object\n  curProperties[type + '_paint'] = p;\n  switch (p.type) {\n  case 'solidColor':\n    this.setColor(type, p.solidColor !== 'none' ? '#' + p.solidColor : 'none');\n    break;\n  case 'linearGradient':\n  case 'radialGradient':\n    canvas[type + 'Grad'] = p[p.type];\n    setGradient(type);\n    break;\n  }\n};\n\n// alias\nthis.setStrokePaint = function (paint) {\n  this.setPaint('stroke', paint);\n};\n\nthis.setFillPaint = function (paint) {\n  this.setPaint('fill', paint);\n};\n\n/**\n* @returns The current stroke-width value\n*/\nthis.getStrokeWidth = function () {\n  return curProperties.stroke_width;\n};\n\n/**\n* Sets the stroke width for the current selected elements\n* When attempting to set a line's width to 0, this changes it to 1 instead\n* @param {Number} val - A Float indicating the new stroke width value\n*/\nthis.setStrokeWidth = function (val) {\n  if (val === 0 && ['line', 'path'].includes(currentMode)) {\n    canvas.setStrokeWidth(1);\n    return;\n  }\n  curProperties.stroke_width = val;\n\n  const elems = [];\n  function addNonG (e) {\n    if (e.nodeName !== 'g') {\n      elems.push(e);\n    }\n  }\n  let i = selectedElements.length;\n  while (i--) {\n    const elem = selectedElements[i];\n    if (elem) {\n      if (elem.tagName === 'g') {\n        walkTree(elem, addNonG);\n      } else {\n        elems.push(elem);\n      }\n    }\n  }\n  if (elems.length > 0) {\n    changeSelectedAttribute('stroke-width', val, elems);\n    call('changed', selectedElements);\n  }\n};\n\n/**\n* Set the given stroke-related attribute the given value for selected elements\n* @param {String} attr - String with the attribute name\n* @param {String|Number} val - String or number with the attribute value\n*/\nthis.setStrokeAttr = function (attr, val) {\n  curShape[attr.replace('-', '_')] = val;\n  const elems = [];\n\n  let i = selectedElements.length;\n  while (i--) {\n    const elem = selectedElements[i];\n    if (elem) {\n      if (elem.tagName === 'g') {\n        walkTree(elem, function (e) { if (e.nodeName !== 'g') { elems.push(e); } });\n      } else {\n        elems.push(elem);\n      }\n    }\n  }\n  if (elems.length > 0) {\n    changeSelectedAttribute(attr, val, elems);\n    call('changed', selectedElements);\n  }\n};\n\n/**\n* @returns current style options\n*/\nthis.getStyle = function () {\n  return curShape;\n};\n\n/**\n* @returns the current opacity\n*/\nthis.getOpacity = getOpacity;\n\n/**\n* Sets the given opacity to the current selected elements\n* @param val\n*/\nthis.setOpacity = function (val) {\n  curShape.opacity = val;\n  changeSelectedAttribute('opacity', val);\n};\n\n/**\n* @returns the current fill opacity\n*/\nthis.getFillOpacity = function () {\n  return curShape.fill_opacity;\n};\n\n/**\n* @returns the current stroke opacity\n*/\nthis.getStrokeOpacity = function () {\n  return curShape.stroke_opacity;\n};\n\n/**\n* Sets the current fill/stroke opacity\n* @param {String} type - String with \"fill\" or \"stroke\"\n* @param {Number} val - Float with the new opacity value\n* @param {Boolean} preventUndo - Indicates whether or not this should be an undoable action\n*/\nthis.setPaintOpacity = function (type, val, preventUndo) {\n  curShape[type + '_opacity'] = val;\n  if (!preventUndo) {\n    changeSelectedAttribute(type + '-opacity', val);\n  } else {\n    changeSelectedAttributeNoUndo(type + '-opacity', val);\n  }\n};\n\n/**\n* Gets the current fill/stroke opacity\n* @param {\"fill\"|\"stroke\"} type - String with \"fill\" or \"stroke\"\n* @returns Fill/stroke opacity\n*/\nthis.getPaintOpacity = function (type) {\n  return type === 'fill' ? this.getFillOpacity() : this.getStrokeOpacity();\n};\n\n/**\n* Gets the stdDeviation blur value of the given element\n* @param elem - The element to check the blur value for\n* @returns stdDeviation blur attribute value\n*/\nthis.getBlur = function (elem) {\n  let val = 0;\n  // const elem = selectedElements[0];\n\n  if (elem) {\n    const filterUrl = elem.getAttribute('filter');\n    if (filterUrl) {\n      const blur = getElem(elem.id + '_blur');\n      if (blur) {\n        val = blur.firstChild.getAttribute('stdDeviation');\n      }\n    }\n  }\n  return val;\n};\n\n(function () {\nlet curCommand = null;\nlet filter = null;\nlet filterHidden = false;\n\n/**\n* Sets the stdDeviation blur value on the selected element without being undoable\n* @param val - The new stdDeviation value\n*/\ncanvas.setBlurNoUndo = function (val) {\n  if (!filter) {\n    canvas.setBlur(val);\n    return;\n  }\n  if (val === 0) {\n    // Don't change the StdDev, as that will hide the element.\n    // Instead, just remove the value for \"filter\"\n    changeSelectedAttributeNoUndo('filter', '');\n    filterHidden = true;\n  } else {\n    const elem = selectedElements[0];\n    if (filterHidden) {\n      changeSelectedAttributeNoUndo('filter', 'url(#' + elem.id + '_blur)');\n    }\n    if (isWebkit()) {\n      console.log('e', elem);\n      elem.removeAttribute('filter');\n      elem.setAttribute('filter', 'url(#' + elem.id + '_blur)');\n    }\n    changeSelectedAttributeNoUndo('stdDeviation', val, [filter.firstChild]);\n    canvas.setBlurOffsets(filter, val);\n  }\n};\n\nfunction finishChange () {\n  const bCmd = canvas.undoMgr.finishUndoableChange();\n  curCommand.addSubCommand(bCmd);\n  addCommandToHistory(curCommand);\n  curCommand = null;\n  filter = null;\n}\n\n/**\n* Sets the x, y, with, height values of the filter element in order to\n* make the blur not be clipped. Removes them if not neeeded\n* @param filter - The filter DOM element to update\n* @param stdDev - The standard deviation value on which to base the offset size\n*/\ncanvas.setBlurOffsets = function (filter, stdDev) {\n  if (stdDev > 3) {\n    // TODO: Create algorithm here where size is based on expected blur\n    assignAttributes(filter, {\n      x: '-50%',\n      y: '-50%',\n      width: '200%',\n      height: '200%'\n    }, 100);\n  } else {\n    // Removing these attributes hides text in Chrome (see Issue 579)\n    if (!isWebkit()) {\n      filter.removeAttribute('x');\n      filter.removeAttribute('y');\n      filter.removeAttribute('width');\n      filter.removeAttribute('height');\n    }\n  }\n};\n\n/**\n* Adds/updates the blur filter to the selected element\n* @param {Number} val - Float with the new stdDeviation blur value\n* @param {Boolean} complete - Boolean indicating whether or not the action should be completed (to add to the undo manager)\n*/\ncanvas.setBlur = function (val, complete) {\n  if (curCommand) {\n    finishChange();\n    return;\n  }\n\n  // Looks for associated blur, creates one if not found\n  const elem = selectedElements[0];\n  const elemId = elem.id;\n  filter = getElem(elemId + '_blur');\n\n  val -= 0;\n\n  const batchCmd = new BatchCommand();\n\n  // Blur found!\n  if (filter) {\n    if (val === 0) {\n      filter = null;\n    }\n  } else {\n    // Not found, so create\n    const newblur = addSvgElementFromJson({ element: 'feGaussianBlur',\n      attr: {\n        in: 'SourceGraphic',\n        stdDeviation: val\n      }\n    });\n\n    filter = addSvgElementFromJson({ element: 'filter',\n      attr: {\n        id: elemId + '_blur'\n      }\n    });\n\n    filter.appendChild(newblur);\n    findDefs().appendChild(filter);\n\n    batchCmd.addSubCommand(new InsertElementCommand(filter));\n  }\n\n  const changes = {filter: elem.getAttribute('filter')};\n\n  if (val === 0) {\n    elem.removeAttribute('filter');\n    batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));\n    return;\n  }\n\n  changeSelectedAttribute('filter', 'url(#' + elemId + '_blur)');\n  batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));\n  canvas.setBlurOffsets(filter, val);\n\n  curCommand = batchCmd;\n  canvas.undoMgr.beginUndoableChange('stdDeviation', [filter ? filter.firstChild : null]);\n  if (complete) {\n    canvas.setBlurNoUndo(val);\n    finishChange();\n  }\n};\n}());\n\n/**\n* Check whether selected element is bold or not\n* @returns {Boolean} Indicates whether or not element is bold\n*/\nthis.getBold = function () {\n  // should only have one element selected\n  const selected = selectedElements[0];\n  if (selected != null && selected.tagName === 'text' &&\n    selectedElements[1] == null) {\n    return (selected.getAttribute('font-weight') === 'bold');\n  }\n  return false;\n};\n\n/**\n* Make the selected element bold or normal\n* @param {Boolean} b - Indicates bold (true) or normal (false)\n*/\nthis.setBold = function (b) {\n  const selected = selectedElements[0];\n  if (selected != null && selected.tagName === 'text' &&\n    selectedElements[1] == null) {\n    changeSelectedAttribute('font-weight', b ? 'bold' : 'normal');\n  }\n  if (!selectedElements[0].textContent) {\n    textActions.setCursor();\n  }\n};\n\n/**\n* Check whether selected element is italic or not\n* @returns {Boolean} Indicates whether or not element is italic\n*/\nthis.getItalic = function () {\n  const selected = selectedElements[0];\n  if (selected != null && selected.tagName === 'text' &&\n    selectedElements[1] == null) {\n    return (selected.getAttribute('font-style') === 'italic');\n  }\n  return false;\n};\n\n/**\n* Make the selected element italic or normal\n* @param {Boolean} b - Indicates italic (true) or normal (false)\n*/\nthis.setItalic = function (i) {\n  const selected = selectedElements[0];\n  if (selected != null && selected.tagName === 'text' &&\n    selectedElements[1] == null) {\n    changeSelectedAttribute('font-style', i ? 'italic' : 'normal');\n  }\n  if (!selectedElements[0].textContent) {\n    textActions.setCursor();\n  }\n};\n\n/**\n* @returns The current font family\n*/\nthis.getFontFamily = function () {\n  return curText.font_family;\n};\n\n/**\n* Set the new font family\n* @param {String} val - String with the new font family\n*/\nthis.setFontFamily = function (val) {\n  curText.font_family = val;\n  changeSelectedAttribute('font-family', val);\n  if (selectedElements[0] && !selectedElements[0].textContent) {\n    textActions.setCursor();\n  }\n};\n\n/**\n* Set the new font color\n* @param {String} val - String with the new font color\n*/\nthis.setFontColor = function (val) {\n  curText.fill = val;\n  changeSelectedAttribute('fill', val);\n};\n\n/**\n* @returns The current font color\n*/\nthis.getFontColor = function () {\n  return curText.fill;\n};\n\n/**\n* Returns the current font size\n*/\nthis.getFontSize = function () {\n  return curText.font_size;\n};\n\n/**\n* Applies the given font size to the selected element\n* @param {Number} val - Float with the new font size\n*/\nthis.setFontSize = function (val) {\n  curText.font_size = val;\n  changeSelectedAttribute('font-size', val);\n  if (!selectedElements[0].textContent) {\n    textActions.setCursor();\n  }\n};\n\n/**\n* @returns The current text (textContent) of the selected element\n*/\nthis.getText = function () {\n  const selected = selectedElements[0];\n  if (selected == null) { return ''; }\n  return selected.textContent;\n};\n\n/**\n* Updates the text element with the given string\n* @param {String} val - String with the new text\n*/\nthis.setTextContent = function (val) {\n  changeSelectedAttribute('#text', val);\n  textActions.init(val);\n  textActions.setCursor();\n};\n\n/**\n* Sets the new image URL for the selected image element. Updates its size if\n* a new URL is given\n* @param {String} val - String with the image URL/path\n*/\nthis.setImageURL = function (val) {\n  const elem = selectedElements[0];\n  if (!elem) { return; }\n\n  const attrs = $(elem).attr(['width', 'height']);\n  let setsize = (!attrs.width || !attrs.height);\n\n  const curHref = getHref(elem);\n\n  // Do nothing if no URL change or size change\n  if (curHref !== val) {\n    setsize = true;\n  } else if (!setsize) { return; }\n\n  const batchCmd = new BatchCommand('Change Image URL');\n\n  setHref(elem, val);\n  batchCmd.addSubCommand(new ChangeElementCommand(elem, {\n    '#href': curHref\n  }));\n\n  if (setsize) {\n    $(new Image()).load(function () {\n      const changes = $(elem).attr(['width', 'height']);\n\n      $(elem).attr({\n        width: this.width,\n        height: this.height\n      });\n\n      selectorManager.requestSelector(elem).resize();\n\n      batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));\n      addCommandToHistory(batchCmd);\n      call('changed', [elem]);\n    }).attr('src', val);\n  } else {\n    addCommandToHistory(batchCmd);\n  }\n};\n\n/**\n* Sets the new link URL for the selected anchor element.\n* @param {String} val - String with the link URL/path\n*/\nthis.setLinkURL = function (val) {\n  let elem = selectedElements[0];\n  if (!elem) { return; }\n  if (elem.tagName !== 'a') {\n    // See if parent is an anchor\n    const parentsA = $(elem).parents('a');\n    if (parentsA.length) {\n      elem = parentsA[0];\n    } else {\n      return;\n    }\n  }\n\n  const curHref = getHref(elem);\n\n  if (curHref === val) { return; }\n\n  const batchCmd = new BatchCommand('Change Link URL');\n\n  setHref(elem, val);\n  batchCmd.addSubCommand(new ChangeElementCommand(elem, {\n    '#href': curHref\n  }));\n\n  addCommandToHistory(batchCmd);\n};\n\n/**\n* Sets the rx & ry values to the selected rect element to change its corner radius\n* @param val - The new radius\n*/\nthis.setRectRadius = function (val) {\n  const selected = selectedElements[0];\n  if (selected != null && selected.tagName === 'rect') {\n    const r = selected.getAttribute('rx');\n    if (r !== String(val)) {\n      selected.setAttribute('rx', val);\n      selected.setAttribute('ry', val);\n      addCommandToHistory(new ChangeElementCommand(selected, {rx: r, ry: r}, 'Radius'));\n      call('changed', [selected]);\n    }\n  }\n};\n\n/**\n* Wraps the selected element(s) in an anchor element or converts group to one\n* @param url\n*/\nthis.makeHyperlink = function (url) {\n  canvas.groupSelectedElements('a', url);\n\n  // TODO: If element is a single \"g\", convert to \"a\"\n  //  if (selectedElements.length > 1 && selectedElements[1]) {\n};\n\n/**\n*\n*/\nthis.removeHyperlink = function () {\n  canvas.ungroupSelectedElement();\n};\n\n/**\n* Group: Element manipulation\n*/\n\n/**\n* Sets the new segment type to the selected segment(s).\n* @param {Number} newType - Integer with the new segment type\n* See https://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSeg for list\n*/\nthis.setSegType = function (newType) {\n  pathActions.setSegType(newType);\n};\n\n/**\n* @todo (codedread): Remove the getBBox argument and split this function into two.\n* Convert selected element to a path, or get the BBox of an element-as-path\n* @param elem - The DOM element to be converted\n* @param getBBox - Boolean on whether or not to only return the path's BBox\n* @returns If the getBBox flag is true, the resulting path's bounding box object.\n* Otherwise the resulting path element is returned.\n*/\nthis.convertToPath = function (elem, getBBox) {\n  if (elem == null) {\n    const elems = selectedElements;\n    $.each(elems, function (i, elem) {\n      if (elem) { canvas.convertToPath(elem); }\n    });\n    return;\n  }\n  if (getBBox) {\n    return getBBoxOfElementAsPath(elem, addSvgElementFromJson, pathActions);\n  } else {\n    // TODO: Why is this applying attributes from curShape, then inside utilities.convertToPath it's pulling addition attributes from elem?\n    // TODO: If convertToPath is called with one elem, curShape and elem are probably the same; but calling with multiple is a bug or cool feature.\n    const attrs = {\n      fill: curShape.fill,\n      'fill-opacity': curShape.fill_opacity,\n      stroke: curShape.stroke,\n      'stroke-width': curShape.stroke_width,\n      'stroke-dasharray': curShape.stroke_dasharray,\n      'stroke-linejoin': curShape.stroke_linejoin,\n      'stroke-linecap': curShape.stroke_linecap,\n      'stroke-opacity': curShape.stroke_opacity,\n      opacity: curShape.opacity,\n      visibility: 'hidden'\n    };\n    return convertToPath(elem, attrs, addSvgElementFromJson, pathActions, clearSelection, addToSelection, history, addCommandToHistory);\n  }\n};\n\n/**\n* This function makes the changes to the elements. It does not add the change\n* to the history stack.\n* @param {String} attr - Attribute name\n* @param {String|Number} newValue - String or number with the new attribute value\n* @param elems - The DOM elements to apply the change to\n*/\nconst changeSelectedAttributeNoUndo = function (attr, newValue, elems) {\n  if (currentMode === 'pathedit') {\n    // Editing node\n    pathActions.moveNode(attr, newValue);\n  }\n  elems = elems || selectedElements;\n  let i = elems.length;\n  const noXYElems = ['g', 'polyline', 'path'];\n  const goodGAttrs = ['transform', 'opacity', 'filter'];\n\n  while (i--) {\n    let elem = elems[i];\n    if (elem == null) { continue; }\n\n    // Set x,y vals on elements that don't have them\n    if ((attr === 'x' || attr === 'y') && noXYElems.includes(elem.tagName)) {\n      const bbox = getStrokedBBoxDefaultVisible([elem]);\n      const diffX = attr === 'x' ? newValue - bbox.x : 0;\n      const diffY = attr === 'y' ? newValue - bbox.y : 0;\n      canvas.moveSelectedElements(diffX * currentZoom, diffY * currentZoom, true);\n      continue;\n    }\n\n    // only allow the transform/opacity/filter attribute to change on <g> elements, slightly hacky\n    // TODO: FIXME: This doesn't seem right. Where's the body of this if statement?\n    if (elem.tagName === 'g' && goodGAttrs.includes(attr)) {}\n    let oldval = attr === '#text' ? elem.textContent : elem.getAttribute(attr);\n    if (oldval == null) { oldval = ''; }\n    if (oldval !== String(newValue)) {\n      if (attr === '#text') {\n        // const oldW = utilsGetBBox(elem).width;\n        elem.textContent = newValue;\n\n        // FF bug occurs on on rotated elements\n        if ((/rotate/).test(elem.getAttribute('transform'))) {\n          elem = ffClone(elem);\n        }\n        // Hoped to solve the issue of moving text with text-anchor=\"start\",\n        // but this doesn't actually fix it. Hopefully on the right track, though. -Fyrd\n        // const box = getBBox(elem), left = box.x, top = box.y, {width, height} = box,\n        //   dx = width - oldW, dy = 0;\n        // const angle = getRotationAngle(elem, true);\n        // if (angle) {\n        //   const r = Math.sqrt(dx * dx + dy * dy);\n        //   const theta = Math.atan2(dy, dx) - angle;\n        //   dx = r * Math.cos(theta);\n        //   dy = r * Math.sin(theta);\n        //\n        //   elem.setAttribute('x', elem.getAttribute('x') - dx);\n        //   elem.setAttribute('y', elem.getAttribute('y') - dy);\n        // }\n      } else if (attr === '#href') {\n        setHref(elem, newValue);\n      } else { elem.setAttribute(attr, newValue); }\n\n      // Go into \"select\" mode for text changes\n      // NOTE: Important that this happens AFTER elem.setAttribute() or else attributes like\n      // font-size can get reset to their old value, ultimately by svgEditor.updateContextPanel(),\n      // after calling textActions.toSelectMode() below\n      if (currentMode === 'textedit' && attr !== '#text' && elem.textContent.length) {\n        textActions.toSelectMode(elem);\n      }\n\n      // if (i === 0) {\n      //   selectedBBoxes[0] = utilsGetBBox(elem);\n      // }\n\n      // Use the Firefox ffClone hack for text elements with gradients or\n      // where other text attributes are changed.\n      if (isGecko() && elem.nodeName === 'text' && (/rotate/).test(elem.getAttribute('transform'))) {\n        if (String(newValue).startsWith('url') || (['font-size', 'font-family', 'x', 'y'].includes(attr) && elem.textContent)) {\n          elem = ffClone(elem);\n        }\n      }\n      // Timeout needed for Opera & Firefox\n      // codedread: it is now possible for this function to be called with elements\n      // that are not in the selectedElements array, we need to only request a\n      // selector if the element is in that array\n      if (selectedElements.includes(elem)) {\n        setTimeout(function () {\n          // Due to element replacement, this element may no longer\n          // be part of the DOM\n          if (!elem.parentNode) { return; }\n          selectorManager.requestSelector(elem).resize();\n        }, 0);\n      }\n      // if this element was rotated, and we changed the position of this element\n      // we need to update the rotational transform attribute\n      const angle = getRotationAngle(elem);\n      if (angle !== 0 && attr !== 'transform') {\n        const tlist = getTransformList(elem);\n        let n = tlist.numberOfItems;\n        while (n--) {\n          const xform = tlist.getItem(n);\n          if (xform.type === 4) {\n            // remove old rotate\n            tlist.removeItem(n);\n\n            const box = utilsGetBBox(elem);\n            const center = transformPoint(box.x + box.width / 2, box.y + box.height / 2, transformListToTransform(tlist).matrix);\n            const cx = center.x,\n              cy = center.y;\n            const newrot = svgroot.createSVGTransform();\n            newrot.setRotate(angle, cx, cy);\n            tlist.insertItemBefore(newrot, n);\n            break;\n          }\n        }\n      }\n    } // if oldValue != newValue\n  } // for each elem\n};\n\n/**\n* Change the given/selected element and add the original value to the history stack\n* If you want to change all selectedElements, ignore the elems argument.\n* If you want to change only a subset of selectedElements, then send the\n* subset to this function in the elems argument.\n* @param {String} attr - String with the attribute name\n* @param {String|Number} newValue - String or number with the new attribute value\n* @param elems - The DOM elements to apply the change to\n*/\nconst changeSelectedAttribute = this.changeSelectedAttribute = function (attr, val, elems) {\n  elems = elems || selectedElements;\n  canvas.undoMgr.beginUndoableChange(attr, elems);\n  // const i = elems.length;\n\n  changeSelectedAttributeNoUndo(attr, val, elems);\n\n  const batchCmd = canvas.undoMgr.finishUndoableChange();\n  if (!batchCmd.isEmpty()) {\n    addCommandToHistory(batchCmd);\n  }\n};\n\n// Removes all selected elements from the DOM and adds the change to the\n// history stack\nthis.deleteSelectedElements = function () {\n  const batchCmd = new BatchCommand('Delete Elements');\n  const len = selectedElements.length;\n  const selectedCopy = []; // selectedElements is being deleted\n\n  for (let i = 0; i < len; ++i) {\n    const selected = selectedElements[i];\n    if (selected == null) { break; }\n\n    let parent = selected.parentNode;\n    let t = selected;\n\n    // this will unselect the element and remove the selectedOutline\n    selectorManager.releaseSelector(t);\n\n    // Remove the path if present.\n    pathModule.removePath_(t.id);\n\n    // Get the parent if it's a single-child anchor\n    if (parent.tagName === 'a' && parent.childNodes.length === 1) {\n      t = parent;\n      parent = parent.parentNode;\n    }\n\n    const {nextSibling} = t;\n    const elem = parent.removeChild(t);\n    selectedCopy.push(selected); // for the copy\n    batchCmd.addSubCommand(new RemoveElementCommand(elem, nextSibling, parent));\n  }\n  selectedElements = [];\n\n  if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); }\n  call('changed', selectedCopy);\n  clearSelection();\n};\n\n/**\n* Removes all selected elements from the DOM and adds the change to the\n* history stack. Remembers removed elements on the clipboard\n*/\nthis.cutSelectedElements = function () {\n  canvas.copySelectedElements();\n  canvas.deleteSelectedElements();\n};\n\nconst CLIPBOARD_ID = 'svgedit_clipboard';\n\n/**\n* Flash the clipboard data momentarily on localStorage so all tabs can see.\n* @returns {void}\n*/\nfunction flashStorage () {\n  const data = sessionStorage.getItem(CLIPBOARD_ID);\n  localStorage.setItem(CLIPBOARD_ID, data);\n  setTimeout(function () {\n    localStorage.removeItem(CLIPBOARD_ID);\n  }, 1);\n}\n\n/**\n* Transfers sessionStorage from one tab to another.\n* @param {!Event} ev Storage event.\n* @returns {void}\n*/\nfunction storageChange(ev) {\n  if (!ev.newValue) return; // This is a call from removeItem.\n  if (ev.key === CLIPBOARD_ID + '_startup') {\n    // Another tab asked for our sessionStorage.\n    localStorage.removeItem(CLIPBOARD_ID + '_startup');\n    flashStorage();\n  } else if (ev.key === CLIPBOARD_ID) {\n    // Another tab sent data.\n    sessionStorage.setItem(CLIPBOARD_ID, ev.newValue);\n  }\n}\n\n// Listen for changes to localStorage.\nwindow.addEventListener('storage', storageChange, false);\n// Ask other tabs for sessionStorage (this is ONLY to trigger event).\nlocalStorage.setItem(CLIPBOARD_ID + '_startup', Math.random());\n\n/**\n* Remembers the current selected elements on the clipboard.\n* @function module:svgcanvas.SvgCanvas#copySelectedElements\n* @returns {void}\n*/\nthis.copySelectedElements = function () {\n  const data =\n      JSON.stringify(selectedElements.map((x) => getJsonFromSvgElement(x)));\n  // Use sessionStorage for the clipboard data.\n  sessionStorage.setItem(CLIPBOARD_ID, data);\n  flashStorage();\n\n  const menu = $('#cmenu_canvas');\n  // Context menu might not exist (it is provided by editor.js).\n  if (menu.enableContextMenuItems) {\n    menu.enableContextMenuItems('#paste,#paste_in_place');\n  }\n};\n\n/**\n* @function module:svgcanvas.SvgCanvas#pasteElements\n* @param {\"in_place\"|\"point\"|void} type\n* @param {Integer|void} x Expected if type is \"point\"\n* @param {Integer|void} y Expected if type is \"point\"\n* @fires module:svgcanvas.SvgCanvas#event:changed\n* @fires module:svgcanvas.SvgCanvas#event:ext_IDsUpdated\n* @returns {void}\n*/\nthis.pasteElements = function (type, x, y) {\n  let cb = JSON.parse(sessionStorage.getItem(CLIPBOARD_ID));\n  if (!cb) return;\n  let len = cb.length;\n  if (!len) return;\n\n  const pasted = [];\n  const batchCmd = new BatchCommand('Paste elements');\n  // const drawing = getCurrentDrawing();\n  const changedIDs = {};\n\n  // Recursively replace IDs and record the changes\n  function checkIDs (elem) {\n    if (elem.attr && elem.attr.id) {\n      changedIDs[elem.attr.id] = getNextId();\n      elem.attr.id = changedIDs[elem.attr.id];\n    }\n    if (elem.children) elem.children.forEach(checkIDs);\n  }\n  cb.forEach(checkIDs);\n\n  // Give extensions like the connector extension a chance to reflect new IDs and remove invalid elements\n  runExtensions('IDsUpdated', {elems: cb, changes: changedIDs}, true).forEach(function (extChanges) {\n    if (!extChanges || !('remove' in extChanges)) return;\n\n    extChanges.remove.forEach(function (removeID) {\n      cb = cb.filter(function (cbItem) {\n        return cbItem.attr.id !== removeID;\n      });\n    });\n  });\n\n  // Move elements to lastClickPoint\n  while (len--) {\n    const elem = cb[len];\n    if (!elem) { continue; }\n\n    const copy = addSvgElementFromJson(elem);\n    pasted.push(copy);\n    batchCmd.addSubCommand(new InsertElementCommand(copy));\n\n    restoreRefElems(copy);\n  }\n\n  selectOnly(pasted);\n\n  if (type !== 'in_place') {\n    let ctrX, ctrY;\n\n    if (!type) {\n      ctrX = lastClickPoint.x;\n      ctrY = lastClickPoint.y;\n    } else if (type === 'point') {\n      ctrX = x;\n      ctrY = y;\n    }\n\n    const bbox = getStrokedBBoxDefaultVisible(pasted);\n    const cx = ctrX - (bbox.x + bbox.width / 2),\n      cy = ctrY - (bbox.y + bbox.height / 2),\n      dx = [],\n      dy = [];\n\n    $.each(pasted, function (i, item) {\n      dx.push(cx);\n      dy.push(cy);\n    });\n\n    const cmd = canvas.moveSelectedElements(dx, dy, false);\n    if (cmd) batchCmd.addSubCommand(cmd);\n  }\n\n  addCommandToHistory(batchCmd);\n  call('changed', pasted);\n};\n\n/**\n* Wraps all the selected elements in a group (g) element\n* @param type - type of element to group into, defaults to &lt;g>\n*/\nthis.groupSelectedElements = function (type, urlArg) {\n  if (!type) { type = 'g'; }\n  let cmdStr = '';\n  let url;\n\n  switch (type) {\n  case 'a': {\n    cmdStr = 'Make hyperlink';\n    url = '';\n    if (arguments.length > 1) {\n      url = urlArg;\n    }\n    break;\n  } default: {\n    type = 'g';\n    cmdStr = 'Group Elements';\n    break;\n  }\n  }\n\n  const batchCmd = new BatchCommand(cmdStr);\n\n  // create and insert the group element\n  const g = addSvgElementFromJson({\n    element: type,\n    attr: {\n      id: getNextId()\n    }\n  });\n  if (type === 'a') {\n    setHref(g, url);\n  }\n  batchCmd.addSubCommand(new InsertElementCommand(g));\n\n  // now move all children into the group\n  let i = selectedElements.length;\n  while (i--) {\n    let elem = selectedElements[i];\n    if (elem == null) { continue; }\n\n    if (elem.parentNode.tagName === 'a' && elem.parentNode.childNodes.length === 1) {\n      elem = elem.parentNode;\n    }\n\n    const oldNextSibling = elem.nextSibling;\n    const oldParent = elem.parentNode;\n    g.appendChild(elem);\n    batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldParent));\n  }\n  if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); }\n\n  // update selection\n  selectOnly([g], true);\n};\n\n// Pushes all appropriate parent group properties down to its children, then\n// removes them from the group\nconst pushGroupProperties = this.pushGroupProperties = function (g, undoable) {\n  const children = g.childNodes;\n  const len = children.length;\n  const xform = g.getAttribute('transform');\n\n  const glist = getTransformList(g);\n  const m = transformListToTransform(glist).matrix;\n\n  const batchCmd = new BatchCommand('Push group properties');\n\n  // TODO: get all fill/stroke properties from the group that we are about to destroy\n  // \"fill\", \"fill-opacity\", \"fill-rule\", \"stroke\", \"stroke-dasharray\", \"stroke-dashoffset\",\n  // \"stroke-linecap\", \"stroke-linejoin\", \"stroke-miterlimit\", \"stroke-opacity\",\n  // \"stroke-width\"\n  // and then for each child, if they do not have the attribute (or the value is 'inherit')\n  // then set the child's attribute\n\n  const gangle = getRotationAngle(g);\n\n  const gattrs = $(g).attr(['filter', 'opacity']);\n  let gfilter, gblur, changes;\n  const drawing = getCurrentDrawing();\n\n  for (let i = 0; i < len; i++) {\n    const elem = children[i];\n\n    if (elem.nodeType !== 1) { continue; }\n\n    if (gattrs.opacity !== null && gattrs.opacity !== 1) {\n      // const c_opac = elem.getAttribute('opacity') || 1;\n      const newOpac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100) / 100;\n      changeSelectedAttribute('opacity', newOpac, [elem]);\n    }\n\n    if (gattrs.filter) {\n      let cblur = this.getBlur(elem);\n      const origCblur = cblur;\n      if (!gblur) { gblur = this.getBlur(g); }\n      if (cblur) {\n        // Is this formula correct?\n        cblur = Number(gblur) + Number(cblur);\n      } else if (cblur === 0) {\n        cblur = gblur;\n      }\n\n      // If child has no current filter, get group's filter or clone it.\n      if (!origCblur) {\n        // Set group's filter to use first child's ID\n        if (!gfilter) {\n          gfilter = getRefElem(gattrs.filter);\n        } else {\n          // Clone the group's filter\n          gfilter = drawing.copyElem(gfilter);\n          findDefs().appendChild(gfilter);\n        }\n      } else {\n        gfilter = getRefElem(elem.getAttribute('filter'));\n      }\n\n      // Change this in future for different filters\n      const suffix = (gfilter.firstChild.tagName === 'feGaussianBlur') ? 'blur' : 'filter';\n      gfilter.id = elem.id + '_' + suffix;\n      changeSelectedAttribute('filter', 'url(#' + gfilter.id + ')', [elem]);\n\n      // Update blur value\n      if (cblur) {\n        changeSelectedAttribute('stdDeviation', cblur, [gfilter.firstChild]);\n        canvas.setBlurOffsets(gfilter, cblur);\n      }\n    }\n\n    let chtlist = getTransformList(elem);\n\n    // Don't process gradient transforms\n    if (elem.tagName.includes('Gradient')) { chtlist = null; }\n\n    // Hopefully not a problem to add this. Necessary for elements like <desc/>\n    if (!chtlist) { continue; }\n\n    // Apparently <defs> can get get a transformlist, but we don't want it to have one!\n    if (elem.tagName === 'defs') { continue; }\n\n    if (glist.numberOfItems) {\n      // TODO: if the group's transform is just a rotate, we can always transfer the\n      // rotate() down to the children (collapsing consecutive rotates and factoring\n      // out any translates)\n      if (gangle && glist.numberOfItems === 1) {\n        // [Rg] [Rc] [Mc]\n        // we want [Tr] [Rc2] [Mc] where:\n        //  - [Rc2] is at the child's current center but has the\n        // sum of the group and child's rotation angles\n        //  - [Tr] is the equivalent translation that this child\n        // undergoes if the group wasn't there\n\n        // [Tr] = [Rg] [Rc] [Rc2_inv]\n\n        // get group's rotation matrix (Rg)\n        const rgm = glist.getItem(0).matrix;\n\n        // get child's rotation matrix (Rc)\n        let rcm = svgroot.createSVGMatrix();\n        const cangle = getRotationAngle(elem);\n        if (cangle) {\n          rcm = chtlist.getItem(0).matrix;\n        }\n\n        // get child's old center of rotation\n        const cbox = utilsGetBBox(elem);\n        const ceqm = transformListToTransform(chtlist).matrix;\n        const coldc = transformPoint(cbox.x + cbox.width / 2, cbox.y + cbox.height / 2, ceqm);\n\n        // sum group and child's angles\n        const sangle = gangle + cangle;\n\n        // get child's rotation at the old center (Rc2_inv)\n        const r2 = svgroot.createSVGTransform();\n        r2.setRotate(sangle, coldc.x, coldc.y);\n\n        // calculate equivalent translate\n        const trm = matrixMultiply(rgm, rcm, r2.matrix.inverse());\n\n        // set up tlist\n        if (cangle) {\n          chtlist.removeItem(0);\n        }\n\n        if (sangle) {\n          if (chtlist.numberOfItems) {\n            chtlist.insertItemBefore(r2, 0);\n          } else {\n            chtlist.appendItem(r2);\n          }\n        }\n\n        if (trm.e || trm.f) {\n          const tr = svgroot.createSVGTransform();\n          tr.setTranslate(trm.e, trm.f);\n          if (chtlist.numberOfItems) {\n            chtlist.insertItemBefore(tr, 0);\n          } else {\n            chtlist.appendItem(tr);\n          }\n        }\n      } else { // more complicated than just a rotate\n        // transfer the group's transform down to each child and then\n        // call recalculateDimensions()\n        const oldxform = elem.getAttribute('transform');\n        changes = {};\n        changes.transform = oldxform || '';\n\n        const newxform = svgroot.createSVGTransform();\n\n        // [ gm ] [ chm ] = [ chm ] [ gm' ]\n        // [ gm' ] = [ chmInv ] [ gm ] [ chm ]\n        const chm = transformListToTransform(chtlist).matrix,\n          chmInv = chm.inverse();\n        const gm = matrixMultiply(chmInv, m, chm);\n        newxform.setMatrix(gm);\n        chtlist.appendItem(newxform);\n      }\n      const cmd = recalculateDimensions(elem);\n      if (cmd) { batchCmd.addSubCommand(cmd); }\n    }\n  }\n\n  // remove transform and make it undo-able\n  if (xform) {\n    changes = {};\n    changes.transform = xform;\n    g.setAttribute('transform', '');\n    g.removeAttribute('transform');\n    batchCmd.addSubCommand(new ChangeElementCommand(g, changes));\n  }\n\n  if (undoable && !batchCmd.isEmpty()) {\n    return batchCmd;\n  }\n};\n\n/**\n* Unwraps all the elements in a selected group (g) element. This requires\n* significant recalculations to apply group's transforms, etc to its children\n*/\nthis.ungroupSelectedElement = function () {\n  let g = selectedElements[0];\n  if (!g) {\n    return;\n  }\n  if ($(g).data('gsvg') || $(g).data('symbol')) {\n    // Is svg, so actually convert to group\n    convertToGroup(g);\n    return;\n  }\n  if (g.tagName === 'use') {\n    // Somehow doesn't have data set, so retrieve\n    const symbol = getElem(getHref(g).substr(1));\n    $(g).data('symbol', symbol).data('ref', symbol);\n    convertToGroup(g);\n    return;\n  }\n  const parentsA = $(g).parents('a');\n  if (parentsA.length) {\n    g = parentsA[0];\n  }\n\n  // Look for parent \"a\"\n  if (g.tagName === 'g' || g.tagName === 'a') {\n    const batchCmd = new BatchCommand('Ungroup Elements');\n    const cmd = pushGroupProperties(g, true);\n    if (cmd) { batchCmd.addSubCommand(cmd); }\n\n    const parent = g.parentNode;\n    const anchor = g.nextSibling;\n    const children = new Array(g.childNodes.length);\n\n    let i = 0;\n    while (g.firstChild) {\n      let elem = g.firstChild;\n      const oldNextSibling = elem.nextSibling;\n      const oldParent = elem.parentNode;\n\n      // Remove child title elements\n      if (elem.tagName === 'title') {\n        const {nextSibling} = elem;\n        batchCmd.addSubCommand(new RemoveElementCommand(elem, nextSibling, oldParent));\n        oldParent.removeChild(elem);\n        continue;\n      }\n\n      children[i++] = elem = parent.insertBefore(elem, anchor);\n      batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldParent));\n    }\n\n    // remove the group from the selection\n    clearSelection();\n\n    // delete the group element (but make undo-able)\n    const gNextSibling = g.nextSibling;\n    g = parent.removeChild(g);\n    batchCmd.addSubCommand(new RemoveElementCommand(g, gNextSibling, parent));\n\n    if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); }\n\n    // update selection\n    addToSelection(children);\n  }\n};\n\n/**\n* Repositions the selected element to the bottom in the DOM to appear on top of\n* other elements\n*/\nthis.moveToTopSelectedElement = function () {\n  const selected = selectedElements[0];\n  if (selected != null) {\n    let t = selected;\n    const oldParent = t.parentNode;\n    const oldNextSibling = t.nextSibling;\n    t = t.parentNode.appendChild(t);\n    // If the element actually moved position, add the command and fire the changed\n    // event handler.\n    if (oldNextSibling !== t.nextSibling) {\n      addCommandToHistory(new MoveElementCommand(t, oldNextSibling, oldParent, 'top'));\n      call('changed', [t]);\n    }\n  }\n};\n\n/**\n* Repositions the selected element to the top in the DOM to appear under\n* other elements\n*/\nthis.moveToBottomSelectedElement = function () {\n  const selected = selectedElements[0];\n  if (selected != null) {\n    let t = selected;\n    const oldParent = t.parentNode;\n    const oldNextSibling = t.nextSibling;\n    let {firstChild} = t.parentNode;\n    if (firstChild.tagName === 'title') {\n      firstChild = firstChild.nextSibling;\n    }\n    // This can probably be removed, as the defs should not ever apppear\n    // inside a layer group\n    if (firstChild.tagName === 'defs') {\n      firstChild = firstChild.nextSibling;\n    }\n    t = t.parentNode.insertBefore(t, firstChild);\n    // If the element actually moved position, add the command and fire the changed\n    // event handler.\n    if (oldNextSibling !== t.nextSibling) {\n      addCommandToHistory(new MoveElementCommand(t, oldNextSibling, oldParent, 'bottom'));\n      call('changed', [t]);\n    }\n  }\n};\n\n/**\n* Moves the select element up or down the stack, based on the visibly\n* intersecting elements\n* @param {\"Up\"|\"Down\"} dir - String that's either 'Up' or 'Down'\n*/\nthis.moveUpDownSelected = function (dir) {\n  const selected = selectedElements[0];\n  if (!selected) { return; }\n\n  curBBoxes = [];\n  let closest, foundCur;\n  // jQuery sorts this list\n  const list = $(getIntersectionList(getStrokedBBoxDefaultVisible([selected]))).toArray();\n  if (dir === 'Down') { list.reverse(); }\n\n  $.each(list, function () {\n    if (!foundCur) {\n      if (this === selected) {\n        foundCur = true;\n      }\n      return;\n    }\n    closest = this;\n    return false;\n  });\n  if (!closest) { return; }\n\n  const t = selected;\n  const oldParent = t.parentNode;\n  const oldNextSibling = t.nextSibling;\n  $(closest)[dir === 'Down' ? 'before' : 'after'](t);\n  // If the element actually moved position, add the command and fire the changed\n  // event handler.\n  if (oldNextSibling !== t.nextSibling) {\n    addCommandToHistory(new MoveElementCommand(t, oldNextSibling, oldParent, 'Move ' + dir));\n    call('changed', [t]);\n  }\n};\n\n/**\n* Moves selected elements on the X/Y axis\n* @param {Number} dx - Float with the distance to move on the x-axis\n* @param {Number} dy - Float with the distance to move on the y-axis\n* @param {Boolean} undoable - Boolean indicating whether or not the action should be undoable\n* @returns Batch command for the move\n*/\nthis.moveSelectedElements = function (dx, dy, undoable) {\n  // if undoable is not sent, default to true\n  // if single values, scale them to the zoom\n  if (dx.constructor !== Array) {\n    dx /= currentZoom;\n    dy /= currentZoom;\n  }\n  undoable = undoable || true;\n  const batchCmd = new BatchCommand('position');\n  let i = selectedElements.length;\n  while (i--) {\n    const selected = selectedElements[i];\n    if (selected != null) {\n      // if (i === 0) {\n      //   selectedBBoxes[0] = utilsGetBBox(selected);\n      // }\n      // const b = {};\n      // for (const j in selectedBBoxes[i]) b[j] = selectedBBoxes[i][j];\n      // selectedBBoxes[i] = b;\n\n      const xform = svgroot.createSVGTransform();\n      const tlist = getTransformList(selected);\n\n      // dx and dy could be arrays\n      if (dx.constructor === Array) {\n        // if (i === 0) {\n        //   selectedBBoxes[0].x += dx[0];\n        //   selectedBBoxes[0].y += dy[0];\n        // }\n        xform.setTranslate(dx[i], dy[i]);\n      } else {\n        // if (i === 0) {\n        //   selectedBBoxes[0].x += dx;\n        //   selectedBBoxes[0].y += dy;\n        // }\n        xform.setTranslate(dx, dy);\n      }\n\n      if (tlist.numberOfItems) {\n        tlist.insertItemBefore(xform, 0);\n      } else {\n        tlist.appendItem(xform);\n      }\n\n      const cmd = recalculateDimensions(selected);\n      if (cmd) {\n        batchCmd.addSubCommand(cmd);\n      }\n\n      selectorManager.requestSelector(selected).resize();\n    }\n  }\n  if (!batchCmd.isEmpty()) {\n    if (undoable) {\n      addCommandToHistory(batchCmd);\n    }\n    call('changed', selectedElements);\n    return batchCmd;\n  }\n};\n\n/**\n* Create deep DOM copies (clones) of all selected elements and move them slightly\n* from their originals\n*/\nthis.cloneSelectedElements = function (x, y) {\n  let i, elem;\n  const batchCmd = new BatchCommand('Clone Elements');\n  // find all the elements selected (stop at first null)\n  const len = selectedElements.length;\n  function sortfunction (a, b) {\n    return ($(b).index() - $(a).index()); // causes an array to be sorted numerically and ascending\n  }\n  selectedElements.sort(sortfunction);\n  for (i = 0; i < len; ++i) {\n    elem = selectedElements[i];\n    if (elem == null) { break; }\n  }\n  // use slice to quickly get the subset of elements we need\n  const copiedElements = selectedElements.slice(0, i);\n  this.clearSelection(true);\n  // note that we loop in the reverse way because of the way elements are added\n  // to the selectedElements array (top-first)\n  const drawing = getCurrentDrawing();\n  i = copiedElements.length;\n  while (i--) {\n    // clone each element and replace it within copiedElements\n    elem = copiedElements[i] = drawing.copyElem(copiedElements[i]);\n    (currentGroup || drawing.getCurrentLayer()).appendChild(elem);\n    batchCmd.addSubCommand(new InsertElementCommand(elem));\n  }\n\n  if (!batchCmd.isEmpty()) {\n    addToSelection(copiedElements.reverse()); // Need to reverse for correct selection-adding\n    this.moveSelectedElements(x, y, false);\n    addCommandToHistory(batchCmd);\n  }\n};\n\n/**\n* Aligns selected elements\n* @param {String} type - String with single character indicating the alignment type\n* @param {\"selected\"|\"largest\"|\"smallest\"|\"page\"} relativeTo\n*/\nthis.alignSelectedElements = function (type, relativeTo) {\n  const bboxes = []; // angles = [];\n  const len = selectedElements.length;\n  if (!len) { return; }\n  let minx = Number.MAX_VALUE, maxx = Number.MIN_VALUE,\n    miny = Number.MAX_VALUE, maxy = Number.MIN_VALUE;\n  let curwidth = Number.MIN_VALUE, curheight = Number.MIN_VALUE;\n  for (let i = 0; i < len; ++i) {\n    if (selectedElements[i] == null) { break; }\n    const elem = selectedElements[i];\n    bboxes[i] = getStrokedBBoxDefaultVisible([elem]);\n\n    // now bbox is axis-aligned and handles rotation\n    switch (relativeTo) {\n    case 'smallest':\n      if (((type === 'l' || type === 'c' || type === 'r') &&\n        (curwidth === Number.MIN_VALUE || curwidth > bboxes[i].width)) ||\n        ((type === 't' || type === 'm' || type === 'b') &&\n        (curheight === Number.MIN_VALUE || curheight > bboxes[i].height))\n      ) {\n        minx = bboxes[i].x;\n        miny = bboxes[i].y;\n        maxx = bboxes[i].x + bboxes[i].width;\n        maxy = bboxes[i].y + bboxes[i].height;\n        curwidth = bboxes[i].width;\n        curheight = bboxes[i].height;\n      }\n      break;\n    case 'largest':\n      if (((type === 'l' || type === 'c' || type === 'r') &&\n        (curwidth === Number.MIN_VALUE || curwidth < bboxes[i].width)) ||\n        ((type === 't' || type === 'm' || type === 'b') &&\n        (curheight === Number.MIN_VALUE || curheight < bboxes[i].height))\n      ) {\n        minx = bboxes[i].x;\n        miny = bboxes[i].y;\n        maxx = bboxes[i].x + bboxes[i].width;\n        maxy = bboxes[i].y + bboxes[i].height;\n        curwidth = bboxes[i].width;\n        curheight = bboxes[i].height;\n      }\n      break;\n    default: // 'selected'\n      if (bboxes[i].x < minx) { minx = bboxes[i].x; }\n      if (bboxes[i].y < miny) { miny = bboxes[i].y; }\n      if (bboxes[i].x + bboxes[i].width > maxx) { maxx = bboxes[i].x + bboxes[i].width; }\n      if (bboxes[i].y + bboxes[i].height > maxy) { maxy = bboxes[i].y + bboxes[i].height; }\n      break;\n    }\n  } // loop for each element to find the bbox and adjust min/max\n\n  if (relativeTo === 'page') {\n    minx = 0;\n    miny = 0;\n    maxx = canvas.contentW;\n    maxy = canvas.contentH;\n  }\n\n  const dx = new Array(len);\n  const dy = new Array(len);\n  for (let i = 0; i < len; ++i) {\n    if (selectedElements[i] == null) { break; }\n    // const elem = selectedElements[i];\n    const bbox = bboxes[i];\n    dx[i] = 0;\n    dy[i] = 0;\n    switch (type) {\n    case 'l': // left (horizontal)\n      dx[i] = minx - bbox.x;\n      break;\n    case 'c': // center (horizontal)\n      dx[i] = (minx + maxx) / 2 - (bbox.x + bbox.width / 2);\n      break;\n    case 'r': // right (horizontal)\n      dx[i] = maxx - (bbox.x + bbox.width);\n      break;\n    case 't': // top (vertical)\n      dy[i] = miny - bbox.y;\n      break;\n    case 'm': // middle (vertical)\n      dy[i] = (miny + maxy) / 2 - (bbox.y + bbox.height / 2);\n      break;\n    case 'b': // bottom (vertical)\n      dy[i] = maxy - (bbox.y + bbox.height);\n      break;\n    }\n  }\n  this.moveSelectedElements(dx, dy);\n};\n\n/**\n* Group: Additional editor tools\n*/\n\nthis.contentW = getResolution().w;\nthis.contentH = getResolution().h;\n\n/**\n* Updates the editor canvas width/height/position after a zoom has occurred\n* @param {Number} w - Float with the new width\n* @param {Number} h - Float with the new height\n* @returns Object with the following values:\n* - x - The canvas' new x coordinate\n* - y - The canvas' new y coordinate\n* - oldX - The canvas' old x coordinate\n* - oldY - The canvas' old y coordinate\n* - d_x - The x position difference\n* - d_y - The y position difference\n*/\nthis.updateCanvas = function (w, h) {\n  svgroot.setAttribute('width', w);\n  svgroot.setAttribute('height', h);\n  const bg = $('#canvasBackground')[0];\n  const oldX = svgcontent.getAttribute('x');\n  const oldY = svgcontent.getAttribute('y');\n  const x = (w / 2 - this.contentW * currentZoom / 2);\n  const y = (h / 2 - this.contentH * currentZoom / 2);\n\n  assignAttributes(svgcontent, {\n    width: this.contentW * currentZoom,\n    height: this.contentH * currentZoom,\n    x,\n    y,\n    viewBox: '0 0 ' + this.contentW + ' ' + this.contentH\n  });\n\n  assignAttributes(bg, {\n    width: svgcontent.getAttribute('width'),\n    height: svgcontent.getAttribute('height'),\n    x,\n    y\n  });\n\n  const bgImg = getElem('background_image');\n  if (bgImg) {\n    assignAttributes(bgImg, {\n      width: '100%',\n      height: '100%'\n    });\n  }\n\n  selectorManager.selectorParentGroup.setAttribute('transform', 'translate(' + x + ',' + y + ')');\n  runExtensions('canvasUpdated', {new_x: x, new_y: y, old_x: oldX, old_y: oldY, d_x: x - oldX, d_y: y - oldY});\n  return {x, y, old_x: oldX, old_y: oldY, d_x: x - oldX, d_y: y - oldY};\n};\n\n/**\n* Set the background of the editor (NOT the actual document)\n* @param {String} color - String with fill color to apply\n* @param url - URL or path to image to use\n*/\nthis.setBackground = function (color, url) {\n  const bg = getElem('canvasBackground');\n  const border = $(bg).find('rect')[0];\n  let bgImg = getElem('background_image');\n  border.setAttribute('fill', color);\n  if (url) {\n    if (!bgImg) {\n      bgImg = svgdoc.createElementNS(NS.SVG, 'image');\n      assignAttributes(bgImg, {\n        id: 'background_image',\n        width: '100%',\n        height: '100%',\n        preserveAspectRatio: 'xMinYMin',\n        style: 'pointer-events:none'\n      });\n    }\n    setHref(bgImg, url);\n    bg.appendChild(bgImg);\n  } else if (bgImg) {\n    bgImg.parentNode.removeChild(bgImg);\n  }\n};\n\n/**\n* Select the next/previous element within the current layer\n* @param {Boolean} next - true = next and false = previous element\n*/\nthis.cycleElement = function (next) {\n  let num;\n  const curElem = selectedElements[0];\n  let elem = false;\n  const allElems = getVisibleElements(currentGroup || getCurrentDrawing().getCurrentLayer());\n  if (!allElems.length) { return; }\n  if (curElem == null) {\n    num = next ? allElems.length - 1 : 0;\n    elem = allElems[num];\n  } else {\n    let i = allElems.length;\n    while (i--) {\n      if (allElems[i] === curElem) {\n        num = next ? i - 1 : i + 1;\n        if (num >= allElems.length) {\n          num = 0;\n        } else if (num < 0) {\n          num = allElems.length - 1;\n        }\n        elem = allElems[num];\n        break;\n      }\n    }\n  }\n  selectOnly([elem], true);\n  call('selected', selectedElements);\n};\n\nthis.clear();\n\n/**\n* @deprecated getPrivateMethods\n* Since all methods are/should be public somehow, this function should be removed;\n*  we might require `import` in place of this in the future once ES6 Modules\n*  widespread\n\n* Being able to access private methods publicly seems wrong somehow,\n* but currently appears to be the best way to allow testing and provide\n* access to them to plugins.\n*/\nthis.getPrivateMethods = function () {\n  const obj = {\n    addCommandToHistory,\n    setGradient,\n    addSvgElementFromJson,\n    assignAttributes,\n    BatchCommand,\n    buildCanvgCallback,\n    call,\n    canvg,\n    ChangeElementCommand,\n    copyElem (elem) { return getCurrentDrawing().copyElem(elem); },\n    decode64,\n    encode64,\n    executeAfterLoads,\n    ffClone,\n    findDefs,\n    findDuplicateGradient,\n    getElem,\n    getId,\n    getIntersectionList,\n    getMouseTarget,\n    getNextId,\n    getPathBBox,\n    getTypeMap,\n    getUrlFromAttr,\n    hasMatrixTransform,\n    identifyLayers: draw.identifyLayers,\n    InsertElementCommand,\n    isChrome,\n    isIdentity,\n    isIE,\n    logMatrix,\n    matrixMultiply,\n    MoveElementCommand,\n    NS,\n    preventClickDefault,\n    recalculateAllSelectedDimensions,\n    recalculateDimensions,\n    remapElement,\n    RemoveElementCommand,\n    removeUnusedDefElems,\n    round,\n    runExtensions,\n    sanitizeSvg,\n    SVGEditTransformList,\n    text2xml,\n    toString,\n    transformBox,\n    transformListToTransform,\n    transformPoint,\n    walkTree\n  };\n  return obj;\n};\n  } // End constructor\n} // End class\n\nexport default SvgCanvas;\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/svgedit.js",
    "content": "/**\n *\n * Licensed under the MIT License\n */\n\n/**\n* Common namepaces constants in alpha order\n*/\nexport const NS = {\n  HTML: 'http://www.w3.org/1999/xhtml',\n  MATH: 'http://www.w3.org/1998/Math/MathML',\n  SE: 'http://svg-edit.googlecode.com',\n  SVG: 'http://www.w3.org/2000/svg',\n  XLINK: 'http://www.w3.org/1999/xlink',\n  XML: 'http://www.w3.org/XML/1998/namespace',\n  XMLNS: 'http://www.w3.org/2000/xmlns/' // see http://www.w3.org/TR/REC-xml-names/#xmlReserved\n};\n\n/**\n* @returns The NS with key values switched and lowercase\n*/\nexport const getReverseNS = function () {\n  const reverseNS = {};\n  Object.entries(NS).forEach(([name, URI]) => {\n    reverseNS[URI] = name.toLowerCase();\n  });\n  return reverseNS;\n};\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/svgtransformlist.js",
    "content": "/**\n * SVGTransformList\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2010 Alexis Deveria\n * Copyright(c) 2010 Jeff Schiller\n */\n\nimport {NS} from './svgedit.js';\nimport {supportsNativeTransformLists} from './browser.js';\n\nconst svgroot = document.createElementNS(NS.SVG, 'svg');\n\n// Helper function.\nfunction transformToString (xform) {\n  const m = xform.matrix;\n  let text = '';\n  switch (xform.type) {\n  case 1: // MATRIX\n    text = 'matrix(' + [m.a, m.b, m.c, m.d, m.e, m.f].join(',') + ')';\n    break;\n  case 2: // TRANSLATE\n    text = 'translate(' + m.e + ',' + m.f + ')';\n    break;\n  case 3: // SCALE\n    if (m.a === m.d) {\n      text = 'scale(' + m.a + ')';\n    } else {\n      text = 'scale(' + m.a + ',' + m.d + ')';\n    }\n    break;\n  case 4: { // ROTATE\n    let cx = 0;\n    let cy = 0;\n    // this prevents divide by zero\n    if (xform.angle !== 0) {\n      const K = 1 - m.a;\n      cy = (K * m.f + m.b * m.e) / (K * K + m.b * m.b);\n      cx = (m.e - m.b * cy) / K;\n    }\n    text = 'rotate(' + xform.angle + ' ' + cx + ',' + cy + ')';\n    break;\n  }\n  }\n  return text;\n}\n\n/**\n * Map of SVGTransformList objects.\n */\nlet listMap_ = {};\n\n// **************************************************************************************\n// SVGTransformList implementation for Webkit\n// These methods do not currently raise any exceptions.\n// These methods also do not check that transforms are being inserted.  This is basically\n// implementing as much of SVGTransformList that we need to get the job done.\n//\n//  interface SVGEditTransformList {\n//    attribute unsigned long numberOfItems;\n//    void   clear (  )\n//    SVGTransform initialize ( in SVGTransform newItem )\n//    SVGTransform getItem ( in unsigned long index ) (DOES NOT THROW DOMException, INDEX_SIZE_ERR)\n//    SVGTransform insertItemBefore ( in SVGTransform newItem, in unsigned long index ) (DOES NOT THROW DOMException, INDEX_SIZE_ERR)\n//    SVGTransform replaceItem ( in SVGTransform newItem, in unsigned long index ) (DOES NOT THROW DOMException, INDEX_SIZE_ERR)\n//    SVGTransform removeItem ( in unsigned long index ) (DOES NOT THROW DOMException, INDEX_SIZE_ERR)\n//    SVGTransform appendItem ( in SVGTransform newItem )\n//    NOT IMPLEMENTED: SVGTransform createSVGTransformFromMatrix ( in SVGMatrix matrix );\n//    NOT IMPLEMENTED: SVGTransform consolidate (  );\n//  }\n// **************************************************************************************\nexport class SVGTransformList {\n  constructor (elem) {\n    this._elem = elem || null;\n    this._xforms = [];\n    // TODO: how do we capture the undo-ability in the changed transform list?\n    this._update = function () {\n      let tstr = '';\n      /* const concatMatrix = */ svgroot.createSVGMatrix();\n      for (let i = 0; i < this.numberOfItems; ++i) {\n        const xform = this._list.getItem(i);\n        tstr += transformToString(xform) + ' ';\n      }\n      this._elem.setAttribute('transform', tstr);\n    };\n    this._list = this;\n    this._init = function () {\n      // Transform attribute parser\n      let str = this._elem.getAttribute('transform');\n      if (!str) { return; }\n\n      // TODO: Add skew support in future\n      const re = /\\s*((scale|matrix|rotate|translate)\\s*\\(.*?\\))\\s*,?\\s*/;\n      let m = true;\n      while (m) {\n        m = str.match(re);\n        str = str.replace(re, '');\n        if (m && m[1]) {\n          const x = m[1];\n          const bits = x.split(/\\s*\\(/);\n          const name = bits[0];\n          const valBits = bits[1].match(/\\s*(.*?)\\s*\\)/);\n          valBits[1] = valBits[1].replace(/(\\d)-/g, '$1 -');\n          const valArr = valBits[1].split(/[, ]+/);\n          const letters = 'abcdef'.split('');\n          const mtx = svgroot.createSVGMatrix();\n          Object.values(valArr).forEach(function (item, i) {\n            valArr[i] = parseFloat(item);\n            if (name === 'matrix') {\n              mtx[letters[i]] = valArr[i];\n            }\n          });\n          const xform = svgroot.createSVGTransform();\n          const fname = 'set' + name.charAt(0).toUpperCase() + name.slice(1);\n          const values = name === 'matrix' ? [mtx] : valArr;\n\n          if (name === 'scale' && values.length === 1) {\n            values.push(values[0]);\n          } else if (name === 'translate' && values.length === 1) {\n            values.push(0);\n          } else if (name === 'rotate' && values.length === 1) {\n            values.push(0, 0);\n          }\n          xform[fname].apply(xform, values);\n          this._list.appendItem(xform);\n        }\n      }\n    };\n    this._removeFromOtherLists = function (item) {\n      if (item) {\n        // Check if this transform is already in a transformlist, and\n        // remove it if so.\n        let found = false;\n        for (const id in listMap_) {\n          const tl = listMap_[id];\n          for (let i = 0, len = tl._xforms.length; i < len; ++i) {\n            if (tl._xforms[i] === item) {\n              found = true;\n              tl.removeItem(i);\n              break;\n            }\n          }\n          if (found) {\n            break;\n          }\n        }\n      }\n    };\n\n    this.numberOfItems = 0;\n    this.clear = function () {\n      this.numberOfItems = 0;\n      this._xforms = [];\n    };\n\n    this.initialize = function (newItem) {\n      this.numberOfItems = 1;\n      this._removeFromOtherLists(newItem);\n      this._xforms = [newItem];\n    };\n\n    this.getItem = function (index) {\n      if (index < this.numberOfItems && index >= 0) {\n        return this._xforms[index];\n      }\n      const err = new Error('DOMException with code=INDEX_SIZE_ERR');\n      err.code = 1;\n      throw err;\n    };\n\n    this.insertItemBefore = function (newItem, index) {\n      let retValue = null;\n      if (index >= 0) {\n        if (index < this.numberOfItems) {\n          this._removeFromOtherLists(newItem);\n          const newxforms = new Array(this.numberOfItems + 1);\n          // TODO: use array copying and slicing\n          let i;\n          for (i = 0; i < index; ++i) {\n            newxforms[i] = this._xforms[i];\n          }\n          newxforms[i] = newItem;\n          for (let j = i + 1; i < this.numberOfItems; ++j, ++i) {\n            newxforms[j] = this._xforms[i];\n          }\n          this.numberOfItems++;\n          this._xforms = newxforms;\n          retValue = newItem;\n          this._list._update();\n        } else {\n          retValue = this._list.appendItem(newItem);\n        }\n      }\n      return retValue;\n    };\n\n    this.replaceItem = function (newItem, index) {\n      let retValue = null;\n      if (index < this.numberOfItems && index >= 0) {\n        this._removeFromOtherLists(newItem);\n        this._xforms[index] = newItem;\n        retValue = newItem;\n        this._list._update();\n      }\n      return retValue;\n    };\n\n    this.removeItem = function (index) {\n      if (index < this.numberOfItems && index >= 0) {\n        const retValue = this._xforms[index];\n        const newxforms = new Array(this.numberOfItems - 1);\n        let i;\n        for (i = 0; i < index; ++i) {\n          newxforms[i] = this._xforms[i];\n        }\n        for (let j = i; j < this.numberOfItems - 1; ++j, ++i) {\n          newxforms[j] = this._xforms[i + 1];\n        }\n        this.numberOfItems--;\n        this._xforms = newxforms;\n        this._list._update();\n        return retValue;\n      }\n      const err = new Error('DOMException with code=INDEX_SIZE_ERR');\n      err.code = 1;\n      throw err;\n    };\n\n    this.appendItem = function (newItem) {\n      this._removeFromOtherLists(newItem);\n      this._xforms.push(newItem);\n      this.numberOfItems++;\n      this._list._update();\n      return newItem;\n    };\n  }\n}\n\nexport const resetListMap = function () {\n  listMap_ = {};\n};\n\n/**\n * Removes transforms of the given element from the map.\n * Parameters:\n * elem - a DOM Element\n */\nexport let removeElementFromListMap = function (elem) {\n  if (elem.id && listMap_[elem.id]) {\n    delete listMap_[elem.id];\n  }\n};\n\n/**\n* Returns an object that behaves like a SVGTransformList for the given DOM element\n* @param elem - DOM element to get a transformlist from\n*/\nexport const getTransformList = function (elem) {\n  if (!supportsNativeTransformLists()) {\n    const id = elem.id || 'temp';\n    let t = listMap_[id];\n    if (!t || id === 'temp') {\n      listMap_[id] = new SVGTransformList(elem);\n      listMap_[id]._init();\n      t = listMap_[id];\n    }\n    return t;\n  }\n  if (elem.transform) {\n    return elem.transform.baseVal;\n  }\n  if (elem.gradientTransform) {\n    return elem.gradientTransform.baseVal;\n  }\n  if (elem.patternTransform) {\n    return elem.patternTransform.baseVal;\n  }\n\n  return null;\n};\n\n// For unit-testing\nexport const changeRemoveElementFromListMap = function (cb) {\n  removeElementFromListMap = cb;\n};\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/svgutils.js",
    "content": "/* globals jQuery, ActiveXObject */\n/**\n * Package: svgedit.utilities\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2010 Alexis Deveria\n * Copyright(c) 2010 Jeff Schiller\n */\n\nimport './pathseg.js';\nimport RGBColor from './canvg/rgbcolor.js';\nimport jqPluginSVG from './jquery-svg.js'; // Needed for SVG attribute setting and array form with `attr`\nimport {importScript, importModule} from './external/dynamic-import-polyfill/importModule.js';\nimport {NS} from './svgedit.js';\nimport {getTransformList} from './svgtransformlist.js';\nimport {setUnitAttr, getTypeMap} from './units.js';\nimport {convertPath} from './path.js';\nimport {\n  hasMatrixTransform, transformListToTransform, transformBox\n} from './math.js';\nimport {\n  isWebkit, supportsHVLineContainerBBox, supportsPathBBox, supportsXpath,\n  supportsSelectors\n} from './browser.js';\n\n// Constants\nconst $ = jqPluginSVG(jQuery);\n\n// String used to encode base64.\nconst KEYSTR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n// Much faster than running getBBox() every time\nconst visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use';\nconst visElemsArr = visElems.split(',');\n// const hidElems = 'clipPath,defs,desc,feGaussianBlur,filter,linearGradient,marker,mask,metadata,pattern,radialGradient,stop,switch,symbol,title,textPath';\n\nlet editorContext_ = null;\nlet domdoc_ = null;\nlet domcontainer_ = null;\nlet svgroot_ = null;\n\nexport const init = function (editorContext) {\n  editorContext_ = editorContext;\n  domdoc_ = editorContext.getDOMDocument();\n  domcontainer_ = editorContext.getDOMContainer();\n  svgroot_ = editorContext.getSVGRoot();\n};\n\n/**\n* Converts characters in a string to XML-friendly entities.\n* @example: '&' becomes '&amp;'\n* @param str - The string to be converted\n* @returns {String} The converted string\n*/\nexport const toXml = function (str) {\n  // &apos; is ok in XML, but not HTML\n  // &gt; does not normally need escaping, though it can if within a CDATA expression (and preceded by \"]]\")\n  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/, '&#x27;');\n};\n\n/**\n* Converts XML entities in a string to single characters.\n* @example '&amp;amp;' becomes '&amp;'\n* @param str - The string to be converted\n* @returns The converted string\n*/\nexport const fromXml = function (str) {\n  return $('<p/>').html(str).text();\n};\n\n// This code was written by Tyler Akins and has been placed in the\n// public domain.  It would be nice if you left this header intact.\n// Base64 code from Tyler Akins -- http://rumkin.com\n\n// schiller: Removed string concatenation in favour of Array.join() optimization,\n//        also precalculate the size of the array needed.\n\n// Converts a string to base64\nexport const encode64 = function (input) {\n  // base64 strings are 4/3 larger than the original string\n  input = encodeUTF8(input); // convert non-ASCII characters\n  // input = convertToXMLReferences(input);\n  if (window.btoa) {\n    return window.btoa(input); // Use native if available\n  }\n  const output = [];\n  output.length = Math.floor((input.length + 2) / 3) * 4;\n\n  let i = 0, p = 0;\n  do {\n    const chr1 = input.charCodeAt(i++);\n    const chr2 = input.charCodeAt(i++);\n    const chr3 = input.charCodeAt(i++);\n\n    const enc1 = chr1 >> 2;\n    const enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n\n    let enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n    let enc4 = chr3 & 63;\n\n    if (isNaN(chr2)) {\n      enc3 = enc4 = 64;\n    } else if (isNaN(chr3)) {\n      enc4 = 64;\n    }\n\n    output[p++] = KEYSTR.charAt(enc1);\n    output[p++] = KEYSTR.charAt(enc2);\n    output[p++] = KEYSTR.charAt(enc3);\n    output[p++] = KEYSTR.charAt(enc4);\n  } while (i < input.length);\n\n  return output.join('');\n};\n\n// Converts a string from base64\nexport const decode64 = function (input) {\n  if (window.atob) {\n    return decodeUTF8(window.atob(input));\n  }\n\n  // remove all characters that are not A-Z, a-z, 0-9, +, /, or =\n  input = input.replace(/[^A-Za-z0-9+/=]/g, '');\n\n  let output = '';\n  let i = 0;\n\n  do {\n    const enc1 = KEYSTR.indexOf(input.charAt(i++));\n    const enc2 = KEYSTR.indexOf(input.charAt(i++));\n    const enc3 = KEYSTR.indexOf(input.charAt(i++));\n    const enc4 = KEYSTR.indexOf(input.charAt(i++));\n\n    const chr1 = (enc1 << 2) | (enc2 >> 4);\n    const chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);\n    const chr3 = ((enc3 & 3) << 6) | enc4;\n\n    output += String.fromCharCode(chr1);\n\n    if (enc3 !== 64) {\n      output = output + String.fromCharCode(chr2);\n    }\n    if (enc4 !== 64) {\n      output = output + String.fromCharCode(chr3);\n    }\n  } while (i < input.length);\n  return decodeUTF8(output);\n};\n\nexport const decodeUTF8 = function (argString) {\n  return decodeURIComponent(escape(argString));\n};\n\n// codedread:does not seem to work with webkit-based browsers on OSX // Brettz9: please test again as function upgraded\nexport const encodeUTF8 = function (argString) {\n  return unescape(encodeURIComponent(argString));\n};\n\n/**\n * convert dataURL to object URL\n * @param {string} dataurl\n * @return {string} object URL or empty string\n */\nexport const dataURLToObjectURL = function (dataurl) {\n  if (typeof Uint8Array === 'undefined' || typeof Blob === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL) {\n    return '';\n  }\n  const arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],\n    bstr = atob(arr[1]);\n  let n = bstr.length;\n  const u8arr = new Uint8Array(n);\n  while (n--) {\n    u8arr[n] = bstr.charCodeAt(n);\n  }\n  const blob = new Blob([u8arr], {type: mime});\n  return URL.createObjectURL(blob);\n};\n\n/**\n * get object URL for a blob object\n * @param {Blob} blob A Blob object or File object\n * @return {string} object URL or empty string\n */\nexport const createObjectURL = function (blob) {\n  if (!blob || typeof URL === 'undefined' || !URL.createObjectURL) {\n    return '';\n  }\n  return URL.createObjectURL(blob);\n};\n\n/**\n * @property {string} blankPageObjectURL\n */\nexport const blankPageObjectURL = (function () {\n  if (typeof Blob === 'undefined') {\n    return '';\n  }\n  const blob = new Blob(['<html><head><title>SVG-edit</title></head><body>&nbsp;</body></html>'], {type: 'text/html'});\n  return createObjectURL(blob);\n})();\n\n// Converts a string to use XML references\nexport const convertToXMLReferences = function (input) {\n  let n,\n    output = '';\n  for (n = 0; n < input.length; n++) {\n    const c = input.charCodeAt(n);\n    if (c < 128) {\n      output += input[n];\n    } else if (c > 127) {\n      output += ('&#' + c + ';');\n    }\n  }\n  return output;\n};\n\n// Cross-browser compatible method of converting a string to an XML tree\n// found this function here: http://groups.google.com/group/jquery-dev/browse_thread/thread/c6d11387c580a77f\nexport const text2xml = function (sXML) {\n  if (sXML.includes('<svg:svg')) {\n    sXML = sXML.replace(/<(\\/?)svg:/g, '<$1').replace('xmlns:svg', 'xmlns');\n  }\n\n  let out, dXML;\n  try {\n    dXML = (window.DOMParser) ? new DOMParser() : new ActiveXObject('Microsoft.XMLDOM');\n    dXML.async = false;\n  } catch (e) {\n    throw new Error('XML Parser could not be instantiated');\n  }\n  try {\n    if (dXML.loadXML) {\n      out = (dXML.loadXML(sXML)) ? dXML : false;\n    } else {\n      out = dXML.parseFromString(sXML, 'text/xml');\n    }\n  } catch (e2) { throw new Error('Error parsing XML string'); }\n  return out;\n};\n\n/**\n* Converts a SVGRect into an object.\n* @param bbox - a SVGRect\n* @returns An object with properties names x, y, width, height.\n*/\nexport const bboxToObj = function (bbox) {\n  return {\n    x: bbox.x,\n    y: bbox.y,\n    width: bbox.width,\n    height: bbox.height\n  };\n};\n\n/**\n* Walks the tree and executes the callback on each element in a top-down fashion\n* @param elem - DOM element to traverse\n* @param {Function} cbFn - Callback function to run on each element\n*/\nexport const walkTree = function (elem, cbFn) {\n  if (elem && elem.nodeType === 1) {\n    cbFn(elem);\n    let i = elem.childNodes.length;\n    while (i--) {\n      walkTree(elem.childNodes.item(i), cbFn);\n    }\n  }\n};\n\n/**\n* Walks the tree and executes the callback on each element in a depth-first fashion\n* @todo FIXME: Shouldn't this be calling walkTreePost?\n* @param elem - DOM element to traverse\n* @param {Function} cbFn - Callback function to run on each element\n*/\nexport const walkTreePost = function (elem, cbFn) {\n  if (elem && elem.nodeType === 1) {\n    let i = elem.childNodes.length;\n    while (i--) {\n      walkTree(elem.childNodes.item(i), cbFn);\n    }\n    cbFn(elem);\n  }\n};\n\n/**\n* Extracts the URL from the url(...) syntax of some attributes.\n* Three variants:\n*  - <circle fill=\"url(someFile.svg#foo)\" />\n*  - <circle fill=\"url('someFile.svg#foo')\" />\n*  - <circle fill='url(\"someFile.svg#foo\")' />\n* @param attrVal - The attribute value as a string\n* @returns {String} String with just the URL, like \"someFile.svg#foo\"\n*/\nexport const getUrlFromAttr = function (attrVal) {\n  if (attrVal) {\n    // url('#somegrad')\n    if (attrVal.startsWith('url(\"')) {\n      return attrVal.substring(5, attrVal.indexOf('\"', 6));\n    }\n    // url('#somegrad')\n    if (attrVal.startsWith(\"url('\")) {\n      return attrVal.substring(5, attrVal.indexOf(\"'\", 6));\n    }\n    if (attrVal.startsWith('url(')) {\n      return attrVal.substring(4, attrVal.indexOf(')'));\n    }\n  }\n  return null;\n};\n\n/**\n* @returns The given element's xlink:href value\n*/\nexport let getHref = function (elem) {\n  return elem.getAttributeNS(NS.XLINK, 'href');\n};\n\n/**\n* Sets the given element's xlink:href value\n* @param elem\n* @param {String} val\n*/\nexport let setHref = function (elem, val) {\n  elem.setAttributeNS(NS.XLINK, 'xlink:href', val);\n};\n\n/**\n* @returns The document's &lt;defs> element, create it first if necessary\n*/\nexport const findDefs = function () {\n  const svgElement = editorContext_.getSVGContent();\n  let defs = svgElement.getElementsByTagNameNS(NS.SVG, 'defs');\n  if (defs.length > 0) {\n    defs = defs[0];\n  } else {\n    defs = svgElement.ownerDocument.createElementNS(NS.SVG, 'defs');\n    if (svgElement.firstChild) {\n      // first child is a comment, so call nextSibling\n      svgElement.insertBefore(defs, svgElement.firstChild.nextSibling);\n    } else {\n      svgElement.appendChild(defs);\n    }\n  }\n  return defs;\n};\n\n// TODO(codedread): Consider moving the next to functions to bbox.js\n\n/**\n* Get correct BBox for a path in Webkit\n* Converted from code found here:\n* http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html\n* @param path - The path DOM element to get the BBox for\n* @returns A BBox-like object\n*/\nexport const getPathBBox = function (path) {\n  const seglist = path.pathSegList;\n  const tot = seglist.numberOfItems;\n\n  const bounds = [[], []];\n  const start = seglist.getItem(0);\n  let P0 = [start.x, start.y];\n\n  for (let i = 0; i < tot; i++) {\n    const seg = seglist.getItem(i);\n\n    if (seg.x === undefined) { continue; }\n\n    // Add actual points to limits\n    bounds[0].push(P0[0]);\n    bounds[1].push(P0[1]);\n\n    if (seg.x1) {\n      const P1 = [seg.x1, seg.y1],\n        P2 = [seg.x2, seg.y2],\n        P3 = [seg.x, seg.y];\n\n      for (let j = 0; j < 2; j++) {\n        const calc = function (t) {\n          return Math.pow(1 - t, 3) * P0[j] +\n            3 * Math.pow(1 - t, 2) * t * P1[j] +\n            3 * (1 - t) * Math.pow(t, 2) * P2[j] +\n            Math.pow(t, 3) * P3[j];\n        };\n\n        const b = 6 * P0[j] - 12 * P1[j] + 6 * P2[j];\n        const a = -3 * P0[j] + 9 * P1[j] - 9 * P2[j] + 3 * P3[j];\n        const c = 3 * P1[j] - 3 * P0[j];\n\n        if (a === 0) {\n          if (b === 0) {\n            continue;\n          }\n          const t = -c / b;\n          if (t > 0 && t < 1) {\n            bounds[j].push(calc(t));\n          }\n          continue;\n        }\n        const b2ac = Math.pow(b, 2) - 4 * c * a;\n        if (b2ac < 0) { continue; }\n        const t1 = (-b + Math.sqrt(b2ac)) / (2 * a);\n        if (t1 > 0 && t1 < 1) { bounds[j].push(calc(t1)); }\n        const t2 = (-b - Math.sqrt(b2ac)) / (2 * a);\n        if (t2 > 0 && t2 < 1) { bounds[j].push(calc(t2)); }\n      }\n      P0 = P3;\n    } else {\n      bounds[0].push(seg.x);\n      bounds[1].push(seg.y);\n    }\n  }\n\n  const x = Math.min.apply(null, bounds[0]);\n  const w = Math.max.apply(null, bounds[0]) - x;\n  const y = Math.min.apply(null, bounds[1]);\n  const h = Math.max.apply(null, bounds[1]) - y;\n  return {\n    x,\n    y,\n    width: w,\n    height: h\n  };\n};\n\n/**\n* Get the given/selected element's bounding box object, checking for\n* horizontal/vertical lines (see issue 717)\n* Note that performance is currently terrible, so some way to improve would\n* be great.\n* @param selected - Container or &lt;use> DOM element\n* @returns Bounding box object\n*/\nfunction groupBBFix (selected) {\n  if (supportsHVLineContainerBBox()) {\n    try { return selected.getBBox(); } catch (e) {}\n  }\n  const ref = $.data(selected, 'ref');\n  let matched = null;\n  let ret, copy;\n\n  if (ref) {\n    copy = $(ref).children().clone().attr('visibility', 'hidden');\n    $(svgroot_).append(copy);\n    matched = copy.filter('line, path');\n  } else {\n    matched = $(selected).find('line, path');\n  }\n\n  let issue = false;\n  if (matched.length) {\n    matched.each(function () {\n      const bb = this.getBBox();\n      if (!bb.width || !bb.height) {\n        issue = true;\n      }\n    });\n    if (issue) {\n      const elems = ref ? copy : $(selected).children();\n      ret = getStrokedBBox(elems); // getStrokedBBox defined in svgcanvas\n    } else {\n      ret = selected.getBBox();\n    }\n  } else {\n    ret = selected.getBBox();\n  }\n  if (ref) {\n    copy.remove();\n  }\n  return ret;\n}\n\n/**\n* Get the given/selected element's bounding box object, convert it to be more\n* usable when necessary\n* @param elem - Optional DOM element to get the BBox for\n* @returns Bounding box object\n*/\nexport const getBBox = function (elem) {\n  const selected = elem || editorContext_.geSelectedElements()[0];\n  if (elem.nodeType !== 1) { return null; }\n  const elname = selected.nodeName;\n\n  let ret = null;\n  switch (elname) {\n  case 'text':\n    if (selected.textContent === '') {\n      selected.textContent = 'a'; // Some character needed for the selector to use.\n      ret = selected.getBBox();\n      selected.textContent = '';\n    } else {\n      if (selected.getBBox) { ret = selected.getBBox(); }\n    }\n    break;\n  case 'path':\n    if (!supportsPathBBox()) {\n      ret = getPathBBox(selected);\n    } else {\n      if (selected.getBBox) { ret = selected.getBBox(); }\n    }\n    break;\n  case 'g':\n  case 'a':\n    ret = groupBBFix(selected);\n    break;\n  default:\n\n    if (elname === 'use') {\n      ret = groupBBFix(selected, true);\n    }\n    if (elname === 'use' || (elname === 'foreignObject' && isWebkit())) {\n      if (!ret) { ret = selected.getBBox(); }\n      // This is resolved in later versions of webkit, perhaps we should\n      // have a featured detection for correct 'use' behavior?\n      // ——————————\n      if (!isWebkit()) {\n        const bb = {};\n        bb.width = ret.width;\n        bb.height = ret.height;\n        bb.x = ret.x + parseFloat(selected.getAttribute('x') || 0);\n        bb.y = ret.y + parseFloat(selected.getAttribute('y') || 0);\n        ret = bb;\n      }\n    } else if (visElemsArr.includes(elname)) {\n      if (selected) {\n        try {\n          ret = selected.getBBox();\n        } catch (err) {\n          // tspan (and textPath apparently) have no `getBBox` in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=937268\n          // Re: Chrome returning bbox for containing text element, see: https://bugs.chromium.org/p/chromium/issues/detail?id=349835\n          const extent = selected.getExtentOfChar(0); // pos+dimensions of the first glyph\n          const width = selected.getComputedTextLength(); // width of the tspan\n          ret = {\n            x: extent.x,\n            y: extent.y,\n            width,\n            height: extent.height\n          };\n        }\n      } else {\n        // Check if element is child of a foreignObject\n        const fo = $(selected).closest('foreignObject');\n        if (fo.length) {\n          if (fo[0].getBBox) {\n            ret = fo[0].getBBox();\n          }\n        }\n      }\n    }\n  }\n  if (ret) {\n    ret = bboxToObj(ret);\n  }\n\n  // get the bounding box from the DOM (which is in that element's coordinate system)\n  return ret;\n};\n\n/**\n* Create a path 'd' attribute from path segments.\n* Each segment is an array of the form: [singleChar, [x,y, x,y, ...]]\n* @param pathSegments - An array of path segments to be converted\n* @returns The converted path d attribute.\n*/\nexport const getPathDFromSegments = function (pathSegments) {\n  let d = '';\n\n  $.each(pathSegments, function (j, seg) {\n    const pts = seg[1];\n    d += seg[0];\n    for (let i = 0; i < pts.length; i += 2) {\n      d += (pts[i] + ',' + pts[i + 1]) + ' ';\n    }\n  });\n\n  return d;\n};\n\n/**\n* Make a path 'd' attribute from a simple SVG element shape.\n* @param elem - The element to be converted\n* @returns The path d attribute or `undefined` if the element type is unknown.\n*/\nexport const getPathDFromElement = function (elem) {\n  // Possibly the cubed root of 6, but 1.81 works best\n  let num = 1.81;\n  let d, a, rx, ry;\n  switch (elem.tagName) {\n  case 'ellipse':\n  case 'circle':\n    a = $(elem).attr(['rx', 'ry', 'cx', 'cy']);\n    const {cx, cy} = a;\n    ({rx, ry} = a);\n    if (elem.tagName === 'circle') {\n      rx = ry = $(elem).attr('r');\n    }\n\n    d = getPathDFromSegments([\n      ['M', [(cx - rx), (cy)]],\n      ['C', [(cx - rx), (cy - ry / num), (cx - rx / num), (cy - ry), (cx), (cy - ry)]],\n      ['C', [(cx + rx / num), (cy - ry), (cx + rx), (cy - ry / num), (cx + rx), (cy)]],\n      ['C', [(cx + rx), (cy + ry / num), (cx + rx / num), (cy + ry), (cx), (cy + ry)]],\n      ['C', [(cx - rx / num), (cy + ry), (cx - rx), (cy + ry / num), (cx - rx), (cy)]],\n      ['Z', []]\n    ]);\n    break;\n  case 'path':\n    d = elem.getAttribute('d');\n    break;\n  case 'line':\n    a = $(elem).attr(['x1', 'y1', 'x2', 'y2']);\n    d = 'M' + a.x1 + ',' + a.y1 + 'L' + a.x2 + ',' + a.y2;\n    break;\n  case 'polyline':\n    d = 'M' + elem.getAttribute('points');\n    break;\n  case 'polygon':\n    d = 'M' + elem.getAttribute('points') + ' Z';\n    break;\n  case 'rect':\n    const r = $(elem).attr(['rx', 'ry']);\n    ({rx, ry} = r);\n    const b = elem.getBBox();\n    const {x, y} = b, w = b.width, h = b.height;\n    num = 4 - num; // Why? Because!\n\n    if (!rx && !ry) {\n      // Regular rect\n      d = getPathDFromSegments([\n        ['M', [x, y]],\n        ['L', [x + w, y]],\n        ['L', [x + w, y + h]],\n        ['L', [x, y + h]],\n        ['L', [x, y]],\n        ['Z', []]\n      ]);\n    } else {\n      d = getPathDFromSegments([\n        ['M', [x, y + ry]],\n        ['C', [x, y + ry / num, x + rx / num, y, x + rx, y]],\n        ['L', [x + w - rx, y]],\n        ['C', [x + w - rx / num, y, x + w, y + ry / num, x + w, y + ry]],\n        ['L', [x + w, y + h - ry]],\n        ['C', [x + w, y + h - ry / num, x + w - rx / num, y + h, x + w - rx, y + h]],\n        ['L', [x + rx, y + h]],\n        ['C', [x + rx / num, y + h, x, y + h - ry / num, x, y + h - ry]],\n        ['L', [x, y + ry]],\n        ['Z', []]\n      ]);\n    }\n    break;\n  default:\n    break;\n  }\n\n  return d;\n};\n\n/**\n* Get a set of attributes from an element that is useful for convertToPath.\n* @param elem - The element to be probed\n* @returns {Object} An object with attributes.\n*/\nexport const getExtraAttributesForConvertToPath = function (elem) {\n  const attrs = {};\n  // TODO: make this list global so that we can properly maintain it\n  // TODO: what about @transform, @clip-rule, @fill-rule, etc?\n  $.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function () {\n    const a = elem.getAttribute(this);\n    if (a) {\n      attrs[this] = a;\n    }\n  });\n  return attrs;\n};\n\n/**\n* Get the BBox of an element-as-path\n* @param elem - The DOM element to be probed\n* @param addSvgElementFromJson - Function to add the path element to the current layer. See canvas.addSvgElementFromJson\n* @param pathActions - If a transform exists, `pathActions.resetOrientation()` is used. See: canvas.pathActions.\n* @returns The resulting path's bounding box object.\n*/\nexport const getBBoxOfElementAsPath = function (elem, addSvgElementFromJson, pathActions) {\n  const path = addSvgElementFromJson({\n    element: 'path',\n    attr: getExtraAttributesForConvertToPath(elem)\n  });\n\n  const eltrans = elem.getAttribute('transform');\n  if (eltrans) {\n    path.setAttribute('transform', eltrans);\n  }\n\n  const parent = elem.parentNode;\n  if (elem.nextSibling) {\n    parent.insertBefore(path, elem);\n  } else {\n    parent.appendChild(path);\n  }\n\n  const d = getPathDFromElement(elem);\n  if (d) path.setAttribute('d', d);\n  else path.parentNode.removeChild(path);\n\n  // Get the correct BBox of the new path, then discard it\n  pathActions.resetOrientation(path);\n  let bb = false;\n  try {\n    bb = path.getBBox();\n  } catch (e) {\n    // Firefox fails\n  }\n  path.parentNode.removeChild(path);\n  return bb;\n};\n\n/**\n* Convert selected element to a path.\n* @param elem - The DOM element to be converted\n* @param attrs - Apply attributes to new path. see canvas.convertToPath\n* @param addSvgElementFromJson - Function to add the path element to the current layer. See canvas.addSvgElementFromJson\n* @param pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions.\n* @param clearSelection - see canvas.clearSelection\n* @param addToSelection - see canvas.addToSelection\n* @param history - see svgedit.history\n* @param addCommandToHistory - see canvas.addCommandToHistory\n* @returns The converted path element or null if the DOM element was not recognized.\n*/\nexport const convertToPath = function (elem, attrs, addSvgElementFromJson, pathActions, clearSelection, addToSelection, history, addCommandToHistory) {\n  const batchCmd = new history.BatchCommand('Convert element to Path');\n\n  // Any attribute on the element not covered by the passed-in attributes\n  attrs = $.extend({}, attrs, getExtraAttributesForConvertToPath(elem));\n\n  const path = addSvgElementFromJson({\n    element: 'path',\n    attr: attrs\n  });\n\n  const eltrans = elem.getAttribute('transform');\n  if (eltrans) {\n    path.setAttribute('transform', eltrans);\n  }\n\n  const {id} = elem;\n  const parent = elem.parentNode;\n  if (elem.nextSibling) {\n    parent.insertBefore(path, elem);\n  } else {\n    parent.appendChild(path);\n  }\n\n  const d = getPathDFromElement(elem);\n  if (d) {\n    path.setAttribute('d', d);\n\n    // Replace the current element with the converted one\n\n    // Reorient if it has a matrix\n    if (eltrans) {\n      const tlist = getTransformList(path);\n      if (hasMatrixTransform(tlist)) {\n        pathActions.resetOrientation(path);\n      }\n    }\n\n    const {nextSibling} = elem;\n    batchCmd.addSubCommand(new history.RemoveElementCommand(elem, nextSibling, parent));\n    batchCmd.addSubCommand(new history.InsertElementCommand(path));\n\n    clearSelection();\n    elem.parentNode.removeChild(elem);\n    path.setAttribute('id', id);\n    path.removeAttribute('visibility');\n    addToSelection([path], true);\n\n    addCommandToHistory(batchCmd);\n\n    return path;\n  } else {\n    // the elem.tagName was not recognized, so no \"d\" attribute. Remove it, so we've haven't changed anything.\n    path.parentNode.removeChild(path);\n    return null;\n  }\n};\n\n/**\n* Can the bbox be optimized over the native getBBox? The optimized bbox is the same as the native getBBox when\n* the rotation angle is a multiple of 90 degrees and there are no complex transforms.\n* Getting an optimized bbox can be dramatically slower, so we want to make sure it's worth it.\n*\n* The best example for this is a circle rotate 45 degrees. The circle doesn't get wider or taller when rotated\n* about it's center.\n*\n* The standard, unoptimized technique gets the native bbox of the circle, rotates the box 45 degrees, uses\n* that width and height, and applies any transforms to get the final bbox. This means the calculated bbox\n* is much wider than the original circle. If the angle had been 0, 90, 180, etc. both techniques render the\n* same bbox.\n*\n* The optimization is not needed if the rotation is a multiple 90 degrees. The default technique is to call\n* getBBox then apply the angle and any transforms.\n*\n* @param angle - The rotation angle in degrees\n* @param {Boolean} hasMatrixTransform - True if there is a matrix transform\n* @returns {Boolean} True if the bbox can be optimized.\n*/\nfunction bBoxCanBeOptimizedOverNativeGetBBox (angle, hasMatrixTransform) {\n  const angleModulo90 = angle % 90;\n  const closeTo90 = angleModulo90 < -89.99 || angleModulo90 > 89.99;\n  const closeTo0 = angleModulo90 > -0.001 && angleModulo90 < 0.001;\n  return hasMatrixTransform || !(closeTo0 || closeTo90);\n}\n\n/**\n* Get bounding box that includes any transforms.\n* @param elem - The DOM element to be converted\n* @param  addSvgElementFromJson - Function to add the path element to the current layer. See canvas.addSvgElementFromJson\n* @param  pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions.\n* @returns A single bounding box object\n*/\nexport const getBBoxWithTransform = function (elem, addSvgElementFromJson, pathActions) {\n  // TODO: Fix issue with rotated groups. Currently they work\n  // fine in FF, but not in other browsers (same problem mentioned\n  // in Issue 339 comment #2).\n\n  let bb = getBBox(elem);\n\n  if (!bb) {\n    return null;\n  }\n\n  const tlist = getTransformList(elem);\n  const angle = getRotationAngleFromTransformList(tlist);\n  const hasMatrixXForm = hasMatrixTransform(tlist);\n\n  if (angle || hasMatrixXForm) {\n    let goodBb = false;\n    if (bBoxCanBeOptimizedOverNativeGetBBox(angle, hasMatrixXForm)) {\n      // Get the BBox from the raw path for these elements\n      // TODO: why ellipse and not circle\n      const elemNames = ['ellipse', 'path', 'line', 'polyline', 'polygon'];\n      if (elemNames.includes(elem.tagName)) {\n        bb = goodBb = getBBoxOfElementAsPath(elem, addSvgElementFromJson, pathActions);\n      } else if (elem.tagName === 'rect') {\n        // Look for radius\n        const rx = elem.getAttribute('rx');\n        const ry = elem.getAttribute('ry');\n        if (rx || ry) {\n          bb = goodBb = getBBoxOfElementAsPath(elem, addSvgElementFromJson, pathActions);\n        }\n      }\n    }\n\n    if (!goodBb) {\n      const {matrix} = transformListToTransform(tlist);\n      bb = transformBox(bb.x, bb.y, bb.width, bb.height, matrix).aabox;\n\n      // Old technique that was exceedingly slow with large documents.\n      //\n      // Accurate way to get BBox of rotated element in Firefox:\n      // Put element in group and get its BBox\n      //\n      // Must use clone else FF freaks out\n      // const clone = elem.cloneNode(true);\n      // const g = document.createElementNS(NS.SVG, 'g');\n      // const parent = elem.parentNode;\n      // parent.appendChild(g);\n      // g.appendChild(clone);\n      // const bb2 = bboxToObj(g.getBBox());\n      // parent.removeChild(g);\n    }\n  }\n  return bb;\n};\n\n// TODO: This is problematic with large stroke-width and, for example, a single horizontal line. The calculated BBox extends way beyond left and right sides.\nfunction getStrokeOffsetForBBox (elem) {\n  const sw = elem.getAttribute('stroke-width');\n  return (!isNaN(sw) && elem.getAttribute('stroke') !== 'none') ? sw / 2 : 0;\n}\n\n/**\n* Get the bounding box for one or more stroked and/or transformed elements\n* @param elems - Array with DOM elements to check\n* @param addSvgElementFromJson - Function to add the path element to the current layer. See canvas.addSvgElementFromJson\n* @param pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions.\n* @returns A single bounding box object\n*/\nexport const getStrokedBBox = function (elems, addSvgElementFromJson, pathActions) {\n  if (!elems || !elems.length) { return false; }\n\n  let fullBb;\n  $.each(elems, function () {\n    if (fullBb) { return; }\n    if (!this.parentNode) { return; }\n    fullBb = getBBoxWithTransform(this, addSvgElementFromJson, pathActions);\n  });\n\n  // This shouldn't ever happen...\n  if (fullBb === undefined) { return null; }\n\n  // fullBb doesn't include the stoke, so this does no good!\n  // if (elems.length == 1) return fullBb;\n\n  let maxX = fullBb.x + fullBb.width;\n  let maxY = fullBb.y + fullBb.height;\n  let minX = fullBb.x;\n  let minY = fullBb.y;\n\n  // If only one elem, don't call the potentially slow getBBoxWithTransform method again.\n  if (elems.length === 1) {\n    const offset = getStrokeOffsetForBBox(elems[0]);\n    minX -= offset;\n    minY -= offset;\n    maxX += offset;\n    maxY += offset;\n  } else {\n    $.each(elems, function (i, elem) {\n      const curBb = getBBoxWithTransform(elem, addSvgElementFromJson, pathActions);\n      if (curBb) {\n        const offset = getStrokeOffsetForBBox(elem);\n        minX = Math.min(minX, curBb.x - offset);\n        minY = Math.min(minY, curBb.y - offset);\n        // TODO: The old code had this test for max, but not min. I suspect this test should be for both min and max\n        if (elem.nodeType === 1) {\n          maxX = Math.max(maxX, curBb.x + curBb.width + offset);\n          maxY = Math.max(maxY, curBb.y + curBb.height + offset);\n        }\n      }\n    });\n  }\n\n  fullBb.x = minX;\n  fullBb.y = minY;\n  fullBb.width = maxX - minX;\n  fullBb.height = maxY - minY;\n  return fullBb;\n};\n\n/**\n* Get all elements that have a BBox (excludes `&lt;defs>`, `&lt;title>`, etc).\n* Note that 0-opacity, off-screen etc elements are still considered \"visible\"\n* for this function\n* @param parent - The parent DOM element to search within\n* @returns {Array} All \"visible\" elements.\n*/\nexport const getVisibleElements = function (parent) {\n  if (!parent) {\n    parent = $(editorContext_.getSVGContent()).children(); // Prevent layers from being included\n  }\n\n  const contentElems = [];\n  $(parent).children().each(function (i, elem) {\n    if (elem.getBBox) {\n      contentElems.push(elem);\n    }\n  });\n  return contentElems.reverse();\n};\n\n/**\n* Get the bounding box for one or more stroked and/or transformed elements\n* @param elems - Array with DOM elements to check\n* @returns A single bounding box object\n*/\nexport const getStrokedBBoxDefaultVisible = function (elems) {\n  if (!elems) { elems = getVisibleElements(); }\n  return getStrokedBBox(\n    elems,\n    editorContext_.addSvgElementFromJson,\n    editorContext_.pathActions\n  );\n};\n\n/**\n* Get the rotation angle of the given transform list.\n* @param tlist - List of transforms\n* @param {Boolean} toRad - When true returns the value in radians rather than degrees\n* @returns {Number} Float with the angle in degrees or radians\n*/\nexport const getRotationAngleFromTransformList = function (tlist, toRad) {\n  if (!tlist) { return 0; } // <svg> elements have no tlist\n  const N = tlist.numberOfItems;\n  for (let i = 0; i < N; ++i) {\n    const xform = tlist.getItem(i);\n    if (xform.type === 4) {\n      return toRad ? xform.angle * Math.PI / 180.0 : xform.angle;\n    }\n  }\n  return 0.0;\n};\n\n/**\n* Get the rotation angle of the given/selected DOM element\n* @param elem - Optional DOM element to get the angle for\n* @param {Boolean} toRad - When true returns the value in radians rather than degrees\n* @returns {Number} Float with the angle in degrees or radians\n*/\nexport let getRotationAngle = function (elem, toRad) {\n  const selected = elem || editorContext_.getSelectedElements()[0];\n  // find the rotation transform (if any) and set it\n  const tlist = getTransformList(selected);\n  return getRotationAngleFromTransformList(tlist, toRad);\n};\n\n/**\n* Get the reference element associated with the given attribute value\n* @param {String} attrVal - The attribute value as a string\n* @returns Reference element\n*/\nexport const getRefElem = function (attrVal) {\n  return getElem(getUrlFromAttr(attrVal).substr(1));\n};\n\n/**\n* Get a DOM element by ID within the SVG root element.\n* @param {String} id - String with the element's new ID\n*/\nexport const getElem = (supportsSelectors())\n  ? function (id) {\n    // querySelector lookup\n    return svgroot_.querySelector('#' + id);\n  } : supportsXpath()\n    ? function (id) {\n      // xpath lookup\n      return domdoc_.evaluate(\n        'svg:svg[@id=\"svgroot\"]//svg:*[@id=\"' + id + '\"]',\n        domcontainer_,\n        function () { return NS.SVG; },\n        9,\n        null).singleNodeValue;\n    }\n    : function (id) {\n      // jQuery lookup: twice as slow as xpath in FF\n      return $(svgroot_).find('[id=' + id + ']')[0];\n    };\n\n/**\n* Assigns multiple attributes to an element.\n* @param node - DOM element to apply new attribute values to\n* @param {Object} attrs - Object with attribute keys/values\n* @param {Number} suspendLength - Optional integer of milliseconds to suspend redraw\n* @param {Boolean} unitCheck - Boolean to indicate the need to use svgedit.units.setUnitAttr\n*/\nexport const assignAttributes = function (node, attrs, suspendLength, unitCheck) {\n  for (const i in attrs) {\n    const ns = (i.substr(0, 4) === 'xml:'\n      ? NS.XML\n      : i.substr(0, 6) === 'xlink:' ? NS.XLINK : null);\n\n    if (ns) {\n      node.setAttributeNS(ns, i, attrs[i]);\n    } else if (!unitCheck) {\n      node.setAttribute(i, attrs[i]);\n    } else {\n      setUnitAttr(node, i, attrs[i]);\n    }\n  }\n};\n\n/**\n* Remove unneeded (default) attributes, makes resulting SVG smaller\n* @param element - DOM element to clean up\n*/\nexport const cleanupElement = function (element) {\n  const defaults = {\n    'fill-opacity': 1,\n    'stop-opacity': 1,\n    opacity: 1,\n    stroke: 'none',\n    'stroke-dasharray': 'none',\n    'stroke-linejoin': 'miter',\n    'stroke-linecap': 'butt',\n    'stroke-opacity': 1,\n    'stroke-width': 1,\n    rx: 0,\n    ry: 0\n  };\n\n  if (element.nodeName === 'ellipse') {\n    // Ellipse elements requires rx and ry attributes\n    delete defaults.rx;\n    delete defaults.ry;\n  }\n\n  for (const attr in defaults) {\n    const val = defaults[attr];\n    if (element.getAttribute(attr) === String(val)) {\n      element.removeAttribute(attr);\n    }\n  }\n};\n\n// round value to for snapping\nexport const snapToGrid = function (value) {\n  const unit = editorContext_.getBaseUnit();\n  let stepSize = editorContext_.getSnappingStep();\n  if (unit !== 'px') {\n    stepSize *= getTypeMap()[unit];\n  }\n  value = Math.round(value / stepSize) * stepSize;\n  return value;\n};\n\nexport const regexEscape = function (str, delimiter) {\n  // From: http://phpjs.org/functions\n  return String(str).replace(new RegExp('[.\\\\\\\\+*?\\\\[\\\\^\\\\]$(){}=!<>|:\\\\' + (delimiter || '') + '-]', 'g'), '\\\\$&');\n};\n\nconst loadedScripts = {};\n/**\n* @param {string} name A global which can be used to determine if the script is already loaded\n* @param {array} scripts An array of scripts to preload (in order)\n* @param {function} cb The callback to execute upon load.\n* @param {object} options Object with `globals` boolean property (if it is not a module)\n*/\nexport const executeAfterLoads = function (name, scripts, cb, options = {globals: false}) {\n  return function () {\n    const args = arguments;\n    function endCallback () {\n      cb.apply(null, args);\n    }\n    const modularVersion = !('svgEditor' in window) ||\n      !window.svgEditor ||\n      window.svgEditor.modules !== false;\n    if (loadedScripts[name] === true) {\n      endCallback();\n    } else if (Array.isArray(loadedScripts[name])) { // Still loading\n      loadedScripts[name].push(endCallback);\n    } else {\n      loadedScripts[name] = [];\n      const importer = modularVersion && !options.globals\n        ? importModule\n        : importScript;\n      scripts.reduce(function (oldProm, script) {\n        // Todo: Once `import()` and modules widely supported, switch to it\n        return oldProm.then(() => importer(script));\n      }, Promise.resolve()).then(function () {\n        endCallback();\n        loadedScripts[name].forEach((cb) => {\n          cb();\n        });\n        loadedScripts[name] = true;\n      })();\n    }\n  };\n};\n\nexport const buildCanvgCallback = function (callCanvg) {\n  return executeAfterLoads('canvg', ['canvg/rgbcolor.js', 'canvg/canvg.js'], callCanvg);\n};\n\nexport const buildJSPDFCallback = function (callJSPDF) {\n  return executeAfterLoads('RGBColor', ['canvg/rgbcolor.js'], () => {\n    const arr = [];\n    if (!RGBColor || RGBColor.ok === undefined) { // It's not our RGBColor, so we'll need to load it\n      arr.push('canvg/rgbcolor.js');\n    }\n    executeAfterLoads('jsPDF', [\n      ...arr,\n      'jspdf/underscore-min.js',\n      'jspdf/jspdf.min.js',\n      'jspdf/jspdf.plugin.svgToPdf.js'\n    ], callJSPDF, {globals: true})();\n  });\n};\n\n/**\n * Prevents default browser click behaviour on the given element\n * @param img - The DOM element to prevent the click on\n */\nexport const preventClickDefault = function (img) {\n  $(img).click(function (e) { e.preventDefault(); });\n};\n\n/**\n * Create a clone of an element, updating its ID and its children's IDs when needed\n * @param {Element} el - DOM element to clone\n * @param {Function} getNextId - The getter of the next unique ID.\n * @returns {Element}\n */\nexport const copyElem = function (el, getNextId) {\n  // manually create a copy of the element\n  const newEl = document.createElementNS(el.namespaceURI, el.nodeName);\n  $.each(el.attributes, function (i, attr) {\n    if (attr.localName !== '-moz-math-font-style') {\n      newEl.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value);\n    }\n  });\n  // set the copied element's new id\n  newEl.removeAttribute('id');\n  newEl.id = getNextId();\n\n  // Opera's \"d\" value needs to be reset for Opera/Win/non-EN\n  // Also needed for webkit (else does not keep curved segments on clone)\n  if (isWebkit() && el.nodeName === 'path') {\n    const fixedD = convertPath(el);\n    newEl.setAttribute('d', fixedD);\n  }\n\n  // now create copies of all children\n  $.each(el.childNodes, function (i, child) {\n    switch (child.nodeType) {\n    case 1: // element node\n      newEl.appendChild(copyElem(child, getNextId));\n      break;\n    case 3: // text node\n      newEl.textContent = child.nodeValue;\n      break;\n    default:\n      break;\n    }\n  });\n\n  if ($(el).data('gsvg')) {\n    $(newEl).data('gsvg', newEl.firstChild);\n  } else if ($(el).data('symbol')) {\n    const ref = $(el).data('symbol');\n    $(newEl).data('ref', ref).data('symbol', ref);\n  } else if (newEl.tagName === 'image') {\n    preventClickDefault(newEl);\n  }\n\n  return newEl;\n};\n\n// Unit testing\nexport const mock = ({\n  getHref: getHrefUser, setHref: setHrefUser, getRotationAngle: getRotationAngleUser\n}) => {\n  getHref = getHrefUser;\n  setHref = setHrefUser;\n  getRotationAngle = getRotationAngleUser;\n};\n"
  },
  {
    "path": "third_party/SVG-Edit/editor/units.js",
    "content": "/**\n * Package: svgedit.units\n *\n * Licensed under the MIT License\n *\n * Copyright(c) 2010 Alexis Deveria\n * Copyright(c) 2010 Jeff Schiller\n */\n\nimport {NS} from './svgedit.js';\n\nconst wAttrs = ['x', 'x1', 'cx', 'rx', 'width'];\nconst hAttrs = ['y', 'y1', 'cy', 'ry', 'height'];\nconst unitAttrs = ['r', 'radius', ...wAttrs, ...hAttrs];\n// unused\n/*\nconst unitNumMap = {\n  '%': 2,\n  em: 3,\n  ex: 4,\n  px: 5,\n  cm: 6,\n  mm: 7,\n  in: 8,\n  pt: 9,\n  pc: 10\n};\n*/\n// Container of elements.\nlet elementContainer_;\n\n/**\n * Stores mapping of unit type to user coordinates.\n */\nlet typeMap_ = {};\n\n/**\n * ElementContainer interface\n *\n * function getBaseUnit() - Returns a string of the base unit type of the container ('em')\n * function getElement() - Returns an element in the container given an id\n * function getHeight() - Returns the container's height\n * function getWidth() - Returns the container's width\n * function getRoundDigits() - Returns the number of digits number should be rounded to\n */\n\n/**\n * Initializes this module.\n *\n * @param elementContainer - An object implementing the ElementContainer interface.\n */\nexport const init = function (elementContainer) {\n  elementContainer_ = elementContainer;\n\n  // Get correct em/ex values by creating a temporary SVG.\n  const svg = document.createElementNS(NS.SVG, 'svg');\n  document.body.appendChild(svg);\n  const rect = document.createElementNS(NS.SVG, 'rect');\n  rect.setAttribute('width', '1em');\n  rect.setAttribute('height', '1ex');\n  rect.setAttribute('x', '1in');\n  svg.appendChild(rect);\n  const bb = rect.getBBox();\n  document.body.removeChild(svg);\n\n  const inch = bb.x;\n  typeMap_ = {\n    em: bb.width,\n    ex: bb.height,\n    in: inch,\n    cm: inch / 2.54,\n    mm: inch / 25.4,\n    pt: inch / 72,\n    pc: inch / 6,\n    px: 1,\n    '%': 0\n  };\n};\n\n/**\n* Group: Unit conversion functions\n*/\n\n/**\n* @returns The unit object with values for each unit\n*/\nexport const getTypeMap = function () {\n  return typeMap_;\n};\n\n/**\n* Rounds a given value to a float with number of digits defined in save_options\n*\n* @param val - The value as a String, Number or Array of two numbers to be rounded\n*\n* @returns\n* If a string/number was given, returns a Float. If an array, return a string\n* with comma-separated floats\n*/\nexport const shortFloat = function (val) {\n  const digits = elementContainer_.getRoundDigits();\n  if (!isNaN(val)) {\n    // Note that + converts to Number\n    return +((+val).toFixed(digits));\n  }\n  if (Array.isArray(val)) {\n    return shortFloat(val[0]) + ',' + shortFloat(val[1]);\n  }\n  return parseFloat(val).toFixed(digits) - 0;\n};\n\n/**\n* Converts the number to given unit or baseUnit\n* @returns {number}\n*/\nexport const convertUnit = function (val, unit) {\n  unit = unit || elementContainer_.getBaseUnit();\n  // baseVal.convertToSpecifiedUnits(unitNumMap[unit]);\n  // const val = baseVal.valueInSpecifiedUnits;\n  // baseVal.convertToSpecifiedUnits(1);\n  return shortFloat(val / typeMap_[unit]);\n};\n\n/**\n* Sets an element's attribute based on the unit in its current value.\n*\n* @param elem - DOM element to be changed\n* @param attr - String with the name of the attribute associated with the value\n* @param val - String with the attribute value to convert\n*/\nexport const setUnitAttr = function (elem, attr, val) {\n  //  if (!isNaN(val)) {\n  // New value is a number, so check currently used unit\n  // const oldVal = elem.getAttribute(attr);\n\n  // Enable this for alternate mode\n  // if (oldVal !== null && (isNaN(oldVal) || elementContainer_.getBaseUnit() !== 'px')) {\n  //   // Old value was a number, so get unit, then convert\n  //   let unit;\n  //   if (oldVal.substr(-1) === '%') {\n  //     const res = getResolution();\n  //     unit = '%';\n  //     val *= 100;\n  //     if (wAttrs.includes(attr)) {\n  //       val = val / res.w;\n  //     } else if (hAttrs.includes(attr)) {\n  //       val = val / res.h;\n  //     } else {\n  //       return val / Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2);\n  //     }\n  //   } else {\n  //     if (elementContainer_.getBaseUnit() !== 'px') {\n  //       unit = elementContainer_.getBaseUnit();\n  //     } else {\n  //       unit = oldVal.substr(-2);\n  //     }\n  //     val = val / typeMap_[unit];\n  //   }\n  //\n  // val += unit;\n  // }\n  // }\n  elem.setAttribute(attr, val);\n};\n\nconst attrsToConvert = {\n  line: ['x1', 'x2', 'y1', 'y2'],\n  circle: ['cx', 'cy', 'r'],\n  ellipse: ['cx', 'cy', 'rx', 'ry'],\n  foreignObject: ['x', 'y', 'width', 'height'],\n  rect: ['x', 'y', 'width', 'height'],\n  image: ['x', 'y', 'width', 'height'],\n  use: ['x', 'y', 'width', 'height'],\n  text: ['x', 'y']\n};\n\n/**\n* Converts all applicable attributes to the configured baseUnit\n* @param element - A DOM element whose attributes should be converted\n*/\nexport const convertAttrs = function (element) {\n  const elName = element.tagName;\n  const unit = elementContainer_.getBaseUnit();\n  const attrs = attrsToConvert[elName];\n  if (!attrs) { return; }\n\n  const len = attrs.length;\n  for (let i = 0; i < len; i++) {\n    const attr = attrs[i];\n    const cur = element.getAttribute(attr);\n    if (cur) {\n      if (!isNaN(cur)) {\n        element.setAttribute(attr, (cur / typeMap_[unit]) + unit);\n      }\n      // else {\n      // Convert existing?\n      // }\n    }\n  }\n};\n\n/**\n* Converts given values to numbers. Attributes must be supplied in\n* case a percentage is given\n*\n* @param attr - String with the name of the attribute associated with the value\n* @param val - String with the attribute value to convert\n*/\nexport const convertToNum = function (attr, val) {\n  // Return a number if that's what it already is\n  if (!isNaN(val)) { return val - 0; }\n  if (val.substr(-1) === '%') {\n    // Deal with percentage, depends on attribute\n    const num = val.substr(0, val.length - 1) / 100;\n    const width = elementContainer_.getWidth();\n    const height = elementContainer_.getHeight();\n\n    if (wAttrs.includes(attr)) {\n      return num * width;\n    }\n    if (hAttrs.includes(attr)) {\n      return num * height;\n    }\n    return num * Math.sqrt((width * width) + (height * height)) / Math.sqrt(2);\n  }\n  const unit = val.substr(-2);\n  const num = val.substr(0, val.length - 2);\n  // Note that this multiplication turns the string into a number\n  return num * typeMap_[unit];\n};\n\n/**\n* Check if an attribute's value is in a valid format\n* @param attr - String with the name of the attribute associated with the value\n* @param val - String with the attribute value to check\n*/\nexport const isValidUnit = function (attr, val, selectedElement) {\n  let valid = false;\n  if (unitAttrs.includes(attr)) {\n    // True if it's just a number\n    if (!isNaN(val)) {\n      valid = true;\n    } else {\n    // Not a number, check if it has a valid unit\n      val = val.toLowerCase();\n      Object.keys(typeMap_).forEach((unit) => {\n        if (valid) { return; }\n        const re = new RegExp('^-?[\\\\d\\\\.]+' + unit + '$');\n        if (re.test(val)) { valid = true; }\n      });\n    }\n  } else if (attr === 'id') {\n    // if we're trying to change the id, make sure it's not already present in the doc\n    // and the id value is valid.\n\n    let result = false;\n    // because getElem() can throw an exception in the case of an invalid id\n    // (according to https://www.w3.org/TR/xml-id/ IDs must be a NCName)\n    // we wrap it in an exception and only return true if the ID was valid and\n    // not already present\n    try {\n      const elem = elementContainer_.getElement(val);\n      result = (elem == null || elem === selectedElement);\n    } catch (e) {}\n    return result;\n  }\n  valid = true;\n\n  return valid;\n};\n"
  }
]